diff --git "a/6088.jsonl" "b/6088.jsonl" new file mode 100644--- /dev/null +++ "b/6088.jsonl" @@ -0,0 +1,612 @@ +{"seq_id":"429273341","text":"#!/usr/bin/env python3\n\nimport sqlite3\n\ndb = sqlite3.connect('database.sqlite3')\n\nwhile True:\n cmd = input(\"sqlite3> \")\n cur = db.cursor()\n try:\n cur.execute(cmd)\n db.commit()\n out = cur.fetchall()\n if out is not None:\n for x in out:\n print(repr(x))\n except Exception as e:\n print(e)\n finally:\n cur.close()\n","sub_path":"sqlite-shell.py","file_name":"sqlite-shell.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474848253","text":"import os\nimport tensorflow as tf\nimport numpy as np\nimport pickle as pkl\nfrom data import Dataset\nfrom model import TabNet\n\n\ncol_metadata_file = 'col_metadata.pkl'\ninput_file = \"bank-full.csv\"\nexp_dir= \"test_dir\"\nbatch_size= 10\nsparsity_loss_weight= 0.0001\ndecay_rate = 0.95\ndecay_every = 500\ninit_localearning_rate = 0.02\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\ncol_metadata = pkl.load(open(col_metadata_file, 'rb'))\n\ndata_preprocess = Dataset(input_file, col_metadata, sep=';',exp_dir= exp_dir)\n\ndata_preprocess.split_dataset()\n\ntrain_data, test_data, val_data = data_preprocess.load_dataset()\n\ninp_feature_columns = data_preprocess.make_feature_layer()\n\nMODEL = TabNet(feature_columns = inp_feature_columns, num_features= 16, feature_dim = 128, output_dim= 64, num_decision_steps= 6, relaxation_factor= 1.5, virtual_batch_size= 10, num_classes=2, batch_size= 10, batch_momentum= 0.7, is_training= True)\n\nglobal_step = tf.compat.v1.train.get_or_create_global_step()\n\nlearning_rate = tf.compat.v1.train.exponential_decay(\n init_localearning_rate,\n global_step= global_step,\n decay_steps= decay_every,\n decay_rate= decay_rate\n)\n\noptimizer= tf.compat.v1.train.AdamOptimizer(learning_rate= learning_rate)\n\ndef model_objective(entropy, actual_output, predicted_output):\n softmax_orig_key_op = tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits= predicted_output, labels= actual_output\n )\n )\n train_loss = softmax_orig_key_op + sparsity_loss_weight * entropy\n return train_loss\n\n@tf.function()\ndef training_steps(tabnet_model, inp_data, out_data, k= 1, batch_size= 10):\n print(\"Train step called\")\n for i in range(k):\n #print(i)\n with tf.GradientTape() as model_tape:\n logits, predictions, entropy = MODEL(inp_data)\n print(\"##one block finished\")\n total_loss = model_objective(entropy, out_data, logits)\n print(\"##second block finished\")\n model_gradient = model_tape.gradient(total_loss, tabnet_model.trainable_variables)\n print(\"## third block finished\")\n optimizer.apply_gradients(zip(model_gradient, tabnet_model.trainable_variables))\n\n\ndef training(dataset, epochs):\n for epoch in range(epochs):\n for i, (inp_data, out_data) in enumerate(dataset):\n print(f'{i}-iteration')\n training_steps(MODEL, inp_data, out_data)\n\ntraining(train_data, 2)\n","sub_path":"main_old.py","file_name":"main_old.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377158760","text":"\"\"\" Module for File Storage Manager.\nThis module defines the FileStorageManager class.\n\nClasses\n-------\nFileStorageManager(StorageManagerInterface):\n Define the FileStorageManager class for managing storage of timeseries data to database files.\n\nMethods\n-------\n__init__(self):\n Constructor of FileStorageManager, loading IDs for timeseries in the database\ngen_id(self):\n Generate an ID for a timeseries\nts2nparray(self, t):\n Convert a timeseries to a 2D np array in float64, returning a 2D np array\n containing time and value\nstore(self, id, t):\n Store the given timeseries t in database using the input id, returning the same timeseries\nsize(self, id):\n Get the size of timeseries using the given ID, returning int size of the timeseries\nget(self, id):\n Get the timeseries using an given ID, returning the timeseries of the given ID\n\n\"\"\"\n\nimport os\nimport numpy as np\nimport pickle\nfrom storagemanager.SMInterface import StorageManagerInterface\nfrom timeseries.ArrayTimeSeries import ArrayTimeSeries\n\n\nclass FileStorageManager(StorageManagerInterface):\n \"\"\" FileStorageManager(StorageManagerInterface):\n Define the FileStorageManager class for managing storage of timeseries data to database files.\n\n Methods\n -------\n __init__(self):\n Constructor of FileStorageManager, loading IDs for timeseries in the database\n gen_id(self):\n Generate an ID for a timeseries\n ts2nparray(self, t):\n Convert a timeseries to a 2D np array in float64, returning a 2D np array\n containing time and value\n store(self, id, t):\n Store the given timeseries t in database using the input id, returning the same timeseries\n size(self, id):\n Get the size of timeseries using the given ID, returning int size of the timeseries\n get(self, id):\n Get the timeseries using an given ID, returning the timeseries of the given ID\n\n \"\"\"\n def __init__(self):\n \"\"\"\n Constructor of FileStorageManager\n \"\"\"\n try:\n with open('data/id.pkl', 'rb') as f:\n self._id = pickle.load(f)\n except FileNotFoundError:\n self._id = set()\n\n @property\n def id(self):\n \"The id set\"\n return self._id\n\n @property\n def ts(self):\n \"The timeseries set\"\n for i in self.id:\n ts = self.get(i)\n yield ts\n\n def gen_id(self):\n \"\"\"\n Generate an ID for a timeseries\n :return: ID of a timeseries\n \"\"\"\n gid = 0\n while gid in self._id: gid += 1\n self._id.add(gid)\n return gid\n\n def ts2nparray(self, t):\n \"\"\"\n Convert a timeseries to a 2D np array in float64\n :param t: input timeseries\n :return: a 2D np array containing time and value\n \"\"\"\n return np.vstack((t.times, t.values)).astype(np.float64)\n\n def store(self, id, t):\n \"\"\"\n Store the given timeseries t in database using the input id\n :param id: assigned ID of timeseries,\n :param t: the timeseries to store\n :type id: int or string\n :type t: SizedContainerTimeSeriesInterface\n :return: the same timeseries\n :rtype: SizedContainerTimeSeriesInterface\n \"\"\"\n # np.save('data/ts.'+str(id), self.ts2nparray(t))\n np.savetxt('data/ts_data_'+str(id)+'.txt', np.transpose(np.array([list(t.itertimes()), list(t)])), delimiter=' ')\n\n self._id.add(id)\n with open('data/id.pkl', 'wb') as f:\n pickle.dump(self._id, f)\n return t\n\n def size(self, id):\n \"\"\"\n Get the size of timeseries using the given ID\n :param id: ID of timeseries\n :type id: int or string\n :return: size of the timeseries\n :rtype: int\n \"\"\"\n if not os.path.exists('data/ts.'+str(id)+'.npy'):\n raise ValueError(\"Timeseries with ID={0} does not exist.\".format(id))\n ts = np.loadtxt('data/ts_data_'+str(id)+'.txt', delimiter=' ')\n return ts.shape[0]\n # return len(np.load('data/ts.'+str(id)+'.npy')[0])\n\n def get(self, id):\n \"\"\"\n Get the timeseries using an given ID\n :param id: ID of timeseries\n :type id: int or string\n :return: timeseries of the given ID\n :rtype: SizedContainerTimeSeriesInterface\n \"\"\"\n if not os.path.exists('data/ts_data_'+str(id)+'.txt'):\n raise ValueError(\"Timeseries with ID={0} does not exist.\".format(id))\n ts = np.loadtxt('data/ts_data_'+str(id)+'.txt')\n return ArrayTimeSeries(ts[:, 1], ts[:, 0])\n","sub_path":"storagemanager/FileStorageManager.py","file_name":"FileStorageManager.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"492342864","text":"import time\nimport pickle\nimport os\n\nclass Subject:\n def __init__(self, number=666, session=\"\", run=\"\", experiment=\"unknown\", dataDir=\"\"):\t\t\n self.number = number\n self.session = session\n self.run = run\n self.date = time.strftime(\"%d_%b_%y_%I_%M%p\")\n #create dictionary to hold trial results\n self.fname = \"%s_%s_%s_%s_%s.csv\" % (number, experiment, session, run, self.date)\n self.experiment = experiment\n\n if dataDir:\n self.fname = os.path.join(dataDir, self.fname)\n\n self.results = {}\n self.statics = {}\n\n def addStatic(self, key, value):\n self.statics[key] = value\n\n #stimulus = image_dict[block].pop()\n #sub.inputData(trial, \"stimulus\", stimulus)\n def inputData(self, trial, condition, value):\n trial = str(trial)\n if self.results.has_key(trial):\n data = self.results[trial]\n data[condition] = value\n self.results[trial] = data\n else:\n data = {}\n data[condition] = value\n self.results[trial] = data\t\t\t\t\t\n\n\n def printData(self):\t\n trials = self.results.keys()\n intTrials = []\n for t in trials:\n intTrials.append(int(t))\n intTrials.sort()\n trials = []\n for t in intTrials:\n trials.append(str(t))\n f = open(self.fname, \"w\")\n\n #get the trial keys from the first row\n keys = []\n for t in trials:\n tk = self.results[t].keys()\n keys += tk\n trialKeys = list(set(keys))\n trialKeys.sort()\n\n #construct the header\n header = \"s_id,experiment,session,trial\"\n\n staticLine = \"\"\n\n if self.statics:\n keys = self.statics.keys()\n keys.sort()\n for k in keys:\n header += \",%s\" % k\n staticLine += \",%s\" % self.statics[k]\n\n for tk in trialKeys:\n header += \",%s\" % tk\n header += \"\\n\"\n\n f.write(header)\n\n #write each trial, filling in blank spaces\n for t in trials:\n line = \"%s,%s,%s,%s\" % (self.number, self.experiment, self.session, t)\n line += staticLine\n\n trial = self.results[t]\n for tk in trialKeys:\n if trial.has_key(tk):\n value = trial[tk]\n else:\n value = \"\"\n line += \",%s\" % value\n line = line + \"\\n\"\n f.write(line)\n\n f.close()\n\n def preserve(self):\n f = open(\"%s.sub\" % self.number, \"w\")\n pickle.dump(self, f)\n f.close()\n\n","sub_path":"subject.py","file_name":"subject.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"526715964","text":"class Player:\n\n player = None\n PlayerSpeed = 15\n\n def __init__(self, turtle):\n\n player = turtle.Turtle()\n player.color(\"blue\")\n player.shape(\"circle\")\n player.penup()\n player.speed(0)\n player.setposition(0, -250)\n self.player = player\n\n turtle.listen()\n turtle.onkey(self.moveRight, \"Right\")\n turtle.onkey(self.moveLeft, \"Left\")\n\n def moveRight(self):\n player = self.player\n x = self.player.xcor() + self.PlayerSpeed\n if(x > 280):\n x = 280\n player.setx(x)\n def moveLeft(self):\n player = self.player\n x = self.player.xcor() - self.PlayerSpeed\n if(x < -280):\n x = -280\n player.setx(x)","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164537868","text":"'''\nCreated on 19.08.2013\n\n@author: Walter\n\nThe number 145 is well known for the property that the sum of the factorial of\nits digits is equal to 145:\n\n1! + 4! + 5! = 1 + 24 + 120 = 145\n\nPerhaps less well known is 169, in that it produces the longest chain of\nnumbers that link back to 169; it turns out that there are only three such\nloops that exist:\n\n169 → 363601 → 1454 → 169\n871 → 45361 → 871\n872 → 45362 → 872\n\nIt is not difficult to prove that EVERY starting number will eventually get\nstuck in a loop. For example,\n\n69 → 363600 → 1454 → 169 → 363601 (→ 1454)\n78 → 45360 → 871 → 45361 (→ 871)\n540 → 145 (→ 145)\n\nStarting with 69 produces a chain of five non-repeating terms, but the longest\nnon-repeating chain with a starting number below one million is sixty terms.\n\nHow many chains, with a starting number below one million, contain exactly\nsixty non-repeating terms?\n'''\nimport unittest\n\n\ndef digit_factorial_chains(pInt):\n\n lCount = 0\n lMax = pInt - 1\n lSum = 0\n\n while (lCount < lMax):\n lCount += 1\n if lCount % 3 == 0 or lCount % 5 == 0:\n lSum += lCount\n\n return lSum\n\n\n# =============================================================================\n# Unit tests\n# -----------------------------------------------------------------------------\n\n\nclass Test(unittest.TestCase):\n\n def test_digit_factorial_chains_10(self):\n self.assertEqual(digit_factorial_chains(10), 23)\n\n def test_digit_factorial_chains_1000(self):\n self.assertEqual(digit_factorial_chains(1000), 233168)\n\n# =============================================================================\n# Solution of the Euler task\n# -----------------------------------------------------------------------------\n\n\nprint(digit_factorial_chains(1000))\n","sub_path":"problems/074_Solution.py","file_name":"074_Solution.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"517120295","text":"import sys\nimport os\nfrom shutil import copyfile\nfrom git import Repo\nfrom tag_helper import *\nfrom tex_helper import *\n\nrepoPath = sys.argv[1]\next = 'tex'\n\nos.chdir(repoPath)\n\n# Fix for bitbuckit pipeline -> is necessary for tag trigger\nos.system('git config remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\"')\nos.system('git fetch origin')\n\nprint('')\nprint('Branches')\nos.system('git branch')\nprint('')\n\nos.system('git checkout master')\nos.system('git pull origin master')\n\nrepo = Repo('./')\n\nif 'origin/publish' not in repo.refs:\n os.system('git branch publish')\n\nos.system('git checkout publish')\nos.system('git pull origin publish')\nos.system('git merge --strategy-option=theirs master')\n\nprint('')\nprint('current state')\nos.system('ls')\n\nprint('')\nos.system('git status')\n\ndoneList = []\ndoneNotList = []\n\nfor tag in repo.tags:\n tag = str(tag)\n\n if validateTag(tag):\n tagl = parseTag(tag)\n\n version = tagl[0]\n filenames = tagl[1:]\n filename = checkIfSourceFileExists(filenames, ext)\n\n if filename != False:\n\n pdfInPlace = checkIfVersionExists(filenames, version, 'pdf')\n\n if pdfInPlace == False:\n print(version)\n print(filename)\n print(tag)\n\n tagFile = tag + '.' + ext\n\n os.system('git checkout tags/' + tag)\n\n cwd = os.getcwd()\n\n if filename[2] is not '':\n os.chdir(filename[2])\n\n copyfile(filename[1], tagFile)\n addVersion(tagFile, version)\n generateLatexFile(tagFile)\n os.remove(tagFile)\n\n doneList.append(\"%s -> %s\" % (tag, tagFile))\n\n os.chdir(cwd)\n\n os.system('git checkout publish')\n os.system('git add -f *.pdf')\n os.system('git commit -m \"Robot build for tag: %s\"' % tag)\n os.system('git clean -f')\n os.system('git push origin publish')\n else:\n print(\"Skip \")\n doneNotList.append(\"%s -> pdf already in place\" % (tag))\n else:\n print(\"Skip \")\n doneNotList.append(\"%s -> tex file not in master\" % (tag))\n\nprint(\"\")\nprint(\"Generated %s versions\" % len(doneList))\nprint(\"\")\nfor done in doneList:\n print(done)\n\nprint(\"\")\nprint(\"Skipped %s versions\" % len(doneNotList))\nprint(\"\")\nfor doneNot in doneNotList:\n print(doneNot)\n\n","sub_path":"tag_rund/tag_run.py","file_name":"tag_run.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"602669296","text":"class Solution:\n\n def hitBricks(self, grid, hits):\n \"\"\"\n :type grid: List[List[int]]\n :type hits: List[List[int]]\n :rtype: List[int]\n \"\"\"\n\n m, n = len(grid), len(grid[0])\n\n # Connect unconnected bricks and\n def dfs(i, j):\n if not (0 <= i < m and 0 <= j < n) or grid[i][j] != 1:\n return 0\n ret = 1\n grid[i][j] = 2\n ret += dfs(i - 1, j)\n ret += dfs(i + 1, j)\n ret += dfs(i, j - 1)\n ret += dfs(i, j + 1)\n return ret\n\n # Check whether (i, j) is connected to Not Falling Bricks\n def is_connected(i, j):\n ret = False\n ret |= (h[0] - 1 >= 0 and grid[h[0] - 1][h[1]] == 2)\n ret |= (h[0] + 1 < m and grid[h[0] + 1][h[1]] == 2)\n ret |= (h[1] - 1 >= 0 and grid[h[0]][h[1] - 1] == 2)\n ret |= (h[1] + 1 < n and grid[h[0]][h[1] + 1] == 2)\n ret |= (h[0] == 0)\n return ret\n\n # Mark whether there is a brick at the each hit\n for h in hits:\n if grid[h[0]][h[1]] == 1:\n grid[h[0]][h[1]] = 0\n else:\n grid[h[0]][h[1]] = -1\n\n # Get grid after all hits\n for i in range(n):\n dfs(0, i)\n\n # Reversely add the block of each hits and get count of newly add bricks\n ret = [0] * len(hits)\n for i in reversed(range(len(hits))):\n h = hits[i]\n if grid[h[0]][h[1]] == -1:\n continue\n grid[h[0]][h[1]] = 1\n if not is_connected(h[0], h[1]):\n continue\n ret[i] = dfs(h[0], h[1]) - 1\n\n return ret\n\n\n# https://leetcode.com/problems/bricks-falling-when-hit/discuss/119829/Python-Solution-by-reversely-adding-bricks/119285?page=1\n\n# We can reverse the problem and count how many new no-dropping bricks are\n# added when we add the bricks reversely. It’s just the same of counting\n# dropping bricks when erase one brick.\n\n# Let m, n = len(grid), len(grid[0]).\n\n# Here is the detailed solution:\n\n# For each hit (i, j), if grid[i][j]==0, set grid[i][j]=-1 otherwise set grid[i][j]=0. Since a hit may happen at an empty position, we need to seperate emptys from bricks.\n# For i in [0, n], do dfs at grid[i][0] and mark no-dropping bricks. Here we get the grid after all hits.\n# Then for each hit (i,j) (reversely), first we check grid[i][j]==-1, if yes, it’s empty, skip this hit. Then we check whether it’s connected to any no-dropping bricks or it’s at the top, if not, it can’t add any no-dropping bricks, skip this hit. Otherwise we do dfs at grid[i][j], mark new added no-dropping bricks and record amount of them.\n# Return the amounts of new added no-dropping bricks at each hits.\n\n\n# Improved by li to li.py\n","sub_path":"problems/803.Bricks_Falling_When_Hit/LuckyPants.py","file_name":"LuckyPants.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"251941921","text":"import logging\n\nfrom Simulation import Simulation\nfrom examples.cstr.CSTRModel import CSTRModel\n\nif __name__ == \"__main__\":\n format = \"%(asctime)s: %(message)s\"\n logging.basicConfig(format=format, level=logging.INFO,\n datefmt=\"%H:%M:%S\")\n\n model = CSTRModel()\n simulation = Simulation(None, model, 1, 1)\n simulation.run()\n\n\n\n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"70862990","text":"from typing import List\n\n\nLOW = 284639\nHIGH = 748759\n\n\ndef is_not_descending(digits: List[int]) -> bool:\n \"\"\"Whether a number represented by `digits` has\n all digits not descending.\n\n Args:\n digits (list): the number as digits\n\n Returns:\n bool: True if the digits are not descending;\n False otherwise\n\n \"\"\"\n prev = digits.pop(0)\n for digit in digits:\n if prev > digit:\n return False\n else:\n prev = digit\n return True\n\n\ndef has_adjacent_digits(digits: List[int]) -> bool:\n \"\"\"Whether a number represented by `digits` has\n repeating digits.\n\n Args:\n digits (list): the number as digits\n\n Returns:\n bool: True if the number has repeating digits;\n False otherwise\n\n \"\"\"\n adj = 0\n ignored = []\n last = digits.pop(0)\n for digit in digits:\n if digit in ignored:\n continue\n elif digit == last:\n adj += 1\n if adj > 1:\n # Because the length of the code is only 6,\n # an \"invalid\" code will always be 3+, which\n # leaves only one possible pair if at all.\n # Furthermore, e.g. 111211 is not valid anyway,\n # so we can safely ignore 1.\n ignored.append(digit)\n adj = 0\n else:\n if adj > 0:\n return True\n last = digit\n\n # For cases where two consecutive digits are at the end,\n # flush the result. (adj == 1)\n if adj > 0:\n return True\n else:\n return False\n\n\ndef iterate_range() -> None:\n \"\"\"Iterate from `LOW` to `HIGH` to find the number of valid codes.\"\"\"\n valids = []\n for i in range(LOW, HIGH + 1):\n l = [int(x) for x in str(i)]\n if is_not_descending(l) and has_adjacent_digits(l):\n valids.append(i)\n\n print(len(valids))\n\n\nif __name__ == '__main__':\n iterate_range()\n","sub_path":"2019/4/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"438661639","text":"# -*- coding: utf-8 -*-\n__author__ = 'AllenCHM'\n\nimport json\nimport sys\nimport time\nimport re\n\nfrom scrapy.spider import Spider\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nimport requests\n\nfrom pcauto.items import PcautoItem\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass pcautoKSpider(Spider):\n name = u\"pcautoK\"\n allowed_domains = [u\"pcauto.com.cn\",\n ]\n start_urls = [\n u'http://price.pcauto.com.cn/comment/sg164/', #修改此处即可修改车型\n ]\n\n def __init__(self):\n self.host = u'http://price.pcauto.com.cn/comment/sg164/p'\n\n def parse(self, response):\n hxs = Selector(response)\n mainBodys = hxs.xpath('//div[@class=\"main_table clearfix\"]')\n if mainBodys:\n for mainBody in mainBodys:\n item = PcautoItem()\n item[u\"source\"] = u'太平洋汽车网'\n item[u\"author\"] = mainBody.xpath('.//div[@class=\"info\"]/a/text()').extract()[0].strip()\n tmp = mainBody.xpath('.//div[@class=\"car\"]/div[2]/span[2]/text()').extract()[0].strip()\n tmp = re.findall(u'(.*?)年(.*?)月', tmp)\n item[u\"registerDate\"] = tmp[0][0] + u'-' + tmp[0][1]\n item[u\"recordDate\"] = mainBody.xpath('.//div[@class=\"info\"]/p/a/text()').extract()[0].strip()[:-2]\n item[u\"attention\"] = mainBody.xpath('.//div[@class=\"car\"]/div[1]/span[2]/a/text()').extract()[0].strip()\n item[u\"addr\"] = mainBody.xpath('.//div[@class=\"car\"]/div[3]/span[2]/text()').extract()[0].strip()\n item[u\"content\"] = mainBody.xpath('.//div[@class=\"table_text clearfix\"]').xpath('string(.)').extract()[0].strip()\n item[u\"link\"] = mainBody.xpath('.//a[@data-event=\"toggleComment\"]/@data-url').extract()[0]\n tmp = mainBody.xpath('.//div[@class=\"corners\"]/a[contains(@class,\"good\")]/em/text()').extract()\n if tmp:\n item[u\"clicknum\"] = re.findall('\\((.*)\\)', tmp[0])[0]\n else:\n item[u\"clicknum\"] = 0\n # item[u\"title\"] = ''\n # item[u\"sourceEquipment\"] = ''\n item[u\"reContent\"] = self.reViewParse(item[u'link'])\n item[u\"datatype\"] = u'车主点评'\n item[u\"replynum\"] = len(item[u'reContent'])\n if item[u'reContent']:\n item[u\"lastReDate\"] = item[u'reContent'][0][u'recordDate']\n else:\n item[u\"lastReDate\"] = item[u\"recordDate\"]\n yield item\n\n nextPage = hxs.xpath('//div[@class=\"pcauto_page\"]/a[@class=\"next\"]') #下一页\n if nextPage:\n nextPage = nextPage.extract()[0]\n pageNum = re.findall('goCommentPage\\((.*?)\\)', nextPage)[0]\n nextPage = self.host + str(pageNum) + u'.html'\n yield Request(nextPage, callback=self.parse)\n\n\n def reViewParse(self, link):\n params = {\n u'urlHandle': u'1',\n u'url': link,\n u'pageSize': u'5',\n u'callback': u'jsonpdplg3qg',\n }\n url = u'http://cmt.pcauto.com.cn/action/comment/list_new_json.jsp'\n r = requests.get(url, params=params)\n try:\n tmp = re.findall(u'\\((.*)\\)', r.content)[0]\n tmp = json.loads(tmp)\n t = []\n for i in tmp[u'data']:\n data = {}\n data[u'content'] = i[u'content']\n data[u'recordDate'] = i[u'createTime']\n data[u'author'] = i[u'nickName']\n t.append(data)\n return t\n except:\n return []\n\n\n","sub_path":"太平洋汽车网/pcautoBB/pcauto/spiders/pcautoK.py","file_name":"pcautoK.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"408692370","text":"\"\"\"Optimize the quantum yield of a retinal model (Hahn, Susanne, and Gerhard Stock.\n\"Quantum-mechanical modeling of the femtosecond isomerization in rhodopsin.\"\nThe Journal of Physical Chemistry B 104.6 (2000): 1146-1149.)\"\"\"\n\n\nimport torch\nimport numpy as np\nimport os\nimport torch\nimport random\nimport pdb\nfrom math import pi\nimport sys\nimport json\n\nfrom torchmd.md import Isomerization\nfrom torchmd.sovlers import odeint_adjoint as odeint\n\n# time conversion\nFS_TO_EV = 41.341 / 27.2 \n# time step\nDT = 2 * pi / 2.8 / 30\n# max time\nTMAX = 1500 * FS_TO_EV\n# TMAX = 1 * FS_TO_EV\n\nNUM_EPOCHS = 50\n# NUM_EPOCHS = 5\n\n\n# pulse duration\nTAU = 10 * FS_TO_EV \n# center pulse frequency\nW0 = 2.4\n# pulse time\nTP = 3 * TAU\nDEVICE = 2\n\n# files for saving\nYIELD_FILE = 'isom_results/q_yields.json'\nFIELD_FILE = 'isom_results/e_fields.json'\nT_YIELD_FILE = 'isom_results/t_dep_yields.json'\n\ndef make_quants():\n\n\n \"\"\"Load matrices for the retinal model.\n Args:\n None\n Returns:\n dic (dict): dictionary of matrices (operators)\n \"\"\"\n\n # hamiltonian\n ham = torch.tensor(np.load('../data/isom/hamiltonian.npy')).float().to(DEVICE)\n # dipole operator\n dipole = torch.tensor(np.load('../data/isom/unitless_mu.npy')).float().to(DEVICE)\n # product projection operator\n prod_op = torch.tensor(np.load('../data/isom/Pt_11.npy')).float().to(DEVICE)\n # reactant projection operator\n reac_op = torch.tensor(np.load('../data/isom/Pc_00.npy')).float().to(DEVICE)\n # initial wave function is in the ground state\n # note that we double its size: the first half of the elements \n # are the real part, and the second half is the imaginary part\n psi_0 = torch.zeros(int(2*len(ham))).to(DEVICE)\n psi_0[0] = 1\n\n\n dic = {\"ham\": ham, \"dipole\": dipole, \"prod_op\": prod_op,\n \"reac_op\": reac_op, \"psi_0\": psi_0}\n\n return dic\n\n\ndef initialize_Et(dt=DT, tmax=TMAX, w0=W0, tau=TAU, tp=TP):\n\n \"\"\"Initialize a reasonable guess for the electric field\n and create the time grid.\n Args:\n dt (float): time step\n tmax (float): max time\n w0 (float): pulse center frequency\n tau (float): pulse duration\n tp (float): pulse arrival time\n Returns:\n combined (torch.Tensor): a tensor with elements\n (t, E(t))\n t_grid (torch.Tensor): time grid for the simulation\n t_grid_0 (torch.Tensor): coarse time grid for the\n first half of the simulation for E(t)\n \"\"\"\n\n # number of total steps\n num_steps = int(tmax/dt)\n # number of steps during which the electric field\n # can be non-zero. Take larger time steps so that\n # it can't vary more quickly than we can resolve\n first_num_steps = int(tmax/dt/5)\n\n # time grid for the electric field part\n t_grid_0 = torch.linspace(0, tmax/2, first_num_steps)\n # time grid for the rest\n t_grid_1 = torch.linspace(t_grid_0[-1] + dt, tmax, int(num_steps/2))\n\n # time grid for the rest of the simulation (more steps, finer grid)\n t_grid = torch.linspace(0, tmax, num_steps)\n\n\n # electric field amplitude: this number maximizes the population that\n # will make it to the excited state\n e0 = pi**0.5 / tau \n # E(t)\n e_t = e0 * np.cos(w0 * (t_grid_0-tp)) * np.exp(-(t_grid_0-tp)**2 / tau**2)\n # [t, E(t)]\n combined = torch.stack((t_grid_0, e_t), dim=-1)\n\n return combined, t_grid, t_grid_0\n\ndef calc_yield(psi_t, prod_op, reac_op):\n \"\"\" Calculate the quantum yield.\n \n Args:\n psi_t (torch.Tensor): wave function as a function of time\n prod_op (torch.Tensor): product operator\n reac_op (torch.Tensor): reactant operator\n Returns:\n expec_t (list): quantum yield as a function of time\n \n \"\"\"\n\n # dimension of the Hilbert space\n dim = int(len(psi_t[-1])/2)\n expec_t = []\n\n # loop over times\n for i in range(len(psi_t)):\n\n # real and imaginary parts of psi\n psi_r = psi_t[i, :dim]\n psi_i = psi_t[i, dim:]\n\n # expression for expectation values from the real and imaginary parts.\n # Valid for real-valued operators (which is the case here)\n\n # \n expec_r = (psi_r * (torch.matmul(prod_op, psi_r))).sum().reshape(-1)\n expec_i = (psi_i * (torch.matmul(prod_op, psi_i))).sum().reshape(-1)\n\n # \n expec_rC = (psi_r * (torch.matmul(reac_op, psi_r))).sum().reshape(-1)\n expec_iC = (psi_i * (torch.matmul(reac_op, psi_i))).sum().reshape(-1)\n\n # subtract the part that remained in the ground state\n pg = psi_r[0]**2 + psi_i[0] **2\n y = (expec_r + expec_i) / ((expec_r + expec_i) + (expec_rC + expec_iC) - pg)\n\n expec_t.append(y)\n\n return expec_t\n\n\ndef objective(expec_t, look_back=20000):\n\n \"\"\"\n Creates the objective function to minimize.\n Args:\n expec_t (list): time-dependent quantum yield\n look_back (int): number of previous time steps\n over which to average the yield\n Returns:\n obj (torch.Tensor): objective function\n Note:\n 20,000 time steps = 1 ps, since dt = 0.05 fs,\n so this defaults to averaging the QY over 1 ps.\n \"\"\"\n\n # want to maximize quantum yield (i.e. minimize its negative)\n obj = -torch.mean(torch.cat(expec_t)[-look_back:])\n\n return obj\n\ndef main():\n\n quant_dic = make_quants()\n e_field, t, t_grid_et = initialize_Et()\n max_e_t = max(t_grid_et)\n\n # initialize the ode\n ode = Isomerization(dipole=quant_dic[\"dipole\"], e_field=e_field, ham=quant_dic[\"ham\"],\n max_e_t=max_e_t, device=DEVICE).to(DEVICE)\n\n # define optimizer \n trainable_params = filter(lambda p: p.requires_grad, ode.parameters())\n optimizer = torch.optim.Adam(trainable_params, lr=1e-2)\n\n q_yields = []\n e_fields = []\n t_yields = []\n\n for i in range(NUM_EPOCHS):\n\n print(\"simulation epoch {}\".format(i))\n psi_0 = quant_dic['psi_0'].to(DEVICE)\n psi_t = odeint(ode, psi_0, t, method='rk4')\n q_yield = calc_yield(psi_t, quant_dic[\"prod_op\"].to(DEVICE), quant_dic[\"reac_op\"].to(DEVICE))\n\n loss = objective(q_yield)\n\n loss.backward()\n print(\"Average quantum yield is {}\".format(-loss.item()))\n\n q_yields.append(-loss.item())\n e_fields.append(ode.e_field.cpu().detach().numpy().tolist())\n t_dep_yield = [item.item() for item in q_yield]\n t_yields.append(t_dep_yield)\n\n with open(YIELD_FILE, 'w') as f:\n json.dump(q_yields, f)\n with open(T_YIELD_FILE, 'w') as f:\n json.dump(t_yields, f)\n with open(FIELD_FILE, 'w') as f:\n json.dump(e_fields, f)\n\n\n optimizer.step()\n optimizer.zero_grad()\n\nif __name__ == \"__main__\":\n\n if os.path.exists(\"isom_results/\") == False:\n os.makedirs(\"isom_results/\")\n\n main()\n","sub_path":"demo/isom.py","file_name":"isom.py","file_ext":"py","file_size_in_byte":6844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"579843698","text":"# Copyright (c) 2021 PaddlePaddle 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\nimport unittest\nimport warnings\n\nimport paddle\nfrom paddle.fluid.framework import _test_eager_guard\n\n\nclass TestTensorTypePromotion(unittest.TestCase):\n def setUp(self):\n self.x = paddle.to_tensor([2, 3])\n self.y = paddle.to_tensor([1.0, 2.0])\n\n def add_operator(self):\n with warnings.catch_warnings(record=True) as context:\n warnings.simplefilter(\"always\")\n self.x + self.y\n self.assertTrue(\n \"The dtype of left and right variables are not the same\"\n in str(context[-1].message)\n )\n\n def sub_operator(self):\n with warnings.catch_warnings(record=True) as context:\n warnings.simplefilter(\"always\")\n self.x - self.y\n self.assertTrue(\n \"The dtype of left and right variables are not the same\"\n in str(context[-1].message)\n )\n\n def mul_operator(self):\n with warnings.catch_warnings(record=True) as context:\n warnings.simplefilter(\"always\")\n self.x * self.y\n self.assertTrue(\n \"The dtype of left and right variables are not the same\"\n in str(context[-1].message)\n )\n\n def div_operator(self):\n with warnings.catch_warnings(record=True) as context:\n warnings.simplefilter(\"always\")\n self.x / self.y\n self.assertTrue(\n \"The dtype of left and right variables are not the same\"\n in str(context[-1].message)\n )\n\n def test_operator(self):\n with _test_eager_guard():\n pass\n # add / sub / mul / div has been sunk to cpp level, there is no warnings to catch by this test.\n self.setUp()\n self.add_operator()\n self.sub_operator()\n self.mul_operator()\n self.div_operator()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"python/paddle/fluid/tests/unittests/test_tensor_type_promotion.py","file_name":"test_tensor_type_promotion.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"285366222","text":"#!/usr/bin/env python\r\n# -*- coding: utf_8 -*-\r\n\"\"\"\r\n Modbus TestKit: Implementation of Modbus protocol in python\r\n\"\"\"\r\n\r\nimport modbus_tk\r\nimport modbus_tk.defines as cst\r\nfrom modbus_tk import modbus_tcp\r\n\r\n\r\ndef main():\r\n \"\"\"main\"\"\"\r\n logger = modbus_tk.utils.create_logger(\"console\")\r\n\r\n try:\r\n #Connect to the slave\r\n master = modbus_tcp.TcpMaster()\r\n master.set_timeout(5.0)\r\n logger.info(\"connected\")\r\n\r\n logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 0))\r\n\r\n #send some queries\r\n\r\n\r\n except modbus_tk.modbus.ModbusError as exc:\r\n logger.error(\"%s- Code=%d\", exc, exc.get_exception_code())\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"completed/6263/projects/02/tcp_master.py","file_name":"tcp_master.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"423705308","text":"from ..utility.lib import many_to_one_csv\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport pandas as pd\nimport numpy as np\nimport requests\nimport json\nimport re\nimport os\n\n\ndef scrape_from_feltrinelli(books_for_page, timeout, path_output, name_file_out):\n \"\"\"Scrape catalog from Feltrinelli's online books store and save it to csv format.\n\n Args:\n books_for_page (int): Number of books that will be send to us by the server for each request.\n timeout (int): How many seconds to wait for the server to send data before giving up.\n path_output (str): Path where catalog will be saved.\n name_file_out (str): Name of the final csv containing scraped data.\n \"\"\"\n total_books_catalog = 6460\n lst_titles = []\n lst_authors = []\n try:\n for i in range(1, round(total_books_catalog / books_for_page)):\n main_url = f\"https://www.lafeltrinelli.it/libri/c-1/0/{i}/?languageId=22&pblValue=%3C+20210000&type=1&cat1=1&sort=0&pageSize={books_for_page}\"\n response = requests.get(main_url, timeout)\n soup_main = BeautifulSoup(response.text, \"html.parser\")\n div_item = soup_main.find(\"div\", {\"class\": \"product-result\"})\n book_href = div_item.findAll(\"div\", {\"class\": \"cover\"})\n book_descriptions = div_item.findAll(\"div\", {\"class\": \"description\"})\n for book_link in book_href:\n link = book_link.a[\"href\"].strip()\n lst_titles.append(link)\n for book_desc in book_descriptions:\n author = book_desc.h4.text.strip()\n lst_authors.append(author)\n print(f\"Page {i} finished!\")\n except requests.ConnectionError as e:\n print(\n \"OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\\n\"\n )\n print(str(e))\n except requests.Timeout as e:\n print(\"OOPS!! Timeout Error\")\n print(str(e))\n except requests.RequestException as e:\n print(\"OOPS!! General Error\")\n print(str(e))\n except KeyboardInterrupt:\n print(\"Someone closed the program\")\n finally:\n try:\n list_cols = [\"title\", \"author\"]\n rows = list(zip(lst_titles, lst_authors))\n final_df = pd.DataFrame(rows, columns=list_cols)\n # create output directory if not exists, otherwise skip\n os.makedirs(path_output, exist_ok=True)\n output_path = os.path.join(path_output, name_file_out)\n final_df.to_csv(output_path, index=False)\n except Exception as ex:\n print(\"Unable to store records in CSV file. Technical details below.\\n\")\n print(str(ex))\n\n\ndef scrape_from_ny(\n starting_index,\n ending_index,\n timeout,\n out_dir_split,\n out_dir_full_csv,\n name_full_csv,\n):\n \"\"\"\n Getting New York Public Library's books catalog\n LINK: https://catalog.nypl.org/search~S1?/X(*)&searchscope=1&l=eng&m=a&SORT=D/X(*)&searchscope=5&l=eng&m=a&SORT=D&SUBKEY=(*)/1%2C32000%2C32000%2CB/browse\n\n This function make a request to the 'main_link' url passing the first index of the book at each iteration.\n In each page there are 50 books, each of which has a unique index, all index are sorted in ascending order.\n This function extracts info from all the books which index is in the range [starting_index, starting_index+50] and at each\n iteration we increase the starting index by 50. Then we nagivate in the DOM of the page and collects all data\n in a pandas dataframe.\n\n Args:\n starting_index (int): Index of the first book from which extract info.\n ending_index (int): Index of the last book from which extract info.\n timeout (int): Stop waiting for a response after a given number of seconds.\n out_dir_split (str): Path where csv extracted from each page where saved.\n out_dir_full_csv (str): Path where merged csv will be saved.\n name_full_csv (type): Name of the merged csv file.\n \"\"\"\n # create output directory if not exists, otherwise skip\n os.makedirs(out_dir_split, exist_ok=True)\n # final dataset's columns\n list_cols = [\"author\", \"title\", \"publish_year\", \"location\"]\n # interate until the last page which contains books which have indices in the range [starting_index, starting_index + 50]\n for i in range(starting_index, ending_index + 1, 50):\n main_link = f\"https://catalog.nypl.org/search~S1?/X(*)&searchscope=1&l=eng&m=a&SORT=D/X(*)&searchscope=5&l=eng&m=a&SORT=D&SUBKEY=(*)/{i}%2C32000%2C32000%2CB/browse\"\n while True:\n # try to connect to the page\n try:\n page = requests.get(main_link, timeout=timeout)\n break\n except (requests.ConnectionError, requests.Timeout) as e:\n print(\n f\"C'è stato il seguente errore: {e}!\\n\\nCi dormo sopra, mi sveglierò tra 15 secondi! \\U0001F634\"\n )\n # wait 15s then retry to connect\n sleep(15)\n continue\n print(f\"Elaborazione libri a partire dall'indice {i}...\")\n soup = BeautifulSoup(page.text, \"html.parser\")\n # find all td tags which class is \"briefcitDetail\"\n td_tags = soup.find_all(\"td\", class_=[\"briefcitDetail\"])\n # regex used to get the name of the authors\n auth_re = re.compile(r\"(\\w*,\\s\\w*)\")\n books_info = []\n for td in td_tags:\n res = auth_re.search(td.text.strip())\n if res:\n book_author = res.group(1)\n else:\n book_author = \"\"\n # find span which contains book's title\n container = td.find(\"span\", class_=\"briefcitTitle\")\n book_title = container.text.strip()\n # find div tag which contains book's publis year\n book_publishYear = container.findNext(\"div\").text.strip()\n # find all tr tags whic class is 'briefcitDetail'\n location_list = td.find_all(\"tr\", class_=\"briefcitDetail\")\n # using set to eliminate duplicate location\n book_location = list(\n set([location.find(\"td\").text.strip() for location in location_list])\n )\n if not len(book_location):\n book_location = \"\"\n # create a tupla which contains all book's info\n tupla = (book_author, book_title, book_publishYear, book_location)\n # append tupla to a list which contains all books in that page\n books_info.append(tupla)\n # create pandas dataframe for each page (reusable)\n df = pd.DataFrame(books_info, columns=list_cols)\n df.replace(\",\", \" \", regex=True, inplace=True)\n # create dynamically out path\n out_path = os.path.join(out_dir_split, f\"ny_{i}.csv\")\n # save csv\n df.to_csv(out_path, index=False)\n print(f\"Tutti i libri dall'indice {i} all'indice {i+50} sono stati estratti!\")\n print(\n f\"Tutti i libri aventi indice da {starting_index} a {ending_index} sono stati memorizzati in {out_dir_split}.\\\n \\nAdesso unisco in un unico CSV...\"\n )\n many_to_one_csv(out_dir_split, out_dir_full_csv, name_full_csv)\n print(f\"È stato creato un unico csv nel path {out_dir_full_csv}\")\n\n\ndef enr_from_mondadori(fltr_dataset, path_output, name_file_out):\n \"\"\"Take the already enriched Feltrinelli's dataset and further enrich with data taken by Mondadori website.\n\n Args:\n fltr_dataset (pd.Dataset): Feltrinelli's dataset to enrich with Mondadori's data.\n path_output (str): path were the result dataset will be saved.\n name_file_out (str): namefile of the result dataset.\n\n Returns:\n [pd.Dataset]: dataset enriched with Mondadori's data.\n \"\"\"\n # create new columns for data taken from Mondadori\n fltr_dataset[\"description\"] = np.nan\n fltr_dataset[\"price\"] = np.nan\n fltr_dataset[\"mondadori_url\"] = np.nan\n timeout = 15\n start_idx = 0\n end_idx = 6474\n fltr_dataset = fltr_dataset.iloc[start_idx:end_idx].copy()\n try:\n for i, row in fltr_dataset.iterrows():\n author = \"\"\n description = \"\"\n price = \"\"\n format = \"\"\n publisher = \"\"\n language = \"\"\n publish_year = \"\"\n category = \"\"\n n_pages = \"\"\n book_isbn = row[\"isbn_13\"]\n main_url = f\"https://www.mondadoristore.it/search/?g={book_isbn}&swe=N&search-input=active\"\n response = requests.get(main_url, timeout=timeout)\n if not \"Prova a impostarne una nuova\" in response.text:\n if \"Ordinati per rilevanza\" in response.text:\n # take the first book if there's more than one book with the first name\n temp_soup = BeautifulSoup(response.text, \"html.parser\")\n link_first_title = temp_soup.find(\"h3\", {\"class\": \"title\"}).a[\n \"href\"\n ]\n main_url = link_first_title\n response = requests.get(main_url, timeout=timeout)\n soup_main = BeautifulSoup(response.text, \"html.parser\")\n # find authors\n list_auth = soup_main.findAll(\"a\", {\"class\": \"nti-author\"})\n authors_name = [a.text.strip() for a in list_auth]\n author = \",\".join(authors_name)\n # find editor\n publisher = soup_main.find(\"a\", {\"class\": \"nti-editor\"}).text.strip()\n # find price\n price = soup_main.find(\"span\", {\"class\": \"new-detail-price\"})[\"content\"]\n # find description\n div_description = soup_main.find(\"p\", {\"itemprop\": \"description\"})\n if div_description:\n description = div_description.text.strip()\n # others books' attributes\n table_detail = soup_main.find(\"div\", {\"class\": \"product-details\"})\n text_full_list = table_detail.findAll(\"p\", {\"class\": \"text-full\"})\n for _, detail in enumerate(text_full_list):\n attribute_span = detail.find(\"span\", {\"class\": \"intestation\"})\n attribute_name = attribute_span.text.strip()\n if attribute_name == \"Generi\":\n category = (\n attribute_span.find_next_siblings(\"span\")[0]\n .text.strip()\n .split(\"»\")[0]\n )\n if attribute_name == \"Editore\":\n publisher = attribute_span.find_next_siblings(\"span\")[\n 0\n ].text.strip()\n if attribute_name == \"Formato\":\n format = attribute_span.find_next_siblings(\"span\")[\n 0\n ].text.strip()\n if attribute_name == \"Pubblicato\":\n publish_year = attribute_span.find_next_siblings(\"span\")[\n 0\n ].text.strip()\n if attribute_name == \"Pagine\":\n n_pages = attribute_span.find_next_siblings(\"span\")[\n 0\n ].text.strip()\n if attribute_name == \"Lingua\":\n language = attribute_span.find_next_siblings(\"span\")[\n 0\n ].text.strip()\n fltr_dataset.loc[i, \"mondadori_url\"] = main_url\n fltr_dataset.loc[i, \"price\"] = price\n fltr_dataset.loc[i, \"description\"] = description\n # check if data are already be taken by OL datasets\n if pd.isna(fltr_dataset.loc[i, \"publishers\"]):\n if pd.isna(fltr_dataset.loc[i, \"author\"]):\n fltr_dataset.loc[i, \"author\"] = author\n fltr_dataset.loc[i, \"publishers\"] = publisher\n fltr_dataset.loc[i, \"languages\"] = language\n fltr_dataset.loc[i, \"number_of_pages\"] = n_pages\n fltr_dataset.loc[i, \"physical_format\"] = format\n fltr_dataset.loc[i, \"publish_date\"] = publish_year\n fltr_dataset.loc[i, \"subjects\"] = category\n else:\n if pd.isna(fltr_dataset.loc[i, \"author\"]):\n fltr_dataset.loc[i, \"author\"] = author\n if pd.isna(fltr_dataset.loc[i, \"subjects\"]):\n fltr_dataset.loc[i, \"subjects\"] = category\n if pd.isna(fltr_dataset.loc[i, \"publishers\"]):\n fltr_dataset.loc[i, \"publishers\"] = publisher\n if pd.isna(fltr_dataset.loc[i, \"physical_format\"]):\n fltr_dataset.loc[i, \"physical_format\"] = format\n if pd.isna(fltr_dataset.loc[i, \"publish_date\"]):\n fltr_dataset.loc[i, \"publish_date\"] = publish_year\n if pd.isna(fltr_dataset.loc[i, \"number_of_pages\"]):\n fltr_dataset.loc[i, \"number_of_pages\"] = n_pages\n if pd.isna(fltr_dataset.loc[i, \"languages\"]):\n fltr_dataset.loc[i, \"languages\"] = language\n print(f\"IDX. {i} PROCESSED --> {main_url}\")\n else:\n print(f\"URL NOT FOUND --> {main_url}\")\n except requests.ConnectionError as e:\n print(\n \"OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\\n\"\n )\n print(str(e))\n except requests.Timeout as e:\n print(\"OOPS!! Timeout Error\")\n print(str(e))\n except requests.RequestException as e:\n print(\"OOPS!! General Error\")\n print(str(e))\n except KeyboardInterrupt:\n print(\"Execution ended because of keyboard shortcut!\")\n finally:\n try:\n print(f\"Interrupted at rows number: {i} ** URL --> {main_url}\")\n os.makedirs(path_output, exist_ok=True)\n output_path = os.path.join(path_output, name_file_out)\n fltr_dataset.to_csv(output_path, index=False)\n print(f\"'{name_file_out}' saved in '{path_output}'\")\n return fltr_dataset\n except Exception as ex:\n print(\"Unable to store records in CSV file. Technical details below.\\n\")\n print(str(ex))\n\n\ndef enr_from_hoepli(fltr_mond, path_output, name_file_out, timeout):\n \"\"\"Take the dataset enriched with Mondadori and try to fill unavailable data with data taken from Hoepli.\n\n Args:\n fltr_mond ([pd.Dataframe]): dataset enriched with Mondadori that will be enriched with Hoepli\n path_output (str): path were the result dataset will be saved.\n name_file_out (str): namefile of the result dataset.\n timeout ([int]): number of seconds to wait on a response before timing out.\n\n Returns:\n [pd.Dataframe]: final dataset where Feltrinelli's books are enriched with Mondadori, Open Library and Hoeply's book catalogue.\n \"\"\"\n num_enrich = 0\n start_idx = 0\n end_idx = 6474\n fltr_mond[\"hoepli_url\"] = np.nan\n fltr_mond = fltr_mond.iloc[start_idx:end_idx].copy()\n try:\n print(\"Getting data from Hoepli...\")\n for i, row in fltr_mond.iterrows():\n book_isbn = row[\"isbn_13\"]\n main_url = \"https://www.hoepli.it/cerca/libri.aspx?query=9788853630360\"\n main_url = f\"https://www.hoepli.it/cerca/libri.aspx?query={book_isbn}\"\n response = requests.get(main_url, timeout=timeout)\n # check if the book exists\n if not \"non ha prodotto risultati\" in response.text:\n print(f\"IDX {i} --> {main_url}\")\n soup_main = BeautifulSoup(response.text, \"html.parser\")\n dict_info_book = {}\n r_fields = r\">(\\w+\\s?\\w+)(?=:).*\\>(\\w+|\\d+/?\\d+)<\"\n # iterate for each match and create a new key-value pair in the dict\n for details in re.finditer(r_fields, response.text.lower().strip()):\n dict_info_book[details.group(1)] = details.group(2)\n r_price = re.compile(\".*price|prezzo.*\")\n # get book's price\n dict_info_book[\"price\"] = (\n soup_main.find(\"div\", {\"class\": r_price})\n .span.text.strip()\n .split(\" \")[0]\n .replace(\",\", \".\")\n )\n # get book's category/subject\n if soup_main.findAll(\"span\", {\"class\": \"fs11\"}):\n dict_info_book[\"category\"] = soup_main.findAll(\n \"span\", {\"class\": \"fs11\"}\n )[1].text.strip()\n else:\n dict_info_book[\"category\"] = \"\"\n r_description = r\"\\\"description\\\":\\s\\\"(.*)\\\"\"\n search = re.search(r_description, response.text)\n if search is not None:\n dict_info_book[\"description\"] = search.group(1)\n else:\n # if description is not present in the metadata, search for the plot (TRAMA)\n r_description = re.compile(\".*lh22.*\")\n div_description = soup_main.findAll(\"div\", {\"class\": r_description})\n # if there're more than 2 div with lh22 class, the element at 1-th position will be always the description\n if len(div_description) > 2:\n dict_info_book[\"description\"] = (\n div_description[1].text.lower().strip()\n )\n if pd.isna(fltr_mond.loc[i, \"publishers\"]):\n fltr_mond.loc[i, \"publishers\"] = dict_info_book.get(\n \"editore\", np.nan\n )\n if pd.isna(fltr_mond.loc[i, \"number_of_pages\"]):\n fltr_mond.loc[i, \"number_of_pages\"] = dict_info_book.get(\n \"pagine arabe\", np.nan\n )\n if pd.isna(fltr_mond.loc[i, \"physical_format\"]):\n fltr_mond.loc[i, \"physical_format\"] = dict_info_book.get(\n \"formato\", np.nan\n )\n if pd.isna(fltr_mond.loc[i, \"publish_date\"]):\n fltr_mond.loc[i, \"publish_date\"] = dict_info_book.get(\n \"pubblicazione\", np.nan\n )\n if pd.isna(fltr_mond.loc[i, \"subjects\"]):\n fltr_mond.loc[i, \"subjects\"] = dict_info_book.get(\n \"category\", np.nan\n )\n if pd.isna(fltr_mond.loc[i, \"description\"]):\n fltr_mond.loc[i, \"description\"] = dict_info_book.get(\n \"description\", np.nan\n )\n if pd.isna(fltr_mond.loc[i, \"price\"]):\n fltr_mond.loc[i, \"price\"] = dict_info_book.get(\"price\", np.nan)\n if pd.isna(fltr_mond.loc[i, \"languages\"]):\n fltr_mond.loc[i, \"languages\"] = dict_info_book.get(\"lingua\", np.nan)\n fltr_mond.loc[i, \"hoepli_url\"] = main_url\n num_enrich += 1\n if i % 500 == 0:\n print(f\"I'm in the {i}th row...\")\n else:\n pass\n except requests.ConnectionError as e:\n print(\n \"OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\\n\"\n )\n print(str(e))\n except requests.Timeout as e:\n print(\"OOPS!! Timeout Error\")\n print(str(e))\n except requests.RequestException as e:\n print(\"OOPS!! General Error\")\n print(str(e))\n except KeyboardInterrupt:\n print(\"Someone closed the program\")\n finally:\n try:\n # create folder where the enriched dataset will be saved, create if it doesn't exist\n os.makedirs(path_output, exist_ok=True)\n output_path = os.path.join(path_output, name_file_out)\n fltr_mond.to_csv(output_path, index=False)\n print(\n f\"{num_enrich} books were enriched.\\n'{name_file_out}' was enriched with Hoepli and saved in '{path_output}'\"\n )\n return fltr_mond\n except Exception as ex:\n print(\"Unable to store records in CSV file. Technical details below.\\n\")\n print(str(ex))","sub_path":"lib/scraping/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":20655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"528259013","text":"from flask import abort, jsonify, request\nfrom . import workout_app, system\n\n@workout_app.route('/workouts', methods=['GET', 'POST']) \ndef workouts_requests():\n data = request.form.to_dict()\n # get workouts\n if request.method == 'GET':\n return jsonify(system.workouts)\n # add workout\n elif request.method == 'POST':\n try:\n workout = system.add_workout(**data)\n except Exception as ex:\n return str(ex), 400\n else:\n return jsonify(workout)\n\n@workout_app.route('/workout/', methods=['GET', 'PATCH', 'POST', 'DELETE'])\ndef workout_requests(workout_id):\n workout = system.get_workout_by_id(workout_id)\n data = request.form.to_dict()\n if not workout:\n abort(404)\n # get workout\n if request.method == 'GET':\n return jsonify(workout)\n # update workout\n elif request.method == 'PATCH':\n try:\n workout.set(**data)\n except Exception as ex:\n return str(ex), 400\n else:\n return jsonify(workout)\n # add exercise to workout\n elif request.method == 'POST':\n try:\n exercise = workout.add_exercise(**data)\n except Exception as ex:\n return str(ex), 400\n else:\n return jsonify(exercise)\n # delete workout\n elif request.method == 'DELETE':\n system.remove_workout(workout)\n return '', 204\n \n\n \n","sub_path":"backend/routes/Workout/workout_requests.py","file_name":"workout_requests.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"146013029","text":"\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\n\ndef image_to_pointcloud(depth, intrinsics):\n assert depth.dim() == 4\n assert depth.size(1) == 1\n\n X = depth * intrinsics.X_cam\n Y = depth * intrinsics.Y_cam\n return torch.cat((X, Y, depth), dim=1)\n\n\ndef pointcloud_to_image(pointcloud, intrinsics):\n assert pointcloud.dim() == 4\n\n batch_size = pointcloud.size(0)\n X = pointcloud[:, 0, :, :] #.view(batch_size, -1)\n Y = pointcloud[:, 1, :, :] #.view(batch_size, -1)\n Z = pointcloud[:, 2, :, :].clamp(min=1e-3) #.view(batch_size, -1)\n\n # compute pixel coordinates\n U_proj = intrinsics.fu * X / Z + intrinsics.cu # horizontal pixel coordinate\n V_proj = intrinsics.fv * Y / Z + intrinsics.cv # vertical pixel coordinate\n\n # normalization to [-1, 1], required by torch.nn.functional.grid_sample\n U_proj_normalized = (2 * U_proj / (intrinsics.width - 1) - 1).view(batch_size, -1)\n V_proj_normalized = (2 * V_proj / (intrinsics.height - 1) - 1).view(batch_size, -1)\n\n # This was important since PyTorch didn't do as it claimed for points out of boundary\n # See https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py\n # Might not be necessary any more\n U_proj_mask = ((U_proj_normalized > 1) + (U_proj_normalized < -1)).detach()\n U_proj_normalized[U_proj_mask] = 2\n V_proj_mask = ((V_proj_normalized > 1) + (V_proj_normalized < -1)).detach()\n V_proj_normalized[V_proj_mask] = 2\n\n pixel_coords = torch.stack([U_proj_normalized, V_proj_normalized], dim=2) # [B, H*W, 2]\n return pixel_coords.view(batch_size, intrinsics.height, intrinsics.width, 2)\n\n\ndef batch_multiply(batch_scalar, batch_matrix):\n # input: batch_scalar of size b, batch_matrix of size b * 3 * 3\n # output: batch_matrix of size b * 3 * 3\n batch_size = batch_scalar.size(0)\n output = batch_matrix.clone()\n for i in range(batch_size):\n output[i] = batch_scalar[i] * batch_matrix[i]\n return output\n\n\ndef transform_curr_to_near(pointcloud_curr, r_mat, t_vec, intrinsics):\n\n # translation and rotmat represent the transformation from tgt pose to src pose\n batch_size = pointcloud_curr.size(0)\n XYZ_ = torch.bmm(r_mat, pointcloud_curr.view(batch_size, 3, -1))\n\n X = (XYZ_[:, 0, :] + t_vec[:, 0].unsqueeze(1)).view(-1, 1, intrinsics.height, intrinsics.width)\n Y = (XYZ_[:, 1, :] + t_vec[:, 1].unsqueeze(1)).view(-1, 1, intrinsics.height, intrinsics.width)\n Z = (XYZ_[:, 2, :] + t_vec[:, 2].unsqueeze(1)).view(-1, 1, intrinsics.height, intrinsics.width)\n\n pointcloud_near = torch.cat((X, Y, Z), dim=1)\n\n return pointcloud_near\n\n\ndef homography_from(rgb_near, depth_curr, r_mat, t_vec, intrinsics):\n # inverse warp the RGB image from the nearby frame to the current frame\n\n # to ensure dimension consistency\n r_mat = r_mat.view(-1, 3, 3)\n t_vec = t_vec.view(-1, 3)\n\n # compute source pixel coordinate\n pointcloud_curr = image_to_pointcloud(depth_curr, intrinsics)\n pointcloud_near = transform_curr_to_near(pointcloud_curr, r_mat, t_vec, intrinsics)\n pixel_coords_near = pointcloud_to_image(pointcloud_near, intrinsics)\n\n # the warping\n warped = F.grid_sample(rgb_near, pixel_coords_near)\n\n return warped\n\n\n\nclass Intrinsics:\n def __init__(self, width, height, fu, fv, cu=0, cv=0):\n self.height, self.width = height, width\n self.fu, self.fv = fu, fv # fu, fv: focal length along the horizontal and vertical axes\n\n # cu, cv: optical center along the horizontal and vertical axes\n self.cu = cu if cu > 0 else (width - 1) / 2.0\n self.cv = cv if cv > 0 else (height - 1) / 2.0\n\n # U, V represent the homogeneous horizontal and vertical coordinates in the pixel space\n self.U = torch.arange(start=0, end=width).expand(height, width).float()\n self.V = torch.arange(start=0, end=height).expand(width, height).t().float()\n \n # X_cam, Y_cam represent the homogeneous x, y coordinates (assuming depth z=1) in the camera coordinate system\n self.X_cam = (self.U - self.cu) / self.fu\n self.Y_cam = (self.V - self.cv) / self.fv\n\n self.is_cuda = False\n\n def cuda(self):\n self.X_cam.data = self.X_cam.data.cuda()\n self.Y_cam.data = self.Y_cam.data.cuda()\n self.is_cuda = True\n return self\n\n def scale(self, height, width):\n # return a new set of corresponding intrinsic parameters for the scaled image\n ratio_u = float(width) / self.width\n ratio_v = float(height) / self.height\n fu = ratio_u * self.fu\n fv = ratio_v * self.fv\n cu = ratio_u * self.cu\n cv = ratio_v * self.cv\n new_intrinsics = Intrinsics(width, height, fu, fv, cu, cv)\n if self.is_cuda:\n new_intrinsics.cuda()\n return new_intrinsics\n\n def __print__(self):\n print('size=({},{})\\nfocal length=({},{})\\noptical center=({},{})'.\n format(self.height, self.width, self.fv, self.fu, self.cv,\n self.cu))\n\n\ndef _SSIM(x, y):\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n\n mu_x = nn.AvgPool2d(3, 1)(x)\n mu_y = nn.AvgPool2d(3, 1)(y)\n mu_x_mu_y = mu_x * mu_y\n mu_x_sq = mu_x.pow(2)\n mu_y_sq = mu_y.pow(2)\n\n sigma_x = nn.AvgPool2d(3, 1)(x * x) - mu_x_sq\n sigma_y = nn.AvgPool2d(3, 1)(y * y) - mu_y_sq\n sigma_xy = nn.AvgPool2d(3, 1)(x * y) - mu_x_mu_y\n\n SSIM_n = (2 * mu_x_mu_y + C1) * (2 * sigma_xy + C2)\n SSIM_d = (mu_x_sq + mu_y_sq + C1) * (sigma_x + sigma_y + C2)\n SSIM = SSIM_n / SSIM_d\n\n SSIM_img = torch.clamp((1 - SSIM) / 2, 0, 1)\n\n return F.pad(SSIM_img, pad=(1, 1, 1, 1), mode='constant', value=0)\n\n\n\nclass L1Loss(nn.Module):\n def __init__(self, args):\n super(L1Loss, self).__init__()\n\n self.args = args\n self.t_valid = 0.0001\n\n def forward(self, gt, pred):\n gt = torch.clamp(gt, min=0, max=self.args.maxdisp)\n pred = torch.clamp(pred, min=0, max=self.args.maxdisp)\n\n mask = (gt > self.t_valid).type_as(pred).detach()\n\n d = torch.abs(pred - gt) * mask\n \n d = torch.sum(d, dim=[1, 2])\n num_valid = torch.sum(mask, dim=[1, 2])\n\n loss = d / (num_valid + 1e-8)\n\n loss = loss.sum()\n\n return loss\n\nclass L2Loss(nn.Module):\n def __init__(self, args):\n super(L2Loss, self).__init__()\n\n self.args = args\n self.t_valid = 0.0001\n\n def forward(self, gt, pred):\n gt = torch.clamp(gt, min=0, max=self.args.maxdisp)\n pred = torch.clamp(pred, min=0, max=self.args.maxdisp)\n\n mask = (gt > self.t_valid).type_as(pred).detach()\n\n d = torch.pow(pred - gt, 2) * mask\n\n d = torch.sum(d, dim=[1, 2])\n num_valid = torch.sum(mask, dim=[1, 2])\n\n loss = d / (num_valid + 1e-8)\n\n loss = loss.sum()\n\n return loss\n\n\nclass PhotometricLoss(nn.Module):\n def __init__(self):\n super(PhotometricLoss, self).__init__()\n \n self.F = 320\n self.B = 0.25\n \n self.r_mat = torch.eye(3)\n self.t_vec = torch.tensor([self.B, 0, 0])\n self.intrinsics = Intrinsics(640,480, self.F, self.F)\n\n def forward(self, rgb_right, rgb_left, depth_right):\n\n # compute the corresponding intrinsic parameters\n batch, channel, height_, width_ = depth_right.shape\n #intrinsics_ = self.intrinsics.scale(height_, width_)\n\n # inverse warp from a nearby frame to the current frame\n warped_ = homography_from(rgb_left, depth_right, self.r_mat, self.t_vec, self.intrinsics_)\n \n \"\"\"\n plt.imshow(rgb_left[0].permute(1,2,0) / 255.0)\n plt.show()\n plt.imshow(rgb_right[0].permute(1,2,0) / 255.0)\n plt.show()\n plt.imshow(warped_[0].permute(1,2,0) / 255.0)\n plt.show()\n \"\"\"\n\n \n \n #diff = (warped_ - rgb_right).abs()\n #diff = torch.sum(diff, 1) # sum along the color channel\n diff = _SSIM(warped_, rgb_right)\n\n \"\"\"\n plt.imshow(diff[0].permute(1,2,0) / 255.0)\n plt.show()\n \"\"\"\n \n # compare only pixels that are not black\n valid_mask = (torch.sum(warped_, 1) > 0).float() * (torch.sum(rgb_left, 1) > 0).float()\n valid_mask = valid_mask.byte().detach()\n if valid_mask.numel() > 0:\n\n diff = diff * valid_mask\n \n \"\"\"\n plt.imshow(valid_mask[0])\n plt.show()\n plt.imshow(diff[0])\n plt.show()\n \"\"\"\n \n if diff.nelement() > 0:\n self.loss = diff.mean()\n else:\n print(\n \"warning: diff.nelement()==0 in PhotometricLoss (this is expected during early stage of training, try larger batch size).\"\n )\n self.loss = 0\n else:\n print(\"warning: 0 valid pixel in PhotometricLoss\")\n self.loss = 0\n return self.loss\n\nclass InputOutputLoss(nn.Module):\n def __init__(self, args):\n super(InputOutputLoss, self).__init__()\n\n self.maxdisp = args.maxdisp\n \n def forward(self, input, output):\n\n mask = input < self.maxdisp\n mask.detach_()\n # loss = F.smooth_l1_loss(pred[mask], GT[mask], size_average=True)\n loss = (input[mask] - output[mask]).abs().mean()\n\n return loss\n\nclass SmoothnessLoss(nn.Module):\n def __init__(self):\n super(SmoothnessLoss, self).__init__()\n\n def forward(self, depth):\n def second_derivative(x):\n assert x.dim(\n ) == 4, \"expected 4-dimensional data, but instead got {}\".format(\n x.dim())\n horizontal = 2 * x[:, :, 1:-1, 1:-1] - x[:, :, 1:-1, :\n -2] - x[:, :, 1:-1, 2:]\n vertical = 2 * x[:, :, 1:-1, 1:-1] - x[:, :, :-2, 1:\n -1] - x[:, :, 2:, 1:-1]\n der_2nd = horizontal.abs() + vertical.abs()\n return der_2nd.mean()\n\n self.loss = second_derivative(depth)\n return self.loss\n\n\nclass Loss(nn.Module):\n def __init__(self, args):\n super(Loss, self).__init__()\n\n loss = args.loss.split(\"+\")\n self.fn = []\n self.ln = [] \n self.weights = []\n for l in loss:\n w, ln = l.split(\"*\")\n if ln == 'l1':\n loss_fn = L1Loss(args)\n elif ln == 'l2':\n loss_fn = L2Loss(args)\n elif ln == 'photo':\n loss_fn = PhotometricLoss(args)\n elif ln == 'smooth':\n loss_fn = SmoothnessLoss(args)\n elif ln == 'inputoutput':\n loss_fn = InputOutputLoss(args)\n\n self.fn.append(loss_fn)\n self.ln.append(ln)\n self.weights.append(float(w))\n\n def forward(self, GT, pred, imgL, imgR, K):\n \n loss = 0\n for w, fn, ln in zip(self.weights, self.fn, self.ln):\n \n if ln in ['l1', 'l2']:\n loss += w * fn(GT, pred)\n elif ln in ['photo']:\n depR = 0.25 * 320.0 / pred \n loss += w * fn(imgR, imgL, depR)\n elif ln in ['inputoutput']:\n loss += w * fn(GT, pred)\n\n return loss","sub_path":"utils/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":11335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"621955302","text":"'''\nFunction:\n build dropout\nAuthor:\n Zhenchao Jin\n'''\nimport torch\nimport torch.nn as nn\nfrom .droppath import DropPath\n\n\n'''build dropout'''\ndef BuildDropout(dropout_type, **kwargs):\n supported_dropouts = {\n 'droppath': DropPath,\n 'dropout': nn.Dropout,\n 'dropout2d': nn.Dropout2d,\n 'dropout3d': nn.Dropout3d,\n }\n assert dropout_type in supported_dropouts, 'unsupport dropout type %s...' % dropout_type\n return supported_dropouts[dropout_type](**kwargs)","sub_path":"ssseg/modules/backbones/bricks/dropout/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"55990667","text":"#!/usr/bin/python\nimport os\nimport sklearn as sk\nimport numpy as np\nimport pandas as pd\nimport sklearn.manifold, sklearn.decomposition\nimport matplotlib.pyplot as plt\nimport glob\nimport re\n\n\nmethdir = '../tcga_brca/methylation'\noutdir = '../tcga_brca/analysis'\nrnadir = '../tcga_brca/rnaseq-fpkm/gdc_download_20170331_011914'\n\nrseqmeta = pd.read_json('../tcga_brca/metadata.rnaseq_tcga_brca_cart.2017-03-27T21-58-01.224631.json')\nmeta_450k = pd.read_json('../tcga_brca/metadata.450k_methylation_tcga_brca_cart.2017-03-27T22-07-22.151718.json')\n\n\nif os.path.isfile(os.path.join(methdir, 'df_tcgabrca_methylation_450k_truncated.hdf')):\n df = pd.read_hdf(os.path.join(methdir, 'df_tcgabrca_methylation_450k_truncated.hdf'))\nelse: \n ptrn = re.compile('TCGA'+'.+'+'.txt')\n f = os.listdir(methdir)\n f = [x for x in f if ptrn.match(x)]\n df0 = pd.DataFrame()\n\n for ii in range(0, len(f)):\n y = np.genfromtxt(os.path.join(methdir, f[ii]), delimiter='\\n')\n df0[f[ii]] = y\n if ii % 25 == 0:\n print(ii)\n\n # Dat row slice - remove the ~120k rows out of 480k that have NaNs anywhere \n nancols = df0.isnull().mean(axis=1)\n df = df0[nancols == 0]\n\n # Annotate!!\n df.to_hdf(os.path.join(methdir, 'df_tcgabrca_methylation_450k_truncated.hdf'), 'methdf')\n\n#TSNE\nif not os.path.isfile('../tcga_brca/analysis/tcgabrca_450k_tsne_euclidean.png'):\n mymodel = sk.manifold.TSNE()\n dftsne = mymodel.fit_transform(pd.DataFrame.transpose(df))\n plt.scatter(dftsne[:,0], dftsne[:,1])\n plt.xlabel('TSNE1')\n plt.ylabel('TSNE2')\n plt.title('TSNE 2-dim of TCGA-BRCA 450k methylation data, n=869')\n plt.grid(1)\n plt.savefig(os.path.join(outdir, 'tcgabrca_450k_tsne_euclidean.png'))\n plt.clf()\n\n# PCA\nif not os.path.isfile('../tcga_brca/analysis/tcgabrca_450k_pccumvar.png'):\n mypca = sk.decomposition.PCA()\n dfpc = mypca.fit_transform(pd.DataFrame.transpose(df))\n\n plt.scatter(dfpc[:,0], dfpc[:,1])\n plt.xlabel('PC1')\n plt.ylabel('PC2')\n plt.title('Scatter of principal components of TCGA-BRCA 450k methylation data, n = '+dfpc.shape[0])\n plt.savefig(os.path.join(outdir, 'tcgabrca_450k_pcscatter.png'))\n\n plt.clf()\n plt.plot(np.cumsum(mypca.explained_variance_ratio_))\n plt.grid(1)\n plt.xlabel('Number of principal components')\n plt.ylabel('Fraction of variance explained')\n plt.title('Variance explaiend by PCA of 869x360k TCGA-BRCA 450k methylation data')\n plt.tight_layout()\n plt.ylim([0,1])\n plt.savefig(os.path.join(outdir, 'tcgabrca_450k_pccumvar.png'))\n\n\n# Read gene data\nif os.path.isfile(os.path.join(rnadir, 'df_tcgabrca_rnaseq.hdf')):\n rseqdf = pd.read_hdf(os.path.join(rnadir, 'df_tcgabrca_rnaseq.hdf'))\nelse: \n fr = os.listdir(rnadir)\n ptrn = re.compile('.+'+'.txt.gz')\n fr = [x for x in fr if ptrn.match(x)]\n\n rseqdf = pd.read_table(os.path.join(rnadir, fr[0]), index_col=0, header=None, names=[fr[0]]) \n for ii in range(1,len(fr)):\n y = pd.read_table(os.path.join(rnadir, fr[ii]), index_col=0, header=None, names=[fr[ii]])\n rseqdf = pd.concat([rseqdf, y], axis=1, join_axes=[rseqdf.index])\n if ii % 30 == 0:\n print(ii)\n \n rseqdf.to_hdf(os.path.join(rnadir, 'df_tcgabrca_rnaseq.hdf'), 'rseqdf')\n\n\n\n# Align the four (!) data frames; use case_id as the primary key\nrseqdt = pd.DataFrame.transpose(rseqdf)\nrseqmeta = rseqmeta.loc[rseqmeta['file_name'].isin(rseqdt.index),:]\nrseqmeta = rseqmeta.set_index(['file_name'])\nrseqmeta = rseqmeta.reindex(rseqdt.index)\n\nrseqmeta['cases'][0][0]['diagnoses']\nrseqmeta['case_id'] = [y[0]['case_id'] for y in rseqmeta['cases']]\n\n\ndf = pd.DataFrame.transpose(df)\nmeta_450k['case_id'] = [x[0]['case_id'] for x in meta_450k['cases']]\nmeta_450k['adjustfile'] = ['TCGA' + str.split(str(x),'TCGA')[1][0:11]+'.txt' for x in meta_450k['file_name']]\nt_450k = meta_450k[['case_id', 'adjustfile']].set_index('adjustfile')\n","sub_path":"hoffman/brca_tgca_meth_expl.py","file_name":"brca_tgca_meth_expl.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"123044222","text":"def bmi(weight: float, height: float) -> float:\n return weight / height ** 2\n\n\ndef print_bmi(bmi: float) -> float:\n if bmi < 18.5:\n print(\"Underweight\")\n elif bmi < 25:\n print(\"Normal\")\n elif bmi < 30:\n print(\"Overweight\")\n else:\n print(\"Obesity\")\n\n\nwhile True:\n try:\n weight, height = map(float, input().split())\n\n if weight <= 0 or height <= 0:\n print(\"Одно или несколько чисел меньше нуля.\")\n continue\n\n print_bmi(bmi(weight, height / 100))\n\n break\n\n except KeyboardInterrupt:\n break\n except ValueError:\n print(\"Ошибка парсинга значения. Повторите ввод.\")\n","sub_path":"Practice/21/Python/21.py","file_name":"21.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"511724435","text":"import math\nimport random\n\n# Bubble: sort random list with checking statements\n\n# create random number list\nrandlist = []\n\nfor i in range(6):\n i = random.randint(1, 10)\n randlist.append(i)\n\nprint(randlist)\n\n# set i to the 1 less the length of the list to get the max index value\ni = len(randlist) - 1\n\n# start a while loop where i is greate than 1 where i will be later decremented to start the loop again\nwhile i > 1:\n \n # index j\n j = 0\n\n# where j is less than i run loop until j is is incremented\n while j < i:\n\n # simple print statement allowing the user to see what the programme is comparing\n print(\"\\n is {} > {}\".format(randlist[j], randlist[j+1]))\n\n # if statement to compare the two numbers next to each other in the list\n if randlist[j] > randlist[j+1]:\n\n # if the index starting at j is > than the index of j+1 we need to switch the positions of the indexs\n print(\"Switch\")\n\n # formula to switch the index numbers around\n temp = randlist[j]\n randlist[j] = randlist[j + 1]\n randlist[j + 1] = temp\n\n # handling index j is < index j+1 don't switch\n else:\n print(\"Don't Switch\")\n\n # increment j so move to next number in the list\n j += 1\n\n # after each run through print the current list\n for k in randlist:\n print(k, end = \", \")\n print()\n\n print(\"End of round\")\n\n # decrement i by 1 for a new round\n i -= 1\n\n# once all conditions met print finished list\nfor k in randlist:\n print(k, end = \", \")\nprint()\n\n","sub_path":"Bubblesort.py","file_name":"Bubblesort.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"334002215","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCore helper functions.\n\"\"\"\n\n####################################################################################################\n\ndef get_files_to_recompile(config):\n \"\"\"\n Return a list of source files that, given the existing object files in the \"build\" folder, need\n to be (re)compiled.\n\n :param config: The configuration to operate on.\n\n :returns: A list of files to recompile.\n \"\"\"\n import os\n\n from codestacker.constants import keys, extensions\n from codestacker.system.file_utilities import get_files\n\n # Dereferenced for performance.\n build_dir = config[keys.BUILD]\n to_compile = set()\n\n for target, prerequisites in _get_recipes(config[keys.SOURCES], config[keys.INCLUDE]).items():\n # Case 1: new targets.\n if target not in [os.path.basename(x) for x in get_files(build_dir, '.o')]:\n to_compile.update(prerequisites)\n # Case 2: modified source files.\n else:\n for file in prerequisites:\n if os.path.getmtime(file) > os.path.getmtime(os.path.join(build_dir, target)):\n to_compile.add(file)\n\n to_compile = set(x for x in to_compile if x.endswith(extensions.SOURCES))\n\n return to_compile\n\n####################################################################################################\n\ndef _get_recipes(sources_dir, include_dir):\n \"\"\"\n Get a list of recipes needed to (re)compute the dependencies.\n\n :param sources_dir: The sources directory to look in.\n :param include_dir: The include directory to look in.\n\n :returns: A list of recipes.\n\n :raises TechnicalError: a recipe failed to compute.\n \"\"\"\n import subprocess\n\n from codestacker.constants import extensions\n from codestacker.errors import errors\n from codestacker.errors.exceptions import TechnicalError\n from codestacker.system.file_utilities import get_files\n\n preproc_command = ['g++', '-I', include_dir, '-MM']\n recipes = {}\n\n for file in get_files(sources_dir, extensions.SOURCES):\n try:\n output = subprocess.run(\n [*preproc_command, file],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, encoding='UTF-8')\n except subprocess.CalledProcessError as error:\n raise TechnicalError(errors.RECIPE_FAILED, error=error.stderr)\n\n target, prerequisites = output.stdout.split(':', 1)\n\n recipes[target] = prerequisites.replace('\\\\', '').split()\n\n return recipes\n","sub_path":"codestacker/core/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"275803637","text":"import sqlite3, os, sys, time\n\nimport hashlib\nimport random\n\nstart = time.time()\ndb = sqlite3.connect(\"data.db\")\ncur = db.cursor()\n\ncount = 0\ntotal = 0\nvalue = 0\nfor i in range(1000):\n n1 = random.randint(1, 99000)\n n2 = random.randint(1, 1000)\n sql = \"select count(*) from MOCKDATA where ID>=%s AND ID<=%s;\" % (n1, n1+n2)\n h = hash(sql)\n\n if h % 2 == 0:\n print(sql, \" count() = \", 0)\n else:\n cur.execute(sql)\n value = int(cur.fetchone()[0])\n print(sql, \" count() = \", value) \n \n count += 1\n total += value\n\nprint()\nprint()\nprint(\"num query = %d, total return value = %d\" % (count, total))\n\ndb.close()\nprint(\"waktu: = \", time.time()-start)","sub_path":"tugas5/query_sqlv2.py","file_name":"query_sqlv2.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"316304989","text":"from django.test import TestCase\nfrom django.test import Client\nfrom django.urls import reverse\nfrom aliss.models import Organisation, ALISSUser, Service, Location, ServiceArea, Postcode\n\nclass SearchViewTestCase(TestCase):\n fixtures = ['service_areas.json', 'g2_postcodes.json']\n\n def setUp(self):\n t = ALISSUser.objects.create(name=\"Mr Test\", email=\"tester@aliss.org\")\n u = ALISSUser.objects.create(name=\"Mr Updater\", email=\"updater@aliss.org\", is_editor=True)\n o = Organisation.objects.create(\n name=\"TestOrg\",\n description=\"A test description\",\n created_by=t, updated_by=u\n )\n s = Service.objects.create(name=\"My First Service\", description=\"A handy service\", organisation=o, created_by=t, updated_by=u)\n s.service_areas.add(ServiceArea.objects.get(name=\"Glasgow City\", type=2))\n\n def test_no_postcode(self):\n response = self.client.get('/search/?postcode=ZZ+ZZZ')\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, '

Sorry, ZZ ZZZ doesn\\'t appear to be a valid postcode.

')\n\n def test_get(self):\n response = self.client.get('/search/?postcode=G2+4AA')\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Help & support in G2 4AA')","sub_path":"aliss/tests/views/test_search_view.py","file_name":"test_search_view.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"200884213","text":"from __future__ import absolute_import, unicode_literals\n\nimport logging\n\nfrom kombu import Exchange, Queue\n\nfrom django.apps import apps\nfrom django.db.models.signals import post_delete, post_save\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom acls import ModelPermission\nfrom acls.links import link_acl_list\nfrom acls.permissions import permission_acl_edit, permission_acl_view\nfrom common import (\n MayanAppConfig, menu_facet, menu_multi_item, menu_object, menu_secondary,\n menu_setup, menu_sidebar\n)\nfrom common.classes import ModelAttribute, ModelField\nfrom common.widgets import TwoStateWidget\nfrom documents.search import document_page_search, document_search\nfrom documents.signals import post_document_type_change\nfrom events import ModelEventType\nfrom events.links import (\n link_events_for_object, link_object_event_types_user_subcriptions_list,\n)\nfrom events.permissions import permission_events_view\nfrom mayan.celery import app\nfrom navigation import SourceColumn\n\nfrom .classes import DocumentMetadataHelper\nfrom .events import (\n event_document_metadata_added, event_document_metadata_edited,\n event_document_metadata_removed, event_metadata_type_edited,\n event_metadata_type_relationship\n)\nfrom .handlers import (\n handler_index_document, post_document_type_metadata_type_add,\n post_document_type_metadata_type_delete,\n post_document_type_change_metadata\n)\nfrom .links import (\n link_metadata_add, link_metadata_edit, link_metadata_multiple_add,\n link_metadata_multiple_edit, link_metadata_multiple_remove,\n link_metadata_remove, link_metadata_view,\n link_setup_document_type_metadata_types, link_setup_metadata_type_create,\n link_setup_metadata_type_delete, link_setup_metadata_type_document_types,\n link_setup_metadata_type_edit, link_setup_metadata_type_list,\n)\nfrom .permissions import (\n permission_metadata_document_add, permission_metadata_document_edit,\n permission_metadata_document_remove, permission_metadata_document_view,\n permission_metadata_type_delete, permission_metadata_type_edit,\n permission_metadata_type_view\n)\n\nfrom .queues import * # NOQA\nfrom .search import metadata_type_search # NOQA\nfrom .widgets import get_metadata_string\n\nlogger = logging.getLogger(__name__)\n\n\nclass MetadataApp(MayanAppConfig):\n has_rest_api = True\n has_tests = True\n name = 'metadata'\n verbose_name = _('Metadata')\n\n def ready(self):\n super(MetadataApp, self).ready()\n from actstream import registry\n\n from .wizard_steps import WizardStepMetadata # NOQA\n\n Document = apps.get_model(\n app_label='documents', model_name='Document'\n )\n DocumentPageResult = apps.get_model(\n app_label='documents', model_name='DocumentPageResult'\n )\n\n DocumentType = apps.get_model(\n app_label='documents', model_name='DocumentType'\n )\n\n DocumentMetadata = self.get_model('DocumentMetadata')\n DocumentTypeMetadataType = self.get_model('DocumentTypeMetadataType')\n MetadataType = self.get_model('MetadataType')\n\n Document.add_to_class(\n 'metadata_value_of', DocumentMetadataHelper.constructor\n )\n\n ModelAttribute(\n Document, 'metadata_value_of',\n description=_(\n 'Return the value of a specific document metadata'\n ),\n )\n\n ModelField(\n Document, 'metadata__metadata_type__name',\n label=_('Metadata type name')\n )\n ModelField(\n Document, 'metadata__value', label=_('Metadata type value'),\n )\n\n ModelEventType.register(\n model=Document, event_types=(\n event_document_metadata_added,\n event_document_metadata_edited,\n event_document_metadata_removed,\n )\n )\n\n ModelEventType.register(\n model=MetadataType, event_types=(\n event_document_metadata_added,\n event_document_metadata_edited,\n event_document_metadata_removed,\n event_metadata_type_edited,\n event_metadata_type_relationship,\n )\n )\n\n ModelEventType.register(\n model=DocumentType, event_types=(\n event_metadata_type_relationship,\n )\n )\n\n ModelPermission.register(\n model=Document, permissions=(\n permission_metadata_document_add,\n permission_metadata_document_edit,\n permission_metadata_document_remove,\n permission_metadata_document_view,\n )\n )\n ModelPermission.register(\n model=MetadataType, permissions=(\n permission_acl_edit, permission_acl_view,\n permission_events_view, permission_metadata_type_delete,\n permission_metadata_type_edit, permission_metadata_type_view\n )\n )\n\n SourceColumn(\n source=Document, label=_('Metadata'),\n func=lambda context: get_metadata_string(context['object'])\n )\n\n SourceColumn(\n source=DocumentPageResult, label=_('Metadata'),\n func=lambda context: get_metadata_string(\n context['object'].document\n )\n )\n\n SourceColumn(\n source=DocumentMetadata, label=_('Value'),\n attribute='value'\n )\n SourceColumn(\n source=DocumentMetadata, label=_('Required'),\n func=lambda context: TwoStateWidget(\n state=context['object'].is_required\n ).render()\n )\n\n app.conf.CELERY_QUEUES.append(\n Queue('metadata', Exchange('metadata'), routing_key='metadata'),\n )\n\n app.conf.CELERY_ROUTES.update(\n {\n 'metadata.tasks.task_remove_metadata_type': {\n 'queue': 'metadata'\n },\n 'metadata.tasks.task_add_required_metadata_type': {\n 'queue': 'metadata'\n },\n }\n )\n\n document_search.add_model_field(\n field='metadata__metadata_type__name', label=_('Metadata type')\n )\n document_search.add_model_field(\n field='metadata__value', label=_('Metadata value')\n )\n\n document_page_search.add_model_field(\n field='document_version__document__metadata__metadata_type__name',\n label=_('Metadata type')\n )\n document_page_search.add_model_field(\n field='document_version__document__metadata__value',\n label=_('Metadata value')\n )\n\n menu_facet.bind_links(links=(link_metadata_view,), sources=(Document,))\n menu_multi_item.bind_links(\n links=(\n link_metadata_multiple_add, link_metadata_multiple_edit,\n link_metadata_multiple_remove\n ), sources=(Document,)\n )\n menu_object.bind_links(\n links=(\n link_setup_document_type_metadata_types,\n ), sources=(DocumentType,)\n )\n menu_object.bind_links(\n links=(\n link_setup_metadata_type_edit,\n link_setup_metadata_type_document_types, link_acl_list,\n link_object_event_types_user_subcriptions_list,\n link_events_for_object, link_setup_metadata_type_delete,\n ), sources=(MetadataType,)\n )\n menu_secondary.bind_links(\n links=(\n link_setup_metadata_type_list,\n link_setup_metadata_type_create\n ), sources=(\n MetadataType, 'metadata:setup_metadata_type_list',\n 'metadata:setup_metadata_type_create'\n )\n )\n menu_setup.bind_links(links=(link_setup_metadata_type_list,))\n menu_sidebar.bind_links(\n links=(\n link_metadata_add, link_metadata_edit, link_metadata_remove\n ), sources=(\n 'metadata:metadata_add', 'metadata:metadata_edit',\n 'metadata:metadata_remove', 'metadata:metadata_view'\n )\n )\n\n post_delete.connect(\n post_document_type_metadata_type_delete,\n dispatch_uid='metadata_post_document_type_metadata_type_delete',\n sender=DocumentTypeMetadataType\n )\n post_document_type_change.connect(\n post_document_type_change_metadata,\n dispatch_uid='metadata_post_document_type_change_metadata',\n sender=Document\n )\n post_save.connect(\n post_document_type_metadata_type_add,\n dispatch_uid='metadata_post_document_type_metadata_type_add',\n sender=DocumentTypeMetadataType\n )\n\n # Index updating\n\n post_delete.connect(\n handler_index_document,\n dispatch_uid='metadata_handler_index_document_delete',\n sender=DocumentMetadata\n )\n post_save.connect(\n handler_index_document,\n dispatch_uid='metadata_handler_index_document_save',\n sender=DocumentMetadata\n )\n\n registry.register(MetadataType)\n registry.register(DocumentTypeMetadataType)\n","sub_path":"mayan/apps/metadata/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":9329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"558850910","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\"\"\"\n @Author: cc\n @CreateTime: 2017-12-18T20:20:50+09:00\n @Email: guangmingwu2010@gmail.com\n @Copyright: go-hiroaki\n @License: MIT\n\"\"\"\n\n\n\nimport numpy as np\nfrom chainer.serializers import npz\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer.links.caffe.caffe_function import CaffeFunction\n\n\nclass Alex(chainer.Chain):\n\n \"\"\"Single-GPU AlexNet without partition toward the channel axis.\"\"\"\n\n insize = 227\n\n def __init__(self, nb_class=1000):\n super(Alex, self).__init__()\n with self.init_scope():\n self.conv1 = L.Convolution2D(None, 96, 11, stride=4)\n self.conv2 = L.Convolution2D(None, 256, 5, pad=2)\n self.conv3 = L.Convolution2D(None, 384, 3, pad=1)\n self.conv4 = L.Convolution2D(None, 384, 3, pad=1)\n self.conv5 = L.Convolution2D(None, 256, 3, pad=1)\n self.fc6 = L.Linear(None, 4096)\n self.fc7 = L.Linear(None, 4096)\n self.fc8 = L.Linear(None, nb_class)\n\n def __call__(self, x, t):\n h = F.max_pooling_2d(F.local_response_normalization(\n F.relu(self.conv1(x))), 3, stride=2)\n h = F.max_pooling_2d(F.local_response_normalization(\n F.relu(self.conv2(h))), 3, stride=2)\n h = F.relu(self.conv3(h))\n h = F.relu(self.conv4(h))\n h = F.max_pooling_2d(F.relu(self.conv5(h)), 3, stride=2)\n h = F.dropout(F.relu(self.fc6(h)))\n h = F.dropout(F.relu(self.fc7(h)))\n h = self.fc8(h)\n return h\n\n\nif __name__ == \"__main__\":\n caffemodel = CaffeFunction(\"bvlc_alexnet.caffemodel\")\n npz.save_npz(\"alexnet.npz\", caffemodel, compression=False)\n alexnet = Alex()\n npz.load_npz(\"alexnet.npz\", alexnet)\n","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"128342848","text":"import random\n\n# Load data set and labels from given filename\ndef LoadDataSet(filename):\n data_set = []; labels = []\n with open(filename, \"r\") as f:\n for line in f.readlines():\n line_content = line.strip().split(\"\\t\")\n # Convert str to float type\n data = map(float, line_content[:-2])\n data_set.append(data)\n labels.append(int(line_content[-1]))\n return data_set, labels\n\n# Select index different from give index j\ndef SelectRandJ(i, m):\n j = i\n while j == i:\n j = int(random.uniform(0, m))\n return j\n\n# Make alpha strained in range [low, high]\ndef ClipAlpha(a, low, high):\n if a < low:\n a = low\n elif a > high:\n a = high\n return a\n\nif __name__ == \"__main__\":\n data_set, labels = LoadDataSet(\"./testSet.txt\")\n print(labels)\n","sub_path":"MachineLearning/maching_learning_in_action/chapter6_svm/svmMLiA.py","file_name":"svmMLiA.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"64073814","text":"'''\nInteractive dashboard to show characteristics of a classification model\nfor emails. Will display what emails were successfully categorized and which\nweren't and which terms are most important for classifier.\n'''\n\n#----------------------------------------------------------------------#\n# Libraries and dependencies #\n#----------------------------------------------------------------------#\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\nfrom dash.dependencies import Input, Output, State\nimport numpy as np\nimport pandas as pd\nimport csv\nfrom collections import defaultdict\nimport sys\nimport os\nfrom flask import send_from_directory\nimport pickle\nimport nltk\nfrom nltk.corpus import stopwords\nimport getopt\n#\n# def usage():\n# sys.stdout.write(\"Usage: python viz_classifyer.py [-d|--directory= ] [-n|--number= ] [-h|?|--help]\")\n# return True\n\n#---------------------------------------------------#\n# Return name of dataframe based on input parameter #\n#---------------------------------------------------#\n\ndef chooseDF(responseClass):\n\n global resultsDF_tp\n global resultsDF_fp\n global resultsDF_tn\n global resultsDF_fn\n\n print(type(resultsDF_tn))\n if responseClass == 'truePositive':\n return (resultsDF_tp)\n elif responseClass == 'falsePositive':\n return (resultsDF_fp)\n elif responseClass == 'falseNegative':\n return (resultsDF_fn)\n elif responseClass == 'trueNegative':\n return (resultsDF_tn)\n else:\n return Null\n\n\n\n#------------------------------------------------------#\n# Prepare input data #\n#Load results from classifier notebook\n#------------------------------------------------------#\n\nstopwords_english = stopwords.words('english')\n\n# try:\n# opts, args = getopt.getopt(sys.argv[1:], \"d:n:h?\", [\"--directory=\", \"--number=\", \"--help\"])\n# except getopt.GetoptError as err:\n# #Exit if can't parse args\n# usage()\n# sys.exit(2)\n# for o, a in opts:\n# if (o == '-h' or o == '-?'):\n# usage()\n# exit(0)\n# elif o in ('-d', '--directory'):\n# parent_path = a\n# sys.path.insert(0, parent_path + '//' + 'utils')\n# from load_directories import directory_loader\n# input_directory, output_directory = directory_loader(parent_path)\nfrom utils.viz_utils import highlightTerms, formatEmail\nfrom utils.viz_utils import countTokens, countFreqs\nfrom utils.viz_utils import generateAccuracyTable,generateTruthTable\nfrom utils.viz_utils import load_term_scores\nfrom utils.viz_utils import generateTermsTable\n\noutput_directory='/Users/austinlasseter/github_repos/federal_register'\n# #Load term scores from csv\ntermScores=pd.read_csv(output_directory + '/' + 'termScores.csv', index_col=None)\n\n#Load dict of accuracy scores for classifiery\nwith open(output_directory + '/' + 'classifierStats.pyc', 'rb') as f:\n classifierStats = pickle.load(f)\n f.close()\n\n#Load results of testing each test doc\nwith open(output_directory + '/' + 'classifierTestResults.pyc', 'rb') as f:\n classifierTestResults = pickle.load(f)\n f.close()\n\n#-------------------------------------------------------------------------#\n# Make 4 chunks of the test data, depending on truth value #\n#-------------------------------------------------------------------------#\nresultsDF_tp = classifierTestResults[classifierTestResults['truthValue'] == 'truePositive']\nresultsDF_fp = classifierTestResults[classifierTestResults['truthValue'] == 'falsePositive']\nresultsDF_tn = classifierTestResults[classifierTestResults['truthValue'] == 'trueNegative']\nresultsDF_fn = classifierTestResults[classifierTestResults['truthValue'] == 'falseNegative']\n\n\nresponseTypes = ['truePositive', 'trueNegative', 'falsePositive', 'falseNegative']\n\n#-------------------------------------------------------------------#\n# Store all terms in list for easy access #\n#-------------------------------------------------------------------#\ntermsList = termScores['term'].tolist()\nselectedDF = resultsDF_tp\n# numEmailsInSelectedDF = selectedDF.shape[0]\nnumEmailsInSelectedDF = len(selectedDF)\nemailPointer = 1\n\n#Highlight the terms in the email which are in the visible list\n# highlightedEmailSubject = highlightTerms(resultsDF_tp.iloc[(emailPointer - 1)].subject, termsList, stopwords_english)\nhighlightedEmailBody = highlightTerms(resultsDF_tp.iloc[(emailPointer - 1)].abstract, termsList, stopwords_english)\nposScore = selectedDF.iloc[(emailPointer - 1)].posProbability\nnegScore = selectedDF.iloc[(emailPointer - 1)].negProbability\n# subjectPlusBody = (resultsDF_tp.iloc[(emailPointer -1)].abstract)\n\n#------------------------------------------------------------------------#\n#Local version of stylesheet https://codepen.io/chriddyp/pen/bWLwgP.css #\n#------------------------------------------------------------------------#\nstylesheets = ['bWLwgP.css']\n\n#--------------------------------------------#\n# Start building the dashboard - initialize #\n#--------------------------------------------#\napp = dash.Dash()\napp.title = \"Explore Email Classifier Performance\"\n\n#--------------------------------------------#\n#Allow locally-served css\n#--------------------------------------------#\napp.css.config.serve_locally=True\napp.scripts.config.serve_locally=True\n\n@app.server.route('/static/')\ndef static_file(path):\n static_folder = os.path.join(os.getcwd(), 'static')\n return send_from_directory(static_folder, path)\n\n#-----------------------------------------------------#\n# Layout dashboard with HTML and dash core components #\n#-----------------------------------------------------#\napp.layout = html.Div(children = [\n html.Link(\n rel='stylesheet',\n href='/static/bWLwgP.css'\n ),\n html.Link(\n href='/static/sorttable.js'\n ),\n html.Div(id=\"bannerDiv\",\n children = [\n html.Img(id = \"contextEdgeLogo\",\n src='./static/ContextEdge.png'),\n html.H1(id = \"appHeader\",\n children = \"How Well is My Email Classifier Working?\",\n style={'textAlign': 'center'}) #H1\n ]), #bannerDiv,\n html.H2(\"Overall Classifier Performance\"),\n html.Div(id=\"classifier_stats_div\", children =\n [\n html.Div(id=\"performanceDiv\",\n children = [\n html.Div(\n id=\"accuracy_table_div\",\n children = [\n generateAccuracyTable(classifierStats)\n ],\n className = \"six columns\"\n ),\n html.Div(\n id = \"truth_table_div\",\n children = generateTruthTable(classifierStats),\n className = \"six columns\"\n )\n ],\n className=\"row\")\n ]), #classifier_stats_div\n html.Div(id=\"text_and_graph_div\", children=[\n html.Div(id=\"holder_div\", className = \"six columns\", children = [\n html.H2(\"Performance On Each Email\"),\n html.Div(id=\"output_class_selector_div\", children=[\n html.Label(\"Show me...\"),\n dcc.RadioItems(\n id=\"showMe\",\n options = [{'label': \"{}s\".format(responseType), 'value': responseType } for responseType in responseTypes ],\n value = 'truePositive',\n labelStyle={'display': 'inline-block'}\n )\n ]),\n html.Table(id = 'tableJumpTo', children = [\n html.Tr(children = [\n html.Th(html.Label(\"Jump to Email No.\")),\n html.Th(dcc.Input(id='inputEmailNumber', value = 1, type='number')), #Returns unicode string even though we request a number!\n html.Th(html.P(id = 'pTotalEmails', children = \" of {}\".format(numEmailsInSelectedDF))),\n html.Th(html.Button(id='buttonSubmit', children=\"Submit\")),\n ]) #tr\n ],\n style={'margin-left': '0px'}), #tableJumpTo\n html.Div(id=\"text_div\", children=[\n html.Iframe(\n id = 'email_text_iframe',\n sandbox='',\n srcDoc = formatEmail(posScore,\n negScore,\n # highlightedEmailSubject,\n highlightedEmailBody),\n style = {'width': '650px', 'height': '200px'}\n )\n ], style= {'height':'200px', 'padding-top': '20px'})\n ]), #holder div\n ]),\n html.H2(\"Terms/features used in model:\"),\n html.Div\n (\n id=\"tableAndSortdiv\",\n className = \"six columns\",\n children=\n [\n html.Div\n (\n id = \"sortSelectDiv\",\n style = {'display': 'block'},\n children =\n [\n html.Label(\"Sort By...\"),\n html.Div\n (\n id=\"sortOptionsDiv\",\n children =\n [\n dcc.RadioItems\n (\n id=\"sortBy\",\n style={'display': 'inline-block', 'float': 'left'},\n options = [{'label': \"{}\".format(col), 'value': col } for col in termScores.columns ],\n value = 'modelCoef',\n labelStyle={'display': 'inline-block'}\n ),\n dcc.RadioItems\n (\n id = \"sortOrder\",\n style = {'display': 'inline-block', 'float': 'left'},\n options = [{'label': \"{}\".format(col), 'value': col } for col in ['Ascending', 'Descending']],\n value = 'Ascending',\n labelStyle={'display': 'inline-block'}\n )\n ]\n ), #SortoptionsDiv\n html.Div\n (\n id = \"table_div\",\n style= { 'clear': 'left', 'overflow-y': 'scroll', 'height': '350px'},\n children = [generateTermsTable(termScores)]\n ) #table_div\n ]\n\n ), #sortSelectDiv\n ]\n ) #tableAndSortDiv\n])\n\n#-------------------------------------------------------------------#\n# Define interactive behaviors from inputs #\n#-------------------------------------------------------------------#\n\n#-------------------------------------------------------------------#\n# callbacks for radio button to select email subset and number #\n#-------------------------------------------------------------------#\n@app.callback(Output('pTotalEmails', 'children'),\n [Input('showMe', 'value')])\ndef update_df_selection(input1):\n global resultsDF_tp\n global resultsDF_tn\n global resultsDF_fn\n global resultsDF_fp\n global emailPointer\n\n selectedDF = chooseDF(input1)#\n\n #Reset to ist email\n emailPointer = 1\n\n # return (\" of {}\".format(selectedDF.shape[0]))\n return (\" of {}\".format(len(selectedDF)))\n\n#------------------------------------------------------------#\n# Update the text in the iframe #\n# depending on which class of data and number email selected #\n#------------------------------------------------------------#\n@app.callback(Output('email_text_iframe', 'srcDoc'),\n [Input('buttonSubmit', 'n_clicks')],\n [State('showMe', 'value'),\n State('inputEmailNumber', 'value')])\ndef update_displayed_email_text(nClicks, inputDF, inputEmailNumber):\n global resultsDF_tp\n global resultsDF_tn\n global resultsDF_fn\n global resultsDF_fp\n global selectedDF\n global emailPointer\n global termsList\n\n #Switch to selected type of emails, true positive, false pos, etc\n selectedDF = chooseDF(inputDF)\n\n # if (int(inputEmailNumber) > selectedDF.shape[0]):\n if (int(inputEmailNumber) > len(selectedDF)):\n emailPointer = 1\n else:\n emailPointer = int(inputEmailNumber)\n\n posProbability = selectedDF.iloc[(emailPointer - 1)].posProbability\n\n negProbability = selectedDF.iloc[(emailPointer - 1)].negProbability\n\n # highlightedEmailSubject = highlightTerms(selectedDF.iloc[(emailPointer - 1)].subject, termsList, stopwords_english)\n highlightedEmailBody = highlightTerms(selectedDF.iloc[(emailPointer - 1)].abstract, termsList, stopwords_english)\n\n return(formatEmail(posProbability,\n negProbability,\n # highlightedEmailSubject,\n highlightedEmailBody))\n\n\n#---------------------------------------------------------------#\n# Highlight accuracy or error rate depending on which value #\n# chosen in radio button #\n# Feeling bad about writing four functions to update four cells #\n# but can't see better way... #\n#---------------------------------------------------------------#\n@app.callback(Output('accuracyTableCell2', 'className'),\n [Input('buttonSubmit', 'n_clicks')],\n [State('showMe', 'value')])\ndef updateAccuracyCell2(n_clicks, showMe):\n if (showMe in ['truePositive', 'trueNegative']):\n return('highlightedCell')\n else:\n return('normalCell')\n@app.callback(Output('errorTableCell2', 'className'),\n [Input('buttonSubmit', 'n_clicks')],\n [State('showMe', 'value')])\ndef updateErrorCell2(n_clicks, showMe):\n if (showMe in ['truePositive', 'trueNegative']):\n return('normalCell')\n else:\n return('highlightedCell')\n\n#---------------------------------------------------------------#\n# Highlight truth table depending on radio button selection #\n#---------------------------------------------------------------#\n@app.callback(Output('truePositivesCell', 'className'),\n [Input('buttonSubmit', 'n_clicks')],\n [State('showMe', 'value')])\ndef updateTruePositivesCell(n_clicks, showMe):\n if (showMe == 'truePositive'):\n return('highlightedCell')\n else:\n return('normalCell')\n@app.callback(Output('trueNegativesCell', 'className'),\n [Input('buttonSubmit', 'n_clicks')],\n [State('showMe', 'value')])\ndef updateTrueNegativesCell(n_clicks, showMe):\n if (showMe == 'trueNegative'):\n return('highlightedCell')\n else:\n return('normalCell')\n@app.callback(Output('falsePositivesCell', 'className'),\n [Input('buttonSubmit', 'n_clicks')],\n [State('showMe', 'value')])\ndef updateFalsePositivesCell(n_clicks, showMe):\n if (showMe == 'falsePositive'):\n return('highlightedCell')\n else:\n return('normalCell')\n@app.callback(Output('falseNegativesCell', 'className'),\n [Input('buttonSubmit', 'n_clicks')],\n [State('showMe', 'value')])\ndef updateFalseNegativesCell(n_clicks, showMe):\n if (showMe == 'falseNegative'):\n return('highlightedCell')\n else:\n return('normalCell')\n\n#------------------------------------------------------------------------#\n# Sort and return the terms table using the options in the radio buttons #\n#------------------------------------------------------------------------#\n@app.callback(Output('table_div', 'children'),\n [Input('sortBy', 'value'),\n Input('sortOrder', 'value')])\ndef sortTermsTable(mySortBy, mySortOrder):\n print(\"{}|{}\".format(mySortBy, mySortOrder))\n return(generateTermsTable(termScores, mySortBy, mySortOrder))\n\napp.run_server(debug=True)\n","sub_path":"explore_classifier_model_austin.py","file_name":"explore_classifier_model_austin.py","file_ext":"py","file_size_in_byte":16430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72880394","text":"import time\nimport threading\n\n\ndef _func1():\n time.sleep(5)\n print('func1()')\n\n\ndef _func2():\n print('func2()')\n\n\nif __name__ == '__main__':\n threads = []\n\n thread1 = threading.Thread(target=_func1, args=())\n threads.append(thread1)\n\n thread2 = threading.Thread(target=_func2, args=())\n threads.append(thread2)\n\n for thread in threads:\n thread.start()\n\n for thread in threads:\n thread.join()\n\n print('main finish')\n","sub_path":"Multi_Thread/MultiThreading.py","file_name":"MultiThreading.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"584072046","text":"import tensorflow as tf \nfrom tensorflow.keras.layers import Conv2D, Conv2DTranspose, ReLU, LeakyReLU, BatchNormalization, Concatenate\nimport matplotlib.pyplot as plt \nimport time\n\n\n### 所有 pytorch BN 裡面有兩個參數的設定不確定~: affine=True, track_running_stats=True,目前思考覺得改道tf2全拿掉也可以\n### 目前 總共用7層,所以size縮小 2**7 ,也就是 1/128 這樣子!例如256*256*3丟進去,最中間的feature map長寬2*2*512喔!\nclass Generator(tf.keras.models.Model):\n def __init__(self,out_channel=3, **kwargs):\n super(Generator,self).__init__(**kwargs)\n self.conv1 = Conv2D(64, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv1\") #,bias=False) ### in_channel:3\n\n self.lrelu2 = LeakyReLU(alpha=0.2,name=\"lrelu2\")\n self.conv2 = Conv2D(128, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv2\") #,bias=False) ### in_channel:64\n self.bn2 = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn2\") ### b_in_channel:128\n\n self.lrelu3 = LeakyReLU(alpha=0.2,name=\"lrelu3\")\n self.conv3 = Conv2D(256, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv3\") #,bias=False) ### in_channel:128\n self.bn3 = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn3\") ### b_in_channel:256\n\n self.lrelu4 = LeakyReLU(alpha=0.2,name=\"lrelu4\")\n self.conv4 = Conv2D(512, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv4\") #,bias=False) ### in_channel:256\n self.bn4 = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn4\") ### b_in_channel:512\n\n self.lrelu5 = LeakyReLU(alpha=0.2,name=\"lrelu5\")\n self.conv5 = Conv2D(512, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv5\") #,bias=False) ### in_channel:512\n self.bn5 = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn5\") ### b_in_channel:512\n\n self.lrelu6 = LeakyReLU(alpha=0.2,name=\"lrelu6\")\n self.conv6 = Conv2D(512, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv6\") #,bias=False) ### in_channel:512\n self.bn6 = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn6\") ### b_in_channel:512\n\n ###################\n # 最底層\n self.lrelu7 = LeakyReLU(alpha=0.2,name=\"lrelu7\")\n self.conv7 = Conv2D(512, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv7\") #,bias=False) ### in_channel:512\n\n self.relu7t = ReLU(name=\"relu7t\")\n self.conv7t = Conv2DTranspose(512, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv7t\") #,bias=False) ### in_channel:512\n self.bn7t = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn7t\") ### b_in_channel:512\n self.concat7 = Concatenate(name=\"concat7\")\n ###################\n\n self.relu6t = ReLU(name=\"relu6t\")\n self.conv6t = Conv2DTranspose(512, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv6t\") #,bias=False) ### in_channel:1024\n self.bn6t = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn6t\") ### b_in_channel:512\n self.concat6 = Concatenate(name=\"concat6\")\n\n self.relu5t = ReLU(name=\"relu5t\")\n self.conv5t = Conv2DTranspose(512, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv5t\") #,bias=False) ### in_channel:1024\n self.bn5t = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn5t\") ### b_in_channel:512\n self.concat5 = Concatenate(name=\"concat5\")\n\n self.relu4t = ReLU(name=\"relu4t\")\n self.conv4t = Conv2DTranspose(256, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv4t\") #,bias=False) ### in_channel:1024\n self.bn4t = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn4t\") ### b_in_channel:256\n self.concat4 = Concatenate(name=\"concat4\")\n\n self.relu3t = ReLU(name=\"relu3t\")\n self.conv3t = Conv2DTranspose(128, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv3t\") #,bias=False) ### in_channel:512\n self.bn3t = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn3t\") ### b_in_channel:128\n self.concat3 = Concatenate(name=\"concat3\")\n\n\n self.relu2t = ReLU(name=\"relu2t\")\n self.conv2t = Conv2DTranspose(64, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv2t\") #,bias=False) ### in_channel:256\n self.bn2t = BatchNormalization(epsilon=1e-05, momentum=0.1,name=\"bn2t\") ### b_in_channel:64\n self.concat2 = Concatenate(name=\"concat2\")\n\n\n self.relu1t = ReLU(name=\"relu1t\")\n self.conv1t = Conv2DTranspose(out_channel, kernel_size=(4, 4), strides=(2, 2), padding=\"same\",name=\"conv1t\") ### in_channel:128\n # (4): Tanh()\n\n def call(self, input_tensor):\n x = self.conv1(input_tensor)\n\n skip2 = x\n x = self.lrelu2(skip2)\n x = self.conv2(x)\n x = self.bn2(x)\n \n skip3 = x\n x = self.lrelu3(skip3)\n x = self.conv3(x)\n x = self.bn3(x)\n\n skip4 = x\n x = self.lrelu4(skip4)\n x = self.conv4(x)\n x = self.bn4(x)\n\n skip5 = x\n x = self.lrelu5(skip5)\n x = self.conv5(x)\n x = self.bn5(x)\n\n skip6 = x\n x = self.lrelu6(skip6)\n x = self.conv6(x)\n x = self.bn6(x)\n ###############################\n skip7 = x\n x = self.lrelu7(skip7)\n x = self.conv7(x)\n\n x = self.relu7t(x)\n x = self.conv7t(x)\n x = self.bn7t(x)\n # x = self.concat7([skip7,x])\n x = self.concat7([x,skip7])\n ###############################\n x = self.relu6t(x)\n x = self.conv6t(x)\n x = self.bn6t(x)\n # x = self.concat6([skip6,x])\n x = self.concat6([x,skip6])\n\n x = self.relu5t(x)\n x = self.conv5t(x)\n x = self.bn5t(x)\n # x = self.concat5([skip5,x])\n x = self.concat5([x,skip5])\n\n\n x = self.relu4t(x)\n x = self.conv4t(x)\n x = self.bn4t(x)\n # x = self.concat4([skip4,x])\n x = self.concat4([x,skip4])\n\n\n x = self.relu3t(x)\n x = self.conv3t(x)\n x = self.bn3t(x)\n # x = self.concat3([skip3,x])\n x = self.concat3([x,skip3])\n\n\n x = self.relu2t(x)\n x = self.conv2t(x)\n x = self.bn2t(x)\n # x = self.concat2([skip2,x])\n x = self.concat2([x,skip2])\n\n x = self.relu1t(x)\n x = self.conv1t(x)\n return tf.nn.tanh(x)\n \n \n def model(self, x):\n return tf.keras.models.Model(inputs=[x], outputs=self.call(x) )\n \n\n\n#######################################################################################################################################\ndef downsample(filters, size, apply_batchnorm=True):\n initializer = tf.random_normal_initializer(0., 0.02)\n\n result = tf.keras.Sequential()\n result.add(\n tf.keras.layers.Conv2D(filters, size, strides=2, padding='same',\n kernel_initializer=initializer, use_bias=False))\n\n if apply_batchnorm:\n result.add(tf.keras.layers.BatchNormalization())\n\n result.add(tf.keras.layers.LeakyReLU())\n\n return result\ndef Discriminator():\n initializer = tf.random_normal_initializer(0., 0.02)\n\n inp = tf.keras.layers.Input(shape=[256, 256, 3], name='input_image')\n tar = tf.keras.layers.Input(shape=[256, 256, 2], name='target_image')\n\n x = tf.keras.layers.concatenate([inp, tar]) # (bs, 256, 256, channels*2)\n\n down1 = downsample(64, 4, False)(x) # (bs, 128, 128, 64)\n down2 = downsample(128, 4)(down1) # (bs, 64, 64, 128)\n down3 = downsample(256, 4)(down2) # (bs, 32, 32, 256)\n\n zero_pad1 = tf.keras.layers.ZeroPadding2D()(down3) # (bs, 34, 34, 256)\n conv = tf.keras.layers.Conv2D(512, 4, strides=1,\n kernel_initializer=initializer,\n use_bias=False)(zero_pad1) # (bs, 31, 31, 512)\n\n batchnorm1 = tf.keras.layers.BatchNormalization()(conv)\n\n leaky_relu = tf.keras.layers.LeakyReLU()(batchnorm1)\n\n zero_pad2 = tf.keras.layers.ZeroPadding2D()(leaky_relu) # (bs, 33, 33, 512)\n\n last = tf.keras.layers.Conv2D(1, 4, strides=1,\n kernel_initializer=initializer)(zero_pad2) # (bs, 30, 30, 1)\n\n return tf.keras.Model(inputs=[inp, tar], outputs=last)\n\n\n#######################################################################################################################################\nif(__name__==\"__main__\"):\n from data_pipline import step1_load_one_img, get_dataset\n import os\n import time\n\n PATH = \"datasets/facades\" \n inp, re = step1_load_one_img(PATH+\"/\"+'train/100.jpg')\n \n BUFFER_SIZE = 400\n BATCH_SIZE = 1\n\n start_time = time.time()\n train_dataset, test_dataset = get_dataset(db_dir=\"datasets\", db_name=\"facades\")\n\n ##############################################################################################################################\n start_time = time.time()\n generator = Generator()\n tf.keras.utils.plot_model(generator, show_shapes=True, dpi=64)\n\n gen_output = generator(inp[tf.newaxis,...], training=False) \n plt.imshow(gen_output[0,...])\n plt.show()\n\n discriminator = Discriminator()\n tf.keras.utils.plot_model(discriminator, show_shapes=True, dpi=64)\n\n disc_out = discriminator([inp[tf.newaxis,...], gen_output], training=False)\n plt.imshow(disc_out[0,...,-1], vmin=-20, vmax=20, cmap='RdBu_r')\n plt.colorbar()\n plt.show()","sub_path":"try11_myunet 這應該已經都包含再kong_model2理了,不過為了try_things讀起來的連續性還是保留一下好了/step2_kong_model.py","file_name":"step2_kong_model.py","file_ext":"py","file_size_in_byte":9502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"420070569","text":"import os\nimport sys\nimport transaction\nimport json\nimport requests\n\nfrom pyramid.paster import (\n setup_logging,\n bootstrap,\n )\n\nfrom pyramid.scripts.common import parse_vars\n\nfrom ..models import (\n Kitten,\n Base,\n )\n\n\ndef usage(argv):\n cmd = os.path.basename(argv[0])\n print('usage: %s [var=value]\\n'\n '(example: \"%s development.ini hippos.json\")' % (cmd, cmd))\n sys.exit(1)\n\n\ndef main(argv=sys.argv):\n if len(argv) < 3:\n usage(argv)\n config_uri = argv[1]\n json_path = argv[2]\n options = parse_vars(argv[3:])\n setup_logging(config_uri)\n # Configure the application, so we can access the registry.\n env = bootstrap(config_uri, options=options)\n # Generate a DBSession using the sessionmaker:\n DBSession = env['registry']['db_sessionmaker']()\n # The SQLAlchemy engine is accessible as the session's bind.\n engine = DBSession.bind\n Base.metadata.create_all(engine)\n json_data = json.load(open(json_path))\n with transaction.manager:\n for kitten_data in json_data:\n kitten = Kitten(source_url=kitten_data['source_url'],\n credit=kitten_data['credit'])\n r = requests.get(kitten_data['download_url'])\n if r.headers['content-type'] == 'image/jpeg':\n kitten.file_extension = '.jpeg'\n elif r.headers['content-type'] == 'image/png':\n kitten.file_extension = '.png'\n kitten.file_data = r.content\n DBSession.add(kitten)\n # Not strictly necessary, as everything gets unwound when main returns anyway.\n # But it's a good habit to keep.\n env['closer']()\n","sub_path":"kittenwar/scripts/initializedb.py","file_name":"initializedb.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"219501063","text":"import numpy as np\nfrom functools import reduce\nfrom sklearn.preprocessing import Normalizer\nimport serial\nfrom time import sleep\n\ndef read_line():\n line = ser.readline()\n data = str(line.decode('cp437')).strip('\\r0\\r\\n')\n if not data.isnumeric():\n data = 0\n try:\n return int(data)\n except ValueError:\n return 0\n\n\ndef debouncer(pulses=5):\n test = []\n if pulses == 0:\n return True\n for _ in range(pulses):\n if read_line() != 0:\n test.append(True)\n else:\n test.append(False)\n eval = reduce(lambda x, y: x and y, test)\n return eval\n\n\n#Cambiar normalizacion o.. normalizar los datos de entrenamiento tambien\ndef normalizar(data):\n scaler = Normalizer(norm='max')\n if len(data) == 1:\n data = data.reshape(1, -1)\n return scaler.transform(data)\n if len(data) > 1:\n return scaler.transform(data)\n\n\ndef get_measure(length):\n test_feat = []\n print('Tomando medicion !!')\n while len(test_feat) < length: #esa cantidad mas 1 del label\n data = read_line()\n test_feat.append(float(data))\n return np.array(test_feat).reshape(1, -1)\n\n\nser = serial.Serial(\"COM4\", baudrate=115200, timeout=1)\n\ndata_len = 1200\ncount = 0\nfeatures = np.zeros((1, data_len))\n\nwhile count < 300:\n\n print(f\"Ingresando dato {count} a la matriz.. preparese\")\n label = 3 # int(input('Ingrese label de la muestra proxima: '))\n while True:\n if debouncer(pulses=0):\n test_data = get_measure(data_len)\n test_data = np.insert(test_data, 0, label, axis=1)\n if not features.any():\n features = test_data\n else:\n features = np.append(features, test_data, axis=0)\n break\n print('### Fin de la muestra ###\\n')\n count += 1\n\nsave = input('desea guardar los datos recopilados? [y/n]: ')\nif save.lower() == 'y':\n print(features.shape)\n features = normalizar(features)\n save_name = input('Ingrese nombre del archivo: ')\n np.save(save_name, features)\n","sub_path":"Get_features.py","file_name":"Get_features.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"436023031","text":"\ntest = {\n 'name': 'Question 1_penalties',\n 'points': 1,\n 'suites': [\n {\n 'cases': [\n {\n 'code': r\"\"\"\n >>> # You need to set the value for 'p_15_of_15'\n >>> 'p_15_of_15' in vars()\n True\n \"\"\",\n 'hidden': False,\n 'locked': False\n },\n {\n 'code': r\"\"\"\n >>> # You haven't changed the value for 'p_15_of_15'\n >>> # from its initial state (of ...)\n >>> p_15_of_15 != ...\n True\n \"\"\",\n 'hidden': False,\n 'locked': False\n },\n {\n # n = 10000\n # # Take 10000 samples of 10000 trials of this problem.\n # res = np.sum(np.random.binomial(15, 0.8, (n, n)) == 0, axis=1) / n\n # np.quantile(res, [0.001, 0.999])\n 'code': r\"\"\"\n >>> 0.029 < p_15_of_15 < 0.041\n True\n \"\"\",\n 'hidden': False,\n 'locked': False\n }\n ],\n 'scored': True,\n 'setup': '',\n 'teardown': '',\n 'type': 'doctest'\n }\n ]\n}\n","sub_path":"tests/q_1_penalties.py","file_name":"q_1_penalties.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"559689528","text":"# Import dependencies\nfrom flask import Flask, render_template, redirect\nfrom flask_pymongo import PyMongo\nimport scrape_mars\n# Initialize flask app\napp = Flask(__name__)\n# Use flask_pymongo to set up mongo connection\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/mars_app\"\nmongo = PyMongo(app)\n# Will render a page from the index.html template\n@app.route(\"/\")\ndef index():\n # query for data from the mongo collection\n queried_data = mongo.db.mars_data.find_one()\n print(queried_data)\n return render_template(\"index.html\", data = queried_data)\n# Will scrape the latest mars data from Nasa's website and load it into\n# the MongoDB collection.\n@app.route(\"/scrape\")\ndef scraper():\n # Create the database collection and collection object \n mars_data_collection = mongo.db.mars_data\n \n # Empty the contents of the database to prevent duplicate data\n mongo.db.drop_collection(mars_data_collection)\n\n # Store the latest URL data into the dict\n data_dict = scrape_mars.scrape_all()\n print(data_dict)\n # Update the database\n mars_data_collection.insert(data_dict)\n return redirect(\"/\", code=302)\n # Main\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"Web Scraping Homework/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"89493112","text":"from openpyxl import load_workbook\r\n\r\nfilename = 'aalh_iit_transportation_002.xlsx'\r\nwb = load_workbook(filename)\r\nws = wb['Metadata Template']\r\n\r\nminimumcol = 2\r\nmaximumcol = 2\r\nminimumrow = 7\r\nmaximumrow = 639\r\n\r\niterationrow = 7\r\ntitlecol = 2\r\n\r\nfor row in ws.iter_rows(min_row=minimumrow, min_col=minimumcol, max_row=maximumrow, max_col=maximumcol):\r\n testvar = ws.cell(row=iterationrow, column=titlecol).value\r\n print(iterationrow)\r\n print(testvar)\r\n for cell in row:\r\n if testvar.find('Jones Junior High School') != -1:\r\n print('JONES')\r\n elif testvar.find(',') != -1:\r\n names = testvar.split(',')\r\n lastname = names[0]\r\n firstname = names[1]\r\n lastname = lastname.strip()\r\n firstname = firstname.strip()\r\n finaltitle = firstname + ' ' + lastname\r\n ws.cell(row=iterationrow, column=titlecol).value = finaltitle\r\n print(ws.cell(row=iterationrow, column=titlecol).value)\r\n iterationrow = iterationrow + 1\r\n#wb.save('aalh_iit_transportation_002.xlsx')","sub_path":"aalh_iit_transportation_002/cleanup-title-column.py","file_name":"cleanup-title-column.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"291686200","text":"\nimport numpy as np\nfrom scipy import *\nimport matplotlib.pyplot as plt\nfrom pylab import *\n\ndef f(x): \n tmp=-0.1*x**4-0.15*x**3-0.5*x**2-0.25*x+1.2\n return tmp\n\ndef c(x):\n tmp=(f(x+dx)-f(x))/dx\n return tmp\n\n\n\ndef prog(f,a,x0,dx): \n return (f(x0)+c(x0)*dx-f(x0))/dx \n\ndef reg(f,a,x0,dx): \n return (f(x0)-(f(x0)-c(x0)*dx))/dx\n\ndef cent(f,a,x0,dx): \n return (f(x0)+c(x0)*dx-(f(x0)-c(x0)*dx))/(2*dx)\n\n\nif(__name__==\"__main__\"):\n a=-10.0 \n b=10.0\n dx=0.5 \n x0=0.5 \n\n x=np.arange(a,b,dx) \n f1=f(x)\n f2=c(x)\n\n tmp=-0.4*x**3-0.45*x**2-x-0.25 \n \n pro=prog(f,a,x0,dx)\n re=reg(f,a,x0,dx)\n ce=cent(f,a,x0,dx)\n \n plt.plot(x,f1,\"-\",x,f2,\"--\",x,tmp,pro,\"o\",re,\"x\",ce,\"w\")\n plt.legend([\"funkcja\",\"obliczona\",\"recznie liczone\",\"ilorazy \"])\n plt.show()\n","sub_path":"Lab 5 zad 2.py","file_name":"Lab 5 zad 2.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"114315722","text":"from django.urls import path, include\nfrom . import views\n\nurlpatterns = [\n path('cinemas/search', views.get_matching_cinemas),\n path('movies/by_cinema', views.get_movies_by_cinema),\n path('sessions/by_duration', views.get_sessions_by_duration),\n path('sessions/next_sessions', views.next_sessions),\n path('sessions/by_movie', views.get_sessions_by_movie),\n path('sessions/by_date', views.get_sessions_by_date),\n path('movies/search', views.search_movies),\n path('movies/releases',views.upcoming_releases),\n path('movies/details',views.get_movie_details),\n]\n","sub_path":"scrapper/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"441958257","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 12 11:45:52 2019\n\n@author: Royston Marian Mascarenhas\n\n\"\"\"\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n#function to read images\ndef read_image(ipath,height1,width1,display_flag):\n Img1 = open(ipath,'rb').read()\n Img1 = np.frombuffer(Img1,np.uint8)\n ImageP1 = Img1[0:height1*width1]\n ImageP1 = np.reshape(ImageP1,(height1,width1))\n if(display_flag==1):\n plt.matshow(ImageP1,cmap='gray')\n return ImageP1\n\n#function to obtain tensor product between two 5x1 laws filters\ndef tensorprod(f_arr,arr):\n result = np.zeros((5,5))\n for i in range(0,5):\n for j in range(0,5):\n result[i,j] = f_arr[i]*arr[j];\n return result\n\n#*****************************BOUNDARY EXTENSION*******************************\n\ndef boundary_ext(Imagedata,n):\n n_width = height + 2*n;\n n_height = width + 2*n;\n ImageG = np.zeros((n_height,n_width))\n for i in range(n,height+n):\n for j in range(n,width+n):\n ImageG[i,j] = Imagedata[i-n,j-n]\n\n for i in range(0,n):\n for j in range(0,n_width):\n ImageG[i,j] = ImageG[n,j]\n \t\n for i in range(n_height-n,n_height):\n for j in range(0,n_width):\n ImageG[i,j] = ImageG[n_height-n-1,j]\n \n for i in range(0,n):\n for j in range(0,n_height):\n ImageG[j,i] = ImageG[j,n]\n \n for i in range(n_width-n,n_width):\n for j in range(0,n_height):\n ImageG[j,i] = ImageG[j,n_width-n-1]\n #ImageG = np.pad(Imagedata,n,'reflect');\n return ImageG\n#******************************************************************************\n#**********************APPLYING LAWS FILTER************************************\ndef apply_laws(Im1,fil,display_flag):\n n=n1;\n Im2 = np.zeros((height,width));\n ImDisp = np.zeros((height,width));\n for i in range(n,height+n):\n for j in range(n,width+n):\n temp = 0;\n x = 0\n for k in range(i-2,i+3):\n y = 0\n for l in range(j-2,j+3):\n temp = temp + Im1[k,l]*fil[x,y]\n y = y+1\n x = x+1\n Im2[i-n,j-n]= temp\n ImDisp[i-n,j-n]= temp\n if(display_flag==1):\n '''for x in range(0,height):\n for y in range(0,width):\n if ImDisp[x,y] < 0:\n ImDisp[x,y] = 0;\n elif (ImDisp[x,y] > 255):\n ImDisp[x,y] = 255;'''\n plt.matshow(ImDisp,cmap='gray')\n return Im2\n#******************************************************************************\n\n#*************************AVERAGE ENERGY PIXEL*********************************\ndef average_energy_pixel(ImP,feature_n):\n #print(\"energy: \"+str(energy_method));\n ImP_R = [];\n w = int(n_p/2);\n n=n2;\n for i in range(n,height+n):\n for j in range(n,width+n):\n sample = ImP[i-w:i+w+1,j-w:j+w+1];\n if (energy_method == 1):\n samplef = sample**2;\n elif(energy_method == 2):\n samplef = abs(sample)\n #print(\"here\")\n sumP = (np.sum(samplef)) / (n_p*n_p);\n ImP_R.append(sumP);\n #print(sumP)data\n for s in range (0,height*width):\n pixel_vectors[s,feature_n] = ImP_R[s];\n return(ImP_R);\n\n'''def average_energy_pixel(ImP,feature_n):\n ImP_R = [];\n w = int(n_p/2);\n n=n2;\n for i in range(n,height+n):\n for j in range(n,width+n):\n sumP = 0;\n for k in range(i-w,i+w+1):\n for l in range(j-w,j+w+1):\n sumP = sumP + np.square(ImP[k,l]);\n sumP = sumP / (n_p*n_p);\n ImP_R.append(sumP);\n for s in range (0,height*width):\n pixel_vectors[s,feature_n] = ImP_R[s];\n return(ImP_R);'''\n#******************************************************************************\n\n\n\n#******************************DECLARATIONS************************************\nn1=2;\nn2=12; #Boundary padding\nheight = 510\nwidth = 510\nnwidth = height + 2*n1\nnheight = width + 2*n1\nn_p = 25;\nprint(n_p)\nprint(\"Normalization L5L5\")\n\nL5 = np.array([1,4,6,4,1])\nE5 = np.array([-1,-2,0,2,1])\nS5 = np.array([-1,0,2,0,-1])\nW5 = np.array([-1,2,0,-2,1])\nR5 = np.array([1,-4,6,-4,1])\n#******************************************************************************\n\nL5L5 = tensorprod(L5,L5)\nL5E5 = tensorprod(L5,E5)\nL5S5 = tensorprod(L5,S5)\nL5W5 = tensorprod(L5,W5)\nL5R5 = tensorprod(L5,R5)\nE5E5 = tensorprod(E5,E5)\nE5L5 = tensorprod(E5,L5)\nE5S5 = tensorprod(E5,S5)\nE5W5 = tensorprod(E5,W5)\nE5R5 = tensorprod(E5,R5)\nS5S5 = tensorprod(S5,S5)\nS5L5 = tensorprod(S5,L5)\nS5E5 = tensorprod(S5,E5)\nS5W5 = tensorprod(S5,W5)\nS5R5 = tensorprod(S5,R5)\nW5W5 = tensorprod(W5,W5)\nW5L5 = tensorprod(W5,L5)\nW5E5 = tensorprod(W5,E5)\nW5S5 = tensorprod(W5,S5)\nW5R5 = tensorprod(W5,R5)\nR5R5 = tensorprod(R5,R5)\nR5L5 = tensorprod(R5,L5)\nR5E5 = tensorprod(R5,E5)\nR5S5 = tensorprod(R5,S5)\nR5W5 = tensorprod(R5,W5)\n\nenergy_method = int(input(\"Enter 1 to compute average energy of window by square method. Select 2 to compute average energy of window by absolute method\"));\nI1 = read_image(\"comb.raw\",510,510,1);\nI2 = np.zeros((nheight,nwidth))\nI3 = np.zeros((height,width))\npixel_vectors = np.zeros((height*width,25));\ndata = np.zeros((height*width,25));\n\n\nI2 = boundary_ext(I1,n1);\n\n\n#L5L5\nI3 = apply_laws(I2,L5L5,0);\n#print(I3[0:10,0:10])\nI4 = boundary_ext(I3,n2);\n#print(\"^^^^^^^^^\");\n#print(I4[0:10,0:10])\nvec_L5L5 = average_energy_pixel(I4,0);\n\n\n#L5E5\nI3 = apply_laws(I2,L5E5,0);\nI4 = boundary_ext(I3,n2);\nvec_L5E5 = average_energy_pixel(I4,1);\n\n#L5S5\nI3 = apply_laws(I2,L5S5,0);\nI4 = boundary_ext(I3,n2);\nvec_L5S5 = average_energy_pixel(I4,2);\n\n#L5W5\nI3 = apply_laws(I2,L5W5,0);\nI4 = boundary_ext(I3,n2);\nvec_L5W5 = average_energy_pixel(I4,3);\n\n#L5R5\nI3 = apply_laws(I2,L5R5,0);\nI4 = boundary_ext(I3,n2);\nvec_L5R5 = average_energy_pixel(I4,4);\n\n#---\n#E5L5\nI3 = apply_laws(I2,E5L5,0);\nI4 = boundary_ext(I3,n2);\nvec_E5L5 = average_energy_pixel(I4,5);\n\n#E5E5\nI3 = apply_laws(I2,E5E5,0);\nI4 = boundary_ext(I3,n2);\nvec_E5E5 = average_energy_pixel(I4,6);\n\n#E5S5\nI3 = apply_laws(I2,E5S5,0);\nI4 = boundary_ext(I3,n2);\nvec_E5S5 = average_energy_pixel(I4,7);\n\n#E5W5\nI3 = apply_laws(I2,E5W5,0);\nI4 = boundary_ext(I3,n2);\nvec_E5W5 = average_energy_pixel(I4,8);\n\n#E5R5\nI3 = apply_laws(I2,E5R5,0);\nI4 = boundary_ext(I3,n2);\nvec_E5R5 = average_energy_pixel(I4,9);\n\n#---\n#S5L5\nI3 = apply_laws(I2,S5L5,0);\nI4 = boundary_ext(I3,n2);\nvec_S5L5 = average_energy_pixel(I4,10);\n\n#S5E5\nI3 = apply_laws(I2,S5E5,0);\nI4 = boundary_ext(I3,n2);\nvec_S5E5 = average_energy_pixel(I4,11);\n\n#S5S5\nI3 = apply_laws(I2,S5S5,0);\nI4 = boundary_ext(I3,n2);\nvec_S5S5 = average_energy_pixel(I4,12);\n\n#S5W5\nI3 = apply_laws(I2,S5W5,0);\nI4 = boundary_ext(I3,n2);\nvec_S5W5 = average_energy_pixel(I4,13);\n\n#S5R5\nI3 = apply_laws(I2,S5R5,0);\nI4 = boundary_ext(I3,n2);\nvec_S5R5 = average_energy_pixel(I4,14);\nprint(\"HALFWAY CHECK\")\n#---\n#W5L5\nI3 = apply_laws(I2,W5L5,0);\nI4 = boundary_ext(I3,n2);\nvec_W5L5 = average_energy_pixel(I4,15);\n\n#W5E5\nI3 = apply_laws(I2,W5E5,0);\nI4 = boundary_ext(I3,n2);\nvec_W5E5 = average_energy_pixel(I4,16);\n\n#W5S5\nI3 = apply_laws(I2,W5S5,0);\nI4 = boundary_ext(I3,n2);\nvec_W5S5 = average_energy_pixel(I4,17);\n\n#W5W5\nI3 = apply_laws(I2,W5W5,0);\nI4 = boundary_ext(I3,n2);\nvec_W5W5 = average_energy_pixel(I4,18);\n\n#W5R5\nI3 = apply_laws(I2,W5R5,0);\nI4 = boundary_ext(I3,n2);\nvec_W5R5 = average_energy_pixel(I4,19);\n\n#---\n#R5L5\nI3 = apply_laws(I2,R5L5,0);\nI4 = boundary_ext(I3,n2);\nvec_R5L5 = average_energy_pixel(I4,20);\n\n#R5E5\nI3 = apply_laws(I2,R5E5,0);\nI4 = boundary_ext(I3,n2);\nvec_R5E5 = average_energy_pixel(I4,21);\n\n#R5S5\nI3 = apply_laws(I2,R5S5,0);\nI4 = boundary_ext(I3,n2);\nvec_R5S5 = average_energy_pixel(I4,22);\n\n#R5W5\nI3 = apply_laws(I2,R5W5,0);\nI4 = boundary_ext(I3,n2); \nvec_R5W5 = average_energy_pixel(I4,23);\n\n#R5R5\nI3 = apply_laws(I2,R5R5,0);\nI4 = boundary_ext(I3,n2);\nvec_R5R5 = average_energy_pixel(I4,24);\n\ndata = pixel_vectors.copy();\n\n#**************************NORMALIZATON****************************************\n'''m_n = np.mean(pixel_vectors[:,0]);\nstd_n = np.std(pixel_vectors[:,0]);\n\nfor i in range(0,height*width):\n temp1 = pixel_vectors[i,0];\n for j in range(0,25):\n pixel_vectors[i,j] = pixel_vectors[i,j] /temp1;'''\n\nmean_list = []\nvar_list = []\n#get the means and the variances\nfor i in range(0,25):\n buff = pixel_vectors[:,i]\n mean_list.append(np.mean(buff))\n var_list.append(np.std(buff))\n \n#normalize\nfor i in range(0,25):\n for j in range(0,height*width):\n pixel_vectors[j,i] = (pixel_vectors[j,i] - mean_list[i])/var_list[i];\n'''mean_list = []\nstd_list = []\nfor i in range(0,25):\n mean_list.append(np.mean(pixel_vectors[:,i]))\n std_list.append(np.std(pixel_vectors[:,i]))\n\nfor i in range(0,25):\n for j in range(0,height*width):\n pixel_vectors[j,i] = (pixel_vectors[j,i]-mean_list[i])/std_list[i];\n\npixel_vectors = pixel_vectors[:,1:25];'''\n\n'''mean_list = []\nstd_list = []\nfor i in range(0,height*width):\n mean_list.append(np.mean(pixel_vectors[i,:]))\n std_list.append(np.std(pixel_vectors[i,:]))\n\nfor i in range(0,height*width):\n for j in range(0,25):\n pixel_vectors[i,j] = (pixel_vectors[i,j]-mean_list[i])/std_list[i];\n\n#pixel_vectors = pixel_vectors[:,1:25];'''\n#******************************************************************************\n#*******************************PCA********************************************\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=7)\npca.fit(pixel_vectors)\nData_new = pca.transform(pixel_vectors)\n\n#******************************************************************************\n#**************************SEGMENTATION****************************************\nfrom sklearn.cluster import KMeans \nimport pandas as pd\ndf = pd.DataFrame(Data_new)\nkmeans = KMeans(n_clusters=7)\nkmeans.fit(df)\nlabels = kmeans.predict(df)\ncentroids = kmeans.cluster_centers_\n#******************************************************************************\nlab = labels.copy()\n#********************************DENOTATION************************************\noutput = np.reshape(labels,(height,width));\nfor i in range(0,height):\n for j in range(0,width):\n if(output[i,j]==0):\n output[i,j] = 0;\n if(output[i,j]==1):\n output[i,j] = 42;\n if(output[i,j]==2):\n output[i,j] = 84;\n if(output[i,j]==3):\n output[i,j] = 126;\n if(output[i,j]==4):\n output[i,j] = 168;\n if(output[i,j]==5):\n output[i,j] = 210;\n if(output[i,j]==6):\n output[i,j] = 255;\n\nplt.figure(figsize=(10,10)) #before interplation\nplt.matshow(output,cmap='gray',fignum=1)\n\ng = 19;\noutput2 = np.zeros((height,width));\noutput2a = boundary_ext(output,g);\n\nfrom scipy import stats\n\nfor i in range(g,height+g):\n for j in range(g,width+g):\n #m = output[i,j];\n #comp = np.ones((7,7));\n #comp2 = comp * m;\n comp3 = output2a[i-g:i+g+1,j-g:j+g+1];\n a,b=stats.mode(comp3,axis=None);\n a1 = a[0]\n output2[i-g,j-g] = int(a1);\n\n \nprint(\"EOF Reached: Success\");\nplt.figure(figsize=(10,10)) #before interplation\n#plt.matshow(output,cmap='gray',fignum=1)\nplt.matshow(output2,cmap='gray',fignum=1)","sub_path":"Texture-Analysis-and-Segmentation/improving_segmentation.py","file_name":"improving_segmentation.py","file_ext":"py","file_size_in_byte":11332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"488686673","text":"#!/usr/bin/env python\n\"\"\"\nCompare two files for equality.\n\nUsage::\n\n python -m riboviz.tools.compare_files [-h]\n -1 FILE1 -2 FILE2 [-n]\n\n -h, --help show this help message and exit\n -1 FILE1, --file1 FILE1\n File1\n -2 FILE2, --file2 FILE2\n File2\n -n, --names Compare file names\n\nIf the files are equivalent an exit code of 0 is returned. If the\nfiles are not equivalent an exception is raised and an exit code of 1\nis returned.\n\nIf ``-n`` is provided then the file names are also compared for\nequality (for example, if comparing the same file in two different\ndirectories).\n\nSee :py:func:`riboviz.compare_files.compare_files` for information on\nthe nature of the comparisons.\n\"\"\"\nimport argparse\nfrom riboviz import compare_files\n\n\ndef parse_command_line_options():\n \"\"\"\n Parse command-line options.\n\n :returns: command-line options\n :rtype: argparse.Namespace\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Compare two files for equality\")\n parser.add_argument(\"-1\",\n \"--file1\",\n dest=\"file1\",\n required=True,\n help=\"File1\")\n parser.add_argument(\"-2\",\n \"--file2\",\n dest=\"file2\",\n required=True,\n help=\"File2\")\n parser.add_argument(\"-n\",\n \"--names\",\n dest='names',\n action='store_true',\n help=\"Compare file names\")\n options = parser.parse_args()\n return options\n\n\ndef invoke_compare_files():\n \"\"\"\n Parse command-line options then invoke\n :py:func:`riboviz.compare_files.compare_files`.\n \"\"\"\n options = parse_command_line_options()\n file1 = options.file1\n file2 = options.file2\n names = options.names\n compare_files.compare_files(file1, file2, names)\n\n\nif __name__ == \"__main__\":\n invoke_compare_files()\n","sub_path":"riboviz/tools/compare_files.py","file_name":"compare_files.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"178852015","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.contrib.messages.views import SuccessMessageMixin\n# Create your models here.\nclass Teacherinfo(models.Model):\n\tfirst_name=models.CharField(max_length=100)\n\tlast_name=models.CharField(max_length=100)\n\temail_address=models.EmailField(max_length=100)\n\tsalary=models.IntegerField()\n\tdate_of_birth=models.DateField()\n\tdate_join=models.DateField()\n\tuser=models.OneToOneField(User,on_delete=models.CASCADE)\n\tliving_address=models.CharField(max_length=100)\n\tintroduction=models.TextField(blank=True,null=True)\n\tsubject=models.CharField(max_length=100,null=True)\n\tsalarypay_date=models.DateField(blank=True,null=True)\n\tdue=models.IntegerField(default=0,blank=True,null=True)\n\n\n\tdef __str__(self):\n\t\treturn self.first_name\n\tdef get_absolute_url(self):\n\t\treturn reverse('teacher-detail',kwargs={'pk':self.pk})\nclass Teacher_Subject(models.Model):\n\tuser_name=models.ForeignKey(Teacherinfo,on_delete=models.CASCADE)\n\tsubject=models.CharField(max_length=50)\n\tclass_name=models.IntegerField(null=True,blank=True)\n\tavg_score=models.IntegerField(null=True,blank=True)\n\tdef get_absolute_url(self):\n\t\treturn reverse('subject-add')\n\nclass Teacher_Evaluation(models.Model):\n\tperfomance=models.TextChoices('perfomance','A B C D E')\n\tcreativity=models.CharField(blank=True,choices=perfomance.choices,max_length=10)\n\tAttendence=models.CharField(blank=True,choices=perfomance.choices,max_length=10)\n\tAssignment=models.CharField(blank=True,choices=perfomance.choices,max_length=10)\n\tstudent_voting=models.CharField(blank=True,choices=perfomance.choices,max_length=10)\n\tstaff_voting=models.CharField(blank=True,choices=perfomance.choices,max_length=10)\nclass Attendence(models.Model):\n\tperfomance=models.TextChoices('perfomance','A P')\n\tattendence=models.CharField(choices=perfomance.choices,max_length=10)\n\tteacherinfo=models.ForeignKey(Teacherinfo,on_delete=models.CASCADE)\n\tdate=models.DateField(default=timezone.now)\n\tdef get_absolute_url(self):\n\t\t# messages.add_message(self.request, messages.INFO, 'form submission success')\n\t\treturn reverse('teacher-attendence')\n\nclass Teacher_Payment_Bill(models.Model):\n\tteacherinfo=models.ForeignKey(Teacherinfo,on_delete=models.CASCADE)\n\tbill_payer_name=models.CharField(max_length=100)\n\tpaid_amount=models.IntegerField()\n\tdue_amount=models.IntegerField()\n\tpaid_date=models.DateField(default=timezone.now)\n\t# def get_absolute_url(self):\n\t# \t# messages.add_message(self.request, messages.INFO, 'form submission success')\n\t# \treturn reverse('salary-pdf',kwargs={\"pk\":self.})\n\n\n","sub_path":"teacher/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"291102933","text":"#!/usr/bin/env python\n'''\ntest_simple.py - Tests registration of a single video against a background\n image, detection and classification of things, and\n identification of the classified things on screen.\n '''\n# import all necessary packages and utilities\nimport cv2\nimport context\nimport os\nfrom vision.vision_tools import VisionTools\nfrom vision.cameras.camera_img_feed import imgFeedCamera\n\n\nif __name__ == '__main__':\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print(\"Buoy Bounding Boxes Test: Takes in a single image and \")\n print(\" draws bounding boxes around discovered 'buoys'.\")\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n\n # read in image from camera (debug denotes test image)\n #define relative path to test file\n path = os.getcwd()\n #in case of windows users, switched backslashes with fwd slashes\n pathFwd = '/'.join(path.split('\\\\'))\n pathFwd = pathFwd + '/test_files/'\n filename = 'Circle.png'\n fullFilePath = pathFwd + filename\n\n joeCamera = imgFeedCamera(debug=fullFilePath)\n image = joeCamera.getFrame()\n\n # Resize Image\n r = 640.0 / image.shape[1]\n dim = (640, int(image.shape[0] * r))\n\n image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)\n cv2.imshow('image', image)\n cv2.waitKey(0)\n\n tools = VisionTools()\n\n final = tools.BuoyBoxes(image)\n cv2.imshow('image', final)\n cv2.waitKey(0)\n","sub_path":"tests/test_BuoyBoxes.py","file_name":"test_BuoyBoxes.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"82647528","text":"import argparse\nimport os\nimport sys\nimport time\n\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\"))\nfrom caac_package.Crawler import Crawler\nfrom caac_package.Year import Year\n\nparser = argparse.ArgumentParser(description=\"A Crawler for CAAC website.\")\nparser.add_argument(\n \"--year\",\n type=int,\n default=Year.YEAR_CURRENT,\n help=\"The year of data to be processed. (ex: 2017 or 106 is the same)\",\n)\n# fmt: off\nparser.add_argument(\n \"--projectBaseUrl\",\n type=str,\n default=\"\",\n help=\"The (base) URL of the CAAC HTML page.\",\n)\n# fmt: on\nargs = parser.parse_args()\n\nyear = Year.taiwanize(args.year)\n\nt_start = time.time()\n\ncrawler = Crawler(year, \"apply_entrance\", args.projectBaseUrl)\ncrawler.run(showMessage=True)\n\nt_end = time.time()\n\nprint(f\"[Done] It takes {t_end - t_start} seconds.\")\n","sub_path":"第二階段-分發結果(甄選委員會)/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"145726724","text":"from django.test import TestCase\nimport mock\nfrom datetime import datetime\n\nfrom nectar_allocations.models.allocation import AllocationRequest\nfrom nectar_allocations.sitemap import AllocationsSitemap\n\n\nclass SitemapTest(TestCase):\n\n @mock.patch(\n 'nectar_allocations.models.allocation.AllocationRequest.'\n 'find_active_allocations')\n def test_items(self, mock_find_active_allocations):\n request0 = AllocationRequest(project_name=\"Project X\", status=\"E\")\n request1 = AllocationRequest(project_name=\"Project Y\", status=\"X\")\n expected_items = [request0, request1]\n\n mock_find_active_allocations.return_value = expected_items\n site_map = AllocationsSitemap()\n actual_items = site_map.items()\n self.assertListEqual(expected_items, actual_items)\n\n def test_lastmod(self):\n expected_datetime = datetime(2014, 10, 13)\n request0 = AllocationRequest(project_name=\"Project X\", status=\"E\")\n request0.modified_time = expected_datetime\n site_map = AllocationsSitemap()\n actual_modification_datetime = site_map.lastmod(request0)\n self.assertEquals(expected_datetime, actual_modification_datetime)\n\n def test_location(self):\n request0 = AllocationRequest(project_name=\"Project X\", status=\"E\")\n request0.id = 12345\n site_map = AllocationsSitemap()\n actual_location = site_map.location(request0)\n expected_location = '/allocations/applications/12345/approved'\n self.assertEquals(expected_location, actual_location)\n","sub_path":"nectar_allocations/tests/test_sitemap.py","file_name":"test_sitemap.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"523687829","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 4 16:28:48 2021\r\n\r\n@author: User\r\n\"\"\"\r\n\r\nfrom astropy.io import fits\r\nimport numpy as np\r\nimport random\r\n\r\nfrom matplotlib import pyplot as plt\r\n\r\nabs_file = fits.open('xabsgrid_ufo.fits')\r\nspectra = abs_file['spectra'].data\r\nenergies = abs_file['energies'].data\r\nparams = abs_file['parameters'].data\r\n\r\ndef E_mid(E):\r\n E_mid = []\r\n for i in E:\r\n E_mid.append((i[0]+i[1])/2)\r\n return E_mid\r\n\r\n#returns the flux at random ionisation energy coordinates at same energy (index) \r\n#and col density are the same within index 0-5, 6-10 etc, see c\r\nc_lower=0\r\nc_upper=5\r\ndef randm_20(ind_en):\r\n r_flux = []\r\n for i in range(0,20):\r\n r = random.randrange(c_lower,c_upper)\r\n r_flux.append(spectra['intpspec'][r][ind_en])\r\n \r\n return r_flux\r\n\r\n\r\n#returns F_var eqn10 without error\r\n#http://articles.adsabs.harvard.edu/pdf/2003MNRAS.345.1271V\r\ndef F_var(mean,std):\r\n return np.sqrt(std**2/(mean**2))\r\n\r\n\r\n#print(spectra['paramval'])","sub_path":"F_var_functions.py","file_name":"F_var_functions.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"434804316","text":"from pygame import *\r\nfrom random import randint\r\nfont.init()\r\nmixer.init()\r\n\r\n#classes\r\nclass GameSprite(sprite.Sprite):\r\n def __init__(self, player_image, player_x, player_y, size_x,size_y,player_speed):\r\n super().__init__()\r\n\r\n #images\r\n self.image = transform.scale(image.load(player_image), (size_x,size_y))\r\n self.speed = player_speed\r\n\r\n #rect\r\n self.rect = self.image.get_rect()\r\n self.rect.x = player_x\r\n self.rect.y = player_y\r\n\r\n def reset(self):\r\n window.blit(self.image, (self.rect.x, self.rect.y))\r\n\r\n#player class\r\nclass Player(GameSprite):\r\n def update(self):\r\n keys = key.get_pressed()\r\n if keys[K_a]:\r\n self.rect.x -= self.speed\r\n if keys[K_d]:\r\n self.rect.x += self.speed\r\n def fire(self):\r\n bullet = Bullet(\"bullet.png\", self.rect.centerx, self.rect.top, 20, 20, 5)\r\n bullets.add(bullet)\r\n\r\n\r\n#enemy class\r\nmiss = 0\r\nclass Enemy(GameSprite):\r\n def update(self):\r\n self.rect.y += self.speed\r\n if self.rect.y > 1000:\r\n self.rect.x = randint(10, 620)\r\n self.rect.y = -65\r\n\r\nclass Bullet(GameSprite):\r\n def update(self):\r\n self.rect.y -= self.speed\r\n if self.rect.y < -10:\r\n self.kill()\r\n #install gamed\r\n#view\r\nwindow = display.set_mode((700, 900))\r\ndisplay.set_caption(\"Межгалактические войны\")\r\nbackground = transform.scale(image.load('galaxy.jpg'), (700, 900))\r\n#переменные\r\nscore = 0\r\nfinish = False\r\n#music\r\nmixer.music.load('space.ogg')\r\nmixer.music.play()\r\nfire_sound = mixer.Sound('fire.ogg')\r\n\r\n#spites\r\nplayer = Player(\"rocket.png\", 0, 815, 100, 100, 3)\r\n\r\nmonsters = sprite.Group()\r\nfor i in range (5):\r\n monster = Enemy('ufo.png', randint(10, 320), -65, 100, 100,randint(2, 5))\r\n monsters.add(monster)\r\n\r\nbullets = sprite.Group()\r\n\r\n\r\n#time|FPS\r\nFPS = 60\r\nclock = time.Clock()\r\n\r\n#game functional\r\ngame = True\r\nfont1 = font.Font(None, 100)\r\nwhile game == True:\r\n for e in event.get():\r\n if e.type == QUIT:\r\n game = False\r\n elif e.type == KEYDOWN:\r\n if e.key == K_SPACE:\r\n player.fire()\r\n\r\n if miss == 3:\r\n finish = True\r\n\r\n if finish == False:\r\n window.blit(background, (0, 0))\r\n\r\n player.update()\r\n player.reset()\r\n monsters.update()\r\n monsters.draw(window)\r\n bullets.update()\r\n bullets.draw(window)\r\n\r\n collides = sprite.groupcollide(monsters, bullets, True, True)\r\n for collide in collides:\r\n monster = Enemy('ufo.png', randint(10, 320), -65, 100, 100,randint(2, 5))\r\n monsters.add(monster)\r\n score += 1\r\n\r\n if sprite.spritecollide(player, monsters, False, False):\r\n finish = True\r\n text_lose = font1.render('LOSER', 1, (255, 255, 200))\r\n window.blit(text_lose, (10, 50))\r\n\r\n display.update()\r\n clock.tick(FPS) ","sub_path":"PingPong/shooter.py","file_name":"shooter.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"7363850","text":"#xps_file = r'C:\\Users\\Administrator\\Documents\\*'\n# p = os.listdir(xps_file)\n# xps_file += \"\\\\\" + str(p[0])\nimport os\n\ndef a_remove1(files):\n\n for f in files:\n os.remove(f)\n print('removed all invoice pdf files from download folder')\n#a_remove1(xps_file)","sub_path":"amazon_processing_code/dd/remove_file.py","file_name":"remove_file.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"136924297","text":"\nfrom pymongo import MongoClient\n\nclass Connector(object):\n\n def __init__(self):\n self.client = MongoClient('mongodb://mongo:mongo@127.0.0.1:27017')\n\n def add_record(self):\n name = input(\"Name: \")\n role = input(\"Role: \")\n try:\n db = self.client.blog.Users\n db.insert_one({\"Name\":name, \"Role\":role})\n self.client.close()\n return \"Done!\"\n except Exception as e:\n return e\n\n def search_record(self):\n name = input(\"Name: \")\n db = self.client.blog.Users\n data = db.find_one({\"Name\":name})\n self.client.close()\n return data\n\n\n","sub_path":"databases/mongodb_add_search_record.py","file_name":"mongodb_add_search_record.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"169251172","text":"\"\"\"\nClasses Of The Game Mac Gyver\n\n\"\"\"\n\n#! /usr/bin/env python3\n# coding: utf-8\n\nimport random\nimport pygame\nfrom constants import NB_SPRITE, SIZE_SPRITE, LVL_DESIGN, PIC_WALL, PIC_START, PIC_END, OBJECT_TAKEN\n\n\n\n\nclass Map:\n\n \"\"\"\n This class generates a level from the file\n\n \"\"\"\n\n def __init__(self):\n\n # The map's file\n self.file = LVL_DESIGN\n # The map in the form of list\n self.structure = 0\n\n\n\n\n def create(self):\n\n \"\"\"\n This class scan a level from the file\n\n \"\"\"\n\n # Open the lvl file\n with open(self.file, 'r') as file:\n # Create a list of list\n structure_file = []\n\n for lign in file:\n lign_lvl = []\n\n # Each caracter will be a case of the grid\n for caracter in lign:\n if caracter != \"\\n\":\n lign_lvl.append(caracter)\n\n structure_file.append(lign_lvl)\n\n self.structure = structure_file\n\n def display(self, window):\n \"\"\"\n This class generates the level design\n\n \"\"\"\n\n\n # Different sprite of the lvl design\n wall = pygame.image.load(PIC_WALL).convert()\n start = pygame.image.load(PIC_START).convert()\n end = pygame.image.load(PIC_END).convert()\n\n lign_number = 0\n for lign in self.structure:\n\n case_number = 0\n for sprite in lign:\n # Add the corresponding sprite at the good place\n x_case = case_number * SIZE_SPRITE\n y_case = lign_number * SIZE_SPRITE\n if sprite == 'm':\n window.blit(wall, (x_case, y_case))\n elif sprite == 'd':\n window.blit(start, (x_case, y_case))\n elif sprite == 'a':\n window.blit(end, (x_case, y_case))\n case_number += 1\n lign_number += 1\n\n\nclass Character:\n\n \"\"\"\n This class generates the character\n\n \"\"\"\n\n def __init__(self, right_char, left_char, up_char, down_char, lvl):\n\n # Character's sprite\n self.right = pygame.image.load(right_char).convert_alpha()\n self.left = pygame.image.load(left_char).convert_alpha()\n self.up = pygame.image.load(up_char).convert_alpha()\n self.down = pygame.image.load(down_char).convert_alpha()\n\n # Initialization of the direction\n self.direction = self.right\n\n # Initialization of the position on the grid\n self.x = 0\n self.y = 0\n\n # Initialization of the position on the design\n self.sprite_x = 0\n self.sprite_y = 0\n\n # LVL where the character is\n self.lvl = lvl\n\n # Number of object taken\n self.nb_object = 0\n\n\n def move(self, direction):\n\n \"\"\"\n\n Character's deplacement\n\n \"\"\"\n\n if direction == 'right':\n # Test if the character will not go out of the screen\n if self.x < (NB_SPRITE - 1):\n # Test if the destination is not a wall\n if self.lvl.structure[self.y][self.x + 1] != 'm':\n # Incrementing self.x by 1\n self.x += 1\n # Update the position on the interface\n self.sprite_x = self.x * SIZE_SPRITE\n # Update the direction on the interface\n self.direction = self.right\n\n if direction == 'left':\n if self.x > 0:\n if self.lvl.structure[self.y][self.x - 1] != 'm':\n self.x -= 1\n self.sprite_x = self.x * SIZE_SPRITE\n self.direction = self.left\n\n if direction == 'up':\n if self.y > 0:\n if self.lvl.structure[self.y - 1][self.x] != 'm':\n self.y -= 1\n self.sprite_y = self.y * SIZE_SPRITE\n self.direction = self.up\n\n if direction == 'down':\n if self.y < (NB_SPRITE - 1):\n if self.lvl.structure[self.y + 1][self.x] != 'm':\n self.y += 1\n self.sprite_y = self.y * SIZE_SPRITE\n self.direction = self.down\n\n def take_obj(self, obj):\n \"\"\"\n\n Get the object\n\n\n \"\"\"\n\n if (self.x == obj.obj_x) and (self.y ==\n obj.obj_y) and (obj.taken is False):\n self.nb_object += 1\n obj.taken = True\n obj.design = pygame.image.load(OBJECT_TAKEN).convert_alpha()\n\n\nclass Object:\n\n \"\"\"\n Class that generate objects\n\n \"\"\"\n\n # Create an object and place him in random position\n def __init__(self, lvl, design):\n\n # Object's position on the grid\n self.obj_x = 0\n self.obj_y = 0\n\n # Object's position on the design\n self.obj_sprite_x = 0\n self.obj_sprite_y = 0\n\n # Bool if the object has been picked up\n self.taken = False\n self.lvl = lvl\n self.design = pygame.image.load(design).convert_alpha()\n\n # Place the object on a sprite o\n while self.lvl.structure[self.obj_y][self.obj_x] != 'o':\n # Update the position on the grid\n self.obj_x = random.randint(0, NB_SPRITE - 1)\n self.obj_y = random.randint(0, NB_SPRITE - 1)\n # Update the position on the design\n self.obj_sprite_x = self.obj_x * SIZE_SPRITE\n self.obj_sprite_y = self.obj_y * SIZE_SPRITE\n","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"417528378","text":"import cv2;\n\ndef CV_isButtonPressed(key = \"q\"):\n return cv2.waitKey(1) & 0xFF == ord(key);\n\ndef CV_waitForAnyKeyToBePressed():\n cv2.waitKey(0);\n\ndef frameResize(frame, new_width):\n h,w,c = 0,0,0;\n if len(frame.shape) > 2:\n h, w, c = frame.shape;\n else:\n h, w = frame.shape;\n ratio = float(new_width) / float(w);\n dim = (int(new_width), int(float(h) * ratio));\n frame = cv2.resize(frame, dim, interpolation= cv2.INTER_LINEAR); \n return (ratio, frame);","sub_path":"EyeTracker/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"632458482","text":"from django.shortcuts import render, redirect\n\nfrom team.forms import UpsertTeamForm, JoinTeam\nfrom account.models import CustomUser as User\nfrom service_api.models.teams import Team, Member\nfrom service_api.models.tournaments import Participate\n\n\ndef upsert_team(request, user_id=None, team_id=None):\n \"\"\"\n チームの新規作成・修正を行う\n :param request:\n :param int user_id:\n :param int team_id:\n :return:\n \"\"\"\n if request.method == 'POST':\n # 編集時\n if team_id:\n form = UpsertTeamForm(request.POST, request.FILES, instance=Team.objects.get(pk=team_id))\n if form.is_valid():\n form.save()\n return redirect('/competition/team/')\n return render(request, 'cms/team/upsert_team.html', context={\n 'user_id': user_id,\n 'participate_tournaments': Participate.objects.filter(team_id=team_id).all(),\n 'members': Member.objects.filter(team_id=team_id).order_by('id').all(),\n 'form': form\n })\n # 新規追加\n form = UpsertTeamForm(request.POST, request.FILES)\n if form.is_valid():\n new_team = form.save()\n\n # Team Organizerとして登録しておく\n user = User.objects.get(pk=user_id)\n team = Team.objects.get(pk=new_team.pk)\n Member.objects.add_member(user, team, is_admin=True)\n return redirect('/competition/team/')\n return render(request, 'cms/team/upsert_team.html', context={\n 'user_id': user_id,\n 'form': form,\n })\n return render(request, 'cms/team/upsert_team.html', context={\n 'user_id': user_id,\n 'team_id': team_id,\n 'participate_tournaments': Participate.objects.filter(team_id=team_id).all(),\n 'members': Member.objects.filter(team_id=team_id).order_by('id').all(),\n 'form': UpsertTeamForm(instance=Team.objects.get(pk=team_id)) if team_id else UpsertTeamForm()\n })\n\n\ndef delete_team(request, team_id):\n \"\"\"\n チームを削除する\n :param request:\n :param int team_id:\n :rtype redirect:\n \"\"\"\n team = Team.objects.get(pk=team_id)\n if team:\n team.delete()\n return redirect('/competition/team/')\n\n\ndef belong_teams(request, user_id):\n \"\"\"\n 指定されたユーザーの所属チームを返す\n :param request:\n :param int user_id:\n :rtype render:\n \"\"\"\n return render(request, 'cms/user/edit_belong_team.html', context={\n 'user_id': user_id,\n 'nickname': User.objects.get(pk=user_id).username,\n 'teams': Member.get_joined_teams(user_id),\n 'team_form': JoinTeam(user_id)\n })\n\n\ndef join_team(request):\n \"\"\"\n 指定されたチームに所属させる\n :param request:\n :rtype redirect:\n \"\"\"\n if request.method == 'POST':\n user_id = request.POST.get('user_id')\n user = User.objects.get(pk=user_id)\n team = Team.objects.get(pk=request.POST.get('team_id'))\n if user and team:\n Member.objects.add_member(user, team, is_admin=False)\n return redirect('/competition/user/edit/{}/belong_team/'.format(user_id))\n return redirect('/competition/team/')\n\n\ndef secession_team(request, user_id, team_id):\n \"\"\"\n チームから脱退する\n :param request:\n :param int user_id:\n :param int team_id:\n :rtype redirect:\n \"\"\"\n\n user = User.objects.get(pk=user_id)\n team = Team.objects.get(pk=team_id)\n if user and team:\n member = Member.objects.filter(user=user).filter(team=team)\n member.delete()\n return redirect('/user/edit/{}/belong_team/'.format(user_id))\n return redirect('/user/edit/{}/belong_team/'.format(user_id))\n\n\ndef team_list(request):\n \"\"\"\n チームリストを返す\n :param request:\n :rtype render:\n \"\"\"\n return render(request, 'cms/team/team_list.html', context={\n 'teams': Team.get_all_teams_with_organizer()\n })\n","sub_path":"team/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"357853105","text":"#!/usr/bin/env python27\nimport matplotlib.pyplot as plt\nimport numpy as np\n'''\nThe resonant frequency is gamma times H_0. \n\ngamma is 2pi 0.630 kHz/G and H_0 has units of Gauss. \n \nYour probability distribution for H_0 should be centered at 100G with a width of 1G.\n ### It is centered at 100 G and the width is 1 Gauss according to the gaussian\n #\n ### Print out the equation of the gaussian you are using and exemplify how your sigma \n value is equal to 1\n ### Redirect his attention to the graph. Ask a question as to why this does not correspond\n to a central value of 1\n \nIt looks like you are missing a factor of gamma somewhere or the x axis is mislabelled?\\\n ### True. Acknowledge\n\nTheta is a function of H_0 so if H_0 is distributed so is theta. \nI am wondering why you say theta is pi/2? Do you mean the average value of theta?\n ### As we discussed, the equation coverning the signal is defined for...\n #\n ### I see. Need to have a nested loop to average over all theta and for all H_0\n ... new algorithm.\n\nAn important check is to narrow the distribution of H_0 \n (say to 0.01 G and check that the signal is an undamped cosine with amplitude \n 1 and frequency 0.630 kHz/G times H1.\n ### This was found. Print out at show.\n'''\n\n'''\nThe next step is to make a few plots of P_z(t) on resonance \n and on either side of the resonance.\n ### Completed in signal.py?\n\nOn resonance you expect a cosine with amplitude 1.0\n ### Seen.\n\nThen calculate the signal averaged over a Gaussian distribution of H_0.\n ### Done. \n\nIn this case you expect a damped cosine with damping proportional to the\n width of the assumed Gaussian distribution of H_0. \n \nThis is the signal we expect to see in the experiment. \n\nThen investigate how the damping depends on H1.\n'''\nnp.set_printoptions(threshold=np.inf)\n\n\ntmin = 0\ntmax = 1\nbin_amount = 1000\n\n\n## Amplitude and Net Mag Field\nh_0 = 100 # Gauss\nh_1 = 14 # Gauss\ngamma = 2*np.pi*0.630 # kHz/G\n\n## Test Thetas\n#theta = np.linspace(0,np.pi/2,100)\ntheta = [np.pi/4] #,np.pi/4,np.pi/6,np.pi/12,np.pi/32,np.pi/64,np.pi/128,0]\n#theta = [0]\n\n## time\nt = np.linspace(tmin,tmax,bin_amount + 1)\n\n \n## Gaussian + Plot\nplt.figure(2)\nmu, sigma = 100, 1 # mean and standard deviation\ns = np.random.normal(mu, sigma, 1000)\n#Plot histogram Points\ncount, bins, ignored = plt.hist(s, bin_amount, normed=True)\ngaussian = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2))\n#Plot the gaussian curve\nplt.plot(bins, gaussian,linewidth=2, color='r')\nplt.xlabel(r'$B$ [$Gauss$]')\nplt.ylabel(r'$pdf(H_0)$')\nplt.title(r'$H_0$ Histogram')\nplt.show()\n\n\n## Signal for a fixed theta and h_0\nx0 = np.zeros(bin_amount + 1)\nx0 = np.cos(np.pi/2)**2 + np.sin(np.pi/2)**2 * np.cos(gamma * h_0 * gaussian[100] * t)\n\n## Signal averaged \ny0 = np.zeros(bin_amount + 1)\nfor m in theta:\n for i in s: \n y0 += np.cos(m)**2 + np.sin(m)**2 * np.cos(gamma * h_0 * i * t)\n y0 /= s.size\n#y0 /= len(theta)\n\n### Doesn't this need to be here?\n#y0 /= 100\n\n\n\n###Assumption\n \n\n\n\n#plt.figure(1)\n#plt.plot(w,np.sin(theta)**2)#(h_1/(h_0-w/gamma))**2)\n#plt.xlabel(r'$\\omega \\quad [rad/s]$')\n#plt.ylabel(r'$\\sin^2(\\theta) \\quad [none]$')\n#plt.title(r'$Amplitude$')\n#\n#plt.figure(2)\n#plt.plot(w,h_tot)\n#plt.xlabel(r'$\\omega \\quad [rad/s]$')\n#plt.ylabel(r'$ \\sqrt{h_1^2 + (h_0 - \\frac{\\omega}{\\gamma})^2} \\quad [G]$')\n#plt.title(r'$H_{Tot}$')\n\nplt.figure(3)\nplt.plot(t,x0)\nplt.xlabel(r'$t$ $[s]$')\nplt.ylabel(r'$P_z(t)$ $[none]$')\nplt.title(r'Regular Signal')\n\n\nplt.figure(4)\nplt.plot(t,y0)\nplt.xlabel(r'$t$ $[s]$')\nplt.ylabel(r'$P_z(t)$ $[none]$')\nplt.title(r'Averaged Signal')\n\n\nplt.figure(5)\nplt.plot(s)\nplt.xlabel(r'$t$ $[s]$')\nplt.ylabel(r'$P_z(t)$ $[none]$')\nplt.title(r'$Gaussian$ Test')\n\n\n\n####################################################################################################\n####################################################################################################\n\n\n\n","sub_path":"Signal Program Suite/Scripts_01/signal.py","file_name":"signal.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"461889111","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport hashlib\n\n\ndef get_md5(data):\n obj = hashlib.md5()\n obj.update(data.encode('utf-8'))\n return obj.hexdigest()\n\n\nv = get_md5('hellodjango')\nprint(len(v))\nprint(v)\n\n\n# def get_hash(data):\n# h = hashlib.sha1()\n# h.update(bytes(data, encoding='utf-8'))\n# s = h.hexdigest()\n# print(s)\n#\n# get_hash('admin')\n\n\n","sub_path":"012 函数闭包&模块/5. hashlib模块.py","file_name":"5. hashlib模块.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"570329395","text":"#!/usr/bin/env python2.7\n\n# ---- MODULE DOCSTRING\nfrom __future__ import print_function,division\n__doc__ = \"\"\"\n\n(C) Hive, Romain Wuilbercq, 2017\n\t _\n\t/_/_ .'''.\n =O(_)))) ...' `.\n\t\\_\\ `. .'''X\n\t\t\t\t\t `..'\n.---. .---..-./`) ,---. ,---. .-''-.\n| | |_ _|\\ .-.')| / | | .'_ _ \\\n| | ( ' )/ `-' \\| | | .'/ ( ` ) '\n| '-(_{;}_)`-'`\"`| | _ | |. (_ o _) |\n| (_,_) .---. | _( )_ || (_,_)___|\n| _ _--. | | | \\ (_ o._) /' \\ .---.\n|( ' ) | | | | \\ (_,_) / \\ `-' /\n(_{;}_)| | | | \\ / \\ /\n'(_,_) '---' '---' `---` `'-..-'\n\nThe Artificial Bee Colony (ABC) algorithm is based on the\nintelligent foraging behaviour of honey bee swarm, and was first proposed\nby Karaboga in 2005.\n\n\"\"\"\n\n# ---- IMPORT MODULES\n\ntry:\n\timport numpy as np\nexcept:\n\traise ImportError(\"Numpy module not installed.\")\n\nimport random\nimport time\nimport math\t\nfrom Bio import SeqIO\n#from Hive import DNASequence as dnaSeq\nfrom Hive import HiveMotif\n#from Hive import Utilities\n\nrandom.seed(time.time()) \n\ndef evaluator(vector):\n\t\"\"\"\n\tA n-dimensional Rastrigin's function is defined as:\n\n\t\t\t\t\t\t\tn\n\t\t\tf(x) = 10*n + Sigma { x_i^2 - 10*cos(2*PI*x_i) }\n\t\t\t\t\t\t i=1\n\n\twhere -5.12 <= x_i <= 5.12.\n\n\tThus the global minima of the function being f(x) = 0 at all x_i = 0.\n\n\t\"\"\"\n\n\tvector = np.array(vector)\n\n\treturn 10 * vector.size + sum(vector*vector - 10 * np.cos(2 * np.pi * vector))\n\n\"\"\"\n###################################\n#Codigo de fatorial retirado de https://stackoverflow.com/questions/16325988/factorial-of-a-large-number-in-python\ndef range_prod(lo,hi):\n if lo+1 < hi:\n mid = (hi+lo)//2\n return range_prod(lo,mid) * range_prod(mid+1,hi)\n if lo == hi:\n return lo\n return lo*hi\n\ndef treefactorial(n):\n if n < 2:\n return 1\n return range_prod(1,n)\n #################################### \ndef thresholdConsensus(dna_sequences, consensus):\n\tdna_approvedSequences = []\n\tseqId = 0\n\tfor sequence in dna_sequences:\n\t\tsimilarityRate = 0 #contador de similaridade com o consenso para cada sequencia\n\t\ti = 0\n\t\twhile i < len(consensus):\n\t\t\tif sequence[i] == consensus[i]:\n\t\t\t\tsimilarityRate +=1\n\t\t\ti += 1\n\t\tsimilarityRate = similarityRate/len(consensus) #average\n\t\t#print(\"Seq\",seqId,\"threshold approval% =\",similarityRate)\n\t\tif similarityRate > 0.50: #aprovacao\n\t\t\tdna_approvedSequences.append(sequence)\n\t\tseqId += 1\n\t\n\t#print(\"#Approved :\",len(dna_approvedSequences))\n\treturn dna_approvedSequences\n\t\t\ndef consensusMotif(positionCountMatrix):\n\tconsensus = []\n\ti = 0\n\n\twhile i < len(positionCountMatrix[0]):\n\t\tw_consensus = [] #para evitar bias para determinada base\n\t\twindow = [positionCountMatrix[0][i],positionCountMatrix[1][i],positionCountMatrix[2][i],positionCountMatrix[3][i]]\n\t\tif window[0] >= window[1] and window[0] >= window[2] and window[0] >= window[3]:\n\t\t\tw_consensus.append('A')\n\t\tif window[1] >= window[0] and window[1] >= window[2] and window[1] >= window[3]:\n\t\t\tw_consensus.append('C')\n\t\tif window[2] >= window[0] and window[2] >= window[1] and window[2] >= window[3]:\n\t\t\tw_consensus.append('G')\n\t\tif window[3] >= window[0] and window[3] >= window[1] and window[3] >= window[2]:\n\t\t\tw_consensus.append('T')\n\t\t\n\t\tconsensus.append(random.choice(w_consensus)) # um dos empatantes eh escolhido com probabilidades equivalentes\n\t\t\n\t\t#print (consensus[i], end = '')\n\t\ti += 1\n\t#print('\\n')\t\t\n\treturn consensus\n\ndef printDNAMatrix(DNAMatrix):\n\tnames = ['A','C','G','T']\n\ti = 0\n\tfor baseVector in DNAMatrix:\n\t\tprint(\"#\",names[i],\":\",end=\" \")\n\t\tfor base in baseVector:\n\t\t\tprint(format(round(base,3),'.2f'), end=\" \")\n\t\tprint('\\n')\n\t\ti += 1\n\treturn\n\n\ndef positionCountMatrix(dna_subsequences): \n #col_1 col_2 ... col_n\n #Linha A\n #Linha C\n #Linha G\n #Linha T\n #o tamanho de todas as sequencias eh igual\n sequenceSize = len(dna_subsequences[0])\n #print(dna_subsequences)\n positionCountMatrix = np.zeros([4,sequenceSize],dtype=int)\n #print(len(dna_subsequences))\n for j in range(len(dna_subsequences)):\n sequence = dna_subsequences[j]\n for i in range(len(sequence)):\n if sequence[i] == 'A':\n positionCountMatrix[0][i] += 1\n elif sequence[i] == 'C':\n positionCountMatrix[1][i] += 1\n elif sequence[i] == 'G':\n positionCountMatrix[2][i] += 1\n elif sequence[i] == 'T':\n positionCountMatrix[3][i] += 1\n \n #print ('PCM')\n #printDNAMatrix(positionCountMatrix)\n return positionCountMatrix\n\n\ndef sequenceFromSolution(dna_sequences, solutionVector):\n dna_solutionInstance = []\n dna_subSequences = []\n sequenceSize = len(dna_sequences[0])\n lowerLimit = 7\n higherLimit = 64\n if sequenceSize < higherLimit: #ajusta o tamanho da sequencia para um menor valor\n higherLimit = sequenceSize\n\n if sequenceSize >= lowerLimit: #uma sequencia nao eh considerada como motivo se for menor que 7\n motifSize = solutionVector[0] #tamanho do motivo\n i = 1\n #motifSize = 7 #tamanho do motivo\n print(\"candidate size = \",motifSize)\n \n for sequence in dna_sequences:\n motifStart = solutionVector[i] #-1 pois o vetor comeca no 0\n #print(\"start = \",motifStart)\n subSequence = sequence[motifStart:motifStart+motifSize]\n dna_subSequences.append(subSequence)\n #print(subSequence)\n i += 1\n else:\n #print(\"Sequencias de tamanho insuficiente:\",sequenceSize,\"<\",lowerLimit)\n\n return dna_subSequences\n\n\n\ndef readFasta(filePath):\n\t\n\tdna_sequences = []\n\tfasta_sequences = SeqIO.parse(open(filePath),'fasta')\n\ti = 0\n\tfor fasta in fasta_sequences:\n\t\tname,sequence = fasta.id,str(fasta.seq)\n\t\tdna_sequences.append(sequence)\n\t\tprint(\">Seq\",i,dna_sequences[len(dna_sequences)-1])\n\t\ti += 1\n\treturn dna_sequences\n\t\ndef randomSubSequences(dna_sequences):\n dna_solutionInstance = []\n dna_subSequences = []\n sequenceSize = len(dna_sequences[0])\n lowerLimit = 7\n higherLimit = 64\n if sequenceSize < higherLimit: #ajusta o tamanho da sequencia para um menor valor\n higherLimit = sequenceSize\n\n if sequenceSize >= lowerLimit: #uma sequencia nao eh considerada como motivo se for menor que 7\n motifSize = random.randint(lowerLimit,higherLimit) #tamanho do motivo\n #motifSize = 7 #tamanho do motivo\n print(\"candidate size = \",motifSize)\n dna_solutionInstance.append(motifSize)\n\n for sequence in dna_sequences:\n motifStart = random.randint(0,sequenceSize-motifSize) #-1 pois o vetor comeca no 0\n print(\"start = \",motifStart)\n subSequence = sequence[motifStart:motifStart+motifSize]\n dna_subSequences.append(subSequence)\n print(subSequence)\n dna_solutionInstance.append(motifStart)\n #print(\"Sequencias de tamanho insuficiente:\",sequenceSize,\"<\",lowerLimit)\n\n returnValues = []\n returnValues.append(dna_solutionInstance)\n returnValues.append(dna_subSequences)\n return returnValues\n\ndef printDNAMatrix(DNAMatrix):\n names = ['A','C','G','T']\n i = 0\n for baseVector in DNAMatrix:\n print(\"#\",names[i],\":\",end=\" \")\n for base in baseVector:\n print(base, end=\" \")\n #print(format(round(base,3),'.2f'), end=\" \")\n print('\\n')\n i += 1\n return\ndef positionFrequencyMatrix(positionCountMatrix): #calcula as frequencias\n i = 0\n sumWindow = 0.0\n window = []\n sequenceSize = len(positionCountMatrix[0])\n positionFrequencyMatrix = np.zeros([4,sequenceSize]) #cria uma matriz de floats\n for i in range(sequenceSize):\n window = [positionCountMatrix[0][i],positionCountMatrix[1][i],positionCountMatrix[2][i],positionCountMatrix[3][i]]\n sumWindow = window[0] + window[1] + window[2] + window[3] #somatorio de nucleotideos na posicao i\n positionFrequencyMatrix[0][i] = float(window[0]/sumWindow)\n positionFrequencyMatrix[1][i] = float(window[1]/sumWindow)\n positionFrequencyMatrix[2][i] = float(window[2]/sumWindow)\n positionFrequencyMatrix[3][i] = float(window[3]/sumWindow)\n #print ('PFM')\n #printDNAMatrix(positionFrequencyMatrix)\n return positionFrequencyMatrix\n\ndef similarity(positionFrequencyMatrix):\n\ti = 0 \n\tsequenceSize = len(positionFrequencyMatrix[0])\n\tmaxSum = 0.0\n\twhile i < sequenceSize:\n\t\twindow = [positionFrequencyMatrix[0][i],positionFrequencyMatrix[1][i],positionFrequencyMatrix[2][i],positionFrequencyMatrix[3][i]]\n\t\tmaxSum += max(window)\n\t\ti += 1\n\n\tsimilarity = maxSum/sequenceSize\n\treturn similarity\n\ndef complexity(motif):\n\tmotifSize = len(motif)\n\n\tnumA = 0\n\tnumC = 0\n\tnumG = 0\n\tnumT = 0\n\tmotifSizeFactorial = treefactorial(motifSize)\n\ti = 0\n\twhile i < motifSize: #conta a quantidade de cada base\n\t\tif motif[i] == 'A':\n\t\t\tnumA += 1\n\t\t\t\t\n\t\telif motif[i] == 'C':\n\t\t\tnumC += 1\n\n\t\telif motif[i] == 'G':\n\t\t\tnumG += 1\n\n\t\telif motif[i] == 'T':\n\t\t\tnumT += 1\n\t\ti += 1\n\n\tproductBasesFactorial = treefactorial(numA)*treefactorial(numC)*treefactorial(numG)*treefactorial(numT)\n\t\t\t\t\t\t\t#produtorio do fatorial do numero de cada base\n\n\tcomplexity = math.log(motifSizeFactorial/productBasesFactorial,4) #logaritmo base 4 (numero de bases) \n\treturn complexity\n\ndef isBiased(support,totalSequences):\n\tif totalSequences <= 4 :#minimo dado pelos autores (Alvarez)\n\t\tif support >= 2 :\n\t\t\tisBiased = False\n\t\telse :\n\t\t\tisBiased = True\n\telse :\n\t\tif support >=3 :\n\t\t\tisBiased = False\n\t\telse :\n\t\t\tisBiased = True\n\n\treturn isBiased\n\t\n\"\"\"\n\n\ndef readFasta(filePath):\n\t\n\tdna_sequences = []\n\tfasta_sequences = SeqIO.parse(open(filePath),'fasta')\n\ti = 0\n\tfor fasta in fasta_sequences:\n\t\tname,sequence = fasta.id,str(fasta.seq)\n\t\tdna_sequences.append(sequence)\n\t\t#print(\">Seq\",i,dna_sequences[len(dna_sequences)-1])\n\t\ti += 1\n\treturn dna_sequences\n\n\ndef sequenceFromSolution(dna_sequences, solutionVector):\n\tdna_solutionInstance = []\n\tdna_subSequences = []\n\tsequenceSize = len(dna_sequences[0])\n\tlowerLimit = 7\n\thigherLimit = 64\n\tif sequenceSize < higherLimit: #ajusta o tamanho da sequencia para um menor valor\n\t\thigherLimit = sequenceSize\n\n\tif sequenceSize >= lowerLimit: #uma sequencia nao eh considerada como motivo se for menor que 7\n\t\tmotifSize = solutionVector[0] #tamanho do motivo\n\t\ti = 1\n\t\t#motifSize = 7 #tamanho do motivo\n\t\t#print(\"candidate size = \",motifSize)\n \n\t\tfor sequence in dna_sequences:\n\t\t\tmotifStart = solutionVector[i] #-1 pois o vetor comeca no 0\n\t\t\tprint(\"start = \",motifStart)\n\t\t\tsubSequence = sequence[motifStart:motifStart+motifSize]\n\t\t\tdna_subSequences.append(subSequence)\n\t\t\tprint(subSequence)\n\t\t\ti += 1\n\telse:\n\t\tprint(\"Sequencias de tamanho insuficiente:\",sequenceSize,\"<\",lowerLimit)\n\n\treturn dna_subSequences\n\n\ndef run():\n ###############readFasta(sys.argv[1]) #1 = path name\n import glob\n import os\n import re\n import sys\n path = \"assets/Real/\"\n objectives = [\"support\",\"similarity\",\"complexity\"]\n for objective in objectives:\n orig_stdout = sys.stdout\n f = open(objective+'.txt', 'w')\n sys.stdout = f\n \n for filename in os.listdir(path): \n if re.match(\".*r\\.fasta\", filename):\n dna_sequences = readFasta(path+filename)\n if(len(dna_sequences) > 1):\n print(\">data set\")\n print(filename[:-6])\n print(\">instances\")\n dnaLength = len(dna_sequences[0])\n model = HiveMotif.BeeHive(lower = [0],\n upper = [64],\n dna_sequences = dna_sequences,\n numb_bees = 200,\n max_itrs = 200,\n max_trials = 20,\n obj = objective)\n cost = model.run()\n #print(\"Fitness Value ABC: {0}\".format(model.best))\n model.bestSolution._printSolution(dna_sequences)\n print(\"Objective =\",objective) \n #break\n \n sys.stdout = orig_stdout\n f.close()\n \n \"\"\"\n dna_sequences = readFasta(\"assets/Real/_testDNA.fasta\")\n dnaLength = len(dna_sequences[0])\n model = HiveMotif.BeeHive(lower = [0],\n upper = [64],\n dna_sequences = dna_sequences,\n numb_bees = 50,\n max_itrs = 100,\n max_trials = 10)\n cost = model.run()\n print(\"Fitness Value ABC: {0}\".format(model.best))\n \"\"\"\n #Utilities.ConvergencePlot(cost)\n \"\"\"\n solutionData = randomSubSequences(dna_sequences)\n solutionInstance = solutionData[0]\n dna_subSequences = solutionData[1]\n print(\"Solution Instance: \",solutionInstance)\n pcm = positionCountMatrix(dna_subSequences)\n consensus = consensusMotif(pcm)\n dna_approvedSequences = thresholdConsensus(dna_subSequences,consensus)\n finalPcm = positionCountMatrix(dna_approvedSequences)\n finalPfm = positionFrequencyMatrix(finalPcm)\n print(\"Motif:\")\n finalMotif = consensusMotif(finalPcm)\n motifSimilarity = similarity(finalPfm)\n motifComplexity = complexity(finalMotif)\n motifSupport= len(dna_approvedSequences)\n biased = isBiased(motifSupport,len(dna_subSequences))\n print(\"Similarity:\",motifSimilarity)\n print(\"Complexity:\",motifComplexity)\n print(\"Support:\",motifSupport)\n print(\"Biased?\",biased)\n \"\"\"\n\nif __name__ == \"__main__\":\n\trun()\n\n\n# ---- END\n","sub_path":"MDP.py","file_name":"MDP.py","file_ext":"py","file_size_in_byte":13409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"559085724","text":"\n\nfrom xai.brain.wordbase.nouns._alley import _ALLEY\n\n#calss header\nclass _ALLEYS(_ALLEY, ):\n\tdef __init__(self,): \n\t\t_ALLEY.__init__(self)\n\t\tself.name = \"ALLEYS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"alley\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_alleys.py","file_name":"_alleys.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"10252264","text":"#-*- coding: utf-8 -*-\n\n# The majority of this module I took from the autofeat lybrary: https://github.com/cod3licious/autofeat\n# which is an automated feature engineer tool.\n# The original code is here: https://github.com/cod3licious/autofeat/blob/master/autofeat/feateng.py\n# I simply made some minor changes in order to fulfill my needs. Like implement fit and transform capabilities.\n\nfrom builtins import str\nimport re\nimport operator as op\nfrom functools import reduce\nfrom itertools import combinations, product\nimport numpy as np\nimport pandas as pd\nimport sympy\nfrom sympy.utilities.lambdify import lambdify\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass NumericalFeatureEngineering(BaseEstimator, TransformerMixin):\n \"\"\"\n Given a DataFrame with original features, perform the feature engineering routine for max_steps.\n It starts with a transformation of the original features (applying log, ^2, sqrt, etc.),\n then in the next step, the features are combined (x+y, x*y, ...), and in further steps, the resulting\n features are again transformed and combinations of the resulting features are computed.\n\n Inputs:\n - start_features: list with column names for X with features that should be considered for expansion\n (default: None --> all columns)\n - max_steps: how many feature engineering steps should be performed. Default is 3, this produces:\n Step 1: transformation of original features\n Step 2: first combination of features\n Step 3: transformation of new features\n (Step 4: combination of old and new features)\n --> with 3 original features, after 4 steps you will already end up with around 200k features!\n - transformations: list of transformations that should be applied; possible elements:\n \"1/\", \"exp\", \"log\", \"abs\", \"sqrt\", \"^2\", \"^3\", \"1+\", \"1-\", \"sin\", \"cos\", \"exp-\", \"2^\"\n (first 7, i.e., up to ^3, are applied by default)\n - verbose: verbosity level (int; default: 0)\n\n Attributes:\n - input_data: original data passed to fit method\n - df_fit_stage: data transformed after fit is applied\n - variables_to_persist: what variables will be includded in the final dataset\n\n Methods:\n - fit: fit the data in order to proceed with the transformation considering the correlation between variables in the training set\n - transform: transform the data based on the results of the fit process.\n \"\"\"\n\n def __init__(self,\n start_features=None,\n max_steps=2,\n transformations=(\"1/\", \"exp\", \"log\", \"abs\", \"sqrt\", \"^2\", \"^3\"),\n verbose=0):\n\n self.start_features = start_features\n self.max_steps = max_steps\n self.transformations = transformations\n self.verbose = verbose\n self.input_data = None\n self.df_fit_stage = None\n self.variables_to_persist = None\n\n def __engineer_features(self, X, y=None, correlation_threshold=0.9):\n \n def colnames2symbols(c, i=0):\n # take a messy column name and transform it to something sympy can handle\n # worst case: i is the number of the features\n # has to be a string\n c = str(c)\n # should not contain non-alphanumeric characters\n c = re.sub(r\"\\W+\", \"\", c)\n if not c:\n c = \"x%03i\" % i\n elif c[0].isdigit():\n c = \"x\" + c\n return c\n\n def ncr(n, r):\n # compute number of combinations for n chose r\n r = min(r, n - r)\n numer = reduce(op.mul, range(n, n - r, -1), 1)\n denom = reduce(op.mul, range(1, r + 1), 1)\n return numer // denom\n\n # initialize the feature pool with columns from the dataframe\n if not self.start_features:\n variables = X.columns\n dont_transform = []\n df_dont_transform = pd.DataFrame()\n else:\n for c in self.start_features:\n if c not in X.columns:\n raise ValueError(\"[feateng] start feature %r not in X.columns\" % c)\n variables = self.start_features\n dont_transform = [c for c in X.columns if c not in X[variables].columns]\n df_dont_transform = pd.DataFrame(X[dont_transform], columns=dont_transform)\n X = X[variables].copy()\n\n feature_pool = {c: sympy.symbols(colnames2symbols(c, i), real=True) for i, c in enumerate(variables)}\n if self.max_steps < 1:\n if self.verbose > 0:\n print(\"[feateng] Warning: no features generated for self.max_steps < 1.\")\n return X, feature_pool\n # get a copy of the dataframe - this is where all the features will be added\n df = pd.DataFrame(X.copy(), dtype=np.float32)\n\n\n def apply_transformations(features_list):\n # feature transformations\n func_transform = {\n \"exp\": lambda x: sympy.exp(x),\n \"exp-\": lambda x: sympy.exp(-x),\n \"log\": lambda x: sympy.log(x),\n \"abs\": lambda x: sympy.Abs(x),\n \"sqrt\": lambda x: sympy.sqrt(x),\n \"sin\": lambda x: sympy.sin(x),\n \"cos\": lambda x: sympy.cos(x),\n \"2^\": lambda x: 2**x,\n \"^2\": lambda x: x**2,\n \"^3\": lambda x: x**3,\n \"1+\": lambda x: 1 + x,\n \"1-\": lambda x: 1 - x,\n \"1/\": lambda x: 1 / x\n }\n \n # conditions on the original features that have to be met to apply the transformation\n func_transform_cond = {\n \"exp\": lambda x: np.all(x < 10),\n \"exp-\": lambda x: np.all(-x < 10),\n \"log\": lambda x: np.all(x >= 0),\n \"abs\": lambda x: np.any(x < 0),\n \"sqrt\": lambda x: np.all(x >= 0),\n \"sin\": lambda x: True,\n \"cos\": lambda x: True,\n \"2^\": lambda x: np.all(x < 50),\n \"^2\": lambda x: np.all(np.abs(x) < 1000000),\n \"^3\": lambda x: np.all(np.abs(x) < 10000),\n \"1+\": lambda x: True,\n \"1-\": lambda x: True,\n \"1/\": lambda x: np.all(x != 0)\n }\n # apply transformations to the features in the given features list\n # modifies global variables df and feature_pool!\n nonlocal df, feature_pool#, units\n # returns a list of new features that were generated\n new_features = []\n uncorr_features = set()\n # store all new features in a preallocated numpy array before adding it to the dataframe\n feat_array = np.zeros((df.shape[0], len(features_list) * len(self.transformations)), dtype=np.float32)\n for i, feat in enumerate(features_list):\n if self.verbose and not i % 100:\n print(\"[feateng] %15i/%15i features transformed\" % (i, len(features_list)), end=\"\\r\")\n for ft in self.transformations:\n # check if transformation is valid for particular feature (i.e. given actual numerical values)\n # (don't compute transformations on categorical features)\n if len(df[feat].unique()) > 2 and func_transform_cond[ft](df[feat]):\n # get the expression (based on the primary features)\n expr = func_transform[ft](feature_pool[feat])\n expr_name = str(expr)\n # we're simplifying expressions, so we might already have that one\n if expr_name not in feature_pool:\n feature_pool[expr_name] = expr\n # create temporary variable expression and apply it to precomputed feature\n t = sympy.symbols(\"t\")\n if expr == \"log\" and np.any(df[feat] < 1):\n expr_temp = func_transform[ft](t + 1)\n else:\n expr_temp = func_transform[ft](t)\n f = lambdify(t, expr_temp)\n new_feat = np.array(f(df[feat].to_numpy()), dtype=np.float32)\n # near 0 variance test - sometimes all that's left is \"e\"\n if np.isfinite(new_feat).all() and np.var(new_feat) > 1e-10:\n corr = abs(np.corrcoef(new_feat, df[feat])[0, 1])\n if corr < 1.:\n feat_array[:, len(new_features)] = new_feat\n new_features.append(expr_name)\n # correlation test: don't include features that are basically the same as the original features\n # but we only filter them out at the end, since they still might help in other steps!\n if corr < correlation_threshold:\n uncorr_features.add(expr_name)\n if self.verbose > 0:\n print(\"[feateng] Generated %i transformed features from %i original features - done.\" % (len(new_features), len(features_list)))\n df = df.join(pd.DataFrame(feat_array[:, :len(new_features)], columns=new_features, index=df.index, dtype=np.float32))\n return new_features, uncorr_features\n\n def get_feature_combinations(feature_tuples):\n # new features as combinations of two other features\n func_combinations = {\n \"x+y\": lambda x, y: x + y,\n \"x*y\": lambda x, y: x * y,\n \"x-y\": lambda x, y: x - y,\n \"y-x\": lambda x, y: y - x\n }\n # get all feature combinations for the given feature tuples\n # modifies global variables df and feature_pool!\n nonlocal df, feature_pool#, units\n # only compute all combinations if there are more transformations applied afterwards\n # additions at the highest level are sorted out later anyways\n if steps == self.max_steps:\n combinations = [\"x*y\"]\n else:\n combinations = list(func_combinations.keys())\n # returns a list of new features that were generated\n new_features = []\n uncorr_features = set()\n # store all new features in a preallocated numpy array before adding it to the dataframe\n feat_array = np.zeros((df.shape[0], len(feature_tuples) * len(combinations)), dtype=np.float32)\n for i, (feat1, feat2) in enumerate(feature_tuples):\n if self.verbose and not i % 100:\n print(\"[feateng] %15i/%15i feature tuples combined\" % (i, len(feature_tuples)), end=\"\\r\")\n for fc in combinations:\n expr = func_combinations[fc](feature_pool[feat1], feature_pool[feat2])\n expr_name = str(expr)\n if expr_name not in feature_pool:\n feature_pool[expr_name] = expr\n # create temporary variable expression to apply it to precomputed features\n s, t = sympy.symbols(\"s t\")\n expr_temp = func_combinations[fc](s, t)\n f = lambdify((s, t), expr_temp)\n new_feat = np.array(f(df[feat1].to_numpy(), df[feat2].to_numpy()), dtype=np.float32)\n # near 0 variance test - sometimes all that's left is \"e\"\n if np.isfinite(new_feat).all() and np.var(new_feat) > 1e-10:\n corr = max(abs(np.corrcoef(new_feat, df[feat1])[0, 1]), abs(np.corrcoef(new_feat, df[feat2])[0, 1]))\n if corr < 1.:\n feat_array[:, len(new_features)] = new_feat\n new_features.append(expr_name)\n # correlation test: don't include features that are basically the same as the original features\n # but we only filter them out at the end, since they still might help in other steps!\n if corr < correlation_threshold:\n uncorr_features.add(expr_name)\n if self.verbose > 0:\n print(\"[feateng] Generated %i feature combinations from %i original feature tuples - done.\" % (len(new_features), len(feature_tuples)))\n df = df.join(pd.DataFrame(feat_array[:, :len(new_features)], columns=new_features, index=df.index, dtype=np.float32))\n return new_features, uncorr_features\n\n # get transformations of initial features\n steps = 1\n if self.verbose > 0:\n print(\"[feateng] Step 1: transformation of original features\")\n original_features = list(feature_pool.keys())\n uncorr_features = set(feature_pool.keys())\n temp_new, temp_uncorr = apply_transformations(original_features)\n original_features.extend(temp_new)\n uncorr_features.update(temp_uncorr)\n steps += 1\n # get combinations of first feature set\n if steps <= self.max_steps:\n if self.verbose > 0:\n print(\"[feateng] Step 2: first combination of features\")\n new_features, temp_uncorr = get_feature_combinations(list(combinations(original_features, 2)))\n uncorr_features.update(temp_uncorr)\n steps += 1\n while steps <= self.max_steps:\n # apply transformations on these new features\n if self.verbose > 0:\n print(\"[feateng] Step %i: transformation of new features\" % steps)\n temp_new, temp_uncorr = apply_transformations(new_features)\n new_features.extend(temp_new)\n uncorr_features.update(temp_uncorr)\n steps += 1\n # get combinations of old and new features\n if steps <= self.max_steps:\n if self.verbose > 0:\n print(\"[feateng] Step %i: combining old and new features\" % steps)\n new_new_features, temp_uncorr = get_feature_combinations(list(product(original_features, new_features)))\n uncorr_features.update(temp_uncorr)\n steps += 1\n # and combinations of new features within themselves\n if steps <= self.max_steps:\n if self.verbose > 0:\n print(\"[feateng] Step %i: combining new features\" % steps)\n temp_new, temp_uncorr = get_feature_combinations(list(combinations(new_features, 2)))\n new_new_features.extend(temp_new)\n uncorr_features.update(temp_uncorr)\n steps += 1\n # update old and new features and repeat\n original_features.extend(new_features)\n new_features = new_new_features\n\n # sort out all features that are just additions on the highest level or correlated with more basic features\n if self.verbose > 0:\n print(\"[feateng] Generated altogether %i new features in %i steps\" % (len(feature_pool) - len(variables), self.max_steps))\n print(\"[feateng] Removing correlated features, as well as additions at the highest level\")\n feature_pool = {c: feature_pool[c] for c in feature_pool if c in uncorr_features and not feature_pool[c].func == sympy.add.Add}\n cols = [c for c in list(df.columns) if (c in feature_pool) and (c not in X.columns)] # categorical cols not in feature_pool\n if cols:\n # check for correlated features again; this time with the start features\n corrs = dict(zip(cols, np.max(np.abs(np.dot(StandardScaler().fit_transform(df[cols]).T, StandardScaler().fit_transform(X))/X.shape[0]), axis=1)))\n cols = [c for c in cols if corrs[c] < correlation_threshold]\n\n # correlation between original variables\n cor_matrix = X.astype('float64').corr().abs() # corelation matrix\n upper_tri = cor_matrix.where(np.triu(np.ones(cor_matrix.shape),k=1).astype(np.bool)) # get upper triangle part\n to_drop = [c for c in upper_tri.columns if any(upper_tri[c] > correlation_threshold)]\n keep = [c for c in upper_tri.columns if c not in to_drop]\n else:\n keep = []\n to_drop = []\n\n selected = keep + cols if keep else list(variables) + cols\n if self.verbose > 0:\n print(\"[feateng] Generated a total of %i additional features\" % (len(feature_pool) - len(variables)))\n print(\"[feateng] Drop a total of %i features %s from the original set\" % (len(to_drop), to_drop))\n \n final_df = df[selected].join(df_dont_transform)\n\n return final_df\n\n def fit(self, X, y=None, correlation_threshold=0.9):\n '''\n Inputs:\n - X: pandas DataFrame with original features in columns\n - y: No need to be passed. It´s here only for compatibility with sklearn pipelines\n - correlation_threshold: threshold to be choosed for eliminating correlated features\n '''\n self.input_data = X\n self.df_fit_stage = self.__engineer_features(X, y=None, correlation_threshold=correlation_threshold)\n self.variables_to_persist = self.df_fit_stage.columns\n\n return self\n\n def transform(self, X):\n '''\n Inputs:\n - X: pandas DataFrame with original features in columns\n '''\n # check if data to be tranaformed was used in the fit process, so there´s no reason to reapet it.\n if (list(X.index) == list(self.input_data.index)) and all(X.columns == self.input_data.columns) and not (len(X.compare(self.input_data)) > 1):\n return self.df_fit_stage\n else:\n df_transform_stage = self.__engineer_features(X, y=None, correlation_threshold=1)\n return df_transform_stage[self.variables_to_persist]\n","sub_path":"numerical_feature_engineering.py","file_name":"numerical_feature_engineering.py","file_ext":"py","file_size_in_byte":18268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"638837945","text":"#!/usr/bin/env python3\r\n\r\nimport os\r\nimport time\r\nimport frida\r\nimport logging\r\nimport platform\r\nimport subprocess\r\nfrom Helpers.Scanner import Scan\r\n\r\nlogging.basicConfig(\r\n format='%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s',\r\n datefmt='%Y-%m-%d %I:%M:%S %p',\r\n level=logging.DEBUG,\r\n)\r\n\r\nlogging.addLevelName( logging.ERROR, \"\\033[1;31m%s\\033[1;0m\" % logging.getLevelName(logging.ERROR))\r\nlogging.addLevelName( logging.INFO, \"\\033[1;33m%s\\033[1;0m\" % logging.getLevelName(logging.INFO))\r\nlogging.addLevelName( logging.DEBUG, \"\\033[1;34m%s\\033[1;0m\" % logging.getLevelName(logging.DEBUG))\r\n\r\nif platform.system() == \"Windows\":\r\n\tadb_location = os.path.dirname(os.path.realpath(__file__))+\"\\\\Tools\\\\adb.exe\"\r\n\tfastboot_location = os.path.dirname(os.path.realpath(__file__))+\"\\\\Tools\\\\fastboot.exe\"\r\nelse:\r\n\tadb_location = \"adb\"\r\n\tfastboot_location = \"fastboot\"\r\n\r\noutput = subprocess.run(adb_location+' devices', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.decode('utf-8')\r\noutput = output.split(\"\\n\")\r\nfor text in output:\r\n\tif text != \"\" and text != \"\\r\":\r\n\t\tlogging.info(text)\r\nprint()\r\ntry:\r\n\tdevice = frida.get_usb_device()\r\nexcept frida.InvalidArgumentError as err:\r\n\tif \"device not found\" in str(err):\r\n\t\tlogging.error(\"No devices. Please connect your Android device.\")\r\n\telse:\r\n\t\tlogging.error(err)\r\n\texit()\r\nscanner = Scan(device.name)\r\nlogging.info(f'Connected to {device.name}')\r\nlogging.info('Do you want to launch DRM content on Chrome (y/n)?')\r\nchoice = input(\"\")\r\nif choice.lower() == \"y\":\r\n\toutput = subprocess.run(adb_location+' shell am start -n com.android.chrome/org.chromium.chrome.browser.ChromeTabbedActivity -d \"https://bitmovin.com/demos/drm\"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.decode('utf-8')\r\n\toutput = output.split(\"\\n\")\r\n\tfor text in output:\r\n\t\tif text != \"\" and text != \"\\r\":\r\n\t\t\tlogging.debug(text)\r\nlogging.info('Scanning all processes for the following libraries')\r\ntry:\r\n\tfor process in device.enumerate_processes():\r\n\t\tlogging.debug(process)\r\n\t\tif 'drm' in process.name:\r\n\t\t\tlibraries = scanner.find_widevine_process(device, process.name)\r\n\t\t\tif libraries:\r\n\t\t\t\tfor library in libraries:\r\n\t\t\t\t\tscanner.hook_to_process(device, process.name, library)\r\nexcept frida.ServerNotRunningError as err:\r\n\tif \"unable to connect to remote frida-server: closed\" in str(err):\r\n\t\tlogging.error(\"Frida Server is not running on the Android Device.\")\r\n\telse:\r\n\t\tlogging.error(err)\r\n\texit()\r\nlogging.info('Hooks completed')\r\nwhile True:\r\n time.sleep(1000)\r\n","sub_path":"dump_keys.py","file_name":"dump_keys.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"299880165","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nelectron_mass = 9.11e-31 #[kg]\nelectron_charge = -1.6e-19 #[C]\n\nelectric_field = np.array([-5.0, 0, 0]) #[N/C]\n\ntotal_time = 1e-6\n\nforce = electron_charge*electric_field\nacceleration = force/electron_mass\n\ndef integrate(dt):\n total_time_steps = int(total_time/dt)\n\n positions = np.zeros((3, total_time_steps))\n velocities = np.zeros((3, total_time_steps))\n\n for t in range(total_time_steps-1):\n velocities[:, t+1] = velocities[:, t] + acceleration*dt\n positions[:, t+1] = positions[:, t] + velocities[:, t+1]*dt\n\n return positions\n\ndef plot3d(positions):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection=\"3d\")\n\n ax.set_xlabel(\"x[m]\")\n ax.set_ylabel(\"y[m]\")\n ax.set_zlabel(\"z[m]\")\n\n ax.plot(positions[0, :], positions[1, :], positions[2, :])\n\n ax.legend([\"dt = 1ns\", \"dt = 100ns\"])\n\n plt.show()\n\ndef plot2d(positions):\n #Numerical\n time = np.linspace(0, total_time-total_time/len(positions[0, :]), len(positions[0, :]))\n plt.plot(time, positions[0, :])\n\n #Analytical\n plt.plot(time, 0.5*acceleration[0]*time**2)\n\n plt.xlabel(\"time[s]\")\n plt.ylabel(\"position[m]\")\n\n plt.legend([\"Numerical position\", \"Analytical position\"])\n plt.show()\n\n\n\n\nplot2d(integrate(1e-7))\n","sub_path":"Oblig2/oppg1.py","file_name":"oppg1.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"486834500","text":"import json\nimport requests\nimport flow.utils.commons as commons\nfrom flow.buildconfig import BuildConfig\nfrom flow.utils.commons import Object\nimport os\n\nclass ServiceNow():\n\n clazz = 'ServiceNow'\n servicenow_url = None\n config = BuildConfig\n\n def __init__(self, config_override=None):\n method = '__init__'\n commons.print_msg(ServiceNow.clazz, method, 'begin')\n\n if config_override is not None:\n self.config = config_override\n\n try:\n # below line is to maintain backwards compatibility since stanza was renamed\n servicenow_json_config = self.config.json_config['servicenow'] if 'servicenow' in self.config.json_config else \\\n self.config.json_config['servicemanagement'][\"servicenow\"]\n except KeyError as e:\n commons.print_msg(ServiceNow.clazz,\n method,\n \"The build config associated with servicemanagement is missing key {}\".format(str(e)), 'ERROR')\n exit(1)\n\n # Check for servicenow url first in buildConfig, second try settings.ini\n try:\n # noinspection PyUnboundLocalVariable\n ServiceNow.servicenow_url = servicenow_json_config['url']\n except:\n if self.config.settings.has_section('servicenow') and self.config.settings.has_option('servicenow', 'url'):\n ServiceNow.servicenow_url = self.config.settings.get('servicenow', 'url')\n else:\n commons.print_msg(ServiceNow.clazz, method, 'No service now url found in buildConfig or settings.ini.', 'ERROR')\n exit(1)\n\n def create_chg(self, story_details = None):\n servicenow_create_chg_url = ServiceNow.servicenow_url + '/api/now/table/change_request'\n\n cr = Object()\n cr.category = \"Software\"\n cr.description = self._format_release_notes(story_details)\n cr.short_description = \"Deployment of {app}-{version} to {env}\".format(app=BuildConfig.project_name, version=BuildConfig.version_number, env=os.getenv('NEXT_ENVIRONMENT'))\n cr.assignment_group = 'CAB Approval'\n cr.work_start = '2018-08-10 23:59:59'\n cr.work_end = '2018-08-11 23:59:59'\n cr.cmdb_ci = 'Cloud Foundry'\n cr.start_date = '2018-08-10 23:59:59'\n cr.end_date = '2018-08-11 23:59:59'\n cr.reason = 'Continuous Deployment'\n # headers = {'Content-type': 'application/json', 'Accept': 'application/json',\n # 'Authorization': \"Bearer {}\".format(os.getenv('SERVICENOW_TOKEN'))}\n\n headers = {'Content-type': 'application/json', 'Accept': 'application/json'}\n\n print(servicenow_create_chg_url)\n resp = requests.post(servicenow_create_chg_url, cr.to_JSON(), headers=headers, auth=(os.getenv('SERVICENOW_USER'), os.getenv('SERVICENOW_PWD')),)\n resp_obj = json.loads(resp.text)\n print(resp)\n print(resp.text)\n print(resp_obj[\"result\"][\"number\"])\n\n def _format_release_notes(self, story_details):\n\n formatted_release_notes = None\n\n if story_details is not None and isinstance(story_details, list) and len(story_details) > 0:\n\n for i, story in enumerate(story_details):\n if story is not None:\n\n if formatted_release_notes is None:\n formatted_release_notes = \"======================================RELEASE NOTES======================================\"\n formatted_release_notes = formatted_release_notes + \"\\r\\n=========================================from Jira=========================================\"\n\n formatted_release_notes = \"{existing} \\r\\n {counter}. ({type}) {name} => {description}\".format(existing=formatted_release_notes, counter=i+1, type=story.story_type, name=story.name, description=story.description)\n\n if formatted_release_notes is None:\n formatted_release_notes = 'No Release Notes'\n\n return formatted_release_notes\n","sub_path":"flow/servicemanagement/servicenow/service_now.py","file_name":"service_now.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124282809","text":"from bs4 import BeautifulSoup\r\n\r\nhtml = \"\"\"\r\n\r\n
\r\n

강의목록

\r\n
    \r\n
  • Java
  • \r\n
  • Python
  • \r\n
  • Python machine learning
  • \r\n
  • Android
  • \r\n
\r\n
\r\n\r\n\"\"\"\r\n\r\nbsObj = BeautifulSoup(html, \"html.parser\")\r\n#select는 list값을 배열하므로 반환한 값에 .string을 할 수 없다.\r\nh1 = bsObj.select(\"div#main > h1\")\r\nprint('h1', h1)\r\n\r\nh1 = bsObj.select_one(\"div#main > h1\")\r\nprint('h1', h1)\r\n#select_one은 하나의 값을 반환하므로 .string으로 문자열값을 받을 수 있다.\r\nprint(h1.string)\r\n\r\nlist_li = bsObj.select(\"div#main > ul.lecs > li\")\r\n\r\nfor li in list_li:\r\n print(li.string)\r\n \r\n","sub_path":"bs04_css_selector.py","file_name":"bs04_css_selector.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"626957671","text":"def load_sequences(filename):\n list_of_seqs = []\n \n fp = open(filename)\n for count, line in enumerate(fp):\n if (count % 4) == 1:\n seq = line.strip()\n list_of_seqs.append(seq)\n return list_of_seqs\n\ndef count_Ns(seq):\n # only valid input should be strings of ACGTN\n n_bases = len(seq)\n # Fixed to handle lower-case\n # 1) convert seq to be upper case\n # 2) count lower case 'n's as well\n\n seq = seq.upper() # handle lower case input\n \n \n good_bases = seq.count('A') + seq.count('C') + seq.count('G') + \\\n seq.count('T') + seq.count('N')\n \n # Error handling\n if len(seq) != good_bases:\n raise ValueError(\"error, sequence contains non-DNA\")\n \n \n n_ns = seq.upper().count('N')\n return (n_bases, n_ns)\n\n\n\n\ndef count_Ns_case(seq):\n n_bases = len(seq)\n n_ns = seq.upper().count('N')\n return (n_bases, n_ns)\n\n## Testing & Automated Tests\n\n# Create an initial test function\ndef test_count_ns():\n seq = \"NATGC\"\n nb, nn = count_Ns(seq)\n \n assert nb==5, \"nb should be 5\"\n assert nn==1\n\n \n# Create a new test function: lower case input\ndef test_count_ns_2():\n seq = \"nATGC\"\n nb, nn = count_Ns_case(seq)\n \n assert nb==5, \"nb should be 5\"\n assert nn==1\n\n \ndef test_bad_input():\n print('running test_count_ns')\n seq = \"nATGCmy favorite sequence\"\n \n # Runs correctly if there is an error\n # Throws an error if the input is correct \n try:\n nb, nn = count_Ns(seq)\n assert False, \"count_Ns should break on this input\"\n except ValueError:\n pass\n\n \n\n# test_count_ns() # This runs every time jfaUtils.py is IMPORTED\n\n# This fixes it so that when jfaUtils.py is run as a script \n# at the command line\n\n","sub_path":"jfaUtils.py","file_name":"jfaUtils.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"115367073","text":"import numpy as np\nfrom personal_utilities.arc_length_reparametrization import arc_length_parameterize\nfrom personal_utilities.nufft_interpolation import nufft_interpolation1d\nfrom ipde.embedded_boundary import EmbeddedBoundary\nfrom ipde.ebdy_collection import EmbeddedBoundaryCollection, BoundaryFunction\nfrom ipde.embedded_function import EmbeddedFunction\nfrom fast_interp import interp1d\n\nclass SecondOrder_Advector(object):\n \"\"\"\n General class for semi-lagrangian advection\n \"\"\"\n def __init__(self, ebdyc, u, v, old_advector, filter_fraction=0.9):\n self.ebdyc = ebdyc\n self.u = u\n self.v = v\n self.ebdyc_old = old_advector.ebdyc\n ### CHECK: DO ALL OF THESE COPIES REALLY NEED TO BE MADE?\n ### NOW THAT I'VE FIXED THE LEAK, SHOULD CHECK...\n self.uo = old_advector.u.copy()\n self.vo = old_advector.v.copy()\n self.ux, self.uy = self.ebdyc.gradient(self.u)\n self.vx, self.vy = self.ebdyc.gradient(self.v)\n self.uxo = old_advector.ux.copy()\n self.uyo = old_advector.uy.copy()\n self.vxo = old_advector.vx.copy()\n self.vyo = old_advector.vy.copy()\n self.filter_fraction = filter_fraction\n del old_advector\n def generate(self, bxs, bys, dt, fixed_grid=False):\n ebdyc = self.ebdyc\n ebdyc_old = self.ebdyc_old\n u, v = self.u, self.v\n uo, vo = self.uo, self.vo\n ux, uy, vx, vy = self.ux, self.uy, self.vx, self.vy\n uxo, uyo, vxo, vyo = self.uxo, self.uyo, self.vxo, self.vyo\n\n # interpolate the velocity\n ubs = ebdyc.interpolate_radial_to_boundary(u)\n vbs = ebdyc.interpolate_radial_to_boundary(v)\n\n # move all boundarys; generate new embedded boundaries\n new_ebdys = []\n for ind, ebdy in enumerate(self.ebdyc):\n # generate the new embedded boundary\n # bx, by, new_t = arc_length_parameterize(bxs[ind], bys[ind], filter_fraction=self.filter_fraction, return_t=True)\n # new_ebdy = ebdy.regenerate(bx, by)\n new_ebdy = ebdy.regenerate(bxs[ind], bys[ind])\n new_ebdys.append(new_ebdy)\n\n\n # # interpolate the velocity\n # ub = ubs.bdy_value_list[ind]\n # vb = vbs.bdy_value_list[ind]\n # ubo_new_parm = self.ubos[ind]\n # vbo_new_parm = self.vbos[ind]\n # # move the boundary with Forward Euler\n # bx = ebdy.bdy.x + 0.5*dt*(3*ub - ubo_new_parm)\n # by = ebdy.bdy.y + 0.5*dt*(3*vb - vbo_new_parm)\n # # repararmetrize the boundary\n # bx, by, new_t = arc_length_parameterize(bx, by, filter_fraction=self.filter_fraction, return_t=True)\n # # move these boundary values for velocity to the new parametrization\n # self.reparmed_ubs.append(nufft_interpolation1d(new_t, np.fft.fft(ub)))\n # self.reparmed_vbs.append(nufft_interpolation1d(new_t, np.fft.fft(vb)))\n # # generate the new embedded boundary\n # new_ebdy = ebdy.regenerate(bx, by)\n # new_ebdys.append(new_ebdy)\n\n new_ebdyc = EmbeddedBoundaryCollection(new_ebdys)\n # get dnager zone distance\n umax = np.sqrt(u*u + v*v).max()\n ddd = 2*umax*dt\n # raise an exception if danger zone thicker than radial width\n if ddd > new_ebdyc[0].radial_width:\n raise Exception('Velocity is so fast that one timestep oversteps safety zones; reduce timestep.')\n # register the grid...\n if fixed_grid:\n new_ebdyc.register_grid(ebdyc.grid, danger_zone_distance=ddd)\n else:\n new_ebdyc.generate_grid(danger_zone_distance=ddd)\n\n # let's get the points that need to be interpolated to\n aap = new_ebdyc.pnar\n AP_key = ebdyc.register_points(aap.x, aap.y, dzl=new_ebdyc.danger_zone_list, gil=new_ebdyc.guess_ind_list)\n OAP_key = ebdyc_old.register_points(aap.x, aap.y, dzl=new_ebdyc.danger_zone_list, gil=new_ebdyc.guess_ind_list)\n\n # now we need to interpolate onto things\n AEP = ebdyc.registered_partitions[AP_key]\n OAEP = ebdyc_old.registered_partitions[OAP_key]\n\n # get departure points\n xd_all = np.zeros(aap.N)\n yd_all = np.zeros(aap.N)\n xD_all = np.zeros(aap.N)\n yD_all = np.zeros(aap.N)\n\n # advect those in the annulus\n c1n, c2n, c3n = AEP.get_Ns()\n oc1n, oc2n, oc3n = OAEP.get_Ns()\n # category 1 and 2\n c1_2 = AEP.zone1_or_2\n oc1_2 = OAEP.zone1_or_2\n fc12 = np.logical_and(c1_2, oc1_2)\n fc12n = np.sum(fc12)\n\n # category 1 and 2\n # NOTE: THESE INTERPOLATIONS CAN BE MADE FASTER BY EXPLOITING SHARED\n # GRIDPOINTS IF THAT IS ENFORCED IN GRID GENERATION\n # THIS IS NOT EXPLOITED, FOR THE TIME BEING\n uxh = ebdyc.interpolate_to_points(ux, aap.x, aap.y)\n uyh = ebdyc.interpolate_to_points(uy, aap.x, aap.y)\n vxh = ebdyc.interpolate_to_points(vx, aap.x, aap.y)\n vyh = ebdyc.interpolate_to_points(vy, aap.x, aap.y)\n uh = ebdyc.interpolate_to_points(u, aap.x, aap.y)\n vh = ebdyc.interpolate_to_points(v, aap.x, aap.y)\n\n uxoh = ebdyc_old.interpolate_to_points(uxo, aap.x, aap.y)\n uyoh = ebdyc_old.interpolate_to_points(uyo, aap.x, aap.y)\n vxoh = ebdyc_old.interpolate_to_points(vxo, aap.x, aap.y)\n vyoh = ebdyc_old.interpolate_to_points(vyo, aap.x, aap.y)\n uoh = ebdyc_old.interpolate_to_points(uo, aap.x, aap.y)\n voh = ebdyc_old.interpolate_to_points(vo, aap.x, aap.y)\n\n SLM = np.zeros([fc12n,] + [4,4], dtype=float)\n SLR = np.zeros([fc12n,] + [4,], dtype=float)\n\n # solve for departure points\n SLM[:,0,0] = uxh[fc12]\n SLM[:,0,1] = uyh[fc12]\n SLM[:,0,2] = 0.5/dt\n SLM[:,0,3] = 0.0\n SLM[:,1,0] = vxh[fc12]\n SLM[:,1,1] = vyh[fc12]\n SLM[:,1,2] = 0.0\n SLM[:,1,3] = 0.5/dt\n SLM[:,2,0] = 2.0/dt + 3*uxh[fc12]\n SLM[:,2,1] = 3*uyh[fc12]\n SLM[:,2,2] = -uxoh[fc12]\n SLM[:,2,3] = -uyoh[fc12]\n SLM[:,3,0] = 3*vxh[fc12]\n SLM[:,3,1] = 2.0/dt + 3*vyh[fc12]\n SLM[:,3,2] = -vxoh[fc12]\n SLM[:,3,3] = -vyoh[fc12]\n SLR[:,0] = uh[fc12]\n SLR[:,1] = vh[fc12]\n SLR[:,2] = 3*uh[fc12] - uoh[fc12]\n SLR[:,3] = 3*vh[fc12] - voh[fc12]\n OUT = np.linalg.solve(SLM, SLR)\n dx, dy, Dx, Dy = OUT[:,0], OUT[:,1], OUT[:,2], OUT[:,3]\n xd, yd = aap.x[fc12] - dx, aap.y[fc12] - dy\n xD, yD = aap.x[fc12] - Dx, aap.y[fc12] - Dy\n xd_all[fc12] = xd\n yd_all[fc12] = yd\n xD_all[fc12] = xD\n yD_all[fc12] = yD\n\n # categroy 3... this is the tricky one\n fc3n = aap.N - fc12n\n # print('Number of points in category 3 is:', fc3n)\n if fc3n > 0:\n for ind, (ebdy, ebdy_old) in enumerate(zip(ebdyc, ebdyc_old)):\n ub = ubs[ind]\n vb = vbs[ind]\n\n c3l = AEP.zone3l[ind]\n oc3l = OAEP.zone3l[ind]\n fc3l = np.unique(np.concatenate([c3l, oc3l]))\n th = ebdy.bdy.dt\n tk = ebdy.bdy.k\n def d1_der(f):\n return np.fft.ifft(np.fft.fft(f)*tk*1j).real\n interp = lambda f: interp1d(0, 2*np.pi, th, f, k=3, p=True)\n bx_interp = interp(ebdy.bdy.x)\n by_interp = interp(ebdy.bdy.y)\n bxs_interp = interp(d1_der(ebdy.bdy.x))\n bys_interp = interp(d1_der(ebdy.bdy.y))\n nx_interp = interp(ebdy.bdy.normal_x)\n ny_interp = interp(ebdy.bdy.normal_y)\n nxs_interp = interp(d1_der(ebdy.bdy.normal_x))\n nys_interp = interp(d1_der(ebdy.bdy.normal_y))\n urb = ebdy.interpolate_radial_to_boundary_normal_derivative(u[0])\n vrb = ebdy.interpolate_radial_to_boundary_normal_derivative(v[0])\n urrb = ebdy.interpolate_radial_to_boundary_normal_derivative2(u[0])\n vrrb = ebdy.interpolate_radial_to_boundary_normal_derivative2(v[0])\n ub_interp = interp(ub)\n vb_interp = interp(vb)\n urb_interp = interp(urb)\n vrb_interp = interp(vrb)\n urrb_interp = interp(urrb)\n vrrb_interp = interp(vrrb)\n ubs_interp = interp(d1_der(ub))\n vbs_interp = interp(d1_der(vb))\n urbs_interp = interp(d1_der(urb))\n vrbs_interp = interp(d1_der(vrb))\n urrbs_interp = interp(d1_der(urrb))\n vrrbs_interp = interp(d1_der(vrrb))\n\n old_bx_interp = interp(ebdy_old.bdy.x)\n old_by_interp = interp(ebdy_old.bdy.y)\n old_bxs_interp = interp(d1_der(ebdy_old.bdy.x))\n old_bys_interp = interp(d1_der(ebdy_old.bdy.y))\n old_nx_interp = interp(ebdy_old.bdy.normal_x)\n old_ny_interp = interp(ebdy_old.bdy.normal_y)\n old_nxs_interp = interp(d1_der(ebdy_old.bdy.normal_x))\n old_nys_interp = interp(d1_der(ebdy_old.bdy.normal_y))\n old_ub = ebdy_old.interpolate_radial_to_boundary(uo[0])\n old_vb = ebdy_old.interpolate_radial_to_boundary(vo[0])\n old_urb = ebdy_old.interpolate_radial_to_boundary_normal_derivative(uo[0])\n old_vrb = ebdy_old.interpolate_radial_to_boundary_normal_derivative(vo[0])\n old_urrb = ebdy_old.interpolate_radial_to_boundary_normal_derivative2(uo[0])\n old_vrrb = ebdy_old.interpolate_radial_to_boundary_normal_derivative2(vo[0])\n # i think the old parm is right, but should think about\n old_ub_interp = interp(old_ub)\n old_vb_interp = interp(old_vb)\n old_urb_interp = interp(old_urb)\n old_vrb_interp = interp(old_vrb)\n old_urrb_interp = interp(old_urrb)\n old_vrrb_interp = interp(old_vrrb)\n old_ubs_interp = interp(d1_der(old_ub))\n old_vbs_interp = interp(d1_der(old_vb))\n old_urbs_interp = interp(d1_der(old_urb))\n old_vrbs_interp = interp(d1_der(old_vrb))\n old_urrbs_interp = interp(d1_der(old_urrb))\n old_vrrbs_interp = interp(d1_der(old_vrrb))\n\n xx = aap.x[fc3l]\n yy = aap.y[fc3l]\n def objective(s, r, so, ro):\n f = np.empty([s.size, 4])\n f[:,0] = old_bx_interp(so) + ro*old_nx_interp(so) + 2*dt*ub_interp(s) + 2*dt*r*urb_interp(s) + dt*r**2*urrb_interp(s) - xx\n f[:,1] = old_by_interp(so) + ro*old_ny_interp(so) + 2*dt*vb_interp(s) + 2*dt*r*vrb_interp(s) + dt*r**2*vrrb_interp(s) - yy\n f[:,2] = bx_interp(s) + r*nx_interp(s) + 1.5*dt*ub_interp(s) + 1.5*dt*r*urb_interp(s) + 0.75*dt*r**2*urrb_interp(s) - 0.5*dt*old_ub_interp(so) - 0.5*dt*ro*old_urb_interp(so) - 0.25*dt*ro**2*old_urrb_interp(so) - xx\n f[:,3] = by_interp(s) + r*ny_interp(s) + 1.5*dt*vb_interp(s) + 1.5*dt*r*vrb_interp(s) + 0.75*dt*r**2*vrrb_interp(s) - 0.5*dt*old_vb_interp(so) - 0.5*dt*ro*old_vrb_interp(so) - 0.25*dt*ro**2*old_vrrb_interp(so) - yy\n return f\n def Jac(s, r, so, ro):\n J = np.empty([s.size, 4, 4])\n # derivative with respect to s\n J[:,0,0] = 2*dt*ubs_interp(s) + 2*dt*r*urbs_interp(s) + dt*r**2*urrbs_interp(s)\n J[:,1,0] = 2*dt*vbs_interp(s) + 2*dt*r*vrbs_interp(s) + dt*r**2*vrrbs_interp(s)\n J[:,2,0] = bxs_interp(s) + r*nxs_interp(s) + 1.5*dt*ubs_interp(s) + 1.5*dt*r*urbs_interp(s) + 0.75*dt*r**2*urrbs_interp(s)\n J[:,3,0] = bys_interp(s) + r*nys_interp(s) + 1.5*dt*vbs_interp(s) + 1.5*dt*r*vrbs_interp(s) + 0.75*dt*r**2*vrrbs_interp(s)\n # derivative with respect to r\n J[:,0,1] = 2*dt*urb_interp(s) + 2*dt*r*urrb_interp(s)\n J[:,1,1] = 2*dt*vrb_interp(s) + 2*dt*r*vrrb_interp(s)\n J[:,2,1] = nx_interp(s) + 1.5*dt*urb_interp(s) + 1.5*dt*r*urrb_interp(s)\n J[:,3,1] = ny_interp(s) + 1.5*dt*vrb_interp(s) + 1.5*dt*r*vrrb_interp(s)\n # derivative with respect to so\n J[:,0,2] = old_bxs_interp(so) + ro*old_nxs_interp(so)\n J[:,1,2] = old_bys_interp(so) + ro*old_nys_interp(so)\n J[:,2,2] = -0.5*dt*old_ubs_interp(so) - 0.5*dt*ro*old_urbs_interp(so) - 0.25*dt*ro**2*old_urrbs_interp(so)\n J[:,3,2] = -0.5*dt*old_vbs_interp(so) - 0.5*dt*ro*old_vrbs_interp(so) - 0.25*dt*ro**2*old_vrrbs_interp(so)\n # derivative with respect to ro\n J[:,0,3] = old_nx_interp(so)\n J[:,1,3] = old_ny_interp(so)\n J[:,2,3] = -0.5*dt*old_urb_interp(so) - 0.5*dt*ro*old_urrb_interp(so)\n J[:,3,3] = -0.5*dt*old_vrb_interp(so) - 0.5*dt*ro*old_vrrb_interp(so)\n return J\n # take as guess inds our s, r\n s = AEP.full_t[fc3l]\n r = AEP.full_r[fc3l]\n so = OAEP.full_t[fc3l]\n ro = OAEP.full_r[fc3l]\n # now solve for sd, rd\n res = objective(s, r, so, ro)\n mres1 = np.hypot(res[:,0], res[:,1]).max()\n mres2 = np.hypot(res[:,2], res[:,3]).max()\n mres = max(mres1, mres2)\n tol = 1e-12\n while mres > tol:\n J = Jac(s, r, so, ro)\n d = np.linalg.solve(J, res)\n s -= d[:,0]\n r -= d[:,1]\n so -= d[:,2]\n ro -= d[:,3]\n res = objective(s, r, so, ro)\n mres1 = np.hypot(res[:,0], res[:,1]).max()\n mres2 = np.hypot(res[:,2], res[:,3]).max()\n mres = max(mres1, mres2)\n r_fail_1 = r.max() > 0.0\n r_fail_2 = r.min() < -ebdy.radial_width\n ro_fail_1 = ro.max() > 0.0\n ro_fail_2 = ro.min() < -ebdy_old.radial_width\n r_fail = r_fail_1 or r_fail_2\n ro_fail = ro_fail_1 or ro_fail_2\n fail = r_fail or ro_fail\n fail_amount = 0.0\n if fail:\n if r_fail_1:\n fail_amount = max(fail_amount, r.max())\n r[r > 0.0] = 0.0\n if r_fail_2:\n fail_amount = max(fail_amount, (-r-ebdy.radial_width).max())\n r[r < -ebdy.radial_width] = -ebdy.radial_width\n if ro_fail_1:\n fail_amount = max(fail_amount, ro.max())\n ro[ro > 0.0] = 0.0\n if ro_fail_2:\n fail_amount = max(fail_amount, (-ro-ebdy_old.radial_width).max())\n ro[ro < -ebdy_old.radial_width] = -ebdy_old.radial_width\n\n # get the departure points\n xd = bx_interp(s) + nx_interp(s)*r\n yd = by_interp(s) + ny_interp(s)*r\n xD = old_bx_interp(so) + old_nx_interp(so)*ro\n yD = old_by_interp(so) + old_ny_interp(so)*ro\n xd_all[fc3l] = xd\n yd_all[fc3l] = yd\n xD_all[fc3l] = xD\n yD_all[fc3l] = yD\n\n self.new_ebdyc = new_ebdyc\n self.xd_all = xd_all\n self.yd_all = yd_all\n self.xD_all = xD_all\n self.yD_all = yD_all\n\n return self.new_ebdyc#, new_t\n\n def __call__(self, f, fo):\n new_ebdyc = self.new_ebdyc\n # create holding ground\n f_new = EmbeddedFunction(new_ebdyc)\n f_new.zero()\n # semi-lagrangian interpolation\n # fh1 = self.ebdyc.interpolate_to_points(f, self.xd_all, self.yd_all, fix_r=True, dzl=new_ebdyc.danger_zone_list, gil=new_ebdyc.guess_ind_list)\n # fh2 = self.ebdyc_old.interpolate_to_points(fo, self.xD_all, self.yD_all, fix_r=True, dzl=new_ebdyc.danger_zone_list, gil=new_ebdyc.guess_ind_list)\n\n # something seems to be going wrong with the danger zone lists?\n fh1 = self.ebdyc.interpolate_to_points(f, self.xd_all, self.yd_all, fix_r=True)#, dzl=new_ebdyc.danger_zone_list, gil=new_ebdyc.guess_ind_list)\n fh2 = self.ebdyc_old.interpolate_to_points(fo, self.xD_all, self.yD_all, fix_r=True)#, dzl=new_ebdyc.danger_zone_list, gil=new_ebdyc.guess_ind_list)\n\n fh = fh1 + fh2\n # set the grid values\n # f_new.grid_value[new_ebdyc.phys_not_in_annulus] = fh[:new_ebdyc.grid_pna_num]\n # this is pretty hacky here!\n # f_new.grid_value[new_ebdyc.phys_not_in_annulus[new_ebdyc.phys]] = fh[:new_ebdyc.grid_pna_num]\n f_new['grid'][new_ebdyc.phys_not_in_annulus[new_ebdyc.phys]] = fh[:new_ebdyc.grid_pna_num]\n # set the radial values (needs to be upgraded to a loop!)\n f_new[0][:] = fh[new_ebdyc.grid_pna_num:].reshape(new_ebdyc[0].radial_shape)\n # overwrite under grid under annulus by radial grid\n new_ebdyc.update_radial_to_grid2(f_new)\n\n return f_new\n\n def remove_refs(self):\n del self.ebdyc_old\n","sub_path":"ipde/advection/second_order_advector_given_bdy.py","file_name":"second_order_advector_given_bdy.py","file_ext":"py","file_size_in_byte":17440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"68270051","text":"import pytest\nfrom parsers.ameblo_parser import AmebloParser\n\n\n@pytest.fixture(scope = 'class')\ndef parser(request):\n return AmebloParser('', '')\n\n\n@pytest.mark.usefixtures('parser')\nclass TestAuthorSetting:\n def test_author_is_string(self, parser):\n parser.bloggers = 'string'\n parser.determine_author()\n assert parser.author == 'string'\n\n def test_list_with_one_author(self, parser):\n parser.bloggers = ['blogger']\n parser.determine_author()\n assert parser.author == 'blogger'\n\n def test_list_with_several_authors_one_in_theme(self, parser):\n parser.bloggers = ['first', 'second', 'third']\n parser.theme = 'second'\n parser.determine_author()\n assert parser.author == 'second'\n \n def test_list_with_several_authors_noone_in_theme_parse_title(self, parser):\n parser.bloggers = ['first', 'second', 'third']\n parser.theme = 'not an author'\n parser.title = 'This article is written by second author'\n parser.determine_author()\n assert parser.author == 'second'\n","sub_path":"tests/parsers/test_ameblo_parser.py","file_name":"test_ameblo_parser.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"249468673","text":"# import some packages we need\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\n# Task 6.1\n# Choose one image\ncolourful_face03 = cv2.imread('face 03 u6492108.jpg')\n\n# resize it\nface03_colorful = cv2.resize(colourful_face03, (512, 512))\n\ndef my_rotation(img, angle):\n '''\n input: 1. image to be rotated\n 2. the degree of angle\n output:1. img1: forward warping image\n 2. img2: backward warping image using nearest neighbour\n 3 img3: backward warping image using bilinear interpolation\n '''\n img = img.astype(int)\n # Get old image h and w\n h, w = img.shape[0], img.shape[1]\n\n # Calculate the new h and w\n newW = int(w * abs(np.cos(angle)) + h * abs(np.sin(angle))) + 1\n newH = int(w * abs(np.sin(angle)) + h * abs(np.cos(angle))) + 1\n\n # Our three output images\n newimg1 = np.zeros((newH, newW, 3), dtype=int)\n newimg2 = np.zeros((newH, newW, 3), dtype=int)\n newimg3 = np.zeros((newH, newW, 3), dtype=int)\n\n # scr -> des\n trans1 = np.array([[1, 0, 0], [0, -1, 0], [-0.5 * w, 0.5 * h, 1]])\n trans1 = trans1 @ np.array([[np.cos(angle), -np.sin(angle), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1]])\n trans1 = trans1 @ np.array([[1, 0, 0], [0, -1, 0], [0.5 * newW, 0.5 * newH, 1]])\n # des -> src\n trans2 = np.array([[1, 0, 0], [0, -1, 0], [-0.5 * newW, 0.5 * newH, 1]])\n trans2 = trans2 @ np.array([[np.cos(angle), np.sin(angle), 0], [-np.sin(angle), np.cos(angle), 0], [0, 0, 1]])\n trans2 = trans2 @ np.array([[1, 0, 0], [0, -1, 0], [0.5 * w, 0.5 * h, 1]])\n\n # Forward Warping\n for x in range(w):\n for y in range(h):\n # Find the position in target image\n newPos = np.array([x, y, 1]) @ trans1\n # move the greyscale values to target image\n # If the new position is not on the pixel, we round it to the nearest pixel\n newimg1[int(newPos[1])][int(newPos[0])] = img[y][x]\n\n # Backward Warping\n for x in range(newW):\n for y in range(newH):\n # Get the position in the source image\n srcPos = np.array([x, y, 1]) @ trans2\n # Check if the position is in the range of the source image\n if srcPos[0] >= 0 and srcPos[0] < w and srcPos[1] >= 0 and srcPos[1] < h:\n # nearest neighbour\n newimg2[y][x] = img[int(srcPos[1])][int(srcPos[0])]\n # biliear\n bix, biy = int(srcPos[0]), int(srcPos[1]) # 取左上角坐标\n if bix < w - 1 and biy < h - 1:\n rgbX1 = img[biy][bix] + (img[biy][bix + 1] - img[biy][bix]) * (srcPos[0] - bix)\n rgbX2 = img[biy + 1][bix] + (img[biy + 1][bix + 1] - img[biy + 1][bix]) * (srcPos[0] - bix)\n rgb = rgbX1 + (rgbX2 - rgbX1) * (srcPos[1] - biy)\n newimg3[y][x] = rgb\n\n return newimg1, newimg2, newimg3\n\n# 6.1\n# -90 , -45 , -15 , 45 , and 90\nfig = plt.figure(figsize=(14, 10))\n\n# swap channels\nface03_colorful[:, :, [0, 2]] = face03_colorful[:, :, [2, 0]]\n\n# -90 rotation\nimg1, img2, img3 = my_rotation(face03_colorful, -90 * np.pi/180)\n\nimg1 = np.uint8(img1)\nimg2 = np.uint8(img2)\nimg3 = np.uint8(img3)\n\nax1 = fig.add_subplot(231)\nax1.imshow(img3)\nax1.set_title('face03 with -90 degree rotation')\n\n# -45\nimg1, img2, img3 = my_rotation(face03_colorful, -45 * np.pi/180)\n\nimg1 = np.uint8(img1)\nimg2 = np.uint8(img2)\nimg3 = np.uint8(img3)\n\nax2 = fig.add_subplot(232)\nax2.imshow(img3)\nax2.set_title('face03 with -45 degree rotation')\n\n# -15\nimg1, img2, img3 = my_rotation(face03_colorful, -15 * np.pi/180)\n\nimg1 = np.uint8(img1)\nimg2 = np.uint8(img2)\nimg3 = np.uint8(img3)\n\nax3 = fig.add_subplot(233)\nax3.imshow(img3)\nax3.set_title('face03 with -15 degree rotation')\n\n# 45\nimg1, img2, img3 = my_rotation(face03_colorful, 45 * np.pi/180)\n\nimg1 = np.uint8(img1)\nimg2 = np.uint8(img2)\nimg3 = np.uint8(img3)\n\nax4 = fig.add_subplot(234)\nax4.imshow(img3)\nax4.set_title('face03 with 45 degree rotation')\n\n# 90\nimg1, img2, img3 = my_rotation(face03_colorful, 90 * np.pi/180)\n\nimg1 = np.uint8(img1)\nimg2 = np.uint8(img2)\nimg3 = np.uint8(img3)\n\nax5 = fig.add_subplot(235)\nax5.imshow(img3)\nax5.set_title('face03 with 90 degree rotation')\n\n#4.2\n# compare forward and backward warping\n# rotate -15 degrees\nimg1, img2, img3 = my_rotation(face03_colorful, -15 * np.pi/180)\n\nimg1 = np.uint8(img1)\nimg2 = np.uint8(img2)\nimg3 = np.uint8(img3)\n\n# Plot\nfig = plt.figure(figsize=(10, 7))\n\nax1 = fig.add_subplot(121)\nax1.imshow(img1)\nax1.set_title('Forward warping')\nax1 = fig.add_subplot(122)\nax1.imshow(img3)\nax1.set_title('Backward warping')\n\n#4.3\n\n# Plot\nfig = plt.figure(figsize=(10, 7))\n\nax1 = fig.add_subplot(121)\nax1.imshow(img2)\nax1.set_title('Nearest neighbour')\nax1 = fig.add_subplot(122)\nax1.imshow(img3)\nax1.set_title('Bilinear interpolation')\n\nplt.show()\ncv2.waitKey(0)","sub_path":"Lab1/Task6.py","file_name":"Task6.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"644132204","text":"import sys\nfrom bs4 import BeautifulSoup\nimport re\n\nfp=open(\"obama_debate.html\",\"rt\")\nhtml_doc=fp.read()\nod = BeautifulSoup(html_doc, 'html.parser')\n#print(dps.prettify())\ncurrent_speaker=\"\"\n# Beautiful soup\ni=0\nmy_document={}\ncurrent_blank=False\n\nfor turn in od.p:\n turn_string=str(turn.string)\n i+=1\n my_split=turn_string.split()\n if len(my_split)>0:\n if re.match(r\"^[A-Z]+\\:$\",my_split[0]):\n candidate_speaker=my_split[0].replace(\":\",\"\")\n else:\n candidate_speaker=\"\"\n else:\n candidate_speaker=\"\"\n# print \"speaker\", candidate_speaker\n if candidate_speaker!=\"\":\n current_speaker=candidate_speaker\n modified_line=' '.join(my_split[1:])\n else:\n modified_line=turn_string\n if current_speaker!=\"\":\n if not current_speaker in my_document:\n my_document[current_speaker]=[]\n my_document[current_speaker].append(modified_line)\nfor speaker in my_document:\n fp=open(speaker+\".txt\",\"wt\")\n fp.write(\" \".join(my_document[speaker]))\n fp.close()\n\n\n\n","sub_path":"l01s01.py","file_name":"l01s01.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"400144490","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# pa_api.py\n#\n# ------------------------------------------------------------------\nimport sys\nimport requests\nimport hmac\nimport hashlib\nimport base64\nimport urllib.parse\nfrom datetime import datetime\n#\n# ------------------------------------------------------------------\nsys.stderr.write(\"*** 開始 ***\\n\")\n# Amazon Product Advertising APIの設定\nhash_func = hashlib.sha256\nencode_func = base64.b64encode\n#id関係の設定\naccess_key = \"AK******************\"\nsecret_key = \"mn**************************************\"\nassociate_id = \"w**********\"\n#\n# メッセージの生成\ntime_stamp = urllib.parse.quote(datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))\n#\n# 商品のASINコード\nasin_code = \"487311778X\" # (ASINコードがない場合は変わりにISBN-10)\n#\nquery=\"AWSAccessKeyId=\" + access_key + \\\n \"&AssociateTag=\" + associate_id + \\\n \"&ItemId=\" + asin_code + \\\n \"&Operation=ItemLookup\" + \\\n \"&ResponseGroup=Images%2CItemAttributes%2COffers%2CReviews\" + \\\n \"&Service=AWSECommerceService\" + \\\n \"&Timestamp=\" + time_stamp + \\\n \"&Version=2013-08-01\"\napi_domain = \"webservices.amazon.co.jp\"\napi_page = \"/onca/xml\"\nmessage = \"\\n\".join([\"GET\", api_domain, api_page, query])\n#\n# HMACのSignature生成\n#\nsing_gen = hmac.new(secret_key.encode('utf8'), message.encode('utf8'), hash_func)\nraw_sign = sing_gen.digest()\nsign = urllib.parse.quote(encode_func(raw_sign))\n\n# APIの呼び出し\nurl = \"http://\" + api_domain + api_page + \"?\" + query + \"&Signature=\" + sign\nres = requests.get(url)\nwith open(asin_code + \".xml\", \"wb\") as ff:\n ff.write(res.content)\nsys.stderr.write(\"*** 終了 ***\\n\")\n# ------------------------------------------------------------------","sub_path":"test-api.py","file_name":"test-api.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"256032347","text":"# -*- coding: utf-8 -*-\nimport socket\nimport sys\nimport jamesdiary\n\n# 建立协议,当client发送信息为keyword时,返回所有日记历史信息\nKEYWORD = 'P'\n\ndef response1(sock, data, address):\n \"\"\"定义反应行为,如果接收到信息为KEYWORD,发回日记历史,否则则将信息记入日记\"\"\"\n if data == 'P':\n history_message = jamesdiary.readdiary()\n sent = sock.sendto(history_message, address)\n print >>sys.stderr, 'sent %s back to %s' % (sent, address)\n # elif data==\"q\":\n # sock.close() \n else: \n sent = sock.sendto(data, address)\n \n print >>sys.stderr, 'received %s bytes from %s' % (len(data), address)\n print >>sys.stderr, data\n\n jamesdiary.writediary(data)\n \n\n\n\ndef main():\n# Create a TCP/IP socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n# Bind the socket to the port\n server_address = ('localhost', 10000)\n print >>sys.stderr, 'starting up on %s port %s' % server_address\n sock.bind(server_address)\n\n while True:\n print >>sys.stderr, '\\nwaiting to receive message'\n data, address = sock.recvfrom(4096)\n #print \"py debug\",len(data)\n if data == 'q':\n break\n response1(sock, data, address)\n\n #print >>sys.stderr, 'received %s bytes from %s' % (len(data), address)\n #print >>sys.stderr, data\n #if data:\n #sent = sock.sendto(data, address)\n #print >>sys.stderr, 'sent %s bytes back to %s' % (sent, address)\n sock.close()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"_src/om2py3w/3wex0/udp/server1.py","file_name":"server1.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"343646580","text":"#!/usr/bin/env python\n#\n# Created by: Shawn Chen \n#\n# LICENSE\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the Free\n# Software Foundation; either version 2 of the License, or(at your option)\n# any later version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details at http://www.gnu.org/copyleft/gpl.html\n#\n# Brief\n# Solves LeetCode Problem 19: Remove Nth Node From End of List\n\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n fastp = head\n slowp = head\n prev = None\n while n > 1:\n fastp = fastp.next\n n -= 1\n while fastp.next:\n fastp = fastp.next\n prev = slowp\n slowp = slowp.next\n if prev:\n prev.next = prev.next.next\n else:\n # delete head\n head = head.next\n return head\n","sub_path":"Problem19/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"132575644","text":"import matplotlib.pyplot as plt\nimport misc\nimport pickle\n\nplt.close('all')\n\nwith open('./test_rising_flank.pkl', 'rb') as f:\n bp = pickle.load(f)\n\nplt.figure()\nsp = plt.subplot(1, 1, 1)\n\nbp.plot_standard(sp, center='Left', label='Left')\nbp.plot_standard(sp, center='Right', label='Right')\n\nout1 = misc.find_rising_flank(bp._yy)\nout2 = misc.find_rising_flank(bp._yy[::-1])\n\nsp.legend()\n\n\nplt.show()\n\n\n","sub_path":"037_test_rising_flank.py","file_name":"037_test_rising_flank.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"215833398","text":"import numpy as np\nimport scipy.stats\n\n\ndef knn(x, x_train, y_train, k):\n '''\n KNN k-Nearest Neighbors Algorithm.\n\n INPUT: x: testing sample features, (N_test, P) matrix.\n x_train: training sample features, (N, P) matrix.\n y_train: training sample labels, (N, ) column vector.\n k: the k in k-Nearest Neighbors\n\n OUTPUT: y : predicted labels, (N_test, ) column vector.\n '''\n\n # Warning: uint8 matrix multiply uint8 matrix may cause overflow, take care\n # Hint: You may find numpy.argsort & scipy.stats.mode helpful\n\n # YOUR CODE HERE\n # begin answer\n N_test = x.shape[0]\n y = np.zeros(N_test)\n\n for i in range(N_test):\n diff = x_train - x[i,:]\n square_dist = np.sum(diff * diff, axis=1)\n sorted_index = np.argsort(square_dist)\n nodes_label = []\n\n for j in range(k):\n index = sorted_index[j]\n nodes_label.append(y_train[index])\n\n y[i] = scipy.stats.mode(nodes_label).mode[0]\n # end answer\n\n return y\n","sub_path":"ml2018winter_hw3/knn/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"560113959","text":"# Copyright (c) 2013, System Engineering Software Society\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the System Engineering Software Society nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED.\n# IN NO EVENT SHALL SYSTEM ENGINEERING SOFTWARE SOCIETY BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nimport os\nimport os.path\nimport glob\nimport base64\nimport json\n\nfrom sympathy.platform import qt_compat\nQtCore = qt_compat.QtCore\nQtGui = qt_compat.import_module('QtGui')\n\n\nclass PresetsWidget(QtGui.QWidget):\n \"\"\"A widget for handling preset data (loading, storing).\"\"\"\n\n def __init__(self, parent=None):\n super(PresetsWidget, self).__init__(parent)\n\n vlayout = QtGui.QVBoxLayout()\n vlayout.setContentsMargins(0, 0, 0, 0)\n hlayout = QtGui.QHBoxLayout()\n\n presets_label = QtGui.QLabel(\"Presets\")\n self.presets_combobox = QtGui.QComboBox()\n self.presets_save_button = QtGui.QPushButton(\"Save\")\n self.presets_saveas_button = QtGui.QPushButton(\"Save As...\")\n self.presets_load_button = QtGui.QPushButton(\"Load\")\n\n hlayout.addWidget(self.presets_load_button)\n hlayout.addWidget(self.presets_save_button)\n hlayout.addWidget(self.presets_saveas_button)\n\n vlayout.addWidget(presets_label)\n vlayout.addWidget(self.presets_combobox)\n vlayout.addItem(hlayout)\n\n self.setLayout(vlayout)\n\n self.presets_load_button.clicked[bool].connect(self._presetLoad)\n self.presets_save_button.clicked[bool].connect(self._presetSave)\n self.presets_saveas_button.clicked[bool].connect(self._presetSaveAs)\n\n def set_presets(self, item_list):\n self.presets_combobox.addItems(sorted(item_list))\n\n def append_preset(self, item):\n self.presets_combobox.addItem(item)\n self.presets_combobox.setCurrentIndex(\n self.presets_combobox.count() - 1)\n\n def get_selected_preset(self):\n return self.presets_combobox.currentText()\n\n def _presetLoad(self):\n self.emit(QtCore.SIGNAL('presetLoad()'))\n\n def _presetSave(self):\n self.emit(QtCore.SIGNAL('presetSave()'))\n\n def _presetSaveAs(self):\n self.emit(QtCore.SIGNAL('presetSaveAs()'))\n\n\nclass PresetHandlerWidget(QtGui.QWidget):\n def __init__(self, parameters, definition, parent=None):\n super(PresetHandlerWidget, self).__init__(parent)\n\n self._parameters = parameters\n self._nodeid = definition['nodeid']\n self._loaded_data = None\n\n self._preset_dir = self._create_preset_dir()\n\n vlayout = QtGui.QVBoxLayout()\n\n self._preset_view = PresetsWidget()\n\n # Init preset view\n self._name_file_map = self._list_presets_on_disk(self._preset_view)\n\n vlayout.addWidget(self._preset_view)\n\n self.setLayout(vlayout)\n\n QtCore.QObject.connect(self._preset_view,\n QtCore.SIGNAL(\"presetLoad()\"),\n self.preset_load)\n QtCore.QObject.connect(self._preset_view,\n QtCore.SIGNAL(\"presetSave()\"),\n self.preset_save)\n QtCore.QObject.connect(self._preset_view,\n QtCore.SIGNAL(\"presetSaveAs()\"),\n self.preset_saveas)\n\n def _create_preset_dir(self):\n preset_dir = os.path.join(os.getcwdu(), 'presets', self._nodeid)\n if not os.path.isdir(preset_dir):\n os.makedirs(preset_dir)\n return preset_dir\n\n def _list_presets_on_disk(self, preset_view):\n preset_files = glob.glob(os.path.join(self._preset_dir, '*'))\n name_file_map = {}\n\n for preset_filename in preset_files:\n with open(preset_filename, 'r') as f:\n data = f.read()\n data_format = json.loads(data)\n preset_view.append_preset(data_format['name'])\n name_file_map[data_format['name']] = preset_filename\n\n return name_file_map\n\n def loaded_data(self):\n return self._loaded_data\n\n def preset_load_name(self, preset_name):\n fq_filename = self._name_file_map[preset_name]\n\n self._parameters['active_preset']['value'] = preset_name\n\n with open(fq_filename, 'r') as f:\n data = f.read()\n data_format = json.loads(data)\n self._loaded_data = data_format['data']\n\n # Update combobox the correct name\n model = self._preset_view.presets_combobox.model()\n item_count = model.rowCount(model.parent(model.index(0, 0)))\n preset_names = [str(model.data(model.index(i, 0)).toString())\n for i in xrange(0, item_count)]\n\n if preset_name in preset_names:\n self._preset_view.presets_combobox.setCurrentIndex(\n preset_names.index(preset_name))\n\n self.emit(QtCore.SIGNAL(\"presetLoad()\"))\n\n def preset_load(self):\n preset_name = str(self._preset_view.get_selected_preset())\n self.preset_load_name(preset_name)\n\n def preset_save(self):\n preset_name = str(self._preset_view.get_selected_preset())\n fq_filename = self._name_file_map[preset_name]\n\n self._parameters['active_preset']['value'] = preset_name\n\n data_format = {}\n data_format['name'] = preset_name\n data_format['nodeid'] = self._nodeid\n data_format['data'] = self._parameters\n\n with open(fq_filename, 'w') as f:\n f.write(json.dumps(data_format, sort_keys=True, indent=4))\n\n def preset_saveas(self):\n preset_name, ok = QtGui.QInputDialog.getText(self,\n \"Save As...\",\n \"Preset name:\")\n preset_name = str(preset_name)\n if ok:\n preset_filename_base64 = base64.urlsafe_b64encode(preset_name)\n fq_filename = os.path.join(self._preset_dir,\n preset_filename_base64 + '.json')\n\n self._parameters['active_preset']['value'] = preset_name\n\n data_format = {}\n data_format['name'] = preset_name\n data_format['nodeid'] = self._nodeid\n data_format['data'] = self._parameters\n\n with open(fq_filename, 'w') as f:\n f.write(json.dumps(data_format, sort_keys=True, indent=4))\n\n if preset_name not in self._name_file_map:\n self._preset_view.append_preset(preset_name)\n self._name_file_map[preset_name] = fq_filename\n","sub_path":"Library/Common/sylib/preset_handler.py","file_name":"preset_handler.py","file_ext":"py","file_size_in_byte":7855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"178389744","text":"import numpy as np\nimport argparse\nimport cv2\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--image', default='../images/example_12.jpg')\nparser.add_argument('--prototxt', default='./cfgs/MobileNetSSD_deploy.prototxt.txt')\nparser.add_argument('--model', default='./weights/MobileNetSSD_deploy.caffemodel')\nparser.add_argument('--confidence', type=float, default=0.2)\nargs = parser.parse_args()\n\n# initialize the list of class labels MobileNet SSD was trained to detect, then generate a set of bounding box colors for each class.\nCLASSES = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\n\t\"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\n\t\"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\",\n\t\"sofa\", \"train\", \"tvmonitor\"]\nCOLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n\n# load our serialized model from disk\nprint('[INFO] loading model...')\nnet = cv2.dnn.readNetFromCaffe(args.prototxt, args.model)\n\n# load the input image and construct an input blob for the image by resizing to a fixed 300x300 pixels and then normalizing it (note: normalization is done via the authors of the MobileNet SDD implementation)\nimage = cv2.imread(args.image)\n(h, w) = image.shape[:2]\nblob = cv2.dnn.blobFromImage(cv2.resize(image, (512, 512)), 1.0, (512, 512), 127.5)\nprint(blob.shape)\n\nprint('[INFO] computing object detections...')\nnet.setInput(blob)\ndetections = net.forward()\nprint(detections.shape)\n\nfor i in np.arange(0, detections.shape[2]):\n # extract the confidence(i.e., probability) associated with prediciton\n confidence = detections[0, 0, i, 2]\n\n # filter out weak detections by ensuring the confidence is greater than the minimum confidence\n if confidence > args.confidence:\n # extract the index of the class label from the detections, then compute the (x, y)-coordinates of the bounding box for the object.\n idx = int(detections[0, 0, i, 1])\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (start_x, start_y, end_x, end_y) = box.astype('int')\n # display the prediction\n label = '{}: {:2f}%'.format(CLASSES[idx], confidence * 100)\n print('[INFO] {}'.format(label))\n cv2.rectangle(image, (start_x, start_y), (end_x, end_y), COLORS[idx], 2)\n y = start_y - 15 if start_y - 15 > 15 else start_y + 15\n cv2.putText(image, label, (start_x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)\n\n # show the output image\n cv2.imshow('Output', image)\n cv2.waitKey(0)\n","sub_path":"others/image_detect.py","file_name":"image_detect.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"194817543","text":"from django import forms\n\nfrom .. import models\n\n\nclass CourseForm(forms.ModelForm):\n class Meta:\n model = models.Course\n fields = '__all__'\n widgets = {\n \"remark\": forms.Textarea\n }\n help_texts = {\n 'manager': '과목 관리자를 선택하세요.',\n 'name': '과목명을 입력하세요.',\n 'start_date': '과목 시작일을 입력하세요.',\n 'end_date': '과목 종료일을 입력하세요.',\n 'is_test': '시험 여부를 선택하세요.',\n }\n\n\nclass LanguageOfCourseForm(forms.ModelForm):\n class Meta:\n model = models.LanguageOfCourse\n fields = '__all__'\n widgets = {\n \"remark\": forms.Textarea\n }\n help_texts = {\n 'course': '과목을 선택하세요.',\n 'language': '사용 언어를 선택하세요.',\n }\n\n\nclass StudentInCourseForm(forms.ModelForm):\n class Meta:\n model = models.StudentInCourse\n fields = '__all__'\n widgets = {\n \"remark\": forms.Textarea\n }\n help_texts = {\n 'course': '과목을 선택하세요.',\n 'student': '수강 학생을 선택하세요.',\n }\n","sub_path":"algolab_class_API/forms/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"500427506","text":"# Imprime n elementos de la serie de fibonacci\n\nentrada = input(\"Cuantos elementos? \")\nelementos = int(entrada)\n\nn1 = 1\nn2 = 1\n\nif elementos >= 1:\n print(n1)\nif elementos >= 2:\n print(n2)\nif elementos >= 3:\n contador = 2\n while contador < elementos:\n siguiente = n1 + n2\n print(siguiente)\n n1 = n2\n n2 = siguiente\n contador = contador + 1\n","sub_path":"source/fibonacci_v1.py","file_name":"fibonacci_v1.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"610496260","text":"from tkinter import *\r\n\r\ndef color( event ):\r\n var = scale.get()\r\n\r\n if var == 1:\r\n frame.configure(bg=\"red\")\r\n elif var == 2:\r\n frame.configure(bg=\"green\")\r\n else:\r\n frame.configure(bg=\"blue\")\r\n\r\nroot =Tk()\r\n\r\nframe = Frame(\r\n root,\r\n width=250,\r\n height=250\r\n)\r\n\r\nvar = IntVar()\r\nscale = Scale(\r\n root,\r\n orient=HORIZONTAL,\r\n from_=1,\r\n to=3,\r\n tickinterval=1\r\n)\r\nscale.bind(\"\", color)\r\n\r\nframe.pack()\r\nscale.pack()\r\nroot.mainloop()\r\n","sub_path":"Основы tkinter/5. Переменные tkinter/5_1.py","file_name":"5_1.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"309009352","text":"# https://www.hackerrank.com/challenges/two-strings/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps\n\nimport unittest\n\nclass Solution:\n # collect all possibilities list x 2\n # try to find intersect s1 and s2 - if yes we have good result\n def two_strings(self, s1, s2):\n # slow option\n # comb_s1 = set(s1[x:y] for y in range(len(s1) + 1) for x in range(len(s1)) if y > x and y-x <= len(s2))\n # comb_s2 = set(s2[x:y] for y in range(len(s2) + 1) for x in range(len(s2)) if y > x and y-x <= len(s1))\n #\n # return 'NO' if len(list(comb_s1 & comb_s2)) <= 0 else 'YES'\n\n # Still slow\n # comb_s1 = set(s1[x:y] for y in range(len(s1) + 1) for x in range(len(s1)) if y > x and y - x <= len(s2))\n # for x in range(len(s2)):\n # for y in range(1, len(s2)+1):\n # if s2[x:y] in comb_s1:\n # return 'YES'\n # return 'NO'\n\n # one line winner\n return 'YES' if set(s1) & set(s2) else 'NO'\n# test\n\ns = Solution()\n\n# test_cases = [['and', 'art'], ['be', 'cat'], ['hello', 'world'], ['hi', 'world']]\n#\n# for t1 in test_cases:\n# print(t1, s.count_triplets(t1[0], t1[1]))\n\n\nclass TestInt(unittest.TestCase):\n\n def test_integer(self):\n s = Solution()\n\n test_cases = [['and', 'art'], ['be', 'cat'], ['hello', 'world'], ['hi', 'world']]\n test_results = ['YES', 'NO', 'YES','NO']\n\n for i, test_case in enumerate(test_cases):\n self.assertEqual(s.two_strings(test_case[0], test_case[1]), test_results[i])\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"hackerrank/arrays/two_strings.py","file_name":"two_strings.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"348220319","text":"def decrypt():\n alph = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\",\n \"v\", \"w\", \"x\", \"y\", \"z\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\", \" \", \".\", \",\", \"!\"]\n input_message = input(\"Enter a message to be encrypted. \")\n input_message_array = []\n output_message_array = []\n\n for i in range(len(input_message)):\n input_message_array.append(input_message[i].lower())\n print(input_message_array)\n\n # Check all the letters in the message are valid and accepted\n for y in range(len(input_message_array)):\n if input_message_array[y] not in alph:\n print(\"Character {} is not in my alphabet!\".format(input_message_array[y]))\n\n try:\n encrypt_by = int(input(\"How many letters to decrypt by?\")) * -1\n except ValueError:\n print(\"Invalid number!\")\n encrypt()\n\n for enc in range(len(input_message_array)):\n letter_location = alph.index(input_message_array[enc])\n if letter_location + encrypt_by < len(alph):\n output_message_array.append(alph[letter_location + encrypt_by])\n else:\n output_message_array.append(alph[letter_location + encrypt_by - len(alph)])\n output_message = ''.join(output_message_array)\n print(\"Final message: {}\".format(output_message))","sub_path":"decrpyt.py","file_name":"decrpyt.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"349010358","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\n\nclass Session(models.Model):\n _name = 'odoo-dpd-integration.session'\n description = fields.Text()\n\n name = fields.Char(required=True)\n\n responsible_id = fields.Many2one('res.users',\n ondelete='set null', string=\"Responsible\", index=True)\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"449923637","text":"from django.core import serializers\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\n\n# Create your views here.\nfrom mall.models import Product\n\n\n@csrf_exempt\ndef add(request):\n if request.method == 'POST':\n try:\n test1 = Product(\n name=request.POST.get('name'),\n price=request.POST.get(\"price\"),\n category=request.POST.get(\"category\"),\n )\n test1.save()\n data = Product.objects.filter(name=request.POST.get(\"name\"))\n isdict = serializers.serialize('json', data)\n return JsonResponse(isdict, safe=False)\n except:\n return JsonResponse({\"code\": 404})\n else:\n return JsonResponse({\"code\": 404})\n\n\n@csrf_exempt\ndef delete(request):\n if request.method == 'POST':\n try:\n uid = request.POST.get('uid')\n data = Product.objects.filter(uid=uid)\n isdict = serializers.serialize('json', data)\n if data:\n data.delete()\n return JsonResponse(isdict, safe=False)\n except:\n return JsonResponse({\"code\": 404})\n else:\n return JsonResponse({\"code\": 404})\n\n\n@csrf_exempt\ndef change(request):\n if request.method == 'POST':\n try:\n uid = request.POST.get('uid')\n nameIndb = Product.objects.filter(uid=uid).first()\n if nameIndb:\n nameIndb.name = request.POST.get('name')\n nameIndb.price = request.POST.get('price')\n nameIndb.category = request.POST.get('category')\n nameIndb.save()\n data = Product.objects.filter(uid=uid)\n isdict = serializers.serialize('json', data)\n return JsonResponse(isdict, safe=False)\n except:\n return JsonResponse({\"code\": 404})\n else:\n return JsonResponse({\"code\": 404})\n\n\n@csrf_exempt\ndef select(request):\n if request.method == 'GET':\n try:\n uid = request.GET.get('uid')\n nameIndb = Product.objects.filter(uid=uid)\n if nameIndb:\n isdict = serializers.serialize('json', nameIndb)\n return JsonResponse(isdict, safe=False)\n except:\n return JsonResponse({\"code\": 404})\n else:\n return JsonResponse({\"code\": 404})\n","sub_path":"mall/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"206435336","text":"# Для начала следует импортировать библиотеку и подключить токен Telegram-бота на Python\nimport telebot\nfrom telebot import types\n\nbot = telebot.TeleBot('1674146353:AAH_RT5G4jqkoFNcSC6oKM_fYc0SVYWk0dI')\n\n# Теперь напишем обработчик текстовых сообщений, который будет обрабатывать входящую команду /start, через запятую\n# можно добавить /help\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n bot.reply_to(message, \"Начинаем! Поздоровайся с ботом, ему будет приятно\")\n\n# Добавим ещё один обработчик для получения текстовых сообщений. Если бот получит «Привет», он также поздоровается.\n\n# это кнопочки чтобы ответить боту. ReplyKeyboardMarkup — это шаблоны сообщений.\n# К при��еру, ваш бот задаёт пользователю вопрос и предлагает варианты ответа.\n# Пользователь может самостоятельно напечатать ответ, либо нажать на готовую кнопку.\n# Такая клавиатура показывается вместо основной и не привязана ни к какому сообщению.\n# В кнопки такой клавиатуры нельзя заложить никакой информации,\n# нельзя запрограммировать для неё подобный алгоритм, если пользователь нажимает кнопку с текстом «abc» отправить\n# текст «qwerty» отправлено будет только то, что написано на кнопке (есть два исключения, о которых ниже).\n\nmm = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)\nbutton1 = types.KeyboardButton(\" Учиться\")\nbutton2 = types.KeyboardButton(\" Играть\")\nmm.add(button1,button2)\n# keyboard1 = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True, True)\n# # первый Тру отвечает за размер, второй за исчезновение\n# keyboard1.row('Учиться', 'Играть')\n\n@bot.message_handler(content_types=['text'])\ndef hello_messages(message):\n if message.text.lower() == 'привет':\n bot.send_message(message.from_user.id, f'Привет, {message.from_user.first_name}')\n bot.send_message(message.from_user.id, 'Чем хочешь заняться? Будем учиться или пойграем?',\n reply_markup=mm)\n\n if message.text == \" Учиться\":\n bot.send_message(message.chat.id, \"Отлично!\")\n if message.text == \" Играть\":\n bot.send_message(message.chat.id, \"Будь серьезней!\")\n # if message.from_user.id == 'Учиться':\n # bot.send_message(message.from_user.id, 'Ok')\n # else:\n # bot.send_message(message.from_user.id, 'Будь серьезней!')\n # else:\n # # Все остальные сообщения будут определены, как нераспознанные\n # bot.send_message(message.from_user.id, 'А поздороваться?!')\n\n# @bot.message_handler(content_types=['sticker'])\n# def stics(message):\n# if message.text.lower() == 'привет':\n# bot.send_message(message.chat.id, 'Привет, мой создатель')\n# elif message.text.lower() == 'пока':\n# bot.send_message(message.chat.id, 'Прощай, создатель')\n\n# Запускаем бота следующей строкой. Так мы задаём боту непрерывное отслеживание новых сообщений. \n# Если бот упадёт, а сообщения продолжат поступать, они будут накапливаться в течение 24 часов \n# на серверах Telegram, и в случае восстановления бота прилетят ему все сразу.\nbot.polling(none_stop=True)","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"564433844","text":"from math import *\r\n\r\ndef funkcja1(x):\r\n return (2*x*x)-(3*x)+5\r\n\r\ndef funkcja2(x):\r\n return (x*x)+x-10\r\n\r\ndef g(x):\r\n return -(x*x)-15\r\n\r\ndef pole(p,q,n):\r\n dl=(q-p)/n\r\n s=0\r\n i=0\r\n while(i int(etc.knob4 * 75):\n r = random.randrange(0,254)\n g = random.randrange(0,254)\n b = random.randrange(0,254)\n counter = 0\n \n colorshift = 20 - int(etc.knob4 * 20)\n r= (r+colorshift)%255\n g= (g+colorshift)%255\n b= (b+colorshift)%255\n color = (r,g,b)\n \n#set teeth number and shape \n teeth = int(etc.knob1 * 10)\n teethwidth = int(1280-128*teeth)\n if teethwidth == 0 : teethwidth = 128\n shape = int(etc.knob2*3)\n clench = 100 - teethwidth/2\n if teethwidth > 640 and shape >= 1 : clench = -360\n if shape < 1 : clench = 5\n \n#top row\n for i in range(0, 10) :\n x = (i * teethwidth)+teethwidth/2\n y0 = 0\n y1 = y0 + abs(etc.audio_in[i] / 85) + clench\n pygame.draw.line(screen, color, [x, y0], [x, y1], teethwidth)\n if shape == 1 :\n pygame.gfxdraw.filled_trigon(screen, x-teethwidth/2, y1, x, y1+teethwidth/2, x+teethwidth/2, y1, color)\n if shape >= 2 :\n pygame.gfxdraw.filled_circle(screen, x, y1, teethwidth/2, color) \n\n#bottom row \n for i in range(10, 20) :\n x = ((i-10) * teethwidth) + teethwidth/2\n y0 = 720\n y1 = y0 - abs(etc.audio_in[i] / 85) - clench\n pygame.draw.line(screen, color, [x, y0], [x, y1], teethwidth)\n if shape == 1 :\n pygame.gfxdraw.filled_trigon(screen, x-teethwidth/2, y1, x, y1-teethwidth/2, x+teethwidth/2, y1, color)\n if shape >= 2 :\n pygame.gfxdraw.filled_circle(screen, x, y1, teethwidth/2, color)\n \n \n#print background color layer over entire image\n veil = pygame.Surface((1280,720)) \n veil.set_alpha(int(etc.knob3 * 200)) # adjust transparency on knob1\n veil.fill((etc.bg_color[0],etc.bg_color[1],etc.bg_color[2])) \n screen.blit(veil, (0,0)) # (0,0) = starts at top left \n ","sub_path":"docs/ETC/ErrorModes/S - Sound Jaws-Trails/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"420977810","text":"#!/usr/bin/python\nimport sys\n\n\"\"\"\nDefinition for a Directed graph node\nclass DirectedGraphNode:\n def __init__(self, x):\n self.label = x\n self.neighbors = []\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param: graph: A list of Directed graph node\n @return: Any topological order for the given graph.\n \"\"\"\n def topSort(self, graph):\n # write your code here\n indegree = {}\n for n in graph:\n if n not in indegree:\n indegree[n] = 0\n for i in n.neighbors:\n indegree[i] = indegree.get(i, 0) + 1\n q = []\n for k, v in indegree.items():\n if v == 0:\n q.append(k)\n if not q:\n return []\n result = []\n while q:\n node = q.pop(0)\n result.append(node)\n for n in node.neighbors:\n indegree[n] -= 1\n if indegree[n] == 0:\n q.append(n)\n return result\n\ndef main():\n aa = Solution()\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(main())","sub_path":"LintCode/topologicalSorting.py","file_name":"topologicalSorting.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207908387","text":"\n\n#!/usr/bin/env python3\n# author: @netmanchris\n\n\"\"\"\nCopyright 2016 Hewlett Packard Enterprise Development LP.\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\"\"\" This file will take the GET the contents of the HPE IMC Network Assets module and dump them into a CSV file called\nall_assets.csv where each line of the CSV file represents one physical or logical asset as discovered by the HPE IMC\nplatform.\n\n\n This library uses the pyhpeimc python wrapper around the IMC RESTful API to automatically push the new performance tasks\n with minimal effort on the part of the user.\"\"\"\n\nimport csv\nfrom pyhpeimc.auth import *\nfrom pyhpeimc.plat.system import *\n\nauth = IMCAuth(\"http://\", \"10.101.0.203\", \"8080\", \"admin\", \"admin\")\n\n\nall_device_series = get_system_series(auth.creds, auth.url)\n\n\nkeys = all_device_series[0].keys()\n\n\n\nwith open ('all_device_series.csv', 'w') as file:\n dict_writer = csv.DictWriter(file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(all_device_series)\n\n\n\n","sub_path":"PythonUtilities/Gather_IMC_Data/Gather_Device_Series/gather_device_series.py","file_name":"gather_device_series.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"275448553","text":"# -*- coding:utf8 -*-\nfrom bson import ObjectId\n\nfrom util.dbInit import Mongdb\nfrom util.openTokenGetData import checkAuth,checkDeleAuth\nimport re\n\n\nclass DeleObj(Mongdb):\n def __init__(self, db, *table):\n try:\n self.table = table[0]\n print('table', table[0])\n except Exception:\n pass\n super(DeleObj, self).__init__(db)\n\n def useTokenGetData(self, token):\n coundList = self.openToken(token).get('message').get('cound')\n adminpeople = self.openToken(token).get('message').get('type0')\n superAdmin = self.openToken(token).get('message').get('superAdmin')\n return coundList, superAdmin, adminpeople\n\n @checkDeleAuth\n @checkAuth\n def deleData(self, data):\n for i in data['jsonMessage']:\n if \"_id\" == i:\n data['jsonMessage'][i] = ObjectId(data['jsonMessage'][i])\n if 'type' in data and data.get('type') == '模糊查询':\n try:\n for i in data['jsonMessage']:\n if \"_id\" != i:\n data['jsonMessage'][i] = re.compile(data['jsonMessage'][i])\n except Exception:\n pass\n rest = self.db[self.table].delete_many(data['jsonMessage'])\n if rest.deleted_count:\n return self.responseContent('200', '删除成功', data)\n elif rest.deleted_count == 0:\n return self.responseContent('201', '无删除', {})\n\n @checkDeleAuth\n @checkAuth\n def dropData(self, data):\n try:\n self.db[self.table].drop()\n return self.responseContent('200', '删除成功', {'table':self.table})\n except Exception:\n return self.responseContent('410', '系统异常', {})\n","sub_path":"dele/deleserver/deleserver.py","file_name":"deleserver.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"115088791","text":"from django.contrib import admin\n\nfrom .models import SoalUlangan, Ulangan, Nilai\n\n\nclass SoalUlanganInline(admin.StackedInline):\n fieldsets = (\n ('+', {\n 'classes': ('collapse',),\n 'fields': (\n 'pertanyaan', 'gambar', 'a', 'b', 'c', 'd', 'e', 'jawaban',)\n }),\n )\n model = SoalUlangan\n extra = 0\n\n\n@admin.register(Ulangan)\nclass MapelAdmin(admin.ModelAdmin):\n list_display = ('mata_pelajaran', 'id', 'guru', 'kelas', 'semester', 'tanggal',)\n\n fieldsets = (\n ('+', {\n 'classes': ('collapse',),\n 'fields': (\n 'mata_pelajaran', 'guru', 'kelas',\n 'semester', 'kkm', 'duration', 'kisi_kisi')\n }),\n )\n\n inlines = [SoalUlanganInline,]\n\n\n@admin.register(Nilai)\nclass NilaiAdmin(admin.ModelAdmin):\n list_display = ('siswa', 'mapel', 'nilai', 'tanggal',)\n\n fields = ('siswa', 'mapel', 'nilai')\n","sub_path":"src/cbt/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"201584287","text":"import random\nimport time\nimport socket\nimport pickle\nimport sys\nimport os\nimport threading\n\nimport simulation\n\nrandom.seed(time.time())\n\nroutes = []\n\nfor i in range(0,5):\n x = 5-i\n y = 0\n z = x+3\n w = 9\n routes.append([x, y, z, w])\n routes.append([y, x, w, z])\n\n\ndef spawn_vehicles(sim, amount, mode):\n grid_size_x = sim.grid_size_x\n grid_size_y = sim.grid_size_y\n\n cell_size_x = sim.cell_size_x\n cell_size_y = sim.cell_size_y\n\n n_vehicles = len(sim.vehicles)\n i = n_vehicles\n\n while i < amount + n_vehicles and i < 10:\n sim.add_vehicle(mode, amount)\n\n start_x = random.randint(0, grid_size_x - 1) * cell_size_x + cell_size_x / 2\n start_y = random.randint(0, grid_size_y - 1) * cell_size_y + cell_size_y / 2\n\n goal_x = random.randint(0, grid_size_x - 1) * cell_size_x + cell_size_x / 2\n goal_y = random.randint(0, grid_size_y - 1) * cell_size_y + cell_size_y / 2\n\n #start_x = routes[i][0] * cell_size_x + cell_size_x / 2\n #start_y = routes[i][1] * cell_size_y + cell_size_y / 2\n # \n #goal_x = routes[i][2] * cell_size_x + cell_size_x / 2\n #goal_y = routes[i][3] * cell_size_y + cell_size_y / 2\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n while True:\n try:\n sock.connect(('127.0.0.1', 100 + i))\n except:\n print('cant connect to index ' + str(i))\n continue\n break\n sock.sendall(pickle.dumps([start_x, start_y, goal_x, goal_y]))\n #sock.sendall(pickle.dumps(routes[i]))\n sock.close()\n\n i += 1\n\ndef main():\n\n n_vehicles = 4\n mode = 2\n if len(sys.argv) >= 2:\n n_vehicles = int(sys.argv[1])\n if len(sys.argv) == 3:\n mode = sys.argv[2]\n \n print('Running with ', n_vehicles, ' vehicles in mode ', mode)\n # Create window and set coordinate system.\n size_x = 1000\n size_y = 1000\n grid_size_x = 10\n grid_size_y = 10\n \n sim = simulation.Simulation(size_x, size_y, grid_size_x, grid_size_y)\n spawn_vehicles(sim, n_vehicles, mode)\n sim.win.close()\n del sim\n #return\n \n while True:\n time.sleep(5)\n if threading.active_count() == 1:\n return\n\n\n\n frame_time = 0\n frame_start = time.time()\n\n while True:\n if frame_time < 1 / 1000:\n frame_time = time.time() - frame_start\n else:\n frame_start = time.time()\n sim.update(frame_time)\n if not sim.open:\n break\n\nmain()\n","sub_path":"Version4/Simulation/Simulation2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"27860054","text":"import numpy, matplotlib.pyplot , scipy.special\n# nerual network class definition\n\n\nclass neuralNetwork:\n \n # initialize the nerual network\n def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):\n \n self._input = input_nodes\n self._hidden = hidden_nodes\n self._output = output_nodes\n \n self._learning_rate = learning_rate\n # activiation function is the sigmoid function\n self._activation_function = lambda x: scipy.special.expit(x) \n\n # link weight matrices, wih and who\n # weights inside the arrays are w_i_j, where link is from node i to node j in the next layer\n # w11 w21\n # w12 w22 etc\n \n self._w_input_hidden = numpy.random.normal(0.0, pow(self._hidden, -0.5),(self._hidden, self._input))\n self._w_hidden_output = numpy.random.normal(0.0, pow(self._output, -0.5),(self._output, self._hidden))\n \n\n \n \n # train the nerual network\n def train(self, inputs_list, targets_list):\n \n # convert inputs list to 2d array\n inputs = numpy.array(inputs_list, ndmin = 2).T\n targets = numpy.array(targets_list, ndmin = 2).T\n \n # calculate signals into hidden layer\n hidden_inputs = numpy.dot(self._w_input_hidden, inputs)\n \n # calculate the signals emerging from hidden layer\n hidden_outputs = self._activation_function(hidden_inputs)\n \n # calculate signals into final output laer\n final_inputs = numpy.dot(self._w_hidden_output, hidden_outputs)\n \n # calculate the signals emerging from final output layer\n final_outputs = self._activation_function(final_inputs)\n \n # error is: (target - output)\n output_errors = targets - final_outputs\n \n # hidden layer error is the output_errors, split by weights, recombined at hidden nodes\n hidden_errors = numpy.dot(self._w_hidden_output.T, output_errors)\n \n # update the weights for the link between the hidden and output layers\n self._w_hidden_output += self._learning_rate * numpy.dot((output_errors*final_outputs * (1.0 - final_outputs)),numpy.transpose(hidden_outputs))\n \n # update the weights for the link between the input and hidden layers \n self._w_input_hidden += self._learning_rate * numpy.dot((hidden_errors*hidden_outputs * (1.0 - hidden_outputs)),numpy.transpose(inputs))\n \n \n # queru the nerual network:\n def query(self, inputs_list):\n # convert inputs list to 2d array\n inputs = numpy.array(inputs_list, ndmin = 2).T\n \n # calculate signals into hidden layer\n hidden_inputs = numpy.dot(self._w_input_hidden, inputs)\n hidden_outputs = self._activation_function(hidden_inputs) \n \n # calculate signals into output layer\n final_inputs = numpy.dot(self._w_hidden_output, hidden_outputs)\n final_outputs = self._activation_function(final_inputs)\n \n return final_outputs\n\n\ndef main():\n\t\n\tdata_file = open(\"/home/tonytang/Desktop/Machine Learning/mnist_train.csv\", 'r')\n\tdata_list = data_file.readlines()\n\tdata_file.close()\n\n\n\tinput_nodes = 784\n\thidden_nodes = 200\n\toutput_nodes = 10\n\n\tlearning_rate = 0.1\n\n\tnerual_network = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)\n\n\ttraining_data_file = open(\"/home/tonytang/Desktop/Machine Learning/mnist_train.csv\", 'r')\n\ttraining_data_list = training_data_file.readlines()\n\ttraining_data_file.close()\n\n\tepochs = 7\n\n\t# Train the nerual network \n\n\tfor e in range (epochs):\n\t\tfor record in training_data_list:\n\t\t # split the record by ','\n\n\t\t all_values = record.split(',')\n\n\t\t # scale and shift the inputs\n\t\t inputs = (numpy.asfarray(all_values[1:]) / 255 * 0.99) + 0.01\n\n\t\t # create the target ouput values (all 0.01, except the desired label which is 0.99)\n\t\t targets = numpy.zeros(output_nodes) + 0.01\n\n\t\t # all values[0] is the target label for this record gets the value 0.99\n\t\t targets[(int)(all_values[0])] = 0.99\n\n\t\t nerual_network.train(inputs, targets)\n\n\n\t# load the training test data\n\ttraining_data_test = open(\"/home/tonytang/Desktop/Machine Learning/mnist_test.csv\", 'r')\n\ttraining_data_test_list = training_data_test.readlines()\n\ttraining_data_test.close()\n\n\t# test the neural network\n\n\t# scorecard for how well the network performs\n\tscore_card = []\n\n\tfor record in training_data_test_list:\n\t \n\t # split the record by ',' commas\n\t \n\t all_values = record.split(',')\n\t \n\t # correct answer is the first value\n\t \n\t correct_label = int(all_values[0])\n\t \n\t # print(correct_label, \"correct label\")\n\t \n\t # scale and shift the inputs\n\t inputs = (numpy.asfarray(all_values[1:])/ 255 * 0.99) + 0.01\n\t # query the network\n\t \n\t outputs = nerual_network.query(inputs)\n\t \n\t # the index of the highest values corresponds to the label\n\t \n\t label = numpy.argmax(outputs)\n\t \n\t # print(label, \"network's answer\")\n\t \n\t # append correct or incorrect to list\n\t \n\t if(label == correct_label):\n\t # network answer matches correct answer\n\t score_card.append(1)\n\t else:\n\t # doesn't match\n\t score_card.append(0)\n\n\t# calculate the performance score, the fraction of correct answers\n\tscore_card_array = numpy.asarray(score_card)\n\n\tprint(\"performance = \", score_card_array.sum()/score_card_array.size)\n\nmain()\n","sub_path":"nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":5509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"365984983","text":"import keras.backend as K\nfrom keras.layers import (\n Dropout,\n Lambda,\n Activation,\n Dense,\n Flatten\n)\nfrom keras.layers.convolutional import (\n Conv2D,\n Conv2DTranspose,\n MaxPooling2D,\n AveragePooling2D,\n ZeroPadding2D\n)\nfrom keras.layers.merge import add\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.regularizers import l2\nfrom NeMO_layers import CroppingLike2D, BilinearUpSampling2D\nfrom hyperopt import fmin, tpe, hp, STATUS_OK, Trials\n\ndef alex_conv(filters, kernel_size, conv_strides=(1,1), pad_bool=False, pool_bool=False, batchnorm_bool = False, pool_size=(2,2), pool_strides=(2,2), weight_decay=0., block_name='alexblock'):\n def f(input):\n x = input\n if pad_bool:\n x = ZeroPadding2D(padding=(1,1))(x)\n\n x = Conv2D(filters, kernel_size, strides=conv_strides, activation='relu',\n kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay),\n name='{}_conv'.format(block_name))(x)\n\n if pool_bool:\n x = MaxPooling2D(pool_size=pool_size, strides=pool_strides, name='{}_pool'.format(block_name))(x)\n if batchnorm_bool:\n x = BatchNormalization()(x)\n return x\n return f\n\ndef alex_fc(filters, flatten_bool=False, dropout_bool=False, dropout=0.5, weight_decay=0., block_name='alexfc'):\n def f(input):\n x = input\n if flatten_bool:\n x = Flatten()(x)\n\n x = Dense(filters, kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay), name='{}_dense'.format(block_name))(x)\n if dropout_bool:\n x = Dropout(dropout)(x)\n return x\n return f\n\n\ndef vgg_conv(filters, convs, padding=False, weight_decay=0., block_name='blockx'):\n \"\"\"A VGG convolutional block for encoding.\n # NOTE: All kernels are 3x3 hard-coded!\n\n :param filters: Integer, number of filters per conv layer\n :param convs: Integer, number of conv layers in the block\n :param block_name: String, the name of the block, e.g., block1\n\n >>> from keras_fcn.blocks import vgg_conv\n >>> x = vgg_conv(filters=64, convs=2, block_name='block1')(x)\n\n \"\"\"\n def f(x):\n for i in range(convs):\n if block_name == 'block1' and i == 0:\n if padding is True:\n x = ZeroPadding2D(padding=(100, 100))(x)\n x = Conv2D(filters, (3, 3), activation='relu', padding='same',\n kernel_initializer='he_normal',\n kernel_regularizer=l2(weight_decay),\n name='{}_conv{}'.format(block_name, int(i + 1)))(x)\n else:\n x = Conv2D(filters, (3, 3), activation='relu', padding='same',\n kernel_initializer='he_normal',\n kernel_regularizer=l2(weight_decay),\n name='{}_conv{}'.format(block_name, int(i + 1)))(x)\n\n pool = MaxPooling2D((2, 2), strides=(2, 2), padding='same',\n name='{}_pool'.format(block_name))(x)\n return pool\n return f\n\n\ndef vgg_fc(filters, weight_decay=0., block_name='block5'):\n \"\"\"A fully convolutional block for encoding.\n\n :param filters: Integer, number of filters per fc layer\n\n >>> from keras_fcn.blocks import vgg_fc\n >>> x = vgg_fc(filters=4096)(x)\n\n \"\"\"\n def f(x):\n fc6 = Conv2D(filters, kernel_size=(7, 7),\n activation='relu', padding='same',\n dilation_rate=(2, 2),\n kernel_initializer='he_normal',\n kernel_regularizer=l2(weight_decay),\n name='{}_fc6'.format(block_name))(x)\n drop6 = Dropout(0.5)(fc6)\n fc7 = Conv2D(filters, kernel_size=(1, 1),\n activation='relu', padding='same',\n kernel_initializer='he_normal',\n kernel_regularizer=l2(weight_decay),\n name='{}_fc7'.format(block_name))(drop6)\n drop7 = Dropout(0.5)(fc7)\n return drop7\n return f\n\ndef res_shortcut(input, residual, weight_decay=0):\n \"\"\" Adds a shortcut between input and residual block and merges them with \"sum\"\n \"\"\"\n shortcut = input\n input_shape = K.int_shape(input)\n residual_shape = K.int_shape(residual)\n\n stride_width = int(round(input_shape[1] / residual_shape[1]))\n stride_height = int(round(input_shape[2] / residual_shape[2]))\n equal_channels = input_shape[3] == residual_shape[3]\n\n if stride_width > 1 or stride_height > 1 or not equal_channels:\n shortcut = Conv2D(filters=residual_shape[3], kernel_size=(1,1), strides=(stride_width,stride_height),\n padding=\"valid\", kernel_initializer=\"he_normal\", kernel_regularizer=l2(weight_decay))(input)\n\n return add([shortcut, residual])\n\ndef res_initialconv(filters, init_kernel=(7,7), init_strides=(2,2), weight_decay=0., block_name='initblock'):\n \"\"\" First basic convolution that gets everything started. \n Format is Conv (/2) -> BN -> Actv -> Pool (/2)\n \"\"\"\n def f(input):\n x = Conv2D(filters, init_kernel, strides=init_strides, padding='same',\n kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay),\n name='{}_conv'.format(block_name))(input)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\", name='{}_pool'.format(block_name))(x)\n return x\n return f\n\ndef res_basicconv(filters, convs=2, init_strides=(1,1), weight_decay=0., block_name='blockx'):\n \"\"\" Basic 3 X 3 convolution blocks for use in resnets with layers <= 34.\n Follows improved proposed scheme in hhttp://arxiv.org/pdf/1603.05027v2.pdf\n Format is BN -> Actv -> Conv (/2, if first of block), except for the very first conv of first block (just Conv).\n \"\"\"\n def f(input):\n for i in range(convs):\n if i == 0:\n x = input\n\n if block_name =='megablock1_block1' and i==0:\n x = Conv2D(filters, (3,3), strides=init_strides, padding='same',\n kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay),\n name='{}_conv{}'.format(block_name, int(i+1)))(x) # linear activation for very first conv of first block\n else:\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n if i==0:\n x = Conv2D(filters, (3,3), strides=init_strides, padding='same', \n kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay),\n name='{}_conv{}'.format(block_name, int(i+1)))(x)\n else:\n x = Conv2D(filters, (3,3), strides=(1,1), padding='same',\n kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay),\n name='{}_conv{}'.format(block_name, int(i+1)))(x)\n return res_shortcut(input, x, weight_decay)\n return f\n\ndef res_megaconv(filters, convs, reps, init_strides=(1,1), weight_decay=0., block_name='megablockx'):\n \"\"\" Mega convolution block that combines multiple res_basicconv blocks. Note that init_strides must be defined for the first block\n in case downsampling is necessary\n \"\"\"\n def f(input):\n x = input\n for i in range(reps):\n if i == 0:\n x = res_basicconv(filters, convs, init_strides=init_strides, weight_decay = weight_decay, block_name='{}_block{}'.format(block_name, int(i+1)))(x)\n else:\n x = res_basicconv(filters, convs, init_strides=(1,1), weight_decay = weight_decay, block_name='{}_block{}'.format(block_name, int(i+1)))(x)\n return x\n return f\n\ndef res_1b1conv(filters, convs, init_kernelsize=(1,1), init_dilationrate=(1,1), weight_decay=0., block_name='block1b1'):\n \"\"\" 1x1xM convolution filter for resnet\n \"\"\"\n def f(input):\n for i in range(convs):\n if i==0:\n x = BatchNormalization()(input)\n x = Activation('relu')(x)\n x = Conv2D(filters, kernel_size=init_kernelsize, padding='same', dilation_rate=init_dilationrate,\n kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay), name='{}_1b1conv{}'.format(block_name,int(i+1)))(x)\n else:\n x = Activation('relu')(x)\n x = Conv2D(filters, kernel_size=(1,1), activation='relu', padding='same',\n kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay), name='{}_1b1conv{}'.format(block_name,int(i+1)))(x)\n return x\n return f\n\ndef res_fc(classes, weight_decay=0., block_name='blockfc'):\n \"\"\" Fully connected layer for resnet\n \"\"\"\n def f(input):\n block_shape = K.int_shape(input)\n pool = AveragePooling2D(pool_size=(block_shape[1], block_shape[2]), strides=(1,1), name='{}_pool'.format(block_name))(input)\n flatten = Flatten()(pool)\n dense = Dense(units=classes, kernel_initializer='he_normal', kernel_regularizer=l2(weight_decay), name='{}_dense'.format(block_name))(flatten)\n return dense\n return f\n\ndef vgg_deconv(classes, scale=1, kernel_size=(4, 4), strides=(2, 2),\n crop_offset='centered', weight_decay=0., block_name='featx'):\n \"\"\"A VGG convolutional transpose block for decoding.\n\n :param classes: Integer, number of classes\n :param scale: Float, scale factor to the input feature, varing from 0 to 1\n :param kernel_size: Tuple, the kernel size for Conv2DTranspose layers\n :param strides: Tuple, the strides for Conv2DTranspose layers\n :param crop_offset: Tuple or \"centered\", the offset for cropping.\n The default is \"centered\", which crop the center of the feature map.\n\n >>> from keras_fcn.blocks import vgg_deconv\n >>> x = vgg_deconv(classes=21, scale=1e-2, block_name='feat2')(x)\n\n \"\"\"\n def f(x, y):\n def scaling(xx, ss=1):\n return xx * ss\n scaled = Lambda(scaling, arguments={'ss': scale},\n name='scale_{}'.format(block_name))(x)\n score = Conv2D(filters=classes, kernel_size=(1, 1),\n activation='linear',\n kernel_initializer='he_normal',\n kernel_regularizer=l2(weight_decay),\n name='score_{}'.format(block_name))(scaled)\n if y is None:\n upscore = Conv2DTranspose(filters=classes, kernel_size=kernel_size,\n strides=strides, padding='valid',\n kernel_initializer='he_normal',\n kernel_regularizer=l2(weight_decay),\n use_bias=False,\n name='upscore_{}'.format(block_name))(score)\n else:\n crop = CroppingLike2D(target_shape=K.int_shape(y),\n offset=crop_offset,\n name='crop_{}'.format(block_name))(score)\n merge = add([y, crop])\n upscore = Conv2DTranspose(filters=classes, kernel_size=kernel_size,\n strides=strides, padding='valid',\n kernel_initializer='he_normal',\n kernel_regularizer=l2(weight_decay),\n use_bias=False,\n name='upscore_{}'.format(block_name))(merge)\n return upscore\n return f\n\n\ndef vgg_upsampling(classes, target_shape=None, scale=1, weight_decay=0., block_name='featx'):\n \"\"\"A VGG convolutional block with bilinear upsampling for decoding.\n\n :param classes: Integer, number of classes\n :param scale: Float, scale factor to the input feature, varing from 0 to 1\n :param target_shape: 4D Tuples with targe_height, target_width as\n the 2nd, 3rd elements if `channels_last` or as the 3rd, 4th elements if\n `channels_first`.\n\n >>> from keras_fcn.blocks import vgg_upsampling\n >>> feat1, feat2, feat3 = feat_pyramid[:3]\n >>> y = vgg_upsampling(classes=21, target_shape=(None, 14, 14, None),\n >>> scale=1, block_name='feat1')(feat1, None)\n >>> y = vgg_upsampling(classes=21, target_shape=(None, 28, 28, None),\n >>> scale=1e-2, block_name='feat2')(feat2, y)\n >>> y = vgg_upsampling(classes=21, target_shape=(None, 224, 224, None),\n >>> scale=1e-4, block_name='feat3')(feat3, y)\n\n \"\"\"\n def f(x, y):\n score = Conv2D(filters=classes, kernel_size=(1, 1),\n activation='linear',\n padding='valid',\n kernel_initializer='he_normal',\n kernel_regularizer=l2(weight_decay),\n name='score_{}'.format(block_name))(x)\n if y is not None:\n def scaling(xx, ss=1):\n return xx * ss\n scaled = Lambda(scaling, arguments={'ss': scale},\n name='scale_{}'.format(block_name))(score)\n score = add([y, scaled])\n upscore = BilinearUpSampling2D(\n target_shape=target_shape,\n name='upscore_{}'.format(block_name))(score)\n return upscore\n return f\n\n\ndef vgg_score(crop_offset='centered'):\n \"\"\"A helper block to crop the decoded feature.\n\n :param crop_offset: Tuple or \"centered\", the offset for cropping.\n The default is \"centered\", which crop the center of the feature map.\n\n >>> from keras_fcn.blocks import vgg_deconv\n >>> score = vgg_score(crop_offset='centered')(image, upscore)\n\n \"\"\"\n def f(x, y):\n score = CroppingLike2D(target_shape=K.int_shape(\n x), offset=crop_offset, name='score')(y)\n return score\n return f\n","sub_path":"CNN/utils/NeMO_blocks.py","file_name":"NeMO_blocks.py","file_ext":"py","file_size_in_byte":13624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"441096792","text":"from setuptools import setup, find_packages\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\nwith open(path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='constellation-pkgtools-cli',\n version='1.0.6',\n description='Constellation Package Tools CLI',\n long_description=long_description,\n url='https://developer.myconstellation.io',\n author='Sebastien Warin',\n author_email='support@myconstellation.io',\n license='Apache',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7'\n ],\n keywords='constellation package python tools development',\n packages=find_packages(exclude=['contrib', 'docs', 'tests']),\n install_requires=['docopt', 'requests'],\n entry_points={\n 'console_scripts': [\n 'ctln=constellationpkgtools:main',\n ],\n },\n)\n\n","sub_path":"pypi_install_script/constellation-pkgtools-cli-1.0.6.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"415044915","text":"from sklearn import svm\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import accuracy_score, f1_score\nfrom joblib import dump\nfrom training.dataLoader import get_data\nimport time\n\nX, y, _ = get_data()\n\n# Split the data into training, validation, and testing sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\nprint(\"Training SVC Model...\")\nclf = svm.SVC(gamma='scale', max_iter=1000, probability=True)\n\nt0 = time.time()\nclf.fit(X_train, y_train)\nt1 = time.time()\ntotal = t1-t0\nprint(\"Training Finished in \"+str(round(total, 2))+\" seconds!\")\n\n#\n# # # Evaulate the model on the augmented test data\n# # means = X_train.mean(axis=0)\n# # stds = X_train.std(axis=0)\n# #\n# # X_test_input = X_test - np.expand_dims(means, 0)\n# # X_test_input /= np.expand_dims(stds, 0)\n#\n# # print(\"F1 score:\", f1_score(X_test, predictions, average='weighted'))\n#\n\n# print(\"Calculating Cross Validation Accuracy...\")\n# scores = cross_val_score(clf, X, y, cv=5)\n# print(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\n\nprint(\"Calculating Simple Accuracy...\")\nt0 = time.time()\npredictions = clf.predict(X_test)\nt1 = time.time()\ntotal = t1-t0\nprint(\"Predicting Finished in \"+str(total)+\" seconds!\")\nprint(\"Accuracy:\", accuracy_score(y_test, predictions))\n\n# dump(clf, 'svm.joblib')\n","sub_path":"training/trainSVM.py","file_name":"trainSVM.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"92900529","text":"import math\r\np = int(input(\"Enter number from where you want to start :\"))\r\nprint(\"Your input starts after\" , p) \r\nz = int(input(\"Enter number before which you want to end :\"))\r\nprint(\"Your input end before\" , z)\r\nwith open('file.txt', 'w') as f:\r\n for n in range(p , z):\r\n if (n+1)%3 != 0 and (n-1)%3 != 0:\r\n continue\r\n else:\r\n s = math.sqrt(n+2)\r\n for x in range(2, int(s)):\r\n if n % x == 0:\r\n break\r\n else:\r\n print(n, 'is a prime number')\r\ninput()\r\n","sub_path":"Out dated/Prime finder (7).py","file_name":"Prime finder (7).py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"531100247","text":"from unittest import TestCase\nfrom flask import url_for\nfrom core import app\nimport jwt\nimport string\nimport random\n\n\nclass RootTests(TestCase):\n def setUp(self):\n self.app = app\n self.app.testing = True\n self.app_context = self.app.test_request_context()\n self.app_context.push()\n self.client = self.app.test_client()\n\n def test_root_deve_retornar_hello_world(self):\n request = self.client.get(url_for('hello_world'))\n self.assertEqual('Hello, World!', request.data.decode())\n\n def test_root_deve_retornar_status_code_200(self):\n request = self.client.get(url_for('hello_world'))\n self.assertEqual(200, request.status_code)\n\n def test_registration(self):\n expected = 200\n login = \"test_user_\" + ''.join(random.choice(string.ascii_letters) for i in range(5))\n token = jwt.encode({}, app.config['SECRET_KEY'], algorithm='HS256')\n request = self.client.post(url_for('create_user'),\n json={\"username\": login, \"password\": \"1234\"},\n headers={'x-access-token': token},\n content_type='application/json'\n )\n # print(request.data.decode())\n # self.assertIn(\"id\", request.data.decode())\n self.assertEqual(expected, request.status_code)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"73561807","text":"import json, os, random, secrets\nfrom datetime import datetime\n\nfrom flask import Flask, request\nfrom flask_cors import CORS\nfrom flask_restful import Api, Resource\n\nfrom . import dbaccess as db\n\n\nclass Reviews(Resource):\n\n # Getting reviews for a product\n # Url format: `review?productId=${productId}&userId=${userId)}`\n def get(self):\n print('Get reviews attempt received')\n\n productId = request.args.get('productId')\n userId = request.args.get('userId')\n reviews = db.getProductReviews(int(productId))\n\n # For each review, calculate the overall score based on the number of upvotes and downvotes\n for review in reviews:\n review['reviewdate'] = json.dumps(review['reviewdate'].__str__())\n score = 0\n review['userVote'] = 0\n for id in review['votes']:\n score += review['votes'][id]\n if userId != 'null' and id == int(userId):\n print('here')\n review['userVote'] = review['votes'][id]\n\n # If the score is negative, display it just as\n # 0 people found this helpful\n if score < 0:\n score = 0\n\n review['score'] = score\n\n if reviews is None:\n return {'error': 'Unable to fetch reviews'}\n\n return {'reviews': reviews}\n\n # Adding a new review\n # Url format: `review`\n def post(self):\n print('Add review attempt received')\n data = request.json\n\n productId = int(data.get('productId'))\n userId = int(data.get('userId'))\n rating = data.get('rating')\n reviewText = data.get('comment')\n\n reviewDate = datetime.today().strftime('%Y-%m-%d')\n\n reviewId = db.addReview(productId, userId, \n rating, reviewText, reviewDate)\n \n if reviewId is None:\n return {'error': 'An error occurred: review not added'}\n else:\n return {'reviewId': reviewId}\n\n # Removing a review\n # Url format: `review`\n def delete(self):\n print('Delete review attempt received')\n data = request.json\n\n reviewId = int(data.get('reviewId'))\n status = db.deleteReview(reviewId)\n db.deleteReports(reviewId)\n if status == 1:\n return {'status': 'Review successfully removed'}\n else:\n return {'error': 'Error: unable to delete review'}\n \n\nclass Votes(Resource):\n\n # Adding a vote\n # Url format: `review/vote`\n def post(self):\n print ('Add vote attempt received')\n\n data = request.json\n print('data for add vote:', data)\n reviewId = int(data.get('reviewId'))\n userId = int(data.get('userId'))\n vote = int(data.get('vote'))\n status = db.addVote(reviewId, userId, vote)\n\n if status == 0:\n return {'error': 'Error: voting failed'}\n else:\n return {'status': 'Vote successfully submitted'}\n\n # Changing an existing vote (e.g. from upvote to downvote)\n # Url format: `review/vote`\n def put(self):\n print ('Edit vote attempt received')\n \n data = request.json\n reviewId = int(data.get('reviewId'))\n userId = int(data.get('userId'))\n newVote = int(data.get('vote'))\n status = db.editVote(reviewId, userId, newVote)\n\n if status == 0:\n return {'error': 'Error: voting failed'}\n else:\n return {'status': 'New vote successfully submitted'}\n\n # Deleting a vote \n # Url format: `review/vote`\n def delete(self):\n print ('Delete vote attempt received')\n\n data = request.json\n reviewId = int(data.get('reviewId'))\n userId = int(data.get('userId'))\n status = db.deleteVote(reviewId, userId)\n\n if status == 0:\n return {'error': 'Error: deleting vote failed'}\n else:\n return {'status': 'Vote successfully removed'}\n\nclass Reports(Resource):\n # Getting all reported reviews\n def get(self):\n print(\"Get reports received\")\n reports = db.getReports()\n reportedReviews = []\n\n #Define the information needed for a reported review\n for report in reports:\n reportedReview = {\n 'productname': None,\n 'reviewid': None,\n 'reviewtext': \"\",\n 'harassment': 0,\n 'offensive': 0,\n 'irrelevant': 0\n }\n \n # Get the original report and extract the relevant information \n review = db.getReview(report['reviewid'])\n reportedReview['reviewid'] = review['reviewid']\n reportedReview['reviewtext'] = review['reviewtext']\n\n #Get the product name\n product = db.getProduct(review['productid'])\n reportedReview['productname'] = product['name']\n\n # Add this reported review to the List if it is not already in the list\n if reportedReview not in reportedReviews:\n reportedReviews.append(reportedReview)\n\n # Sum up how many times a review was reported for each of the reasons\n for reported in reportedReviews:\n reviewReports = db.getReviewReports(reported['reviewid'])\n for reviewReport in reviewReports:\n print(\"reviewReport = \", reviewReport)\n reported[reviewReport['reason']] += 1\n \n return reportedReviews\n \n # Add a report to a review\n def post(self):\n print(\"Post report recieved\")\n \n data = request.json\n reviewID = data.get('reviewID')\n reason = data.get('reason')\n\n db.reportReview(reviewID, reason)\n\n # Delete all reports of a review\n def delete(self):\n print(\"Delete reports received\")\n \n data = request.json\n reviewID = data.get('reviewId')\n\n db.deleteReports(reviewID)\n","sub_path":"backend/api/reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":5972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"602019101","text":"t1 = ()\nt2 = (1, 'two', 3)\nprint(t1)\nprint(t2)\n\nt3 = (1,)\nprint(t3)\n\nt4 = (1)\nprint(t4)\n\nprint(3 * ('a', 2))\n\nt5 = (1, 'two', 3)\nt6 = (t5, 3.25)\nprint(t6)\n\nprint((t5 + t6))\nprint((t5 + t6)[3])\nprint((t5 + t6)[2:5])\n\ndef intersect(t1, t2):\n \"\"\"\n Assumes t1 and t2 are tuples\n Returns a tuple containing elements that are in\n both t1 and t2\n \"\"\"\n result = ()\n for e in t1:\n if e in t2:\n result += (e,)\n return result\n\nt7 = ('a', 'b', 'c', 'd', 'e')\nt8 = ('c', 'd', 'b', 'f', 'g', 'h')\n\nprint(intersect(t7, t8))\n \nx, y = (3, 4)\nprint(x)\nprint(y)\n\na, b, c = 'xyz'\nprint(a, b, c)\n\ndef findExtremeDivisors(n1, n2):\n \"\"\"\n Assumes that n1 and n2 are positive ints\n Returns a tuple containing the smallest common divisor > 1 and\n the largest common divisor of n1 and n2. If no common divisor,\n returns (None, None)\n \"\"\"\n minVal, maxVal = None, None\n for i in range(2, min(n1, n2) + 1):\n if n1 % i == 0 and n2 % i == 0:\n if minVal == None:\n minVal = i\n maxVal = i\n return (minVal, maxVal)\n\nlow, high = findExtremeDivisors(100, 200)\n\nprint(low)\nprint(high)\n","sub_path":"mit/6.0001/session-03/5_1_tuples.py","file_name":"5_1_tuples.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"93709190","text":"def convert(string: str):\n # check for bools\n if string == 'true':\n return True\n if string == 'false':\n return False\n \n # check for ints and strings\n try:\n number = int(string)\n if str(number) == string:\n return number\n else:\n return string\n except (TypeError, ValueError) as e:\n return string\n \ndef refine_parameters(data: dict):\n \n clean_dict = {}\n\n for key, val in data.items():\n # if we encounter a dictionary - refine that\n if type(val) == dict:\n clean_dict[key] = refine_parameters(val)\n continue\n\n # if we encounter a list - convert each element\n if type(val) == list:\n clean_dict[key] = list(map(convert, val))\n continue\n\n # if we encounter anything else - convert that\n clean_dict[key] = convert(val)\n\n return clean_dict\n","sub_path":"python_solution.py","file_name":"python_solution.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"495655872","text":"import web3\nimport solcx\nimport os\n\nfrom dotenv import load_dotenv\nfrom sys import argv\n\nfrom web3.middleware import geth_poa_middleware\n# inject the poa compatibility middleware to the innermost layer\n\ndotenv_path = '.env'\nif os.path.exists(dotenv_path):\n load_dotenv(dotenv_path)\n\nvalidators = list(set(os.environ['VALIDATORS'].split(\" \")))\nthreshold = int(os.environ['THRESHOLD'])\n\n\ndef deploy_bridge(side):\n w3 = web3.Web3(web3.HTTPProvider(os.environ[side + '_RPCURL']))\n w3.middleware_onion.inject(geth_poa_middleware, layer=0)\n master_account = w3.eth.account.from_key(os.environ['PRIVKEY'])\n gas_price = int(os.environ[side + '_GASPRICE'])\n solc_version = \"0.6.0\"\n solcx.install_solc(solc_version)\n\n compiled_code = \"deployment/ValidatorsManagement.sol:ValidatorsManagement\"\n compiled_contract = solcx.compile_files('deployment/ValidatorsManagement.sol', output_values=[\"abi\", \"bin\"], solc_version=solc_version)\n ABI = compiled_contract[compiled_code]['abi']\n BYTECODE = compiled_contract[compiled_code]['bin']\n contract = w3.eth.contract(abi=ABI, bytecode=BYTECODE)\n\n needed_gas = contract.constructor(validators, threshold).estimateGas()\n\n nonce = w3.eth.getTransactionCount(master_account.address)\n tx_hash = contract.constructor(validators, threshold).buildTransaction(\n {'from': master_account.address,\n 'chainId': w3.eth.chain_id,\n 'gas': int(w3.eth.getBlock('latest').gasLimit * 0.95),#needed_gas\n 'gasPrice': gas_price,\n 'nonce': nonce,\n \"value\": 0\n }\n )\n\n private_key = master_account.privateKey\n signed_txn = w3.eth.account.sign_transaction(tx_hash, private_key=private_key)\n hsh = w3.eth.sendRawTransaction(signed_txn.rawTransaction).hex()\n contract_id = w3.eth.waitForTransactionReceipt(hsh)[\"contractAddress\"]\n\n if side == 'LEFT':\n print(f\"#1 [LEFT] Validators Set deployed at {contract_id}\")\n else:\n print(f\"#3 [RIGHT] Validators Set deployed at {contract_id}\")\n validator = contract_id\n\n compiled_code = \"deployment/Bridge.sol:Bridge\"\n compiled_contract = solcx.compile_files('deployment/Bridge.sol', output_values=[\"abi\", \"bin\"], solc_version=solc_version)\n ABI = compiled_contract[compiled_code]['abi']\n BYTECODE = compiled_contract[compiled_code]['bin']\n\n contract = w3.eth.contract(abi=ABI, bytecode=BYTECODE)\n\n nonce = w3.eth.getTransactionCount(master_account.address)\n tx_hash = contract.constructor(validator, side == \"LEFT\").buildTransaction(\n {'from': master_account.address,\n 'chainId': w3.eth.chain_id,\n 'gas': int(w3.eth.getBlock('latest').gasLimit * 0.95),#needed_gas\n 'gasPrice': gas_price,\n 'nonce': nonce,\n \"value\": 0\n }\n )\n\n private_key = master_account.privateKey\n signed_txn = w3.eth.account.sign_transaction(tx_hash, private_key=private_key)\n hsh = w3.eth.sendRawTransaction(signed_txn.rawTransaction).hex()\n AttributeDict = w3.eth.waitForTransactionReceipt(hsh)\n contract_id = AttributeDict[\"contractAddress\"]\n blockNumber = AttributeDict['blockNumber']\n\n if side == 'LEFT':\n print(f\"#2 [LEFT] Bridge deployed at {contract_id}\")\n with open(\".env\", \"a\") as myfile:\n myfile.write(\"\\n\")\n myfile.write(f'RIGHT_ADDRESS={contract_id}')\n else:\n print(f\"#4 [RIGHT] Bridge deployed at {contract_id}\")\n with open(\".env\", \"a\") as myfile:\n myfile.write(\"\\n\")\n myfile.write(f'LEFT_ADDRESS={contract_id}')\n\n return blockNumber\n\n\nl_block = deploy_bridge('LEFT')\nr_block = deploy_bridge('RIGHT')\nprint(f'#5 [LEFT] Bridge deployed at block {l_block}' )\nprint(f'#6 [RIGHT] Bridge deployed at block {r_block}')\nwith open(\".env\", \"a\") as myfile:\n myfile.write(\"\\n\")\n myfile.write(f'LEFT_START_BLOCK={l_block}')\nwith open(\".env\", \"a\") as myfile:\n myfile.write(\"\\n\")\n myfile.write(f'RIGHT_START_BLOCK={r_block}')","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13411757","text":"import os\nimport torch\n\nfrom tqdm import tqdm\nfrom torchvision.datasets import ImageFolder\nfrom torch.utils.data import DataLoader\nfrom src.cnn import *\n\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\nclass AverageMeter(object):\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.avg = 0\n self.sum = 0\n self.cnt = 0\n\n def update(self, val, n=1):\n self.sum += val * n\n self.cnt += n\n self.avg = self.sum / self.cnt\n\ndef accuracy(logits, labels):\n preds = torch.argmax(logits, axis=1)\n return torch.sum(preds == labels) / len(labels)\n\ndef eval_fn(model, loader, device, train=False):\n \"\"\"\n Evaluation method\n :param model: model to evaluate\n :param loader: data loader for either training or testing set\n :param device: torch device\n :param train: boolean to indicate if training or test set is used\n :return: accuracy on the data\n \"\"\"\n score = AverageMeter()\n model.eval()\n\n t = tqdm(loader)\n with torch.no_grad(): # no gradient needed\n for images, labels in t:\n images = images.to(device)\n labels = labels.to(device)\n\n outputs = model(images)\n acc = accuracy(outputs, labels)\n score.update(acc.item(), images.size(0))\n\n t.set_description('(=> Test) Score: {:.4f}'.format(score.avg))\n\n return score.avg\n\ndef eval_model(model, saved_model_file, test_data_dir, data_augmentations):\n model = model.to(device)\n model.load_state_dict(torch.load(os.path.join(os.getcwd(), 'models', saved_model_file)))\n data = ImageFolder(test_data_dir, transform=data_augmentations)\n\n test_loader = DataLoader(dataset=data,\n batch_size=128,\n shuffle=False)\n\n score = eval_fn(model, test_loader, device, train=False)\n\n print('Avg accuracy:', str(score*100) + '%')\n","sub_path":"src/eval/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"352880888","text":"#Author: NWANKWO CHUKWUEBUKA JUSTIN\r\n# Date: 5/24/2016 \r\n\r\n\r\n\"\"\"\r\n Rook Moves:\r\n\"\"\"\r\n\r\n\r\nclass Rook:\r\n def __init__(self, row, col, player_num):\r\n self.row = row\r\n self.col = col\r\n self.first_move = 1\r\n self.symbol = 'R'\r\n self.player_num = player_num\r\n\r\n\r\n\r\n def get_position(self):\r\n return (self.row, self.col)\r\n\r\n def update_first_move(self):\r\n self.first_move = 0\r\n\r\n def get_symbol(self):\r\n return self.symbol\r\n\r\n def is_first_move(self):\r\n return self.first_move\r\n\r\n def move(self, to_row, to_col):\r\n self.row = to_row\r\n self.col = to_col\r\n if(self.first_move):\r\n self.update_first_move()\r\n \r\n\r\n def is_valid(self, piece_positions, from_row, from_col, to_row, to_col): \r\n if((from_row == to_row) and (from_col != to_col)):\r\n is_row_move = 0 # 1 if move is by row else 0 if move is by column\r\n lesser_to_move = 0 # 1 if to_row or to_col is less than from _row or from_col\r\n if(from_col < to_col):\r\n start_index = from_col + 1\r\n stop_index = to_col\r\n \r\n\r\n elif(from_col > to_col):\r\n piece, num = piece_positions.get_piece(to_row, to_col)\r\n if(self.player_num != num):\r\n start_index = to_col + 1\r\n stop_index = from_col\r\n lesser_to_move = 1\r\n else:\r\n return False\r\n\r\n else:\r\n return False\r\n\r\n elif((from_row != to_row) and (from_col == to_col)):\r\n is_row_move = 1 # 1 if move is by row else 0 if move is by column\r\n lesser_to_move = 0 # 1 if to_row or to_col is less than from _row or from_col\r\n if(from_row < to_row):\r\n start_index = from_row + 1\r\n stop_index = to_row\r\n\r\n elif(from_row > to_row):\r\n piece, num = piece_positions.get_piece(to_row, to_col)\r\n if(self.player_num != num):\r\n start_index = to_row + 1\r\n stop_index = from_row\r\n lesser_to_move = 1\r\n else:\r\n return False\r\n\r\n else:\r\n return False\r\n\r\n else:\r\n return False\r\n\r\n\r\n \r\n #piece, num = None, None #Used so that variables dont go out of scope after while loop below \r\n \r\n while(start_index <= stop_index):\r\n if(is_row_move):\r\n piece, num = piece_positions.get_piece(start_index, from_col)\r\n else:\r\n piece, num = piece_positions.get_piece(from_row, start_index)\r\n \r\n if(num != '-'):\r\n break\r\n start_index += 1\r\n\r\n if(start_index < stop_index):\r\n return False\r\n\r\n if(lesser_to_move):\r\n if(num == self.player_num):\r\n return True\r\n else:\r\n return False\r\n\r\n else:\r\n if(num != self.player_num):\r\n return True\r\n else:\r\n return False\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":"RookModule.py","file_name":"RookModule.py","file_ext":"py","file_size_in_byte":3450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"613143091","text":"import requests\nimport os\nimport bs4\nimport re\nimport openpyxl\nfrom openpyxl.comments import Comment\n\nurlbase = 'http://www.abelardoimoveis.com.br/imoveis-tipo-%s-para-locacao-em-blumenau-pg-%s'\nformato_moeda = '_-\"R$\"\\\\ * #,##0.00_-;\\\\-\"R$\"\\\\ * #,##0.00_-;_-\"R$\"\\\\ * \"-\"??_-;_-@_-'\npadrao_um = r\"R\\$\\s*([0-9]*\\.*[0-9]+,[0-9]{2})(\\s[\\wÀ-ú]+)*(\\scondomínio)\"\npadrao_dois = r\"(\\scondomínio)(\\s[\\wÀ-ú:\\.]*)*R\\$\\s*([0-9]*\\.*[0-9]+,[0-9]{2})\"\n\nclass Imovel(object):\n def __init__(self, elemento):\n self.carregar(elemento)\n\n def carregar(self, elemento):\n link = elemento.select('a.visualizar-imovel')[0]\n self.url = 'http://www.abelardoimoveis.com.br' + link['href']\n #print(self.url)\n self.nome = link['title']\n self._carregar_bairro(elemento)\n self._carregar_preco(elemento)\n self._carregar_info(self.url)\n self._carregar_anunciante(elemento)\n\n def _carregar_bairro(self, elemento):\n self.bairro = ''\n endereco = elemento.select('div.endereco-imovel')\n if endereco != []:\n endereco = endereco[0]\n bairro = endereco.get_text().strip()\n span = endereco.select('span')\n if span != []:\n bairro = bairro.replace(span[0].get_text().strip(), '')\n bairro = bairro.replace('Blumenau -', '').strip()\n self.bairro = bairro\n\n def _carregar_preco(self, elemento):\n self.preco = 0\n self.preco_str = elemento.select('strong.preco-imovel')[0].get_text().strip()\n try:\n self.preco = float(self.preco_str.replace('.', '').replace(',', '.'))\n except:\n self.preco = 0\n\n def _carregar_info(self, url):\n self.quartos = 0\n self.vagas = 0\n self.metros = 0\n self.suites = 0\n self.condominio = 0\n res = requests.get(url)\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, 'html.parser')\n\n dormitorios = soup.select('div.dormitorios div.quantidade')\n if dormitorios != []:\n self.quartos = int(dormitorios[0].get_text().strip())\n suites = soup.select('div.suites div.quantidade')\n if suites != []:\n self.suites = int(suites[0].get_text().strip())\n garagens = soup.select('div.garagens div.quantidade')\n if garagens != []:\n self.vagas = int(garagens[0].get_text().strip())\n areaprivada = soup.select('div.areaprivada div.quantidade')\n if areaprivada != []:\n self.metros = float(areaprivada[0].get_text().strip())\n self._carregar_condominio(soup)\n \n def _carregar_condominio(self, soup):\n resumo = soup.select('div.resumo-imovel')\n if resumo != []:\n texto = resumo[0].get_text()\n busca = re.findall(padrao_um, texto, re.I)\n if busca != []:\n self.condominio = float(busca[0][0].replace('.','').replace(',','.'))\n else:\n busca = re.findall(padrao_dois, texto, re.I)\n if busca != []:\n self.condominio = float(busca[0][-1].replace('.','').replace(',','.'))\n\n def _carregar_anunciante(self, elemento):\n self.anunciante = 'Abelardo'\n\n def __str__(self):\n return self.nome\n\n def __repr__(self):\n return self.nome\n\n\nclass Abelardo(object):\n def __init__(self, tipo):\n self.tipo = tipo\n\n def get_url(self, pagina):\n return urlbase % (self.tipo, pagina)\n\n def get_numero_de_paginas(self):\n url = self.get_url(1)\n res = requests.get(url)\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, 'html.parser')\n paginas = soup.select('ul.nav-paginas li a')[-2].get_text()\n return int(paginas)\n\n def get_imoveis(self):\n imoveis = []\n numero_de_paginas = self.get_numero_de_paginas()\n for i in range(1, numero_de_paginas + 1):\n url = self.get_url(i)\n res = requests.get(url)\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, 'html.parser')\n articles = soup.select('div.imovel')\n if articles != []:\n for article in articles:\n imovel = Imovel(article)\n imoveis.append(imovel)\n return imoveis\n\nif __name__ == \"__main__\":\n rem = Abelardo('apartamento')\n imoveis = rem.get_imoveis()\n wb = openpyxl.load_workbook(filename='imoveis.xlsx', read_only=False)\n sheet = wb['imoveis']\n linha = 2\n for imovel in imoveis:\n cell = sheet.cell(row=linha, column=1)\n cell.value = imovel.nome\n cell = sheet.cell(row=linha, column=2)\n cell.value = imovel.bairro\n cell = sheet.cell(row=linha, column=3)\n cell.number_format = formato_moeda \n cell.value = imovel.preco\n if imovel.preco == 0:\n cell.comment = Comment('Preço: ' + imovel.preco_str, '')\n cell = sheet.cell(row=linha, column=4)\n cell.number_format = formato_moeda \n cell.value = imovel.condominio\n cell = sheet.cell(row=linha, column=5)\n cell.value = imovel.quartos\n cell = sheet.cell(row=linha, column=6)\n cell.value = imovel.vagas\n cell = sheet.cell(row=linha, column=7)\n cell.value = imovel.metros\n cell = sheet.cell(row=linha, column=8)\n cell.value = imovel.suites\n cell = sheet.cell(row=linha, column=9)\n cell.value = imovel.anunciante\n cell = sheet.cell(row=linha, column=10)\n cell.value = 'Abrir'\n cell.hyperlink = imovel.url\n linha = linha + 1\n wb.save('resultado_abelardo.xlsx')","sub_path":"abelardo.py","file_name":"abelardo.py","file_ext":"py","file_size_in_byte":5684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"631335907","text":"#!/usr/bin/env python3\n\nimport asyncio\nimport json\nimport time\nfrom datetime import datetime\nimport logging\nfrom typing import List, Dict, Optional, Any, Iterable\n\nfrom .mssql import mssql, types_map\nimport pymssql\n\nfrom asyncdb.exceptions import (\n ConnectionTimeout,\n DataError,\n EmptyStatement,\n NoDataFound,\n ProviderError,\n StatementError,\n TooManyConnections,\n)\nfrom asyncdb.providers import (\n BaseProvider,\n registerProvider,\n)\nfrom asyncdb.utils import (\n EnumEncoder,\n SafeDict,\n)\n\nfrom asyncdb.providers.sql import SQLProvider, baseCursor\n\n\nclass sqlserverCursor(baseCursor):\n _connection = None\n\n async def __aenter__(self) -> \"sqlserverCursor\":\n if not self._connection:\n await self.connection()\n self._cursor = self._connection.cursor()\n try:\n self._cursor.execute(self._sentence, self._params)\n except (pymssql.StandardError, pymssql.Error) as err:\n print(err)\n error = \"SQL Server Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n print(err)\n raise\n finally:\n return self\n\n async def __anext__(self):\n \"\"\"Use `cursor.fetchone()` to provide an async iterable.\"\"\"\n row = await self.fetchone()\n if row is not None:\n return row\n else:\n raise StopAsyncIteration\n\n async def fetchone(self) -> Optional[Dict]:\n return self._cursor.fetchone()\n\n async def fetchmany(self, size: int = None) -> Iterable[List]:\n return self._cursor.fetchmany(size)\n\n async def fetchall(self) -> Iterable[List]:\n return self._cursor.fetchall()\n\n\nclass sqlserver(mssql):\n \"\"\"sqlserver.\n\n Microsoft SQL Server using DB-API connection\n \"\"\"\n\n _provider = \"sqlserver\"\n\n async def connection(self):\n \"\"\"\n Get a connection\n \"\"\"\n self._connection = None\n self._connected = False\n try:\n self._params[\"appname\"] = self.application_name\n self._params[\"as_dict\"] = True\n self._params[\"timeout\"] = self._timeout\n self._params[\"charset\"] = self._charset.upper()\n self._params[\"tds_version\"] = \"8.0\"\n self._connection = pymssql.connect(**self._params)\n if self._connection:\n self._connected = True\n self._initialized_on = time.time()\n if 'database' in self._params:\n self.use(self._params[\"database\"])\n except Exception as err:\n print(err)\n self._connection = None\n self._cursor = None\n raise ProviderError(\"connection Error, Terminated: {}\".format(str(err)))\n finally:\n return self\n\n def use(self, dbname: str = \"\"):\n try:\n self._cursor = self._connection.cursor()\n self._cursor.execute(f\"USE {dbname!s}\")\n except pymssql.Warning as warn:\n logging.warning(f\"SQL Server Warning: {warn!s}\")\n error = warn\n except (pymssql.StandardError, pymssql.Error) as err:\n error = \"SQL Server Error: {}\".format(str(err))\n raise ProviderError(error)\n return self\n\n async def execute(self, sentence=\"\", params: dict = {}):\n \"\"\"\n Execute a sentence\n \"\"\"\n error = None\n self._result = None\n if not sentence:\n raise EmptyStatement(\"Error: Empty Sentence\")\n if not self._connection:\n await self.connection()\n # getting a cursor\n try:\n self._cursor = self._connection.cursor()\n self._result = self._cursor.execute(sentence, *params)\n # self._connection.commit()\n except pymssql.Warning as warn:\n logging.warning(f\"SQL Server Warning: {warn!s}\")\n error = warn\n except (pymssql.StandardError, pymssql.Error) as err:\n error = \"SQL Server Error: {}\".format(str(err))\n raise ProviderError(error)\n except RuntimeError as err:\n error = \"Runtime Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n error = \"Error on Query: {}\".format(str(err))\n raise Exception(error)\n finally:\n logging.debug(error)\n return [self._result, error]\n\n async def executemany(self, sentence=\"\", params: list = []):\n \"\"\"\n Execute multiple sentences\n \"\"\"\n \"\"\"\n Execute a sentence\n \"\"\"\n error = None\n self._result = None\n if not sentence:\n raise EmptyStatement(\"Error: Empty Sentence\")\n if not self._connection:\n await self.connection()\n # getting a cursor\n try:\n self._cursor = self._connection.cursor()\n self._result = self._cursor.executemany(sentence, params)\n # self._connection.commit()\n except pymssql.Warning as warn:\n logging.warning(f\"SQL Server Warning: {warn!s}\")\n error = warn\n except (pymssql.StandardError, pymssql.Error) as err:\n error = \"SQL Server Error: {}\".format(str(err))\n raise ProviderError(error)\n except RuntimeError as err:\n error = \"Runtime Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n error = \"Error on Query: {}\".format(str(err))\n raise Exception(error)\n finally:\n # self._connection.commit()\n print(error)\n return [self._result, error]\n\n async def query(self, sentence=\"\", params: list = None):\n \"\"\"\n Making a Query and return result\n \"\"\"\n error = None\n self._result = None\n if not sentence:\n raise EmptyStatement(\"Error: Empty Sentence\")\n if not self._connection:\n await self.connection()\n if isinstance(sentence, str):\n sentence = sentence.encode(self._charset)\n try:\n startTime = datetime.now()\n self._cursor = self._connection.cursor()\n self._cursor.execute(sentence, params)\n self._result = self._cursor.fetchall()\n if not self._result:\n raise NoDataFound(\"SQL Server: No Data was Found\")\n return [None, \"SQL Server: No Data was Found\"]\n except (pymssql.StandardError, pymssql.Error) as err:\n error = \"SQL Server Error: {}\".format(str(err))\n raise ProviderError(error)\n except RuntimeError as err:\n error = \"Runtime Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n error = \"Error on Query: {}\".format(str(err))\n raise Exception(error)\n finally:\n self._generated = datetime.now() - startTime\n return [self._result, error]\n\n async def queryrow(self, sentence=\"\"):\n cursor.execute(\"SELECT * FROM persons WHERE salesrep=%s\", \"John Doe\")\n row = cursor.fetchone()\n\n async def fetchone(self, sentence=\"\", params: list = []):\n error = None\n self._result = None\n if not sentence:\n raise EmptyStatement(\"Error: Empty Sentence\")\n if not self._connection:\n await self.connection()\n try:\n startTime = datetime.now()\n self._cursor = self._connection.cursor()\n self._cursor.execute(sentence, *params)\n self._result = self._cursor.fetchone()\n if not self._result:\n raise NoDataFound(\"SQL Server: No Data was Found\")\n return [None, \"SQL Server: No Data was Found\"]\n except RuntimeError as err:\n error = \"Runtime Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n error = \"Error on Query: {}\".format(str(err))\n raise Exception(error)\n finally:\n self._generated = datetime.now() - startTime\n return [self._result, error]\n\n async def fetch(self, sentence=\"\", size: int = 1, params: list = []):\n error = None\n self._result = None\n if not sentence:\n raise EmptyStatement(\"Error: Empty Sentence\")\n if not self._connection:\n await self.connection()\n try:\n startTime = datetime.now()\n self._cursor = self._connection.cursor()\n self._cursor.execute(sentence, *params)\n self._result = self._cursor.fetchmany(size)\n if not self._result:\n raise NoDataFound(\"SQL Server: No Data was Found\")\n return [None, \"SQL Server: No Data was Found\"]\n except RuntimeError as err:\n error = \"Runtime Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n error = \"Error on Query: {}\".format(str(err))\n raise Exception(error)\n finally:\n self._generated = datetime.now() - startTime\n return [self._result, error]\n\n\n\"\"\"\nRegistering this Provider\n\"\"\"\nregisterProvider(sqlserver)\n","sub_path":"asyncdb/providers/sqlserver.py","file_name":"sqlserver.py","file_ext":"py","file_size_in_byte":9235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"650998179","text":"#!python3\r\nimport discord, asyncio, sqlite3, modules.channel\r\nimport config\r\nfrom discord.ext import commands\r\n\r\nclass Roles:\r\n ### Fields ###\r\n def __init__(self, client):\r\n self.client = client\r\n print(\"Module {} loaded\".format(self.__class__.__name__))\r\n\r\n ### Helper Functions ###\r\n # Find a role in the server\r\n def find(self, name, context):\r\n ret = None\r\n for role in context.guild.roles:\r\n if role.name == name: ret = role\r\n return ret\r\n\r\n # Find if an argument is a Chapter\r\n def isChapter(self, s):\r\n ret = True\r\n try: \r\n int(s)\r\n except ValueError:\r\n ret = False\r\n return ret\r\n\r\n # Remove chapter roles\r\n async def strip_chapter_roles(self, context, prefix):\r\n for role in context.message.author.roles:\r\n if role.name.startswith(prefix):\r\n await context.author.remove_roles(role)\r\n break\r\n\r\n # Remove route ro les\r\n async def strip_route_roles(self, context, suffix):\r\n for role in context.message.author.roles:\r\n if role.name.endswith(suffix):\r\n await context.author.remove_roles(role)\r\n\r\n ### Commands ###\r\n # Handling Chapter / Route finishing\r\n @commands.command(pass_context=True)\r\n async def chapter(self, context, arg: str):\r\n # The difference between Chapter and Route is that routes are not completed linearly. Chapters are also numbered from 1 to whatever\r\n\r\n # Loading info from the config\r\n chapter_prefix, route_prefix = modules.channel.Channel(self.client).fetch_guild_info(context, 'Chapter_prefix', 'Route_prefix')\r\n\r\n # if we have a chapter\r\n if self.isChapter(arg):\r\n # remove previous chapter roles\r\n await self.strip_chapter_roles(context, chapter_prefix)\r\n match = chapter_prefix + ' {}' # String we are going to find a role with\r\n c = modules.channel.Channel(self.client) # To check if the user has a channel\r\n channel = discord.utils.find(lambda cha: cha.id == c.owns(context), context.message.guild.text_channels)\r\n if channel is not None: # if he has a channel\r\n overwrites = c.set_chapter_perms(int(arg), context, False) # Block permissions up until the chapter he just completed\r\n for role, perm in overwrites.items():\r\n await channel.set_permissions(role, overwrite=perm)\r\n \r\n else: # If we have a route\r\n arg = arg.capitalize()\r\n match = '{} ' + route_prefix\r\n\r\n target_role = self.find(match.format(arg), context)\r\n if target_role is not None:\r\n await context.author.add_roles(target_role)\r\n await context.send(\"Successfully added the {} role.\".format(target_role.name))\r\n else:\r\n await context.send(\"Role not found.\")\r\n\r\n # Handling Game finishing\r\n @commands.command(pass_context=True)\r\n async def finished(self, context, *, game: str):\r\n # Getting the role for the game\r\n self.client.cursor.execute(\"SELECT Role_Name, Progress FROM Game JOIN Game_Alias ON Game.Name = Game_Alias.Game_Name WHERE Game.Name = ? OR Game_Alias.Alias = ?\", (game, game,))\r\n role = self.client.cursor.fetchone()\r\n if role: # if it exists\r\n target_role = self.find(role[0], context)\r\n if target_role is not None: # If it exists in the server\r\n # Loading info from the config\r\n chapter_prefix, route_prefix = modules.channel.Channel(self.client).fetch_guild_info(context, 'Chapter_prefix', 'Route_prefix')\r\n # remove any other progression roles if the game is progressable\r\n if role[1] == 1:\r\n await self.strip_chapter_roles(context, chapter_prefix)\r\n await self.strip_route_roles(context, route_prefix)\r\n # add the new role\r\n await context.message.author.add_roles(target_role)\r\n await context.send(\"Successfully added the {} role.\".format(target_role.name))\r\n else:\r\n await context.send(\"Role {} not found, which should not be the case. Contact someone who is administrating the server to add it.\".format(role))\r\n else:\r\n await context.send(\"Game {} not found\".format(game))\r\n\r\ndef setup(client):\r\n client.add_cog(Roles(client))","sub_path":"modules/roles.py","file_name":"roles.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"465767186","text":"import os\nfrom appium import webdriver\nfrom selenium import webdriver as sel_webdriver\n\nclass AppiumHandler():\n\n def __init__(self, phoneIdentifier, appiumPort):\n desired_caps = {}\n desired_caps['platformName'] = 'Android'\n desired_caps['deviceName'] = 'Telefon'\n desired_caps['appPackage'] = 'com.huuuge.stars.slots'\n desired_caps['appActivity'] = 'com.huuuge.casino.BootActivity'\n desired_caps['udid'] = phoneIdentifier\n self.driver = webdriver.Remote('http://localhost:{}/wd/hub'.format(appiumPort), desired_caps)\n self.endLogcat()\n\n def getScreenshot(self, path = None):\n if path == None:\n path = 'temp.png'\n self.driver.get_screenshot_as_file(path)\n return path\n else:\n self.driver.get_screenshot_as_file(path)\n return path\n\n def endLogcat(self):\n self.driver.execute_script('mobile:stopLogsBroadcast')\n","sub_path":"engine/appium_helper.py","file_name":"appium_helper.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"75445582","text":"##################208. 实现 Trie (前缀树)########################################\n# 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。\n# 示例:\n# Trie trie = new Trie();\n# trie.insert(\"apple\");\n# trie.search(\"apple\"); // 返回 true\n# trie.search(\"app\"); // 返回 false\n# trie.startsWith(\"app\"); // 返回 true\n# trie.insert(\"app\");\n# trie.search(\"app\"); // 返回 true\n# 说明:\n# 你可以假设所有的输入都是由小写字母 a-z 构成的。\n# 保证所有输入均为非空字符串。\nclass Trie(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root ={}\n self.end_of_word = \"#\"\n\n def insert(self, word):\n \"\"\"\n Inserts a word into the trie.\n :type word: str\n :rtype: None\n \"\"\"\n cur_node = self.root\n for c in word:\n if c not in cur_node:\n cur_node[c] = {}\n cur_node = cur_node[c]\n cur_node[self.end_of_word] = self.end_of_word\n\n def search(self, word):\n \"\"\"\n Returns if the word is in the trie.\n :type word: str\n :rtype: bool\n \"\"\"\n cur_node = self.root\n for c in word:\n if c not in cur_node:\n return False\n cur_node = cur_node[c]\n if self.end_of_word not in cur_node:\n return False\n return True\n\n def startsWith(self, prefix):\n \"\"\"\n Returns if there is any word in the trie that starts with the given prefix.\n :type prefix: str\n :rtype: bool\n \"\"\"\n cur_node = self.root\n for c in prefix:\n if c not in cur_node:\n return False\n cur_node = cur_node[c]\n return True\n\nt = Trie()\nt.insert(\"abcd\")\nt.insert(\"adcd\")\nprint(t.search(\"abc\"))\nprint(t.startsWith(\"abc\"))\nprint(t.root)\n","sub_path":"python_data_structure/tree/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"578340170","text":"import sys\nimport util\n\n\nif len(sys.argv) != 5:\n sys.exit('Error! Invalid number of arguments. Expected 3')\n\nif sys.argv[1] != 'ExtractProfiles':\n sys.exit('Error! Invalid operation. Expected \"ExtractProfiles\"')\n\nprofiles = util.extract_profiles(sys.argv[2])\n\nutil.write_profiles(sys.argv[3], profiles['users'])\nutil.write_profiles(sys.argv[4], profiles['items'])\n","sub_path":"Part1.py","file_name":"Part1.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"551642644","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# 我们先写一个计算x2的函数:\n# def power(x):\n# return x * x\n\n# 现在,如果我们要计算x3怎么办?可以再定义一个power3函数,但是如果要计算x4、x5……怎么办?我们不可能定义无限多个函数。\n# 你也许想到了,可以把power(x)修改为power(x, n),用来计算xn,说干就干:\ndef power(x, n = 2):\n s = 1\n while n > 0:\n n = n - 1\n s = s * x\n return s\n\n# 这样,当我们调用power(5)时,相当于调用power(5, 2):\n# 而对于n > 2的其他情况,就必须明确地传入n,比如power(5, 3)\n\n\n# 默认参数很有用,但使用不当,也会掉坑里。默认参数有个最大的坑,演示如下:\n# 先定义一个函数,传入一个list,添加一个END再返回:\ndef add_end(L = []):\n L.append('END')\n return L\n\n# 正常调用时,结果似乎不错:\nadd_end([1, 2, 3])\nadd_end(['x', 'y', 'z'])\n\n# 使用默认参数调用时,一开始结果也是对的:\nadd_end()\n# 再次调用add_end()时,结果就不对了:\nadd_end()\nadd_end()\n\n# 很多初学者很疑惑,默认参数是[],但是函数似乎每次都“记住了”上次添加了'END'后的list。\n# 原因解释如下:Python函数在定义的时候,默认参数L的值就被计算出来了,即[],因为默认参数L也是一个变量,它指向对象[],每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。\n\n# 定义默认参数要牢记一点:默认参数必须指向不变对象!\n\n# 要修改上面的例子,我们可以用None这个不变对象来实现:\ndef add_end_new(L = None):\n if L is None:\n L = []\n L.append('END')\n return L\n\n# 为什么要设计str、None这样的不变对象呢?因为不变对象一旦创建,对象内部的数据就不能修改,这样就减少了由于修改数据导致的错误。\n# 此外,由于对象不变,多任务环境下同时读取对象不需要加锁,同时读一点问题都没有。我们在编写程序时,如果可以设计一个不变对象,那就尽量设计成不变对象。\n\n\n\n# 可变参数\n# 在Python函数中,还可以定义可变参数。顾名思义,可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个。\n# 我们以数学题为例子,给定一组数字a,b,c……,请计算a2 + b2 + c2 + ……。\n# 要定义出这个函数,我们必须确定输入的参数。由于参数个数不确定,我们首先想到可以把a,b,c……作为一个list或tuple传进来,这样,函数可以定义如下:\ndef calc(numbers):\n sum = 0\n for n in numbers:\n sum = sum + n * n\n return sum\n\n# 但是调用的时候,需要先组装出一个list或tuple:\nprint(calc([1, 2, 3]))\nprint(calc((1, 3, 5, 7)))\n\n# 把函数的参数改为可变参数:\ndef calc_new(*numbers):\n sum = 0\n for n in numbers:\n sum = sum + n * n\n return sum\n\n# 定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。\n# 在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数:\nprint(calc_new(1, 2))\nprint(calc_new())\n# 如果已经有一个list或者tuple,要调用一个可变参数怎么办?可以这样做\nnums = [1, 2, 3]\nprint(calc_new(nums[0], nums[1], nums[2]))\n\n\n# 关键字参数\n# 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。\n# 而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。请看示例:\ndef person(name, age, **kw):\n print('name:', name, 'age:', age, 'other:', kw)\n\n# 函数person除了必选参数name和age外,还接受关键字参数kw。在调用该函数时,可以只传入必选参数:\nprint(person('Michael', 30))\n# 也可以传入任意个数的关键字参数:\nprint(person('Bob', 35, city='Beijing'))\nprint(person('Adam', 45, gender='M', job='Engineer'))\n\n# 关键字参数有什么用?它可以扩展函数的功能。比如,在person函数里,我们保证能接收到name和age这两个参数,但是,如果调用者愿意提供更多的参数,我们也能收到。\n# 试想你正在做一个用户注册的功能,除了用户名和年龄是必填项外,其他都是可选项,利用关键字参数来定义这个函数就能满足注册的需求。\n# 和可变参数类似,也可以先组装出一个dict,然后,把该dict转换为关键字参数传进去:\n\n\n# 命名关键字参数\n# 如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city和job作为关键字参数。这种方式定义的函数如下:\ndef person_test1(name, age, *, city, job):\n print(name, age, city, job)\n\nprint(person('Jack', 24, city='Beijing', job='Engineer'))\n\n# 命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错:\n\n# 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了:\ndef person_test2(name, age, *args, city, job):\n print(name, age, args, city, job)","sub_path":"src/weicools/c02_func/f03_func_params/practice_func_params.py","file_name":"practice_func_params.py","file_ext":"py","file_size_in_byte":5430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"32824625","text":"from django import forms\nfrom .models import Product\n\nclass ProductForm(forms.ModelForm):\n title=forms.CharField()\n # email=forms.EmailField()\n description=forms.CharField(required=False,widget=forms.Textarea(attrs={\n \"class\":\"new-class-name two\",\n \"rows\":2,\n \"cols\":20,\n \"placeholder\":\"your description\"\n\n }))\n price=forms.FloatField(initial=99.99)\n class Meta:\n model=Product\n fields=[\n 'title',\n 'description',\n 'price'\n ]\n\n # def clean_title(self,*args,**kwargs):\n # title=self.cleaned_data.get(\"title\")\n # if \"karan\" in title:\n # return title\n # else:\n # raise forms.ValidationError(\"this is not a valid title\")\n\n # def clean_email(self,*args,**kwargs):\n # email=self.cleaned_data.get(\"email\")\n # if not email.endswith(\"com\"):\n # raise forms.ValidationError(\"this is not a valid email\")\n # return email\n\nclass RawProductForm(forms.Form):\n title=forms.CharField()\n description=forms.CharField(required=False,widget=forms.Textarea(attrs={\n \"class\":\"new-class-name two\",\n \"rows\":2,\n \"cols\":20,\n \"placeholder\":\"your description\"\n\n }))\n price=forms.FloatField(initial=99.99)\n","sub_path":"django/Django_project/products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"133609576","text":"#!/usr/bin/env python\n\"\"\" Validate regulon prediction with gene expression bicluster results\"\"\"\n\ndef read_regulon(file=\"./regulon_by_first_gene.txt\"):\n \"\"\" regulon as hash of set \"\"\"\n rv = {}\n reg_now = ''\n\n datafile = open(file)\n for line in datafile:\n line = line.rstrip('\\n\\r')\n if line.startswith('>'):\n reg_now = line[1:]\n else:\n # at least 2 operons in a regulon to deal with\n if len(line.lstrip().split()) > 1:\n rv[reg_now] = set(line.lstrip().split())\n\n return rv\n\ndef read_mcl(file):\n \"\"\" mcl clusters as list of set \"\"\"\n rv = []\n\n count = 0\n\n datafile = open(file)\n for line in datafile:\n count = count + 1\n line = line.rstrip()\n\n opr_set = set()\n\n for motif in line.split():\n items = motif.split('_')\n opr = items[0]\n opr_set.add(opr)\n\n rv.append(opr_set)\n\n return rv\n\ndef read_bicluster(f):\n \"\"\" read biclusters as list of sets \"\"\"\n rv = []\n\n fin = open(f)\n cur_cluster = ''\n for line in fin:\n line = line.rstrip()\n if line.startswith('BC'): cur_cluster = line\n if cur_cluster and line.startswith(\" Gene\"):\n genes = line.split(' ')\n genes = genes[3:]\n genes = [g.split('_')[1] for g in genes]\n rv.append(set(genes))\n return rv\n\ndef read_bicluster_positive(f):\n \"\"\" read biclusters as list of sets, only keep positive set \"\"\"\n rv = []\n\n fin = open(f)\n cur_cluster = ''\n cur_gene_set = set()\n for line in fin:\n line = line.rstrip()\n if line.startswith('BC'): \n cur_cluster = line\n if cur_gene_set: rv.append(cur_gene_set)\n cur_gene_set = set()\n continue\n\n if line == '': \n cur_cluster = ''\n continue\n\n if cur_cluster and line.startswith(\" Gene\"): continue\n if cur_cluster and line.startswith(\" Conds\"): continue\n if cur_cluster:\n g = line.split('\\t')[0]\n g = g.split('_')[1]\n cur_gene_set.add(g)\n\n return rv\n\ndef ppt_b2gi(file='NC_000913.ptt'):\n ''' read ppt file, return bnum to gi'''\n fin = open(file)\n fin.readlines(3)\n rv = {}\n for line in fin:\n line = line.rstrip()\n items = line.split(\"\\t\")\n rv[ items[5] ] = items[3]\n\n return rv\n\ndef opr_gi2set(file='NC_000913.opr'):\n ''' read opr file, return ang gi to the opr gi set it is in'''\n fin = open(file)\n rv = {}\n for l in fin:\n l = l.rstrip()\n gs = l.split('\\t')[1]\n gs = gs.split(' ')\n\n gis = []\n for g in gs:\n if g.find('-') == -1:\n gis.append(g)\n\n\n for gi in gis:\n rv[gi] = set(gis)\n\n return rv\n\n\n\n\nif __name__ == \"__main__\":\n from pprint import pprint\n from scipy.stats import hypergeom\n import sys\n import math \n\n exp_f = \"co-expression-validation-09072014/avg_E_coli_v4_Build_6_exps466probes4297.tab.blocks.default\"\n\n if len(sys.argv) != 5:\n print(\"python %s \" %\n sys.argv[0])\n sys.exit(-1);\n\n exp_f = sys.argv[1];\n cluster_f = sys.argv[2];\n clusters = read_mcl(cluster_f)\n #clusters = read_mcl(\"bbs_cluster.mcl\")\n\n GENE_COUNT = 4146\n P_CUTOFF = 1e-5\n\n biclu = read_bicluster(exp_f)\n bic_p = read_bicluster_positive(exp_f)\n b2gi = ppt_b2gi()\n\n # bicluster from bnum to gi\n biclusters = []\n for clu in biclu:\n gis = [b2gi[b] for b in clu if b2gi.has_key(b)]\n biclusters.append(set(gis))\n\n biclusters_p = []\n for clu in bic_p:\n gis = [b2gi[b] for b in clu if b2gi.has_key(b)]\n biclusters_p.append(set(gis))\n\n opr = opr_gi2set()\n\n clu_index = 0\n for clu in clusters:\n clu_index += 1\n if clu_index > 100: break\n clu_set = set()\n # transfer cluster from operon set to gene set\n for gi in clu:\n clu_set.add(gi)\n if opr.has_key(gi):\n clu_set.update(opr[gi])\n\n clu_sig_score = 0\n clu_sig_smallest = -1;\n for bic in biclusters:\n bic_size = len(bic)\n clu_size = len(clu_set)\n overlap = len(bic & clu_set)\n\n\n hyper = hypergeom(GENE_COUNT, bic_size, clu_size)\n hypersf = hyper.sf(overlap)\n #print(\"%d\\t%d\\t%d\\t%.3f\" % (bic_size, clu_size, overlap, hypersf))\n if clu_sig_smallest < 0:\n clu_sig_smallest = hypersf\n elif clu_sig_smallest > hypersf:\n clu_sig_smallest = hypersf\n\n\n if hypersf < P_CUTOFF:\n if hypersf <= 0: hypersf = P_CUTOFF\n clu_sig_score += -math.log10(hypersf)\n\n clu_sig_score_p = 0\n clu_sig_smallest_p = -1;\n for bic in biclusters_p:\n bic_size = len(bic)\n clu_size = len(clu_set)\n overlap = len(bic & clu_set)\n\n\n hyper = hypergeom(GENE_COUNT, bic_size, clu_size)\n hypersf = hyper.sf(overlap)\n #print(\"%d\\t%d\\t%d\\t%.3f\" % (bic_size, clu_size, overlap, hypersf))\n\n if clu_sig_smallest_p < 0:\n clu_sig_smallest_p = hypersf\n elif clu_sig_smallest_p > hypersf:\n clu_sig_smallest_p = hypersf\n\n if hypersf < P_CUTOFF:\n if hypersf <= 0: hypersf = P_CUTOFF\n clu_sig_score_p += -math.log10(hypersf)\n\n print(\"%d\\t%.3e\\t%.3e\\t%.3f\\t%.3f\\t%s\\t%s\" % (clu_index, \n clu_sig_smallest,\n clu_sig_smallest_p,\n clu_sig_score,\n clu_sig_score_p, \n sys.argv[3],\n sys.argv[4]))\n\n\n\n\n","sub_path":"results/2014-09-09_validate_microarray/bicluster_validation.py","file_name":"bicluster_validation.py","file_ext":"py","file_size_in_byte":5678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"227268064","text":"from django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom fobi.base import BaseFormFieldPluginForm, get_theme\n\ntheme = get_theme(request=None, as_instance=True)\n\n\nclass TimeStopForm(forms.Form, BaseFormFieldPluginForm):\n \"\"\"TimeStopForm.\"\"\"\n\n plugin_data_fields = [\n (\"label\", \"What is the stop time of this survey?\"),\n (\"name\", \"name\"),\n (\"help_text\", \"If this question is left blank, end time will be \"\n \"recorded as the time the survey is submitted.\"),\n (\"required\", False),\n ]\n\n label = forms.CharField(label=\"Question text\",\n required=True,\n help_text=\"If this question is left blank or \"\n \"not included, end time will be recorded as \"\n \"the time the survey is submitted.\")\n\n name = forms.CharField(required=True, widget=forms.widgets.HiddenInput())\n\n help_text = forms.CharField(label=_(\"Help text\"),\n required=False,\n widget=forms.widgets.Textarea(\n attrs={'class': theme.form_element_html_class}),\n help_text=\"This text will show up under the \\\n question and provide the \\\n survey taker with additional \\\n information.\"\n )\n\n required = forms.BooleanField(label=\"Required\",\n required=False,\n help_text=\"Is answering this question required to submit the survey?\")\n","sub_path":"fobi_custom/plugins/form_elements/fields/metadata/time_stop/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"328015378","text":"\"\"\"\nTwo method:\n1. convert number to string and test whether 00 or 11 in it\n2. fetch the right most digit one by one\n\"\"\"\nclass Solution(object):\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n isOne = None\n while n:\n if isOne == bool(n & 1):\n return False\n else:\n isOne = bool(n & 1)\n n >>= 1\n return True\n","sub_path":"solution/python/693.py","file_name":"693.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"68565987","text":"def find(a, v):\n remove = 0\n canRemove = False\n array_remove = [0, 0]\n n = len(a)\n index = (n - 1) // 2\n \n if a[index][index] == v:\n return(index, index)\n elif a[index][index] >= v:\n direction = -1\n elif a[index][index] <= v:\n direction = 1\n \n index += direction\n while index < n and index >= 0:\n if canRemove == True:\n remove += 1\n if a[index][index - remove] == v:\n return(index, index - remove)\n if a[index - remove][index] == v:\n return(index - remove, index) \n \n if a[index][index] == v:\n return(index, index)\n elif a[index][index] >= v:\n if direction == 1:\n canRemove = True\n remove = 1\n nums = array_search(a, v, 0, index - 1, index, array_remove)\n if type(nums) is list:\n if nums[0] > array_remove[0]:\n array_remove[0] = nums[0]\n if nums[1] > array_remove[1]:\n array_remove[1] = nums[1]\n else:\n return nums\n elif a[index][index] <= v:\n if direction == -1:\n canRemove = True\n remove = 1\n nums = array_search(a, v, index + 1, n - 1, index, array_remove)\n if type(nums) is list:\n if nums[0] > array_remove[0]:\n array_remove[0] = nums[0]\n if nums[1] > array_remove[1]:\n array_remove[1] = nums[1]\n else:\n return nums\n index += direction\n return None\n \ndef array_search(a, v, start, end, c, a_rem):\n remove1 = 0\n start1 = start\n end1 = end - a_rem[0]\n while start1 <= end1:\n mid = (start1 + end1) // 2\n if a[c][mid] == v:\n return (c, mid)\n elif a[c][mid] >= v:\n if end1 - mid > remove1:\n remove1 = end1 - mid\n end1 = mid - 1\n elif a[c][mid] <= v:\n start1 = mid +1\n \n remove2 = 0\n start2 = start\n end2 = end - a_rem[1]\n while start2 <= end2:\n mid = (start2 + end2) // 2\n if a[mid][c] == v:\n return (mid, c)\n elif a[mid][c] >= v:\n if end2 - mid > remove2:\n remove2 = end2 - mid\n end2 = mid - 1\n elif a[mid][c] <= v:\n start2 = mid +1\n \n return [remove1, remove2]\n\nA = [[19, 30, 31, 45, 57], [25, 32, 32, 51, 69], [33, 35, 38, 58, 78], [34, 49, 67, 84, 102], [44, 54, 73, 90, 115]]\nB = [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]]\nprint(find(B, 19)) # (0, 0)\nprint(find(A, 80)) # None\nprint(find(B, 30)) # (0, 1)\nprint(find(A, 54)) # (4, 1)\nprint(find(A, 75)) # None\nprint(find(B, 32)) # (1, 1)\nprint(find(A, 115)) # (4, 4)","sub_path":"KSI_18-19/Uloha - 10B/binary_search_3.0.py","file_name":"binary_search_3.0.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"340981597","text":"import bleach\nfrom bleach_whitelist.bleach_whitelist import all_styles, markdown_attrs, markdown_tags\nfrom django import template\nfrom django.template.defaultfilters import stringfilter\nfrom django.utils.safestring import mark_safe\nfrom markdown import markdown as markdown_render\n\nfrom .. import make_escape_function\n\nregister = template.Library()\n\n\n@register.filter(needs_autoescape=True)\n@stringfilter\ndef anti_spamize(email, autoescape=True):\n \"\"\"\n Filter to turn email addresses into HTML entity encoded mailto links.\n\n Args:\n email (str): The email to encode. The encoded email will be the link's\n href value and text.\n autoescape (bool): Whether or not this template tag should escape blurb\n before inserting hashtag link markup.\n\n \"\"\"\n esc = make_escape_function(autoescape)\n\n def encode(value):\n return \"\".join([\"&#x{:x};\".format(ord(char)) for char in value])\n\n result = '{text}'.format(\n link=encode(\"mailto:{}\".format(esc(email))), text=encode(esc(email))\n )\n return mark_safe(result)\n\n\n@register.simple_tag(takes_context=True)\ndef fullurl(context, path):\n request = context[\"request\"]\n return request.build_absolute_uri(path)\n\n\n@register.filter\ndef markdown(text):\n tags = markdown_tags + [\"pre\"]\n attrs = {**markdown_attrs, **{\"div\": [\"class\"], \"span\": [\"class\"], \"img\": [\"class\", \"srcset\"]}}\n ext_opts = {\"codehilite\": {\"css_class\": \"syntax\"}}\n rendered = markdown_render(\n text, extensions=[\"codehilite\", \"fenced_code\", \"footnotes\"], extension_configs=ext_opts\n )\n return mark_safe(bleach.clean(rendered, tags, attrs, all_styles))\n","sub_path":"hyperbola/core/templatetags/hyperbola_core_tags.py","file_name":"hyperbola_core_tags.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279477376","text":"import random\r\n\r\nfirst1 = [\"An old silent pond...\", \"Autumn moonlight—\", \"In the twilight rain\"]\r\nx = random.choice(first)\r\nsecond = [\"A frog jumps into the pond,\", \"a worm digs silently\", \"these brilliant-hued hibiscus —\"]\r\ny = random.choice(second)\r\nthird = [\"splash! Silence again.\", \"into the chestnut.\", \"A lovely sunset.\"]\r\nz = random.choice(third)\r\n\r\nprint(x + '\\n' + y + '\\n' + z)\r\n","sub_path":"HaikuGenerator.py","file_name":"HaikuGenerator.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240412704","text":"#S3C4 Michael\n# Queue\nclass Node():\n def __init__(self):\n self.Next=None\n self.content=None\n\ndef _init_():\n global Nullpointer,StartPointer,FreeListPointer,full,List,RealPtr\n Nullpointer=-1\n StartPointer=Nullpointer\n RealPtr=0\n FreeListPointer=0\n List=[0]*10\n full=0\n for i in range(10):\n List[i]=Node()\n List[i].Next=i+1\n List[9].Next=Nullpointer\n\ndef Push(NewItem):\n global Nullpointer,StartPointer,FreeListPointer,full,List,RealPtr\n EndlistPtr=full\n if full==10:\n print(\"No extra space\")\n elif StartPointer==Nullpointer:\n StartPointer=0\n List[0].Next=Nullpointer\n List[FreeListPointer].content=NewItem\n FreeListPointer=1\n full=full+1\n else:\n ThisNodePtr=RealPtr\n full=full+1\n RealPtr=FreeListPointer\n List[ThisNodePtr].Next=FreeListPointer\n List[FreeListPointer].content=NewItem\n Previous=FreeListPointer\n FreeListPointer=List[FreeListPointer].Next\n List[Previous].Next=Nullpointer\n\ndef Pop():\n global Nullpointer,StartPointer,FreeListPointer,full,List,RealPtr\n full=full-1\n if not full==0:\n ThisNodePtr=StartPointer\n List[ThisNodePtr].content=None\n StartPointer=List[ThisNodePtr].Next\n \n\ndef Print():\n global Nullpointer,StartPointer,FreeListPointer,full,List,RealPtr\n NewItem=StartPointer\n for i in range(full):\n print(List[NewItem].content,end=\" \" )\n NewItem=List[NewItem].Next\n print(\"\")\n\n\n\n_init_()\nPush(2)\nPush(4)\nPush(6)\nPush(1)\nPush(6)\nPush(5)\nPop()\nPop()\nPop()\nPush(6)\nPush(4)\nPrint()\nPush(2)\nPrint()\nPush(5)\nPrint()\nPop()\nPop()\nPush(6)\nPush(4)\nPrint()\nPush(2)\nPrint()\nPush(5)\nPrint()\n","sub_path":"Ch23/Michael_Queue2.py","file_name":"Michael_Queue2.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"181144476","text":"import random\n'''\nSquare matrix. Each square is black or white. \nFind largest subsquare such that its bordered by black squares.\nCorner borders don't matter. Inside the square can be anything\n\nNeed: largest black border that I can find in the square.\n - Some B's in the square with related list index values\n\n[\n\n[W,B,W,B,B,W]\n[B,W,B,W,W,B]\n[B,W,B,W,W,B]\n[B,W,W,B,B,W]\n[B,W,B,W,B,B]\n[B,W,B,W,W,B]\n\n]\n\nI want information about a subsquare stored somehow. store the info about subsquare in tuples (2 of them)\n\nI want a class that is given a matrix and checks all potential subsquares going from biggest to smallest\n\n'''\n\nclass LargestSubsquare:\n \n def __init__(self, matrix):\n self.matrix = matrix\n self.x_boundaries = (0, len(matrix)-1)\n self.y_boundaries = (0, len(matrix[0])-1)\n self.current_size = len(matrix) - 3\n self.init_square = Square(len(matrix)-2, 1, 1, len(matrix)-2, self.matrix)\n \n \n def get_largest_subsquare(self):\n \n if self.init_square.check_borders():\n return self.init_square\n \n while self.current_size > 0:\n for i in range(1, len(self.matrix) - 1 - self.current_size):\n for j in range(1, len(self.matrix) - 1 - self.current_size):\n current_square = Square(i + self.current_size - 1, j, i, j + self.current_size - 1, self.matrix)\n if current_square.check_borders():\n return current_square.location()\n \n self.current_size -= 1\n \n\nclass Square:\n \n def __init__(self, x1, y1, x2, y2, matrix):\n self.bottom_left = (x1, y1)\n self.upper_right = (x2, y2)\n self.big_square = matrix\n \n def location(self):\n return (self.bottom_left, self.upper_right)\n \n #evaluate everything directly against whatever border I'm currently on\n def check_borders(self):\n \n return self.check_upper_border() and self.check_lower_border() and self.check_left_border() and self.check_right_border()\n \n \n def check_upper_border(self):\n for i in range(self.bottom_left[1], self.upper_right[1]+1):\n if self.big_square[self.upper_right[0]-1][i] != 'B':\n return False\n return True\n \n def check_lower_border(self):\n for i in range(self.bottom_left[1], self.upper_right[1]+1):\n if self.big_square[self.bottom_left[0]+1][i] != 'B':\n return False\n return True\n \n def check_left_border(self):\n for i in range(self.upper_right[0], self.bottom_left[0] + 1):\n if self.big_square[i][self.bottom_left[1] - 1] != 'B':\n return False\n return True\n\n def check_right_border(self):\n for i in range(self.upper_right[0], self.bottom_left[0] + 1):\n if self.big_square[i][self.upper_right[1] + 1] != 'B':\n return False\n return True\n \n def get_square(self):\n return [self.bottom_left, self.upper_right]\n\n\n\n\ndef main():\n matrix = []\n for i in range(0, 15):\n l1 = []\n for i in range(0, 15):\n if random.randint(0, 99) > 11:\n l1.append('B')\n else:\n l1.append('W')\n matrix.append(l1)\n for item in matrix:\n print(item)\n\n LSS = LargestSubsquare(matrix)\n print(LSS.get_largest_subsquare())\nif __name__ == \"__main__\": main()\n ","sub_path":"CPS/SubSquares.py","file_name":"SubSquares.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"507804324","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pprint\nimport logging\nimport os\nimport sys\nimport datetime\nfrom flask import Flask, render_template\nfrom elasticsearch import Elasticsearch\n\npp = pprint.PrettyPrinter(indent=4)\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO,\n format=\"%(asctime)s %(levelname)-5s: %(message)s\")\napp = Flask(__name__)\n\nusername = os.environ['ELASTIC_USER']\npassword = os.environ['ELASTIC_PASS']\ntry:\n es = Elasticsearch(\"https://elastic.dreng.ch\",\n http_auth=(username, password),\n scheme=\"https\", port=443)\nexcept Exception:\n es = Elasticsearch(\"elasticsearch-master.efk:9200\")\n\n\n@app.route(\"/\", methods=['GET'])\ndef root():\n count, array = getPlayerList()\n htmlTable = calcFame(array)\n return render_template(\"index.jinja\", table=htmlTable, \n count=countData())\n\n\n@app.route(\"/healthz\", methods=['GET'])\ndef healthz():\n return {}, 200\n\n\ndef calcFame(array):\n dataset = []\n for player in array:\n result = searchPlayer(player[\"name\"])\n # result [\"tweets\"]/[\"likes\"]/[\"follow\"] \n fame = int((result[\"tweets\"]) + \n (player[\"follower\"]) + \n (player[\"posts\"]) +\n (result[\"likes\"]) + \n (result[\"follow\"]))\n\n player[\"follower\"] = player[\"follower\"] + result[\"follow\"]\n player[\"fame\"] = fame\n player[\"tweets\"] = result[\"tweets\"]\n player[\"likes\"] = result[\"likes\"]\n dataset.append(player)\n return createHtmlTable(dataset)\n\n\ndef createHtmlTable(dataset):\n sentiList = getSenti()\n htmlTable=''\n htmlTable+=\"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\"\n for player in dataset:\n sentiVal = getPlayerFromSenti(sentiList, player[\"name\"])\n if sentiVal > 0: \n icon = ''\n elif sentiVal == 0: \n icon = ''\n elif sentiVal < 0: \n icon = ''\n htmlTable+=\"\"\"\n \n \n \n \n \n \n \n \n \n \"\"\" % (icon,\n player[\"name\"], \n player[\"fame\"], \n player[\"follower\"], \n player[\"likes\"],\n player[\"posts\"], \n player[\"tweets\"])\n htmlTable += \"
ImageSpielerFameFollowerLikesPostsTweets
%s%s%s\n %s %s %s %s
\"\n return htmlTable\n\n\ndef create_indexes():\n settings = {\n \"settings\": {\n \"number_of_shards\": 3,\n \"number_of_replicas\": 0\n },\n \"mappings\": {\n \"properties\": {\n \"name\": {\"type\": \"text\", \"fields\": {\"keyword\": {\"type\": \"keyword\"}}},\n \"text\": {\"type\": \"text\"},\n \"senti\": {\"type\": \"float\"},\n \"datetime\": {\"type\": \"date\"},\n }\n }\n }\n es.indices.create(index=\"twitter\", ignore=400, body=settings)\n settings = {\n \"settings\": {\n \"number_of_shards\": 3,\n \"number_of_replicas\": 0\n },\n \"mappings\": {\n \"properties\": {\n \"name\": {\"type\": \"text\", \"fields\": {\"keyword\": {\"type\": \"keyword\"}}},\n \"follower\": {\"type\": \"integer\"},\n \"posts\": {\"type\": \"integer\"},\n \"datetime\": {\"type\": \"date\"},\n }\n }\n }\n es.indices.create(index=\"insta\", ignore=400, body=settings)\n settings = {\n \"settings\": {\n \"number_of_shards\": 3,\n \"number_of_replicas\": 0\n },\n \"mappings\": {\n \"properties\": {\n \"name\": {\"type\": \"text\", \"fields\": {\"keyword\": {\"type\": \"keyword\"}}},\n \"follower\": {\"type\": \"integer\"},\n \"posts\": {\"type\": \"integer\"},\n \"datetime\": {\"type\": \"date\"},\n }\n }\n }\n es.indices.create(index=\"insta2\", ignore=400, body=settings)\n settings = {\n \"settings\": {\n \"number_of_shards\": 3,\n \"number_of_replicas\": 0\n },\n \"mappings\": {\n \"properties\": {\n \"name\": {\"type\": \"text\", \"fields\": {\"keyword\": {\"type\": \"keyword\"}}},\n \"likes\": {\"type\": \"integer\"},\n \"follower\": {\"type\": \"integer\"},\n }\n }\n }\n es.indices.create(index=\"facebook\", ignore=400, body=settings)\n\n\ndef getPlayerList():\n # Example data\n e1 = { \"name\":\"Daniel Strohecker\",\n \"follower\": 78,\n \"posts\": 23,\n \"datetime\": datetime.datetime.utcnow() }\n #es.index(index=\"insta\", body=e1)\n\n # search data\n res = es.search(index=\"insta\", body={\"query\": {\"match_all\": {}}}, size=50)\n count = res[\"hits\"][\"total\"][\"value\"]\n dataset = []\n for result in res[\"hits\"][\"hits\"]:\n array = {\"name\": result[\"_source\"][\"name\"], \n \"follower\": result[\"_source\"][\"follower\"], \n \"posts\": result[\"_source\"][\"posts\"]}\n print(array)\n dataset.append(array)\n return count, dataset\n\n\ndef searchPlayer(player):\n # Example data\n e1 = { \"name\":\"Daniel Strohecker\",\n \"text\": \"Challenge to challenge the ...\",\n \"datetime\": datetime.datetime.utcnow() }\n #es.index(index='twitter', body=e1)\n\n # search data\n res = es.search(index=\"twitter\", body={\"query\": {\"match\": {\"name\": player }}}, size=10000)\n tweets = res[\"hits\"][\"total\"][\"value\"]\n res = es.search(index=\"facebook\", body={\"query\": {\"match\": {\"name\": player }}}, size=10000)\n try:\n likes = res[\"hits\"][\"hits\"][0][\"_source\"][\"likes\"]\n except:\n likes = 0\n try:\n follow = res[\"hits\"][\"hits\"][0][\"_source\"][\"follower\"]\n except:\n follow = 0\n\n return {\"tweets\": int(tweets), \"likes\": int(likes), \"follow\": int(follow)}\n\n\ndef getSenti():\n body = {\"size\": 1, \"aggs\": {\n \"player_name\": {\n \"terms\": { \"field\": \"name.keyword\", \"size\": 10000 },\n \"aggs\" : { \"avg_senti\": { \"avg\": { \"field\": \"senti\" } } }\n }\n }\n }\n\n res = es.search(index=\"twitter\", body=body, size=1)\n return res[\"aggregations\"][\"player_name\"][\"buckets\"]\n\n\ndef getPlayerFromSenti(sentiList, player):\n for entry in sentiList:\n if entry[\"key\"] == player:\n return entry[\"avg_senti\"][\"value\"]\n return 0\n\n\ndef countData():\n res = es.search(index=\"twitter\", body={\"query\": {\"match_all\": {}}})\n return res[\"hits\"][\"total\"][\"value\"]\n\n\nif __name__ == '__main__':\n create_indexes()\n app.run(debug=False, host='0.0.0.0', threaded=True, use_reloader=True)\n","sub_path":"frontend/app/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":7787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"537566793","text":"from django.shortcuts import render, redirect, render_to_response\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic import CreateView\nfrom django.urls import reverse\nfrom App.models import User\nfrom App.forms import RegistrationForm\n\nimport sys\nfrom time import sleep\nimport urllib.request\nimport json\nimport ast\n\nclass thingspeak:\n def __init__(self, write_key, read_key):\n self.write_key = write_key\n self.read_key = read_key\n temp = self.read(1)\n self.id = temp['channel']['id']\n self.name = temp['channel']['name']\n self.num_field = len(temp['channel'])-8\n\n def write(self, field, data):\n url = \"https://api.thingspeak.com/update?api_key={}&field{}={}\".format(self.write_key, str(field), str(data))\n rtn = urllib.request.urlopen(url)\n return 1\n \n def read(self, _range):\n url = \"https://api.thingspeak.com/channels/628897/feeds.json?api_key={}&results={}\".format(self.read_key, str(_range))\n rtn = urllib.request.urlopen(url).read()\n return ast.literal_eval(str(rtn)[2:len(str(rtn))-1].replace('null',\"\\\"\\\"\"))\n \n def get_field(self, field, result):\n url = \"https://api.thingspeak.com/channels/628897/fields/{}.json?api_key={}&results={}\".format(field, self.read_key, result)\n rtn = urllib.request.urlopen(url).read()\n return rtn\n\n def get_data(self):\n temp = self.read(1)['feeds'][0]\n del temp['entry_id']\n return temp\n\n\nif __name__ == \"__main__\":\n \n testt = thingspeak(\"VEMUS670D5ZP2OLN\", \"5LT3QPFMB8XPVWEF\")\n print (testt.get_data())\n \ndef index(request):\n return render(request, 'test.html')\n\ndef profile(request):\n testt = thingspeak(\"VEMUS670D5ZP2OLN\", \"5LT3QPFMB8XPVWEF\")\n context = {\n 'testt': testt.get_data(),\n 'create': testt.get_data()['created_at'],\n 'f1': testt.get_data()['field1'],\n 'f2': testt.get_data()['field2'],\n 'f3': testt.get_data()['field3'],\n 'f4': testt.get_data()['field4'],\n 'f5': testt.get_data()['field5'],\n }\n return render(request, 'profile.html', context)\n\ndef pregister(request):\n if request.method == 'POST':\n form = RegistrationForm(request.POST)\n if form.is_vatest:\n user = form.save(True, False)\n login(request, user)\n return redirect(\"/Profile\")\n else:\n form = RegistrationForm()\n return render(request,'pregister.html',{'form':form}) \n else:\n form = RegistrationForm()\n return render(request,'pregister.html',{'form':form})\n\ndef mregister(request):\n if request.method == 'POST':\n form = RegistrationForm(request.POST)\n if form.is_valid():\n user = form.save(False, True)\n login(request, user)\n return redirect(\"/Profile\")\n else:\n form = RegistrationForm()\n return render(request,'mregister.html',{'form':form})\n\ndef plogin(request):\n if request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n user = form.get_user()\n if user.is_active and user.patient:\n login(request,user)\n return redirect(\"/Profile\")\n elif user.is_active and not user.patient:\n form = AuthenticationForm()\n message = 'This User is not a Patient!'\n context = {\n 'message': message,\n 'form': form,\n }\n return render(request,'plogin.html', context)\n else :\n form = AuthenticationForm()\n message = 'Invalid Username or Password!'\n context = {\n 'message': message,\n 'form': form,\n }\n return render(request,'plogin.html', context)\n else :\n form = AuthenticationForm()\n message = 'Invalid Username or Password!'\n context = {\n 'message': message,\n 'form': form,\n }\n return render(request,'plogin.html', context)\n else :\n form = AuthenticationForm()\n message = ''\n context = {\n 'message': message,\n 'form': form,\n }\n return render(request,'plogin.html', context)\n\ndef mlogin(request):\n if request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n user = form.get_user()\n if user.is_active and user.medical:\n context = {\n 'patient': User.objects.filter(patient=1),\n 'pamount': len(User.objects.filter(patient=1))\n }\n login(request,user)\n return render(request, \"profile.html\", context)\n elif user.is_active and not user.medical:\n form = AuthenticationForm()\n message = 'This User is not a Medical Personnel!'\n context = {\n 'message': message,\n 'form': form,\n }\n return render(request,'mlogin.html', context)\n else :\n form = AuthenticationForm()\n message = 'Invalid Username or Password!'\n context = {\n 'message': message,\n 'form': form,\n }\n return render(request,'mlogin.html', context)\n else :\n form = AuthenticationForm()\n message = 'Invalid Username or Password!'\n context = {\n 'message': message,\n 'form': form,\n }\n return render(request,'mlogin.html', context)\n else :\n form = AuthenticationForm()\n message = ''\n context = {\n 'message': message,\n 'form': form,\n }\n return render(request,'mlogin.html', context)","sub_path":"App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"328338734","text":"#import os\n#def find(name,path):\n#\tfor root,dirs,files in os.walk(path):\n#\t\tif name in files:\n#\t\t\tprint os.path.join(root,name),\n\n#find(\"find.py\",\"/home\")'''\n\nimport os\nfor file in os.listdir(\"/home/ravi/proj\"):\n\tl=0\n\tif file.endswith(\".py\"):\n\t\tfor line in open(file):\n\t\t\tif '\\n'!=line:\n\t\t\t\tif '#'not in line:\n\t\t\t\t\tl+=1\n\t\tprint(file),\"\\t\", l\n","sub_path":"find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"118880672","text":"import sys\nimport os\n\ndef show(num):\n \"\"\"\n 页面显示\n :param num: int\n :return: msg_1 or msg_2\n \"\"\"\n msg_1 = {\"1\":\"登录\",\n \"2\":\"注册\",\n \"3\":\"进入文章页面\",\n \"4\":\"进入评论页面\",\n \"5\":\"进入日记页面\",\n \"6\":\"进入收藏页面\",\n \"7\":\"注销账号\",\n \"8\":\"退出整个程序\"}\n msg_2 = {\"1\":\"登录\",\n \"2\":\"注册\",\n \"Q\":\"退出\"}\n return msg_2 if num == 0 else msg_1\n\ndef user_info():\n \"\"\"\n 用户注册\n :return: None\n \"\"\"\n while True:\n user_name = input(\"请输入用户名(包含数字或字母,按Q退到上一层):\")\n if user_name.upper() == \"Q\":\n return\n password = input(\"请输入密码(长度6~14位,按Q退到上一层):\")\n if password.upper() == \"Q\":\n return\n if not user_name.isalnum():\n print(\"用户名只能包含字母或数字,请重新输入\")\n continue\n elif len(password) < 6 or len(password) > 14:\n print(\"密码长度6~14位,您输入有误,请重新输入\")\n continue\n else:\n with open(\"userinfo.txt\",mode=\"a+\",encoding=\"utf-8\") as f:\n f.seek(0)\n for line in f:\n u_lst = line.strip().split(\":\")\n if user_name in u_lst[0]:\n print(\"用户名已存在,请重新输入\")\n break\n else:\n f.write(f\"{user_name}:{password}:0:0\\n\")\n print(\"注册成功\")\n return\n\ndef check_user(user_name):\n \"\"\"\n 检查用户是否存在及用户状态\n :param user_name: user_name(str)\n :return: 0 1\n \"\"\"\n with open(\"userinfo.txt\",mode=\"a+\",encoding=\"utf-8\") as f:\n f.seek(0)\n for line in f:\n info = line.strip().split(\":\")\n if info[0] == user_name:\n if info[-1] == \"1\":\n print(\"用户已被锁定,禁止登录\")\n return 1\n # elif info[-2] == \"1\":\n # print(\"用户已登录,无需再次登录\")\n # return 1\n else:\n return\n else:\n print(\"用户名不存在\")\n return 0\n\n\ndef user_sign():\n \"\"\"\n 用户登录\n :return: None N\n \"\"\"\n count = 3\n while count:\n user_name = input(\"请输入用户名(按Q返回上一层):\")\n if user_name.upper() == \"Q\":\n return \"N\"\n password = input(\"请输入密码(按Q返回上一层):\")\n if password.upper() == \"Q\":\n return \"N\"\n ret = check_user(user_name)\n if ret == 1:\n return \"N\"\n elif ret == 0:\n continue\n with open(\"userinfo.txt\",mode=\"r+\",encoding=\"utf-8\") as f:\n for line in f:\n f.flush()\n info = line.strip().split(\":\")\n if user_name == info[0]:\n if password == info[1]:\n print(\"登录成功\")\n global num\n num = 1\n with open(\"userinfo.txt\",mode=\"r\",encoding=\"utf-8\") as f1,\\\n open(\"userinfo_back.txt\", mode=\"w\", encoding=\"utf-8\") as f2:\n for l in f1:\n info_1 = l.strip().split(\":\")\n if user_name == info_1[0]:\n info_1[-2] = \"1\"\n f2.write(\":\".join(info_1)+\"\\n\")\n else:\n f2.write(l)\n os.remove(\"userinfo.txt\")\n os.rename(\"userinfo_back.txt\", \"userinfo.txt\")\n\n return user_name\n else:\n count -= 1\n print(f\"用户名或密码错误,请重新输入(还有{count}次机会)\")\n if count == 0:\n print(\"您的账号已被锁定,请联系管理员解锁\")\n with open(\"userinfo.txt\", mode=\"r\", encoding=\"utf-8\") as f3, \\\n open(\"userinfo_back.txt\", mode=\"w\", encoding=\"utf-8\") as f4:\n for line in f3:\n info_2 = line.strip().split(\":\")\n if user_name == info_2[0]:\n info_2[-1] = \"1\"\n f4.write(\":\".join(info_2)+\"\\n\")\n else:\n new_line = line\n f4.write(new_line)\n os.remove(\"userinfo.txt\")\n os.rename(\"userinfo_back.txt\", \"userinfo.txt\")\n return \"N\"\n\ndef logout(user_name):\n \"\"\"\n 用户注销\n :param user_name: user_name\n :return: None\n \"\"\"\n with open(\"userinfo.txt\",mode=\"r+\",encoding=\"utf-8\") as f1,\\\n open(\"userinfo_back.txt\", mode=\"w\", encoding=\"utf-8\") as f2:\n for line in f1:\n info = line.strip().split(\":\")\n if info[0] == user_name:\n info[-2] = \"0\"\n f2.write(\":\".join(info)+\"\\n\")\n else:\n f2.write(line)\n os.remove(\"userinfo.txt\")\n os.rename(\"userinfo_back.txt\", \"userinfo.txt\")\n global num\n num = 0\n return\n\n\nnum = 0\ndef func():\n \"\"\"\n 调用各函数执行\n :return:\n \"\"\"\n default_name = \"N\"\n while True:\n show_msg = show(num)\n for i in show_msg: print(i,show_msg[i])\n use_msg = input(\"请选择序号:\")\n if use_msg.upper() == \"Q\":\n print(\"程序退出\")\n return\n if not use_msg.isdecimal() or int(use_msg) < 1 or int(use_msg) > len(show_msg):\n print(\"输入序号错误,请重新输入\")\n continue\n elif use_msg == \"1\":\n if default_name == \"N\":\n default_name = user_sign()\n else:\n logout(default_name)\n default_name = user_sign()\n elif use_msg == \"2\":\n user_info()\n elif use_msg == \"3\":\n print(f\"欢迎{default_name}进入文章页面\".center(20,\"*\"))\n elif use_msg == \"4\":\n print(f\"欢迎{default_name}进入评论页面\".center(20,\"*\"))\n elif use_msg == \"5\":\n print(f\"欢迎{default_name}进入日记页面\".center(20,\"*\"))\n elif use_msg == \"6\":\n print(f\"欢迎{default_name}进入收藏页面\".center(20,\"*\"))\n elif use_msg == \"7\":\n logout(default_name)\n print(f\"{default_name} 用户已注销\")\n default_name = \"N\"\n elif use_msg == \"8\":\n logout(default_name)\n print(\"程序退出\".center(20,\"*\"))\n return\n\nfunc()\n","sub_path":"week03/第二周大作业.py","file_name":"第二周大作业.py","file_ext":"py","file_size_in_byte":7110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"618650420","text":"import os\nfrom tkinter.filedialog import askdirectory\nimport mutagen\nfrom mutagen.flac import FLAC\nfrom mutagen.id3 import ID3\nfrom mutagen.mp4 import MP4\n\n\ndef directorychooser():\n directory = askdirectory()\n os.chdir(directory)\n\n for files in os.listdir(directory):\n if files.endswith(\".flac\"):\n realdir = os.path.realpath(files)\n audiofile = FLAC(realdir)\n # title, artist, album\n title = ''.join(audiofile['title'])\n artist = ''.join(audiofile['artist'])\n album = ''.join(audiofile['album'])\n flac_metadata = {'title': title, 'artist': artist, 'album': album}\n print(flac_metadata)\n elif files.endswith(\".mp3\"):\n realdir = os.path.realpath(files)\n audiofile = ID3(realdir)\n # TIT2, TPE1, TALB\n title = audiofile['TIT2'].text[0]\n artist = audiofile['TPE1'].text[0]\n album = audiofile['TALB'].text[0]\n mp3_metadata = {'title': title, 'artist': artist, 'album': album}\n print(mp3_metadata)\n elif files.endswith(\".ogg\"):\n realdir = os.path.realpath(files)\n audiofile = mutagen.File(realdir)\n # title, artist, album\n title = ''.join(audiofile['title'])\n artist = ''.join(audiofile['artist'])\n album = ''.join(audiofile['album'])\n ogg_metadata = {'title': title, 'artist': artist, 'album': album}\n print(ogg_metadata)\n elif files.endswith(\".mp4\"):\n realdir4 = os.path.realpath(files)\n audiofile_3 = MP4(realdir4)\n # title, artist, album\n title = audiofile_3['title']\n artist = audiofile_3['artist']\n album = audiofile_3['album']\n mp4_metadata = {'title': title, 'artist': artist, 'album': album}\n print(mp4_metadata)\n\n\ndirectorychooser()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"447116695","text":"#!/usr/bin/env python\n\nfrom nplab import datafile as df\nimport os,sys\n\nif __name__==\"__main__\":\n\tpath = os.path.normpath(sys.argv[1])\n\tdatafile = df.DataFile(name=path,mode='r')\n\tdatafile.show_gui(blocking=True)\n\tdatafile.close()\n\tsys.exit(0)\n\n","sub_path":"archive/scripts/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"56986335","text":"import wx\nimport wx.xrc\n\nfrom db.promote_students import promoteStudents\n\n\n###########################################################################\n# Class PromoteStudents\n###########################################################################\n\nclass PromoteStudents(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(500, 300),\n style=wx.TAB_TRAVERSAL)\n\n container = wx.BoxSizer(wx.VERTICAL)\n\n self.panel_title = wx.StaticText(self, wx.ID_ANY, u\"Promote students to next class\", wx.DefaultPosition,\n wx.DefaultSize, wx.ALIGN_CENTRE)\n self.panel_title.Wrap(-1)\n self.panel_title.SetFont(wx.Font(16, 70, 90, 92, False, wx.EmptyString))\n\n container.Add(self.panel_title, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 30)\n\n self.disclaimer = wx.StaticText(self, wx.ID_ANY, u\"Please do this only when necessary, it cannot be reversed\",\n wx.DefaultPosition, wx.DefaultSize, wx.ALIGN_CENTRE)\n self.disclaimer.Wrap(-1)\n self.disclaimer.SetForegroundColour(wx.Colour(255, 0, 0))\n\n container.Add(self.disclaimer, 0, wx.ALL | wx.EXPAND, 5)\n\n content_sizer = wx.BoxSizer(wx.VERTICAL)\n\n content_sizer.AddSpacer((0, 0), 1, wx.EXPAND, 5)\n\n btnSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n btnSizer.AddSpacer((0, 0), 2, wx.EXPAND, 5)\n\n self.promote_students_btn = wx.Button(self, wx.ID_ANY, u\"Move all students to the next class\",\n wx.DefaultPosition, wx.DefaultSize, 0)\n self.promote_students_btn.SetFont(wx.Font(12, 70, 90, 90, False, wx.EmptyString))\n\n btnSizer.Add(self.promote_students_btn, 1, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL | wx.EXPAND, 5)\n\n btnSizer.AddSpacer((0, 0), 2, wx.EXPAND, 5)\n\n content_sizer.Add(btnSizer, 1, wx.EXPAND, 5)\n\n content_sizer.AddSpacer((0, 0), 3, wx.EXPAND, 5)\n\n container.Add(content_sizer, 1, wx.EXPAND, 5)\n\n self.SetSizer(container)\n self.Layout()\n\n # Connect Events\n self.promote_students_btn.Bind(wx.EVT_BUTTON, self.promoteStudents)\n\n def __del__(self):\n pass\n\n # Virtual event handlers, overide them in your derived class\n def promoteStudents(self, event):\n self.promote_students_btn.Enable(False)\n\n dlg = wx.MessageDialog(None, \"Confirm promoting all students.\", 'Confirm Action.', wx.YES_NO | wx.ICON_INFORMATION)\n retCode = dlg.ShowModal()\n\n if retCode == wx.ID_YES:\n dlg = wx.MessageDialog(None, \"Are you sure? This action cannot be reversed.\", 'Warning Message.',\n wx.YES_NO | wx.ICON_WARNING)\n retCode = dlg.ShowModal()\n\n if retCode == wx.ID_YES:\n promoteStudents()\n dlg.Destroy()\n dlg.Destroy()\n\n self.promote_students_btn.Enable(True)\n\n\n","sub_path":"PromoteStudents.py","file_name":"PromoteStudents.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"346806892","text":"\"\"\"\n\tMakes fig S1.\n\n\tFor each SV, determine if it starts or ends in a TAD.\n\tFor these TADs, count how many genes are in that TAD.\n\tMake a plot where we show the number of SVs vs the number of genes that these disrupt\n\tE.g., 5 genes are disrupted 100 times. \n\n\"\"\"\n\nimport sys\nimport numpy as np\nimport os\n\n\npath = sys.argv[1]\nsys.path.insert(1, path)\nsys.path.insert(1, 'linkSVGenePairs/')\n\nfrom inputParser import InputParser\nimport settings\n\noutDir = sys.argv[2]\nfinalOutDir = outDir + '/figureS1/'\nif not os.path.exists(finalOutDir):\n\tos.makedirs(finalOutDir)\n\n\n#1. Read the SVs\nsvDir = settings.files['svDir']\nsvData = InputParser().getSVsFromFile_hmf(svDir)\n\n#2. read the genes\ncausalGenes = InputParser().readCausalGeneFile(settings.files['causalGenesFile'])\nnonCausalGenes = InputParser().readNonCausalGeneFile(settings.files['nonCausalGenesFile'], causalGenes) #In the same format as the causal genes.\n\n#Combine the genes into one set.\ngenes = np.concatenate((causalGenes, nonCausalGenes), axis=0)\n\n#3. Read the TADs\n\ntadFile = settings.files['tadFile']\ntadData = InputParser().getTADsFromFile(tadFile)\n\n#4. Map the genes to the TADs\ndef mapGenesToTads(genes, tadData):\n\t\t\"\"\"\n\t\t\tFor computing effects of disruptions on genes, it is convenient to know which genes are located in which TADs.\n\t\t\tFind out for every TAD which genes are located inside of these, and map them to the TADs. \n\t\t\n\t\t\tgenes: (numpy array) array with the genes and their information. chr, start, end, geneObject\n\t\t\ttadData: (numpy array) array with the TADs and their information. chr, start, end, tadObject\n\t\t\"\"\"\n\t\t\n\t\tpreviousChromosome = 0\n\t\tfor tad in tadData:\n\t\t\n\t\t\tif tad[0] != previousChromosome:\n\t\t\t\tpreviousChromosome = tad[0]\n\t\t\t\tgeneChrSubset = genes[np.where(genes[:,0] == tad[0])] #TADs are intrachromosomal, so looking at 1 chromosome is sufficient\n\t\t\t\n\t\t\t\n\t\t\t#Find all genes that are within the TAD.\n\t\t\t#Because some genes are in two TADs, and the TAD definition is likely not entirely correct, we will count overlap of TADs with any part of the gene even if it is just 1 bp for now.\n\t\t\t#So the start of the gene must be before the end of the TAD, and the end of the gene after the start of the TAD. \n\t\t\tstartMatches = geneChrSubset[:,1] <= tad[2]\n\t\t\tendMatches = geneChrSubset[:,2] >= tad[1]\n\t\t\t\n\t\t\tallMatches = startMatches * endMatches\n\t\t\tmatchingGenes = geneChrSubset[allMatches,:]\n\t\t\n\t\t\t#Add these genes to the TADs if any.\n\t\t\tif matchingGenes.shape[0] < 1:\n\t\t\t\t\n\t\t\t\t#If there are no genes, we can for now add the genes immediately to the left and right of the TAD.\n\t\t\t\t#With better data, this step can be removed, but since the TADs are so sparse, it is a temporary solution.\n\t\t\t\t\n\t\t\t\t#1. Compute the distance from either TAD boundary to all genes\n\t\t\t\t#We look at all genes to the left, so we can use the end of a gene to the start of a TAD, and the start of a gene to the end of a TAD. \n\t\t\t\t#2. Get the gene with the smallest distance to each boundary\n\t\t\t\t\n\t\t\t\tstartDistances = tad[1] - geneChrSubset[:,2]\n\t\t\t\t#Exclude all negative elements, these are on the right of the TAD while we want genes on the left of the TAD\n\t\t\t\tnegativeElements = startDistances < 0\n\n\t\t\t\tstartDistances[negativeElements] = float(\"inf\") #skip the ones that are on the wrong side of the TAD boundary, so set them to inf and they will never be selected. \n\t\t\t\tif startDistances[negativeElements].shape[0] == startDistances.shape[0]: #but if everything is inf, we skip this TAD.\n\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\n\t\t\t\t#Repeat but then for the other TAD end. \n\t\t\t\tendDistances = geneChrSubset[:,1] - tad[2]\n\t\t\t\t#Exclude all negative elements\n\t\t\t\tnegativeElements = endDistances < 0\n\n\t\t\t\tendDistances[negativeElements] = float(\"inf\") #skip the ones that are on the wrong side of the TAD boundary, so set them to inf and they will never be selected. \n\t\t\t\tif endDistances[negativeElements].shape[0] == endDistances.shape[0]: #but if everything is inf, we skip this TAD.\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\telse:\n\t\t\t\ttad[3].setGenes(matchingGenes[:,3]) #Add the eQTL objects to the TAD objects. \n\t\n\t\treturn tadData\t\ntadData = mapGenesToTads(genes, tadData)\n\n#For each SV, determine which TADs it starts and ends in\n#Count the number of genes in that TAD\ndisruptions = [] #store the number of genes that each SV disrupts.\ndisruptionDict = dict() #store by categories\ndisruptionDict['1'] = 0\ndisruptionDict['2-5'] = 0\ndisruptionDict['6-10'] = 0\ndisruptionDict['11-20'] = 0\ndisruptionDict['>20'] = 0\nfor sv in svData:\n\t\n\tif sv[0] == sv[3]: #intrachromosomal SV\n\t\t\n\t\tgeneCount = 0 \n\t\t\n\t\ttadChrSubset = tadData[tadData[:,0] == sv[0]]\n\t\t\n\t\t#Get the TAD that the SV starts in\n\t\tstartMatches = (sv[1] >= tadChrSubset[:,1]) * (sv[1] <= tadChrSubset[:,2])\n\t\t\n\t\t\n\t\tstartTAD = tadChrSubset[startMatches]\n\t\t\n\t\tif startTAD.shape[0] > 0:\n\t\t\tgeneCount += len(startTAD[0][3].genes)\n\t\t\n\t\t#Get the TAD that the SV ends in\n\t\tendMatches = (sv[5] >= tadChrSubset[:,1]) * (sv[5] <= tadChrSubset[:,2])\n\t\t\n\t\tendTAD = tadChrSubset[endMatches]\n\t\tif endTAD.shape[0] > 0:\n\t\t\tgeneCount += len(endTAD[0][3].genes)\n\t\t\n\t\t#Count the number of genes in the start & end TAD\n\t\t\n\t\tif geneCount > 0:\n\t\t\tdisruptions.append(geneCount)\n\t\t\t\n\t\tif geneCount == 1:\n\t\t\tdisruptionDict['1'] += 1\n\t\tif geneCount > 1 and geneCount < 6:\n\t\t\tdisruptionDict['2-5'] += 1\n\t\tif geneCount > 5 and geneCount < 11:\n\t\t\tdisruptionDict['6-10'] += 1\n\t\tif geneCount > 10 and geneCount < 21:\n\t\t\tdisruptionDict['11-20'] += 1\n\t\tif geneCount > 20:\n\t\t\tdisruptionDict['>20'] += 1\n\n\telse: #interchromosomal\n\t\tgeneCount = 0 \n\t\t\n\t\ttadChrSubset = tadData[tadData[:,0] == sv[0]]\n\t\t\n\t\t#Get the TAD that the SV starts in\n\t\tstartMatches = (sv[1] >= tadChrSubset[:,1]) * (sv[1] <= tadChrSubset[:,2])\n\t\t\n\t\t\n\t\tstartTAD = tadChrSubset[startMatches]\n\t\t\n\t\tif startTAD.shape[0] > 0:\n\t\t\tgeneCount += len(startTAD[0][3].genes)\n\t\t\t\n\t\ttadChr2Subset = tadData[tadData[:,0] == sv[3]]\n\t\t\n\t\t#Get the TAD that the SV ends in\n\t\tendMatches = (sv[5] >= tadChr2Subset[:,1]) * (sv[5] <= tadChr2Subset[:,2])\n\t\t\n\t\tendTAD = tadChr2Subset[endMatches]\n\t\tif endTAD.shape[0] > 0:\n\t\t\tgeneCount += len(endTAD[0][3].genes)\n\t\t\n\t\t#Count the number of genes in the start & end TAD\n\t\t\n\t\tif geneCount > 0:\n\t\t\tdisruptions.append(geneCount)\n\t\t\n\t\tif geneCount == 1:\n\t\t\tdisruptionDict['1'] += 1\n\t\tif geneCount > 1 and geneCount < 6:\n\t\t\tdisruptionDict['2-5'] += 1\n\t\tif geneCount > 5 and geneCount < 11:\n\t\t\tdisruptionDict['6-10'] += 1\n\t\tif geneCount > 10 and geneCount < 21:\n\t\t\tdisruptionDict['11-20'] += 1\n\t\tif geneCount > 20:\n\t\t\tdisruptionDict['>20'] += 1\n\nprint(disruptions)\n\n#Make a histogram showing how frequently how many genes are disrupted\nimport matplotlib.pyplot as plt\n\nlabels = ['1', '2-5', '6-10', '11-20', '>20']\nvalues = [disruptionDict['1'], disruptionDict['2-5'], disruptionDict['6-10'], disruptionDict['11-20'], disruptionDict['>20']]\n\t\t\nfig, ax = plt.subplots()\ny = np.arange(len(labels))\nax.bar(y, values)\nax.set_xticks(y)\nax.set_xticklabels(labels)\nax.set_xlabel('Number of genes in TADs with SV breakpoints')\nax.set_ylabel('Number of SVs')\n\t\nplt.savefig(finalOutDir + '/figS1.svg')\n\n\n\n","sub_path":"src/linkSVsGenes/getGeneCountPerTad.py","file_name":"getGeneCountPerTad.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"530765607","text":"\"\"\"\nparse_xml.py\n\nExtracts specific metadata from XML files. \nStores them into an Elasticsearch (ES) index.\nARG[1]: path of the folder where XML data is stored\n\nExample:\npython parse_xml_files.py ../data\n\nTODO:\n* Replicate for storing in another type of database\n* Allow adding data to ES index without restarting from scratch\n\"\"\"\n\nimport sys\nfrom lxml import etree\nimport json\nfrom elasticsearch import Elasticsearch\n\ndef launchElasticHost(index_name, type_name):\n\t\"\"\"\n\tReset and create an Elasticseach host\n\tINPUT[1]: index_name (str)\n\tINPUT[2]: type_name (str)\n\tOUTPUT[1]: es (Elasticsearch host)\n\t\"\"\"\n\n\tfrom elasticsearch import Elasticsearch\n\tES_HOST = {\"host\" : \"localhost\", \"port\" : 9200}\n\t# Since we are running locally, use one shard and no replicas:\n\trequest_body = {\n\t \"settings\" : {\n\t \"number_of_shards\": 1,\n\t \"number_of_replicas\": 0\n\t }\n\t}\n\t# Create the ES client:\n\tes = Elasticsearch(hosts = [ES_HOST])\n\t# Create/reset the ES index:\n\tif es.indices.exists(index_name):\n\t\tprint(\"Deleting previous version of '%s' index...\" % (index_name))\n\t\tres = es.indices.delete(index = index_name)\n\t\tprint(\" RESPONSE: '%s'\" % (res))\n\tprint(\"Creating '%s' index...\" % (index_name))\n\tres = es.indices.create(index = index_name, body = request_body)\n\tprint(\" RESPONSE: '%s'\" % (res))\n\treturn es\n\ndef bulkIndexData(index_name, bulk_data, es_host):\n\t\"\"\"\n\tBulk-indexes the data of data_dict using the current ES host\n\tINPUT[1]: index_name (str)\n\tINPUT[2]: bulk_data (array of 2 dicts)\n\tINPUT[3]: es_host (Elasticsearch)\n OUTPUT[1]: res (ES bulk)\n\t\"\"\"\n\t# Bulk index the data\n\tprint(\"Bulk indexing...\")\n\tres = es_host.bulk(index = index_name, body = bulk_data, refresh = True)\n\treturn res\n\n\nindex_name = \"corpus_simple\"\ntype_name = \"article\"\n\n# Create the ES index\nes = launchElasticHost(index_name, type_name)\nid_dict = 1\n\n# Account for the fact that pubmed1840.xml is empty!\nnb_of_xml_files = 2279\nmissing_xml = 1839\nfor i in [x for x in range(nb_of_xml_files + 1) if x != missing_xml]:\n\n\t# Define the name of the input (XML file):\n\txml_input_path = sys.argv[1] + '/'\n\txml_input_file = xml_input_path + \"pubmed\" + str(i+1) + \".xml\"\n\n\t# Create an empty dict for storing values of the i-th file:\n\tdict_output_all = {}\n\n\tbulk_data = []\n\t# Parse the XML file:\n\ttree = etree.parse(xml_input_file)\n\tfor result in tree.xpath(\"//result\"):\t\n\t\t# For the meta-data line in the bulk file for ES:\n\t\top_dict = {\"index\": {\"_index\": index_name, \"_type\": type_name, \"_id\": id_dict}}\n\t\tdata_dict = {}\n\t\t# result.getchildren() is a list:\n\t\tfor r in result.getchildren():\n\t\t\t######## CONTENT OF 1 data_dict #############\n\t\t\t# Get the article id:\n\t\t\tif(r.tag==\"id\"):\n\t\t\t\tdata_dict[\"id_pubmed\"] = r.text\n\t\t\t# Get the article title:\n\t\t\tif(r.tag==\"title\"):\n\t\t\t\tdata_dict[\"title\"] = r.text\n\t\t\t# Get the article's abstract text:\n\t\t\tif(r.tag==\"abstractText\"):\n\t\t\t\tdata_dict[\"abstract\"] = r.text\n\t\t\t# Get the affiliation of the lead author:\n\t\t\tif(r.tag==\"affiliation\"):\n\t\t\t\tdata_dict[\"affiliation\"] = r.text\n\t\t\t# Get the publication date:\n\t\t\tif(r.tag==\"firstPublicationDate\"):\n\t\t\t\tdata_dict[\"publication_date\"] = r.text\n\t\t\t# Get the journal title (ISO abbreviation format):\n\t\t\tif(r.tag==\"journalInfo\"):\n\t\t\t\tfor r2 in r.getchildren():\n\t\t\t\t\tif(r2.tag==\"journal\"):\n\t\t\t\t\t\tfor r3 in r2.getchildren():\n\t\t\t\t\t\t\tif(r3.tag==\"ISOAbbreviation\"):\n\t\t\t\t\t\t\t\tdata_dict[\"journal_name\"] = r3.text\n\t\t\t# Get the keywords:\n\t\t\tkeyword_list = []\n\t\t\tif(r.tag==\"keywordList\"):\n\t\t\t\tfor r2 in r.getchildren():\n\t\t\t\t\tkeyword_list.append(r2.text)\n\t\t\t\tdata_dict[\"keyword_list\"] = ','.join(keyword_list)\n\t\t\t# Get the meshwords:\n\t\t\tmesh_list = []\n\t\t\tif(r.tag==\"meshHeadingList\"):\n\t\t\t\tfor r2 in r.getchildren():\n\t\t\t\t\tif(r2.tag==\"meshHeading\"):\n\t\t\t\t\t\tfor r3 in r2.getchildren():\n\t\t\t\t\t\t\tif(r3.tag==\"descriptorName\"):\n\t\t\t\t\t\t\t\tmesh_list.append(r3.text)\n\t\t\t\tdata_dict[\"mesh_list\"] = ','.join(mesh_list)\n\t\tbulk_data.append(op_dict)\n\t\tbulk_data.append(data_dict)\n\t\tid_dict = id_dict + 1\n\tprint(xml_input_file + ':')\n\tres = bulkIndexData(index_name, bulk_data, es)\n","sub_path":"parse_xml_files.py","file_name":"parse_xml_files.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"459349359","text":"#!/usr/local/biotools/python/3.4.3/bin/python3\r\n__author__ = \"Naresh Prodduturi\"\r\n__email__ = \"prodduturi.naresh@mayo.edu\"\r\n__status__ = \"Dev\"\r\n\r\nimport os\r\nimport argparse\r\nimport sys\r\nimport pwd\r\nimport time\r\nimport subprocess\r\nimport re\r\nimport shutil\r\nimport glob\t\r\nimport openslide\r\nimport numpy as np\r\nfrom PIL import Image, ImageDraw\r\n\r\nimport tensorflow as tf\r\nimport io\r\nfrom dataset_utils import * \r\n'''function to check if input files exists and valid''' \t\r\ndef input_file_validity(file):\r\n\t'''Validates the input files'''\r\n\tif os.path.exists(file)==False:\r\n\t\traise argparse.ArgumentTypeError( '\\nERROR:Path:\\n'+file+':Does not exist')\r\n\tif os.path.isfile(file)==False:\r\n\t\traise argparse.ArgumentTypeError( '\\nERROR:File expected:\\n'+file+':is not a file')\r\n\tif os.access(file,os.R_OK)==False:\r\n\t\traise argparse.ArgumentTypeError( '\\nERROR:File:\\n'+file+':no read access ')\r\n\treturn file\r\n\r\n\r\ndef argument_parse():\r\n\t'''Parses the command line arguments'''\r\n\tparser=argparse.ArgumentParser(description='')\r\n\tparser.add_argument(\"-p\",\"--patch_dir\",help=\"Patch dir\",required=\"True\")\r\n\tparser.add_argument(\"-i\",\"--input_file\",help=\"input file\",required=\"True\")\r\n\tparser.add_argument(\"-o\",\"--tf_output\",help=\"output tf dir\",required=\"True\")\r\n\tparser.add_argument(\"-s\",\"--patch_size\",help=\"Patch_size\",required=\"True\")\r\n\treturn parser\r\n\r\n\r\n \r\ndef create_patch(svs,patch_sub_size,patch_dir,samp,p,tf_output):\r\n\t#print(svs+' '+str(patch_sub_size)+' '+patch_dir+' '+samp+' '+' '+tf_output)\r\n\t\r\n\tthreshold=200\r\n\tlevel=3\r\n\tOSobj = openslide.OpenSlide(svs)\r\n\tminx = 0\r\n\tminy = 0\r\n\t#maxx = OSobj.dimensions[0]\r\n\t#maxy = OSobj.dimensions[1]\r\n\t#print(OSobj.dimensions)\r\n\t#print(OSobj.level_dimensions)\r\n\t#print(OSobj.level_downsamples)\r\n\t#sys.exit(0)\r\n\t#print(OSobj.level_dimensions[1])\r\n\t#print(OSobj.level_dimensions[2])\r\n\tprint(\"Level_count \"+str(OSobj.level_count))\r\n\tif OSobj.level_count <= 3:\r\n\t\tprint(\"No enough levels\")\r\n\t\tsys.exit(0)\r\n\ttf_writer=tf.python_io.TFRecordWriter(tf_output+'/'+samp+'.tfrecords')\t\r\n\ttmp=OSobj.level_dimensions[level]\r\n\tmaxx = tmp[0]\r\n\tmaxy = tmp[1]\r\n\t#this factor if required to convert level0 start coordinatess to level2 start coordinates (this is required for OSobj.read_region function)\r\n\tmulti_factor=OSobj.level_downsamples[level]\r\n\t#print(svs+' '+str(patch_sub_size)+' '+patch_dir+' '+str(maxx))\r\n\tstart_x=minx\t\r\n\t'''creating sub patches'''\t\r\n\t'''Iterating through x coordinate'''\t\r\n\tcurrent_x=0\r\n\tfilenames=[]\r\n\t#num=0\r\n\twhile start_x+patch_sub_size < maxx:\r\n\t\t'''Iterating through y coordinate'''\r\n\t\tcurrent_y=0\r\n\t\tstart_y=miny\r\n\t\twhile start_y+patch_sub_size < maxy:\r\n\t\t\ttmp_start_x=int(round(start_x*multi_factor,0))\r\n\t\t\ttmp_start_y=int(round(start_y*multi_factor,0))\r\n\t\t\ttry: \r\n\t\t\t\timg_patch = OSobj.read_region((tmp_start_x,tmp_start_y), level, (patch_sub_size, patch_sub_size))\r\n\t\t\texcept:\r\n\t\t\t\t\tprint(\"error in open slide\")\r\n\t\t\t\t\tsys.exit(0)\r\n\t\t\t#img_patch = OSobj.read_region((start_x,start_y), level, (maxx, maxy))\r\n\t\t\t#num=num+1\r\n\t\t\t#img_patch.save(patch_dir+'/'+str(num)+'.png', \"png\")\r\n\t\t\t#sys.exit(1)\r\n\t\t\tnp_img = np.array(img_patch)\r\n\t\t\tim_sub = Image.fromarray(np_img)\r\n\t\t\twidth, height = im_sub.size\r\n\t\t\t'''Change to grey scale'''\r\n\t\t\tgrey_img = im_sub.convert('L')\r\n\t\t\t'''Convert the image into numpy array'''\r\n\t\t\tnp_grey = np.array(grey_img)\r\n\t\t\tpatch_mean=round(np.mean(np_grey),2)\r\n\t\t\tpatch_std=round(np.std(np_grey),2)\r\n\t\t\t'''Identify patched where there are tissues'''\r\n\t\t\t'''tuple where first element is rows, second element is columns'''\r\n\t\t\t#idx = np.where(np_grey < threshold)\r\n\t\t\t'''proceed further only if patch has non empty values'''\r\n\t\t\t#if len(idx[0])>0 and len(idx[1])>0 and width==patch_sub_size and height==patch_sub_size:\r\n\t\t\tif patch_mean<245 and patch_std>4 and width==patch_sub_size and height==patch_sub_size:\r\n\t\t\t#if patch_mean<255:\r\n #if width==patch_sub_size and height==patch_sub_size:\r\n\t\t\t\t#print(\"sucess\")\r\n\t\t\t\t'''creating patch name'''\r\n\t\t\t\tnum_patch=samp+\"_X_\"+str(start_x)+\"_\"+str(start_x+patch_sub_size)+\"_Y_\"+str(start_y)+\"_\"+str(start_y+patch_sub_size)\r\n\t\t\t\tfilenames.append(num_patch)\r\n\t\t\t\t#tmp_png=patch_dir+'/'+num_patch+'.png'\r\n\t\t\t\t'''saving image'''\r\n\t\t\t\t#im_sub.save(tmp_png, \"png\")\r\n\t\t\t\t#sys.exit(1)\r\n\t\t\t\timage_format=\"png\" \r\n\t\t\t\theight=patch_sub_size\r\n\t\t\t\twidth=patch_sub_size \r\n\t\t\t\timage_name=num_patch \r\n\t\t\t\tsub_type=2\r\n\t\t\t\tif p[1] == \"ADC\":\r\n\t\t\t\t\tsub_type=0\r\n\t\t\t\tif\tp[1] == \"SQCC\":\r\n\t\t\t\t\tsub_type=1\r\n\t\t\t\t#sub_type=p[1]\r\n\r\n\t\t\t\timgByteArr = io.BytesIO()\r\n\t\t\t\tim_sub.save(imgByteArr, format='PNG')\r\n\t\t\t\timgByteArr = imgByteArr.getvalue()\r\n\t\t\t\trecord=image_to_tfexample_tcga(imgByteArr,image_format,int(height),int(width),image_name, sub_type)\r\n\t\t\t\ttf_writer.write(record.SerializeToString())\r\n\t\t\tstart_y\t= start_y+patch_sub_size\r\n\t\t\tcurrent_y = current_y+patch_sub_size\r\n\t\tstart_x = start_x+patch_sub_size\t\r\n\t\tcurrent_x = current_x+patch_sub_size\t\r\n\t#sys.exit(1)\r\n\ttf_writer.close()\r\n\treturn filenames\r\n\t\r\ndef main():\t\r\n\tabspath=os.path.abspath(__file__)\r\n\twords = abspath.split(\"/\")\r\n\t'''reading the config filename'''\r\n\tparser=argument_parse()\r\n\targ=parser.parse_args()\r\n\t'''printing the config param'''\r\n\tprint(\"Entered INPUT Filename \"+arg.input_file)\r\n\tprint(\"Entered Output Patch Directory \"+arg.patch_dir)\r\n\tprint(\"Entered Output TF Directory \"+arg.tf_output)\r\n\tprint(\"Entered Patch size \"+arg.patch_size)\r\n\r\n\tpatch_sub_size=int(arg.patch_size)\r\n\tpatch_dir=arg.patch_dir\r\n\ttf_output=arg.tf_output\r\n\t'''Reading TCGA file'''\r\n\tfobj = open(arg.input_file)\r\n\t#header = fobj.readline()\r\n\tfor file in fobj:\r\n\t\tfile = file.strip()\r\n\t\tp = file.split(\"\\t\")\r\n\t\tsamp=p[0]\r\n\t\tsvs_file=p[2]\r\n\t\tset=p[1]\r\n\t\tfilenames=create_patch(svs_file,patch_sub_size,patch_dir,samp,p,tf_output)\r\n\r\n\tfobj.close()\r\n\r\n\r\n\t\r\nif __name__ == \"__main__\":\r\n\tmain()","sub_path":"Create_TCGA_ImagePatches_level3.py","file_name":"Create_TCGA_ImagePatches_level3.py","file_ext":"py","file_size_in_byte":5755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"137342120","text":"import tkinter as tk\nimport pandas as pd\nimport random \n\nwindow = tk.Tk()\n\nwindow.columnconfigure([0,1,2,3,4,5,6,7,8,9], minsize=100)\nwindow.rowconfigure([0, 1], minsize=100)\n\n\nlabels = [\"Symbol\", \"Price\", \"R Vol 5 min\", \"R Vol 30 min\", \"R Vol\", \"Chg 5 Min(%)\", \"Chg 30 Min(%)\", \"Chg since close(%)\", \"Last Updated On\"]\n\n\n# TOP MENU.\nfor i in range(len(labels)):\n\tlabel1 = tk.Button(text=labels[i],width=15)\n\tlabel1.grid(row=0, column=i, sticky=\"n\")\n\n\nsymbols = [\"AAL.NQ\",\"XRAY.NQ\",\"UAL.NQ\",\"AMWL.NQ\",\"LYFT.NQ\",\"SEIC.NQ\",\"FROG.NQ\",\"YY.NQ\",\"LNC.NQ\"]\n\n\n\n\n## THOUGHT.\n\n# button = tk.Button(\n# text=\"Click me!\",\n# width=25,\n# height=5,\n# bg=\"blue\",\n# fg=\"yellow\",\n# )\n# frame1 = tk.Frame(master=window, width=100, height=100, bg=\"red\")\n# frame1.pack()\n# frame2 = tk.Frame(master=window, width=100, height=100, bg=\"blue\")\n# frame2.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)\n# frame3 = tk.Frame(master=window, width=100, height=100, bg=\"yellow\")\n# frame3.pack(fill=tk.BOTH, side=tk.LEFT, expand=True)\n\n# entry = tk.Entry(fg=\"yellow\", bg=\"blue\", width=50)\n# text_box = tk.Text()\n# text_box.pack()\n# entry.pack()\n# greeting.pack()\n# button.pack()\n\n# label1X = tk.Label(master=frame2, text=\"I'm at (0, 0)\", bg=\"red\")\n# label1X.place(x=0, y=0)\n\n\nwindow.mainloop()","sub_path":"UI/pair_viewer.py","file_name":"pair_viewer.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"646231513","text":"#!/usr/env/bin python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport sys\r\n\r\ndef trans(filename, newfilename):\r\n ws = []\r\n with open(filename) as file:\r\n for line in file:\r\n line = line.strip()\r\n if line == '':\r\n continue\r\n tws = []\r\n tw = line.split(' ')[1:]\r\n for w in tw:\r\n w = w.strip()\r\n if w == '':\r\n continue\r\n w = w.decode('utf-8')\r\n for i in range(len(w)):\r\n #print w\r\n if i == 0:\r\n tws.append((w[i].encode('utf-8'), 'B'))\r\n continue\r\n tws.append((w[i].encode('utf-8'), 'I'))\r\n if len(tws) > 0:\r\n ws.append(tws)\r\n if len(ws) > 0:\r\n with open(newfilename, 'w') as file:\r\n for tws in ws:\r\n for char in tws:\r\n file.write(' '.join([w for w in char]) + '\\n')\r\n file.write('\\n')\r\n\r\nif __name__ == '__main__':\r\n trans(sys.argv[1], sys.argv[2])","sub_path":"seg/pre.py","file_name":"pre.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"263539848","text":"from __future__ import division\n\nimport math\nimport numpy as np\n\n__all__ = [\"gaussian_plus_moffat_psf\", \"psf_3d_from_params\"]\n\ndef gaussian_plus_moffat_psf(shape, xctr, yctr, ellipticity, alpha, angle):\n \"\"\"Evaluate a gaussian+moffat function on a 2-d grid. \n\n Parameters\n ----------\n shape : 2-tuple\n (ny, nx) of output array.\n xctr, yctr : float\n Center of PSF in array coordinates. (0, 0) = centered on lower left\n pixel.\n ellipticity: float\n alpha : float\n angle : float\n\n Returns\n -------\n psf : 2-d array\n The shape will be (len(y), len(x)) \n \"\"\"\n\n ny, nx = shape\n alpha = abs(alpha)\n ellipticity = abs(ellipticity)\n \n # Correlated params\n s1 = 0.215\n s0 = 0.545\n b1 = 0.345\n b0 = 1.685\n e1 = 0.0\n e0 = 1.04\n\n # Moffat\n sigma = s0 + s1*alpha\n beta = b0 + b1*alpha\n eta = e0 + e1*alpha\n\n # In the next line, output arrays are 2-d, both with shape (ny, nx).\n # dx, for example, gives the dx value at each point in the grid.\n dx, dy = np.meshgrid(np.arange(nx) - xctr, np.arange(ny) - yctr)\n\n # Offsets in rotated coordinate system (dx', dy')\n dx_prime = dx * math.cos(angle) - dy * math.sin(angle)\n dy_prime = dx * math.sin(angle) + dy * math.cos(angle)\n r2 = dx_prime**2 + ellipticity * dy_prime**2\n\n # Gaussian, Moffat\n gauss = np.exp(-r2 / (2. * sigma**2))\n moffat = (1. + r2 / alpha**2)**(-beta)\n\n # scalars normalization\n norm_moffat = 1./math.pi * math.sqrt(ellipticity) * (beta-1.) / alpha**2\n norm_gauss = 1./math.pi * math.sqrt(ellipticity) / (2. * eta * sigma**2)\n norm_psf = 1. / (1./norm_moffat + eta * 1./norm_gauss)\n\n return norm_psf * (moffat + eta*gauss)\n\n\ndef psf_3d_from_params(params, wave, wave_ref, shape):\n \"\"\"Create a wavelength-dependent Gaussian+Moffat PSF from given\n parameters.\n\n Parameters\n ----------\n params : 4-tuple\n Ellipticty and polynomial parameters in wavelength\n wave : np.ndarray (1-d)\n Wavelengths\n wave_ref : float\n Reference wavelength\n shape : 2-tuple\n (ny, nx) shape of spatial component of output array.\n\n Returns\n -------\n psf : 3-d array\n Shape is (nw, ny, nx) where (nw,) is the shape of wave array.\n PSF will be spatially centered in array.\n \"\"\"\n\n relwave = wave / wave_ref - 1.\n ellipticity = params[0]\n alpha = params[1] + params[2]*relwave + params[3]*relwave**2\n\n nw = len(wave)\n ny, nx = shape\n xctr = (nx - 1) / 2.\n yctr = (ny - 1) / 2.\n psf = np.empty((nw, ny, nx), dtype=np.float)\n for i in range(nw):\n psf2d = gaussian_plus_moffat_psf(shape, xctr, yctr, ellipticity,\n alpha[i], 0.0)\n psf2d /= np.sum(psf2d) # normalize array sum to 1.0.\n psf[i, :, :] = psf2d\n\n return psf\n","sub_path":"cubefit/psf.py","file_name":"psf.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"248327411","text":"# Open a csv file, load specified row.\n# Input indexing starts at 1\nimport csv\nimport sys\n\nsource_f = sys.argv[1]\nsource_n = int(sys.argv[2]) - 1\n\ncsvfile = open(source_f, 'rb')\ncsvfreader = csv.reader(csvfile)\n\nfor rowi, row in enumerate(csvfreader):\n if rowi == source_n:\n print(row)\n break\n\ncsvfile.close()\n","sub_path":"DataProcessing/row_retrieve_csv.py","file_name":"row_retrieve_csv.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"107783923","text":"# %load q01_outlier_removal/build.py\n# Default imports\nimport pandas as pd\n\nloan_data = pd.read_csv('data/loan_prediction_uncleaned.csv')\nloan_data = loan_data.drop('Loan_ID', 1)\n\n\n# Write your Solution here:\ndef outlier_removal(df):\n num_col=df[['ApplicantIncome','CoapplicantIncome',\n 'LoanAmount']]\n quant=num_col.quantile(0.95)\n for col in num_col:\n df=df.drop(df[df[col]>quant[col]].index)\n return df\nprint(outlier_removal(loan_data))\n\n\n","sub_path":"q01_outlier_removal/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"492834049","text":"from torch.distributions import Categorical\nimport gym\nfrom network import mlp\nfrom torch.optim import Adam\nimport torch.nn as nn\nimport torch\nimport numpy as np\n\nimport time\n\ndef train(env_name='CartPole-v0', hidden_node=[32], activations=[nn.Tanh, nn.Identity], batch_size=5000, epochs=1000, optimizer=Adam, lr=1e-2):\n \n env = gym.make(env_name)\n\n obs_dim = env.observation_space.shape[0]\n act_dim = env.action_space.n\n\n logits_net = mlp([obs_dim]+hidden_node+[act_dim], [nn.Tanh, nn.Identity])\n\n optimizer = optimizer(logits_net.parameters(), lr=lr)\n\n def policy(obs):\n logits = logits_net(obs)\n return Categorical(logits=logits)\n\n def get_action(obs):\n return policy(obs).sample().item()\n\n def get_loss(obs, act, weight):\n logp = policy(obs).log_prob(act)\n\n # simplest policy gradient\n # - for gradient ascent \n return -(logp * weight).mean()\n\n def train_one_epoch():\n batch_ret = []\n batch_len = []\n batch_obs = []\n batch_act = []\n \n # for caulculating policy gradient \n batch_weights = []\n\n eps_rwd = []\n obs = env.reset()\n\n while True:\n act = get_action(torch.as_tensor(obs, dtype=torch.float32))\n batch_obs.append(obs)\n \n obs, rwd, done, _ = env.step(act)\n\n batch_act.append(act) \n eps_rwd.append(rwd)\n\n if done:\n eps_ret, eps_len = sum(eps_rwd), len(eps_rwd)\n batch_ret.append(eps_ret)\n batch_len.append(eps_len)\n batch_weights += [eps_ret] * eps_len\n\n obs = env.reset()\n eps_rwd = []\n\n if len(batch_obs) > batch_size:\n break\n\n optimizer.zero_grad()\n batch_loss = get_loss(torch.as_tensor(batch_obs, dtype=torch.float32),\n torch.as_tensor(batch_act, dtype=torch.int32),\n torch.as_tensor(batch_weights, dtype=torch.float32)\n )\n\n batch_loss.backward()\n optimizer.step()\n\n return batch_ret, batch_len, batch_loss\n\n for i in range(epochs):\n batch_ret, batch_len, batch_loss = train_one_epoch()\n print(f'epoch: {i: 3d} \\t loss: {batch_loss: .3f} \\\n \\t ret: {np.mean(batch_ret): .3f} {np.std(batch_ret): .3f} {np.min(batch_ret): .3f} {np.max(batch_ret): .3f} \\\n \\t len: {np.mean(batch_len): .3f} {np.std(batch_len): .3f} {np.min(batch_len): .3f} {np.max(batch_len): .3f}')\n\n obs = env.reset()\n done = False\n\n try:\n while True:\n env.render()\n act = get_action(torch.as_tensor(obs, dtype=torch.float32))\n obs, rwd, done, _ = env.step(act)\n\n if done:\n break\n\n except KeyboardInterrupt:\n print('stop')\n\nif __name__=='__main__':\n env_name = 'Breakout-ram-v0'\n train(env_name=env_name)","sub_path":"simplePG.py","file_name":"simplePG.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"61698389","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# __author__ = 'Arthur|http://wingedwhitetiger.com/'\n\nimport os\nimport random\nfrom PySide2 import QtWidgets, QtCore, QtGui\n\n\nclass AssetLabel(QtWidgets.QWidget):\n def __init__(self, asset_type, tag=[], material_tag=[], parent=None):\n super(AssetLabel, self).__init__(parent)\n\n '''init data'''\n abc = QtGui.QPixmap()\n self.__palette = ['black', 'orange', 'pink', 'maroon', 'olive', 'Goldenrod', 'Lightslategray',\n 'red', 'darkRed', 'darkCyan', 'magenta', 'darkMagenta', 'green', 'darkGreen', 'blue',\n 'darkBlue', 'gray', 'darkGray']\n self.__type_dict = dict()\n self.__type_label_list = list()\n\n for key, value in {'abc': '../../../../Icons/alembic.png',\n 'vdb': '../../../../Icons/openvdb.png'}.iteritems():\n abc.load(os.path.join(__file__, value))\n self.__type_dict[key] = abc.scaled(30, 30, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation)\n self.__type_label_list.append(QtWidgets.QLabel())\n\n '''create layout'''\n main_layout = QtWidgets.QVBoxLayout(self)\n main_layout.setContentsMargins(0, 0, 0, 0)\n main_layout.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)\n\n type_layout = QtWidgets.QHBoxLayout()\n type_layout.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n\n tag_layout = QtWidgets.QHBoxLayout()\n tag_layout.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n\n self.__tag_layout = QtWidgets.QHBoxLayout()\n self.__tag_layout.setContentsMargins(0, 0, 0, 0)\n self.__tag_layout.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n\n material_layout = QtWidgets.QHBoxLayout()\n material_layout.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n # material_layout.setContentsMargins(0, 0, 0, 0)\n\n self.__material_layout = QtWidgets.QHBoxLayout()\n self.__material_layout.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n self.__material_layout.setContentsMargins(0, 0, 0, 0)\n\n '''create widget'''\n asset_type_label = QtWidgets.QLabel()\n asset_type_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n asset_type_label.setText(' %s' % ('#d5d5d5', '(Type)'))\n tag_label = QtWidgets.QLabel()\n tag_label.setText(' %s' % ('#d5d5d5', '(Tags)'))\n tag_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n\n tag_widget = QtWidgets.QWidget()\n tag_widget.setStyleSheet(\"QLabel{padding: 0px;border: 2px solid #f2f2f2;border-radius:1px;\"\n \"font: bold 15px/25px Arial, sans-serif;color:#f2f2f2;qproperty-alignment:\"\n \"AlignCenter;}\")\n\n material_label = QtWidgets.QLabel()\n material_label.setText(' %s' % ('#d5d5d5', '(Material Tags)'))\n material_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n\n material_widget = QtWidgets.QWidget()\n material_widget.setStyleSheet(\"QLabel{padding: 0px;border: 2px solid #f2f2f2;border-radius:1px;\"\n \"font: bold 15px/25px Arial, sans-serif;color:#f2f2f2;qproperty-alignment:\"\n \"AlignCenter;}\")\n\n '''add layout'''\n main_layout.addLayout(type_layout)\n main_layout.addLayout(tag_layout)\n main_layout.addLayout(material_layout)\n\n tag_widget.setLayout(self.__tag_layout)\n tag_widget.setFixedHeight(25)\n material_widget.setLayout(self.__material_layout)\n material_widget.setFixedHeight(25)\n\n '''add widget'''\n for i in self.__type_label_list:\n i.setFixedSize(30, 30)\n type_layout.addWidget(i)\n type_layout.addWidget(asset_type_label)\n\n tag_layout.addWidget(tag_widget)\n tag_layout.addWidget(tag_label)\n\n material_layout.addWidget(material_widget)\n material_layout.addWidget(material_label)\n\n self.update(asset_type, tag, material_tag)\n\n def update(self, type_list, tag=[], material_tag=[]):\n for i in self.__type_label_list:\n i.setPixmap(QtGui.QPixmap())\n for index, i in enumerate(type_list):\n if i in self.__type_dict:\n self.__type_label_list[len(self.__type_label_list)-index-1].setPixmap(self.__type_dict[i])\n\n # def clearLayout(layout):\n # while layout.count() > 0:\n # item = layout.takeAt(0)\n #\n # if not item:\n # continue\n #\n # w = item.widget()\n # if w:\n # w.deleteLater()\n\n for cnt in reversed(range(self.__tag_layout.count())):\n widget = self.__tag_layout.takeAt(cnt).widget()\n if widget is not None:\n # widget will be None if the item is a layout\n widget.deleteLater()\n\n for cnt in reversed(range(self.__material_layout.count())):\n widget = self.__material_layout.takeAt(cnt).widget()\n if widget is not None:\n # widget will be None if the item is a layout\n widget.deleteLater()\n\n # aa = ['yellow','Aquamarine','cyan']\n # clist = ['Slategray','darkCyan']\n\n for i in tag:\n tag = QtWidgets.QLabel(i)\n col = random.randint(0, len(self.__palette) - 1)\n tag.setStyleSheet(\"QLabel{background-color: %s;}\" % self.__palette[col])\n self.__tag_layout.addWidget(tag)\n\n for i in material_tag:\n tag = QtWidgets.QLabel(i)\n col = random.randint(0, len(self.__palette) - 1)\n tag.setStyleSheet(\"QLabel{background-color: %s;}\" % self.__palette[col])\n self.__material_layout.addWidget(tag)\n\nif __name__ == '__main__':\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n w = AssetLabel(['abc', 'vdb'], ['Vdb', 'Wa', 'Tga'], ['Arnold'])\n w.show()\n sys.exit(app.exec_())\n","sub_path":"WitRepository/Lib/python/pyside2Lib/assetLabelUI.py","file_name":"assetLabelUI.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"21826571","text":"\n## Real time video from webcamera\n\n\nimport numpy as np\nimport cv2\n\n# parameters\n\nthreshold = 100 # BINARY threshold\nblurValue = 41 # GaussianBlur parameter\nbgSubThreshold = 100\n\n# Constants for finding range of skin color in YCrCb\nmin_YCrCb = np.array([0,133,77],np.uint8)\nmax_YCrCb = np.array([255,173,127],np.uint8)\n\nfps = 30\n\ndef getImage():\n cv2.namedWindow(\"webcam-feed\")\n cam = cv2.VideoCapture(0)\n\n if cam.isOpened(): # try to get the first frame\n ret, frame = cam.read()\n else:\n ret = False\n frames = 1\n timer = 0\n img_counter = 0\n while ret:\n\n ret, frame = cam.read()\n #color = np.uint8([[[blue, green, red]]])\n #hsv_color = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n #defining the Range of yellow color\n yellow_lower=np.array([22,60,120],np.uint8)\n yellow_upper=np.array([60,255,255],np.uint8)\n\n #finding the range of yellow color in the image\n yellow=cv2.inRange(hsv,yellow_lower,yellow_upper)\n\n #Morphological transformation, Dilation\n kernal = np.ones((5 ,5), \"uint8\")\n\n yellow=cv2.dilate(yellow,kernal)\n res2=cv2.bitwise_and(frame, frame, mask = yellow)\n\n '''\n #Tracking the Red Color\n (_,contours,hierarchy)=cv2.findContours(red,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\n for pic, contour in enumerate(contours):\n area = cv2.contourArea(contour)\n if(area>300):\n x,y,w,h = cv2.boundingRect(contour)\n img = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)\n cv2.putText(img,\"RED color\",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255))\n '''\n\n\n\n mask = np.zeros(frame.shape[:-1],np.uint8)\n height, width = frame.shape[:-1]\n mask1 = np.zeros((height+2, width+2), np.uint8) # line 26\n cv2.floodFill(mask,mask1,(0,0),255) # line 27\n\n #Tracking the yellow Color\n (_,contours,hierarchy)=cv2.findContours(yellow,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n areaMax = 100\n x = 0\n y = 0\n w = 0\n h = 0\n area = 00\n bigContour = None\n for pic, contour in enumerate(contours):\n area = cv2.contourArea(contour)\n if area > areaMax:\n areaMax = area\n bigContour = contour\n\n x,y,w,h = cv2.boundingRect(bigContour)\n frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)\n res2 = cv2.rectangle(res2,(x,y),(x+w,y+h),(0,255,0),2)\n # Write some Text\n font = cv2.FONT_HERSHEY_SIMPLEX\n bottomLeftCornerOfText = (10,500)\n position = (int(x+h/2),int(y+h/2))\n fontScale = 1\n fontColor = (0,255,0)\n lineType = 2\n cv2.imshow(\"Color Tracking\",frame)\n cv2.putText(res2,\"+\", position,font,fontScale,fontColor,lineType)\n\n #cv2.putText(res2,\"yellow\",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0))\n\n #cv2.imshow(\"Redcolour\",red)\n #cv2.imshow(\"red\",res)\n cv2.imshow(\"yellow\",res2)\n\n frames+=1\n timer = int(frames/fps)\n key = cv2.waitKey(20) # milliseconds\n if frames%30 == 0:\n print(\"Time: {} secs \\r\".format(timer),end=\"\")\n if key==27 : # ESC pressed\n print(\"\\nEscape hit, closing...\")\n break\n\n if key == 32: # SPACE pressed\n img_name = \"opencv_frame_{}.png\".format(img_counter)\n cv2.imwrite(img_name, frame)\n print(\"{} written!\".format(img_name))\n img_counter += 1\n cam.release()\n cv2.destroyAllWindows()\n cv2.destroyWindow(\"yellow\")\n\ngetImage()\n","sub_path":"backend/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"79596908","text":"import numpy as np\nimport wave\nimport time\nimport glob\nimport pyworld.pyworld as pw\nimport os\n\nimport util\n\n\nclass VoiceToDataset:\n \"\"\"\n WAVEデータ群をパッチデータに変換する\n\n Attributes\n ----------\n voice_dir : str\n WAVEデータ群が格納されているルートディレクトリ\n train_dir : str\n 学習用データを保存するディレクトリ\n term : int\n 音響特性を計算するときのブロックサイズ\n rate : int\n WAVEデータのサンプリング周波数\n \"\"\"\n def __init__(self, voice_dir, train_dir, term=4096, rate=16000, fft_size=1024):\n \"\"\"\n Parameters\n ----------\n voice_dir : str\n WAVEデータ群が格納されているルートディレクトリ\n train_dir : str\n 学習用データを保存するディレクトリ\n term : int optional\n 音響特性を計算するときのブロックサイズ\n rate : int optional\n WAVEデータのサンプリング周波数\n \"\"\"\n self.voice_dir = voice_dir\n self.train_dir = train_dir\n self.fft_size = fft_size\n self.term = term\n self.rate = rate\n\n def convert(self, source, target):\n \"\"\"\n 第一, 第二話者のデータを変換する\n\n Parameters\n ----------\n source : str\n 第一話者名、実際のWAVEデータはこの名前のサブディレクトリに格納されていること\n target : str\n 第二話者名、実際のWAVEデータはこの名前のサブディレクトリに格納されていること\n\n Returns\n -------\n plof : np.array [第一話者と第二話者のピッチ平均の差, 第一話者と第二話者のピッチの標準偏差の比]\n 第一話者のf0を第二話者に変換したいときは (f0 - plof[0]) * plof[1]\n \"\"\"\n pitch = {}\n for name in [source, target]:\n files = sorted(\n glob.glob(os.path.join(self.voice_dir, name, \"*.wav\")))\n ff = list()\n m = list()\n for file in files:\n print(\" [*] パッチデータに変換を開始します。 :\", file)\n wf = wave.open(file, 'rb')\n dms = wf.readframes(wf.getnframes())\n data = np.frombuffer(dms, 'int16')\n data_real = (data / 32767).reshape(-1).astype(np.float)\n times = (data_real.shape[0] - 1) // self.term + 1\n\n endpos = data_real.shape[0] % self.term\n for i in range(times):\n data_realAb = data_real[max(endpos -\n self.term, 0):endpos].copy()\n shortage = self.term - data_realAb.shape[0]\n if shortage > 0:\n data_realAb = np.pad(data_realAb, (shortage, 0),\n \"constant\")\n\n f0, psp, _ = util.encode(data_realAb, self.rate, fft_size=self.fft_size, frame_period=5.0)\n ff.extend(f0[f0 > 0.0])\n m.append(psp)\n\n endpos += self.term * i\n\n m = np.asarray(m, dtype=np.float32)\n np.save(os.path.join(self.train_dir, name + \".npy\"), m)\n print(\" [*] \" + name + \"データ変換完了\")\n pitch[name] = {}\n pitch[name][\"mean\"] = np.mean(ff)\n pitch[name][\"var\"] = np.std(ff)\n\n pitch_mean_s = pitch[source][\"mean\"]\n pitch_var_s = pitch[source][\"var\"]\n pitch_mean_t = pitch[target][\"mean\"]\n pitch_var_t = pitch[target][\"var\"]\n\n plof = np.asarray([pitch_mean_s - pitch_mean_t, pitch_var_t / pitch_var_s])\n return plof\n\n","sub_path":"original/voice_to_dataset.py","file_name":"voice_to_dataset.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"457058629","text":"#\n# @lc app=leetcode.cn id=403 lang=python3\n#\n# [403] 青蛙过河\n#\n\n# @lc code=start\nclass Solution:\n def canCross(self, stones: List[int]) -> bool:\n jumps={}\n for stone in stones:\n jumps[stone]=set()\n jumps[0].add(0)\n \n for stone in stones:\n for jump in jumps[stone]:\n for shift in [-1,0,1]:\n if jump+shift>0 and stone+jump+shift in jumps:\n jumps[stone+jump+shift].add(jump+shift)\n return bool(jumps[stones[-1]])\n# @lc code=end\n\n","sub_path":"Week_06/G20200343040276/403.青蛙过河.py","file_name":"403.青蛙过河.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"236268830","text":"# coding=utf-8\n# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nfrom test_pants_plugin.subsystems.pants_test_infra import PantsTestInfra\n\nfrom pants.backend.python.targets.python_tests import PythonTests\n\n\nclass PantsInfraTests(object):\n\n def __init__(self, parse_context):\n self._parse_context = parse_context\n self._pants_test_infra = PantsTestInfra.global_instance()\n\n def __call__(self, dependencies=[], **kwargs):\n dependencies.extend(self._pants_test_infra.dependent_target_addrs())\n self._parse_context.create_object(\n PythonTests.alias(), dependencies=dependencies, **kwargs)\n","sub_path":"testprojects/pants-plugins/src/python/test_pants_plugin/pants_infra_tests.py","file_name":"pants_infra_tests.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"29276278","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, timedelta, date\nimport re\nfrom collections import ChainMap\n\ntry:\n from lxml import etree\nexcept ImportError:\n import xml.etree.ElementTree as etree\n\ndef get_response(initial_url):\n headers = {\n 'Connection':'keep-alive',\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36',\n }\n response = requests.get(initial_url, headers=headers)\n response.encoding='utf-8'\n return response.text\n\ndef get_urls(initial_url):\n response = get_response(initial_url)\n soup = BeautifulSoup(response.text, 'lxml')\n url_selector = soup.select('dl ul li a')\n date_selector = soup.select('dl ul li.price')\n effective_date = datetime.now() - timedelta(weeks=4) # 有效时间为当前时间往前的四周\n useless_url_num = 0\n for url, date in zip(url_selector, date_selector):\n # for each in date_selector:\n extract_date = date.text.split()[0]\n year, month, day = extract_date.split('-')\n begin_date = datetime(int(year), int(month), int(day))\n if begin_date > effective_date:\n # print(begin_date)\n print(url.get('href') + ' ' + date.text)\n else:\n useless_url_num += 1\n if useless_url_num == len(url_selector):\n raise PageUselessException('This page and after is useless')\n\ndef get_item_info(item_url):\n response = get_response(item_url)\n soup = BeautifulSoup(response, 'lxml')\n title_selector = soup.select('h2')\n time_selector = soup.select('td h1')\n area_selector = soup.select('table tr td')\n info_selector = soup.select('div.w770')\n contact_id = re.findall(\"'moduleid=5&html=show&itemid=(.*?)'\", response, re.S)[0]\n contact_dict = get_contact_info('http://www.cnzhantuan.com/api/task.js.php?moduleid=5&html=show&itemid={}'.format(contact_id))\n data = {\n 'title': title_selector[0].text if title_selector else None,\n 'time' : time_selector[0].text if time_selector else None,\n 'venues' : area_selector[5].text if area_selector else None,\n 'location' : area_selector[7].text if area_selector else None,\n 'price' : area_selector[9].text if area_selector else None,\n 'last_updated' : area_selector[15].text if area_selector else None,\n 'info' : list(info_selector[0].stripped_strings) if info_selector else None,\n }\n merged_data = dict({'contact_info': contact_dict})\n merged_data.update(data)\n # all_data = ChainMap(data, {'contact_info':contact_dict})\n # all_data = data.update({'contact_info':contact_dict})\n # print(all_data)\n print(merged_data)\n # print(data)\n\ndef get_contact_info(url):\n headers = {\n 'Connection':'keep-alive',\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36',\n 'Referer':'{}'.format(url)\n }\n response = requests.get(url, headers=headers)\n response.encoding='utf-8'\n response_text = response.text\n # print(response_text)\n contact_people_pattern = re.findall('联系人(.*?) ', response_text, re.S)\n qq_num_pattern = re.findall('邮件(.*?)', response_text, re.S)\n call_pattern = re.findall('电话(.*?)', response_text, re.S)\n phone_pattern = re.findall('手机(.*?)', response_text, re.S)\n area_pattern = re.findall('地区(.*?)', response_text, re.S)\n address_pattern = re.findall('地址(.*?)', response_text, re.S)\n\n data = {\n 'name' : contact_people_pattern[0] if contact_people_pattern else None,\n 'qq_num' : qq_num_pattern[1] if qq_num_pattern else None,\n 'email' : email_pattern[0] if email_pattern else None,\n 'call' : call_pattern[0] if call_pattern else None,\n 'phone' : phone_pattern[0] if phone_pattern else None,\n 'area' : area_pattern[0] if area_pattern else None,\n 'address' : address_pattern[0] if address_pattern else None\n }\n # print(data)\n return data\n\n\nclass PageUselessException(Exception): pass\n\nif __name__ == '__main__':\n initial_url = 'http://www.cnzhantuan.com/zhanhui/'\n # initial_url = 'http://www.cnzhantuan.com/zhanhui/index-htm-page-807.html'\n # get_urls(initial_url)\n get_item_info('http://www.cnzhantuan.com/zhanhui/201509/10/28304.html')\n # get_item_info('http://www.cnzhantuan.com/zhanhui/201601/05/30533.html')\n # getsm('http://www.cnzhantuan.com/api/task.js.php?moduleid=5&html=show&itemid=28304')","sub_path":"zhantuanwang.py","file_name":"zhantuanwang.py","file_ext":"py","file_size_in_byte":4789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"511440333","text":"import cv2\nimport numpy as np\n\nimage = cv2.imread('../db_images/png/captcha.png')\ncv2.imshow('RGB', image)\ncv2.waitKey(0)\n\nblur = cv2.blur(image,(3,3))\ncv2.imshow('blur', blur)\ncv2.waitKey(0)\n\ngaussian = cv2.GaussianBlur(image,(3,3), 0)\ncv2.imshow('Gaussian', gaussian)\ncv2.waitKey(0)\n\nmedian = cv2.medianBlur(image, 5)\ncv2.imshow('Median blur', median)\ncv2.waitKey(0)\n\nbilateral = cv2.bilateralFilter(image,9,75,75)\ncv2.imshow('blilateral', bilateral)\ncv2.waitKey(0)\n\nkernel = np.ones([3,3])\nfilter2d = cv2.filter2D(image, -1, kernel)\ncv2.imshow('filter2d', filter2d)\ncv2.waitKey(0)\n\nkernel = np.array([[-1,-1,-1],[-1, 9,-1],[-1,-1,-1]])\nfilter2d = cv2.filter2D(image, -1, kernel)\ncv2.imshow('filter2d', filter2d)\ncv2.waitKey(0)\n","sub_path":"aulas/vision/aula_03/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"229612472","text":"# --- STD Imports ---\nimport time\nimport contextlib\nimport argparse\nimport pathlib\n\n\n@contextlib.contextmanager\ndef TimedContext() -> float:\n begin = time.perf_counter()\n yield lambda: time.perf_counter() - begin\n\n\ndef parseArguments(argv: list) -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser(\"wrn\")\n parser.add_argument(\"-i\",\n \"--input-path\",\n dest = \"inputPath\",\n type = pathlib.Path,\n default = pathlib.Path(__file__).absolute().parent / \"parameters.json\")\n parser.add_argument(\"-q\",\n \"--quiet\",\n dest = \"quiet\",\n action = \"store_const\",\n default = False,\n const = True,\n help = \"Suppress status reports\")\n parser.add_argument(\"-p\",\n \"--plot\",\n dest = \"plot\",\n action = \"store_const\",\n default = False,\n const = True,\n help = \"plot selected DoFs\")\n parser.add_argument(\"-w\",\n \"--write\",\n dest = \"write\",\n action = \"store_const\",\n default = False,\n const = True,\n help = \"write frames\")\n return parser.parse_args(argv[1:])\n","sub_path":"libraries/fem/python/modules/wrn/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"481984753","text":"#!/usr/bin/env python3\n\"\"\"\nauthor: Michał Kostrzewa, 2016\n\nThis script parses digits of pi shared by Mike Schaudies \n(https://www.schneier.com/code/constants.txt) published on Bruce \nShneier's website (https://www.schneier.com/cryptography/blowfish/) \nand outputs them to a different file, easily integrated in python \nscripts.\n\"\"\"\n\ngroups = []\n\nwith open(\"constants.txt\") as file:\n\t\n\tcurrent = 0\n\tcurrent_group = []\n\n\tfor line in file:\n\t\tif \"0x\" in line:\n\t\t\tline = line.rstrip().split()\n\t\t\tfor word in line:\n\t\t\t\tend = False\n\n\t\t\t\t# remove 0x\n\t\t\t\t#word = word[2:]\n\n\t\t\t\tif(\"};\") in word: \n\t\t\t\t\tend = True\n\t\t\t\t\tword = word.rstrip(\"};\")\n\t\t\t\tif \",\" in word:\n\t\t\t\t\tword = word.rstrip(\",\")\n\t\t\t\tif \"L\" in word: \n\t\t\t\t\tword = word.rstrip(\"L\")\n\t\t\t\tcurrent_group.append(word)\n\n\t\t\t\tif end:\n\t\t\t\t\tcurrent += 1\n\t\t\t\t\tgroups.append(current_group)\n\t\t\t\t\tcurrent_group = []\n\nwith open(\"my_blowfish_init.py\", \"w\") as file:\n\n\toutput_info = \\\n\t\t\"\\\"\\\"\\\"\\n\" \\\n\t\t\"author: Michał Kostrzewa, 2016\\n\" \\\n\t\t\"\\n\" \\\n\t\t\"This file was generated automatically. \\n\" \\\n\t\t\"\\n\" \\\n\t\t\"This module contains digits of pi in hexadecimal, arranged in four boxes and\\n\" \\\n\t\t\"and an array. This corresponds to default Blowfish setup. \\n\" \\\n\t\t\"\\n\" \\\n\t\t\"Original file was written by Mike Schaudies (https://www.schneier.com/code/constants.txt), \\n\"\\\n\t\t\"published on Bruce Shneier's website (https://www.schneier.com/cryptography/blowfish/). \\n\" \\\n\t\t\"Apparently, they have been thoroughly tested and stuff.\\n\" \\\n\t\t\"\\\"\\\"\\\"\\n\\n\" \n\n\tfile.write(output_info)\n\n\tfile.write(\"boxes = [\\n\")\n\tfor i in range(4):\n\t\tfile.write(\"[\\n\")\n\t\tfor j, word in enumerate(groups[i]):\n\t\t\tif j != len(groups[i])-1: file.write(\"%s, \\t\" % word)\n\t\t\telse: file.write(\"%s\" % word)\n\t\t\tif j % 6 == 5: file.write(\"\\n\")\n\t\tif i < 3: file.write(\"\\n],\\n\\n\")\n\t\telse: file.write(\"\\n]\\n]\\n\\n\")\n\n\tfile.write(\"array = [\\n\")\n\tfor j, word in enumerate(groups[4]):\n\t\tif j != len(groups[4])-1: file.write(\"%s, \\t\" % word)\n\t\telse: file.write(\"%s\" % word)\n\t\tif j % 6 == 5: file.write(\"\\n\")\n\tfile.write(\"]\")","sub_path":"hex_pi_parse.py","file_name":"hex_pi_parse.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"446188417","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC COPYRIGHT: Columbia Sportswear 2020
\n# MAGIC DESCRIPTION: This notebook sends forecast data into TM1\n# MAGIC \n# MAGIC -----------------------------------------------------------------\n# MAGIC ###### MODIFICATION LOG\n# MAGIC | Programmmer | Change Request | Date | Change Description |\n# MAGIC |----------------------|-----------------|------------|--------------------------------------------------------------------|\n# MAGIC | Sasi Nagireddy | Omni Planning | 08/27/2020 | This notebook sends forecast data into TM1 | \n# MAGIC | Sasi Nagireddy | Omni Planning | 08/31/2020 | Added Optimize/Vacuum | \n# MAGIC | Sasi Nagireddy | Omni Planning | 09/01/2020 | removed rounding off from quantities | \n# MAGIC | Sasi Nagireddy | Omni Planning | 01/20/2021 | updated logic to handle scenario 2 and 3 | \n# MAGIC | Sasi Nagireddy | Omni Planning | 02/05/2021 | removed seasoncode from the table | \n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE OR REPLACE TEMP VIEW cal_mstr\n# MAGIC AS\n# MAGIC select a.* , case when LENGTH(Yr_Wk_Nbr) < 6 THEN CAST(concat(left(Yr_Wk_Nbr,4),0,right(Yr_Wk_Nbr,1)) as int) ELSE Yr_Wk_Nbr END AS Yr_Wk_Nbr_drvd from entpr_foundation.cal_mstr a\n# MAGIC WHERE CAL_TYP_ID = 13\n\n# COMMAND ----------\n\nfrom datetime import datetime, timedelta\nimport datetime\nimport pandas as pd\nfrom pyspark.sql.types import *\ndef convertjdainternaldate(eff):\n return pd.to_datetime(datetime.datetime.strptime(\"1970-01-01\", \"%Y-%m-%d\") + datetime.timedelta(days=eff/1440)).strftime('%Y-%m-%d')\nconvertjdainternaldate=udf(convertjdainternaldate,StringType())\nspark.udf.register(\"convertjdainternaldate\",convertjdainternaldate)\n\n# COMMAND ----------\n\nimport pandas as pd\nfrom pyspark.sql.functions import (col, when, current_timestamp, current_date, date_format, split, coalesce, month, year, to_date, substring, row_number, max, min, concat, count, lit, sum, length,asc,rank,datediff)\nfrom pyspark.sql.window import Window\nomni_caldata = (spark.table('edw_lnd_by_view.omni_caldata').alias('s')\n .filter((col('s.CAL').like(\"%ALLOC%\")==True)) #Only Alloc like CAL\n .filter((col('s.CAL').like(\"%_WS_%\")==False)) #Exclude Wholesales\n .select(\n col('s.Cal')\n ,to_date(convertjdainternaldate(col('s.EFF'))).alias('EFF')\n ,col('s.DESCR')\n ,col('s.OPT')\n ,col('s.ALTCAL')\n ,col('s.REPEAT')\n ,col('s.ALLOCWGT')\n ,col('s.PERWGT')\n ,col('s.AVAIL')\n ,col('s.COVDUR')\n ,col('s.EDW_UPDT_TS') \n \n )\n \n .withColumn(\"MinEFF\" , min(\"EFF\").over(Window.partitionBy(\"CAL\").orderBy(col(\"CAL\").desc())))\n .withColumn(\"MaxEFF\" , max(\"EFF\").over(Window.partitionBy(\"CAL\").orderBy(col(\"CAL\").desc())))\n .withColumn(\"Datediff\" ,datediff(max(\"EFF\").over(Window.partitionBy(\"CAL\").orderBy(col(\"CAL\").desc())),min(\"EFF\").over(Window.partitionBy(\"CAL\").orderBy(col(\"CAL\").desc()))))\n .withColumn(\"rnk\" , rank().over(Window.partitionBy(\"CAL\",\"OPT\",\"REPEAT\").orderBy(col(\"EDW_UPDT_TS\").desc())))\n \n .filter(col(\"rnk\")==1)\n .drop(\"rnk\")\n \n ).orderBy(asc(\"Eff\"))\nomni_caldata = omni_caldata.withColumn(\"rownum\" , row_number().over(Window.partitionBy(\"CAL\",when((col(\"OPT\") == 5) & (col(\"REPEAT\") == 10080),lit(\"6\").cast(IntegerType())).otherwise(col(\"OPT\").cast(IntegerType()))).orderBy(col(\"EFF\").asc())))\n\ndisplay(omni_caldata)\nomni_caldata.createOrReplaceTempView('omni_caldata')\n\n#omni_caldataomni_caldata.orderBy(asc(\"Eff\"))\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC create or replace temp view omni_caldata1 as\n# MAGIC select *, datediff(lead(eff) OVER (PARTITION BY Cal order BY EFF), eff) as eff_lead from omni_caldata\n\n# COMMAND ----------\n\nfrom typing import List\nimport datetime\nfrom pyspark.sql import DataFrame, Window\nfrom pyspark.sql.functions import col, lit, udf, datediff, lead, explode\nfrom pyspark.sql.types import DateType, ArrayType\n\n\n# COMMAND ----------\n\ndef _get_next_dates(start_date: datetime.date, diff: int) -> List[datetime.date]:\n return [start_date + datetime.timedelta(days=days) for days in range(1, diff)]\n\n# COMMAND ----------\n\ndef _get_fill_dates_df(df: DataFrame, date_column: str, group_columns: List[str], fill_column: str) -> DataFrame:\n get_next_dates_udf = udf(_get_next_dates, ArrayType(DateType()))\n\n window = Window.orderBy(*group_columns, date_column)\n\n return df.withColumn(\"_diff\", datediff(lead(date_column, 1).over(window), date_column)) \\\n .filter(col(\"_diff\") > 1).withColumn(\"_next_dates\", get_next_dates_udf(date_column, \"_diff\")) \\\n .withColumn(fill_column, row_number().over(Window.partitionBy(\"CAL\",when((col(\"OPT\") == 5) & (col(\"REPEAT\") == 10080),lit(\"6\").cast(IntegerType())).otherwise(col(\"OPT\").cast(IntegerType()))).orderBy(col(\"EFF\").asc()))) \\\n .withColumn(date_column, explode(\"_next_dates\")) \\\n .drop(\"_diff\", \"_next_dates\")\n\n# COMMAND ----------\n\nomni_caldata1 = spark.sql(\"select * from omni_caldata1\")\n\n# COMMAND ----------\n\nfill_df = _get_fill_dates_df(omni_caldata1, \"EFF\", [\"Cal\"], \"rownum\")\nomni_caldata_udf = omni_caldata1.union(fill_df)\nomni_caldata_udf.createOrReplaceTempView('omni_caldata_udf')\ndisplay(omni_caldata_udf)\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC create or replace temp view omni_caldata_udf2 as \n# MAGIC select a.*, case when repeat=0 then allocwgt/eff_lead else allocwgt end as new_allocwgt, Yr_Wk_Nbr_drvd from omni_caldata_udf a\n# MAGIC join cal_mstr\n# MAGIC on cast(date_format(eff,'yyyyMMdd') as int) = DT_DIM_ID\n# MAGIC --WHERE CAL IN ('CSC_SCENARIO3_ALLOC')\n# MAGIC ORDER BY 1,2\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC create or replace temp view omni_caldata_udf3 as \n# MAGIC select a.cal, a.eff, a.descr, a.opt, a.ALTCAL\n# MAGIC , a.repeat, case when ((repeat =0 AND descr = 'PA END') OR repeat !=0) then b.new_allocwgt else a.new_allocwgt end as allocwgt,PERWGT\t,\n# MAGIC AVAIL\t,\n# MAGIC COVDUR\t,\n# MAGIC EDW_UPDT_TS\t,\n# MAGIC MinEFF\t,\n# MAGIC MaxEFF\t,\n# MAGIC Datediff\t,\n# MAGIC rownum\t,\n# MAGIC a.Yr_Wk_Nbr_drvd, b.Yr_Wk_Nbr_drvd as yr_wk_nbr2\n# MAGIC from omni_caldata_udf2 a\n# MAGIC left join (select distinct cal,dayofweek(eff) as dayofweek ,new_allocwgt, Yr_Wk_Nbr_drvd from omni_caldata_udf2 where repeat=0 and descr <> 'PA END') as b\n# MAGIC on a.cal = b.cal\n# MAGIC and dayofweek(a.eff) = b.dayofweek\n# MAGIC and a.Yr_Wk_Nbr_drvd > b.Yr_Wk_Nbr_drvd\n# MAGIC order by a.eff\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC create or replace temp view omni_caldata_udf4 as\n# MAGIC select * from (\n# MAGIC select *, row_number() over (partition by cal,eff order by yr_wk_nbr2 desc) as rank\n# MAGIC from omni_caldata_udf3\n# MAGIC ) where rank =1\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import (col, when, current_timestamp, current_date, date_format, split, coalesce, month, year, to_date, substring, row_number, max, min, concat, count, lit, sum, length,asc,rank)\nfrom pyspark.sql.window import Window\nomni_caldata = (spark.table('omni_caldata_udf4').alias('a')\n .join(spark.table('entpr_foundation.cal_mstr').alias('cal') , [(col('a.EFF') == col('CAL_DT').cast(DateType()))], how = 'inner'\n )\n .filter( (col('cal.CAL_TYP_ID') == 13))\n .select (\n col('a.Cal')\n ,col('a.EFF')\n ,col('a.DESCR')\n ,col('a.OPT')\n ,col('a.ALTCAL')\n ,col('a.ALLOCWGT')\n ,col('a.REPEAT')\n ,col('a.PERWGT')\n ,col('a.AVAIL')\n ,col('a.MinEFF')\n ,col('a.MaxEFF')\n ,col('a.Datediff')\n ,col('a.rownum')\n ,col('Cal.WK_BEG_DT').cast(DateType())\n ,col('Cal.DOW_NM')\n ,col('Cal.SEAS_YR_CD')\n \n \n )\n #.withColumn(\"ALLOCWGT_drvd\", max(\"ALLOCWGT\").over(Window.partitionBy(\"CAL\",\"DOW_NM\").orderBy(col(\"CAL\").desc())))\n #.withColumn(\"PERWGT_drvd\", max(\"PERWGT\").over(Window.partitionBy(\"CAL\",\"DOW_NM\").orderBy(col(\"CAL\").desc()))) \n \n \n \n )\n\ndisplay(omni_caldata)\nomni_caldata.createOrReplaceTempView('omni_caldata_daynm1')\n \n \n \n \n\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC create or replace temp view cal_data_allocwgt_daily\n# MAGIC AS\n# MAGIC select \n# MAGIC distinct\n# MAGIC a.CAL, \n# MAGIC -- CASE WHEN substring(CAL,locate('_',CAL)+1,3) like '%US%' THEN 'USA'\n# MAGIC -- WHEN substring(CAL,locate('_',CAL)+1,3) like '%EU%' THEN 'EUR' ELSE substring(CAL,locate('_',CAL)+1,3) END AS SubRegion ,\n# MAGIC -- replace(substring(cal,locate('_',cal,locate('_',cal,locate('_',CAL)+1))+1),'_ALLOC','') AS SubChannel ,\n# MAGIC b.SubRegion, --UMT is incomplete\n# MAGIC b.Channel,\n# MAGIC b.Subchannel, --UMT is incomplete\n# MAGIC b.Brand,\n# MAGIC b.ProductLine,\n# MAGIC a.eff, \n# MAGIC a.WK_BEG_DT,\n# MAGIC SUM(a.ALLOCWGT) OVER (PARTITION BY CAL,SubRegion,Channel,Subchannel,Brand,ProductLine,WK_BEG_DT) AS ALLOCWGT ,\n# MAGIC (100/SUM(a.ALLOCWGT) OVER (PARTITION BY CAL,SubRegion,Channel,Subchannel,Brand,ProductLine,WK_BEG_DT))*ALLOCWGT AS ADJ_ALLOC ,\n# MAGIC REPEAT \n# MAGIC \n# MAGIC from omni_caldata_daynm1 a\n# MAGIC LEFT OUTER JOIN edw_lnd_umt.umt_caldata_rgn_subchannel b \n# MAGIC ON a.Cal = b.StandardCAL\n# MAGIC AND Subchannel <> 'Wholesale'\n# MAGIC \n# MAGIC \n# MAGIC ORDER BY a.CAL, a.eff asc\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE OR REPLACE TEMP VIEW omni_fcst_dtc_weekly\n# MAGIC AS\n# MAGIC select \n# MAGIC a.MTRL_NBR\n# MAGIC , substring(a.MTRL_NBR,1,7) as MTRL_STYL_NBR \n# MAGIC , substring(a.MTRL_NBR,8,3) as COLRWAY_NBR\n# MAGIC , b.BrandCode as BRND_CD -- added Brand Code to match Cal UMT\n# MAGIC , b.ProductLineCode as PROD_LN_CD -- added ProductLineCode to match Cal UMT\n# MAGIC , a.RGN_CD AS SubRegion\n# MAGIC --, a.LOC\n# MAGIC --, case when length(a.DMDUNIT) = 10 then c.LocationCode else d.Lvl_30_Loc_Code end as LOC\n# MAGIC , a.CHNL_DESC as Channel\n# MAGIC , a.SBCHNL_DESC as SubChannel\n# MAGIC , a.PLND_ACCT_CUST_NBR as ACCOUNT_CD\n# MAGIC , a.RPLMT_FLG as ReplenishmentFlag\n# MAGIC , 'Non-Key Account' AS ParentCustomer \n# MAGIC , 'Non-Key Account' AS ParentCustomerDescr\n# MAGIC , TO_DATE(a.FCST_STRT_DT) AS STARTDATE \n# MAGIC --,SUM(QTY) OVER (PARTITION BY MTRL_NBR, PLND_ACCT_CUST_NBR, RGN_CD ) AS Quantity\n# MAGIC ,SUM(QTY) OVER (PARTITION BY MTRL_NBR, BrandCode, ProductLineCode, RGN_CD, SBCHNL_DESC, FCST_STRT_DT ) AS Quantity\n# MAGIC , a.EDW_UPDT_TS\n# MAGIC from entpr_planning.by_fcst_cnsns_lvl1_snpst a \n# MAGIC inner join (select max(SNPST_DT) as SNPST_DT from entpr_planning.by_fcst_cnsns_lvl1_snpst) b on a.SNPST_DT = b.SNPST_DT\n# MAGIC \n# MAGIC Left outer join (Select distinct MaterialNumber, JdaSubRegion, BrandCode, ProductLineCode from entpr_plng_app.planning_product) b on a.MTRL_NBR = b.MaterialNumber and a.RGN_CD = b.JdaSubRegion\n# MAGIC \n# MAGIC where CHNL_DESC = 'DTC'--Weekly DTC only\n# MAGIC \n# MAGIC Union \n# MAGIC \n# MAGIC select \n# MAGIC a.MTRL_STYL_NBR as MTRL_NBR\n# MAGIC , a.MTRL_STYL_NBR as MTRL_STYL_NBR \n# MAGIC , ' ' as COLRWAY_NBR\n# MAGIC , b.BrandCode as BRND_CD -- added Brand Code to match Cal UMT\n# MAGIC , b.ProductLineCode as PROD_LN_CD -- added ProductLineCode to match Cal UMT\n# MAGIC , a.RGN_CD AS SubRegion\n# MAGIC --, a.LOC\n# MAGIC --, case when length(a.DMDUNIT) = 10 then c.LocationCode else d.Lvl_30_Loc_Code end as LOC\n# MAGIC , a.CHNL_DESC as Channel\n# MAGIC , a.SBCHNL_DESC as SubChannel\n# MAGIC , a.PLND_ACCT_CUST_NBR as ACCOUNT_CD\n# MAGIC , a.RPLMT_FLG as ReplenishmentFlag\n# MAGIC , 'Non-Key Account' AS ParentCustomer \n# MAGIC , 'Non-Key Account' AS ParentCustomerDescr\n# MAGIC , TO_DATE(a.FCST_STRT_DT) AS STARTDATE \n# MAGIC --,SUM(QTY) OVER (PARTITION BY MTRL_STYL_NBR, PLND_ACCT_CUST_NBR, RGN_CD ) AS Quantity\n# MAGIC ,SUM(QTY) OVER (PARTITION BY MTRL_STYL_NBR, BrandCode, ProductLineCode, RGN_CD, SBCHNL_DESC, FCST_STRT_DT ) AS Quantity\n# MAGIC , a.EDW_UPDT_TS\n# MAGIC from entpr_planning.by_fcst_cnsns_lvl2_snpst a\n# MAGIC inner join (select max(SNPST_DT) as SNPST_DT from entpr_planning.by_fcst_cnsns_lvl2_snpst) b on a.SNPST_DT = b.SNPST_DT\n# MAGIC \n# MAGIC Left outer join (Select distinct MaterialStyle, JdaSubRegion, BrandCode, ProductLineCode from entpr_plng_app.planning_product) b on a.MTRL_STYL_NBR = b.MaterialStyle and a.RGN_CD = b.JdaSubRegion\n# MAGIC \n# MAGIC where CHNL_DESC = 'DTC'--Weekly DTC only\n# MAGIC \n# MAGIC ORDER BY STARTDATE ASC\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE OR REPLACE TEMP VIEW bydtcforecastdisaggregation\n# MAGIC AS\n# MAGIC --Wholesale only\n# MAGIC select \n# MAGIC MATERIALSTYLENUMBER, \n# MAGIC COLORWAYNUMBER, \n# MAGIC SUBREGION, \n# MAGIC YEAR, \n# MAGIC MONTH,\n# MAGIC -- SEASONYEARCODE, \n# MAGIC CHANNEL, \n# MAGIC SUBCHANNEL, \n# MAGIC ACCOUNTCODE,\n# MAGIC MEASURELEVEL, \n# MAGIC NETPRICELEVEL, \n# MAGIC CAST((QUANTITY) AS decimal(15,5)) AS QUANTITY,\n# MAGIC CURRENT_TIMESTAMP AS EDW_CRT_TS,\n# MAGIC CURRENT_TIMESTAMP AS EDW_UPDT_TS,\n# MAGIC 'Y' AS EDW_ACTV_FLG\n# MAGIC \n# MAGIC FROM\n# MAGIC (\n# MAGIC select \n# MAGIC substring(a.MTRL_NBR,1,7) as MATERIALSTYLENUMBER, \n# MAGIC substring(a.MTRL_NBR,8,3) as COLORWAYNUMBER, \n# MAGIC a.RGN_CD as SUBREGION, \n# MAGIC YEAR(a.FCST_STRT_DT) as YEAR, \n# MAGIC MONTH(a.FCST_STRT_DT) as MONTH,\n# MAGIC --CONCAT(CASE WHEN MONTH(FCST_STRT_DT) IN (1,2,3,4,5,6) THEN 'S' ELSE 'F' END ,Right(YEAR(FCST_STRT_DT),2)) AS SEASONYEARCODE, \n# MAGIC a.CHNL_DESC as CHANNEL, \n# MAGIC 'Wholesale' as SUBCHANNEL, \n# MAGIC a.PLND_ACCT_CUST_NBR as ACCOUNTCODE,\n# MAGIC --a.RPLMT_FLG as ReplenishmentFlag,\n# MAGIC '1' as MEASURELEVEL, \n# MAGIC COALESCE(e.Net_Price_Lcl,'~') AS NETPRICELEVEL, \n# MAGIC sum(QTY) AS QUANTITY\n# MAGIC --a.EDW_UPDT_TS \n# MAGIC \n# MAGIC from entpr_planning.by_fcst_cnsns_lvl1_snpst a\n# MAGIC inner join (select max(SNPST_DT) as SNPST_DT from entpr_planning.by_fcst_cnsns_lvl1_snpst) b on a.SNPST_DT = b.SNPST_DT\n# MAGIC \n# MAGIC Left Outer Join (select distinct xx.SeasonCode, substring(yy.PD_BEG_DT,1,4) as YEAR, substring(yy.PD_BEG_DT,6,2) as MONTH, case when xx.JdaSubRegion = 'IDR' then 'INTL' else xx.JdaSubRegion end as JdaSubRegion , xx.MaterialStyle, xx.WholesaleDemandValueLocal as Net_Price_Lcl from entpr_plng_app.planning_product xx \n# MAGIC inner join entpr_foundation.cal_mstr yy on xx.SeasonCode = yy.SEAS_YR_CD and yy.cal_typ_id = '1' where xx.WholesaleDemandValueLocal > 0 ) e \n# MAGIC on substring(a.MTRL_NBR,1,7) = e.MaterialStyle \n# MAGIC and a.RGN_CD = e.JdaSubRegion \n# MAGIC and e.Year = substring(a.FCST_STRT_DT,1,4)\n# MAGIC and e.Month = substring(a.FCST_STRT_DT,6,2) \n# MAGIC \n# MAGIC where a.CHNL_DESC = 'Wholesale' \n# MAGIC \n# MAGIC GROUP BY\n# MAGIC substring(a.MTRL_NBR,1,7), \n# MAGIC substring(a.MTRL_NBR,8,3), \n# MAGIC a.RGN_CD, \n# MAGIC YEAR(a.FCST_STRT_DT) , \n# MAGIC MONTH(a.FCST_STRT_DT) ,\n# MAGIC --CONCAT(CASE WHEN MONTH(FCST_STRT_DT) IN (1,2,3,4,5,6) THEN 'S' ELSE 'F' END ,Right(YEAR(FCST_STRT_DT),2)) , \n# MAGIC a.CHNL_DESC, \n# MAGIC 'Wholesale', \n# MAGIC a.PLND_ACCT_CUST_NBR,\n# MAGIC --a.RPLMT_FLG,\n# MAGIC '1', \n# MAGIC e.Net_Price_Lcl \n# MAGIC --a.EDW_UPDT_TS \n# MAGIC \n# MAGIC UNION ALL\n# MAGIC -- Level 2 Wholesale only\n# MAGIC \n# MAGIC select \n# MAGIC a.MTRL_STYL_NBR as MATERIALSTYLENUMBER, \n# MAGIC '~' as COLORWAYNUMBER, \n# MAGIC a.RGN_CD as SUBREGION, \n# MAGIC YEAR(a.FCST_STRT_DT) as YEAR, \n# MAGIC MONTH(a.FCST_STRT_DT) as MONTH,\n# MAGIC --CONCAT(CASE WHEN MONTH(FCST_STRT_DT) IN (1,2,3,4,5,6) THEN 'S' ELSE 'F' END ,Right(YEAR(FCST_STRT_DT),2)) AS SEASONYEARCODE, \n# MAGIC a.CHNL_DESC as CHANNEL, \n# MAGIC 'Wholesale' as SUBCHANNEL, \n# MAGIC a.PLND_ACCT_CUST_NBR as ACCOUNTCODE,\n# MAGIC --a.RPLMT_FLG as ReplenishmentFlag,\n# MAGIC '2' as MEASURELEVEL, \n# MAGIC COALESCE(e.Net_Price_Lcl,'~') AS NETPRICELEVEL, \n# MAGIC sum(QTY) AS QUANTITY\n# MAGIC --a.EDW_UPDT_TS \n# MAGIC \n# MAGIC from entpr_planning.by_fcst_cnsns_lvl2_snpst a\n# MAGIC inner join (select max(SNPST_DT) as SNPST_DT from entpr_planning.by_fcst_cnsns_lvl2_snpst) b on a.SNPST_DT = b.SNPST_DT\n# MAGIC \n# MAGIC Left Outer Join (select distinct xx.SeasonCode, substring(yy.PD_BEG_DT,1,4) as YEAR, substring(yy.PD_BEG_DT,6,2) as MONTH, case when xx.JdaSubRegion = 'IDR' then 'INTL' else xx.JdaSubRegion end as JdaSubRegion , xx.MaterialStyle, xx.WholesaleDemandValueLocal as Net_Price_Lcl from entpr_plng_app.planning_product xx \n# MAGIC \n# MAGIC inner join entpr_foundation.cal_mstr yy on xx.SeasonCode = yy.SEAS_YR_CD and yy.cal_typ_id = '1' where xx.WholesaleDemandValueLocal > 0 ) e \n# MAGIC on substring(a.MTRL_STYL_NBR,1,7) = e.MaterialStyle \n# MAGIC and a.RGN_CD = e.JdaSubRegion \n# MAGIC and e.Year = substring(a.FCST_STRT_DT,1,4)\n# MAGIC and e.Month = substring(a.FCST_STRT_DT,6,2) \n# MAGIC \n# MAGIC where a.CHNL_DESC = 'Wholesale' \n# MAGIC \n# MAGIC GROUP BY\n# MAGIC a.MTRL_STYL_NBR, \n# MAGIC ' ', \n# MAGIC a.RGN_CD, \n# MAGIC YEAR(a.FCST_STRT_DT), \n# MAGIC MONTH(a.FCST_STRT_DT),\n# MAGIC --CONCAT(CASE WHEN MONTH(FCST_STRT_DT) IN (1,2,3,4,5,6) THEN 'S' ELSE 'F' END ,Right(YEAR(FCST_STRT_DT),2)) , \n# MAGIC a.CHNL_DESC, \n# MAGIC 'Wholesale', \n# MAGIC a.PLND_ACCT_CUST_NBR,\n# MAGIC --a.RPLMT_FLG,\n# MAGIC '2', \n# MAGIC e.Net_Price_Lcl \n# MAGIC --a.EDW_UPDT_TS \n# MAGIC \n# MAGIC UNION\n# MAGIC ---DTC \n# MAGIC select \n# MAGIC MTRL_STYL_NBR as MATERIALSTYLENUMBER, \n# MAGIC COLORWAYNUMBER, \n# MAGIC SubRegion AS SUBREGION, \n# MAGIC YEAR(eff) as YEAR, \n# MAGIC MONTH(eff) as MONTH,\n# MAGIC --SEAS_YR_CD AS SEASONYEARCODE,\n# MAGIC Channel AS CHANNEL, \n# MAGIC SubChannel as SUBCHANNEL, \n# MAGIC ACCOUNT_CD AS ACCOUNTCODE, \n# MAGIC Measure_Level as MEASURELEVEL,\n# MAGIC Net_Price_Lcl AS NETPRICELEVEL,\n# MAGIC --ParentCustomerDescr,\n# MAGIC --ROUND(CAST(SUM(QTY) AS DECIMAL(15,5))) AS QUANTITY\n# MAGIC SUM(QTY) AS QUANTITY\n# MAGIC FROM\n# MAGIC (\n# MAGIC select \n# MAGIC distinct\n# MAGIC a.MTRL_STYL_NBR, \n# MAGIC CASE WHEN a.COLRWAY_NBR = '' THEN '~' ELSE a.COLRWAY_NBR END AS COLORWAYNUMBER ,\n# MAGIC a.SubRegion, \n# MAGIC a.STARTDATE AS STARTDATE,\n# MAGIC b.eff,\n# MAGIC --CONCAT(CASE WHEN MONTH(eff) IN (1,2,3,4,5,6) THEN 'S' ELSE 'F' END ,Right(YEAR(eff),2)) AS SEAS_YR_CD,\n# MAGIC 'DTC' as Channel, \n# MAGIC a.SubChannel AS SubChannel, \n# MAGIC '~' as ACCOUNT_CD, \n# MAGIC CASE WHEN length(COLRWAY_NBR) < '3' THEN 2 ELSE 1 END AS Measure_Level,\n# MAGIC '~' AS Net_Price_Lcl,\n# MAGIC a.ParentCustomerDescr,\n# MAGIC ((a.Quantity *b.ADJ_ALLOC)/100) as QTY \n# MAGIC from omni_fcst_dtc_weekly a\n# MAGIC left outer join cal_data_allocwgt_daily b\n# MAGIC ON (CASE WHEN a.SubRegion = 'IDR' THEN 'EUR' ELSE a.SubRegion END)= b.SubRegion\n# MAGIC AND a.Channel = b.Channel\n# MAGIC AND a.SubChannel = b.SubChannel\n# MAGIC AND a.BRND_CD = b.Brand\n# MAGIC AND a.PROD_LN_CD = b.ProductLine\n# MAGIC AND a.STARTDATE = b.WK_BEG_DT\n# MAGIC AND b.Channel = 'DTC'\n# MAGIC )\n# MAGIC GROUP BY \n# MAGIC MTRL_STYL_NBR, \n# MAGIC COLORWAYNUMBER, \n# MAGIC SubRegion, \n# MAGIC YEAR(eff) , \n# MAGIC MONTH(eff),\n# MAGIC --SEAS_YR_CD,\n# MAGIC Channel, \n# MAGIC SubChannel, \n# MAGIC ACCOUNT_CD, \n# MAGIC Measure_Level,\n# MAGIC Net_Price_Lcl\n# MAGIC )\n\n# COMMAND ----------\n\nbydtcforecastdisaggregation = spark.table('bydtcforecastdisaggregation')\n\n# COMMAND ----------\n\nbydtcforecastdisaggregation.write.saveAsTable('entpr_plng_app.bydtcforecastdisaggregation', format='delta', mode='overwrite')\n\n# COMMAND ----------\n\nspark.sql(\"OPTIMIZE entpr_plng_app.bydtcforecastdisaggregation\")\n\n# COMMAND ----------\n\nspark.sql(\"VACUUM entpr_plng_app.bydtcforecastdisaggregation RETAIN 0 HOURS\")\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC CREATE OR REPLACE VIEW EDW_INTG_VIEW.bydtcforecastdisaggregation\n# MAGIC AS\n# MAGIC select MATERIALSTYLENUMBER\t,\n# MAGIC COLORWAYNUMBER\t,\n# MAGIC SUBREGION\t,\n# MAGIC YEAR\t,\n# MAGIC MONTH\t,\n# MAGIC --SEASONYEARCODE\t,\n# MAGIC CHANNEL\t,\n# MAGIC SUBCHANNEL\t,\n# MAGIC ACCOUNTCODE\t,\n# MAGIC MEASURELEVEL\t,\n# MAGIC NETPRICELEVEL\t,\n# MAGIC QUANTITY\t,\n# MAGIC EDW_CRT_TS\t,\n# MAGIC EDW_UPDT_TS\t,\n# MAGIC cast(NULL AS STRING) AS EDW_ROW_CHKSUM ,\n# MAGIC cast(NULL AS STRING) AS EDW_HASH_CHK \n# MAGIC from entpr_plng_app.bydtcforecastdisaggregation a\n","sub_path":"Prod/entpr_plng_app/bydtcforecastdisaggregation.py","file_name":"bydtcforecastdisaggregation.py","file_ext":"py","file_size_in_byte":20513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"217816949","text":"# Copyright 2015 Juliano Martinez, Taylan Develioglu\n# 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\nimport traceback\nfrom functools import wraps\n\nimport kombu\nfrom amqp.exceptions import NotFound\n\nfrom balancer.common.message import Message\n\n\nclass QueueConnectionError(Exception):\n pass\n\n\nclass QueueConfigurationError(Exception):\n pass\n\n\nclass Queue(object):\n def __init__(self, queue_name, config=None, logger=lambda m: None,\n dsn=None, ensure_connection=True):\n self.config = config\n self.logger = logger\n self.ensure_connection = ensure_connection\n self._conn = None\n\n if self.config:\n self.dsn = self.config.queue_dsn\n else:\n self.dsn = dsn\n if not self.dsn:\n raise QueueConfigurationError(\"'dsn' not specified\")\n\n self.exchange_name = queue_name\n\n self._configure_queue()\n\n def purge(self):\n try:\n bound_queue = self.queue(self.conn.channel())\n self.logger(\"Purging queue {}\".format(bound_queue))\n bound_queue.purge()\n except NotFound as e:\n self.logger(\"It seems the queue doesn't exist yet.\")\n\n @property\n def conn(self):\n\n # Return the connected connection if available.\n if self._conn and self._conn.connected:\n return self._conn\n\n # If the private connection is not connected, instead of ensuring it\n # is connected we're going to create a new connection object instead.\n # If this proves too expensive we can change it to use the existing\n # object.\n conn = kombu.Connection(self.dsn)\n\n try:\n if self.ensure_connection:\n def errback(exc, interval):\n self.logger(\"Connection could not be established: {}. \"\n \"Waiting for {}s.\".format(exc, interval))\n\n # ensure_connection will ramp up until max_retries, and will\n # throw an exception if it can't ensure a connection. Here we\n # trap the raised exception to give a chance to the caller to skip\n # waiting for the connection.\n conn.ensure_connection(interval_start=1, interval_step=1,\n interval_max=5, errback=errback,\n max_retries=3)\n else:\n conn.connect()\n except OSError as e:\n raise QueueConnectionError(e)\n\n # At this point we should have a valid and connected object,\n # so we replace the private connection with it.\n self.logger(\"Connection to {} established\".format(self.dsn))\n self._conn = conn\n return self._conn\n\n def _configure_queue(self):\n self.logger(\"DSN: {}\".format(self.dsn))\n\n self.logger(\"Queue: {}\".format(self.exchange_name))\n self.exchange = kombu.Exchange(self.exchange_name, 'direct',\n durable=True)\n\n self.logger(\"Routing Key: {}\".format(self.exchange_name))\n self.queue = kombu.Queue(self.exchange_name, exchange=self.exchange,\n routing_key=self.exchange_name)\n\n def wrap_consumer(self, consumer):\n \"\"\"Wraps the callback function checking for success or failure.\n \"\"\"\n\n @wraps(consumer)\n def wrapped_consumer(body, message):\n message_ = None\n try:\n message_ = Message(body, self.logger)\n\n success = consumer(message_)\n if success:\n consumer.logger(\"Processing was successful.\")\n else:\n consumer.logger(\"Processing failed.\")\n\n consumer.logger(\"Will ack() the message\")\n message.ack()\n except Exception as e:\n consumer.logger(\"{}: {}\".format(e.__class__.__name__, e))\n if message_:\n consumer.logger(\" Message: \" + str(message_))\n consumer.logger(\" Raw: \" + str(body))\n\n for line in traceback.format_exc().splitlines():\n consumer.logger(\"{}\".format(line))\n\n return wrapped_consumer\n\n def disconnect(self):\n # If the server closes the remote connection, the local object might\n # still think that it's connected, so we ask it to close the\n # connection and cleanup all its internal state.\n if self._conn and self._conn.connected:\n self._conn.close()\n\n def __del__(self):\n self.disconnect()\n\n def produce(self, body):\n \"\"\"Sends a message to the queue configured by this object\n \"\"\"\n\n producer = self.conn.Producer(serializer='json')\n producer.publish(body, exchange=self.exchange,\n routing_key=self.exchange_name, declare=[self.queue])\n\n def consume(self, consumer):\n \"\"\"Consumes one item from the queue, and executes the given callback.\n \"\"\"\n consumer = self.wrap_consumer(consumer)\n self.logger(\"Waiting for messages...\")\n\n while True:\n try:\n with self.conn.Consumer(self.queue, callbacks=[consumer]):\n while True:\n self.conn.drain_events()\n except QueueConnectionError as e:\n self.logger(\"Couldn't connect to queue: {}\".format(e))\n except Exception as e:\n self.logger(\"Connection to queue was lost: {}\".format(e))\n finally:\n self.disconnect()\n","sub_path":"balancer/common/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"159585999","text":"'''\nCreated on Aug 24, 2013\n\n@author: wiize_000\n'''\nimport mysql.connector\nimport os\nfrom os.path import expanduser\nimport string\nprint(\"hello\")\ncnx = mysql.connector.connect(user='root', password='sigma2', host='174.53.139.220')\n#cnx = mysql.connector.connect(user='root', password='sigma2',\n# host='174.53.139.220',\n# port='50004')\n\n\ncursor = cnx.cursor()\ncnx.database=\"RoseUsers\" \ndef uploadFile(file,table):\n location = expanduser(\"C:/Users/wiize_000/Desktop/Users/\")\n os.chdir(location) \n f = open(file,'r+')\n if(table == \"Profs\"):\n insertQ = \"Insert Into \" +table+\" values (%s,%s,%s)\"\n for line in f:\n print(line)\n lest = line.split(\",\")\n if(line == \"\\n\"):\n print(\"..\")\n continue;\n if(lest[1]!=\"faculty\"):\n continue\n values = (lest[0],lest[2],lest[3].rstrip())\n cursor.execute(insertQ,values)\n\n elif(table==\"Student\"):\n insertQ = \"Insert Into \" +table+\" values (%s,%s,%s,%s,%s)\"\n \n for line in f:\n print(line)\n lest = line.split(\",\")\n if(line == \"\\n\"):\n print(\"..\")\n continue\n if(lest[1]!=\"student\"):\n continue\n values = (lest[0],lest[2],lest[3],lest[4],lest[5])\n cursor.execute(insertQ,values)\n\n f.close()\n\nfor c in string.ascii_lowercase:\n uploadFile(c+'.txt','Student')\n# uploadFile(c+'.txt','Profs')\n\ncnx.commit()\n\ncnx.close()\n\n","sub_path":"src/RoseCourseAndUserDatabase/uploadUsers.py","file_name":"uploadUsers.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"134971378","text":"import pyautogui\r\nimport pydirectinput\r\nimport random\r\nimport time\r\nimport sys\r\nimport os\r\nimport argparse\r\nfrom util import *\r\n\r\nimport pygetwindow as gw\r\n\r\npyautogui.FAILSAFE = False\r\n\r\n\r\nwindow = gw.getWindowsAt(650,350)[0]\r\nprint(window.size)\r\nwindow.moveTo(0,0)\r\nwindow.resizeTo(1350, 790)\r\n#window.resizeTo(2560, 790)\r\n\r\nprint(window.size)\r\ntime.sleep(2)\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--wuxing',action='store_true', default=False,help='go wuxing.')\r\nparser.add_argument('--anying',action='store_true', default=False,help='go anying.')\r\nparser.add_argument('--songli',action='store_true', default=False,help='do songli.')\r\nparser.add_argument('--pengren',action='store_true', default=False,help='do pengren.')\r\nparser.add_argument('--dacan',action='store_true', default=False,help='do pengren.')\r\n\r\nargs = parser.parse_args()\r\n\r\npyautogui.FAILSAFE = False\r\n#near 1349 789\r\n#(jing zhi) or (gao qing) , gao zhen ping\r\nscreenSize = [1400,800]\r\npath = 'jiayuan'\r\n#Sw,Sh = pyautogui.size()\r\n\r\n\r\nclass jiayuan():\r\n def __init__(self):\r\n self.fangdacan = True\r\n self.zhongzhiing = False\r\n self.dacanflag = True\r\n self.replaceCount = 0\r\n self.replacePoss = [[354,387,253,285],\r\n [454,485,277,307],\r\n #[1053,1084,559,588],\r\n #[456,477,609,634],\r\n #[325,347,570,599],\r\n #[354,387,253,285],\r\n #[949,987,529,561],\r\n ] \r\n \r\n self.gifts = ['../'+path+'/muma.png',\r\n '../'+path+'/jiu1.png',\r\n '../'+path+'/jiu2.png',\r\n '../'+path+'/jiu3.png',\r\n '../'+path+'/jiu4.png',\r\n '../'+path+'/shi1.png',\r\n '../'+path+'/shi2.png',\r\n '../'+path+'/shi3.png',\r\n '../'+path+'/shi4.png',\r\n '../'+path+'/shi5.png',\r\n '../'+path+'/shi6.png',\r\n \r\n \r\n '../'+path+'/wan1.png',\r\n \r\n \r\n '../'+path+'/xiang1.png',\r\n '../'+path+'/xiang2.png',\r\n \r\n '../'+path+'/bao1.png',\r\n '../'+path+'/bao2.png',\r\n '../'+path+'/bao3.png',\r\n '../'+path+'/bao4.png',\r\n '../'+path+'/bao5.png',\r\n '../'+path+'/bao6.png',\r\n '../'+path+'/bao7.png',\r\n '../'+path+'/bao8.png',\r\n '../'+path+'/bao9.png',\r\n '../'+path+'/bao10.png',\r\n '../'+path+'/bao11.png',\r\n \r\n \r\n '../'+path+'/zhuang1.png',\r\n '../'+path+'/zhuang2.png',\r\n \r\n '../'+path+'/wuqi1.png',\r\n '../'+path+'/wuqi2.png',\r\n '../'+path+'/wuqi3.png',\r\n \r\n '../'+path+'/yifu.png',\r\n \r\n \r\n '../'+path+'/guihuo.png',\r\n \r\n '../'+path+'/shiwu1.png',\r\n '../'+path+'/shiwu2.png',\r\n '../'+path+'/shiwu3.png',\r\n '../'+path+'/shiwu4.png',\r\n '../'+path+'/shiwu5.png',\r\n '../'+path+'/shiwu6.png',\r\n \r\n \r\n '../'+path+'/yanzhi.png',\r\n '../'+path+'/qingshui.png',\r\n '../'+path+'/gudong.png',\r\n \r\n '../'+path+'/mianju.png',\r\n '../'+path+'/zhuqingting.png'\r\n ]\r\n\r\n def enter(self,imgs):\r\n loca = findImgRegion(imgs[0],0,0,1400,800)\r\n isDone = click(loca)\r\n if isDone:\r\n tillFindClick(imgs[1]) \r\n tillFindClick(imgs[2]) \r\n tillFindClick(imgs[3]) \r\n \r\n def findYao2(self,imgs):\r\n isTrue = hasImgs(['../'+path+'/tuichu.png'])\r\n if isTrue:\r\n time.sleep(0.5)\r\n clickWhenSee(imgs[0])\r\n time.sleep(0.5)\r\n clickWhenSee(imgs[1])\r\n #pack = findImgSize(imgs[1])\r\n isTrue = True\r\n while isTrue:\r\n isTrue = hasImgsRegion(['../'+path+'/zhongzhizhong.png',\r\n '../'+path+'/zhongdi1.png',\r\n '../'+path+'/zhongdi12.png',\r\n \r\n '../'+path+'/zhongdi2.png',\r\n '../'+path+'/zhongdi22.png',\r\n \r\n '../'+path+'/zhongdi3.png',\r\n '../'+path+'/zhongdi32.png',\r\n \r\n '../'+path+'/zaotai1.png',\r\n '../'+path+'/zaotai12.png',\r\n \r\n '../'+path+'/zaotai2.png',\r\n '../'+path+'/zaotai22.png'],x=955,y=258,w=290,h=126)#'../'+path+'/zaotai1.png', '../'+path+'/zaotai2.png'],\r\n if isTrue:\r\n dis = random.randint(70,85)\r\n viewUpDown(screenSize[0],screenSize[1],-dis)\r\n time.sleep(0.2)\r\n \r\n #moveToWhenSee(imgs[1]) \r\n #if pack != None:\r\n #clickRelative(0,3.5*pack[1])\r\n randomClickWithinRegion(273,400,315,320)\r\n time.sleep(0.2)\r\n clickWhenSee(imgs[2])\r\n clickWhenSee('../'+path+'/quedingqingyi.png')\r\n clickWhenSee('../'+path+'/qingyiqueding.png')\r\n \r\n #viewLeftRight(screenSize[0],screenSize[1],-100)\r\n #timedExecute(viewLeftRight,5,[screenSize[0],screenSize[1],-100])\r\n time.sleep(0.1)\r\n count = 5\r\n isDone = False\r\n while count > 0 and not isDone:\r\n randomClickWithinRegion(1020,1060,542,586)\r\n time.sleep(0.5)\r\n count -=1\r\n if hasImgsRegion(['../'+path+'/tuichu.png'],x =1152 ,y=668,w = 1322-1152,h = 773-668 ):\r\n time.sleep(1.5)\r\n else:\r\n if hasImgsRegion(['../'+path+'/songli.png'],x = 831,y=313,w = 1184-831,h = 430-313 ):\r\n time.sleep(0.5)\r\n randomClickWithinRegion(923,1127,338,390)\r\n time.sleep(0.5)\r\n #songli\r\n random.shuffle(self.gifts)\r\n idx,found = findImgsRegion(self.gifts,x=888,y=206,w=1297-888,h=625-206)\r\n click(found)\r\n randomClickWithinRegion(1082,1150,665,685) \r\n time.sleep(0.5)\r\n randomClickWithinRegion(44,134,42,71)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(44,134,42,71)\r\n time.sleep(0.5)\r\n else:\r\n times = 30\r\n while times > 0:\r\n print('clicking '+str(times))\r\n\r\n randomClickWithinRegion(934,964,274,291)\r\n randomClickWithinRegion(653,699,664,685)\r\n \r\n times -= 1\r\n \r\n if hasImgs(['../'+path+'/daojishi.png']):\r\n isDone = True\r\n break\r\n \r\n hasimg = hasImgs(['../'+path+'/huida.png',\r\n '../'+path+'/shouxia.png',\r\n '../'+path+'/shouxia2.png',\r\n '../'+path+'/tuichu.png',\r\n '../'+path+'/kanban.png'])\r\n if hasimg:\r\n time.sleep(2)\r\n if hasImgs(['../'+path+'/huida.png',\r\n '../'+path+'/shouxia.png',\r\n '../'+path+'/shouxia2.png',\r\n '../'+path+'/tuichu.png',\r\n '../'+path+'/kanban.png']):\r\n isDone = True\r\n break\r\n \r\n clickWhenSee('../'+path+'/huaquan.png')\r\n time.sleep(0.3)\r\n clickWhenSee('../'+path+'/huaquanqueding.png')\r\n clickWhenSee(imgs[6])\r\n clickWhenSee(imgs[5])\r\n clickWhenSee('../'+path+'/touxiang.png')\r\n clickWhenSee('../'+path+'/touxiang2.png')\r\n \r\n if clickWhenSee('../'+path+'/generalBack.png'):\r\n time.sleep(0.1)\r\n clickWhenSee('../'+path+'/generalBack.png')\r\n time.sleep(0.1)\r\n clickWhenSee('../'+path+'/generalBack.png')\r\n time.sleep(0.1)\r\n clickWhenSee('../'+path+'/generalBack.png')\r\n time.sleep(0.1)\r\n clickWhenSee('../'+path+'/queding.png')\r\n clickWhenSee('../'+path+'/mapcross.png')\r\n clickWhenSee('../'+path+'/shuzhaiback.png')\r\n clickWhenSee('../'+path+'/qingyiqueding.png')\r\n clickWhenSee('../'+path+'/quedingqingyi.png')\r\n \r\n \r\n print('interact done') \r\n if count == 0:\r\n randomDis = random.randint(200, 400)\r\n timedExecute(viewLeftRight,1,[screenSize[0],screenSize[1],-100-randomDis])\r\n dis = random.randint(100,200)\r\n randomDragUpWithinRegion(164,201,600,641,-dis)\r\n dis = random.randint(100,200)\r\n randomDragUpWithinRegion(164,201,600,641,-dis)\r\n \r\n return count\r\n \r\n def findYao(self,imgs):\r\n isTrue = hasImgs(['../'+path+'/tuichu.png'])\r\n if isTrue:\r\n time.sleep(0.5)\r\n clickWhenSee(imgs[0])\r\n time.sleep(0.5)\r\n clickWhenSee(imgs[1])\r\n #pack = findImgSize(imgs[1])\r\n isTrue = True\r\n while isTrue:\r\n isTrue = hasImgsRegion(['../'+path+'/zhongdi1.png',\r\n '../'+path+'/zhongdi2.png',\r\n '../'+path+'/zhongdi3.png',\r\n '../'+path+'/zaotai1.png',\r\n '../'+path+'/zaotai2.png'],x=955,y=258,w=290,h=126)\r\n if isTrue:\r\n dis = random.randint(70,85)\r\n viewUpDown(screenSize[0],screenSize[1],-dis)\r\n time.sleep(0.2)\r\n \r\n #moveToWhenSee(imgs[1]) \r\n #if pack != None:\r\n #clickRelative(0,3.5*pack[1])\r\n randomClickWithinRegion(273,480,315,320)\r\n time.sleep(0.2)\r\n clickWhenSee(imgs[2])\r\n #viewLeftRight(screenSize[0],screenSize[1],-100)\r\n #timedExecute(viewLeftRight,5,[screenSize[0],screenSize[1],-100])\r\n time.sleep(0.1)\r\n isDone = None\r\n count = 5\r\n while isDone == None and count > 0:\r\n count -= 1\r\n clickWhenSee(imgs[5])\r\n clickWhenSee(imgs[6])\r\n clickWhenSee('../'+path+'/shouxia.png')\r\n clickWhenSee('../'+path+'/shouxiapengren.png')\r\n clickWhenSee('../'+path+'/mapcross.png')\r\n clickWhenSee('../'+path+'/ccross.png')\r\n clickWhenSee('../'+path+'/backhuodong.png')\r\n if clickWhenSee('../'+path+'/generalBack.png'):\r\n time.sleep(0.2)\r\n clickWhenSee('../'+path+'/huaquanqueding.png')\r\n \r\n print('finding tanhao times '+str(count))\r\n pyautogui.scroll(-500)\r\n isDone = tillFindClickTime([imgs[3],imgs[4],'../'+path+'/tanhao3.png','../'+path+'/tanhao4.png'],1)\r\n time.sleep(2)\r\n notThere = findImgRegion('../'+path+'/tuichu.png',0,0,1400,800)\r\n if notThere != None:\r\n isDone = None\r\n \r\n if isDone != None:\r\n times = 30\r\n while times > 0:\r\n print('clicking '+str(times))\r\n clickWhenSee('../'+path+'/huaquan.png')\r\n time.sleep(0.3)\r\n clickWhenSee('../'+path+'/huaquanqueding.png')\r\n clickWhenSee('../'+path+'/touxiang.png')\r\n if clickWhenSee('../'+path+'/generalBack.png'):\r\n clickWhenSee('../'+path+'/generalBack.png')\r\n clickWhenSee('../'+path+'/generalBack.png')\r\n clickWhenSee('../'+path+'/generalBack.png')\r\n clickWhenSee(imgs[6])\r\n clickWhenSee(imgs[5])\r\n clickWhenSee('../'+path+'/mapcross.png')\r\n clickWhenSee('../'+path+'/shuzhaiback.png')\r\n randomClickWithinRegion(934,964,274,291)\r\n times -= 1\r\n \r\n if hasImgs(['../'+path+'/daojishi.png']):\r\n break\r\n \r\n hasimg = hasImgs(['../'+path+'/huida.png',\r\n '../'+path+'/shouxia.png',\r\n '../'+path+'/shouxia2.png',\r\n '../'+path+'/tuichu.png',\r\n '../'+path+'/kanban.png'])\r\n if hasimg:\r\n time.sleep(2)\r\n if hasImgs(['../'+path+'/huida.png',\r\n '../'+path+'/shouxia.png',\r\n '../'+path+'/shouxia2.png',\r\n '../'+path+'/tuichu.png',\r\n '../'+path+'/kanban.png']):\r\n break\r\n \r\n print('interact done')\r\n else:\r\n randomDis = random.randint(200, 400)\r\n timedExecute(viewLeftRight,1,[screenSize[0],screenSize[1],-100-randomDis])\r\n \r\n return count\r\n \r\n def Act(self,imgs):\r\n finishOne = False\r\n print('doing Act')\r\n count = 20\r\n while not finishOne and count > 0:\r\n hasimg = hasImgs(['../'+path+'/tuichu.png'])\r\n if hasimg:\r\n break\r\n print('doing Act While')\r\n idx,found = findImgs(imgs)\r\n count -= 1\r\n if imgs[idx] == '../'+path+'/shouxia.png':\r\n finishOne = True\r\n click(found)\r\n elif imgs[idx] == '../'+path+'/lingqujiangli.png':\r\n finishOne = True\r\n click(found)\r\n elif imgs[idx] == '../'+path+'/huaquan.png':\r\n clickWhenSee('../'+path+'/huaquanqueding.png')\r\n elif imgs[idx] == '../'+path+'/huidaqueren.png':\r\n randomClickWithinRegion(616,667,281,341)\r\n time.sleep(0.5)\r\n clickWhenSee('../'+path+'/huidaqueren2.png')\r\n time.sleep(0.5)\r\n clickWhenSee('../'+path+'/lingqujiangli.png')\r\n randomClickWithinRegion(1049,1114,432,506)\r\n time.sleep(0.5)\r\n clickWhenSee('../'+path+'/huidaqueren2.png')\r\n \r\n time.sleep(0.5)\r\n \r\n clickWhenSee('../'+path+'/lingqujiangli.png')\r\n clickWhenSee('../'+path+'/xiacinuli.png')\r\n elif imgs[idx]=='../'+path+'/daojishi.png':\r\n print('wait for zhuomicang')\r\n time.sleep(90)\r\n else:\r\n print('Shouxia not found, continue try times: '+str(count))\r\n click(found)\r\n \r\n time.sleep(0.5)\r\n clickWhenSee('../'+path+'/sanbuqueren.png')\r\n \r\n if count == 0:\r\n notThere = findImgRegion('../'+path+'/tuichu.png',0,0,1400,800)\r\n if notThere == None:\r\n count +=1\r\n \r\n \r\n return finishOne\r\n \r\n \r\n def zhongzhi(self):\r\n #cli = clickWhenSee('../'+path+'/qianwangzhongzhi.png')\r\n randomClickWithinRegion(1034,1178,690,728)\r\n time.sleep(1)\r\n while hasImgs(['../'+path+'/chengshou.png','../'+path+'/chengshou2.png','../'+path+'/tuichu.png']):\r\n print('walking....')\r\n time.sleep(1.5)\r\n \r\n for i in range(3):\r\n tc = 3\r\n while not clickWhenSee('../'+path+'/shouge.png') and tc > 0:\r\n print('waiting shouge....'+str(tc))\r\n time.sleep(0.25)\r\n tc-=1\r\n time.sleep(0.5)\r\n clickWhenSeeRegion('../'+path+'/zhongzhiqueding.png',556,634,797-556,725-634)\r\n \r\n tc = 3\r\n while not clickWhenSee('../'+path+'/shouxiazuowu.png') and tc > 0:\r\n print('waiting shouxia....'+str(tc))\r\n time.sleep(0.25)\r\n tc-=1\r\n time.sleep(0.5) \r\n clickWhenSeeRegion('../'+path+'/zhongzhiqueding.png',556,634,797-556,725-634)\r\n\r\n '''\r\n tc = 3 \r\n while not hasImgs(['../'+path+'/bozhong.png']) and tc > 0:\r\n print('waiting bozhong....'+str(tc))\r\n time.sleep(0.25)\r\n tc-=1\r\n \r\n for i in range(8):\r\n if hasImgs(['../'+path+'/chanchuzuowu.png']):\r\n break\r\n clickWhenSee('../'+path+'/bozhong.png')\r\n print('bozhong ing ......'+str(i))\r\n time.sleep(0.5)\r\n '''\r\n \r\n randomClickWithinRegion(813,827,397,419)\r\n \r\n tc = 3\r\n while not clickWhenSee('../'+path+'/tuichuzhongzhi.png') and tc > 0:\r\n print('waiting tuichu....'+str(tc))\r\n time.sleep(0.5)\r\n tc-=1\r\n\r\n def pengren(self):\r\n randomClickWithinRegion(1282,1307,253,272)\r\n time.sleep(0.5)\r\n if not hasImgs(['../'+path+'/tuichu.png']):\r\n time.sleep(0.3)\r\n randomClickWithinRegion(1179,1258,127,174)\r\n time.sleep(0.3)\r\n randomClickWithinRegion(1089,1132,105,125)\r\n time.sleep(0.3)\r\n dis = random.randint(100, 200)\r\n randomDragUpWithinRegion(841,1158,353,554,-dis) \r\n \r\n time.sleep(1)\r\n tc = 10\r\n while not clickWhenSeeRegion('../'+path+'/pengrenicon.png',729,119,1275-729,735-119) and tc > 0:\r\n tc =- 1\r\n print('finding pengren: '+str(tc))\r\n time.sleep(0.2)\r\n\r\n time.sleep(1)\r\n randomClickWithinRegion(1056,1159,694,718)\r\n time.sleep(1.5)\r\n while hasImgs(['../'+path+'/tuichu.png']):\r\n print('walking....')\r\n time.sleep(0.5) \r\n\r\n if clickWhenSeeRegion('../'+path+'/pengrenshouqu.png',1104,682,1315-1104,769-682):\r\n tc = 3\r\n while not clickWhenSeeRegion('../'+path+'/shouxiapengren.png',556,632,791-556,723-632) and tc > 0:\r\n print('waiting shouxia pengren....'+str(tc))\r\n time.sleep(0.5)\r\n tc-=1\r\n \r\n tc = 3\r\n while not clickWhenSeeRegion('../'+path+'/shouxiapengren.png',556,632,791-556,723-632) and tc > 0:\r\n print('waiting shouxia pengren....'+str(tc))\r\n time.sleep(0.5)\r\n tc-=1\r\n\r\n time.sleep(0.5)\r\n hasZhizuo = hasImgs(['../'+path+'/zhizuo.png'])\r\n bb = random.choice([0,1])\r\n if not hasZhizuo:\r\n if bb == 0:\r\n cliJia = clickWhenSeeRegion('../'+path+'/jiapengren.png',43,490,570,205)\r\n elif bb == 1:\r\n cliJia = clickWhenSeeRegion('../'+path+'/jiapengren.png',726,507,595,175)\r\n\r\n time.sleep(0.5)\r\n hasjz = hasImgs(['../'+path+'/hasjiaozi.png'])\r\n \r\n cli = clickWhenSee('../'+path+'/zhizuo.png')\r\n #isfinished = hasImgs(['../'+path+'/chaochushangxian.png'])\r\n time.sleep(0.5)\r\n isquxiao = hasImgs(['../'+path+'/yiyuanquxiao.png'])\r\n if isquxiao:\r\n randomClickWithinRegion(901,974,481,512)\r\n \r\n #songli \r\n random.shuffle(self.gifts)\r\n idx,found = findImgsRegion(self.gifts,x=841,y=239,w=1262-841,h=628-239)\r\n click(found)\r\n randomClickWithinRegion(1100,1175,665,692)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(44,134,42,71)\r\n else:\r\n randomClickWithinRegion(668,795,58,90)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(668,795,58,90)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(668,795,58,90)\r\n\r\n \r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/pengren.png')\r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/pengren.png')\r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/pengren.png')\r\n\r\n def gozhongzhi(self):\r\n randomClickWithinRegion(1282,1307,253,272)\r\n time.sleep(0.5)\r\n if not hasImgs(['../'+path+'/tuichu.png']):\r\n time.sleep(0.3)\r\n randomClickWithinRegion(1179,1258,127,174)\r\n time.sleep(0.3)\r\n randomClickWithinRegion(1089,1132,105,125)\r\n time.sleep(0.3)\r\n dis = random.randint(100, 200)\r\n randomDragUpWithinRegion(841,1158,353,554,-dis) \r\n \r\n time.sleep(1)\r\n tc = 10\r\n while not clickWhenSeeRegion('../'+path+'/zhongzhi.png',729,119,1275-729,735-119) and tc > 0:\r\n tc =- 1\r\n print('finding zhongzhi: '+str(tc))\r\n time.sleep(0.2)\r\n\r\n time.sleep(1)\r\n randomClickWithinRegion(1056,1159,694,718)\r\n time.sleep(1.5)\r\n while hasImgs(['../'+path+'/tuichu.png']):\r\n print('walking....')\r\n time.sleep(0.5) \r\n\r\n #entered\r\n for i in range(3): \r\n tc = 3 \r\n while not hasImgs(['../'+path+'/bozhong.png']) and tc > 0:\r\n print('waiting bozhong....'+str(tc))\r\n time.sleep(0.25)\r\n tc-=1\r\n \r\n for i in range(8):\r\n if hasImgs(['../'+path+'/chanchuzuowu.png','../'+path+'/shouge1.png']):\r\n self.zhongzhiing = True\r\n break\r\n #clickWhenSee('../'+path+'/bozhong.png')\r\n randomClickWithinRegion(1052,1130,647,681)\r\n print('bozhong ing ......'+str(i))\r\n time.sleep(0.5)\r\n \r\n randomClickWithinRegion(813,827,397,419)\r\n \r\n \r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[46,63,48,61])\r\n time.sleep(0.5)\r\n '''\r\n tc = 3\r\n while not clickWhenSee('../'+path+'/tuichuzhongzhi.png') and tc > 0:\r\n print('waiting tuichu....'+str(tc))\r\n time.sleep(0.5)\r\n tc-=1\r\n '''\r\n\r\n def shoupengren(self):\r\n cli = clickWhenSee('../'+path+'/pengrenwancheng.png')\r\n\r\n if cli:\r\n time.sleep(0.5)\r\n clickWhenSee('../'+path+'/qianwangpengren.png')\r\n while hasImgs(['../'+path+'/pengrenwancheng.png']):\r\n print('walking....')\r\n time.sleep(0.5)\r\n \r\n tc = 10\r\n while not clickWhenSee('../'+path+'/pengrenshouqu.png') and tc > 0:\r\n print('waiting shoupengren....'+str(tc))\r\n time.sleep(0.5)\r\n tc-=1\r\n \r\n tc = 10\r\n while not clickWhenSee('../'+path+'/shouxiapengren.png') and tc > 0:\r\n print('waiting shouxia pengren....'+str(tc))\r\n time.sleep(0.5)\r\n tc-=1\r\n \r\n tc = 10\r\n while not clickWhenSee('../'+path+'/shouxiapengren.png') and tc > 0:\r\n print('waiting shouxia pengren....'+str(tc))\r\n time.sleep(0.5)\r\n tc-=1\r\n \r\n tc = 10\r\n while not clickWhenSee('../'+path+'/pengren.png') and tc > 0:\r\n print('waiting pengren....'+str(tc))\r\n time.sleep(0.5)\r\n tc-=1\r\n \r\n return cli\r\n \r\n\r\n #wuxing: goFuben('../'+path+'/wuxingxiulian.png','python fuben.py --goal 10 --wuxing') \r\n #huanjing, huodong add based on needs\r\n def goFuben(self,fuben,cmd):\r\n tc = 10\r\n while not clickWhenSee('../'+path+'/tiaomu.png') and tc > 0:\r\n randomDis = random.randint(100, 200)\r\n timedExecute(viewLeftRight,1,[screenSize[0],screenSize[1],-100-randomDis])\r\n time.sleep(1)\r\n tc -=1\r\n print('finding tiaomu wuxing count: '+str(tc))\r\n \r\n if tc > 0: \r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/xingnang.png')\r\n eatCount = 10\r\n while hasImgs(['../'+path+'/qingtuan.png','../'+path+'/lvjiaozi.png','../'+path+'/qingtuan2.png']) and eatCount>0:\r\n clickWhenSee('../'+path+'/qingtuan.png')\r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/shiyong.png')\r\n clickWhenSee('../'+path+'/qingtuan2.png')\r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/shiyong.png')\r\n clickWhenSee('../'+path+'/lvjiaozi.png')\r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/shiyong2.png')\r\n eatCount-=1\r\n print('eatCount : '+str(eatCount))\r\n \r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/xingnangback.png')\r\n time.sleep(0.5)\r\n cli = clickWhenSee('../'+path+'/huodong.png')\r\n time.sleep(0.5)\r\n tc = 10\r\n while not hasImgs([fuben]) and tc>0:\r\n dis = random.randint(100, 150)\r\n randomDragUpWithinRegion(1055,1101,392,471,-dis)\r\n tc -= 1\r\n print('tc count: '+str(tc))\r\n if tc != 0:\r\n time.sleep(0.5)\r\n while not clickWhenSee(fuben):\r\n time.sleep(0.3)\r\n \r\n time.sleep(1)\r\n for i in range(4):\r\n dis = random.randint(100, 200)\r\n randomDragUpWithinRegion(841,1158,353,554,-dis)\r\n time.sleep(0.4)\r\n randomClickWithinRegion(851,1184,650,736)\r\n #os.system('python wuxing2.py 100')\r\n os.system(cmd)\r\n print('Wuxing finished')\r\n else:\r\n clickWhenSee('../'+path+'/generalBack.png')\r\n time.sleep(0.5)\r\n clickWhenSee('../'+path+'/huodongcross.png')\r\n \r\n def dacan(self):\r\n cli = clickWhenSee('../'+path+'/dacanjieshu.png')\r\n\r\n if cli:\r\n time.sleep(0.5)\r\n clickWhenSee('../'+path+'/dacanqueding.png')\r\n \r\n while hasImgs(['../'+path+'/tuichu.png']):\r\n print('walking....')\r\n time.sleep(0.5) \r\n \r\n time.sleep(0.5)\r\n #clickWhenSee('../'+path+'/dacanlingqujiangli.png')\r\n randomClickWithinRegion(1046,1151,658,679)\r\n time.sleep(0.5)\r\n \r\n #clickWhenSee('../'+path+'/dacanBack.png')\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(0.5)\r\n clickWhenSee('../'+path+'/kanban.png')\r\n #randomClickWithinRegion(*[49,66,47,66])\r\n \r\n self.fangdacan = True\r\n \r\n def fangDacan(self):\r\n hasXinxi = clickWhenSeeRegion('../'+path+'/xinxi.png',1155,680,1253-1155,771-680)\r\n if hasXinxi: \r\n time.sleep(1)\r\n randomClickWithinRegion(*[1011,1027,52,65])\r\n time.sleep(1)\r\n youdacan = hasImgsRegion(['../'+path+'/youdacan.png'],939,393,1113-939,447-393)\r\n if not youdacan:\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[961,1073,557,585])\r\n time.sleep(1)\r\n clickWhenSeeRegion('../'+path+'/zhuli300.png',313,559,574-313,637-559)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[890,980,481,513])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(0.5)\r\n \r\n else:\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(0.5)\r\n \r\n \r\n def replaceYao(self):\r\n hasXinxi = clickWhenSeeRegion('../'+path+'/xinxi.png',1155,680,1253-1155,771-680)\r\n if hasXinxi:\r\n print(\"replacing\")\r\n random.shuffle(self.replacePoss)\r\n repPos = self.replacePoss[0]\r\n randomClickWithinRegion(*repPos)\r\n time.sleep(0.5)\r\n \r\n randomClickWithinRegion(*[919,939,255,276])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[1057,1113,679,700])\r\n time.sleep(0.5)\r\n #randomClickWithinRegion(*[49,66,47,66])\r\n if self.fangdacan:\r\n randomClickWithinRegion(*[502,530,451,475])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[1011,1027,52,65])\r\n time.sleep(1)\r\n youdacan = hasImgsRegion(['../'+path+'/youdacan.png'],939,393,1113-939,447-393)\r\n if not youdacan:\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[961,1073,557,585])\r\n time.sleep(1)\r\n clickWhenSeeRegion('../'+path+'/zhuli300.png',313,559,574-313,637-559)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[890,980,481,513])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(0.5)\r\n \r\n else:\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(0.5)\r\n self.fangdacan = False\r\n else:\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(0.5)\r\n \r\n else:\r\n print(\"not ready to replace\")\r\n \r\n def chidacan(self):\r\n pos = [[1021,1104,297,320],[1066,1112,393,415],[1037,1102,487,503],[1057,1119,579,600]]\r\n for i in range(4):\r\n randomClickWithinRegion(830,844,733,741)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(33,51,194,216)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(474,499,718,731)\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*pos[i])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(644,702,580,599)\r\n time.sleep(10)\r\n randomClickWithinRegion(1056,1144,656,678)\r\n time.sleep(2)\r\n randomClickWithinRegion(641,705,682,710)\r\n time.sleep(1)\r\n randomClickWithinRegion(*[49,66,47,66])\r\n time.sleep(2)\r\n randomClickWithinRegion(*[1102,1107,646,652])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[470,497,645,666])\r\n randomClickWithinRegion(*[470,497,645,666])\r\n \r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[513,547,325,363])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[1176,1202,642,656])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[49,66,47,66])\r\n \r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[1287,1296,255,269])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[1266,1284,359,374])\r\n time.sleep(0.5)\r\n randomClickWithinRegion(*[1204,1240,721,732])\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\nif __name__ == '__main__':\r\n \r\n jy = jiayuan()\r\n \r\n #test place\r\n \r\n notThere = findImgRegion('../'+path+'/tuichu.png',0,0,1400,800)\r\n if notThere == None:\r\n jy.enter(['../'+path+'/tiaomu.png','../'+path+'/'+path+'.png','../'+path+'/huijia.png','../'+path+'/kanban.png'])\r\n \r\n if args.dacan:\r\n if jy.dacanflag:\r\n jy.chidacan()\r\n jy.dacanflag = False\r\n \r\n countPengren = 0\r\n countWuxing = 0\r\n countAnying = 0\r\n while True:\r\n print('new iteration')\r\n #cli = clickWhenSee('../'+path+'/chengshou.png')\r\n #idx,found = findImgsRegion(['../'+path+'/chengshou.png','../'+path+'/chengshou2.png'],x=499,y=1127,w=1127-499,h=218-37)\r\n idx,found = findImgs(['../'+path+'/chengshou.png','../'+path+'/chengshou2.png'])\r\n if found != None:\r\n click(found)\r\n time.sleep(1)\r\n jy.zhongzhi()\r\n\r\n jy.zhongzhiing = False\r\n else:\r\n \r\n if args.songli:\r\n count = jy.findYao2(['../'+path+'/yaoling.png',\r\n '../'+path+'/yiyuan.png',\r\n '../'+path+'/quzhaota.png',\r\n '../'+path+'/tanhao.png',\r\n '../'+path+'/tanhao2.png',\r\n '../'+path+'/pengren.png',\r\n '../'+path+'/kanban.png'])\r\n else:\r\n count = jy.findYao(['../'+path+'/yaoling.png',\r\n '../'+path+'/yiyuan.png',\r\n '../'+path+'/quzhaota.png',\r\n '../'+path+'/tanhao.png',\r\n '../'+path+'/tanhao2.png',\r\n '../'+path+'/pengren.png',\r\n '../'+path+'/kanban.png'])\r\n if count != 0:\r\n jy.Act(['../'+path+'/shouxia.png',\r\n '../'+path+'/shouxia2.png',\r\n '../'+path+'/lingqujiangli.png',\r\n '../'+path+'/huida.png',\r\n '../'+path+'/huaquan.png',\r\n '../'+path+'/queding.png',\r\n '../'+path+'/huidaqueren.png',\r\n '../'+path+'/daojishi.png',\r\n '../'+path+'/kanban.png'])\r\n jy.replaceCount += 1\r\n if jy.replaceCount == 1:\r\n jy.replaceCount = 0\r\n jy.replaceYao()\r\n \r\n clickWhenSee('../'+path+'/queding2.png')\r\n \r\n #pengrenDone = jy.shoupengren()\r\n #if pengrenDone:\r\n # print('go pengren')\r\n # if args.pengren:\r\n # jy.pengren()\r\n \r\n jy.dacan()\r\n #jy.fangDacan()\r\n \r\n if hasImgsRegion(['../'+path+'/tuichu.png'],x =1152 ,y=668,w = 1322-1152,h = 773-668 ):\r\n countPengren+=1\r\n countWuxing+=1\r\n countAnying+=1\r\n print('count to pengren: '+str(countPengren))\r\n print('count to wuxing: '+str(countWuxing))\r\n print('count to anying: '+str(countAnying))\r\n \r\n if countPengren == 1 or countPengren == 5:\r\n print('go pengren timely')\r\n if args.pengren:\r\n jy.pengren()\r\n if countPengren == 5:\r\n countPengren = 2\r\n \r\n if countWuxing == 1 or countWuxing == 15:\r\n print('go wuxing timely')\r\n if args.wuxing:\r\n jy.goFuben('../'+path+'/wuxingxiulian.png','python fuben.py --goal 65535 --seq 132 --doge') \r\n if countWuxing == 15:\r\n countWuxing = 2\r\n \r\n if countAnying == 1 or countAnying == 7:\r\n print('go anying timely')\r\n if args.anying:\r\n jy.goFuben('../'+path+'/yunmenganying.png','python fuben.py --goal 65535 --anying --doge') \r\n if countAnying == 7:\r\n countAnying = 2\r\n\r\n if not jy.zhongzhiing:\r\n jy.gozhongzhi()\r\n\r\n\r\n '''\r\n while True:\r\n jy.pengren()\r\n #jy.goWuxing()\r\n '''\r\n","sub_path":"src/jiayuan.py","file_name":"jiayuan.py","file_ext":"py","file_size_in_byte":38059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"543231469","text":"# Copyright 2015 Metaswitch Networks\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom tests.st.test_base import TestBase\nfrom tests.st.utils.docker_host import DockerHost\n\n\nclass TestContainerToHost(TestBase):\n def test_container_to_host(self):\n \"\"\"\n Test that a container can ping the host.\n\n This function is important for Mesos, since the containerized executor\n needs to exchange messages with the Mesos Slave process on the host.\n\n Note also that we do not use the Docker Network driver for this test.\n The Docker Container Network Model defines a \"network\" as a group of\n endpoints that can communicate with each other, but are isolated from\n everything else. Thus, an endpoint of a Docker network should not be\n able to ping the host.\n \"\"\"\n with DockerHost('host', dind=False) as host:\n host.calicoctl(\"profile add TEST\")\n\n # Use standard docker bridge networking.\n node1 = host.create_workload(\"node1\")\n\n # Add the nodes to Calico networking.\n host.calicoctl(\"container add %s 192.168.100.1\" % node1)\n\n # Get the endpoint IDs for the containers\n ep1 = host.calicoctl(\"container %s endpoint-id show\" % node1)\n\n # Now add the profiles.\n host.calicoctl(\"endpoint %s profile set TEST\" % ep1)\n\n # Check it works. Note that the profile allows all outgoing\n # traffic by default, and conntrack should allow the reply.\n node1.assert_can_ping(host.ip, retries=10)\n","sub_path":"calico_containers/tests/st/no_orchestrator/test_container_to_host.py","file_name":"test_container_to_host.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"521517105","text":"#generating parent child dictionary like{food:{parent:media,child:[......]}} from \n#graph_parent_dict\n\nimport cjson\nlocal='/spare/wei/local/%s'\ninfile=local%'graph_parent_dict_ch3-log1'\ninfile=open(infile,'r')\ngraph_parent_dict=cjson.decode(infile.readline())\np_c_dict={}\nfor key,value in graph_parent_dict.iteritems():\n if key not in p_c_dict.keys():\n p_c_dict[key]= {'parent':value, 'child':[]}\n else:\n p_c_dict[key]['parent']=value\n if value not in p_c_dict.keys():\n p_c_dict[value]={'parent':'a', 'child':[key]}\n else:\n p_c_dict[value]['child'].append(key)\noutfile=open(local%'p_c_dict_ch3','w')\noutfile.write(cjson.encode(p_c_dict))\n\n","sub_path":"backbone/houston_lc/generate_p_c_dict.py","file_name":"generate_p_c_dict.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"7049628","text":"# Copyright (C) 2011 by Michele Silva (michele.silva@gmail.com)\n# This code is part of the Biopython distribution and governed by its\n# license. Please see the LICENSE file that should have been included\n# as part of this package.\n\nimport unittest\nimport os\n\nfrom Bio.PDB.Barnacle.Barnacle import Barnacle\n\n\nclass BarnacleTestCase(unittest.TestCase):\n\n def setUp(self):\n current_directory = os.path.dirname(globals()[\"__file__\"])\n self.datadir = os.path.join(current_directory, \"Barnacle/\")\n\n\n def test_model_sample(self):\n # The target sequence\n sequence = \"ACGU\"\n\n # Initialize the model\n model = Barnacle(sequence, seed=123)\n\n # Draw first sample\n model.sample()\n\n # Sample position j\n j = 0 \n model.sample(start=j, end=j+1)\n \n obtained_filename = \"test_Barnacle.pdb.obtained\"\n expected_filename = \"test_Barnacle.pdb.expected\"\n\n # Save the structure\n model.save_structure(os.path.join(self.datadir, obtained_filename))\n\n # Compare generated file\n obtained_file = open(os.path.join(self.datadir, obtained_filename))\n expected_file = open(os.path.join(self.datadir, expected_filename))\n\n self.assertEquals(obtained_file.readlines(), expected_file.readlines())\n\n \n def test_get_log_likelihood(self):\n # The target sequence\n sequence = \"ACGU\"\n\n # Initialize the model\n model = Barnacle(sequence, seed=123)\n\n # Draw first sample\n model.sample()\n\n # Sample position j\n j = 0 \n model.sample(start=j, end=j+1)\n\n # Calculate and print likelihood\n ll = model.get_log_likelihood()\n # print \"test_Barnacle.pdb: ll = %f\" % (ll)\n self.assertAlmostEquals(ll, 19.648623, places=4)\n \n \n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner(verbosity=2)\n unittest.main(testRunner=runner)\n","sub_path":"Tests/test_Barnacle.py","file_name":"test_Barnacle.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"578172366","text":"import re\nfrom iDB import *\n\nclass iParser :\n input_file = '' #default 'info.csv'\n patt_start = ''\n patt_info = ''\n patt_time = ''\n patt_choice = 0\n\n time = ''\n info_item = {}\n\n db = ''\n \n def __init__(self, db, choice) : \n #init******************************************\n self.db = db\n self.input_file = '' #default 'info.csv'\n self.patt_start = '========================================================='\n \n #->read Time ReqEx.\n #patt_time = raw_input('Time ReqEx. [\\w+\\s\\w+\\s+[0-31]+\\s+\\d+:\\d+:\\d+\\s+(KST|GMT)\\s+\\d{4})] : ')\n self.patt_time = '(\\w+\\s+\\w+\\s+[0-9]+\\s+\\d+:\\d+:\\d+\\s+(KST|GMT)\\s+\\d{4})'\n\n #->chosed parsing ReqEx.\n self.patt_choice = choice\n if (self.patt_choice == 1) :\n print ('CputInfo : \\s+(\\d+\\.?\\d)\\%\\s+\\d+\\/([\\w\\.\\/]+)\\:\\s+')\n self.patt_info = '\\s+(\\d+\\.?\\d)\\%\\s+\\d+\\/([\\w\\.\\/]+)\\:\\s+'\n elif (self.patt_choice == 2) :\n print ('PowerWake : \\s*(\\w*WAKE_LOCK)\\s+\\'([\\w\\.\\/]+)\\'\\s?[\\w]*\\s?\\(uid=(\\d+),\\s+pid=(\\d+)')\n self.patt_info = '\\s*(\\w*WAKE_LOCK)\\s+\\'([\\w\\.\\/]+)\\'\\s?[\\w]*\\s?\\(uid=(\\d+),\\s+pid=(\\d+)'\n elif (self.patt_choice == 3) :\n print ('ProcRank : \\s*(\\d+)\\s+(-?\\d+)\\s+(\\d+)K?\\s+(\\d+)K?\\s+(\\d+)K?\\s+(\\d+)K?\\s+(\\d+)K?\\s+([\\w\\.\\/]+)')\n self.patt_info = '\\s*(\\d+)\\s+(-?\\d+)\\s+(\\d+)K?\\s+(\\d+)K?\\s+(\\d+)K?\\s+(\\d+)K?\\s+(\\d+)K?\\s+([\\w\\.\\/]+)'\n elif (self.patt_choice == 4) :\n print ('CpuFreq. : \\s*(\\d+)')\n self.patt_info = '\\s*(\\d+)'\n elif (self.patt_choice == 5) :\n print ('GpuStat. : \\s*(\\d+)\\s+(\\d+)')\n self.patt_info = '\\s*(\\d+)\\s+(\\d+)'\n \n else:\n self.patt_info = ''\n print (self.patt_info)\n\n\n def parse(self, obj):\n if (obj == '') :\n return\n\n cnt =0\n self.db.initItemsList()\n self.db.initItemList()\n data = obj\n for data in obj.splitlines() :\n rs_data = data.rstrip()\n #print rs_data\n if bool(re.match(self.patt_start, rs_data)):\n print (rs_data) \n \n \n elif bool(re.match(self.patt_time, rs_data)):\n #print rs_data \n if (self.db.Item_list != {}):\n self.db.insertItems(self.time, self.db.Item_list)\n\n self.time = rs_data\n self.db.Item_list = {} #info_db.initItemList() \n\n elif bool(re.match(self.patt_info, rs_data)):\n self.info_item = re.match(self.patt_info, rs_data).groups()\n self.db.insertItem(self.info_item, self.patt_choice)\n\n #print info_item\n else:\n pass\n \n self.db.insertItems(self.time, self.db.Item_list)\n'''\ndef main() :\n idb = iDB()\n iparser = iParser(idb, 1)\n\n str = \"\"\"\nSat Jan 31 19:30:02 GMT 1970\nLoad: 13.26 / 13.47 / 11.88\nCPU usage from 116890ms to 56891ms ago with 99% awake:\n 0.2% 1023/system_server: 0.1% user + 0% kernel / faults: 35 minor\n 0.1% 336/atd: 0% user + 0.1% kernel\n 0.1% 1254/com.android.systemui: 0.1% user + 0% kernel / faults: 1 minor\n 0.1% 2238/mpdecision: 0% user + 0.1% kernel\n 0% 3/ksoftirqd/0: 0% user + 0% kernel\n 0% 383/kworker/0:3: 0% user + 0% kernel\n 0% 173/mmcqd/1: 0% user + 0% kernel\n 0% 563/kernel_logger: 0% user + 0% kernel\n 0% 320/thermal-engine: 0% user + 0% kernel\n 0% 550/logcat: 0% user + 0% kernel\n 0% 6669/kworker/u:5: 0% user + 0% kernel\n 0% 6715/adbd: 0% user + 0% kernel\n 0% 7/kworker/u:0H: 0% user + 0% kernel\n 0% 180/flush-179:0: 0% user + 0% kernel\n 0% 187/jbd2/mmcblk0p34: 0% user + 0% kernel\n 0% 234/charger_monitor: 0% user + 0% kernel\n 0% 1248/MC_Thread: 0% user + 0% kernel\n 0% 1419/wpa_supplicant: 0% user + 0% kernel\n 0% 2283/kworker/0:2H: 0% user + 0% kernel\n3.6% TOTAL: 1.3% user + 2.2% kernel + 0% iowait + 0% softirq\n\"\"\"\n iparser.parse(str)\n\n print idb.getAllItemList()\n\nmain()\n'''\n","sub_path":"iNotifier/iParser.py","file_name":"iParser.py","file_ext":"py","file_size_in_byte":4095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"28640140","text":"\"\"\"myDjango01 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom app01.views import index\nadmin.autodiscover()\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n\n url(r'^app01/uid(\\d+)name(\\w+)/$', 'app01.views.index'),\n url(r'^app01/(?P\\d{2})/$', index),\n url(r'^app01/regist/$', 'app01.views.regist'),\n \n url(r'^app02/regist/$', 'app02.views.regist'),\n url(r'^app02/login/$', 'app02.views.login'),\n url(r'^app02/index/$', 'app02.views.index'),\n \n url(r'^session/login/$', 'session.views.login'), \n url(r'^session/index/$', 'session.views.index'), \n url(r'^session/logout/$', 'session.views.logout'), \n]\n","sub_path":"src/myDjango01/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"166339520","text":"# Import libraries\nimport itertools\nimport networkx as nx\n\n# Create the graph containing all cluster valid points outside the cluster \n# boundary and the triangulation edges between them\ndef create_general_graph(cluster_to_expand):\n # Create the general graph\n general_graph = nx.Graph()\n ## Add to the graph all template vertices indices\n for index,keypoint in enumerate(cluster_to_expand['template_triangulation_points']):\n general_graph.add_node(index)\n ## Add to the graph all template triangulation segments\n for template_triangle in cluster_to_expand['template_triangulation']:\n for segment in itertools.combinations(template_triangle,2):\n general_graph.add_edge(segment[0],\n segment[1])\n \n # Remove from the general graph points belonging to the cluster that are not\n # on the boundary\n ## Collect cluster valid points indices\n valid_points_indices = []\n for cluster_triangle in cluster_to_expand['cluster']:\n template_triangle = cluster_to_expand['template_triangulation'][cluster_triangle['template_triangle_index']]\n for template_point_index in template_triangle:\n if template_point_index not in valid_points_indices:\n valid_points_indices.append(template_point_index)\n ## Collect cluster boundary valid points indices\n boundary_valid_points_indices = []\n for cluster_boundary_segment in cluster_to_expand['cluster_template_boundary']['segments']:\n for template_point_index in cluster_boundary_segment:\n if template_point_index not in boundary_valid_points_indices:\n boundary_valid_points_indices.append(template_point_index)\n ## Keep only points to be removed from the general graph.\n ## These are the ones belonging to the cluster excluded the boundary\n valid_points_to_remove_indices = []\n for valid_point_index in valid_points_indices:\n if valid_point_index not in boundary_valid_points_indices:\n valid_points_to_remove_indices.append(valid_point_index)\n ## Remove from the graph the cluster vertices and consequently all their edges\n for valid_point_to_remove_index in valid_points_to_remove_indices:\n general_graph.remove_node(valid_point_to_remove_index)\n \n return general_graph","sub_path":"2. Algorithm test/functions/clusters_expansion/functions/single_cluster_expansion/create_general_graph.py","file_name":"create_general_graph.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"432830065","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass UserProfile(models.Model):\n \"\"\"\n User profile model.\n\n Extends functionality of default django user model and adds some additional fields.\n\n \"\"\"\n\n user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')\n\n class Meta:\n verbose_name = 'User profile'\n\n\n def __str__(self):\n \"\"\"Get user string representation.\"\"\"\n return f'[ID={self.id}] User profile: {self.user}'\n\n\n","sub_path":"backend/user_profile/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"538614420","text":"import json\r\nimport logging\r\nimport re\r\nimport uuid\r\nfrom time import sleep\r\n\r\nimport tls_client\r\nimport undetected_chromedriver as uc\r\nfrom requests.exceptions import HTTPError\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\n\r\n# Disable all logging\r\nlogging.basicConfig(level=logging.ERROR)\r\n\r\nBASE_URL = \"https://chat.openai.com/\"\r\n\r\n\r\nclass Chrome(uc.Chrome):\r\n def __del__(self):\r\n self.quit()\r\n\r\n\r\nclass Chatbot:\r\n def __init__(\r\n self,\r\n config,\r\n conversation_id=None,\r\n parent_id=None,\r\n no_refresh=False,\r\n ) -> None:\r\n self.config = config\r\n self.session = tls_client.Session(\r\n client_identifier=\"chrome_108\",\r\n )\r\n if \"proxy\" in config:\r\n if type(config[\"proxy\"]) != str:\r\n raise Exception(\"Proxy must be a string!\")\r\n proxies = {\r\n \"http\": config[\"proxy\"],\r\n \"https\": config[\"proxy\"],\r\n }\r\n self.session.proxies.update(proxies)\r\n if \"verbose\" in config:\r\n if type(config[\"verbose\"]) != bool:\r\n raise Exception(\"Verbose must be a boolean!\")\r\n self.verbose = config[\"verbose\"]\r\n else:\r\n self.verbose = False\r\n self.conversation_id = conversation_id\r\n self.parent_id = parent_id\r\n self.conversation_mapping = {}\r\n self.conversation_id_prev_queue = []\r\n self.parent_id_prev_queue = []\r\n self.isMicrosoftLogin = False\r\n # stdout colors\r\n self.GREEN = \"\\033[92m\"\r\n self.WARNING = \"\\033[93m\"\r\n self.ENDCOLOR = \"\\033[0m\"\r\n if \"email\" in config and \"password\" in config:\r\n if type(config[\"email\"]) != str:\r\n raise Exception(\"Email must be a string!\")\r\n if type(config[\"password\"]) != str:\r\n raise Exception(\"Password must be a string!\")\r\n self.email = config[\"email\"]\r\n self.password = config[\"password\"]\r\n if \"isMicrosoftLogin\" in config and config[\"isMicrosoftLogin\"] == True:\r\n self.isMicrosoftLogin = True\r\n self.__microsoft_login()\r\n else:\r\n self.__email_login()\r\n elif \"session_token\" in config:\r\n if no_refresh:\r\n self.__get_cf_cookies()\r\n return\r\n if type(config[\"session_token\"]) != str:\r\n raise Exception(\"Session token must be a string!\")\r\n self.session_token = config[\"session_token\"]\r\n self.session.cookies.set(\r\n \"__Secure-next-auth.session-token\",\r\n config[\"session_token\"],\r\n )\r\n self.__get_cf_cookies()\r\n else:\r\n raise Exception(\"Invalid config!\")\r\n self.__retry_refresh()\r\n\r\n def __retry_refresh(self):\r\n retries = 5\r\n refresh = True\r\n while refresh:\r\n try:\r\n self.__refresh_session()\r\n refresh = False\r\n except Exception as exc:\r\n if retries == 0:\r\n raise exc\r\n retries -= 1\r\n\r\n def ask(\r\n self,\r\n prompt,\r\n conversation_id=None,\r\n parent_id=None,\r\n gen_title=False,\r\n session_token=None,\r\n ):\r\n \"\"\"\r\n Ask a question to the chatbot\r\n :param prompt: String\r\n :param conversation_id: UUID\r\n :param parent_id: UUID\r\n :param gen_title: Boolean\r\n :param session_token: String\r\n \"\"\"\r\n if session_token:\r\n self.session.cookies.set(\r\n \"__Secure-next-auth.session-token\",\r\n session_token,\r\n )\r\n self.session_token = session_token\r\n self.config[\"session_token\"] = session_token\r\n self.__retry_refresh()\r\n self.__map_conversations()\r\n if conversation_id == None:\r\n conversation_id = self.conversation_id\r\n if parent_id == None:\r\n parent_id = (\r\n self.parent_id\r\n if conversation_id == self.conversation_id\r\n else self.conversation_mapping[conversation_id]\r\n )\r\n data = {\r\n \"action\": \"next\",\r\n \"messages\": [\r\n {\r\n \"id\": str(uuid.uuid4()),\r\n \"role\": \"user\",\r\n \"content\": {\"content_type\": \"text\", \"parts\": [prompt]},\r\n },\r\n ],\r\n \"conversation_id\": conversation_id,\r\n \"parent_message_id\": parent_id or str(uuid.uuid4()),\r\n \"model\": \"text-davinci-002-render\"\r\n if self.config.get(\"paid\") is not True\r\n else \"text-davinci-002-render-paid\",\r\n }\r\n new_conv = data[\"conversation_id\"] is None\r\n self.conversation_id_prev_queue.append(\r\n data[\"conversation_id\"],\r\n ) # for rollback\r\n self.parent_id_prev_queue.append(data[\"parent_message_id\"])\r\n response = self.session.post(\r\n url=BASE_URL + \"backend-api/conversation\",\r\n data=json.dumps(data),\r\n timeout_seconds=180,\r\n )\r\n if response.status_code != 200:\r\n print(response.text)\r\n self.__refresh_session()\r\n raise HTTPError(\r\n f\"Wrong response code: {response.status_code}! Refreshing session...\",\r\n )\r\n else:\r\n try:\r\n response = response.text.splitlines()[-4]\r\n response = response[6:]\r\n except Exception as exc:\r\n print(\"Incorrect response from OpenAI API\")\r\n raise Exception(\"Incorrect response from OpenAI API\") from exc\r\n # Check if it is JSON\r\n if response.startswith(\"{\"):\r\n response = json.loads(response)\r\n self.parent_id = response[\"message\"][\"id\"]\r\n self.conversation_id = response[\"conversation_id\"]\r\n message = response[\"message\"][\"content\"][\"parts\"][0]\r\n res = {\r\n \"message\": message,\r\n \"conversation_id\": self.conversation_id,\r\n \"parent_id\": self.parent_id,\r\n }\r\n if gen_title and new_conv:\r\n try:\r\n title = self.__gen_title(\r\n self.conversation_id,\r\n self.parent_id,\r\n )[\"title\"]\r\n except Exception as exc:\r\n split = prompt.split(\" \")\r\n title = \" \".join(split[:3]) + (\"...\" if len(split) > 3 else \"\")\r\n res[\"title\"] = title\r\n return res\r\n else:\r\n return None\r\n\r\n def __check_response(self, response):\r\n if response.status_code != 200:\r\n print(response.text)\r\n raise Exception(\"Response code error: \", response.status_code)\r\n\r\n def get_conversations(self, offset=0, limit=20):\r\n \"\"\"\r\n Get conversations\r\n :param offset: Integer\r\n :param limit: Integer\r\n \"\"\"\r\n url = BASE_URL + f\"backend-api/conversations?offset={offset}&limit={limit}\"\r\n response = self.session.get(url)\r\n self.__check_response(response)\r\n data = json.loads(response.text)\r\n return data[\"items\"]\r\n\r\n def get_msg_history(self, id):\r\n \"\"\"\r\n Get message history\r\n :param id: UUID of conversation\r\n \"\"\"\r\n url = BASE_URL + f\"backend-api/conversation/{id}\"\r\n response = self.session.get(url)\r\n self.__check_response(response)\r\n data = json.loads(response.text)\r\n return data\r\n\r\n def __gen_title(self, id, message_id):\r\n \"\"\"\r\n Generate title for conversation\r\n \"\"\"\r\n url = BASE_URL + f\"backend-api/conversation/gen_title/{id}\"\r\n response = self.session.post(\r\n url,\r\n data=json.dumps(\r\n {\r\n \"message_id\": message_id,\r\n \"model\": \"text-davinci-002-render\"\r\n if self.config.get(\"paid\") is not True\r\n else \"text-davinci-002-render-paid\",\r\n },\r\n ),\r\n )\r\n self.__check_response(response)\r\n data = json.loads(response.text)\r\n return data\r\n\r\n def change_title(self, id, title):\r\n \"\"\"\r\n Change title of conversation\r\n :param id: UUID of conversation\r\n :param title: String\r\n \"\"\"\r\n url = BASE_URL + f\"backend-api/conversation/{id}\"\r\n response = self.session.patch(url, data=f'{{\"title\": \"{title}\"}}')\r\n self.__check_response(response)\r\n\r\n def delete_conversation(self, id):\r\n \"\"\"\r\n Delete conversation\r\n :param id: UUID of conversation\r\n \"\"\"\r\n url = BASE_URL + f\"backend-api/conversation/{id}\"\r\n response = self.session.patch(url, data='{\"is_visible\": false}')\r\n self.__check_response(response)\r\n\r\n def clear_conversations(self):\r\n \"\"\"\r\n Delete all conversations\r\n \"\"\"\r\n url = BASE_URL + \"backend-api/conversations\"\r\n response = self.session.patch(url, data='{\"is_visible\": false}')\r\n self.__check_response(response)\r\n\r\n def __map_conversations(self):\r\n conversations = self.get_conversations()\r\n histories = [self.get_msg_history(x[\"id\"]) for x in conversations]\r\n for x, y in zip(conversations, histories):\r\n self.conversation_mapping[x[\"id\"]] = y[\"current_node\"]\r\n\r\n def __refresh_session(self, session_token=None):\r\n if session_token:\r\n self.session.cookies.set(\r\n \"__Secure-next-auth.session-token\",\r\n session_token,\r\n )\r\n self.session_token = session_token\r\n self.config[\"session_token\"] = session_token\r\n url = BASE_URL + \"api/auth/session\"\r\n response = self.session.get(url, timeout_seconds=180)\r\n print(response)\r\n if response.status_code == 403:\r\n self.__get_cf_cookies()\r\n raise Exception(\"Clearance refreshing...\")\r\n try:\r\n if \"error\" in response.json():\r\n raise Exception(\r\n f\"Failed to refresh session! Error: {response.json()['error']}\",\r\n )\r\n elif (\r\n response.status_code != 200\r\n or response.json() == {}\r\n or \"accessToken\" not in response.json()\r\n ):\r\n raise Exception(\r\n f\"Response code: {response.status_code} \\n Response: {response.text}\",\r\n )\r\n else:\r\n self.session.headers.update(\r\n {\r\n \"Authorization\": \"Bearer \" + response.json()[\"accessToken\"],\r\n },\r\n )\r\n self.session_token = self.session.cookies._find(\r\n \"__Secure-next-auth.session-token\",\r\n )\r\n except Exception:\r\n print(\"Failed to refresh session!\")\r\n if self.isMicrosoftLogin:\r\n print(\"Attempting to re-authenticate...\")\r\n self.__microsoft_login()\r\n else:\r\n self.__email_login()\r\n\r\n def reset_chat(self) -> None:\r\n \"\"\"\r\n Reset the conversation ID and parent ID.\r\n\r\n :return: None\r\n \"\"\"\r\n self.conversation_id = None\r\n self.parent_id = str(uuid.uuid4())\r\n\r\n def __microsoft_login(self) -> None:\r\n \"\"\"\r\n Login to OpenAI via Microsoft Login Authentication.\r\n\r\n :return: None\r\n \"\"\"\r\n driver = None\r\n try:\r\n # Open the browser\r\n self.cf_cookie_found = False\r\n self.puid_cookie_found = False\r\n self.session_cookie_found = False\r\n self.agent_found = False\r\n self.cf_clearance = None\r\n self.puid_cookie = None\r\n self.user_agent = None\r\n options = self.__get_ChromeOptions()\r\n print(\"Spawning browser...\")\r\n driver = uc.Chrome(\r\n enable_cdp_events=True,\r\n options=options,\r\n driver_executable_path=self.config.get(\"driver_exec_path\"),\r\n browser_executable_path=self.config.get(\"browser_exec_path\"),\r\n )\r\n print(\"Browser spawned.\")\r\n driver.add_cdp_listener(\r\n \"Network.responseReceivedExtraInfo\",\r\n lambda msg: self.__detect_cookies(msg),\r\n )\r\n driver.add_cdp_listener(\r\n \"Network.requestWillBeSentExtraInfo\",\r\n lambda msg: self.__detect_user_agent(msg),\r\n )\r\n driver.get(BASE_URL)\r\n while not self.agent_found or not self.cf_cookie_found:\r\n sleep(5)\r\n self.__refresh_headers(\r\n cf_clearance=self.cf_clearance,\r\n user_agent=self.user_agent,\r\n )\r\n # Wait for the login button to appear\r\n WebDriverWait(driver, 120).until(\r\n EC.element_to_be_clickable(\r\n (By.XPATH, \"//button[contains(text(), 'Log in')]\"),\r\n ),\r\n )\r\n # Click the login button\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//button[contains(text(), 'Log in')]\",\r\n ).click()\r\n # Wait for the Login with Microsoft button to be clickable\r\n WebDriverWait(driver, 60).until(\r\n EC.element_to_be_clickable(\r\n (By.XPATH, \"//button[@data-provider='windowslive']\"),\r\n ),\r\n )\r\n # Click the Login with Microsoft button\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//button[@data-provider='windowslive']\",\r\n ).click()\r\n # Wait for the email input field to appear\r\n WebDriverWait(driver, 60).until(\r\n EC.visibility_of_element_located(\r\n (By.XPATH, \"//input[@type='email']\"),\r\n ),\r\n )\r\n # Enter the email\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//input[@type='email']\",\r\n ).send_keys(self.config[\"email\"])\r\n # Wait for the Next button to be clickable\r\n WebDriverWait(driver, 60).until(\r\n EC.element_to_be_clickable(\r\n (By.XPATH, \"//input[@type='submit']\"),\r\n ),\r\n )\r\n # Click the Next button\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//input[@type='submit']\",\r\n ).click()\r\n # Wait for the password input field to appear\r\n WebDriverWait(driver, 60).until(\r\n EC.visibility_of_element_located(\r\n (By.XPATH, \"//input[@type='password']\"),\r\n ),\r\n )\r\n # Enter the password\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//input[@type='password']\",\r\n ).send_keys(self.config[\"password\"])\r\n # Wait for the Sign in button to be clickable\r\n WebDriverWait(driver, 60).until(\r\n EC.element_to_be_clickable(\r\n (By.XPATH, \"//input[@type='submit']\"),\r\n ),\r\n )\r\n # Click the Sign in button\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//input[@type='submit']\",\r\n ).click()\r\n # Wait for the Allow button to appear\r\n WebDriverWait(driver, 60).until(\r\n EC.element_to_be_clickable(\r\n (By.XPATH, \"//input[@type='submit']\"),\r\n ),\r\n )\r\n # click Yes button\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//input[@type='submit']\",\r\n ).click()\r\n # wait for input box to appear (to make sure we're signed in)\r\n WebDriverWait(driver, 60).until(\r\n EC.visibility_of_element_located(\r\n (By.XPATH, \"//textarea\"),\r\n ),\r\n )\r\n while not self.session_cookie_found:\r\n sleep(5)\r\n print(self.GREEN + \"Login successful.\" + self.ENDCOLOR)\r\n finally:\r\n # Close the browser\r\n if driver is not None:\r\n driver.quit()\r\n del driver\r\n\r\n def __email_login(self) -> None:\r\n \"\"\"\r\n Login to OpenAI via Email/Password Authentication and 2Captcha.\r\n\r\n :return: None\r\n \"\"\"\r\n # Open the browser\r\n driver = None\r\n try:\r\n self.cf_cookie_found = False\r\n self.puid_cookie_found = False\r\n self.session_cookie_found = False\r\n self.agent_found = False\r\n self.cf_clearance = None\r\n self.puid_cookie = None\r\n self.user_agent = None\r\n options = self.__get_ChromeOptions()\r\n print(\"Spawning browser...\")\r\n driver = uc.Chrome(\r\n enable_cdp_events=True,\r\n options=options,\r\n driver_executable_path=self.config.get(\"driver_exec_path\"),\r\n browser_executable_path=self.config.get(\"browser_exec_path\"),\r\n )\r\n print(\"Browser spawned.\")\r\n driver.add_cdp_listener(\r\n \"Network.responseReceivedExtraInfo\",\r\n lambda msg: self.__detect_cookies(msg),\r\n )\r\n driver.add_cdp_listener(\r\n \"Network.requestWillBeSentExtraInfo\",\r\n lambda msg: self.__detect_user_agent(msg),\r\n )\r\n driver.get(BASE_URL)\r\n while not self.agent_found or not self.cf_cookie_found:\r\n sleep(5)\r\n self.__refresh_headers(\r\n cf_clearance=self.cf_clearance,\r\n user_agent=self.user_agent,\r\n )\r\n # Wait for the login button to appear\r\n WebDriverWait(driver, 120).until(\r\n EC.element_to_be_clickable(\r\n (By.XPATH, \"//button[contains(text(), 'Log in')]\"),\r\n ),\r\n )\r\n print(\"log in can click\")\r\n # Click the login button\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//button[contains(text(), 'Log in')]\",\r\n ).click()\r\n # Wait for the email input field to appear\r\n WebDriverWait(driver, 60).until(\r\n EC.visibility_of_element_located(\r\n (By.ID, \"username\"),\r\n ),\r\n )\r\n # Enter the email\r\n driver.find_element(by=By.ID, value=\"username\").send_keys(\r\n self.config[\"email\"],\r\n )\r\n # Wait for the Continue button to be clickable\r\n WebDriverWait(driver, 60).until(\r\n EC.element_to_be_clickable(\r\n (By.XPATH, \"//button[@type='submit']\"),\r\n ),\r\n )\r\n # Click the Continue button\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//button[@type='submit']\",\r\n ).click()\r\n # Wait for the password input field to appear\r\n WebDriverWait(driver, 60).until(\r\n EC.visibility_of_element_located(\r\n (By.ID, \"password\"),\r\n ),\r\n )\r\n # Enter the password\r\n driver.find_element(by=By.ID, value=\"password\").send_keys(\r\n self.config[\"password\"],\r\n )\r\n # Wait for the Sign in button to be clickable\r\n WebDriverWait(driver, 60).until(\r\n EC.element_to_be_clickable(\r\n (By.XPATH, \"//button[@type='submit']\"),\r\n ),\r\n )\r\n # Click the Sign in button\r\n driver.find_element(\r\n by=By.XPATH,\r\n value=\"//button[@type='submit']\",\r\n ).click()\r\n # wait for input box to appear (to make sure we're signed in)\r\n WebDriverWait(driver, 60).until(\r\n EC.visibility_of_element_located(\r\n (By.XPATH, \"//textarea\"),\r\n ),\r\n )\r\n while not self.session_cookie_found:\r\n sleep(5)\r\n print(self.GREEN + \"Login successful.\" + self.ENDCOLOR)\r\n finally:\r\n if driver is not None:\r\n # Close the browser\r\n driver.quit()\r\n del driver\r\n\r\n def __get_ChromeOptions(self):\r\n options = uc.ChromeOptions()\r\n options.add_argument(\"--start_maximized\")\r\n options.add_argument(\"--disable-extensions\")\r\n options.add_argument(\"--disable-application-cache\")\r\n options.add_argument(\"--disable-gpu\")\r\n options.add_argument(\"--no-sandbox\")\r\n options.add_argument(\"--disable-setuid-sandbox\")\r\n options.add_argument(\"--disable-dev-shm-usage\")\r\n \r\n if self.config.get(\"proxy\", \"\") != \"\":\r\n options.add_argument(\"--proxy-server=\" + self.config[\"proxy\"])\r\n return options\r\n\r\n def __get_cf_cookies(self) -> None:\r\n \"\"\"\r\n Get cloudflare cookies.\r\n\r\n :return: None\r\n \"\"\"\r\n driver = None\r\n try:\r\n self.cf_cookie_found = False\r\n self.agent_found = False\r\n self.puid_cookie_found = False\r\n self.cf_clearance = None\r\n self.puid_cookie = None\r\n self.user_agent = None\r\n options = self.__get_ChromeOptions()\r\n print(\"Spawning browser...\")\r\n driver = uc.Chrome(\r\n enable_cdp_events=True,\r\n options=options,\r\n driver_executable_path=self.config.get(\"driver_exec_path\"),\r\n browser_executable_path=self.config.get(\"browser_exec_path\"),\r\n )\r\n print(driver)\r\n print(\"Browser spawned.\")\r\n driver.add_cdp_listener(\r\n \"Network.responseReceivedExtraInfo\",\r\n lambda msg: self.__detect_cookies(msg),\r\n )\r\n driver.add_cdp_listener(\r\n \"Network.requestWillBeSentExtraInfo\",\r\n lambda msg: self.__detect_user_agent(msg),\r\n )\r\n driver.get(\"https://chat.openai.com/chat\")\r\n print(\"driver.get finish.\")\r\n print(driver.page_source)\r\n while (\r\n not self.agent_found\r\n or not self.cf_cookie_found\r\n or not self.puid_cookie_found\r\n ):\r\n print(driver.page_source)\r\n print(\"sleep.\")\r\n sleep(5)\r\n finally:\r\n # Close the browser\r\n if driver is not None:\r\n driver.quit()\r\n del driver\r\n self.__refresh_headers(\r\n cf_clearance=self.cf_clearance,\r\n user_agent=self.user_agent,\r\n )\r\n\r\n def __detect_cookies(self, message):\r\n print(messages)\r\n if \"params\" in message:\r\n if \"headers\" in message[\"params\"]:\r\n if \"set-cookie\" in message[\"params\"][\"headers\"]:\r\n # Use regex to get the cookie for cf_clearance=*;\r\n cf_clearance_cookie = re.search(\r\n \"cf_clearance=.*?;\",\r\n message[\"params\"][\"headers\"][\"set-cookie\"],\r\n )\r\n # puid_cookie = re.search(\r\n # \"_puid=.*?;\",\r\n # message[\"params\"][\"headers\"][\"set-cookie\"],\r\n # )\r\n session_cookie = re.search(\r\n \"__Secure-next-auth.session-token=.*?;\",\r\n message[\"params\"][\"headers\"][\"set-cookie\"],\r\n )\r\n if cf_clearance_cookie and not self.cf_cookie_found:\r\n print(\"Found Cloudflare Cookie!\")\r\n # remove the semicolon and 'cf_clearance=' from the string\r\n raw_cf_cookie = cf_clearance_cookie.group(0)\r\n self.cf_clearance = raw_cf_cookie.split(\"=\")[1][:-1]\r\n if self.verbose:\r\n print(\r\n self.GREEN\r\n + \"Cloudflare Cookie: \"\r\n + self.ENDCOLOR\r\n + self.cf_clearance,\r\n )\r\n self.cf_cookie_found = True\r\n # if puid_cookie and not self.puid_cookie_found:\r\n # raw_puid_cookie = puid_cookie.group(0)\r\n # self.puid_cookie = raw_puid_cookie.split(\"=\")[1][:-1]\r\n # self.session.cookies.set(\r\n # \"_puid\",\r\n # self.puid_cookie,\r\n # )\r\n # if self.verbose:\r\n # print(\r\n # self.GREEN\r\n # + \"puid Cookie: \"\r\n # + self.ENDCOLOR\r\n # + self.puid_cookie,\r\n # )\r\n # self.puid_cookie_found = True\r\n if session_cookie and not self.session_cookie_found:\r\n print(\"Found Session Token!\")\r\n # remove the semicolon and '__Secure-next-auth.session-token=' from the string\r\n raw_session_cookie = session_cookie.group(0)\r\n self.session_token = raw_session_cookie.split(\"=\")[1][:-1]\r\n self.session.cookies.set(\r\n \"__Secure-next-auth.session-token\",\r\n self.session_token,\r\n )\r\n if self.verbose:\r\n print(\r\n self.GREEN\r\n + \"Session Token: \"\r\n + self.ENDCOLOR\r\n + self.session_token,\r\n )\r\n self.session_cookie_found = True\r\n\r\n def __detect_user_agent(self, message):\r\n if \"params\" in message:\r\n if \"headers\" in message[\"params\"]:\r\n if \"user-agent\" in message[\"params\"][\"headers\"]:\r\n # Use regex to get the cookie for cf_clearance=*;\r\n user_agent = message[\"params\"][\"headers\"][\"user-agent\"]\r\n self.user_agent = user_agent\r\n self.agent_found = True\r\n self.__refresh_headers(\r\n cf_clearance=self.cf_clearance,\r\n user_agent=self.user_agent,\r\n )\r\n\r\n def __refresh_headers(self, cf_clearance, user_agent):\r\n del self.session.cookies[\"cf_clearance\"]\r\n # del self.session.cookies[\"_puid\"]\r\n self.session.headers.clear()\r\n self.session.cookies.set(\"cf_clearance\", cf_clearance)\r\n # self.session.cookies.set(\"_puid\", puid_cookie)\r\n self.session.headers.update(\r\n {\r\n \"Accept\": \"text/event-stream\",\r\n \"Authorization\": \"Bearer \",\r\n \"Content-Type\": \"application/json\",\r\n \"User-Agent\": user_agent,\r\n \"X-Openai-Assistant-App-Id\": \"\",\r\n \"Connection\": \"close\",\r\n \"Accept-Language\": \"en-US,en;q=0.9\",\r\n \"Referer\": \"https://chat.openai.com/chat\",\r\n },\r\n )\r\n\r\n def rollback_conversation(self, num=1) -> None:\r\n \"\"\"\r\n Rollback the conversation.\r\n :param num: The number of messages to rollback\r\n :return: None\r\n \"\"\"\r\n for i in range(num):\r\n self.conversation_id = self.conversation_id_prev_queue.pop()\r\n self.parent_id = self.parent_id_prev_queue.pop()\r\n\r\n\r\ndef get_input(prompt):\r\n # Display the prompt\r\n print(prompt, end=\"\")\r\n\r\n # Initialize an empty list to store the input lines\r\n lines = []\r\n\r\n # Read lines of input until the user enters an empty line\r\n while True:\r\n line = input()\r\n if line == \"\":\r\n break\r\n lines.append(line)\r\n\r\n # Join the lines, separated by newlines, and store the result\r\n user_input = \"\\n\".join(lines)\r\n\r\n # Return the input\r\n return user_input\r\n\r\n\r\nfrom os import getenv\r\nfrom os.path import exists\r\n\r\n\r\ndef configure():\r\n config_files = [\"config.json\"]\r\n xdg_config_home = getenv(\"XDG_CONFIG_HOME\")\r\n if xdg_config_home:\r\n config_files.append(f\"{xdg_config_home}/revChatGPT/config.json\")\r\n user_home = getenv(\"HOME\")\r\n if user_home:\r\n config_files.append(f\"{user_home}/.config/revChatGPT/config.json\")\r\n config_files.append(f\"D:/test/ChatGPT-main/src/config.json\")\r\n\r\n config_file = next((f for f in config_files if exists(f)), None)\r\n if config_file:\r\n with open(config_file, encoding=\"utf-8\") as f:\r\n config = json.load(f)\r\n else:\r\n print(\"No config file found.\")\r\n raise Exception(\"No config file found.\")\r\n return config\r\n\r\n\r\ndef chatGPT_main(config):\r\n print(\"Logging in...\")\r\n chatbot = Chatbot(config)\r\n while True:\r\n prompt = get_input(\"\\nYou:\\n\")\r\n if prompt.startswith(\"!\"):\r\n if prompt == \"!help\":\r\n print(\r\n \"\"\"\r\n !help - Show this message\r\n !reset - Forget the current conversation\r\n !refresh - Refresh the session authentication\r\n !config - Show the current configuration\r\n !rollback x - Rollback the conversation (x being the number of messages to rollback)\r\n !exit - Exit this program\r\n \"\"\",\r\n )\r\n continue\r\n elif prompt == \"!reset\":\r\n chatbot.reset_chat()\r\n print(\"Chat session successfully reset.\")\r\n continue\r\n elif prompt == \"!refresh\":\r\n chatbot.__refresh_session()\r\n print(\"Session successfully refreshed.\\n\")\r\n continue\r\n elif prompt == \"!config\":\r\n print(json.dumps(chatbot.config, indent=4))\r\n continue\r\n elif prompt.startswith(\"!rollback\"):\r\n # Default to 1 rollback if no number is specified\r\n try:\r\n rollback = int(prompt.split(\" \")[1])\r\n except IndexError:\r\n rollback = 1\r\n chatbot.rollback_conversation(rollback)\r\n print(f\"Rolled back {rollback} messages.\")\r\n continue\r\n elif prompt.startswith(\"!setconversation\"):\r\n try:\r\n chatbot.config[\"conversation\"] = prompt.split(\" \")[1]\r\n print(\"Conversation has been changed\")\r\n except IndexError:\r\n print(\"Please include conversation UUID in command\")\r\n continue\r\n elif prompt == \"!exit\":\r\n break\r\n try:\r\n print(\"Chatbot: \")\r\n message = chatbot.ask(\r\n prompt,\r\n conversation_id=chatbot.config.get(\"conversation\"),\r\n parent_id=chatbot.config.get(\"parent_id\"),\r\n )\r\n print(message[\"message\"])\r\n except Exception as exc:\r\n print(\"Something went wrong!\")\r\n print(exc)\r\n continue\r\n\r\n\r\ndef main():\r\n print(\r\n \"\"\"\r\n ChatGPT - A command-line interface to OpenAI's ChatGPT (https://chat.openai.com/chat)\r\n Repo: github.com/acheong08/ChatGPT\r\n \"\"\",\r\n )\r\n print(\"Type '!help' to show a full list of commands\")\r\n print(\"Press enter twice to submit your question.\\n\")\r\n chatGPT_main(configure())\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":32582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"526031330","text":"# Given an integer columnNumber, return its corresponding column title as\n# it appears in an Excel sheet.\n\n# For example:\n# A -> 1\n# B -> 2\n# C -> 3\n# ...\n# Z -> 26\n# AA -> 27\n# AB -> 28\n# ...\n\n# Example 1:\n# Input: columnNumber = 1\n# Output: \"A\"\n\n# Example 2:\n# Input: columnNumber = 28\n# Output: \"AB\"\n\n# Example 3:\n# Input: columnNumber = 701\n# Output: \"ZY\"\n\nclass Solution:\n def convertToTitle(self, columnNumber: int) -> str:\n result = []\n while columnNumber > 0:\n columnNumber -= 1\n result.append(chr(columnNumber % 26 + ord('A')))\n columnNumber //= 26\n return \"\".join(reversed(result))\n","sub_path":"python/leetcode/easy/ex0101_0200/ex0168.py","file_name":"ex0168.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"433923872","text":"import sys, re\n\ndef sortexp2(exp):\n parts = []\n part = \"*\"\n bracket = False\n for i in exp:\n if bracket:\n if i == \")\":\n bracket = False\n part = part + i\n else:\n if i == '(':\n bracket = True\n part = part + i\n elif i == '*' or i == '/':\n parts.append(part)\n part = i\n else:\n part = part + i\n parts.append(part)\n for i in range(len(parts)):\n i2 = parts[i]\n if i2.find('(') != -1:\n parts[i] = i2[:2] + sortexp1(i2[2:-1]) + ')'\n elif i2 == '/1':\n parts[i] = '*1'\n parts.sort()\n parts[0] = parts[0][1:]\n return \"\".join(parts)\n\n\ndef sortexp1(exp):\n parts = []\n part = \"+\"\n bracket = False\n for i in exp:\n if bracket:\n if i == \")\":\n bracket = False\n part = part + i\n else:\n if i == '(':\n bracket = True\n part = part + i\n elif i == '+' or i == '-':\n parts.append(part)\n part = i\n else:\n part = part + i\n parts.append(part)\n for i in range(len(parts)):\n i2 = parts[i]\n if i2.find('*') != -1 or i2.find('/') != -1:\n parts[i] = i2[:1] + sortexp2(i2[1:])\n parts.sort()\n parts[0] = parts[0][1:]\n return \"\".join(parts)\n\ndef prepare(numstr, lowpri=[False, False, False, False]):\n global calclist\n if len(numstr) == 1:\n calclist.append(numstr[0])\n else:\n numlen = len(numstr)\n for i in range(numlen - 1):\n for j in range(i + 1, numlen):\n numstr2 = numstr[:i] + numstr[i + 1:j] + numstr[j + 1:]\n lowpri2 = lowpri[:i] + lowpri[i + 1:j] + lowpri[j + 1:]\n ni = numstr[i]\n nj = numstr[j]\n prepare(numstr2 + [ni + \"+\" + nj], lowpri2 + [True])\n prepare(numstr2 + [ni + \"-\" + nj], lowpri2 + [True])\n prepare(numstr2 + [nj + \"-\" + ni], lowpri2 + [True])\n if lowpri[i]: ni = \"(\" + ni + \")\"\n if lowpri[j]: nj = \"(\" + nj + \")\"\n prepare(numstr2 + [ni + \"*\" + nj], lowpri2 + [False])\n prepare(numstr2 + [ni + \"/\" + nj], lowpri2 + [False])\n prepare(numstr2 + [nj + \"/\" + ni], lowpri2 + [False])\n\n\ndef test(a, b, c, d):\n global calclist2\n for i in calclist2:\n try:\n if eval(i) == 24:\n return True\n except ZeroDivisionError:\n pass\n return False\n\n\ncalclist = []\nprepare(['a', 'b', 'c', 'd'])\nuniq = set()\nfor i in calclist:\n uniq.add(sortexp1(i))\ncalclist2 = list(uniq)\n\nwhile True:\n cin = input(\"input 4 number:\")\n cins = cin.split(' ')\n num = []\n for i in cins:\n if i.isdigit():\n num.append(float(i))\n\n if len(num) != 4:\n print(\"need 4 numbers\")\n sys.exit()\n a, b, c, d = num\n\n result = []\n for i in calclist2:\n try:\n if eval(i) == 24:\n r = i.replace('a', str(int(a))).replace('b', str(int(b))).replace('c', str(int(c))).replace('d', str(int(d)))\n result.append(sortexp1(r))\n except ZeroDivisionError:\n pass\n\n result = list(set(result))\n result.sort()\n\n for i in result:\n print(i)","sub_path":"p24.py","file_name":"p24.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"237285923","text":"from setuptools import setup\r\nfrom setuptools import find_packages\r\n\r\ninstall_requires = ['gplue', 'pymongo', 'falcon', 'waitress']\r\n\r\nsetup(\r\n name='gplue_serving',\r\n version='0.0.1',\r\n description='Deploy gplue graphs as REST Service',\r\n author='Fariz Rahman',\r\n author_email='fariz@datalog.ai',\r\n url='https://github.com/farizrahman4u/gplue-serve',\r\n license='GNU GPL v2',\r\n install_requires=install_requires,\r\n packages=find_packages(),\r\n include_package_data=True\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"345973363","text":"# .csv\n\ndados = []\n\nnome = input('Digite seu nome:')\nsobrenome = input('Digite seu sobrenome:')\nemail = nome.lower()+'.'+sobrenome.lower()+'@email.com'\n\n# adicionando items em lista (append)\ndados.append(nome)\ndados.append(sobrenome)\ndados.append(email)\n\n# check\n#print(dados)\n\n\narq = open('pessoas.csv', 'a')\nfor x in dados:\n arq.write(x + ',')\narq.write('\\n')\n\narq.close()\n","sub_path":"Cap16_Arquivos/script14.py","file_name":"script14.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"329683801","text":"import factoryStation\nimport operations.sendATCommand\n\nfrom operations.operationResult import opResultUnexpected\n\n\nclass modemFusing(operations.sendATCommand.sendATCommand):\n '''Modem Fusing'''\n \n def __init__(self, factoryStation, options=None):\n self.name = 'modemFusing'\n self.description = modemFusing.__doc__\n super(modemFusing,self).__init__(factoryStation, options)\n\n def do(self):\n if not hasattr(self.factoryStation,'fuseImage'): \n self.printToLog('WARNING: Fuse image not provided', 0)\n return opResultUnexpected()\n else:\n self.ATcmd = 'AT%IFUSEIMAGE=' + self.factoryStation.fuseImage\n return super(modemFusing,self).do()\n\n# ------------------------------------------------- \n# Testing \n# -------------------------------------------------\nif __name__ == \"__main__\":\n\n testMode = True\n fs = factoryStation.factoryStation(None , testMode) # default factoryStation object\n fs.fuseImage = '0x0,0x0,0x0,0x0,0x4,0x0,0x0'\n \n fo = modemFusing( fs, {'ATtool' : 'atcmd-itf' } )\n \n fo.postResult( fo.do() )\n \n","sub_path":"ManuFacturingLine/operations/modemFusing.py","file_name":"modemFusing.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"501524002","text":"from scene import *\nimport photos, Image, ImageDraw, evolver, math\n\nw = 254\nh = 254\nopacity = 125\n\ncontrols = [[0,w],[0,h],[0,w/4],[0,h/4],[0,255],[0,255],[0,255]]\npopulation = 40\nparents = 20\nmrate = 0.05\nfigures = 300\n\nmoments = photos.get_albums()\nasset = photos.pick_asset(moments[4], title='Pick your image', multi=False)\nimg = asset.get_image()\nimg = img.convert('RGB')\n\n#scale photo to fit half the screen\nwidth = img.size[0]\nheight = img.size[1]\nwidthratio = width/(w)\nheightratio = height/h\nif widthratio > heightratio:\n\tscale = widthratio\nelse:\n\tscale = heightratio\nif scale != 1:\n\twidth = int(width/scale)\n\theight = int(height/scale)\n\timg = img.resize((width, height))\nimg.show()\n\nimgw = img.size[0]\nimgh = img.size[1]\npainting = Image.new(\"RGB\", (imgw, imgh), 'white')\n\n# fitness function\ndef fitfunc(dude):\n\t#will draw all objects and calculate distance for every pixel\t\n\t# every figure has 4 numeric params, and 3 rgb params \n\tdrawer = ImageDraw.Draw(painting, 'RGBA')\n\tdrawer.rectangle([0,0,w,h],(255,255,255,255))\n\tfor f in dude:\n\t\tdrawer.ellipse([f[0],f[1],f[0]+f[2],f[1]+f[3]],(int(f[4]), int(f[5]), int(f[6]), opacity))\n\t# calculate error\n\terr = 0\n\tfor i in range(img.size[0]):\n\t\tfor j in range(img.size[1]):\n\t\t\tr, g, b = img.getpixel((i, j))\t\n\t\t\trp, gp, bp = painting.getpixel((i,j))\n\t\t\terr = err + math.sqrt( (r-rp)**2 + (g-gp)**2 + (b-bp)**2 )\n\treturn err\n\t\n\ndef makepic(dude):\n\tdrawer = ImageDraw.Draw(painting, 'RGBA')\n\tdrawer.rectangle([0,0,w,h],(255,255,255))\n\tfor f in dude:\n\t\tdrawer.ellipse([f[0],f[1],f[0]+f[2],f[1]+f[3]],(int(f[4]), int(f[5]), int(f[6]), opacity))\n\tpainting.show()\n\tfilename = \"my_drawing.jpg\"\n\tpainting.save(filename)\n\t\n\t\t\nev = evolver.Evolver(population, parents, mrate, controls, figures)\nfor i in range(10000):\n\tev.evolve(fitfunc)\n\tmakepic(ev.fittest[-1])\n\n\n\n\t\n\t\t\n\t\t\t\t\t\t\t\t\t\t\n\n","sub_path":"evolvedrawer.py","file_name":"evolvedrawer.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"327010493","text":"\n\nfunders: {sender: address, value: wei_value}[num]\nnextFunderIndex: num\nbeneficiary: address\ndeadline: timestamp\ngoal: wei_value\nrefundIndex: num\ntimelimit: timedelta\n\n@public\ndef __init__(_beneficiary: address, _goal: wei_value, _timelimit: timedelta):\n self.beneficiary = _beneficiary\n self.deadline = block.timestamp + _timelimit\n self.timelimit = _timelimit\n self.goal = _goal\n\n@public\n@payable\ndef participate():\n assert block.timestamp < self.deadline\n nfi = self.nextFunderIndex\n self.funders[nfi] = {sender: msg.sender, value: msg.value}\n self.nextFunderIndex = nfi + 1\n\n@public\n@constant\ndef expired() -> bool:\n return block.timestamp >= self.deadline\n\n@public\n@constant\ndef timestamp() -> timestamp:\n return block.timestamp\n\n@public\n@constant\ndef deadline() -> timestamp:\n return self.deadline\n\n@public\n@constant\ndef timelimit() -> timedelta:\n return self.timelimit\n\n@public\n@constant\ndef reached() -> bool:\n return self.balance >= self.goal\n\n@public\ndef finalize():\n assert block.timestamp >= self.deadline and self.balance >= self.goal\n selfdestruct(self.beneficiary)\n\n@public\ndef refund():\n ind = self.refundIndex\n for i in range(ind, ind + 30):\n if i >= self.nextFunderIndex:\n self.refundIndex = self.nextFunderIndex\n return\n send(self.funders[i].sender, self.funders[i].value)\n self.funders[i] = None\n self.refundIndex = ind + 30\n\n ","sub_path":"tests/vyper/tests/parser/integration/test_crowdfund/fe4ec764-dbd8-44df-b10a-d5bc8f1d4d63.v.py","file_name":"fe4ec764-dbd8-44df-b10a-d5bc8f1d4d63.v.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"202724210","text":"from graphql_jwt.decorators import login_required\n\nfrom ...order import models\nfrom ..utils import filter_by_query_param, get_node\nfrom .types import Order\n\nORDER_SEARCH_FIELDS = (\n 'id', 'discount_name', 'token', 'user_email', 'user__email')\n\n\n@login_required\ndef resolve_orders(info, query):\n user = info.context.user\n queryset = user.orders.confirmed().distinct()\n if user.get_all_permissions() & {'order.view_order', 'order.edit_order'}:\n queryset = models.Order.objects.all().distinct()\n queryset = filter_by_query_param(queryset, query, ORDER_SEARCH_FIELDS)\n return queryset.prefetch_related('lines')\n\n\n@login_required\ndef resolve_order(info, id):\n \"\"\"Return order only for user assigned to it or proper staff user.\"\"\"\n order = get_node(info, id, only_type=Order)\n user = info.context.user\n if (order.user == user or user.get_all_permissions() & {\n 'order.view_order', 'order.edit_order'}):\n return order\n","sub_path":"saleor/graphql/order/resolvers.py","file_name":"resolvers.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"225243401","text":"# Created by Eugene M. Izhikevich, February 25, 2003\n# Translated to Python by Enrico Migliorini\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport progressbar\nfrom scipy.misc import imsave\n\nNe = 800\nNi = 200\nsampleNeuron = 76\nre = np.random.rand(Ne)\nri = np.random.rand(Ni)\n\na = np.append(np.ones((Ne))*0.02, 0.02+0.08*ri)\nb = np.append(np.ones((Ne))*0.2, 0.25-0.05*ri)\nc = np.append(-65+15*np.power(re, 2), -65*np.ones(Ni)) #-65mV for RS neurons\nd = np.append(8-6*np.power(re, 2), 2*np.ones(Ni)) #As above\nS = np.hstack((0.5*np.random.rand(Ne+Ni, Ne), -1*np.random.rand(Ne+Ni, Ni)))\n\n#np.set_printoptions(threshold=np.nan)\n#print(S)\n\nv = -65*np.ones(Ne+Ni)\nu = np.multiply(b, v)\nfirings = []\nsampleVTracer = []\nsampleUTracer = []\n\n#print(\"Stats[996]: \", a[996], b[996], c[996], d[996], v[996], u[996])\n#print(\"Stats[16]: \", a[16], b[16], c[16], d[16], v[16], u[16])\n\ntimelimit = 1000\nwith progressbar.ProgressBar(max_value=timelimit) as progress:\n for t in range(timelimit):\n I = np.append(5*np.random.normal(size=Ne), 2*np.random.normal(size=Ni))\n #I = np.append(re*5, ri*2)\n fired = np.asarray([n>=30 for n in v])\n sampleVTracer.append(v[sampleNeuron])\n sampleUTracer.append(u[sampleNeuron])\n firings.append([1 if n else 0 for n in fired])\n v[fired] = c[fired]\n u[fired] = u[fired]+d[fired]\n I = I+np.sum(S[:,fired], axis=1)\n v=v+0.5*(0.04*np.power(v,2)+5*v+140-u+I)\n v=v+0.5*(0.04*np.power(v,2)+5*v+140-u+I)\n u=u+np.multiply(a,(np.multiply(b,v)-u))\n progress.update(t)\n\nfirings = np.asarray(firings)\nfirings = np.flipud(firings)\n\nimsave('pyprimo.bmp', np.ones(firings.shape) - firings)\n#plt.matshow(firings, cmap='Greys')\n#plt.show()\n#plt.plot(range(timelimit), sampleVTracer, 'b', range(timelimit), sampleUTracer, 'r', range(timelimit), [30 for tl in range(timelimit)], \"g\")\n#plt.show()\n","sub_path":"python/izhi.py","file_name":"izhi.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"227715072","text":"\"\"\"Small example OSC server\n\nThis program listens to several addresses, and prints some information about\nreceived packets.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport argparse\nimport math\nimport numpy as np\nfrom pythonosc import dispatcher\nfrom pythonosc import osc_server\nfrom pythonosc import udp_client\nimport time\nimport _pickle as cPickle\nimport scipy\nfrom scipy import stats, optimize, interpolate\nimport datetime\nimport keyboard\nimport os\nimport sys\nimport random\nsize = 0\ncheck = -1\n\n\nfilename = '4class_our8e_SVM_max.sav' #58%,6users\nloaded_model = cPickle.load(open(filename, 'rb'))\n\nnum_electrodes = 8\nnum_users= 1 ###############\nnum_entries= num_users\ninput_ = np.full((1,8,8064), -1)\nfor i in range(0,200):\n if(not os.path.exists(str(i)+'.txt')):\n f= open(str(i)+'.txt',\"w+\")\n break \n\n\n#########################################\ndef delta(x,xlen):\n return ( np.sum(np.diff(x,n=1)) / (xlen - 1) )\n\ndef gamma(x,xlen):\n sum=0\n for i in range(0,xlen-2):\n sum += abs(x[i+2] - x[i])\n return ( sum / (xlen - 2) )\n\n\n#################################\n\ndef six_stats(new_data):\n new_data_processed = np.empty([num_entries,num_electrodes,378]) # 6 * 63\n index = 0\n print(\"\\nNew_data original shape:\",new_data.shape)\n for i in range(0,num_entries):\n for j in range(0,num_electrodes):\n index = 0\n for k in range(0,8064,128):\n if k!=7936:\n chunk = new_data[i][j][k:k+512]\n else:\n chunk = new_data[i][j][k:8065]\n \n chunk_len = len(chunk)\n \n new_data_processed[i][j][index] = np.mean(chunk)\n index += 1\n \n chunk_stdev = np.std(chunk) * math.sqrt(chunk_len / (chunk_len-1))\n new_data_processed[i][j][index] = chunk_stdev\n index += 1\n if(chunk_stdev == 0):\n print(\"\\nI AM ZERO!!\")\n #print(k,i,j)\n chunk_delta = delta(chunk,chunk_len)\n new_data_processed[i][j][index] = chunk_delta\n index += 1\n \n new_data_processed[i][j][index] = chunk_delta / chunk_stdev\n index += 1\n \n chunk_gamma = gamma(chunk,chunk_len)\n new_data_processed[i][j][index] = chunk_gamma\n index += 1\n \n new_data_processed[i][j][index] = chunk_gamma / chunk_stdev\n index += 1\n \n return new_data_processed\n # print(index)\n \n \n\n\n\n\ndef print_handler(address, *args):\n\n global size\n global input_\n\n if keyboard.is_pressed('q'):\n server.shutdown()\n print(\"\\nTHANK YOU! :)\")\n os._exit(1)\n #sys.exit(\"\\nTHANK YOU ! :)\")\n\n ele_8 = np.asarray(args)\n\n if(size != 8064):\n if( not np.array_equal(ele_8 , np.zeros(8)) ):\n input_[0,:,size] = ele_8\n size += 1\n \n if(size == 8064):\n size = 0\n #print(input_[0][0])\n #print(\"\\nIN\")\n processed = six_stats(input_)\n #print(\"\\nProcessed:\",processed.shape) #should be 8 X 378\n reshaped_input = processed.reshape((1,num_electrodes*378))\n #print(\"\\nReshaped:\",reshaped_input.shape)\n output = loaded_model.predict(reshaped_input)\n #print(\"\\nResult:\",output)\n #keyboard.press('enter')\n now = datetime.datetime.now()\n f.write(\"\\n%s\\t%s\"%(str(output),str(now.isoformat())) )\n\n '''--------sender code-------------'''\n \n parser1 = argparse.ArgumentParser()\n parser1.add_argument(\"--ip\", default=IP1,\n help=\"The ip of the OSC server\") #IP of Hololens 1\n parser1.add_argument(\"--port\", type=int, default=5005,\n help=\"The port the OSC server is listening on\") #port number of Python\n args1 = parser1.parse_args()\n client = udp_client.SimpleUDPClient(args1.ip, args1.port)\n #p=[\"Sad\",\"Angry\",\"Pleasant\",\"Happy\"]\n #z=random.randint(0,2)\n \n #client.send_message(\"/unity1\",p[z])\n \n if(output == 0):\n client.send_message(\"/unity1\", \"Sad\" )\n if(output == 1):\n client.send_message(\"/unity1\", \"Angry\" )\n if(output == 2):\n client.send_message(\"/unity1\", \"Pleasant\" )\n if(output == 3):\n client.send_message(\"/unity1\", \"Happy\" )\n \n parser2 = argparse.ArgumentParser()\n parser2.add_argument(\"--ip\", default=IP2,\n help=\"The ip of the OSC server\") #IP of Hololens 2\n parser2.add_argument(\"--port\", type=int, default=5005,\n help=\"The port the OSC server is listening on\") #port number of Python\n args2 = parser2.parse_args()\n client2 = udp_client.SimpleUDPClient(args2.ip, args2.port)\n \n if(output == 0):\n client2.send_message(\"/unity2\", \"Sad\" )\n if(output == 1):\n client2.send_message(\"/unity2\", \"Angry\" )\n if(output == 2):\n client2.send_message(\"/unity2\", \"Pleasant\" )\n if(output == 3):\n client2.send_message(\"/unity2\", \"Happy\" )\n \n \n #client2.send_message(\"/unity2\",p[z])\n #print(\"\\nRandom:\",z,p[z])\n print(\"\\nResult:\",output)\n #keyboard.press('enter')\n \n\nif __name__ == \"__main__\":\n \n global IP1 \n IP1 = input(\"\\nEnter IP of your Hololens:\\n\")\n global IP2\n IP2 = input(\"\\nEnter IP of your partner's Hololens:\\n\")\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--ip\",\n default=\"127.0.0.1\", help=\"The ip to listen on\") #IP of OpenBCI\n parser.add_argument(\"--port\",\n type=int, default=12345, help=\"The port to listen on\") #Port number of OpenBCI\n args = parser.parse_args()\n\n dispatcher = dispatcher.Dispatcher()\n dispatcher.map(\"/openbci\", print_handler)\n #print(type(x))\n #dispatcher.map(\"/volume\", print_volume_handler, \"Volume\")\n #dispatcher.map(\"/logvolume\", print_compute_handler, \"Log volume\", math.log)\n\n server = osc_server.ThreadingOSCUDPServer(\n (args.ip, args.port), dispatcher)\n #print(\"Serving on {}\".format(server.server_address))\n #print(type(server) )\n\n \n\n server.serve_forever()\n\n","sub_path":"svm_osc_updated.py","file_name":"svm_osc_updated.py","file_ext":"py","file_size_in_byte":5890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"111567448","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 18 16:01:43 2020\r\n\r\n@author: user\r\n\"\"\"\r\n\r\nfrom mcpi.minecraft import Minecraft\r\n\r\nmc=Minecraft.create()\r\nx,y,z=mc.player.getTilePos()\r\n\r\nBT=int(input(\"請輸入ID: \"))\r\nl=int(input(\"請輸入長度: \"))\r\nw=int(input(\"請輸入寬度: \"))\r\nh=int(input(\"請輸入高度: \"))\r\nmc.setBlocks(x,y,z,x+l,y+h,z+w,BT)\r\n\r\nmc.setBlocks(x+1,y,z+1,x+l-1,y+h-1,z+w-1,0)\r\n\r\nmc.setBlock(x+1,y,z,x+1,y+1,z,0)\r\n\r\nmc.setBlocks(x+1,y+h-2,z+1,x+l-1,y+h-2,z+w-1,169)\r\n\r\na=4\r\nwhile a 0:\n print('Fetch: {} new tweets for {}'.format(count, self.handle))\n else:\n print('Fetch: no new tweets for {}'.format(self.handle))\n\n # def download_tweets_since(self, timestamp):\n\n '''Database'''\n\n def __add_to_database(self, tweets):\n rows = []\n for tweet in tweets:\n if 'id' not in tweet: continue\n id = tweet['id']\n ts = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y'))\n data = pickle.dumps(tweet)\n rows.append((id, ts, sqlite3.Binary(data)))\n self.sqlite.executemany('INSERT OR IGNORE INTO Tweets(id, timestamp, data) VALUES (?,?,?)', rows)\n self.sqlite.commit()\n\n def __get_latest_tweet(self):\n rows = self.sqlite.execute('SELECT id, timestamp, data FROM Tweets ORDER BY id DESC LIMIT 1').fetchall()\n return None if len(rows) == 0 else Tweet(rows[0][0], rows[0][1], rows[0][2])\n\n latest_tweet = property(__get_latest_tweet)\n\n def __get_oldest_tweet(self):\n rows = self.sqlite.execute('SELECT id, timestamp, data FROM Tweets ORDER BY id ASC LIMIT 1').fetchall()\n return None if len(rows) == 0 else Tweet(rows[0][0], rows[0][1], rows[0][2])\n\n oldest_tweet = property(__get_oldest_tweet)\n\n def read_tweets_since(self, timestamp):\n ts = time.strftime('%Y-%m-%d %H:%M:%S', timestamp)\n rows = self.sqlite.execute('SELECT id, timestamp, data FROM Tweets WHERE timestamp > ? ORDER BY timestamp ASC', [(ts)]).fetchall()\n return None if len(rows) == 0 else [Tweet(row[0], row[1], row[2]) for row in rows]","sub_path":"TwitterAnalysis/TwitterBase.py","file_name":"TwitterBase.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"272139888","text":"import tkinter\r\nimport PIL.Image\r\nimport PIL.ImageTk\r\nimport cv2\r\nfrom pandas import DataFrame\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\r\nimport numpy as np\r\nimport doctest\r\ndoctest.testmod()\r\ndata = np.genfromtxt(\"logAngles.txt\", delimiter=\",\", names=[\"date&time\",\"raw_yaw\" ,\"filter_yaw\",\"smooth_yaw\" , \"raw_pitch\",\"filter_pitch\",\"smooth_pitch\" ])\r\nBUFFERSIZE = 15\r\ndataBuffer = [0]*BUFFERSIZE\r\nprint(type(data))\r\nclass App:\r\n def __init__(self,window, video_source1, video_source2):\r\n self.window = window\r\n self.window.title(\"KOMP ELECTRONICS\")\r\n self.video_source1 = video_source1\r\n self.video_source2 = video_source2\r\n self.photo1 = \"\"\r\n self.photo2 = \"\"\r\n\r\n #open video source\r\n self.vid1 = MyVideoCapture(self.video_source1, self.video_source2)\r\n\r\n # Create a canvas that can fit the above video source size\r\n self.canvas1 = tkinter.Canvas(window, width=500, height=500)\r\n self.canvas2 = tkinter.Canvas(window, width=500, height=500)\r\n self.canvas3 = tkinter.Canvas(window, width=500, height=500)\r\n self.canvas1.pack(padx=5, pady=10, side=\"left\")\r\n self.canvas2.pack(padx=5, pady=60, side=\"left\")\r\n self.canvas3.pack(padx=5, pady=60, side=\"left\")\r\n figure2 = plt.Figure(figsize=(5,4), dpi=100)\r\n ax2 = figure2.add_subplot(111)\r\n line2 = FigureCanvasTkAgg(figure2, self.canvas3)\r\n line2.get_tk_widget().pack(side=tkinter.LEFT, fill=tkinter.BOTH)\r\n ax2.plot(data['filter_pitch'],color='red')\r\n ax2.set_xlabel(\"Time(in Seconds)\")\r\n ax2.set_ylabel(\"Changes in Angles(in Degree)\")\r\n ax2.legend(\"Filtered Data\")\r\n ax2.set_title('Mad Filter Output')\r\n # After it is called once, the update method will be automatically called every delay milliseconds\r\n self.delay = 15\r\n self.update()\r\n \r\n\r\n self.window.mainloop()\r\n\r\n def update(self):\r\n # Get a frame from the video source\r\n ret1, frame1, ret2, frame2 = self.vid1.get_frame\r\n\r\n if ret1 and ret2:\r\n self.photo1 = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame1))\r\n self.photo2 = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame2))\r\n self.canvas1.create_image(0, 0, image=self.photo1, anchor=tkinter.NW)\r\n self.canvas2.create_image(0, 0, image=self.photo2, anchor=tkinter.NW)\r\n\r\n self.window.after(self.delay, self.update)\r\nclass MyVideoCapture:\r\n def __init__(self, video_source1, video_source2):\r\n # Open the video source\r\n self.vid1 = cv2.VideoCapture(video_source1)\r\n self.vid2 = cv2.VideoCapture(video_source2)\r\n\r\n if not self.vid1.isOpened():\r\n raise ValueError(\"Unable to open video source\", video_source1)\r\n\r\n @property\r\n def get_frame(self):\r\n ret1 = \"\"\r\n ret2 = \"\"\r\n if self.vid1.isOpened() and self.vid2.isOpened():\r\n ret1, frame1 = self.vid1.read()\r\n ret2, frame2 = self.vid2.read()\r\n frame1 = cv2.resize(frame1, (500, 500))\r\n frame2 = cv2.resize(frame2, (500, 500))\r\n if ret1 and ret2:\r\n # Return a boolean success flag and the current frame converted to BGR\r\n return ret1, cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB), ret2, cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB)\r\n else:\r\n return ret1, None, ret2, None\r\n else:\r\n return ret1, None, ret2, None\r\n\r\n # Release the video source when the object is destroyed\r\n def __del__(self):\r\n if self.vid1.isOpened():\r\n self.vid1.release()\r\n if self.vid2.isOpened():\r\n self.vid2.release()\r\nv1 = \"simple.mp4\"\r\nv2 = \"ball.mp4\"\r\n# Create a window and pass it to the Application object\r\nApp(tkinter.Tk(),v1, v2)\r\n","sub_path":"code/pilotdash/BuggyGUI/dualplayer2.py","file_name":"dualplayer2.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"445099243","text":"from flask_login import LoginManager, login_required, login_user, logout_user, current_user, UserMixin\n\nclass Usuario():\n def __init__(self, id, nome, numeroMatricula, departamento, email, telefone):\n self.id = id\n self.nome = nome\n self.numeroMatricula = numeroMatricula\n self.departamento = departamento\n self.email = email\n self.telefone = telefone\n\n #def is_active(self):\n # return self.is_active()\n \n #def is_anonymous(self):\n # return False\n \n #def is_authenticated(self):\n # return self.authenticated\n \n #def is_active(self):\n # return True\n \n #def get_id(self):\n # return self.id\n\n\n def atualizar(self, dados):\n try:\n id = dados[\"id\"]\n nome = dados[\"nome\"]\n numeroMatricula = dados[\"numeroMatricula\"]\n marca= dados[\"departamento\"]\n modelo = dados[\"email\"]\n telefone = dados[\"telefone\"]\n self.id, self.nome, self.numeroMatricula, self.departamento, self.email, self.telefone = id, nome, numeroMatricula, departamento, email, telefone\n return self\n except Exception as e:\n print(\"Problema ao criar novo usuario!\")\n print(e)\n\n def getDados(self):\n return self.id, self.nome, self.numeroMatricula, self.departamento, self.email, self.telefone\n\n def get_usuario(self):\n return self.id, self.nome, self.numeroMatricula, self.departamento, self.email, self.telefone\n #print(\"{}, {}, {}, {}, {}, {}\".format(self.id, self.nome, self.numeroMatricula, self.departamento, self.email, self.telefone))\n\n @staticmethod\n def criar(dados):\n try:\n id = dados[\"id\"]\n nome = dados[\"nome\"]\n numeroMatricula= dados[\"numeroMatricula\"]\n departamento = dados[\"departamento\"]\n email = dados[\"email\"]\n telefone = dados[\"telefone\"]\n return Usuario(id=id, nome=nome,numeroMatricula=numeroMatricula,departamento=departamento,email=email,telefone=telefone)\n except Exception as e:\n print(\"Problema ao criar novo usuario!\")\n print(e)\n\n def __dict__(self):\n d = dict()\n d[\"id\"] = self.id\n d[\"nome\"] = self.nome\n d[\"numeroMatricula\"] = self.numeroMatricula\n d[\"departamento\"] = self.departamento\n d[\"email\"] = self.email\n d[\"telefone\"] = self.telefone\n return d","sub_path":"model/usuario.py","file_name":"usuario.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"460902340","text":"import json\n\nimport requests\n\nfrom components.Lamp import Lamp\nfrom components.Receiver import Receiver\nfrom components.Sender import Sender\nfrom components.Sensor import Sensor\n\n\nclass CentralUnit:\n\n def __init__(self):\n self.config = self.load_config_file(\"config.json\")\n self.sender = Sender(self.config[\"lamps\"])\n self.sensor = Sensor(self.config[\"raspberry\"][\"echo\"], self.config[\"raspberry\"][\"trigger\"])\n self.lamp = Lamp\n self.receiver = Receiver\n self.standby = False\n self.direction = \"\"\n\n def log(message, level):\n print(level + \": \" + message)\n\n @staticmethod # static method as this method has to be reachable before Object initiation\n def load_config_file(filepath):\n with open(filepath, 'r') as config_file:\n return json.load(config_file)\n\n def ping_all(self):\n print(\"try to ping all\")\n for northlamps in self.config[\"lamps\"][\"north\"]:\n try:\n requests.post(\"http://\" + self.config[\"lamps\"][\"south\"][northlamps] + \":8080/signal\",\n data=None,\n json=self.config[\"signal\"],\n headers={'Content-Type': 'application/json'}\n )\n\n except:\n print(\"ping all failed to ping \" + northlamps)\n for southlamps in self.config[\"lamps\"][\"south\"]:\n try:\n\n requests.post(\"http://\" + self.config[\"lamps\"][\"south\"][southlamps] + \":8080/signal\",\n data=None,\n json=self.config[\"signal\"],\n headers={'Content-Type': 'application/json'}\n )\n except:\n print(\"ping all failed to ping \" + southlamps)\n\n def get_direction(self, post):\n print(\"estimate direction\")\n if self.config[\"lamps\"][\"north\"] != {}:\n for northlamps in self.config[\"lamps\"][\"north\"]:\n if self.config[\"lamps\"][\"south\"][northlamps] == post[\"sender\"]:\n print(\"north\")\n self.direction = \"north\"\n else:\n print(\"no north lamps\")\n if self.config[\"lamps\"][\"south\"] != {}:\n for southlamps in self.config[\"lamps\"][\"south\"]:\n if self.config[\"lamps\"][\"south\"][southlamps] == post[\"sender\"]:\n print(\"south\")\n self.direction = \"south\"\n else:\n print(\"no south lamps\")\n\n def ping_to_direction(self):\n print(\"try to ping into direction\")\n for lamps in self.config[\"lamps\"][self.direction]:\n try:\n requests.post(\"http://\" + self.config[\"lamps\"][self.direction][lamps] + \":8080/signal\",\n data=None,\n json={\n \"counter\": 0,\n \"url\": self.config[\"signal\"][\"url\"]\n },\n headers={'Content-Type': 'application/json'}\n )\n except:\n print(\"failed to ping into direction\")\n\n def use_signal(self):\n print(\"try to use signal\")\n if self.standby:\n print(\"is on standby\")\n self.ping_to_direction()\n self.lamp().ligth_on()\n\n else:\n print(\"not on standby\")\n self.ping_all()\n","sub_path":"components/CentralUnit.py","file_name":"CentralUnit.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"230621379","text":"from random import randint\nfrom time import time\n\nclass Being:\n\n\tx = 0\n\ty = 0\n\tspeed = 2\n\tcolor = \"#333\"\n\tsight_dist = 10\n\t\n\tdef __init__(self, root, canvas, buildings):\n\t\t\n\t\tself.buildings = buildings\n\t\tself.last_time = time()\n\t\t#assume a collision for our first loop\n\t\tcollision = True\n\t\twhile(collision):\n\t\t\tself.x = randint(0,600)\n\t\t\tself.y = randint(0,400)\n\t\t\tcollision = False\n\t\t\tfor building in self.buildings:\n\t\t\t\tif building.hit_test(self.x,self.y):\n\t\t\t\t\tcollision = True\n\t\tself.root = root\t\t\n\t\tself.canvas = canvas\n\t\tself.rectangle = canvas.create_rectangle(self.x,self.y,self.x,self.y,fill=self.color,outline='')\n\t\tself.move()\n\tdef get_x(self):\n\t\treturn self.x\n\tdef get_y(self):\n\t\treturn self.y\n\tdef set_position(self, x, y):\n\t\tmove_x = x-self.x\n\t\tmove_y = y-self.y\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.canvas.move(self.rectangle, move_x, move_y)\n\tdef know_beings(self, humans, zombies, player):\n\t\tself.humans = humans\n\t\tself.zombies = zombies\n\t\tself.player = player\n\tdef set_thread(self,thread):\n\t\tself.thread = thread\n\tdef get_thread(self):\n\t\treturn self.thread","sub_path":"Being.py","file_name":"Being.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"331362773","text":"\r\ndef sub(a=0, b=0):\r\n if isinstance(a, (int, float)) and isinstance(b, (int, float)):\r\n temp=a-b\r\n return temp\r\n else:\r\n # print(\"Wrong argument given\")\r\n # return None\r\n raise Exception(\"Wrong argument given\")\r\n \r\n\r\nresult=sub() # Positional arguments\r\nprint(result)\r\nnb=12\r\nprint(\"Nb is\", nb, \"nb**2 is\", nb**2, sep=\" \")\r\n\r\n\r\n\r\n\r\n","sub_path":"function3.py","file_name":"function3.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"617874518","text":"#!/usr/bin/env python\n\nimport requests\nimport base64\nimport json\nimport subprocess\n\nAPI_URL = \"https://yh956nkkj5.execute-api.us-east-2.amazonaws.com/default/project_uploader\"\nPATH_TO_FILE = \"./test_data/Aurelius+CS633+OL+Spring+2018.pdf\"\n\nwith open(PATH_TO_FILE, 'rb') as f:\n rawbytes = f.read()\nencoded_content = base64.b64encode(rawbytes).decode()\n\ntest_data = {\n \"content-location\": \"/2018/Spring/Aurelius CS633 OL Spring 2018.pdf\",\n \"content-type\": \"application/pdf\",\n \"content\": {\n \"encoded_file\": encoded_content,\n \"encoding\": \"base64\",\n \"details\": {\n \"project_name\": \"aurelius\",\n \"year\": \"2018\",\n \"semester\": \"fall\",\n \"instructor\": \"Elentukh\",\n \"github\": \"github.com\",\n \"description\": \"test description\",\n \"pivotal_tracker\": \"pivotal\",\n \"website\": \"website\",\n \"team_members\": [\n \"member1\", \n \"member2\"]\n },\n \"tag_data\": {\n \"Identifier\": [\n \"/2018/Spring/Aurelius CS633 OL Spring 2018.pdf\",\n \"Sudoku\"\n ],\n \"terms\": {\n \"2018\": \"year\",\n \"Sudoku\": \"project_name\",\n \"Spring\": \"semester\",\n \"Alex Elentukh\": \"instructor\",\n \"javascript\": \"programming_language\",\n \"s3\": \"framework\",\n \"game\": \"keyword\",\n \"cards\": \"keyword\",\n \"matching\": \"keyword\",\n \"git\": \"version_control\"\n }\n }\n }\n}\n\n\nr = requests.post(API_URL, data = json.dumps(test_data))\n\nprint(r)\n\n\n","sub_path":"tests/post_to_apigateway_test.py","file_name":"post_to_apigateway_test.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"135280362","text":"import astropy.io.fits as pf\nimport numpy as np\nfrom astropy.time import Time\nimport astropy.units as u, astropy.constants as c\nimport glob\n\n'''\nA quick selection of code for reading in psrfits files and \ngenerating dynamic spectra.\n'''\n\ndef __init__():\n return\n\nclass psrfits_data:\n '''\n A class for reading in psrfits files and generating a dynamic\n spectrum.\n\n Parameters:\n -----------\n fname: string, the full path to the psrfits file you would like to\n be read in.\n remove_dispersion: Boolean, optional, True if you would like the channel\n offsets due to dispersion to be removed.\n fref: astropy quantity, optional. The frequency you would like to \n dedispersion to. If not passed, but remove_dispersion is True,\n the data will be dedispersed to a frequency of inf.\n '''\n\n def __init__(self,fname,remove_dispersion=False,fref=None):\n self.read(fname,remove_dispersion,fref)\n \n def read(self,fname,remove_dispersion,fref):\n '''\n Reads in the psrfits file.\n \n Parameters:\n -----------\n fname: string, the full path to the psrfits file you would like to\n be read in.\n remove_dispersion: Boolean, optional, True if you would like the channel\n offsets due to dispersion to be removed.\n fref: astropy quantity, optional. The frequency you would like to \n dedispersion to. If not passed, but remove_dispersion is True,\n the data will be dedispersed to a frequency of inf.\n\n Sets:\n ----------\n self.data: numpy array, the flux table\n self.time: array of astropy times, the center time of each profile\n self.tint: astropy quantity, the integration time of each time bin\n self.freq: astropy quantity, the frequency of each channel\n '''\n with pf.open(fname) as hd:\n if hd['PRIMARY'].header['FITSTYPE'] != 'PSRFITS':\n raise ValueError('Not a psrfits file.')\n if hd['HISTORY'].data['NBIN'] == 0:\n raise ValueError('This data is in search mode. '\n 'Try the pypsrfits module by '\n 'Paul Demorest, or use dspsr '\n 'to create fold mode psrfits '\n 'files.')\n self.freq = hd['SUBINT'].data['DAT_FREQ'][0]*u.MHz\n raw_data = hd['SUBINT'].data['DATA']\n shape = raw_data.shape\n\n dat_offs = hd['SUBINT'].data['DAT_OFFS']\n dat_wts = hd['SUBINT'].data['DAT_WTS']\n dat_scl = hd['SUBINT'].data['DAT_SCL']\n self.data = (raw_data * np.repeat(dat_scl.reshape((shape[0],shape[1],shape[2],1)),\n shape[3],axis=3) + \n np.repeat(dat_offs.reshape((shape[0],shape[1],shape[2],1)),\n shape[3],axis=3)) \n self.data = self.data / dat_wts[:,np.newaxis,:,np.newaxis]\n self.data = self.data[:,:2,...].sum(axis=1)\n \n self.time = (hd['SUBINT'].data['OFFS_SUB']*u.s + \n Time(hd['PRIMARY'].header['STT_IMJD'],format='mjd') + \n hd['PRIMARY'].header['STT_SMJD']*u.s +\n hd['PRIMARY'].header['STT_OFFS']*u.s)\n self.tint = (hd['SUBINT'].data['TSUBINT'])*u.s\n \n DM = hd['COHDDISP'].header['DM'] *u.pc *u.cm**(-3)\n f0 = float([h for h in hd['PSRPARAM'].data['PARAM'] if 'F0' in h][0].split()[1])\n dt_bin = 1/(f0*hd['SUBINT'].header['NBIN'])*u.s\n\n for i in np.arange(len(self.freq)):\n if fref is None:\n dt = 4.18808*10.**(-3.)*u.s * DM.to(u.pc*u.cm**(-3)).value * (-1./self.freq[i].to(u.GHz).value**2.)\n else:\n dt = 4.18808*10.**(-3.)*u.s * DM.to(u.pc*u.cm**(-3)).value * (1./fref.to(u.GHz).value**2.-1./self.freq[i].to(u.GHz).value**2.)\n nshift = np.int(np.rint(dt/dt_bin))\n self.data[:,i,:] = np.roll(self.data[:,i,:],nshift,axis=-1)\n \n def dynspec(self,offbins,onbins):\n '''\n Produces a dynamic spectrum from self.data\n \n Parameters:\n -----------\n onweights: array, float; the weight of each phase bin to generate \n the on-pulse dynamic spectrum\n offweights: array, float; the weight of each phase bin to generate the\n off-pusle dynamic spectrum\n \n Returns:\n ---------\n the dynamic spectrum, un-normalized\n '''\n Ion = self.data[:, :, onbins[0]:onbins[1]].mean(axis=-1)\n Ioff = self.data[:,:,offbins[0]:offbins[1]].mean(axis=-1)\n return (Ion/Ioff - 1)\n","sub_path":"folding_scripts/psrfits_analysis.py","file_name":"psrfits_analysis.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"465395685","text":"from flask import Flask\nfrom flask_sockets import Sockets\nfrom gevent import pywsgi\nfrom geventwebsocket.handler import WebSocketHandler\nfrom json import loads, dumps\nfrom abaGEN import aba\n\napp = Flask(__name__)\nsockets = Sockets(app)\n\n@sockets.route('/api/messages')\ndef server(ws):\n while not ws.closed:\n data = loads(ws.receive())\n if data:\n message = data.get('raw_message')\n if data.get('type') == 'GroupMessage' and '阿巴' in message:\n sendGMsg(ws, data.get('group_id'), aba())\n elif data.get('type') == 'PrivateMessage' and '阿巴' in message:\n sendPMsg(ws, data.get('user_id'), aba())\n return data\n\ndef sendGMsg(ws, group_id, msg):\n msg = {\n 'action': 'send_group_msg',\n 'params': {\n 'group_id': group_id,\n 'message': msg\n }\n }\n print(msg)\n ws.send(dumps(msg))\n\ndef sendPMsg(ws, user_id, msg):\n msg = {\n \"action\": \"send_private_msg\",\n \"params\": {\n \"user_id\": user_id,\n \"message\": msg\n }\n }\n print(msg)\n ws.send(dumps(msg))\n\nif __name__ == \"__main__\":\n server = pywsgi.WSGIServer(('0.0.0.0', 5701), application=app, handler_class=WebSocketHandler)\n print('Server Started')\n server.serve_forever()\n","sub_path":"SDQB_ws.py","file_name":"SDQB_ws.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"88513390","text":"# import pdb\n\n\nmylist = [('23.1.240.14', ['3']),('csrfmiddlewaretoken', ['qETylTJRvGvv3bcOcXtsqoJcu1QIwxha']),('165.254.22.101', ['6', '5'])]\n\n# print(mylist)\n\n# ip_port = []\n# # pdb.set_trace()\n# for i in mylist:\n# \tprint (len(i))\n# \tfor a,b in i:\n# \t\tfor c in b:\n# \t\t try:\n# \t\t ipaddress.ip_address(a)\n# \t\t ip_port.append((a,c))\n# \t\t except:\n# \t\t continue\n# print(ip_port)\n\n\n\njlist= []\nfor i in mylist:\n\tjlist.append(list(i))\nprint (jlist)\nfor a,b in jlist:\n\tfor c in b:\n\t\tprint ('got ',a,c)\n","sub_path":"unpack_list_tuple.py","file_name":"unpack_list_tuple.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"625396376","text":"\n\n\nimport runStatus\nrunStatus.preloadDicts = False\n\nimport WebMirror.OutputFilters.FilterBase\n\nimport WebMirror.OutputFilters.util.MessageConstructors as msgpackers\nfrom WebMirror.OutputFilters.util.TitleParsers import extractTitle\n\nimport bs4\nimport re\nimport calendar\nimport datetime\nimport time\nimport json\nimport WebMirror.util.webFunctions\nimport bleach\n\nMIN_RATING = 5\n\n########################################################################################################################\n#\n#\t## ## ### #### ## ## ###### ## ### ###### ######\n#\t### ### ## ## ## ### ## ## ## ## ## ## ## ## ## ##\n#\t#### #### ## ## ## #### ## ## ## ## ## ## ##\n#\t## ### ## ## ## ## ## ## ## ## ## ## ## ###### ######\n#\t## ## ######### ## ## #### ## ## ######### ## ##\n#\t## ## ## ## ## ## ### ## ## ## ## ## ## ## ## ##\n#\t## ## ## ## #### ## ## ###### ######## ## ## ###### ######\n#\n########################################################################################################################\n\n\n\n\nclass RRLSeriesPageProcessor(WebMirror.OutputFilters.FilterBase.FilterBase):\n\n\n\twanted_mimetypes = [\n\n\t\t\t\t\t\t\t'text/html',\n\t\t\t\t\t\t]\n\twant_priority = 50\n\n\tloggerPath = \"Main.Filter.RoyalRoad.Page\"\n\n\n\t@staticmethod\n\tdef wantsUrl(url):\n\t\tif re.search(r\"^http://(?:www\\.)?royalroadl\\.com/fiction/\\d+/?$\", url):\n\t\t\tprint(\"RRLSeriesPageProcessor Wants url: '%s'\" % url)\n\t\t\treturn True\n\t\treturn False\n\n\tdef __init__(self, **kwargs):\n\n\t\tself.kwargs = kwargs\n\n\n\t\tself.pageUrl = kwargs['pageUrl']\n\n\t\tself.content = kwargs['pgContent']\n\t\tself.type = kwargs['type']\n\n\t\tself.log.info(\"Processing RoyalRoadL Item\")\n\t\tsuper().__init__(**kwargs)\n\n\n##################################################################################################################################\n##################################################################################################################################\n##################################################################################################################################\n\n\n\tdef extractSeriesReleases(self, seriesPageUrl, soup):\n\n\t\ttitletg = soup.find(\"h1\", class_='fiction-title')\n\t\tauthortg = soup.find(\"span\", class_='author')\n\t\tratingtg = soup.find(\"span\", class_='overall')\n\n\t\tif not ratingtg:\n\t\t\tself.log.info(\"Could not find rating tag!\")\n\t\t\treturn []\n\n\n\t\trating = float(ratingtg['score'])\n\t\tif not rating >= MIN_RATING and rating != 0.0:\n\t\t\tself.log.info(\"Item rating below upload threshold: %s\", rating)\n\t\t\treturn []\n\n\t\tif not titletg:\n\t\t\tself.log.info(\"Could not find title tag!\")\n\t\t\treturn []\n\t\tif not authortg:\n\t\t\tself.log.info(\"Could not find author tag!\")\n\t\t\treturn []\n\n\n\t\ttitle = titletg.get_text()\n\t\tauthor = authortg.get_text()\n\t\tassert author.startswith(\"by \")\n\t\tauthor = author[2:].strip()\n\n\n\t\ttitle = bleach.clean(title, tags=[], attributes=[], styles=[], strip=True, strip_comments=True)\n\t\tauthor = bleach.clean(author, tags=[], attributes=[], styles=[], strip=True, strip_comments=True)\n\n\t\tdescDiv = soup.find('div', class_='description')\n\t\tparas = descDiv.find_all(\"p\")\n\t\ttags = []\n\n\t\tdesc = []\n\t\tfor para, text in [(para, para.get_text()) for para in paras]:\n\t\t\tif text.lower().startswith('categories:'):\n\t\t\t\ttagstr = text.split(\":\", 1)[-1]\n\t\t\t\titems = tagstr.split(\",\")\n\t\t\t\t[tags.append(item.strip()) for item in items if item.strip()]\n\t\t\telse:\n\t\t\t\tdesc.append(para)\n\n\n\t\tseriesmeta = {}\n\n\t\tseriesmeta['title'] = title\n\t\tseriesmeta['author'] = author\n\t\tseriesmeta['tags'] = tags\n\t\tseriesmeta['homepage'] = seriesPageUrl\n\t\tseriesmeta['desc'] = \" \".join([str(para) for para in desc])\n\t\tseriesmeta['tl_type'] = 'oel'\n\t\tseriesmeta['sourcesite'] = 'RoyalRoadL'\n\n\t\tmeta_pkt = msgpackers.createSeriesInfoPacket(seriesmeta, matchAuthor=True)\n\n\t\textra = {}\n\t\textra['tags'] = tags\n\t\textra['homepage'] = seriesPageUrl\n\t\textra['sourcesite'] = 'RoyalRoadL'\n\n\n\t\tchapters = soup.find(\"div\", class_='chapters')\n\t\treleases = chapters.find_all('li', class_='chapter')\n\n\t\traw_retval = []\n\t\tfor release in releases:\n\t\t\tchp_title, reldatestr = release.find_all(\"span\")\n\t\t\trel = datetime.datetime.strptime(reldatestr.get_text(), '%d/%m/%y')\n\t\t\tif rel.date() == datetime.date.today():\n\t\t\t\treldate = time.time()\n\t\t\telse:\n\t\t\t\treldate = calendar.timegm(rel.timetuple())\n\n\t\t\tchp_title = chp_title.get_text()\n\t\t\t# print(\"Chp title: '{}'\".format(chp_title))\n\t\t\tvol, chp, frag, post = extractTitle(chp_title + \" \" + title)\n\n\t\t\traw_item = {}\n\t\t\traw_item['srcname'] = \"RoyalRoadL\"\n\t\t\traw_item['published'] = reldate\n\t\t\traw_item['linkUrl'] = release.a['href']\n\n\t\t\traw_msg = msgpackers.buildReleaseMessage(raw_item, title, vol, chp, frag, author=author, postfix=chp_title, tl_type='oel', extraData=extra, matchAuthor=True)\n\n\t\t\traw_retval.append(raw_msg)\n\n\t\tmissing_chap = 0\n\t\tfor item in raw_retval:\n\t\t\tif not (item['vol'] or item['chp']):\n\t\t\t\tmissing_chap += 1\n\n\t\tif len(raw_retval):\n\t\t\tunnumbered = (missing_chap/len(raw_retval)) * 100\n\t\t\tif len(raw_retval) >= 5 and unnumbered > 80:\n\t\t\t\tself.log.warning(\"Item seems to not have numbered chapters. Adding simple sequential chapter numbers.\")\n\t\t\t\tchap = 1\n\t\t\t\tfor item in raw_retval:\n\t\t\t\t\titem['vol'] = None\n\t\t\t\t\titem['chp'] = chap\n\t\t\t\t\tchap += 1\n\n\t\t# Do not add series without 3 chapters.\n\t\tif len(raw_retval) < 3:\n\t\t\tself.log.info(\"Less then three chapters!\")\n\t\t\treturn []\n\n\t\tif not raw_retval:\n\t\t\tself.log.info(\"Retval empty?!\")\n\t\t\treturn []\n\n\t\tself.amqp_put_item(meta_pkt)\n\t\tretval = [msgpackers.createReleasePacket(raw_msg) for raw_msg in raw_retval]\n\t\treturn retval\n\n\n\tdef sendReleases(self, releases):\n\t\tself.log.info(\"Total releases found on page: %s. Emitting messages into AMQP local queue.\", len(releases))\n\t\tfor release in releases:\n\t\t\tself.amqp_put_item(release)\n\n\n\n\n\tdef processPage(self, url, content):\n\n\t\tsoup = WebMirror.util.webFunctions.as_soup(self.content)\n\t\treleases = self.extractSeriesReleases(self.pageUrl, soup)\n\t\tif releases:\n\t\t\tself.sendReleases(releases)\n\n\n\n\n##################################################################################################################################\n##################################################################################################################################\n##################################################################################################################################\n\n\n\n\tdef extractContent(self):\n\t\t# print(\"Call to extract!\")\n\t\t# print(self.amqpint)\n\n\t\tself.processPage(self.pageUrl, self.content)\n\n\ndef testJobFromUrl(url):\n\timport datetime\n\timport WebMirror.database\n\treturn WebMirror.database.WebPages(\n\t\t\t\tstate = 'fetching',\n\t\t\t\turl = url,\n\t\t\t\tstarturl = url,\n\t\t\t\tnetloc = \"wat\",\n\t\t\t\tdistance = WebMirror.database.MAX_DISTANCE-2,\n\t\t\t\tis_text = True,\n\t\t\t\tpriority = WebMirror.database.DB_REALTIME_PRIORITY,\n\t\t\t\ttype = \"unknown\",\n\t\t\t\tfetchtime = datetime.datetime.now(),\n\t\t\t\t)\n\n\n\ndef test():\n\tprint(\"Test mode!\")\n\timport logSetup\n\timport WebMirror.rules\n\timport WebMirror.Engine\n\timport WebMirror.Runner\n\timport multiprocessing\n\tlogSetup.initLogging()\n\n\tcrawler = WebMirror.Runner.Crawler()\n\tcrawler.start_aggregator()\n\n\n\tc_lok = cookie_lock = multiprocessing.Lock()\n\tengine = WebMirror.Engine.SiteArchiver(cookie_lock=c_lok, response_queue=crawler.agg_queue)\n\n\n\n\tengine.dispatchRequest(testJobFromUrl('http://royalroadl.com/fiction/3333'))\n\t# engine.dispatchRequest(testJobFromUrl('http://www.royalroadl.com/fiction/2850'))\n\t# engine.dispatchRequest(testJobFromUrl('http://www.royalroadl.com/fictions/latest-updates/'))\n\n\t# engine.dispatchRequest(testJobFromUrl('http://www.royalroadl.com/fictions/best-rated/'))\n\t# engine.dispatchRequest(testJobFromUrl('http://www.royalroadl.com/fictions/latest-updates/'))\n\t# engine.dispatchRequest(testJobFromUrl('http://www.royalroadl.com/fictions/active-top-50/'))\n\t# engine.dispatchRequest(testJobFromUrl('http://www.royalroadl.com/fictions/weekly-views-top-50/'))\n\t# engine.dispatchRequest(testJobFromUrl('http://www.royalroadl.com/fictions/newest/'))\n\n\tcrawler.join_aggregator()\n\nif __name__ == \"__main__\":\n\ttest()\n\n","sub_path":"WebMirror/OutputFilters/RoyalRoadL/RRLSeriesPageFilter.py","file_name":"RRLSeriesPageFilter.py","file_ext":"py","file_size_in_byte":8268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"199153888","text":"import sys\nimport io\n\nold_stdout = sys.stdout\nsys.stdout = mystdout = io.StringIO()\n\nexec(f'x,y=1,2\\nz=x+y\\nprint(\"aaa\")\\nprint(x,y,z)\\n')\nmystdout.flush()\n\nout = mystdout.getvalue()\nmystdout.close()\nsys.stdout = old_stdout\nprint('out=', out)\n","sub_path":"_more/js6/sc6/_try/02-exec/test/redirect.py","file_name":"redirect.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"604290862","text":"__author__ = 'Folaefolc'\n\"\"\"\nCode par Folaefolc\nLicence MIT\n\"\"\"\n\nfrom .constants import *\nfrom .exceptions import SpriteNotFoundError, SpriteNotLoadedError\n\n\nclass Tile:\n def __init__(self, x: int=0, y: int=0, w: int=1, h: int=1, image_path: str=\"\"):\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.image_path = image_path\n self.image = None\n\n def load(self):\n if os.path.exists(self.image_path):\n self.image = pygame.image.load(self.image_path).convert_alpha()\n else:\n raise SpriteNotFoundError(\"The sprite located at '{}' seems to be lacking\".format(self.image_path))\n\n def draw(self):\n if self.image:\n return self.image\n raise SpriteNotLoadedError(\"The sprite was not loaded\")","sub_path":"core/tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"453306355","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nimport oauth2_provider.views as oauth2_views\nfrom django.conf import settings\nfrom rest_framework_swagger.views import get_swagger_view\n\n\nschema_view = get_swagger_view(title='api')\n\n# OAuth2 provider endpoints\noauth2_endpoint_views = [\n url(r'^authorize/$', oauth2_views.AuthorizationView.as_view(), name=\"authorize\"),\n url(r'^token/$', oauth2_views.TokenView.as_view(), name=\"token\"),\n url(r'^revoke-token/$', oauth2_views.RevokeTokenView.as_view(), name=\"revoke-token\"),\n]\n\nif settings.DEBUG:\n # OAuth2 Application Management endpoints\n oauth2_endpoint_views += [\n url(r'^applications/$', oauth2_views.ApplicationList.as_view(), name=\"list\"),\n url(r'^applications/register/$', oauth2_views.ApplicationRegistration.as_view(), name=\"register\"),\n url(r'^applications/(?P\\d+)/$', oauth2_views.ApplicationDetail.as_view(), name=\"detail\"),\n url(r'^applications/(?P\\d+)/delete/$', oauth2_views.ApplicationDelete.as_view(), name=\"delete\"),\n url(r'^applications/(?P\\d+)/update/$', oauth2_views.ApplicationUpdate.as_view(), name=\"update\"),\n ]\n\n # OAuth2 Token Management endpoints\n oauth2_endpoint_views += [\n url(r'^authorized-tokens/$', oauth2_views.AuthorizedTokensListView.as_view(), name=\"authorized-token-list\"),\n url(r'^authorized-tokens/(?P\\d+)/delete/$', oauth2_views.AuthorizedTokenDeleteView.as_view(),\n name=\"authorized-token-delete\"),\n ]\n\nurlpatterns = [\n # OAuth 2 endpoints:\n url(r'^$', schema_view),\n url(r'^o/', include(oauth2_endpoint_views, namespace=\"oauth2_provider\")),\n url(r'^api/', include('api.urls'), name='api'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^api-auth/', include('rest_framework.urls',\n namespace='rest_framework')),\n]\n","sub_path":"beaconapp/beaconapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636127563","text":"\"\"\"\nDetermine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:\n\nEach row must contain the digits 1-9 without repetition.\nEach column must contain the digits 1-9 without repetition.\nEach of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.\nNote:\n\nA Sudoku board (partially filled) could be valid but is not necessarily solvable.\nOnly the filled cells need to be validated according to the mentioned rules.\n\n\"\"\"\nfrom typing import List\n\n\ndef isValidSudoku(board: List[List[str]]) -> bool:\n # rows\n for row in board:\n entries = set()\n for elem in row:\n if elem == \".\":\n continue\n if elem in entries:\n return False\n entries.add(elem)\n\n # columns\n for ii in range(9):\n col = [x[ii] for x in board]\n entries = set()\n for elem in col:\n if elem == \".\":\n continue\n if elem in entries:\n return False\n entries.add(elem)\n\n # boxes\n for start in [0, 3, 6]:\n for ii in [0, 3, 6]:\n entries = set()\n for jj in range(start, 3 + start):\n for entry in board[jj][ii : ii + 3]:\n if entry == \".\":\n continue\n if entry in entries:\n return False\n entries.add(entry)\n\n return True\n\n\nboard = [\n [\"5\", \"3\", \".\", \".\", \"7\", \".\", \".\", \".\", \".\"],\n [\"6\", \".\", \"4\", \"1\", \"9\", \"5\", \".\", \".\", \".\"],\n [\".\", \"9\", \"8\", \".\", \".\", \".\", \".\", \"6\", \".\"],\n [\"8\", \".\", \".\", \".\", \"6\", \".\", \".\", \".\", \"3\"],\n [\"4\", \".\", \".\", \"8\", \".\", \"3\", \".\", \".\", \"1\"],\n [\"7\", \".\", \".\", \".\", \"2\", \".\", \".\", \".\", \"6\"],\n [\".\", \"6\", \".\", \".\", \".\", \".\", \"2\", \"8\", \".\"],\n [\".\", \".\", \".\", \"4\", \"1\", \"9\", \".\", \".\", \"5\"],\n [\".\", \".\", \".\", \".\", \"8\", \".\", \".\", \"7\", \"9\"],\n]\n\n\nprint(isValidSudoku(board))\n","sub_path":"LeetCode/valid_sudoku.py","file_name":"valid_sudoku.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"646994366","text":"import numpy as np\nimport pandas as pd\nimport pickle\nimport streamlit as st \nimport webbrowser\nimport os\nimport pathlib\n#### IMPORT UTILS\npath = pathlib.Path(__file__).parent.resolve()\nimport sys\n# adding utils to the system path\nsys.path.insert(0, f'{path}/utils')\nfrom front_utils import side_bar_void\nfrom visu_house.plot_house import plot_house\nfrom visu_house.house import House\nfrom visu_house.tiff_manipulation import substract_dtm_dsm, mask_chm\n\n\ndef main():\n\n st.set_page_config(layout=\"wide\",page_title='Eye Lisa', page_icon=\":house:\")\n\n col1, col2 = st.beta_columns(2)\n # col2.subheader(\"A webapp by Yolann Sabaux\")\n html_title = html_subtitle = \"\"\"\n

Eye Lisa - Demo @Essen

\n \"\"\"\n col1.markdown(html_title,unsafe_allow_html=True)\n \n html_subtitle = \"\"\"\n

Take a look at your house!

\n \"\"\"\n col1.markdown(html_subtitle,unsafe_allow_html=True)\n\n\n # LIST OF ADDRESS\n df = pd.read_csv(\"dataset/essen_address.csv\") \n\n postal_code = 2910\n city_name = \"Essen\"\n col1.markdown('__Locality__')\n col1.info(f\"{postal_code} - {city_name.upper()}\")\n street_choice = df[\"streetname_nl\"].sort_values().unique()\n selected_street = col1.selectbox('Please select an address:', street_choice)\n\n nb_choice = df[df[\"streetname_nl\"] == \"Albert Yssackersstraat\"].sort_values(by=[\"house_number\"])\n nb_choice = df[df[\"streetname_nl\"] == selected_street].sort_values(by=[\"house_number\"])\n nb_choice = nb_choice[\"house_number\"].astype(int, errors=\"ignore\").sort_values().to_list()\n selected_number = col1.selectbox('Please select a number:',nb_choice)\n\n selected_address = f\"{selected_street} {selected_number}, 2910 Essen\"\n # SUBMIT BUTTON\n # SIDEBAR\n df = side_bar_void(postal_code)\n if col1.button(\"Look at it!\"):\n \n try:\n house = House(selected_address)\n dtm = f\"dataset/DTM/{house.tif_names}\"\n dsm = f\"dataset/DSM/{house.tif_names}\"\n substract_dtm_dsm(dtm, dsm)\n shapes = [feature for feature in house.bounding_box_coordinates] \n mask_chm(shapes)\n chm = \"dataset/masked_chm.tif\"\n fig = plot_house(chm, house.house_coordinates)\n\n config={\"displayModeBar\": False,\n 'displaylogo': False,}\n col1.plotly_chart(fig, use_container_width=False, config=config)\n print(\"Everything's ok\")\n\n html_line = '''\n \n
\n '''\n col1.markdown(html_line,unsafe_allow_html=True)\n\n html_subtitle_price = \"\"\"\n

Get an estimated price!

\n \"\"\"\n col1.markdown(html_subtitle_price,unsafe_allow_html=True)\n with col1.beta_expander(label='Expand me!'):\n cwd = os.getcwd() # Get the current working directory (cwd)\n model = pickle.load(open(cwd+\"/utils/bg_reg.pkl\", \"rb\"))\n result = model.predict(df)\n result = round((np.expm1(result[0])//10000*10000))\n f\"The price estimated is {result} euros.\"\n except Exception as r:\n col1.header(\"It looks like there was an error. Please retry or contact the administrator of the website.\")\n print(f\"There was the following error:{r}\")\n\n # col1.success(f'The output is {np.expm1(result[0])}')\n\n\nif __name__ == '__main__':\n\n main()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"79183431","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\n\"\"\"\n@version: v1.0.1\n@author: cherry\n@license: Apache Licence \n@contact: hjb.123@163.com\n@site: http://www.phpgao.com\n@software: PyCharm\n@project: untitled\n@file: tasks.py\n@time: 2016-08-29 15:47\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport errno\nimport time\n\nfrom celery import Celery\nfrom celery.exceptions import Reject\nfrom celery.utils.log import get_task_logger\n\n\n# app = Celery('tasks',backend='redis://192.168.10.231:6379/11', broker='amqp://test:test@192.168.10.205:5672/myvhost')\nclass Config:\n CELERY_ENABLE_UTC = True\n CELERY_TIMEZONE = 'Europe/London'\n\napp = Celery('tasks')\napp.config_from_object('celeryconfig')\n# app.config_from_object('Config') 可直接加类\n# platforms.C_FORCE_ROOT = True\n\n# app.conf.update(\n# CELERYBEAT_SCHEDULE={\n# \"add\": {\n# \"task\": \"proj.tasks.add\",\n# \"schedule\": timedelta(seconds=10), # 10s执行一次\n# # \"schedule\": crontab(hour=\"*/3\", minute=12), # 每3小时的12分钟执行\n# \"args\": (16, 16)\n# },\n# },\n# )\n\n\n\nlogger = get_task_logger(__name__)\n\n\n@app.task(name='sum-of-two-numbers')\ndef add(x, y):\n time.sleep(10)\n logger.info('Adding {0} + {1}'.format(x, y))\n return x + y\n\n\n@app.task(bind=True, name='proj.tasks.add', default_retry_delay=30 * 60, acks_late=True) # retry in 30 minutes.\ndef add2(self, x, y):\n try:\n logger.info('Adding2 {0} + {1}'.format(x, y))\n time.sleep(10)\n return x + y\n except Exception as exc:\n raise self.retry(exc=exc, countdown=60) # override the default and\n # retry in 1 minute\n except MemoryError as exc:\n raise Reject(exc, requeue=False)\n except OSError as exc:\n if exc.errno == errno.ENOMEM:\n raise Reject(exc, requeue=False)\n\n\nif __name__ == '__main__':\n app.worker_main() # 直接运行\n","sub_path":"Celery_t/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"587529518","text":"def showCreateNewJobdialog(self):\r\n self.newJobDialog = QDialog()\r\n fbox = QFormLayout()\r\n l_conName=QLabel(\"Connection\")\r\n self.c_conName=QComboBox()\r\n for key in Json_evaluation.readJSON(filename=__connectionFile__):\r\n self.c_conName.addItem(key)\r\n fbox.addRow(l_conName,self.c_conName)\r\n self.l_jobName = QLabel(\"Name\")\r\n self.t_jobName = QLineEdit()\r\n fbox.addRow(self.l_jobName,self.t_jobName)\r\n self.l_description = QLabel(\"Description\")\r\n self.t_description = QLineEdit()\r\n fbox.addRow(self.l_description,self.t_description)\r\n l_startDate=QLabel(\"Start Date\")\r\n self.t_startDate=QDateEdit()\r\n self.t_startDate.setDate(QDate.currentDate())\r\n fbox.addRow(l_startDate,self.t_startDate)\r\n l_endDate=QLabel(\"End Date\")\r\n self.t_endDate=QDateEdit()\r\n self.t_endDate.setDate(QDate.currentDate())\r\n fbox.addRow(l_endDate,self.t_endDate)\r\n l_scheduledTime=QLabel(\"Schedule Time\")\r\n self.t_scheduledTime=QTimeEdit()\r\n\r\n fbox.addRow(l_scheduledTime,self.t_scheduledTime)\r\n l_interval=QLabel(\"Interval\")\r\n self.c_interval=QComboBox()\r\n self.c_interval.addItem(\"Daily\",1)\r\n self.c_interval.addItem(\"After One Day\",2)\r\n self.c_interval.addItem(\"After Two Day\",3)\r\n self.c_interval.addItem(\"After Three Day\",4)\r\n self.c_interval.addItem(\"Weekly\",7)\r\n self.c_interval.addItem(\"Month\",30)\r\n fbox.addRow(l_interval,self.c_interval)\r\n b_create=QPushButton(\"Create\")\r\n b_cancel=QPushButton(\"Cancel\")\r\n fbox.addRow(b_create,b_cancel)\r\n b_cancel.clicked.connect(self.newJobDialog.close)\r\n b_create.clicked.connect(partial(self.submitJob,dialog=self.newJobDialog,response=\"Job created successfully!!!\"))\r\n\r\n self.newJobDialog.setLayout(fbox)\r\n #b1.move(50,50)\r\n self.newJobDialog.setWindowTitle(\"Create New Job\")\r\n self.newJobDialog.setWindowModality(Qt.ApplicationModal)\r\n self.newJobDialog.exec_()\r\ndef submitJob(self,dialog,closeDialog=1,response=\"\"):\r\n try:\r\n if self.t_jobName.text()==\"\":\r\n self.testConAlert(response=\"Firstly enter Job name!!!!\")\r\n return 0\r\n job={self.t_jobName.text():{\"conName\":self.c_conName.currentText(),\"jobStatement\":\"\",\"interval\":self.c_interval.currentData(),\"scheuledTime\":self.t_scheduledTime.time().toString(\"HH:mm\"),\"description\":self.t_description.text(),\"type\":\"\",\"startDate\":self.t_startDate.date().toString(\"dd/MM/yyyy\"),\"endDate\":self.t_endDate.date().toString(\"dd/MM/yyyy\"),\"isActive\":1,\"lastRunDate\":\"-1\"}}\r\n Job.setJob(job)\r\n if response!=\"\":\r\n self.testConAlert(response=response)\r\n if closeDialog==1:\r\n dialog.close()\r\n except Exception as e:\r\n self.testConAlert(response=\"Something went wrong!!!!\")\r\n log(\"Error_Window_submitJob@\"+str(e))\r\n\r\n#*******************Manage Job Starts***********\r\ndef manageJobs(self):\r\n try:\r\n self.manageJobDialog = QDialog()\r\n lbox = QFormLayout()\r\n fbox=QFormLayout()\r\n vbox = QHBoxLayout()\r\n self.jobList = QListWidget(self)\r\n #items = ['Item %s' % (i + 1) for i in range(10)]\r\n data=Json_evaluation.readJSON(filename=__jobFile__)\r\n for con in data.keys():\r\n self.jobList.addItem(str(con))\r\n lbox.addRow(self.jobList)\r\n self.jobList.itemClicked.connect(self.getJobBykey)\r\n fbox = QFormLayout()\r\n l_conName=QLabel(\"Connection\")\r\n self.c_conName=QComboBox()\r\n for key in Json_evaluation.readJSON(filename=__connectionFile__):\r\n self.c_conName.addItem(key)\r\n fbox.addRow(l_conName,self.c_conName)\r\n self.l_jobName = QLabel(\"Name\")\r\n self.t_jobName = QLineEdit()\r\n fbox.addRow(self.l_jobName,self.t_jobName)\r\n self.l_description = QLabel(\"Description\")\r\n self.t_description = QLineEdit()\r\n fbox.addRow(self.l_description,self.t_description)\r\n l_startDate=QLabel(\"Start Date\")\r\n self.t_startDate=QDateEdit()\r\n self.t_startDate.setDate(QDate.currentDate())\r\n fbox.addRow(l_startDate,self.t_startDate)\r\n l_endDate=QLabel(\"End Date\")\r\n self.t_endDate=QDateEdit()\r\n self.t_endDate.setDate(QDate.currentDate())\r\n fbox.addRow(l_endDate,self.t_endDate)\r\n l_scheduledTime=QLabel(\"Schedule Time\")\r\n self.t_scheduledTime=QTimeEdit()\r\n\r\n fbox.addRow(l_scheduledTime,self.t_scheduledTime)\r\n l_interval=QLabel(\"Interval\")\r\n self.c_interval=QComboBox()\r\n self.c_interval.addItem(\"Daily\",1)\r\n self.c_interval.addItem(\"After One Day\",2)\r\n self.c_interval.addItem(\"After Two Day\",3)\r\n self.c_interval.addItem(\"After Three Day\",4)\r\n self.c_interval.addItem(\"Weekly\",7)\r\n self.c_interval.addItem(\"Month\",30)\r\n fbox.addRow(l_interval,self.c_interval)\r\n b_create=QPushButton(\"Update\")\r\n b_cancel=QPushButton(\"Delete\")\r\n self.b_addStep=QPushButton(\"Add Step\")\r\n self.b_addStep.setEnabled(False)\r\n self.b_addStep.clicked.connect(partial(self.newStepDialog_m,self.t_jobName))\r\n fbox.addRow(self.b_addStep)\r\n fbox.addRow(b_create,b_cancel)\r\n b_cancel.clicked.connect(self.deleteJob)\r\n b_create.clicked.connect(partial(self.submitJob,dialog=self.manageJobDialog,closeDialog=0,response=\"Job updated successfully!!!\"))\r\n fbox.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)\r\n\r\n vbox.addLayout(lbox)\r\n vbox.addLayout(fbox)\r\n self.manageJobDialog.setLayout(vbox)\r\n self.manageJobDialog.setWindowModality(Qt.ApplicationModal)\r\n self.manageJobDialog.setWindowTitle(\"Manage Jobs\")\r\n self.manageJobDialog.exec_()\r\n except Exception as e:\r\n log(\"Error_Window_manageJob@\"+str(e))\r\ndef deleteJob(self):\r\n try:\r\n key=str(self.t_jobName.text())\r\n if key!=\"\":\r\n Json_evaluation.removeJson(key=key,filename=__jobFile__)\r\n self.manageJobDialog.close()\r\n self.manageJobs()\r\n except Exception as e:\r\n self.testConAlert(response=\"Something went wrong!!!!\")\r\n log(\"Error_Window_deleteJob@\"+str(e))\r\ndef getJobBykey(self):\r\n try:\r\n key=self.jobList.currentItem().text()\r\n data=Json_evaluation.getJsonByKey(key=key,filename=__jobFile__)\r\n self.t_jobName.setText(key)\r\n self.c_conName.setCurrentIndex(self.c_conName.findText((data[\"conName\"])))\r\n self.t_description.setText(data[\"description\"])\r\n self.t_startDate.setDate(QDate.fromString(str(data[\"startDate\"]),\"dd/MM/yyyy\"))\r\n self.t_endDate.setDate(QDate.fromString(data[\"endDate\"],\"dd/MM/yyyy\"))\r\n self.c_interval.setCurrentIndex(self.c_interval.findData((data[\"interval\"])))\r\n self.t_scheduledTime.setTime(QTime.fromString(data[\"scheuledTime\"],\"HH:mm\"))\r\n self.b_addStep.setEnabled(True)\r\n\r\n except Exception as e:\r\n log(\"Error_Window_getJobBykey@\"+str(e))\r\n","sub_path":"JobGui.py","file_name":"JobGui.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"489696081","text":"import logging\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as stats\nfrom flask import g\ndef clean(df):\n g.before_shape = df.shape\n # rename cols\n df = col_fix(df)\n # remove duplicates\n df = remove_duplicates(df)\n # remove nulls\n df = remove_nulls(df)\n # remove outliers\n df = remove_outliers(df)\n # reset indexes\n df = df.reset_index(drop=True)\n g.memory = df.memory_usage(deep=True).sum()//1024\n g.after_shape = df.shape\n return df\n\ndef col_fix(df):\n return df.rename(columns=name_fix(df), inplace=False)\n\ndef name_fix(df):\n cols = list(df.columns)\n newCols = {}\n for col in cols:\n newCols[col] = col.lower().replace(' ', '_')\n return newCols\n\ndef remove_nulls(df):\n nulls = df.isnull().sum().sum()\n g.nulls = nulls\n return df.dropna()\n\ndef remove_duplicates(df):\n duplicates = df.duplicated().sum()\n g.duplicates = duplicates\n return df.drop_duplicates()\n\ndef remove_outliers(df):\n\n # to be added to df\n z_score_cols = []\n\n # to remove zcols in df\n original_cols = list(df.columns)\n\n # only find outliers or cols with numbers\n numbered_cols = list(df.select_dtypes(np.number).columns)\n for col in numbered_cols:\n col_zscore = col + '_zscore'\n df[col_zscore] = abs(stats.stats.zscore(df[col]))\n z_score_cols.append(col_zscore)\n\n before_rows = df.shape[0]\n # row is false when it contains zscore > 3\n condition = (df[z_score_cols] < 3).all(axis=1)\n df = df[condition]\n\n # remove zscore cols\n df = df[original_cols]\n outliers = before_rows - df.shape[0]\n g.outliers = outliers\n return df\n\ndef fix_target(target):\n return target.lower().replace(' ', '_')\n","sub_path":"cleaner.py","file_name":"cleaner.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"14484918","text":"import pyqtgraph as pg\n# from dolfin import Constant\n\nmap = {'x0':0, 'y0':0, 'x1':10018, 'y1':17946,\n 'cmap_x0':0, 'cmap_y0':0,\n 'cmap_x1':10018, 'cmap_y1':17946,\n 'proj_x0':-637925, 'proj_x1':864625,\n 'proj_y0':-657675, 'proj_y1':-3349425,\n 'cmap_proj_x0': -637925, 'cmap_proj_x1': 864625,\n 'cmap_proj_y0': -657675, 'cmap_proj_y1': -3349425}\n\ncolormaps = {'velocity': True,\n 'bed': False,\n 'smb': False,\n 'surface': False,\n 'thickness': False,\n 't2m': False\n }\n\nkeysPress = {'shift': False,\n 'ctrl': False,\n 'alt': False\n }\n\nglobalConstants = {'isPathIntLine': False,\n 'moveLine': False\n }\n\n\n\nrender = True\n\nskinnyBlackPlotPen = pg.mkPen(color=(0, 0, 0), width=1)\nwhitePlotPen = pg.mkPen(color=(255, 255, 255), width=2)\nblackPlotPen = pg.mkPen(color=( 0, 0, 0), width=2)\ngreyPlotPen = pg.mkPen(color=(200, 200, 200), width=2)\nredPlotPen = pg.mkPen(color=(100, 0, 0), width=2)\nbluePlotPen = pg.mkPen(color=( 0, 0, 255), width=2)\ngreenPlotPen = pg.mkPen(color=( 76, 153, 0), width=2)\npurplePlotPen = pg.mkPen(color=(102, 0, 204), width=2)\norangePlotPen = pg.mkPen(color=(255, 128, 0), width=2)\nbluePlotPen = pg.mkPen(color=( 0, 0, 255), width=2)\ntealPlotPen = pg.mkPen(color=( 0, 204, 204), width=2)\npinkPlotPen = pg.mkPen(color=(153, 0, 153), width=2)\n\nspatialRes = 1 # multiplied by 150 meters\n\ndataFileName = './data/GreenlandInBedCoord.h5'\ncmFileName = './data/dataCMValues.h5'\n\n\ndt_float = 5.0 #Time step\nthklim = 10.0\neps_reg = 1e-5 #Regularization parameter\n# dt = Constant(dt_float)\n# theta = Constant(0.5) #Crank-Nicholson parameter\n","sub_path":"helperFiles/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"556812826","text":"#!/usr/bin/env python\n\n# Capstone Python bindings, by Nguyen Anh Quynnh \n\nfrom capstone import *\nfrom capstone.x86 import *\n\nX86_CODE64 = \"\\x55\\x48\\x8b\\x05\\xb8\\x13\\x00\\x00\"\nX86_CODE16 = \"\\x8d\\x4c\\x32\\x08\\x01\\xd8\\x81\\xc6\\x34\\x12\\x00\\x00\\x05\\x23\\x01\\x00\\x00\\x36\\x8b\\x84\\x91\\x23\\x01\\x00\\x00\\x41\\x8d\\x84\\x39\\x89\\x67\\x00\\x00\\x8d\\x87\\x89\\x67\\x00\\x00\\xb4\\xc6\"\nX86_CODE32 = \"\\x8d\\x4c\\x32\\x08\\x01\\xd8\\x81\\xc6\\x34\\x12\\x00\\x00\\x05\\x23\\x01\\x00\\x00\\x36\\x8b\\x84\\x91\\x23\\x01\\x00\\x00\\x41\\x8d\\x84\\x39\\x89\\x67\\x00\\x00\\x8d\\x87\\x89\\x67\\x00\\x00\\xb4\\xc6\"\n\nall_tests = (\n (CS_ARCH_X86, CS_MODE_16, X86_CODE16, \"X86 16bit (Intel syntax)\", 0),\n (CS_ARCH_X86, CS_MODE_32, X86_CODE32, \"X86 32 (AT&T syntax)\", CS_OPT_SYNTAX_ATT),\n (CS_ARCH_X86, CS_MODE_32, X86_CODE32, \"X86 32 (Intel syntax)\", 0),\n (CS_ARCH_X86, CS_MODE_64, X86_CODE64, \"X86 64 (Intel syntax)\", 0),\n )\n\ndef to_hex(s):\n return \" \".join(\"0x\" + \"{0:x}\".format(ord(c)).zfill(2) for c in s) # <-- Python 3 is OK\n\ndef to_x(s):\n from struct import pack\n if not s: return '0'\n x = pack(\">q\", s).encode('hex')\n while x[0] == '0': x = x[1:]\n return x\n\ndef to_x_32(s):\n from struct import pack\n if not s: return '0'\n x = pack(\">i\", s).encode('hex')\n while x[0] == '0': x = x[1:]\n return x\n\n### Test class Cs\ndef test_class():\n def print_string_hex(comment, str):\n print(comment),\n for c in str:\n print(\"0x%02x\" %c),\n print\n\n def print_insn_detail(mode, insn):\n # print address, mnemonic and operands\n print(\"0x%x:\\t%s\\t%s\" %(insn.address, insn.mnemonic, insn.op_str))\n\n # print instruction prefix\n print_string_hex(\"\\tPrefix:\", insn.prefix)\n\n # print segment override (if applicable)\n if insn.segment != X86_REG_INVALID:\n print(\"\\tSegment override: %s\" %insn.reg_name(insn.segment))\n\n # print instruction's opcode\n print_string_hex(\"\\tOpcode:\", insn.opcode)\n\n # print operand's size, address size, displacement size & immediate size\n print(\"\\top_size: %u, addr_size: %u, disp_size: %u, imm_size: %u\" \\\n %(insn.op_size, insn.addr_size, insn.disp_size, insn.imm_size))\n\n # print modRM byte\n print(\"\\tmodrm: 0x%x\" %(insn.modrm))\n\n # print displacement value\n print(\"\\tdisp: 0x%s\" %to_x_32(insn.disp))\n\n # SIB is not available in 16-bit mode\n if (mode & CS_MODE_16 == 0):\n # print SIB byte\n print(\"\\tsib: 0x%x\" %(insn.sib))\n if (insn.sib):\n print(\"\\tsib_index: %s, sib_scale: %d, sib_base: %s\" % (insn.reg_name(insn.sib_index), insn.sib_scale, insn.reg_name(insn.sib_base)))\n\n count = insn.op_count(X86_OP_IMM)\n if count > 0:\n print(\"\\timm_count: %u\" %count)\n for i in xrange(count):\n op = insn.op_find(X86_OP_IMM, i + 1)\n print(\"\\t\\timms[%u]: 0x%s\" %(i+1, to_x(op.imm)))\n\n if len(insn.operands) > 0:\n print(\"\\top_count: %u\" %len(insn.operands))\n c = -1\n for i in insn.operands:\n c += 1\n if i.type == X86_OP_REG:\n print(\"\\t\\toperands[%u].type: REG = %s\" %(c, insn.reg_name(i.reg)))\n if i.type == X86_OP_IMM:\n print(\"\\t\\toperands[%u].type: IMM = 0x%s\" %(c, to_x(i.imm)))\n if i.type == X86_OP_FP:\n print(\"\\t\\toperands[%u].type: FP = %f\" %(c, i.fp))\n if i.type == X86_OP_MEM:\n print(\"\\t\\toperands[%u].type: MEM\" %c)\n if i.mem.base != 0:\n print(\"\\t\\t\\toperands[%u].mem.base: REG = %s\" %(c, insn.reg_name(i.mem.base)))\n if i.mem.index != 0:\n print(\"\\t\\t\\toperands[%u].mem.index: REG = %s\" %(c, insn.reg_name(i.mem.index)))\n if i.mem.scale != 1:\n print(\"\\t\\t\\toperands[%u].mem.scale: %u\" %(c, i.mem.scale))\n if i.mem.disp != 0:\n print(\"\\t\\t\\toperands[%u].mem.disp: 0x%s\" %(c, to_x(i.mem.disp)))\n\n\n for (arch, mode, code, comment, syntax) in all_tests:\n print(\"*\" * 16)\n print(\"Platform: %s\" %comment)\n print(\"Code: %s\" % to_hex(code))\n print(\"Disasm:\")\n\n try:\n md = Cs(arch, mode)\n md.detail = True\n\n if syntax != 0:\n md.syntax = syntax\n\n for insn in md.disasm(code, 0x1000):\n print_insn_detail(mode, insn)\n print\n print (\"0x%x:\\n\" % (insn.address + insn.size))\n except CsError as e:\n print(\"ERROR: %s\" %e)\n\n\ntest_class()\n","sub_path":"bindings/python/test_x86.py","file_name":"test_x86.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"499084908","text":"#New version of the code for cartpole \"improved\"\n\nimport gym\nimport random\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import RMSprop,Adam\nfrom keras import optimizers\nfrom collections import deque\nimport copy\nimport matplotlib.pyplot as plt\n\n#The number of games must be high enough to observe the variation and see if there is a permanent state\nnb_games=100000\n#The best learning rate is 0.0001\n#I've tried others values and the result isn't as good as this value\n#learning_rate=0.002\nlearning_rate=0.0001\n#I've tried diffrent batch sizes as 32, 64, 128,... and I've found out that 64 is giving the best results\nbatch_size=64\nrate=1.0\n#rate=0.7\ngamma=0.95\n\n#We define an agent that learn from the environment by interacting with it\n#we get observations after each of it's actions on the environment\n#we store those experiences so our agent could learn from its mistakes\nclass my_agent:\n #The init funcion is an initialization function that calls the \"myNN\" function which builds our neural network\n #it also defines two constant values, the input and output sizes of our neural network\n def __init__(self, input_size,output_size):\n self.input_size=input_size\n self.output_size=output_size\n self.model=self.myNN()\n\n #Defining the neural network, fixed number of neurones for the input and output layers\n #For different number of neurons and different number of hidden layer, the results are not as good as the ones\n #provided with this specific modal, others activations functions as well as optimizers and losses have been tested\n #better results have been found with the modal bellow\n def myNN(self):\n model=Sequential()\n # 4 inputs representings the observations\n model.add(Dense(30,input_dim=self.input_size,activation='relu'))\n model.add(Dense(30,activation='relu'))\n #model.add(Dense(20,activation='relu'))\n # 2 outputs representing representing 0 and 1 (left, right)\n model.add(Dense(self.output_size,activation='linear'))\n model.compile(loss='mse',optimizer=Adam(lr=learning_rate))\n return model\n \n #The action can be either 0 or 1\n def agent_action(self, state):\n predict_val=self.model.predict(state)\n return np.argmax(predict_val[0])\n\n\n #This function is used to train the neural network bases on the memory(the previous experiencies or actions it had)\n def replay(self):\n minibatch = random.sample(my_memory,batch_size)\n \n for state, action, reward, futur_state, done in minibatch:\n target = reward\n if not done:\n #target=best_reward\n target = reward + gamma * np.amax(self.model.predict(futur_state)[0]) \n target_f = self.model.predict(state)\n target_f[0][action] = target\n #the neural network will predict the reward given a certain state\n # approximate the output based on the input\n self.model.fit(state, target_f, epochs=1, verbose=0)\n\n \n\n \nif __name__==\"__main__\":\n #my_memory is the memory in which we store the previous experiences\n #the size of the memory is fixed to 1000 in this case so the first experiencies are removed sequentially\n #we get better results when we remove some of the previous experiences and keep the most recent ones\n my_memory=deque(maxlen=1000)\n #the decision memory is the memory in which we store the last 100 results so we can decide if the average of those 100\n #exepriences is good enough to consider that our agent has learned\n decision_memory=deque(maxlen=100)\n #data memories are memories in which we store the data to be used for our plots\n data=[]\n data2=[]\n #we decide which environment is to be used, in this case it's CartPole\n env = gym.make('CartPole-v1')\n #the input_size is the number of observations we get from our environment, in this case it's 4\n #cart position, cart velocity, pole angle, pole velocity\n input_size = env.observation_space.shape[0]\n #the output size is the number of actions we could make to interact with the environment,\n # in this case we have 2 actions, moving right or moving left\n output_size = env.action_space.n\n #we initialize our agent with the input and output sizes\n agent=my_agent(input_size,output_size)\n #we initialize done with false, it becomes true when the game ends\n done=False\n #we initialize enough_data with 0, it becomes 1 when we store enough data (data>batch_size) to begin the training\n enough_data=0\n best_reward=0\n \n\n for i in range(nb_games):\n # Obtain an initial observation of the environment\n state=env.reset()\n state=np.reshape(state,[1,input_size])\n reward_sum=0\n reward_avg=0\n #reward=0\n \n for t in range(1000):\n reward=0\n #env.render()\n #at first our agent act randomly then when it start to learn it acts randomly occasionaly\n if(i<80) or np.random.rand()batch_size:\n enough_data=1 \n \n\n #reward=(reward -5) if done else (reward+1)\n #All the actions are stored into a memory, to be used afterwise for the training step\n my_memory.append((state,action,reward,futur_state,done))\n state=futur_state\n \n \n if done:\n reward=reward-10\n print(\"Game number : {}/{},score: {},reward:{},best reward:{}\" .format(i,nb_games,t,reward,best_reward))\n decision_memory.append(t)\n data.append(t)\n if reward>best_reward:\n best_reward=reward\n break\n \n if i>100: \n copy_mem=copy.deepcopy(decision_memory)\n for j in range(99):\n reward_sum = reward_sum + copy_mem.pop()\n \n \n reward_avg=reward_sum/100\n data2.append(reward_avg)\n\n \n if reward_avg >= 195.0:\n print(\"\\n Problem solved, average reward :\", reward_avg)\n #break\n \n\n \n #If we have enough data we can start the training\n if enough_data==1:\n agent.replay()\n \n\n\n\n","sub_path":"CartPole_improved.py","file_name":"CartPole_improved.py","file_ext":"py","file_size_in_byte":6992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"245902196","text":"# -*- coding: utf-8 -*-\n#python3.x\nimport json\nimport urllib\nfrom urllib.error import URLError, HTTPError\nimport urllib.parse\nimport urllib.request\nimport socket \nimport time\n\nimport random\nimport hashlib\n\nsocket.setdefaulttimeout(20) # 设置socket层的超时时间为20秒\nclass MonError(Exception):\n pass\n\n\n'''从文本中读取数据进行翻译'''\ndef Granslate(inputFile, outFile,srcLang, tgtLang,count):\n\n fin = open(inputFile,'r',encoding='utf-8') #以读的方式打开输入文件#以写的方式代开输出文件\n\n i = 0\n for eachLine in fin: #按行读入文件\n fout = open(outFile, 'a',encoding='utf-8')\n line = eachLine.strip() #去除每行首尾可能的空格等\n\n i += 1\n \n if(i >= count):\n# appid = '20160624000023898'\n# secretKey = '9rI5P3RVxnEssULDS6EA'\n# \n appid= '20180731000190551'\n secretKey = 'jqFfs9aNYE_vEbI1Cvoj' \n \n myurl = 'https://api.fanyi.baidu.com/api/trans/vip/translate'\n q = line\n fromLang = srcLang\n toLang = tgtLang\n salt = random.randint(32768, 65536)\n \n sign = appid+q+str(salt)+secretKey\n m1 = hashlib.md5()\n m1.update(sign.encode('utf-8'))\n sign = m1.hexdigest()\n myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign\n try:\n resultPage = urllib.request.urlopen(myurl) #调用百度翻译API进行批量翻译\n resultJason = resultPage.read().decode('utf-8') #取得翻译的结果,翻译的结果是json格式\n resultPage.close()\n js = None\n try:\n js = json.loads(resultJason) #将json格式的结果转换成Python的字典结构\n except Exception as e:\n print ('loads Json error.')\n print (e)\n continue\n \n if 'trans_result' in js:\n getText = js[\"trans_result\"][0][\"dst\"] #取得翻译后的文本结果\n fout.write(getText.encode(\"utf-8\").decode(\"utf-8\")+'\\n')\n print ('baidu ',i,'条语句翻译完成并写入文件.')\n elif 'error_code' in js:\n errorCodestr = js['error_code']\n errorCode = int(errorCodestr)\n if(errorCode ==52000):\n raise MonError('成功')\n elif(errorCode ==52001 ):\n raise MonError(' 52001\t请求超时\t重试')\n elif(errorCode == 52002):\n raise MonError(' 52002\t系统错误\t重试')\n elif(errorCode == 52003):\n raise MonError(' 52003\t未授权用户\t检查您的 appid 是否正确,或者服务是否开通')\n elif(errorCode == 54000):\n raise MonError(' 54000\t必填参数为空\t检查是否少传参数')\n elif(errorCode == 54001):\n raise MonError(' 54001\t签名错误\t请检查您的签名生成方法')\n elif(errorCode == 54003):\n raise MonError(' 54003\t访问频率受限\t请降低您的调用频率')\n elif(errorCode == 54004):\n raise MonError(' 54004\t账户余额不足\t请前往管理控制平台为账户充值')\n elif(errorCode == 54005):\n raise MonError(' 54005\t长query请求频繁\t请降低长query的发送频率,3s后再试')\n elif(errorCode == 58000):\n raise MonError(' 58000\t客户端IP非法\t检查个人资料里填写的 IP地址 是否正确,可前往管理控制平台修改,IP限制,IP可留空') \n elif(errorCode == 58001):\n raise MonError(' 58001\t译文语言方向不支持\t检查译文语言是否在语言列表里')\n else:\n print (errorCode)\n raise MonError(\"未知错误!\")\n else:\n raise MonError(\"未知传回参数!\")\n except Exception as e:\n print (e)\n print (' 翻译遭遇异常,已停止')\n break\n \nif __name__ == '__main__':\n #srctxt, tgttxt, srclanguage,tgtlanguage\n print (\"--------------------百度翻译--------------------\")\n i = 0 + 1\n# Granslate(r'C:\\Users\\Administrator\\Desktop\\corpus\\bien\\baidu\\en_v5.txt', r'C:\\Users\\Administrator\\Desktop\\corpus\\bien\\baidu\\zh_baidu_'+str(i)+'.txt','en','zh',i)\n Granslate(r'C:\\Users\\Administrator\\Desktop\\corpus\\bien\\baidu\\test.txt', r'C:\\Users\\Administrator\\Desktop\\corpus\\bien\\baidu\\test_'+str(i)+'.txt','en','zh',i)\n \n \n print (\"--------------------百度翻译结束--------------------\")","sub_path":"pythonToGetTranslation/api/baidu.py","file_name":"baidu.py","file_ext":"py","file_size_in_byte":5566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"382152285","text":"# Copyright (c) 2021, NVIDIA CORPORATION. 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.\nfrom model_navigator.kubernetes import helm\n\n\nclass Service(helm.Service):\n def data(self):\n service = {\n \"apiVersion\": \"v1\",\n \"kind\": \"Service\",\n }\n\n metadata = {\n \"name\": '{{ template \"selector.fullname\" . }}',\n \"namespace\": \"{{ .Release.Namespace }}\",\n \"labels\": {\n \"app\": '{{ template \"selector.name\" . }}',\n \"chart\": '{{template \"selector.chart\" . }}',\n \"release\": \"{{ .Release.Name }}\",\n \"heritage\": \"{{ .Release.Service }}\",\n },\n }\n\n spec = {\n \"type\": \"{{ .Values.service.type }}\",\n \"ports\": [\n {\"port\": 8000, \"targetPort\": 8000, \"name\": \"http\"},\n {\"port\": 8001, \"targetPort\": 8001, \"name\": \"grpc\"},\n {\"port\": 8002, \"targetPort\": 8002, \"name\": \"metrics\"},\n ],\n \"selector\": {\n \"app\": '{{ template \"selector.name\" . }}',\n \"release\": \"{{ .Release.Name }}\",\n },\n }\n\n service[\"metadata\"] = metadata\n service[\"spec\"] = spec\n\n return service\n","sub_path":"model_navigator/kubernetes/inference/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"619542041","text":"from pathlib import Path\n\n\nclass PyogPath(object):\n\n def __init__(self, app):\n self.app = app\n\n self.base = Path(\".\")\n\n self.themes = self.base / Path(\"themes\")\n self.theme = self.themes / self.app.config['theme']\n assert self.theme.exists() is True, \"theme folder was not found\"\n self.theme_static = self.theme / \"static\"\n self.theme_layout = self.theme / \"layout\"\n\n self.real_root = self.app.config.get(\"root\", \"\")\n if self.real_root[0] == \"/\":\n self.real_root = self.real_root[1:]\n self.real_root = Path(self.real_root)\n if self.real_root == Path(\".\"):\n self.real_root = \"\"\n else:\n self.real_root = str(self.root)\n\n self.root = \"\"\n self.public_folder = Path(self.app.config.get(\"public\", \"public\"))\n\n self.source_base = Path(\".\")\n self.source = self.source_base / Path(\"source\")\n self.source_posts = self.source / \"_posts\"\n self.public = self.base / Path(self.public_folder)\n\n if self.app.config.get(\"multiLangs\", False):\n self.source_base = Path(\"sources\")\n default_lang = self.app.config.get('lang', 'en')\n self.current_lang = default_lang\n self.change_lang(default_lang)\n\n def change_lang(self, lang):\n self.current_lang = lang\n self.root = f\"{self.real_root}/{lang}\"\n if self.root[0] == \"/\":\n self.root = self.root[1:]\n self.source = self.source_base / Path(f\"source_{lang}\")\n self.source_posts = self.source / \"_posts\"\n self.public = self.base / Path(self.public_folder) / lang\n","sub_path":"pyog/models/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72523854","text":"#!/usr/bin/env python\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\"\"\"\nEin StandartNnSuit benutzt ein Nn (eine nnModelFn) und eine Funktion um den Output-Vector des Nns zu interpretieren.\nEr dient dazu um Funktionen wie trian, eval und classify bzw. predict auf das Nn anzuwenden, die Ergebnisse zu speichern,\nzu loggen und für das TensorBoard zugänglich zu machen.\n\"\"\"\n\nfrom State_Component.State.State import State\n\nimport tensorflow as tf\n\nclass StandartNnSuit:\n\n def __init__(self, nnModelFn, preditcionToOutputFn, modelDir = \"/tmp/nnModel\", modelParams = {\"learning_rate\": 0.001}\n):\n \"\"\"\n Constructor, initialisiert Membervariablen.\n\n :param nnModelFn : function Ein CnnModel mit den Methoden train, predict, evaluate.\n :param preditcionToOutputFn : function Eine Funktion um den Output der nnModelFn zu interpretieren,\n :param modelDir : string Pfad unter welchem das trainierte nnModel gespeichert wird.\n \"\"\"\n # Set model params\n\n #Setting up the Loggers\n tf.logging.set_verbosity(tf.logging.INFO)\n self.__logger = State().getLogger(\"Experiment_Executor_Component_Logger\")\n\n #The Function to interprete the Classification Vector\n self.preditcionToOutputFn = preditcionToOutputFn\n\n #The Cnn to be trained and to classify the inputs\n self.__nnClassifier = tf.estimator.Estimator(\n model_fn=nnModelFn, model_dir=modelDir, params=modelParams)\n\n def predict(self, inputData, batch_size):\n \"\"\"\n Bereitet die Inputdaten für das neuronale Netz vor und predicted mit diesem den Input.\n\n :param inputData : Eine Mat welche den zu klassifizierenden Input enthält.\n :return: predictedClass : Die Prediction welche durch die preditcionToOutputFn bestimmt wird.\n \"\"\"\n self.__logger.info(\"Starting classify()\", \"StandartNnSuit:classify\")\n\n #Classify Input with the trained model\n predictInputFn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": inputData},\n num_epochs=1,\n batch_size=batch_size,\n shuffle=False)\n\n predictions = list(self.__nnClassifier.predict(input_fn=predictInputFn))\n\n self.__logger.info(\"Finished classify()\", \"StandartNnSuit:classify\")\n\n return self.preditcionToOutputFn(predictions)\n\n def train(self, trainData, trainLabels, steps, batch_size):\n \"\"\"\n Bereitet die Inputdaten für das neuronale Netz vor und trainiert dieses mit den Daten.\n\n :param trainData : Eine Array von Mats welche traineirt werden sollen.\n :param trainLabels : Eine Array von Labels für die Mats von trainData (Gleiche Länge gleiche Sortierung)\n :param steps : Anzahl der Trainingsschritte\n \"\"\"\n self.__logger.info(\"Starting train()\", \"StandartNnSuit:train\")\n\n #Train the model\n trainInputFn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": trainData},\n y=trainLabels,\n batch_size=batch_size,\n num_epochs=None,\n shuffle=True)\n\n self.__nnClassifier.train(\n input_fn=trainInputFn,\n steps=steps)\n # hooks=[self.__loggingHook])\n\n self.__logger.info(\"Finished train()\", \"StandartNnSuit:train\")\n\n def eval(self, evalData, evalLabels, batch_size):\n \"\"\"\n Bereitet die Inputdaten für das neuronale Netz vor und evaluiert dieses mit den Daten.\n\n :param evalData : Eine Array von Mats mit welchen evaluiert werden sollen.\n :param evalLabels : Eine Array von Labels für die Mats von evalData (Gleiche Länge gleiche Sortierung)\n \"\"\"\n self.__logger.info(\"Starting eval()\", \"StandartNnSuit:eval\")\n\n #Evaluate the model and print results\n evalInputFn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": evalData},\n y=evalLabels,\n num_epochs=1,\n batch_size = batch_size,\n shuffle=False)\n evalResults = self.__nnClassifier.evaluate(input_fn=evalInputFn)\n\n self.__logger.info(\"Finished eval()\", \"StandartNnSuit:eval\")\n return evalResults","sub_path":"DeepLearningProject/hs_robot_demonstrat/NeuralRobotControl/RobotController_Component/RobotBrain/StandartNnSuit.py","file_name":"StandartNnSuit.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"243102793","text":"#Desafio: Qual é o maior e o menor desses três valores.\n#Minha solução ------------------------------------------------------>\nn1 = int(input('1º Número:'))\nn2 = int(input('2º Número:'))\nn3 = int(input('3º Número:'))\naux1 = 0\naux2 = 0\nif n1 > n2:\n aux1 = n1\n aux2 = n2\nelse:\n aux1 = n2\n aux2 = n1\n\nif aux1 > n3:\n print('Maior Valor: {}'.format(aux1))\nelse:\n print('Maior Valor: {}'.format(n3))\n\nif aux2 < n3:\n print('Menor Valor: {}'.format(aux2))\nelse:\n print('Menor Valor: {}'.format(n3))\n\n#Guanabara------------------------------------------------>\n#a = int(input('Primeiro valor: '))\n#b = int(input('Segundo valor: '))\n#c = int(input('Terceiro valor: '))\n#menor = a\n#if b < a and b < c:\n# menor = b\n#if c < a and c < b:\n# menor = c\n#maior = a\n#if b > a and b > c:\n# maior = b\n#if c > a and c > b:\n# maior = c\n#print('O menor valor digitado foi: {}'.format(menor))\n#print('O maior valor digitado foi: {}'.format(maior))","sub_path":"Desafios/Ex033.py","file_name":"Ex033.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"65634902","text":"'''\ndfs 탐색으로 몇개으 그래프가 있는지 탐색\nfor문으로 1번씩 방문하면 된다. 방문한곳은 넘어가기\n'''\nn=3\ncomputers=[[1, 1, 0], [1, 1, 1], [0, 1, 1]]\n\ndef dfs(n,computers,visited):\n s=[n]\n while s:\n node = s.pop()\n \n for j in range(len(computers)):\n if computers[node][j] == 0:\n continue\n if visited[j]:\n continue\n visited[j] = 1\n s.append(j)\n\n\n\ndef solution(n, computers):\n visited=[0]*(n+1)\n answer=0\n for i in range(n):\n if not visited[i]:\n dfs(i,computers,visited)\n answer+=1\n return answer\n\nprint(solution(n, computers))","sub_path":"Programmers/Python3/lv3/네트워크.py","file_name":"네트워크.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"551936440","text":"import hashlib\n\ndef readdb(fn):\n db = {}\n try:\n with open(fn) as fh:\n for entry in fh:\n # Skip empty lines\n if len(entry) <= 1:\n continue\n hash, name = entry.split(None, 1)\n db[hash] = name[:-1]\n except IOError:\n pass\n return db\n\ndef writedb(fn, db):\n with open(fn, 'w') as fh:\n for hash, name in db.items():\n fh.write(hash + \" \" + name + \"\\n\")\n\ndef get_hash(fn):\n hash = hashlib.sha256()\n with open(fn) as fh:\n for chunk in iter((lambda:fh.read(16*256)),''):\n hash.update(chunk)\n return hash.hexdigest()\n\n","sub_path":"photologue/utils/hashdb.py","file_name":"hashdb.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"280554827","text":"\r\n\r\nclass bullish():\r\n \r\n import pandas as pd\r\n import numpy as np\r\n import yfinance as yf\r\n\r\n \r\n\r\n final = []\r\n cryptos = ['BTC-USD','ETH-USD','USDT-USD','ADA-USD','BNB-USD','XRP-USD','DOGE-USD',\r\n 'USDC-USD','MATIC-USD','ETC-USD','EOS-USD','LTC-USD']\r\n # stocks = ['ITC.NS','HAVELLS.NS']\r\n # intervals = 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo\r\n for i in cryptos:\r\n tickerData = yf.Ticker(i)\r\n tickerDf = tickerData.history(period = '30d',interval='1d')\r\n df = tickerDf\r\n df = df.drop(['Volume','Dividends','Stock Splits'],axis=1)\r\n df = df.round(2)\r\n df['Name'] = i\r\n data = df.copy()\r\n # df = df.iloc[-2:,:]\r\n bullish = df[(df['Close'].shift(1) < df['Open'].shift(1)) &\r\n (df['Close'] > df['Open'].shift(1)) &\r\n (df['Open'] < df['Close'].shift(1)) &\r\n (df['High'] > df['High'].shift(1)) &\r\n (df['Low'] < df['Low'].shift(1))\r\n ]\r\n\r\n final.append(bullish)\r\n \r\n final = pd.concat(final)\r\n final['Pattern'] = 'Bullish Engulfing'\r\n bullish_engulfing = final.copy() ","sub_path":"patterns/bullish_engulfing.py","file_name":"bullish_engulfing.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74809409","text":"__author__ = 'maskari'\nfrom PositionalList import PositionalList\n\n\nclass InsertionSort:\n\n def insertion_sort(self, pl):\n \"\"\"\n :param pl: positional list to be sorted\n :return: sorted positional list\n \"\"\"\n if len(pl) <= 1:\n return\n\n if not isinstance(pl, PositionalList):\n return\n\n marker = pl.first()\n while marker != pl.last():\n pivot = pl.after(marker)\n value = pivot.element()\n if value > marker.element():\n marker = pivot\n else:\n walk = marker\n while walk != pl.first() and pl.before(walk).element() > value:\n walk = pl.before(walk)\n pl.delete(pivot)\n pl.add_before(walk, value)\n\nif __name__ == '__main__':\n pl = PositionalList()\n for k in range(10, 0, -2):\n pl.add_last(k)\n\n print(pl)\n\n sorter = InsertionSort()\n sorter.insertion_sort(pl)\n\n print(pl)","sub_path":"python/LinkedList/InsertionSort.py","file_name":"InsertionSort.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"217421516","text":"from django.db import models\n\n\nclass Blog(models.Model):\n id = models.AutoField(primary_key=True)\n\n description = models.TextField(\n null=True,\n blank=True\n )\n files = models.FileField(\n upload_to='blog',\n null=True,\n blank=True,\n )\n # separate with ;\n tags = models.TextField(\n null=False,\n blank=False\n )\n title = models.TextField(\n null=False,\n blank=False\n )\n\n content = models.TextField(\n null=False,\n blank=False\n )\n api_url = models.URLField(\n null=True,\n blank=True,\n )\n\n html_rapport = models.FileField(\n upload_to='rapports',\n null=True,\n blank=True,\n )\n\n\nclass IdeaStatus(models.Model):\n name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.name\n\n\nclass Idea(models.Model):\n id = models.AutoField(primary_key=True)\n\n date = models.DateField(\n auto_now_add=True,\n )\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n title = models.TextField(\n null=False,\n blank=False\n )\n\n status = models.ForeignKey('IdeaStatus',\n verbose_name='Idea Status',\n on_delete=models.SET_NULL,\n null=True,\n blank=True)\n\n description = models.TextField(\n null=True,\n blank=True\n )\n files = models.FileField(\n upload_to='idea',\n null=True,\n blank=True,\n )\n email = models.EmailField(\n null=False,\n blank=False,\n default=\"\"\n )\n app_url = models.URLField(\n null=True,\n blank=True,\n )\n\n likes = models.IntegerField(\n null=False,\n default=0,\n blank=True\n )\n\n @property\n def avatar(self):\n return self.email[0].upper() if self.email else \"\"\n\n def __str__(self):\n return self.title\n\n\nclass Comment(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n email = models.EmailField(\n null=False,\n blank=False,\n default=\"\"\n )\n\n message = models.TextField(\n null=True,\n blank=True\n )\n\n idea = models.ForeignKey(Idea, on_delete=models.CASCADE)\n","sub_path":"backend/idea/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"66234767","text":"import logging\nfrom typing import Optional, Dict\n\nfrom pacco.manager.utils.cache import Cache\n\n\nclass PackageBinaryAbstract:\n \"\"\"\n Represent the existence of a package (e.g. openssl) in the package manager\n This class is the interface class with the expected behavior defined below.\n \"\"\"\n\n def __init__(self, registry_name: Optional[str] = None, assignment: Optional[Dict[str, str]] = None):\n self.registry_name = registry_name\n self.cache = Cache()\n self.assignment = assignment\n self.cache_enabled = bool(self.registry_name) and bool(self.assignment)\n\n def __repr__(self):\n return \"PackageBinaryObject\"\n\n def download_content(self, download_dir_path: str, fresh_download: Optional[bool] = False) -> None:\n \"\"\"\n Download content of uploaded binary from the remote to the ``download_dir_path``\n\n Args:\n download_dir_path: the destination of download\n fresh_download: if true, will not use cache\n \"\"\"\n if self.cache_enabled and (not fresh_download) and \\\n self.cache.download_from_cache(self.registry_name, self.assignment, download_dir_path):\n logging.info(\"Done, used cache to download (not downloading from server)\")\n return\n logging.info(\"Downloading from server\")\n self.fresh_download(download_dir_path)\n logging.info(\"Finish downloading\")\n if self.cache_enabled:\n logging.info(\"Save downloaded file to cache\")\n self.cache.upload_to_cache(self.registry_name, self.assignment, download_dir_path)\n\n def upload_content(self, dir_path: str) -> None:\n \"\"\"\n Remove the previous binary and upload the content of ``dir_path`` to the remote.\n\n Args:\n dir_path: the path to the directory to be uploaded\n \"\"\"\n self.upload_dir(dir_path)\n logging.info(\"Finish uploading\")\n if self.cache_enabled:\n logging.info(\"Saving to cache\")\n self.cache.upload_to_cache(self.registry_name, self.assignment, dir_path)\n logging.info(\"Saved in cache\")\n\n def fresh_download(self, download_dir_path: str) -> None:\n raise NotImplementedError()\n\n def upload_dir(self, dir_path: str) -> None:\n raise NotImplementedError()\n","sub_path":"pacco/manager/abstracts/package_binary.py","file_name":"package_binary.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"373514922","text":"from flask import jsonify, request\nfrom . import api\nfrom .. import db\nfrom ..models import Order, Customer\n\n\n@api.route('/orders/', methods=['GET'])\ndef get_orders():\n return jsonify({'orders': [order.get_url() for order in Order.query.all()]})\n\n@api.route('/customers//orders/', methods=['GET'])\ndef get_customer_orders(id):\n customer = Customer.query.get_or_404(id)\n return jsonify({'orders': [order.get_url() for order in\n customer.orders.all()]})\n\n@api.route('/orders/', methods=['GET'])\ndef get_order(id):\n return jsonify(Order.query.get_or_404(id).export_data())\n\n@api.route('/customers//orders/', methods=['POST'])\ndef new_customer_order(id):\n customer = Customer.query.get_or_404(id)\n order = Order(customer=customer)\n order.import_data(request.json)\n db.session.add(order)\n db.session.commit()\n return jsonify({}), 201, {'Location': order.get_url()}\n\n@api.route('/orders/', methods=['PUT'])\ndef edit_order(id):\n order = Order.query.get_or_404(id)\n order.import_data(request.json)\n db.session.add(order)\n db.session.commit()\n return jsonify({})\n\n@api.route('/orders/', methods=['DELETE'])\ndef delete_order(id):\n order = Order.query.get_or_404(id)\n db.session.delete(order)\n db.session.commit()\n return jsonify({})\n","sub_path":"rest_api_flask/flask-apis-video-0.10/orders/app/api_v1/orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"78058711","text":"from bson.objectid import ObjectId\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom .config import urls_db\n\ndef validate_object_id(id_: str):\n try:\n _id = ObjectId(id_)\n except Exception:\n raise HTTPException(status_code=400)\n return _id\n\n\nasync def _get_or_404(id_: str):\n _id = validate_object_id(id_)\n link = await urls_db.find_one({\"_id\": _id})\n if link:\n return link\n else:\n raise HTTPException(status_code=404, detail=\"Link not found\")\n\n\ndef fix_id(link):\n link[\"id_\"] = str(link[\"_id\"])\n return link\n","sub_path":"backend/api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"355028983","text":"import numpy as np\n\ndef createFourOnTheFloor(bpm, nb_beats, sr, sample):\n\n # 60s/min * min/beats(1/bpm) * sr * nb_beats == seconds/beat * samples/second * nb_beats\n # == samples/beat * nb_beats\n\n samples_per_beat = 60.0 / bpm * sr\n total_loop_len = int(samples_per_beat * nb_beats)\n\n mixing_bed = np.zeros(int(total_loop_len))\n # print(\"[createFourOnTheFloor] Size of mixing bed: \" + str(len(mixing_bed)))\n\n offset = 0\n i = 0\n while (offset < total_loop_len):\n\n # print(\"offset: \" + str(offset) + \" i: \" + str(i) + \" \" + str(float(offset)/sr))\n if(offset + len(sample) > total_loop_len):\n mixing_bed[offset:total_loop_len - 1] += sample[0:total_loop_len - offset - 1]\n break\n\n mixing_bed[offset:offset + len(sample)] += sample\n offset += int(samples_per_beat)\n i += 1\n\n return mixing_bed","sub_path":"Riddim/riddim_utils.py","file_name":"riddim_utils.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"84388518","text":"from flask import *\nimport mlab\nfrom models.service import Service\n\n\napp = Flask(__name__)\nmlab.connect()\n\n\n@app.route ('/admin')\ndef admin():\n all_service = Service.objects()\n return render_template('admin.html',all_service = all_service)\n\n\n@app.route ('/delete/')\ndef delete(service_id):\n xoa = Service.objects().get(id = service_id)\n if xoa is None:\n return (\"Service not found\")\n else:\n xoa.delete()\n return redirect(url_for('admin'))\n\n\n@app.route('/new_service',methods=[\"GET\",\"POST\"])\ndef new_service():\n if request.method == \"GET\":\n return render_template('new_service.html')\n elif request.method == \"POST\":\n form = request.form \n new_service = Service(\n name = form['name'],\n yob = form['yob'],\n gender = form['gender'],\n height = form['height'],\n address = form['address'],\n phone = form['phone'],\n description = form['description'],\n measurements = form['measurements']\n )\n \n new_service.save()\n return redirect(url_for('admin'))\n\n\n@app.route('/search')\ndef search():\n all_service = Service.objects()\n return render_template('search.html',all_service = all_service)\n \n\n@app.route('/detail/')\ndef detail(service_id):\n all_service = Service.objects()\n id_to_get = Service.objects().get(id = service_id)\n return render_template('detail.html',id_to_get = id_to_get)\n\n@app.route('/update/', methods = [\"GET\",\"POST\"])\ndef update(service_id):\n if request.method == \"GET\":\n id_to_get = Service.objects().get(id = service_id)\n return render_template('update-service.html',id_to_get = id_to_get)\n elif request.method == \"POST\":\n form = request.form\n id_to_get = Service.objects().get(id = service_id)\n id_to_get.update (set__name=form['name'],\n set__yob=form['yob'],\n set__gender=form['gender'],\n set__height=form['height'],\n set__phone=form['phone'],\n set__description=form['description'],\n set__measurements=form['measurements'],\n set_avatar=form['avatar']\n )\n id_to_get.reload()\n return redirect(url_for('admin')) \n\n@app.route('/sign-in', methods=['GET','POST'])\ndef signin():\n if request.method =='GET':\n return render_template('signin.html')\n elif request.method == 'POST':\n form = request.form\n fullname = form['username']\n email = form['email']\n username = form['username']\n password = form['password']\n if fullname == '' or email == '' or username =='' or password =='':\n return render_template('signin.html') + \"Registered failed\"\n else:\n new_user = User(\n fullname= fullname,\n email = email,\n username = username,\n password = password\n )\n new_user.save()\n return render_template('signin.html') + \"Registered successfully\"\n \n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"web02+3/homework2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"87910975","text":"import datetime\nfrom os import makedirs, environ\nimport os.path\nimport unittest\nfrom shutil import copy, rmtree\n\n# It must be set before import \"utils\"\nenviron[\"SATNOGS_GUT_CONFIG_DIR\"] = \"tests/config\"\n\nfrom utils import CONFIG_DIRECTORY\n\nfrom orbitdb import OrbitDatabase\n\ntle_filename = \"https___celestrak.com_NORAD_elements_noaa.txt\"\n\nclass TestOrbitDb(unittest.TestCase):\n def setUp(self):\n makedirs(CONFIG_DIRECTORY, exist_ok=True)\n copy(\"tests/config.yml\", CONFIG_DIRECTORY)\n copy(os.path.join(\"tests\", tle_filename),\n os.path.join(CONFIG_DIRECTORY, tle_filename))\n self.db = OrbitDatabase()\n\n def tearDown(self):\n rmtree(CONFIG_DIRECTORY, ignore_errors=True)\n\n def test_get_tle(self):\n now = datetime.datetime.utcnow()\n tle = self.db.get_tle(\"NOAA 15\", now)\n \n self.assertIsNotNone(tle)\n self.assertEqual(len(tle), 2)\n tle_org = (\"1 25338U 98030A 20093.30220133 .00000034 00000-0 32765-4 0 9993\",\n \"2 25338 98.7251 118.7119 0011447 121.8181 238.4115 14.25957034138389\")\n self.assertEqual(tle, tle_org)","sub_path":"station/tests/test_orbitdb.py","file_name":"test_orbitdb.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"352435207","text":"BATCH_SIZE=32\nINPUT_IMAGE_ROWS=160\nINPUT_IMAGE_COLS=320\nINPUT_IMAGE_CHANNELS=3\nAUGMENTATION_NUM_BINS=200\nNUM_EPOCHS=5\nAUGMENTATION_BIN_MAX_PERC=6\nAUGMENTATION_FACTOR=3\n\n\n\nimport csv\nimport cv2\nimport numpy as np\nfrom random import shuffle\nfrom sklearn.model_selection import train_test_split\nimport keras\nfrom keras.callbacks import Callback\nimport threading\nimport math\nfrom keras.preprocessing.image import *\nimport matplotlib.pyplot as plt\n\nprint(\"\\nLoading the dataset from file ...\")\n\ndef load_dataset(file_path):\n dataset = []\n with open(file_path) as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n try:\n dataset.append({'center':line[0], 'left':line[1], 'right':line[2], 'steering':float(line[3]),\n 'throttle':float(line[4]), 'brake':float(line[5]), 'speed':float(line[6])})\n except:\n print(\"ok\")\n continue # some images throw error during loading\n return dataset\n\ndataset = load_dataset('C:\\\\Users\\\\kiit1\\\\Downloads\\\\data\\\\dataset\\\\driving_log.csv')\nprint(\"Loaded {} samples from file {}\".format(len(dataset),'C:\\\\Users\\\\kiit1\\\\Downloads\\\\data\\\\dataset\\\\driving_log.csv'))\n\n\n\nprint(\"Partioning the dataset:\")\n\nshuffle(dataset)\n\n#partitioning data into 80% training, 19% validation and 1% testing\n\nX_train,X_validation=train_test_split(dataset,test_size=0.2)\nX_validation,X_test=train_test_split(X_validation,test_size=0.05)\n\ntest_data=open(\"test.csv\",\"w\")\n#write.csv(X_train,\"test_data.csv\")\nfeildnames=['center','left','right','steering','throttle','brake','speed']\nwriter=csv.DictWriter(test_data,fieldnames=feildnames)\nwriter.writeheader()\nfor row in X_test:\n #writer.writerow({'center':row[0],'left':row[1],'right':row[2],'steering':row[3],'throttle':row[4],'break':row[5],'speed':row[5]})\n writer.writerow(row)\n\n\nprint(\"X_train has {} elements.\".format(len(X_train)))\nprint(\"X_validation has {} elements.\".format(len(X_validation)))\nprint(\"X_test has {} elements.\".format(len(X_test)))\nprint(\"Partitioning the dataset complete.\")\n\n\nfrom PIL import Image\n\n#@threadsafe_generator\ndef generate_batch_data(dataset, batch_size = 16):\n #print(\"in generate_batch_data\")\n global augmented_steering_angles\n global epoch_steering_count\n global epoch_bin_hits\n batch_images = np.zeros((batch_size, INPUT_IMAGE_ROWS, INPUT_IMAGE_COLS, INPUT_IMAGE_CHANNELS))\n batch_steering_angles = np.zeros(batch_size)\n augmented_steering=[]\n\n\n while 1:\n for batch_index in range(batch_size):\n\n # select a random image from the dataset\n image_index = np.random.randint(len(dataset))\n #print(\"Image index=\")\n #print(image_index)\n image_data = dataset[image_index]\n #print(image_data)\n #image, steering_angle = load_and_augment_image(image_data)\n \n\n #image_data.show()\n\n\n\n while 1:\n \n #image, steering_angle = load_and_augment_image(image_data)\n try:\n image, steering_angle = load_and_augment_image(image_data)\n augmented_steering.append(float(steering_angle))\n except:\n continue\n\n\n bin_idx = int (steering_angle * AUGMENTATION_NUM_BINS / 2)\n\n if( epoch_bin_hits[bin_idx] < epoch_steering_count/AUGMENTATION_NUM_BINS*AUGMENTATION_BIN_MAX_PERC\n or epoch_steering_count<500 ):\n\n #print(\"Here\")\n batch_images[batch_index] = image\n batch_steering_angles[batch_index] = steering_angle\n augmented_steering_angles.append(steering_angle)\n\n epoch_bin_hits[bin_idx] = epoch_bin_hits[bin_idx] + 1\n epoch_steering_count = epoch_steering_count + 1\n break\n else:\n print(\"Not taking\")\n\n yield batch_images, batch_steering_angles\n\n\n\n\n\n\n\n\nprint(\"\\nTraining the model ...\")\n\nclass LifecycleCallback(keras.callbacks.Callback):\n\n def on_epoch_begin(self, epoch, logs={}):\n pass\n\n def on_epoch_end(self, epoch, logs={}):\n global epoch_steering_count\n global epoch_bin_hits\n global bin_range\n epoch_steering_count = 0\n epoch_bin_hits = {k:0 for k in range(-bin_range, bin_range)}\n\n def on_batch_begin(self, batch, logs={}):\n pass\n\n def on_batch_end(self, batch, logs={}):\n self.losses.append(logs.get('loss'))\n\n def on_train_begin(self, logs={}):\n print('Beginning training')\n self.losses = []\n\n def on_train_end(self, logs={}):\n print('Ending training')\n\n# Compute the correct number of samples per epoch based on batch size\ndef compute_samples_per_epoch(array_size, batch_size):\n num_batches = array_size / batch_size\n samples_per_epoch = math.ceil(num_batches)\n samples_per_epoch = samples_per_epoch * batch_size\n return samples_per_epoch\n\n\n\n\n\n\n\ndef load_and_augment_image(image_data, side_camera_offset=0.2):\n #print(\"in load_and_augment_image\")\n #co=1\n # select a value between 0 and 2 to swith between center, left and right image\n index = np.random.randint(3)\n if (index==0):\n image_file = image_data['left'].strip()\n angle_offset = side_camera_offset\n elif (index==1):\n image_file = image_data['center'].strip()\n angle_offset = 0.\n elif (index==2):\n image_file = image_data['right'].strip()\n angle_offset = - side_camera_offset\n\n steering_angle = image_data['steering'] + angle_offset\n\n image = cv2.imread(image_file)\n #image = cv2.imread(\"C://Users//kiit1//Downloads//data//dataset//IMG/center_2016_12_01_13_46_36_366.jpg\")\n #cv2.imshow('image',image)\n #cv2.waitKey(0)\n #cv2.destroyAllWindows()\n #print(image.shape)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # apply a misture of several augumentation methods\n image, steering_angle = random_transform(image, steering_angle)\n\n return image, steering_angle\n\n\naugmented_steering_angles = []\n\nepoch_steering_count = 0\nbin_range = int(AUGMENTATION_NUM_BINS / 4 * 3)\nepoch_bin_hits = {k:0 for k in range(-bin_range, bin_range)}\n\n\n\n\n\"\"\"\n******************************************************************************************************************\n ***********************************************************************\n\n DATA PREPROCESSING AND AUGMENTATION\n\n *************************************************************************\n********************************************************************************************************************\n\n\"\"\"\n\n\n\n\n\n#flips image about y-axis\ndef horizontal_flip(image,steering_angle):\n # print(\"in horizontal_flip\")\n flipped_image=cv2.flip(image,1);\n steering_angle=-steering_angle\n return flipped_image,steering_angle\n\ndef translate(image,steering_angle,width_shift_range=50.0,height_shift_range=5.0):\n #print(\"in translate\")\n tx = width_shift_range * np.random.uniform() - width_shift_range / 2\n ty = height_shift_range * np.random.uniform() - height_shift_range / 2\n\n # new steering angle\n steering_angle += tx / width_shift_range * 2 * 0.2\n\n transformed_matrix=np.float32([[1,0,tx],[0,1,ty]])\n rows,cols=(image.shape[0],image.shape[1])\n\n translated_image=cv2.warpAffine(image,transformed_matrix,(cols,rows))\n return translated_image,steering_angle\n\ndef brightness(image,bright_increase=None):\n #print(\"in brightness\")\n if(image.shape[2]>1):\n image_hsv=cv2.cvtColor(image,cv2.COLOR_RGB2HSV)\n else:\n image_hsv=image\n\n if bright_increase:\n image_hsv[:,:,2] += bright_increase\n else:\n bright_increase = int(30 * np.random.uniform(-0.3,1))\n image_hsv[:,:,2] = image[:,:,2] + bright_increase\n\n image = cv2.cvtColor(image_hsv, cv2.COLOR_HSV2RGB)\n return image\n\ndef rotation(image,rotation_range=5):\n #print(\"in rotation\")\n image=random_rotation(image,rotation_range);\n return image\n\n\n# Shift range for each channels\ndef channel_shift(image, intensity=30, channel_axis=2):\n #print(\"in channel_shift\")\n image = random_channel_shift(image, intensity, channel_axis)\n return image\n\n# Crop and resize the image\ndef crop_resize_image(image, cols=INPUT_IMAGE_COLS, rows=INPUT_IMAGE_ROWS, top_crop_perc=0.1, bottom_crop_perc=0.2):\n #print(\"in crop_resize_image\")\n height = image.shape[0]\n width= image.shape[1]\n\n # crop top and bottom\n top_rows = int(height*top_crop_perc)\n bottom_rows = int(height*bottom_crop_perc)\n image = image[top_rows:height-bottom_rows, 0:width]\n\n # resize to the final sizes even the aspect ratio is destroyed\n image = cv2.resize(image, (cols, rows), interpolation=cv2.INTER_LINEAR)\n return image\n\n\n# Apply a sequence of random tranformations for a better generalization and to prevent overfitting\ndef random_transform(image, steering_angle):\n # print(\"in random_transform\")\n # all further transformations are done on the smaller image to reduce the processing time\n image = crop_resize_image(image)\n\n # every second image is flipped horizontally\n if np.random.random() < 0.5:\n image, steering_angle = horizontal_flip(image, steering_angle)\n\n image, steering_angle = translate(image, steering_angle)\n image = rotation(image)\n image = brightness(image)\n image = channel_shift(image)\n\n return img_to_array(image), steering_angle\n\n\n\n\"\"\"\n******************************************************************************************************************\n ***********************************************************************\n\n CONVOLUTIONAL NUERAL NETWORK\n\n *************************************************************************\n********************************************************************************************************************\n\n\"\"\"\n\nfrom keras.models import Sequential, Model\nfrom keras.layers.core import Lambda, Dense, Activation, Flatten, Dropout\nfrom keras.layers.convolutional import Cropping2D, Convolution2D\nfrom keras.layers.advanced_activations import ELU\nfrom keras.layers.noise import GaussianNoise\nfrom keras.optimizers import Adam\n\n\nprint(\"\\nBuilding and compiling the model ...\")\n\nmodel = Sequential()\nmodel.add(Lambda(lambda x: (x / 127.5) - 1.0, input_shape=(INPUT_IMAGE_ROWS, INPUT_IMAGE_COLS, INPUT_IMAGE_CHANNELS)))\n # Conv Layer1 of 16 filters having size(8, 8) with strides (4,4)\nmodel.add(Convolution2D(16, 8, 8, subsample=(4, 4), border_mode=\"same\"))\nmodel.add(ELU())\n # Conv Layer1 of 32 filters having size(5, 5) with strides (2,2)\nmodel.add(Convolution2D(32, 5, 5, subsample=(2, 2), border_mode=\"same\"))\nmodel.add(ELU())\n # Conv Layer1 of 64 filters having size(5, 5) with strides (2,2)\nmodel.add(Convolution2D(64, 5, 5, subsample=(2, 2), border_mode=\"same\"))\nmodel.add(Flatten())\nmodel.add(Dropout(.5))\nmodel.add(ELU())\nmodel.add(Dense(512,activation='elu'))\nmodel.add(Dropout(.5))\nmodel.add(ELU())\nmodel.add(Dense(1))\n\nmodel.summary()\nadam = Adam(lr=0.0001)\nmodel.compile(loss='mse', optimizer=adam)\n\n#saving the model\nmodel_json=model.to_json()\nwith open(\"model.json\",\"w\")as json_file:\n json_file.write(model_json)\nmodel.save_weights(\"model.h5\")\nprint(\"Saved model to disk\")\n\n\n\nlifecycle_callback = LifecycleCallback()\n\ntrain_generator = generate_batch_data(X_train, BATCH_SIZE)\nvalidation_generator = generate_batch_data(X_validation, BATCH_SIZE)\n\nsamples_per_epoch = compute_samples_per_epoch((len(X_train)*AUGMENTATION_FACTOR), BATCH_SIZE)\nnb_val_samples = compute_samples_per_epoch((len(X_validation)*AUGMENTATION_FACTOR), BATCH_SIZE)\n\nhistory = model.fit_generator(train_generator,\n validation_data = validation_generator,\n samples_per_epoch = ((len(X_train) // BATCH_SIZE ) * BATCH_SIZE) * 2,\n nb_val_samples = ((len(X_validation) // BATCH_SIZE ) * BATCH_SIZE) * 2,\n nb_epoch = NUM_EPOCHS, verbose=1,\n )\n\n#plotting accuracy and loss\n\n#print(history.history.keys())\n#plt.plot(history.history['acc'])\n#plt.plot(history.history['val_acc'])\n#plt.title('model accuracy')\n#plt.ylabel('accuracy')\n#plt.xlabel('epoch')\n#plt.legend(['train', 'test'], loc='upper left')\n#plt.show()\n\n# summarize history for loss for traing and validation\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\n#plot batch loss\nbatch_history = lifecycle_callback.losses\nplt.plot(batch_history)\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('batches')\nplt.show()\nprint(\"\\nTraining the model ended.\")\n\n\n\n\n\n\"\"\"\n******************************************************************************************************************\n ***********************************************************************\n\n TRAINING\n\n *************************************************************************\n********************************************************************************************************************\n\n\"\"\"\n\n#plotting augmented train data\n\ndef plot_steering_histogram(steerings, title, num_bins=100):\n plt.hist(steerings, num_bins)\n plt.title(title)\n plt.xlabel('Steering Angles')\n plt.ylabel('# Images')\n plt.show()\n\nplot_steering_histogram(augmented_steering_angles, \"Augmented data\", num_bins=100)\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":13733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"123969620","text":"from vip import API_Key,API_Secret, Access_Token, Access_Token_Secret, App_ID, App_Key\nfrom collections import Counter\nfrom textblob import TextBlob\nimport matplotlib.pyplot as plt\nimport tweepy, codecs\nimport pandas as pd\nimport csv, io\n\n\n# Twitter Credentials\nauth = tweepy.OAuthHandler(API_Key, API_Secret)\nauth.set_access_token(Access_Token, Access_Token_Secret)\napi = tweepy.API(auth)\n\n\n# Search Hashtag and create text file\nsearch_text = input(\"Tell me a search term and we will see how Twitter feels about it. \")\nsearch_result = api.search(search_text, lang = \"en\", result_type = \"recent\", count = 1000) #better search! Tweepy\ntweet_archive = codecs.open('tweet_archive.txt', 'w', 'utf-8')\n\nfor tweet in search_result:\n tweet_archive.write(tweet.text)\n tweet_archive.write(\"\\n\")\n\ntweet_archive.close()\nprint(\"the tweets are alright\")\n\n\n# Analysis\n# Write csv\nwith io.open('twitter_feels.csv', 'w', encoding='utf8', newline='') as csvfile:\n csv_writer = csv.writer(csvfile)\n csv_writer.writerow([\"Tweet\", \"Sentiment\"])\n with io.open('tweet_archive.txt', 'r', encoding='utf8') as archive:\n for tweet in archive.readlines():\n # removing extra spaces\n tweet = tweet.strip()\n # removing empty tweets\n if len(tweet) == 0:\n continue\n # TextBlob in action\n sentiment = TextBlob(tweet).sentiment.polarity\n # put results in csv file\n csv_writer.writerow([tweet, sentiment])\n\n# Open csv file\nwith io.open('twitter_feels.csv', 'r', encoding='utf8') as csvfile:\n # pandas reading the file\n df = pd.read_csv(csvfile)\n print(df.head())\n\n# THE PLOTS\n\n# Plotting time - polarity graph\nthe_graph = df.plot(x=\"Tweet\", y=\"Sentiment\", title=\"Twitter feelings for your search query\")\nthe_graph.set_xlabel(\"Tweet\")\nthe_graph.set_ylabel(\"Polarity (positive/negative)\")\nplt.show()\n\n# Plotting time - pie\npos = 0\nneu = 0\nneg = 0\n\nfor feeling in df[\"Sentiment\"]:\n if feeling > 0.0:\n pos += 1\n elif feeling == 0.0:\n neu += 1\n else:\n neg += 1\n\nlabels = 'Positive', 'Negative', 'Neutral'\nsizes = [pos, neg, neu]\ncolors = ['green', 'blue', 'red']\n\nplt.pie(sizes, labels=labels, colors=colors)\nplt.title(\"Twitter feelings for your search query\")\nplt.show()\n","sub_path":"feelings.py","file_name":"feelings.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"416628857","text":"'''Implementation of shell sort'''\ndef ShellSort(arr):\n sublistcount = len(arr)//2\n while sublistcount > 0: #Until it becomes one single element\n for start in range(sublistcount):\n gap_insertion_sort(arr, start, sublistcount)\n # print(sublistcount)\n # print(arr)\n sublistcount = sublistcount//2\n return arr\n\ndef gap_insertion_sort(arr, start, gap):\n for i in range(start+gap, len(arr), gap):\n position = i\n while position >= gap and arr[position - gap] > arr[position]:\n (arr[position-gap], arr[position]) = (arr[position], arr[position-gap])\n position = position - gap\n return arr\nprint(ShellSort([45,67,23,45,21,24,7,2,6,4,90]))\n","sub_path":"Searching&Sorting/ShellSort.py","file_name":"ShellSort.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"646569643","text":"from tkinter import *\n# create a 300x300 canvas.\n# fill it with a checkerboard pattern.\n\ndef chessboard():\n color = \"black\"\n k = 300 // 8\n for j in range(8) :\n for i in range(8):\n if i % 2 == 0 and j % 2 == 1 or j % 2 == 0 and i % 2 == 1:\n color = \"black\"\n else:\n color = \"white\"\n canvas.create_rectangle(i*k,j*k, k+i*k, k+j*k, fill=color)\n\nroot = Tk()\n\ncanvas = Canvas(root, width=\"300\", height=\"300\")\ncanvas.pack()\n\nchessboard()\n\nroot.mainloop()\n","sub_path":"week-04/day-3/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"599165915","text":"import pandas\nimport numpy\nfrom sklearn import preprocessing, model_selection\n\n\ndef make_data_files(data_set_name, training_file, testing_file):\n embeddings_file = '../data/' + data_set_name + '.emb'\n links_file = '../graph/' + data_set_name + '.tsv'\n embeddings = pandas.read_csv(embeddings_file, sep=' ', header=None, index_col=0, skiprows=1)\n embeddings.sort_index(inplace=True)\n links = pandas.read_csv(links_file, sep='\\t', header=None)\n\n def embed(node_id):\n return ', '.join(str(element) for element in embeddings.loc[[node_id]].values.flatten())\n\n links[0] = links[0].map(embed)\n links[1] = links[1].map(embed)\n links[2] = preprocessing.MaxAbsScaler().fit_transform(numpy.log(links[2].values.reshape(-1, 1)))\n training_links, testing_links = model_selection.train_test_split(links, test_size=0.2)\n training_links.to_csv(training_file, index=False, header=False, quotechar=' ')\n testing_links.to_csv(testing_file, index=False, header=False, quotechar=' ')\n\n\ndef main():\n for data_set_name in ['airport', 'authors', 'collaboration', 'facebook', 'congress', 'forum']:\n training_file = '../data/' + data_set_name + '_training.csv'\n testing_file = '../data/' + data_set_name + '_testing.csv'\n make_data_files(data_set_name, training_file, testing_file)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"evaluation/scale.py","file_name":"scale.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"563076206","text":"__author__ = \"Salim Oussayfi\"\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom scipy.spatial import distance\niris = load_iris()\ndata = iris.data[:10]\nlabels = iris.target\nnames = iris.target_names\n\nprint(\"names \", names[:10])\nprint(\"labels\",labels[:10])\n\n\n#test_data = [5.2,4.1,1.5,0.1] #0\n#test_data = [5.2,2.7,3.9,1.4] #1\ntest_data = [4.8, 2.5, 5.3, 2.4] #2\n\nclass KNeighborsClassifier:\n def __init__(self, k: int, data: np.ndarray, names: list, labels: np.ndarray, test_data: list):\n self.k = k\n self.data = data\n self.names = names\n self.labels = labels\n self.test_data = test_data\n\n normalized_data = self.normalizeData()\n distances = self.euclideanDistance()\n sorted_distances = self.sortDistances(distances)\n nNeighbors = self.determineNeighbors(sorted_distances, self.labels)\n\n print('The {} closest neighbors of searched iris {} are:'.format(self.k, self.test_data))\n for name in nNeighbors:\n print(\"iris \", self.names[name])\n\n self.determinePropability(nNeighbors)\n\n def normalizeData(self):\n x = self.data\n data_min = np.min(x, axis=0)\n data_max = np.max(x, axis=0)\n x_transformed = (x - data_min) / (data_max - data_min)\n return x_transformed\n\n def euclideanDistance(self):\n distances = list()\n for i in self.data:\n distances.append(distance.euclidean(i, self.test_data))\n return distances\n\n def sortDistances(self, x:list):\n print(\"neighbors \",np.argsort(x))\n return np.argsort(x)\n\n def determineNeighbors(self, distances: np.ndarray, y: np.ndarray):\n targetList = list()\n neighbors = distances[0:self.k]\n for i in neighbors:\n targetList.append(y[i])\n return targetList\n\n def determinePropability(self, nNeighbors:list):\n amount = len(nNeighbors)\n closedNeighbor = nNeighbors[0]\n occurrences = nNeighbors.count(closedNeighbor)\n propability = occurrences/amount\n print('Propability for iris {} by examine next {} neighbors is {} %'.format(self.names[closedNeighbor], self.k, propability*100))\n\n#clf = KNeighborsClassifier(8, data, names, labels, test_data)\n\nmovies_ = pd.read_csv(\"movies.csv\")\nmovies = np.array(movies_)\ndata2 = movies[:,[0,1]]\n# print(data2)\nnames2 = np.unique(movies[:,2])\nprint(\"names \", names2)\nlabels2 = movies[:,3]\nprint(\"labels\", labels2)\n\ntest_data2 = [5.0, 140.0]\n\nclf1 = KNeighborsClassifier(5, data2, names2, labels2, test_data2)\n\ntest_data3 = [105.0, 4.0]\n#clf2 = KNeighborsClassifier(5, data2, names2, labels2, test_data3)\n\n\n\n\n","sub_path":"DS_Sandbox/010_KNeighborsClassifier/Exercise_01_KNN.py","file_name":"Exercise_01_KNN.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"34444864","text":"\"\"\"\nsome tools for approximation of Koopman continuous spectrum \n(i.e. power spectral density) in\n\"Data-driven modeling of strongly nonlinear chaotic systems with non-Gaussian statistics\" \nby H. Arbabi and T. Sapsis\nApril 2019, arbabi@mit.edu\n\"\"\"\n\nimport numpy as np\nimport math\nimport scipy.io as sio\nimport scipy.optimize\nfrom scipy.interpolate import interp1d\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom numba import jit\n\nimport SDE_systems as sm\n\ndef Welch_estimator(x,M=100,L=200,fs=1):\n # computes the power spectral density via Welch method based on\n # P. Welch, The use of fast Fourier transform for the estimation of power spectra: A method based on time\n # averaging over short, modified periodograms, IEEE Trans. Audio Electroacoust. 15, 70 (1967).\n # Inputs:\n # x: the signal vector (nx1) \n # M: length of each block \n # K: overlap length \n # L: size of the padded FFT grid\n # fs: sampling frequency (in Hz)\n\n # Outputs:\n # omega: frequency grid (in rad/sec)\n # phi: power spectral density\n\n K = int(M/2) # overlap length\n N = x.shape[0]\n v = np.blackman(M)/10 # the window function\n\n S = int(math.floor(((N-M+K)/K)))\n\n Pv=np.mean(v**2)\n\n # function handle to compute psd for each block\n psd_fft = lambda y: (np.abs(np.fft.fft( (y[0:M]*v),n=L) )**2 ) /M\n\n\n phi = np.zeros(L)\n\n for j in range(0,S):\n phi = phi + psd_fft(x[j*K:j*K+M] )\n \n phi = phi/(S*Pv*fs )\n \n # the freqency grid\n omega = 2*np.pi*fs*np.linspace(0,1,L)\n\n\n\n return omega,phi\n\n\n\n\ndef approx_PSD_w_delta(wg,p,nw=100,fs=1):\n # given spectral density p on the grid w \n # this function approximates that density \n # with nw delta functions (i.e. discrete frequencies)\n # and returns the location of those frequencies (w) and their amplitude (a)\n\n\n # generate a random set of intervals on [0,pi]\n e =np.append(np.random.rand(nw-1)*np.pi*fs,[0,np.pi*fs])\n e = np.sort(e) # endpoints of intervals\n dw = np.diff(e) # length of intervals\n w = (e[:-1]+e[1:])/2 # midpoint of intervals\n\n rho_fun = interp1d(wg,p/(2*np.pi),kind='linear')\n rho= rho_fun(w)\n\n # amplitude of each delta\n a = np.sqrt(2*2*rho*dw)\n # first 2 is to account for the pi 0:\n self.facing = 'right'\n self.change_sprite()\n\n def on_animation_end(self, _, sprite):\n pass\n","sub_path":"game/entity/enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"46300142","text":"from sys import setrecursionlimit\nfrom random import random\n\nimport matplotlib.pyplot as plt\n\nKplus = 0.5 # Rate at which singles enter the bar (per minute).\nKminus = 0.01 # Rate at which singles leave the bar (per single per minute).\nKheart = 0.001 # Rate at which couples form (per single per single per minute)\n\nnMalesInit = 0 # Initial number of males in the bar.\nnFemalesInit = 0 # Initial number of females in the bar.\n\ntimeLimit = 2000\n\ndef runSim(nMales=nMalesInit, nFemales=nFemalesInit, time=0,\\\n Kp=Kplus, Km=Kminus, Kh=Kheart, closingTime=timeLimit):\n if time >= closingTime:\n return [nMales + nFemales]\n\n dMales = 0\n dFemales = 0\n \n # Assume the bouncer maintains the gender ratio\n if random() nMales:\n dMales += 1\n else:\n dFemales += 1\n\n # Assume that the gender ratio is\n # mystically maintained for leavers too.\n for n in range(nMales + nFemales):\n if random()0 and\\\n nFemales+dFemales-nNewCouples>0:\n nNewCouples += 1\n continue\n\n dMales -= nNewCouples\n dFemales -= nNewCouples\n\n return [nMales + nFemales] + \\\n runSim(nMales=nMales+dMales, nFemales=nFemales+dFemales, time=time+1)\n\ndef outputResultsToFile(results, filename):\n file = open(filename, 'w')\n\n titleString = 'Time,'\n for i in range(len(results)):\n titleString += str(i) + ' nSingles,'\n\n titleString += '\\n'\n file.write(titleString)\n\n for i in range(len(results[0])):\n line = str(i) + ','\n for result in results:\n line += str(result[i]) + ','\n\n line += '\\n'\n\n file.write(line)\n\n file.close()\n\ndef outputResultsToPlot(results, filename):\n t = range(len(results[0]))\n\n for result in results:\n plt.plot(t, result)\n\n plt.suptitle('Number of singles in the jazz bar at time t')\n plt.savefig(filename)\n\ndef sim(numberSims = 3, filename = 'jazzbar'):\n setrecursionlimit(max(timeLimit*2, 10000))\n \n results = []\n for i in range(numberSims):\n results.append(runSim())\n \n outputResultsToFile(results, filename + '.csv')\n outputResultsToPlot(results, filename + '.png')\n\nif __name__ == \"__main__\":\n sim()\n\n\n","sub_path":"Jazz bar/jazzbar.py","file_name":"jazzbar.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"122752568","text":"\"\"\"Test the mobile_app websocket API.\"\"\"\n# pylint: disable=redefined-outer-name,unused-import\nfrom homeassistant.components.mobile_app.const import (CONF_SECRET, DOMAIN)\nfrom homeassistant.components.websocket_api.const import TYPE_RESULT\nfrom homeassistant.const import CONF_WEBHOOK_ID\nfrom homeassistant.setup import async_setup_component\n\nfrom .const import (CALL_SERVICE, REGISTER)\n\n\nasync def test_webocket_get_user_registrations(hass, aiohttp_client,\n hass_ws_client,\n hass_read_only_access_token):\n \"\"\"Test get_user_registrations websocket command from admin perspective.\"\"\"\n await async_setup_component(hass, DOMAIN, {DOMAIN: {}})\n\n user_api_client = await aiohttp_client(hass.http.app, headers={\n 'Authorization': \"Bearer {}\".format(hass_read_only_access_token)\n })\n\n # First a read only user registers.\n register_resp = await user_api_client.post(\n '/api/mobile_app/registrations', json=REGISTER\n )\n\n assert register_resp.status == 201\n register_json = await register_resp.json()\n assert CONF_WEBHOOK_ID in register_json\n assert CONF_SECRET in register_json\n\n # Then the admin user attempts to access it.\n client = await hass_ws_client(hass)\n await client.send_json({\n 'id': 5,\n 'type': 'mobile_app/get_user_registrations',\n })\n\n msg = await client.receive_json()\n\n assert msg['id'] == 5\n assert msg['type'] == TYPE_RESULT\n assert msg['success']\n assert len(msg['result']) == 1\n\n\nasync def test_webocket_delete_registration(hass, hass_client,\n hass_ws_client, webhook_client):\n \"\"\"Test delete_registration websocket command.\"\"\"\n authed_api_client = await hass_client() # noqa: F811\n register_resp = await authed_api_client.post(\n '/api/mobile_app/registrations', json=REGISTER\n )\n\n assert register_resp.status == 201\n register_json = await register_resp.json()\n assert CONF_WEBHOOK_ID in register_json\n assert CONF_SECRET in register_json\n\n webhook_id = register_json[CONF_WEBHOOK_ID]\n\n client = await hass_ws_client(hass)\n await client.send_json({\n 'id': 5,\n 'type': 'mobile_app/delete_registration',\n CONF_WEBHOOK_ID: webhook_id,\n })\n\n msg = await client.receive_json()\n\n assert msg['id'] == 5\n assert msg['type'] == TYPE_RESULT\n assert msg['success']\n assert msg['result'] == 'ok'\n\n ensure_four_ten_gone = await webhook_client.post(\n '/api/webhook/{}'.format(webhook_id), json=CALL_SERVICE\n )\n\n assert ensure_four_ten_gone.status == 410\n","sub_path":"tests/components/mobile_app/test_websocket_api.py","file_name":"test_websocket_api.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"514963151","text":"\n\"\"\" Subjects, and reading them from files\nSupported file type:\n* Tab separated values (.tsv)\n:Author: Nicole Zatorski \n:Author: Arthur Goldberg \n:Date: 2018-11-01\n:Copyright: 2018, Arthur Goldberg\n\"\"\"\n\"\"\"\nThis program was created by Fredy Reyes based on original program supplied by faculty\n\"\"\"\n\n##https://stackoverflow.com/questions/16870663/how-do-i-validate-a-date-string-format-in-python#\n#https://stackoverflow.com/questions/46915426/how-to-check-if-a-date-is-earlier-than-todays-date##\n#https://stackoverflow.com/questions/32490629/getting-todays-date-in-yyyy-mm-dd-in-python#\n###https://stackoverflow.com/questions/46422374/efficiently-compare-two-sets-in-python##\n#https://docs.python.org/3/library/enum.html#\n#https://stackoverflow.com/questions/47818314/split-lists-into-multiple-columns-in-a-pandas-dataframe#\n#https://stackoverflow.com/questions/1885324/is-it-possible-to-keep-the-column-order-using-csv-dictreader#\n#https://overlaid.net/2016/02/04/convert-a-csv-to-a-dictionary-in-python/#\n#https://stackoverflow.com/questions/46307998/comparing-values-in-successive-rows-with-pandas#\n#https://stackoverflow.com/questions/354883/how-to-return-multiple-values-from-a-function#\n#https://www.geeksforgeeks.org/g-fact-41-multiple-return-values-in-python/\n#https://docs.python.org/3/library/sys.html\n#https://docs.python.org/3/library/enum.html\n#https://stackoverflow.com/questions/17086038/python-log-stderr-and-stdout-to-a-file\n#https://stackoverflow.com/questions/47269286/how-to-enumerate-a-list-within-a-list-that-was-enumerated\n#https://www.peterbe.com/plog/uniqifiers-benchmark\n#https://stackoverflow.com/questions/483666/python-reverse-invert-a-mapping\n#some of the ideas included in this program were discussed with Allisha. Specifically ideas on how to solve the\n#problems associated with producing an ordered dict with DictReader. \n#https://stackoverflow.com/questions/29576430/shuffle-dataframe-rows\n\n\nimport random\nimport collections\nimport sklearn\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport os\nimport sys\nimport pprint\nimport sklearn\nimport math\nimport csv\nimport re\nfrom sys import stderr\nfrom enum import Enum\nfrom datetime import datetime\nfrom datetime import date\nfrom collections import defaultdict\nfrom collections import OrderedDict\n\nos.system('clear')\nsys.stdout.flush()\n\nclass Gender(Enum):\n\t\"\"\" Gender categories \"\"\"\n\tfemale = 1\n\tmale = 2\n\tunknown = 3\n\nclass XStatus(Enum):\n\t\"\"\" Status categories for condition X \"\"\"\n\tunaffected = 1\n\taffected = 2\n\nclass Training_testing(Enum):\n\ttraining = 1\n\ttesting = 2\n\nclass Class_Out(Enum):\n\tcannot_analyze = 1\n\tcan_analyze = 2\n\tcorrectly_classified = 3\n\tincorrectly_classified = 4\n\n\"\"\"\nThe following list of variables will be used through the code some of them are defined later as global variavles and updated in each function\n\"\"\"\n\nfield_error_entries = []\nextra_field_error = []\nextra_field_error_entries = []\nfile_error = []\nfield_error = []\ncomplete_instances = []\ninstance_validated = None\nvalidity_errors =[]\nvalidity_error_entries = []\nduplicate_errors = []\nduplicate_error_entries=[]\nattrs = []\nindividual_entries = []\ncleaned_data =[]\nNAME_ATTRIBUTES = ['id', 'gender', 'dob', 'x_status', 'assi_in_exp','extra_fields']\nMIN_ID_LEN = 4\ncounter = []\nall_accepted_entries = []\naccepted_entries = []\ndict_of_all_accepted_entries = {}\nextra_field_error_entries_df = ()\nfield_error_entries_df = ()\nvalidty_error_entries_df = ()\ndata_all_incorrectly_classified = []\ndata_all_correctly_classified = []\nall_validatedInstances_ids_l = []\nall_invalidatedInstances_ids_l =[]\nall_validatedInstances_l =[]\nall_invalidatedInstances_l =[]\nall_invalidated_instances_df =[]\nall_validated_instances_df =[]\nrows_of_all_validated_instances =[]\nrows_of_all_invalidated_instances = []\ndict_of_duplicates = {}\nextra_field_error_ids_l =[]\nfield_error_ids_l = []\nvalidity_error_ids_l = []\nall_errors_ids_l = []\n\nclass Subject:\n\t\"\"\" Read, verify and store information about a submect\n\tAttributes:\n\tid (:obj:`str`): a unique identifier for each `Subject`\n\tgender (:obj:`Gender`): a `Subject`'s gender; may be unknown\n\tdob (:obj:`Date`): date of birth\n\tx_status (:obj:`str`): a `Subject`'s status on condition X\n\textra_fields(:obj:'str'): 'additional strings or other types in\n\ta fifth column of the data files\n\t\"\"\"\n\tdef __init__(self, id, gender, dob, x_status, assi_in_exp, extra_fields):\n\t\tself.id = id\n\t\tself.gender = Gender[gender]\n\t\tself.dob = dob\n\t\tself.x_status = XStatus[x_status]\n\t\tself.extra_fields = extra_fields\n\t\tself.assi_in_exp = Training_testing[assi_in_exp]\n\n\t@classmethod\n\tdef load_file(cls, file_name1):\n\t\t\"\"\"\n\t\tthe load file method is a @classmethod. Thwe load file method test if the column headers and \n\t\texpected attributes correspon. If they dont the experimenter must enter a new file. if colum headers and\n\t\tname attributes correspond the file is parsed by a csv reader and converted to a data frame and to a list of\n\t\tindividual entries, each is a list containing an instance. Individual_entries is a list of lists. If the file\n\t\tis accepted the file is sent to a second class method extra_fields_ver It takes individual entries as a global variable.\n\t\textra_fields_ver initiates an iteration over the entries of teh fiel once iteration is complete the method leads to a global cleaning of the data.\n\t\tI use pandas data frames to better analyze and manipulate the data. I also utilize dictionaries and the enumerate class to store the results of\n\t\tthe runs\n\t\t\"\"\"\n\t\tNAME_ATTRIBUTES = ['id', 'gender', 'dob', 'x_status', 'assi_in_exp', 'extra_fields']\n\t\tdata_0 = pd.read_csv(file_name1, delimiter='\\t')\n\t\tpprint.pprint(data_0)\n\t\tindividual_entries = data_0.values.tolist()\n\t\ttotal_data = (len(individual_entries)-1)\n\t\tprint(\"The total number of entries is = \", total_data)\n\t\t\"\"\"the line below reassigns diseases randomly to each row. Entries with 'Non'e and 'Not_avalible' represent errors\"\"\"\n\t\treassign_disease_to_file=cls.random_disease_assig(individual_entries, data_0)\n\t\t\"\"\"the line below assigns the categories of training or testing and undetermined to each row. Assignment is random. 'None' and 'Not_avalible' represent errors\"\"\"\n\t\tcheck_assigment_to_training = cls.train_test_ver(individual_entries, data_0)\n\t\tdata_1=data_0\n\t\tpprint.pprint(data_1)\n\t\t\"\"\"\n\t\tThe following lines remove entries with duplicate subject id. It converts file to pandas df and removes duplicates\n\t\t\"\"\"\n\t\tdata_2 = data_1.drop_duplicates(['id'])\n\t\tpprint.pprint(data_2)\n\t\tindividual_entries_1 = data_2.values.tolist()\n\t\ttotal_data = (len(individual_entries_1)-1)\n\t\tprint(\"The total number of entries after removing duplicates is = \", total_data)\n\t\ts0 = list(data_2.columns.values)\n\t\ts1 = len(NAME_ATTRIBUTES)\n\t\t\"\"\"\n\t\tThe following lines test the structure of the file, wheather column names correspond to ATTRIBUTE_NAMES. Note that an original files must have an extra column extra_fields and that a new column for \n\t\ttraining or testing was assigned\n\t\t\"\"\"\n\t\tif (len(s0) == len(NAME_ATTRIBUTES)) and (s0 == (NAME_ATTRIBUTES)):\n\t\t\tprint(\"File has correct number of column headers and attributes, column header names and attribute names correspond \")\n\t\t\t\"\"\"\n\t\t\tThe following line calls the class method extra_fields_ver this method intitiates the process of reviewing the input file line by line to remove errors\n\t\t\t\"\"\"\n\t\t\tfilter_file = cls.extra_fields_ver(individual_entries_1)\n\t\t\t#cls.tables_out(individual_entries_1)\n\t\telif (len(s0) == s1) and ((s0) != (NAME_ATTRIBUTES)):\n\t\t\tprint(\"Instance has correct number of column headers and attributes, but names of attributes and column headers are not the same \")\n\t\t\tfile_error.append(\"\\nNumbers of column headers and attributtes are the same. But names of column headers in file are not correct '{}' file must be corrected \".format(individual_entries[0]))\n\t\t\tsys.stderr.write(\"\\nNumbers of column headers and attributtes are the same. But names of column headers in file are not correct '{}' file must be corrected \".format(individual_entries[0]))\n\t\telif (len(s0) != (s1)) and (s0 != (NAME_ATTRIBUTES)):\n\t\t\tprint(\"Numbers of column headers and attributtes are not the same. Names of attributes and column headers are not the same\")\n\t\t\tfile_error.append(\"\\nNumbers of column headers and attributtes are not the same. Names of column headers in file are not correct '{}' file must be corrected\".format(individual_entries[0]))\n\t\t\tsys.stderr.write(\"\\nNumbers of column headers and attributtes are not the same. Names of column headers in file are not correct '{}' file must be corrected\".format(individual_entries[0]))\n\t\telse:\n\t\t\tpass\n\n\t\t#cls.prepare_data()\n\t\t\"\"\"\n\t\tThe following method prepares the data for classification runs and data analysis of classification runs. The prepare data method belongs to the class 'Subject' however it deals not with instances \n\t\tof subjects but with groups of instances of subjects, all reviewed, classified as correct and analyzable, correctly classified, incorrectly classified and incorrect and impossible to analyze and \n\t\tcls.prepare_data(individual_entries_1, validity_error_entries, validity_error_ids_l, extra_field_error_entries, extra_field_error_ids_l, field_error_entries, field_error_ids_l, instance_validated)\n\t\t\"\"\"\t\n\t\tif file_error != []:\n\t\t\tprint(\"File is not correct revise and load again a correct file\")\n\t\t\treturn file_error\n\t\telse:\n\t\t\tpass\n\t\t#cls.tables_out(individual_entries_1)\n\t\t#cls.prepare_data(data_2, data_1, individual_entries_1, validity_error_entries, validity_error_ids_l, extra_field_error_entries, extra_field_error_ids_l, field_error_entries, field_error_ids_l, instance_validated)\n\t\n\n\t@classmethod\n\tdef extra_fields_ver(cls, individual_entries_1):\n\t\t\"\"\"\n\t\tclassmethod that verifies if there are extra fields in the list of individual entries.\n\t\tinstances containing extra_fields with strings or other types are appended to an error \n\t\tlist and an error is generated, sent to stdout and stderr logs. Instances where extrafield \n\t\tis NaN are modified such that extrafield is string 'No' and accepted fobe further analyzed. \n\t\tFor those accepted instances only id, dob, gender and disease status are analyzed. Error \n\t\tlists variables for fields are set to global and returned. If instnace is accepted it is moved to\n\t\tload_instance. The program will loop here through all instances or individual entries of the \n\t\tfile and once looping is complete the program exits to a class method that removes incorrect \n\t\tinstances from the original data.\n\t\t\"\"\"\n\t\tprint(\"\\n\")\n\t\tprint(\"==========================================================================================\")\n\t\tprint(\"\\n\")\n\t\tglobal counter\n\t\tfor item in (individual_entries_1):\n\t\t\tcounter = (individual_entries_1.index(item))\n\t\t\tprint(\"Instance is =\", item)\n\t\t\tif isinstance(item[-1], str):\n\t\t\t\tprint(item[-1])\n\t\t\t\tprint(\"\\nInstance '{}' in row '{}' has an extra field, instance is invalid and will be removed\".format(item, counter))\n\t\t\t\textra_field_error.append(\"\\nInstance '{}' in row '{}' has an extra field, instance is invalid and will be removed\".format(item, counter))\n\t\t\t\textra_field_error_entries.append(item)\n\t\t\t\tsys.stderr.write(\"\\nInstance '{}' in row '{}' has an extra field, instance is invalid and will be removed\".format(item, counter))\n\t\t\t\textra_field_error_ids_l.append(item[0])\n\t\t\t\tprint(\"\\n\")\n\t\t\t\tprint(\"==========================================================================================\")\n\t\t\t\tprint(\"\\n\")\n\t\t\telif math.isnan(item[-1]):\n\t\t\t\tprint(\"There are no extra_fields in the instance. Instance will be loaded for further analysis\")\n\t\t\t\titem[-1] = 'No'\n\t\t\t\tSubject.load_instance(item, counter, individual_entries_1)\n\t\tif counter == (len(individual_entries_1)):\n\t\t\tprint(accepted_instances_l)\n\t\t\tprint(rejected_instances_l)\n\t\t\tprint(counter)\n\t\telif counter < (len(individual_entries_1)):\n\t\t\tprint(\"will continue looping\", counter)\n\n\t\telse:\n\t\t\tpass\n\n\t\"\"\"the line below randomly assigns disease status to rows, the assignments include errors\"\"\"\n\n\t@classmethod\n\tdef random_disease_assig(cls, individual_entries, data_0):\n\t\tassig_diseases = []\n\t\tDISEASES_LIST=(\"affected\", \"unaffected\", \"Not_avail\")\n\t\tlist_of_assig_diseases = []\n\t\ti = 1\n\t\tsubject_disease =''\n\t\tfor i in range(0, len(individual_entries)):\n\t\t\tif i <= len(individual_entries):\n\t\t\t\tsubject_disease = random.choice([\"affected\", \"unaffected\", \"Not_avail\"])\n\t\t\t\tlist_of_assig_diseases.append(subject_disease)\n\t\tobserved_diseases=pd.Series(list_of_assig_diseases)\n\t\tdata_0['x_status'] = pd.Series(list_of_assig_diseases)\n\t\tpprint.pprint(data_0)\n\n\t@classmethod\n\tdef train_test_ver(cls,individual_entries, data_0):\n\t\tassi_in_exp= []\n\t\tASSIGMENT=(\"Training\", \"Testing\", \"Not_avail\")\n\t\tlist_of_assig = []\n\t\ti = 1\n\t\tcurrent =''\n\t\tfor i in range(0, len(individual_entries)):\n\t\t\tif i <= len(individual_entries):\n\t\t\t\tcurrent = random.choice(['training', 'testing', 'not_avail'])\n\t\t\t\tlist_of_assig.append(current)\n\t\tprint(len(individual_entries))\n\t\tprint(len(list_of_assig))\n\t\tidx=4\n\t\tassi_in_exp=pd.Series(list_of_assig)\n\t\tdata_0.insert(loc=idx, column='assi_in_exp', value=assi_in_exp)\n\t\tpprint.pprint(data_0)\n\n\t@classmethod\n\tdef load_instance(cls, item, counter, individual_entries_1):\n\t\t\"\"\"\n\t\tload instance is a @classmethod that takes an item a single individual entry or instance\n\t\tand checks that there are not fields that are empty. It sets three variables to global: \n\t\tcomplete instnaces, field error and field error entries to global. If the instance is\n\t\tincomplete, the function outputs an error. If the function is complete it sends the instance\n\t\tfor further analysis to determine that eaqh field is acceptable. The function creates a\n\t\tdictionary to identify the missing field if any in the instance. The value of the key, value\n\t\tpair in the dictionary is matched to the index of the missing argument in the instance.\n\t\t\"\"\"\n\t\tsubject = []\n\t\tmissin_var = []\n\t\targs = []\n\t\tz = []\n\t\tw = []\n\t\tdict_args_s = {}\n\t\tdict_name_attribs = {}\n\t\targs = item\n\t\targs_s =[str(i) for i in args]\n\t\tdict_args_s = dict((i, j) for i, j in enumerate(args_s))\n\t\tdict_name_attribs = dict((i, j) for i, j in enumerate(NAME_ATTRIBUTES))\n\t\tpprint.pprint(args_s)\n\t\tif 'nan' in (args_s):\n\t\t\tw = args_s.index('nan')\n\t\t\tfor k, v in dict_name_attribs.items():\n\t\t\t\tif k == w:\n\t\t\t\t\tmissing_var = v\n\t\t\t\t\tprint(\"\\nInstance '{}'' located in row '{} is missing argument '{}'. Instance is invalid \".format((args_s), counter, missing_var))\n\t\t\t\t\tfield_error.append(\"\\nInstance '{} located in row '{} is missing argument '{}'. Instance is invalid \".format((args_s), counter, missing_var))\n\t\t\t\t\tsys.stderr.write(\"\\nInstance '{} located in row '{} is missing argument '{}'. Instance is invalid \".format((args_s), counter, missing_var))\n\t\t\t\t\tfield_error_entries.append(args)\n\t\t\t\t\tfield_error_ids_l.append(args[0])\n\t\t\t\t\t#return (field_error, field_error_entries, complete_instances, args, args_s, item)\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\telse:\n\t\t\tprint(\"Variables in instance are complete, instance will be sent for validation\")\n\t\t\tsubject = Subject.verify_instance(*args_s, counter, individual_entries_1)\n\t\treturn field_error_entries, field_error_ids_l, individual_entries_1, counter\n\n\tdef __str__(self):\n\t\t\"\"\"\n\t\tProvide string repr\n\t\tReturns:\n\t\t:obj:`str`: tab-separated id, gender, dob, and status\n\t\t\"\"\"\n\t\treturn '\\t'.join([self.id, self.gender.name, str(self.dob), self.x_status.names, self.assi_in_exp])\n\n\t@classmethod\n\tdef verify_instance(cls, id, gender, dob, x_status, assi_in_exp, extra_fields, counter, individual_entries_1):\n\t\t\"\"\"\n\t\tThis method verifies the instances of the file. It focuses on instances that do not contain\n\t\textra fields of information and that have all the require variables. The method reviews \n\t\tid length, spaces in id, gender, disease status, dob format, age less that 150 years and\n\t\tproduces a single boolean variable to indicate if the instance is accepted or not. The method calls\n\t\tthe send for cleaning data.\n\t\t\"\"\"\n\t\ta = []\n\t\tb = []\n\t\tINST_CONF = None\n\t\tSPACES = None\n\t\tDATE_FORMT = None\n\t\tYOUNG = []\n\t\tGNDR = None\n\t\tXS = None\n\t\tTRANG = None\n\t\targs = [id, gender, dob, x_status, assi_in_exp, extra_fields]\n\t\targs_s =[str(i) for i in args]\n\t\tinstance_validated = None\n\t\tvalEnumGender = [item.value for item in Gender]\n\t\tvalEnumXStatus = [item.value for item in XStatus]\n\t\tvalEnumTraining_testing = [item.value for item in Training_testing]\n\t\t\"\"\"\n\t\tThe following lines test wheather ids have at least min len = 4, no spaces, string type\n\t\t\"\"\"\n\t\tprint(args)\n\t\ta = len(id)\n\t\tb = re.findall(r'[\\s]+', id)\n\t\tif isinstance(id, str):\n\t\t\tprint(\"subject sid is string\")\n\t\t\tif a < MIN_ID_LEN:\n\t\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{} has id '{}' shorter than min number of char {}, instance is invalid\".format(([args_s]), counter, id, MIN_ID_LEN))\n\t\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{} has id '{}' shorter than min number of char {}, instance is invalid\".format(([args]), counter, id, MIN_ID_LEN))\n\t\t\t\tvalidity_error_entries.append([args_s])\n\t\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\t\tINST_CONF = False\n\t\t\t\tprint(\"subject sid is shorter than min num of char, instance is invalid\")\n\t\t\telif a >= MIN_ID_LEN:\n\t\t\t\tprint(\"id has the correct number of characters\")\n\t\t\t\tINST_CONF = True\n\t\telse:\n\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{}' is not an string, instance is invalid\".format(([args_s]), counter))\n\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{}' is not an string, instance is invalid\".format(([args_s]), counter))\n\t\t\tvalidity_error_entries.append([args_s])\n\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\tINST_CONF = False\n\t\t\tprint(\"subject sid is not string\")\n\t\tif (len(b)>(0)):\n\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{}' has id '{}' that contains {} white spaces, instance is invalid\".format(([args_s]), counter, id, len(b)))\n\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{}' has id '{}' that contains {} white spaces, instance is invalid\".format(([args]), counter, id, len(b)))\n\t\t\tvalidity_error_entries.append([args_s])\n\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\tSPACES = False\n\t\t\tprint(\"Subject id contains white spaces instance is invalid\")\n\t\telif (len(b)==0):\n\t\t\tSPACES = True\n\t\t\tprint(\"There are not white spaces\")\n\t\t\"\"\"\n\t\tThe following lines test gender\n\t\t\"\"\"\n\t\ttry:\n\t\t\tGender[gender] in valEnumGender\n\t\t\tGNDR = True\n\t\t\tprint(\"subject gender is correct instance is valid\")\n\t\texcept KeyError:\n\t\t\tGNDR = False\n\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{}' has an incorrect gender '{}' instance is invalid\".format((args), counter, gender))\n\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{}' has an incorrect gender '{}' instance is invalid\".format((args), counter, gender))\n\t\t\tvalidity_error_entries.append(args_s)\n\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\tprint(\"subject gender is not correct instance is invalid\")\n\t\t\"\"\"\n\t\tThe following lines test date format and age\n\t\t\"\"\"\n\t\ttotyear =''\n\t\ttry:\n\t\t\tdatetime.strptime(dob, \"%Y-%m-%d\")\n\t\t\tDATE_FORMT = True\n\t\t\tprint(\"dob is in the correct format\")\n\t\texcept ValueError:\n\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{}' has dob '{}' that is not a correct date format instance is invalid\".format((args), counter, dob))\n\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{}' has dob '{}' that is not a correct date format instance is invalid\".format((args), counter, dob))\n\t\t\tvalidity_error_entries.append(args_s)\n\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\tDATE_FORMT = False\n\t\t\tprint(\"dob is not in the correct format instance is invalid\")\n\t\tif DATE_FORMT == True:\n\t\t\tdate = datetime.strptime(dob, \"%Y-%m-%d\")\n\t\t\tpresent = datetime.today().strftime('%Y-%m-%d')\n\t\t\tpresent1 = datetime.strptime(present, '%Y-%m-%d')\n\t\t\t(abs(present1 - date)).days\n\t\t\tif ((abs(present1 - date)).days < (54750)):\n\t\t\t\tYOUNG = True \n\t\t\t\tprint(\"subject is younger than 150 years\")\n\t\t\telif ((abs(present1 - date)).days > (54750)):\n\t\t\t\tYOUNG = False\n\t\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{}' has dob '{}' indicating subject is older than 150 years, instance is invalid\".format((args), counter, dob))\n\t\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{}' has dob '{}' indicating subject is older than 150 years, instance is invalid\".format((args), counter, dob))\n\t\t\t\tvalidity_error_entries.append(args_s)\n\t\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\t\tprint(\"the subject is too old, the instance is invalid\")\n\t\telif DATE_FORMT == False:\n\t\t\tprint(\"Date format is not correct, instance is invalid\")\n\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{}' has dob '{}' with incorrect format, instance is invalid\".format((args), counter, dob))\n\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{}' has dob '{}' with incorrect format, instance is invalid\".format((args), counter, dob))\n\t\t\tvalidity_error_entries.append(args_s)\n\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\"\"\"\n\t\tThe following lines test wheather a disease status has been assigned to the subject\n\t\t\"\"\"\n\t\ttry:\n\t\t\tXStatus[x_status] in valEnumXStatus\n\t\t\tprint(\"subject disease status is correct\")\n\t\t\tXS =True\n\t\texcept KeyError:\n\t\t\tXS = False\n\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{} has incorrect 'x_status '{}' instance is not valid\".format((args_s), counter, x_status))\n\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{} has incorrect 'x_status '{}' instance is not valid\".format((args_s), counter, x_status))\n\t\t\tvalidity_error_entries.append(args_s)\n\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\tprint(\"subject disease status is not correct or missing\")\n\t\ttry:\n\t\t\tTraining_testing[assi_in_exp] in valEnumTraining_testing\n\t\t\tprint(\"subject was correctly assigned to training or testing\")\n\t\t\tTRANG = True\n\t\texcept KeyError:\n\t\t\tTRANG = False\n\t\t\tvalidity_errors.append(\"\\nInstance {} located at row '{} has undetermined assigment to training ot testing '{}' instance is not valid\".format((args_s), counter, assi_in_exp))\n\t\t\tsys.stderr.write(\"\\nInstance {} located at row '{} has undetermined assignment to training/testing '{}' instance is not valid\".format((args_s), counter, assi_in_exp))\n\t\t\tvalidity_error_entries.append(args_s)\n\t\t\tvalidity_error_ids_l.append(args[0])\n\t\t\tprint(\"subject training or testing field is incorrect\")\n\t\tattrs = [INST_CONF, SPACES, YOUNG, GNDR, DATE_FORMT, XS, TRANG]\n\t\tprint(attrs)\n\t\taccepted_instances_l = []\n\t\trejected_instances_l = []\n\t\taccepted_entries = [x for x in individual_entries_1 if instance_validated == True]\n\t\tif all(attrs) ==True:\n\t\t\tinstance_validated = True\n\t\t\t#global accepted_instances_l\n\t\t\t#accepted_instances_l =[]\n\t\t\tprint(\"Instance validated =\", instance_validated)\n\t\t\tprint(args)\n\t\t\taccepted_instances_l.append((args))\n\t\t\tprint(accepted_instances_l)\n\t\t\tprint(\"instance '{}' in row '{}' satisfies all tests\".format((args_s), counter))\n\t\t\tprint(\"\\n\")\n\t\t\tprint(\"==========================================================================================\")\n\t\t\tprint(\"\\n\")\n\t\telse:\n\t\t\tinstance_validated = False\n\t\t\t#global rejected_instances_l\n\t\t\t#rejected_instances_l =[]\n\t\t\tprint(\"Instance validated =\", instance_validated)\n\t\t\trejected_instances_l.append((args))\n\t\t\trows_of_all_invalidated_instances.append(counter)\n\t\t\tprint(rejected_instances_l)\n\t\t\tprint(args)\n\t\t\tprint(\"instance '{}' in row '{}' fails one or more tests\".format((args_s), counter))\n\t\t\tprint(\"\\n\")\n\t\t\tprint(\"==========================================================================================\")\n\t\t\tprint(\"\\n\")\n\t\taccepted_entries = [x for x in individual_entries_1 if instance_validated == True]\n\t\trejected_entries = [x for x in individual_entries_1 if instance_validated == False]\n\t\tpprint.pprint(accepted_entries)\n\t\tprint(\"separator\")\n\t\tpprint.pprint(rejected_entries)\n\n\t\treturn accepted_instances_l, rejected_instances_l, validity_error_entries\n\n\t\"\"\"\n\t@classmethod\n\tdef tables_out(cls, individual_entries_1):\n\t\tif counter == (len(individual_entries_1)):\n\t\t\tprint(accepted_instances_l)\n\t\t\tprint(rejected_instances_l)\n\t\t\tprint(counter)\n\t\telif counter < (len(individual_entries_1)):\n\t\t\tprint(\"will continue looping\", counter)\n\n\t\telse:\n\t\t\tpass\n\t\tprint(accepted_instances_l)\n\t\tprint(rejected_instances_l)\n\t\tprint(counter)\n\t\"\"\"\n\n\"\"\"\n@staticmethod\ndef organize_data():\nprint(accepted_instances_l)\nprint(rejected_instances_l)\n\n\n\n@classmethod\ndef prepare_data(cls, attrs, id, gender, dob, x_status, assi_in_exp, extra_fields, counter, individual_entries_1):\naccepted_instances_l = []\nif all(attrs) == True:\ninstance_validated = True\naccepted_instances_l.append(args_s)\nprint(accepted_instances_l)\nrows_of_all_validated_instances.append(counter)\nprint(\"instance '{}' in row '{}' satisfies all tests\".format((args_s), counter))\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\n\")\n\nif counter < len(individual_entries_1):\nreturn args, args_s, validity_error_entries, validity_error_ids_l, instance_validated, individual_entries_1, counter, attrs, accepted_instances_l\nelif counter == len(individual_entries_1):\ncls.prepare_data()\nreturn args, args_s, validity_error_entries, validity_error_ids_l, instance_validated, individual_entries_1, counter, attrs, rejected_instances_l\nelse:\npass\n\nelse:\ninstance_validated = False\nrejected_instances_l.append(args_s)\nrows_of_all_invalidated_instances.append(counter)\nprint(rejected_instances_l)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\n\")\nprint(\"instance '{}' in row '{}' fails one or more tests\".format((args_s), counter))\n\nreturn args, args_s, validity_error_entries, validity_error_ids_l, instance_validated, individual_entries_1, counter, attrs, rejected_instances_l\n\n\n\nif counter < len(individual_entries_1):\nreturn args, args_s, validity_error_entries, validity_error_ids_l, instance_validated, individual_entries_1, counter, attrs, accepted_instances_l\nelif counter == len(individual_entries_1):\ncls.prepare_data()\nreturn args, args_s, validity_error_entries, validity_error_ids_l, instance_validated, individual_entries_1, counter, attrs, rejected_instances_l\nelse:\npass\n\n\n\n\n@classmethod\ndef prepare_tables(cls, data_2, data_1, individual_entries_1, validity_error_entries, validity_error_ids_l, extra_field_error_entries, extra_field_error_ids_l, field_error_entries, field_error_ids_l, instance_validated):\nprint(\"test\")\naccepted_instances_df = pd.DataFrame(accepted_instances_l)\naccepted_instances_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'assi_in_exp', 5:'extra_fields'}, inplace = True)\nrejected_instances_df = pd.DataFrame(rejected_instances_l)\nrejected_instances_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'assi_in_exp', 5:'extra_fields'}, inplace = True)\npprint.pprint(accepted_instances_df)\npprint.pprint(rejected_instances_df)\nprint(\"test\")\n\n\nindividual_entries_5_l = []\nall_errors_l = (field_error_entries + validity_error_entries + extra_field_error_entries)\nall_errors_df =pd.DataFrame(all_errors_l)\nall_errors_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'assi_in_exp', 5:'extra_fields'}, inplace = True)\ndict_of_all_errors = dict((i, j) for i, j in enumerate(all_errors_l))\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances with missing data, validity errors and extra_field_errors These subjects cannot be analyzed. They are part of class can_not be analyzed\")\nprint(\"\\nThese instances were extracted from the input data file and after the cleaning process\")\nprint(\"math_proof\")\npprint.pprint(all_errors_df)\ncannot_analyze = all_errors_df\n\nindividual_entries_final = [x for x in individual_entries_1 if x not in all_errors_l]\nindividual_entries_final_df =pd.DataFrame(individual_entries_final)\nprint(\"math_proof\")\npprint.pprint(individual_entries_final_df)\nindividual_entries_2 = [x for x in individual_entries_1 if x not in field_error_entries]\nindividual_entries_3 = [x for x in individual_entries_2 if x not in validity_error_entries]\nindividual_entries_4 = [x for x in individual_entries_3 if x not in extra_field_error_entries]\nindividual_entries_4_df =pd.DataFrame(individual_entries_4)\nprint(\"math_proof\")\npprint.pprint(individual_entries_4_df)\nfor item in individual_entries_4:\nif item not in individual_entries_5_l:\nindividual_entries_5_l.append(item)\nelse:\npass\n\n#print(\"data frame substraction\")\n#validated_df = data_2.subtract(all_errors_df)\n#pprint.pprint(validated_df)\n#accepted_subjects2 =list(set(individual_entries_1)-set(all_errors_l))\n\naccepted_subjects2 = [i for i in individual_entries_1 + all_errors_l]\n\naccepted_subjects2 =((individual_entries_1)-(all_errors_l))\nprint(accepted_subjects_2)\n\n#s = set(all_errors_l)\naccepted_subjects = [x for x in individual_entries_1 if x not in s]\nprint(accepted_subjects)\naccepted_subjects_df = pd.DataFrame(accepted_subjects)\npprint.pprint(accepted_subjects_df)\n\n\nprint(\"These entries are the list of instances without errors and duplicates. These are the instances that can be analyzed and they will be divided into correct and incorrect classifications\")\nall_validated_ins_s_df = pd.DataFrame(individual_entries_5_l)\nall_validated_ins_s_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'assi_in_exp', 5:'extra_fields'}, inplace = True)\npprint.pprint(all_validated_ins_s_df)\nall_validated_ins_1_s_df = pd.DataFrame(all_validated_ins_s_df)\npprint.pprint(all_validated_ins_1_s_df)\n#all_validated_ins_2_s_df = all_validated_ins_1_s_df.drop(all_validated_ins_1_s_df.index[0], axis = 0)\nall_validated_ins_2_s_df = all_validated_ins_1_s_df.drop((['extra_fields']), axis = 1)\npprint.pprint(all_validated_ins_2_s_df)\n\n\nthe following produce outfiles for the following: list of errors due to extra_fields, 2. list of errors due to misisng data, \n3. list of errors due to incorrect data entries. 4. All validated data without duplicates. The files are text files to be found in your path\n\nextra_field_error_entries_df = pd.DataFrame(extra_field_error_entries)\nextra_field_error_entries_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'extra_fields'}, inplace = True)\nfield_error_entries_df = pd.DataFrame(field_error_entries)\nfield_error_entries_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'extra_fields'}, inplace = True)\nvalidity_error_entries_df = pd.DataFrame(validity_error_entries)\nvalidity_error_entries_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'extra_fields'}, inplace = True)\nfield_error_entries_df.to_csv('Instances_with_missing_data.txt', header = True, sep='\\t', index = False)\nextra_field_error_entries_df.to_csv('Instances_with_additional_entries.txt', header=True,sep = '\\t', index = False)\nvalidity_error_entries_df.to_csv('Instances_with_wrong_data_values.txt', header = True, sep='\\t', index = False)\nall_validated_ins_2_s_df.to_csv('All_valid_entries.txt', header = True, sep='\\t', index = False)\nall_errors_df.to_csv('all_errors_cannot analyze.txt', header = True, sep='\\t', index = False)\nall_validated_ins_2_s_df.to_csv('Analyzable entries.txt', header = True, sep='\\t', index = False)\n\nthe following code encapsulates all entries into a a dictionary\n\n\n\nkeys = [cannot_analyze, can_analyze, correctly_classified, incorrectly_classified]\nvalues = [all_errors_l, individual_entries_5_l, all_correctly_classified_l, all_incorrectly_classified_l]\n\n@staticmethod\ndef pass_all_msgs(self, msgs):\nsys.stderr.write('\\n'.join(errors))\nsys.stderr.write('\\n')\n\n\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\n\")\npprint.pprint(all_validatedInstances_l)\npprint.pprint(all_validatedInstances_ids_l)\nall_validated_instances_df = pd.DataFrame(all_validatedInstances_l)\npprint.pprint(all_validated_instances_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\n\")\npprint.pprint(all_invalidatedInstances_l)\npprint.pprint(all_invalidatedInstances_ids_l)\nall_invalidated_instances_df = pd.DataFrame(all_invalidatedInstances_l)\npprint.pprint(all_invalidated_instances_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\n\")\n\n@classmethod\ndef prepare_data(cls, sid, all_validatedInstances_l, all_validatedInstances_ids_l, rows_of_all_validated_instances, all_invalidatedInstances_l, all_invalidated_instances_ids_l, rows_of_all_invalidated_instances, validity_errors):\n\n\nThis class method takes the input from the subject verify and adds accepted instances to a list\n\nall_validatedInstnaces_l =[]\nindividual_entries_4_l = []\nall_validated_ins_s_df = []\nall_validated_ins_1_s_df = []\nall_validated_ins_2_s_df = []\nall_validated_ins_2_s_df = []\nall_validated_ins_2_s_df = []\nall_validated_instances_df =[]\nall_validated_instances_df = pd.DataFrame(all_validatedInstances_l)\nall_validated_instances_df.rename(columns = {0 : 'sid', 1: 'gender', 2: 'dob', 3:'x_status', 4:'assi_in_exp', 5:'extra_fields'}, inplace = True)\ndict_of_all_validated = dict((i, j) for i, j in enumerate(all_validatedInstnaces_l))\npprint.pprint(all_validated_instances_df)\nall_errors_l = field_error_entries + validity_error_entries + extra_field_error_entries\nall_errors_df =pd.DataFrame(all_errors_l)\nall_errors_df.rename(columns = {0 : 'sid', 1: 'gender', 2: 'dob', 3:'x_status', 4:'assi_in_exp', 5:'extra_fields'}, inplace = True)\ndict_of_all_errors = dict((i, j) for i, j in enumerate(all_errors_l))\nall_errors_l = field_error_entries + validity_error_entries + extra_field_error_entries\nall_errors_df =pd.DataFrame(all_errors_l)\nall_errors_df.rename(columns = {0 : 'sid', 1: 'gender', 2: 'dob', 3:'x_status', 4:'assi_in_exp', 5:'extra_fields'}, inplace = True)\ndict_of_all_errors = dict((i, j) for i, j in enumerate(all_errors_l))\ncannot_analyze = all_errors_l\ncannot_analyze_runs_df = all_errors_df\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances with missing data. These subjects cannot be analyzed. They are part of class can_not be analyzed\")\nprint(\"\\nThese instances were extracted from the input data file and after the cleaning process\")\npprint.pprint(all_errors_df)\n\nthe following entries create data frames and lists for the list of all valid entries. Valid entries are found by substraction of errors\n\nindividual_entries_1 = [x for x in individual_entries if x not in field_error_entries]\nindividual_entries_2 = [x for x in individual_entries_1 if x not in validity_error_entries]\nindividual_entries_3 = [x for x in individual_entries_2 if x not in extra_field_error_entries]\nfor item in individual_entries_3:\nif item not in individual_entries_4_l:\nindividual_entries_4.append(item)\nelse:\npass\nall_validated_ins_s_df = pd.DataFrame(individual_entries_4_l)\nall_validated_ins_s_df.rename(columns = {0 : 'sid', 1: 'gender', 2: 'dob', 3:'x_status', 4:'assi_in_exp', 5:'extra_fields'}, inplace = True)\nall_validated_ins_1_s_df = pd.DataFrame(all_validated_ins_s_df)\nall_validated_ins_2_s_df = all_validated_ins_1_s_df.drop_duplicates[(sid)]\nall_validated_ins_2_s_df = all_validated_ins_2_s_df.drop(all_validated_ins_2_s_df.index[0], axis = 0)\nall_validated_ins_2_s_df = all_validated_ins_2_s_df.drop(['extra_fields'], axis = 1)\npprint.pprint(all_validated_ins_2_s_df)\n\n@staticmethod\ndef pass_all_msgs(self, msgs):\nif errors:\nsys.stderr.write('\\n'.join(errors))\nsys.stderr.write('\\n')\n\n\n\nkeys_validated = rows_of_all_validated_instances\nvalues_validated = all_validatedInstances_ids_l\ndict_of_all_validated_instances = dict(zip(keys_validated, values_validated))\nkeys_invalidated = rows_of_all_invalidated_instances\nvalues_invalidated = all_invalidatedInstances_ids_l\ndict_of_all_invalidated_instances = dict(zip(keys_invalidated, values_invalidated))\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\n\")\npprint.pprint(all_validatedInstances_l)\npprint.pprint(dict_of_all_validated_instances)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\n\")\nprint(dict_of_all_invalidated_instances)\nprint(\"popo\")\ndict_of_duplicates = {}\nd = defaultdict(list)\nfor k, v in dict_of_all_validated_instances.items():\nd[k].append(v)\nprint(d)\nprint(\"pop\")\ndict_of_duplicates = {}\nd = defaultdict(set)\nfor k, v in dict_of_all_validated_instances.items():\nd[k].add(v)\nprint(d)\nfor k, v in dict_of_all_validated_instances.items():\ndict_of_duplicates = dict((dict_of_all_validated_instances[k], k) for k in dict_of_all_validated_instances)\nprint(\"pop\")\nprint(dict_of_duplicates)\nprint(\"pop\")\n\nif instance_validated == True:\nall_subject_ids_l.append(args_s[0])\nall_duplicates_l = []\nall_subject_ids_l = []\nfor arg_s[0] in args_s:\nif args_s[0] in all_duplicates_l:\nduplicate_errors.append(\"\\ninstance {} located at row '{} has same id '{}' as other instance, instance is not valid\".format((args_s), counter))\nduplicate_error_entries.appedn(args_s)\nelif args_s[0] not in all_duplicates_l: \nall_accepted_entries.append(args_s)\nprint(\"instance has no duplicates and can be analyzed\")\nelse:\npass\nelif instance_validated == False:\n\ndict_of_all_duplicates = dict((i, j) for i, j in enumerate(all_duplicates_l))\nprint(all_duplicates_l)\t\ndict_of_all_accepted_entries = dict((i, j) for i, j in enumerate(all_accepted_entries_l))\nprint(dict_of_all_accepted_entries)\n\n\n\n@classmethod\ndef prep_data_after_class_run(cls):\n\n\nThe clean_data method takes all the files corresponding to: entries with missing data,\nentries with data that are incorrect and entries with additional fields of data and the accepted entries. The\nmethod sequentially removes incorrect data and leaves a pandas data frame without duplicates and errors.\nThe different types of entries are sent to csv files. The data_3_final is the df that contains the data for \nclassification Runs. The output includes all_incorrect_entries, all_valid_entries and in order to simulate the \ndata analysis also the correctly classified and incorrectly classified. The Can not analyze data is the same as the\nall_incorrect_entries. I use pandas data frames to better analyze and manipulate the data. I also utilize dictionaries \nand the enumerate class to store the results of\nthe runs\n\nclass_output_dict = {}\nindividual_entries_1 = []\nindividual_entries_2 =[]\nindividual_entries_3 =[]\nindividual_entries_4 = []\ndata_2 = ()\ndata_3 = ()\ndata_3_final=()\nextra_field_error_entries_df = ()\nfield_error_entries_df = ()\nvalidty_error_entries_df = ()\ndata_all_incorrectly_classified = ()\ndata_all_correctly_classified = ()\nlist_of_incorrectly_classified =[]\nlist_of_correctly_classified = []\ncorrectly_classified = ''\nincorrectly_classified = ''\n\nTo determine if the subjects are acceptable for classification run an analysis each subject must fullfill the condition that it must be assigned to a \na training or testing condition. If the subject was not assigned to either training or testing the subject must be rejected regardless of the quality of\nthe initial data. To simulate assignment to training or testing I will randomly generate three values: testing, training or No assignment. Then those values \nwill be assigned to a column to be added to pandas data frame containing subjects\n\nthe following entries create data frames and lists for the list of all errors\n\n\nall_errors_l = field_error_entries + validity_error_entries + extra_field_error_entries\nall_errors_df =pd.DataFrame(all_errors_l)\nall_errors_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'extra_fields'}, inplace = True)\ndict_of_all_errors = dict((i, j) for i, j in enumerate(all_errors_l))\ncannot_analyze = all_errors_l\ncannot_analyze_runs_df = all_errors_df\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances with missing data. These subjects cannot be analyzed. They are part of class can_not be analyzed\")\nprint(\"\\nThese instances were extracted from the input data file and after the cleaning process\")\npprint.pprint(cannot_analyze_runs_df)\nprint(\"ppe\")\n\nthe following entries create data frames and lists for the list of all valid entries. Valid entries are found by substraction of errors\n\nindividual_entries_1 = [x for x in individual_entries if x not in field_error_entries]\nindividual_entries_2 = [x for x in individual_entries_1 if x not in validity_error_entries]\nindividual_entries_3 = [x for x in individual_entries_2 if x not in extra_field_error_entries]\nfor item in individual_entries_3:\nif item not in individual_entries_4:\nindividual_entries_4.append(item)\nelse:\npass\nall_validated_ins_df = pd.DataFrame(individual_entries_4)\nall_validated_ins_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'extra_fields'}, inplace = True)\nall_validated_ins_1_df = pd.DataFrame(all_validated_ins_df)\nall_validated_ins_2_df = all_validated_ins_1_df.drop_duplicates('id')\nall_validated_ins_2_df = all_validated_ins_2_df.drop(all_validated_ins_2_df.index[0], axis = 0)\nall_validated_ins_2_df = all_validated_ins_2_df.drop(['extra_fields'], axis = 1)\npprint.pprint(all_validated_ins_2_df)\n\nthe following entries create data frames and lists for the list of all valid entries\n\ncan_analyze = individual_entries_4\nall_validated_ins_3_df =pd.DataFrame(all_validated_ins_2_df)\ndict_of_all_valid_entries = dict((i, j) for i, j in enumerate(individual_entries_4))\n\n\nthe following entries create data frames and lists for the list of all incorrectly classified. This is a simulated data set.\n\nall_incorrectly_classified_df = pd.read_csv(file_name3, delimiter='\\t', names=['id', 'gender', 'dob', 'x_status'])\nall_incorrectly_classified_l = all_incorrectly_classified_df.values.tolist()\ndict_of_all_incorrectly_classified = dict((i, j) for i, j in enumerate(all_incorrectly_classified_l))\nall_incorrectly_classified_df.drop(all_incorrectly_classified_df.index[0], inplace = True)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances that contain valid data. The instances were analyzed, however they are incorrectly classified\")\nprint(\"\\n These instances are 'defined' as incorrectly classified, the instances were created\")\npprint.pprint(all_incorrectly_classified_df)\n\n\nall_correctly_classified_df = pd.read_csv(file_name2, delimiter='\\t', names=['id', 'gender', 'dob', 'x_status'])\nall_correctly_classified_l = all_correctly_classified_df.values.tolist()\ndict_of_all_correctly_classified = dict((i, j) for i, j in enumerate(all_correctly_classified_l))\ncorrectly_classified_runs_df = pd.DataFrame(all_correctly_classified_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances that contain correct data. The instances were analyzed, however they are correctly classified\")\nprint(\"\\nThese instances are 'defined' as incorrectly classified, the instances were created\")\npprint.pprint(correctly_classified_runs_df)\n\nthe following produce outfiles for the following: list of errors due to extra_fields, 2. list of errors due to misisng data, \n3. list of errors due to incorrect data entries. The files are text files to be found in your path\n\nextra_field_error_entries_df = pd.DataFrame(extra_field_error_entries)\nextra_field_error_entries_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'extra_fields'}, inplace = True)\nfield_error_entries_df = pd.DataFrame(field_error_entries)\nfield_error_entries_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'extra_fields'}, inplace = True)\nvalidity_error_entries_df = pd.DataFrame(validity_error_entries)\nvalidity_error_entries_df.rename(columns = {0 : 'id', 1: 'gender', 2: 'dob', 3:'x_status', 4:'extra_fields'}, inplace = True)\nfield_error_entries_df.to_csv('Instances_with_missing_data.txt', header = True, sep='\\t', index = False)\nextra_field_error_entries_df.to_csv('Instances_with_additional_entries.txt', header=True,sep = '\\t', index = False)\nvalidity_error_entries_df.to_csv('Instances_with_wrong_data_values.txt', header = True, sep='\\t', index = False)\nall_validated_ins_3_df.to_csv('All_valid_entries.txt', header = True, sep='\\t', index = False)\nall_errors_df.to_csv('all_errors_cannot analyze.txt', header = True, sep='\\t', index = False)\nall_validated_ins_3_df.to_csv('Analyzable entries.txt', header = True, sep='\\t', index = False)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances with missing data. These subjects cannot be analyzed. Instances here belog to the cannot analyze data set\")\nprint(\"\\nThese instances were removed after cleaning the data using subjects.py These instances also contribute to define the cannot_analyze_runs\")\npprint.pprint(field_error_entries_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances with extra_fields. These instances cannot be analyzed\")\nprint(\"\\nThese instances were removed after cleaning the data using subjects.py.These instances also contribute to define the cannot_analyze_runs\")\npprint.pprint(extra_field_error_entries_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances with invalid data entries. These instances cannot be analyzed\")\nprint(\"\\nThese instances were removed after cleaning the data using subjects.py. These instances also contribute to define the cannot_analyze_runs\")\npprint.pprint(validity_error_entries_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following are instances ready for Analysis of classification runs. They have unique IDs and no duplicates\")\nprint(\"\\nThese instances were obtained throuhg the cleaning process of the file subjects.py These instances define the can analyze set of data\")\npprint.pprint(all_validated_ins_3_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following instances are instances that contain valid data entries and that were classified incorrectly\")\nprint(\"\\nThe instances here include the data that passed through cleaning using subjects.py and simulated data\")\npprint.pprint(all_incorrectly_classified_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\nThe following instances are instances that contain valid data entries and that were classified correctly\")\nprint(\"\\nThe instances here include the data that passed through cleaning using subjects.py and simulated data\")\npprint.pprint(all_correctly_classified_df)\nprint(\"\\n\")\nprint(\"==========================================================================================\")\nprint(\"\\n\")\nprint(\"The dictionary defining the classification output is :\")\nprint(\"\\n The dictionary uses as keys the enumeration of outcomes and as values the enumation of the lists of correct and incorrect data \")\nkeys = [cannot_analyze, can_analyze, correctly_classified, incorrectly_classified]\nvalues = [all_errors_l, individual_entries_4, all_correctly_classified_l, all_incorrectly_classified_l]\nfor i in range(0, len(keys)):\nclass_output_dict[i] = values [i]\nprint(class_output_dict)\nincorrectly_classified_runs_df = pd.DataFrame(all_incorrectly_classified_l)\nincorrectly_classified_runs_df ['run_time'] =str(datetime.now())\npprint.pprint(incorrectly_classified_runs_df)\ncorrectly_classified_runs = pd.DataFrame(all_correctly_classified_df)\ncorrectly_classified_runs ['run_time']=str(datetime.now())\ncannot_analyze_runs = pd.DataFrame(all_errors_l)\ncannot_analyze_runs ['run_time']=str(datetime.now())\npprint.pprint(incorrectly_classified_runs_df)\npprint.pprint(correctly_classified_runs_df)\npprint.pprint(cannot_analyze_runs_df)\n#print(\"\\nThe Dictionary and the associated enumeration can be utilized for the accessing the Runs data\")\nreturn\n\n@classmethod\ndef Classification_runs_load_prepare(cls, incorrectly_classified_runs_df, correctly_classified_runs_df, cannot_analyze_runs_df):\n\n@staticmethod\ndef pass_all_msgs(self, msgs):\nif errors:\nsys.stderr.write('\\n'.join(errors))\nsys.stderr.write('\\n')\n\n\n\nclass ClassificationRun(Subject):\n\nThis is the classification class. This class can be called directly by the user or follow after the \nSubject class.\n\n\n\ndef __init__(self, id, timestamp, training, testing, class_out, data_3):\nself.id = id\nself.class_out = Class_Out[Enum]\nself.timestamp = timestamp\nself.training = training\nself.testing = testing\nself.data_3 = data_3\n\nprint(\"popo\")\n\ndef load_desc_data_final_df(cls,data_3):\npprint.pprint(data_3)\ndata_3.describe()\n\"\"\"\n\"\"\"\nfile_name3 = \"subjectinfo3.tsv\"\nfile_name2 = \"subjectinfo1.tsv\" \n\"\"\"\nfile_name1 = \"Subjectinfo7.tsv\"\n\"\"\"This file sill simulate the cleaning process. Incorrect entries are removed from the file and correct entries retain for data analysis\"\"\"\nSubject.load_file(file_name1)\n#Subject.RunClassification(file_name2, file_name3)","sub_path":"Assignment 6- Object-oriented program/Student assignments/Fredy_Reyes/old/hmw006v20.py","file_name":"hmw006v20.py","file_ext":"py","file_size_in_byte":49352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"25527406","text":"#!/usr/bin/python2.5\n# Copyright 2011 JatLeGo Inc. All Rights Reserved.\n# Author: andyzh1314@gmail.com (Andy Zhau)\n\nimport new\nimport re\n\nfrom google.appengine.ext import db\n\nfrom sfdb import db as sfdb\nfrom sfdb import query as query_lib\nfrom sfdb.repository.repository import Repository\nfrom util import simplejson as json_lib\n\nclass_dict = {\n sfdb.Property: db.Property,\n sfdb.BooleanProperty: db.BooleanProperty,\n sfdb.IntegerProperty: db.IntegerProperty,\n sfdb.FloatProperty: db.FloatProperty,\n sfdb.TimestampProperty: db.FloatProperty,\n sfdb.ListProperty: db.ListProperty,\n\n sfdb.StringProperty: db.ByteStringProperty,\n sfdb.PasswordProperty: db.ByteStringProperty,\n sfdb.EmailProperty: db.ByteStringProperty,\n sfdb.JSONProperty: db.ByteStringProperty,\n sfdb.IDProperty: db.ByteStringProperty,\n sfdb.DBRefProperty: db.ByteStringProperty,\n sfdb.CounterProperty: db.ByteStringProperty,\n sfdb.ListRefProperty: db.ByteStringProperty,\n\n sfdb.dbref: db.ByteString,\n str: str,\n unicode: unicode,\n}\n\n\n_TYPE_DICT = {\n sfdb.objid: 0,\n sfdb.json : 1,\n sfdb.dbref: 2,\n sfdb.counter: 3,\n basestring: 4,\n sfdb.list: 6,\n}\n\n_TYPE_REV_DICT = {\n 0: sfdb.objid,\n 1: sfdb.json,\n 2: sfdb.dbref,\n 3: sfdb.counter,\n 4: unicode,\n 6: sfdb.list,\n}\n\n\ndef _encode_dbref(ref):\n if ref._mcs_name:\n return (chr(len(ref._mcs_name)) + ref._mcs_name +\n chr(len(ref._id.key)) + ref._id.key)\n else:\n return chr(0) + chr(len(ref._id.key)) + ref._id.key\n\ndef _encode_counter(cnt):\n return (chr(len(cnt.mcs.__name__)) + cnt.mcs.__name__ +\n _encode_dbref(cnt.counter_ref))\n\ndef _encode_json(json_obj):\n return json_lib.dumps(json_obj.obj)\n\ndef _encode_listref(l):\n return (chr(len(l.mcs.__name__)) + l.mcs.__name__ +\n _encode_dbref(l.list_ref))\n\ndef _decode_dbref(en_ref):\n offset = 0\n l = ord(en_ref[offset])\n offset += 1\n if l: mcs_name = en_ref[offset:offset + l]\n else: mcs_name = None\n offset += l\n l = ord(en_ref[offset])\n offset += 1\n id = sfdb.objid(en_ref[offset:offset + l])\n offset += l\n return sfdb.dbref(id, mcs_name)\n\ndef _decode_counter(en_cnt):\n offset = 0\n l = ord(en_cnt[offset])\n offset += 1\n mcs = sfdb.Model.__model_dict__.get(en_cnt[offset:offset + l])\n offset += l\n counter_ref = _decode_dbref(en_cnt[offset:])\n return sfdb.counter(counter_ref=counter_ref, mcs=mcs)\n\ndef _decode_json(en_json):\n return sfdb.json(json_lib.loads(en_json))\n\ndef _decode_listref(en_list):\n offset = 0\n l = ord(en_list[offset])\n offset += 1\n mcs = sfdb.Model.__model_dict__.get(en_list[offset:offset + l])\n offset += l\n list_ref = _decode_dbref(en_list[offset:])\n return sfdb.list(list_ref, mcs)\n\ndef _encode(obj):\n if isinstance(obj, sfdb.objid):\n return db.ByteString(chr(_TYPE_DICT[sfdb.objid]) + obj.key)\n if isinstance(obj, sfdb.dbref):\n return db.ByteString(chr(_TYPE_DICT[sfdb.dbref]) + _encode_dbref(obj))\n if isinstance(obj, sfdb.counter):\n return db.ByteString(chr(_TYPE_DICT[sfdb.counter]) + _encode_counter(obj))\n if isinstance(obj, sfdb.json):\n return db.ByteString(chr(_TYPE_DICT[sfdb.json]) + _encode_json(obj))\n if isinstance(obj, sfdb.list):\n return db.ByteString(chr(_TYPE_DICT[sfdb.list]) + _encode_listref(obj))\n if isinstance(obj, str):\n return db.ByteString(chr(_TYPE_DICT[basestring]) + obj)\n if isinstance(obj, unicode):\n return db.ByteString(chr(_TYPE_DICT[basestring]) + obj.encode(\"utf-8\"))\n if isinstance(obj, list):\n return [_encode(val) for val in obj]\n if sfdb.issfdbinstance(obj, sfdb.time):\n return sfdb.time.getval(obj)\n return obj\n\ndef _decode(s):\n if isinstance(s, basestring):\n typ = _TYPE_REV_DICT[ord(s[0])]\n if typ is sfdb.objid: return sfdb.objid(s[1:])\n if typ is sfdb.dbref: return _decode_dbref(s[1:])\n if typ is sfdb.counter: return _decode_counter(s[1:])\n if typ is sfdb.json: return _decode_json(s[1:])\n if typ is unicode: return unicode(s[1:].decode(\"utf-8\"))\n if typ is sfdb.list: return _decode_listref(s[1:])\n raise ValueError(\"Internal error.\")\n if isinstance(s, list):\n return [_decode(val) for val in s]\n return s\n\ndef _id_to_key(objid):\n return db.Key(encoded=objid.key)\n\ndef _key_to_id(key):\n return sfdb.objid(\"%s\" % key)\n\ndef _get_match_cls(sfdb_model_class):\n new_properties = {}\n for key, prop in sfdb_model_class.__declared_properties__.iteritems():\n if isinstance(prop, sfdb.ListProperty):\n new_properties[key] = db.ListProperty(class_dict[prop.item_type],\n indexed=prop.indexed)\n else:\n new_properties[key] = class_dict[type(prop)](indexed=prop.indexed)\n\n db_cls = issubclass(sfdb_model_class, sfdb.SFModel) and db.Expando or db.Model\n return new.classobj(sfdb_model_class.__name__, (db_cls, ), new_properties)\n\ndef _sfdb_to_app(sf_model, appengine_model_cls):\n if sf_model._id == sfdb.notset:\n result = appengine_model_cls()\n else:\n result = appengine_model_cls(key=_id_to_key(sf_model._id))\n for key, value in sf_model.to_json(fullkey=True).iteritems():\n setattr(result, key, _encode(value))\n return result\n\ndef _app_to_sfdb(appengine_model, sf_model_cls):\n result = sf_model_cls(id=_key_to_id(appengine_model.key()),\n _type=_decode(appengine_model._type))\n for name in appengine_model.__class__.properties():\n if name != \"_type\":\n attr_type = re.search(\"(__(global|item|meta)__)\", name)\n if attr_type and attr_type.group(1) != result._type:\n continue\n des_name = re.sub(\"__(global|item|meta|counter)__\", \"\", name)\n setattr(result, des_name, _decode(getattr(appengine_model, name)))\n for name in appengine_model.dynamic_properties():\n setattr(result, name, _decode(getattr(appengine_model, name)))\n return result\n\n\nclass AppEngineRepository(Repository):\n\n\n def __init__(self):\n self.class_cache = {}\n\n def get(self, mcs, ids):\n _get_match_cls(mcs)\n if isinstance(ids, sfdb.objid):\n app_model = db.get(_id_to_key(ids))\n if app_model is None: return None\n else: return _app_to_sfdb(app_model, mcs)\n else:\n keys = list(_id_to_key(id) for id in ids)\n return [_app_to_sfdb(app_model, mcs) for app_model in db.get(keys)]\n\n def save_model(self, model):\n model_class = self._get_match_cls(model.__class__)\n if model._id is sfdb.notset:\n handmade_key = db.Key.from_path(model_class.__name__, 1)\n first_batch = db.allocate_ids(handmade_key, 1)\n new_key = db.Key.from_path(model_class.__name__, first_batch[0])\n model._id = _key_to_id(new_key)\n _sfdb_to_app(model, model_class).put()\n return model\n\n def remove_model(self, model):\n model_class = self._get_match_cls(model.__class__)\n app_model = _sfdb_to_app(model, model_class)\n app_model.delete()\n\n def findall(self, mcs, query=None, namespace=None, limit=None, *args,\n **kwds):\n self._get_match_cls(mcs)\n #import logging\n #logging.info(\n #query_lib.SFQuery(query).gql_format(mcs.__name__, limit=limit, *args,\n #**kwds))\n gql_query = db.GqlQuery(\n query_lib.SFQuery(query).gql_format(mcs.__name__, limit=limit, *args,\n **kwds))\n if limit != None:\n gql_query = gql_query.fetch(limit)\n return [_app_to_sfdb(app_model, mcs) for app_model in gql_query]\n\n def finditer(self, mcs, query=None, namespace=None, *args, **kwds):\n gql_query = db.GqlQuery(q.SFQuery(query).gql_format(mcs, *args, **kwds))\n for app_model in gql_query:\n yield _app_to_sfdb(app_model)\n\n def findupdate(self, mcs, query=None, namespace=None, update=None, *args,\n **kwds):\n def updator_func(key, update):\n m = db.get(key)\n for name, value in update[\"assign\"]:\n setattr(m, name, value)\n for name, value in update[\"inc\"]:\n setattr(m, name, getattr(m, name) + value)\n db.put(m)\n return m\n\n self._get_match_cls(mcs)\n gql_query = db.GqlQuery(\n query_lib.SFQuery(query).gql_format(mcs.__name__, *args, **kwds))\n result = gql_query.fetch(1)\n app_model = result and result[0]\n if not app_model: return None\n updator = {\"assign\": [], \"inc\": []}\n if update:\n for u, v in update:\n result = re.match(r\"(\\w+)(\\=|\\+=)\", u)\n if not result: raise ValueError(\"Bad operator %s\" % u)\n if result.group(2) == \"=\":\n updator[\"assign\"].append((result.group(1), v))\n else:\n updator[\"inc\"].append((result.group(1), v))\n return _app_to_sfdb(db.run_in_transaction(updator_func, app_model.key(),\n updator), mcs)\n\n def _get_match_cls(self, sfdb_model_class):\n if sfdb_model_class not in self.class_cache:\n self.class_cache[sfdb_model_class] = _get_match_cls(sfdb_model_class)\n return self.class_cache[sfdb_model_class]\n","sub_path":"sfdb/repository/appengine_repository.py","file_name":"appengine_repository.py","file_ext":"py","file_size_in_byte":8857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"78301498","text":"\ndef numbers(L):\n pos = neg = par = impar = 0\n \n lista = L.split()\n for i in lista:\n i = int(i)\n \n if i % 2 == 0:\n par += 1\n \n if i % 2 != 0:\n impar += 1\n \n if i < 0:\n neg += 1\n \n if i > 0:\n pos += 1 \n \n return print(f\"\"\"{pos} número(s) positivo(s)\\n{neg} número(s) negativo(s)\\n{par} número(s) par(es)\\n{impar} número(s) impar(es)\"\"\".strip())\n\n\nif __name__ == \"__main__\":\n #L = list(map(int, input().split()))\n L = input()\n numbers(L)\n","sub_path":"ene-jun-2021/Jorge-de-Jesus-Hernandez-Vazquez/Practica3/testNumbers/practica1.py","file_name":"practica1.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"94973360","text":"from lotss_corr import Pointings\nimport os\n\n\ndef find_unique_batch():\n found = False\n ifile = 0\n while not found:\n fname = f'batch{ifile}.txt'\n if not os.path.isfile(fname):\n found = True\n ifile += 1\n return fname\n\npt_dr2 = Pointings('data/pointings.txt', '/mnt/extraspace/damonge/LensLotss/DR2_data/')\npt_dr1 = Pointings('data/pointings_dr1.txt', '/mnt/extraspace/damonge/LensLotss/DR1_data/', dr=1)\nfor pt in [pt_dr1, pt_dr2]:\n n_pointings = len(pt.data['name'])\n n_added = 0\n for i_n, n in enumerate(pt.data['name']):\n n = n.decode()\n #fname = pt.prefix_out + f'/{n}_fr_res.fits'\n fname = pt.prefix_out + f'/{n}_fr_rms.fits'\n if not os.path.isfile(fname):\n print(f'{n} Missing {fname}')\n exit(1)\n #fname_o = pt.prefix_out + f'/map_{n}.fits.gz'\n fname_o = pt.prefix_out + f'/map_rms_{n}.fits.gz'\n if os.path.isfile(fname_o):\n print(f'{n} skipped')\n continue\n\n print(f\"adding {i_n}-{n}\")\n if n_added == 0:\n i_n0 = i_n\n stout = \"\"\n stout += f\"{fname} {fname_o}\\n\"\n n_added += 1\n print(i_n, n_pointings)\n if (n_added == 10) or (i_n == n_pointings-1):\n fname_batch = find_unique_batch()\n f = open(fname_batch, \"w\")\n f.write(stout)\n f.close()\n comment = f'{i_n0}_{i_n}_{fname_batch}'\n queue = 'cmb'\n command = f'addqueue -c {comment} -n 1x1 -q {queue} -m 24 /usr/bin/python3 '\n #command = 'python3 '\n command += f'make_pointing_map.py {fname_batch}'\n print(command)\n os.system(command)\n n_added = 0\n","sub_path":"N_D_pipeline/run_pointings.py","file_name":"run_pointings.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"329212173","text":"#!/usr/bin/env python\n \nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom glob import glob\n\nfiles=glob('src/*.cpp')\n\nsetup(name=\"pyrvo2\",\n ext_modules=[\n Extension(\"pyrvo2\", \n \tfiles,\n libraries = [\"boost_python\"]),\n ])\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"589272885","text":"import os\nimport boto3\nfrom pyqldb.driver.pooled_qldb_driver import PooledQldbDriver\n\nQLDB_ENDPOINT = os.environ.get('QLDB_ENDPOINT') or 'http://localhost:4566'\n\n\ndef create_list_tables():\n print('Scenario 1: create and list tables in ledger')\n print('-----------')\n ledger_name = create_ledger()\n print('Creating new test ledger in QLDB API: %s' % ledger_name)\n driver = get_driver(ledger_name)\n session = driver.get_session()\n\n print('Creating two test tables in ledger')\n tables = list(session.list_tables())\n assert tables == []\n session.execute_statement('CREATE TABLE foobar1')\n session.execute_statement('CREATE TABLE foobar2')\n tables = list(session.list_tables())\n tables = [t.text for t in tables]\n print('Retrieves list of tables in ledger %s: %s' % (ledger_name, tables))\n assert tables == ['foobar1', 'foobar2']\n print('-----------')\n\n\ndef query_join_tables():\n print('Scenario 2: create ledger tables and run join query')\n print('-----------')\n ledger_name = create_ledger()\n driver = get_driver(ledger_name)\n session = driver.get_session()\n\n print('Creating two test tables in ledger - \"Vehicle\" and \"VehicleRegistration\"')\n\n # create tables\n session.execute_statement('CREATE TABLE Vehicle')\n session.execute_statement('CREATE TABLE VehicleRegistration')\n\n # insert data\n persons_to_vehicles = {'p1': ['v1'], 'p2': ['v2', 'v3']}\n for person, vehicles in persons_to_vehicles.items():\n for vehicle in vehicles:\n session.execute_statement('INSERT INTO Vehicle ?', {'id': vehicle})\n session.execute_statement('INSERT INTO VehicleRegistration ?',\n {'id': vehicle, 'Owner': {'PersonId': person}})\n\n # run queries\n print('Running a query that joins data from the two tables')\n query = ('SELECT Vehicle FROM Vehicle INNER JOIN VehicleRegistration AS r '\n 'ON Vehicle.id = r.id WHERE r.Owner.PersonId = ?')\n\n result = []\n for pid in persons_to_vehicles.keys():\n cursor = session.execute_statement(query, pid)\n for entry in cursor:\n result.append(convert_to_dict(entry))\n print('Query result: %s' % result)\n assert result == [{'Vehicle': {'id': id}} for id in ['v1', 'v2', 'v3']]\n\n\ndef convert_to_dict(entry):\n entry = dict(entry)\n for k, v in entry.items():\n entry[k] = dict(v)\n return entry\n\n\ndef create_ledger():\n client = connect_qldb()\n ledger_name = 'ledger-test-1'\n client.create_ledger(Name=ledger_name, PermissionsMode='ALLOW_ALL')\n return ledger_name\n\n\ndef get_driver(ledger_name):\n return PooledQldbDriver(ledger_name=ledger_name, endpoint_url=QLDB_ENDPOINT)\n\n\ndef connect_qldb():\n return boto3.client('qldb', endpoint_url=QLDB_ENDPOINT)\n\n\ndef main():\n create_list_tables()\n query_join_tables()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"qldb-ledger-queries/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"414773382","text":"import re\n\nfrom core.lib.ip_utils import IpAddrUtils\nfrom core.lib.mac_utils import MacAddressUtils\nfrom core.static.patterns import EMAIL_REGEX\n\n\nclass StrictNonEmptyStr(str):\n \"\"\"Custom validator to ensure that the string value is not empty. for example, ''\"\"\"\n @classmethod\n def __get_validators__(cls):\n yield cls.validate\n\n @classmethod\n def validate(cls, value):\n if not isinstance(value, str):\n raise ValueError('Strict string: str expected, {} provided'.format(type(value)))\n\n if not value.strip():\n raise ValueError('Strict string: empty string provided')\n\n return value\n\n\nclass StrictMacAddressStr(str):\n @classmethod\n def __get_validators__(cls):\n yield cls.validate\n\n @classmethod\n def validate(cls, value):\n mac_utils = MacAddressUtils()\n if mac_utils.is_valid_mac(value) is False:\n raise ValueError('Invalid mac address format: expected format : or - separated, provided: {}'.format(value))\n\n return value\n\n\nclass StrictIPAddressStr(str):\n @classmethod\n def __get_validators__(cls):\n yield cls.validate\n\n @classmethod\n def validate(cls, value):\n ip_utils = IpAddrUtils()\n if ip_utils.is_valid_ip(value) is False:\n raise ValueError('Invalid IP address format: expected IPv4 or IPv6 address. provided: {}'.format(value))\n\n return value\n\n\ndef is_valid_email(email_address: str) -> bool:\n \"\"\"\n Checks if give string is a valid email address or not.\n :param email_address: String\n :return: True if valid otherwise false\n \"\"\"\n if not email_address:\n return False\n\n if re.compile(EMAIL_REGEX).match(email_address):\n return True\n\n return False\n","sub_path":"core/models/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"643265126","text":"from django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom .models import Gmina, Obwód\n\n\ndef index(request):\n gminy = Gmina.objects.order_by('name')\n context = {'gminy': gminy}\n return render(request, 'obwody/index.html', context)\n\n\ndef gmina(request, gmina_id):\n gmina = get_object_or_404(Gmina, pk=gmina_id)\n obwody = Obwód.objects.filter(gmina=gmina)\n context = {'gmina': gmina, 'obwody': obwody}\n return render(request, 'obwody/gmina.html', context)\n\n@transaction.atomic\ndef obwód(request, obwód_id):\n obwód = get_object_or_404(Obwód, pk=obwód_id)\n\n try:\n cards_old = int(request.POST['cards_old'])\n cards = int(request.POST['cards'])\n voters_old = int(request.POST['voters_old'])\n voters = int(request.POST['voters'])\n\n if cards < 0 or voters < 0:\n messages.error(request, \"Liczby muszą być nieujemne.\")\n elif cards_old != obwód.cards:\n messages.error(request, \"Wystąpił konflikt zapisu dla ilości kart do głosowania: \"\n \"zapisujesz %d a ktoś inny zapisał %d.\" % cards % obwód.cards)\n elif voters_old != obwód.voters:\n messages.error(request, \"Wystąpił konflikt zapisu dla ilości uprawnionych do głosowania: \"\n \"zapisujesz %d a ktoś inny zapisał %d.\" % voters % obwód.voters)\n else:\n obwód.cards = cards\n obwód.voters = voters\n obwód.save()\n messages.success(request, \"Zapisano pomyślnie!\")\n\n except KeyError:\n messages.error(request, \"Proszę wypełnić wszystkie pola.\")\n except ValueError:\n messages.error(request, \"Niepoprawne dane.\")\n\n return HttpResponseRedirect(reverse('gmina', args=(obwód.gmina_id,)))","sub_path":"obwody/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"248509816","text":"import cv2\nimport numpy as np\nimport math\n\ndef preprocess(input_image):\n grayscale_image = extractValue(input_image)\n grayscale_image_with_maximum_contrast = maximizeContrast(grayscale_image)\n height, width = grayscale_image.shape\n \n blurred_image = np.zeros((height, width, 1), np.uint8)\n GAUSSIAN_SMOOTH_FILTER_SIZE = (5, 5)\n blurred_image = cv2.GaussianBlur(grayscale_image_with_maximum_contrast, GAUSSIAN_SMOOTH_FILTER_SIZE, 0)\n\n ADAPTIVE_THRESH_BLOCK_SIZE = 19\n ADAPTIVE_THRESH_WEIGHT = 9\n threshold_image = cv2.adaptiveThreshold(blurred_image, 255.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, ADAPTIVE_THRESH_BLOCK_SIZE, ADAPTIVE_THRESH_WEIGHT)\n return grayscale_image, threshold_image\n\ndef extractValue(input_image):\n height, width, Channel = input_image.shape\n HSV_image = np.zeros((height, width, 3), np.uint8)\n HSV_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2HSV)\n Hue, Saturation, Value = cv2.split(HSV_image)\n return Value\n\ndef maximizeContrast(grayscale_image):\n height, width = grayscale_image.shape\n\n Top_hat_transform = np.zeros((height, width, 1), np.uint8) #enhance bright objects in dark background\n Black_hat_transform = np.zeros((height, width, 1), np.uint8) #enhance dark objects in bright background\n\n structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n\n Top_hat_transform = cv2.morphologyEx(grayscale_image, cv2.MORPH_TOPHAT, structuringElement)\n Black_hat_transform = cv2.morphologyEx(grayscale_image, cv2.MORPH_BLACKHAT, structuringElement)\n\n grayscale_image_Plus_TopHat = cv2.add(grayscale_image, Top_hat_transform)\n grayscale_image_Plus_TopHat_Minus_BlackHat = cv2.subtract(grayscale_image_Plus_TopHat, Black_hat_transform)\n\n return grayscale_image_Plus_TopHat_Minus_BlackHat","sub_path":"Preprocess.py","file_name":"Preprocess.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377526909","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.3 (3230)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: ./src/Attributes.py\n# Compiled at: 2014-08-01 13:34:49\n# Size of source mod 2**32: 2756 bytes\nfrom binding import *\nfrom .namespace import llvm\nfrom .LLVMContext import LLVMContext\nif LLVM_VERSION >= (3, 3):\n llvm.includes.add('llvm/IR/Attributes.h')\nelse:\n llvm.includes.add('llvm/Attributes.h')\nAttrBuilder = llvm.Class()\nif LLVM_VERSION >= (3, 3):\n Attribute = llvm.Class()\n AttributeSet = llvm.Class()\nelse:\n Attributes = llvm.Class()\nif LLVM_VERSION >= (3, 3):\n\n @Attribute\n class Attribute:\n AttrKind = Enum('None, Alignment, AlwaysInline,\\n ByVal, InlineHint, InReg,\\n MinSize, Naked, Nest, NoAlias,\\n NoBuiltin, NoCapture, NoDuplicate, NoImplicitFloat,\\n NoInline, NonLazyBind, NoRedZone, NoReturn,\\n NoUnwind, OptimizeForSize, ReadNone, ReadOnly,\\n Returned, ReturnsTwice, SExt, StackAlignment,\\n StackProtect, StackProtectReq, StackProtectStrong, StructRet,\\n SanitizeAddress, SanitizeThread, SanitizeMemory, UWTable,\\n ZExt, EndAttrKinds')\n delete = Destructor()\n get = StaticMethod(Attribute, ref(LLVMContext), AttrKind, cast(int, Uint64)).require_only(2)\n\n\n @AttrBuilder\n class AttrBuilder:\n new = Constructor()\n delete = Destructor()\n clear = Method()\n addAttribute = Method(ref(AttrBuilder), Attribute.AttrKind)\n removeAttribute = Method(ref(AttrBuilder), Attribute.AttrKind)\n addAlignmentAttr = Method(ref(AttrBuilder), cast(int, Unsigned))\n\n\n @AttributeSet\n class AttributeSet:\n delete = Destructor()\n get = StaticMethod(AttributeSet, ref(LLVMContext), cast(int, Unsigned), ref(AttrBuilder))\n\n\nelse:\n\n @Attributes\n class Attributes:\n AttrVal = Enum('None, AddressSafety, Alignment, AlwaysInline,\\n ByVal, InlineHint, InReg, MinSize,\\n Naked, Nest, NoAlias, NoCapture,\\n NoImplicitFloat, NoInline, NonLazyBind, NoRedZone,\\n NoReturn, NoUnwind, OptimizeForSize, ReadNone,\\n ReadOnly, ReturnsTwice, SExt, StackAlignment,\\n StackProtect, StackProtectReq, StructRet, UWTable, ZExt')\n delete = Destructor()\n get = StaticMethod(Attributes, ref(LLVMContext), ref(AttrBuilder))\n\n\n @AttrBuilder\n class AttrBuilder:\n new = Constructor()\n delete = Destructor()\n clear = Method()\n addAttribute = Method(ref(AttrBuilder), Attributes.AttrVal)\n removeAttribute = Method(ref(AttrBuilder), Attributes.AttrVal)\n addAlignmentAttr = Method(ref(AttrBuilder), cast(int, Unsigned))","sub_path":"pycfiles/llvmpy-0.12.7.tar/Attributes.cpython-33.py","file_name":"Attributes.cpython-33.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"297729674","text":"import discord\r\nimport asyncio\r\n\r\nclient=discord.Client()\r\n\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n print('I have come!')\r\n \r\n@client.event\r\nasync def on_message(message):\r\n if message.author.name+'#'+message.author.discriminator!='BuffDJ#9856':\r\n await client.add_reaction(message, \"U+1F923\")\r\n print(message.author.name+'@'+message.channel.name+': '+message.content)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclient.run('Token_Placeholder')\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"640544501","text":"from rest_framework import permissions\n\n\nclass RecordPermission(permissions.BasePermission):\n \"\"\"\n Restricts Charts APIs depending on the UserAccess\n \"\"\"\n message = 'You don\\'t have permission to perform this operation on ' + \\\n 'this Chart.'\n\n def has_permission(self, request, view):\n\n print(request.user)\n return True\n","sub_path":"records_app/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"400105387","text":"#! /usr/bin/env python\n\nimport argparse\nimport os\nimport sys\n\n\nif __name__ == '__main__':\n # parse command-line\n parser = argparse.ArgumentParser()\n parser.add_argument(\"inputs\", nargs='+', type=str, help=\"Path to input files\")\n parser.add_argument(\"-o\", type=str, help=\"Path to aggregate output file\")\n args = parser.parse_args()\n\n output = open(args.o, 'w')\n\n ones = 0\n for infile in infile:\n num = int(line)\n if num == 1:\n ones += 1\n output.write(\"%s\\n\" % num)\n\n output.close()\n print(\"Number of ones seen: %d\" % ones)\n","sub_path":"d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"489982125","text":"#!/usr/bin/env python3\n\nfrom itertools import combinations\nfrom itertools import permutations\n\nif __name__==\"__main__\":\n\tN=5\n\tall_possibilities = []\n\t\n\tcombinations_iter = combinations(map(lambda x: x+1, range(2*N)),N)\n\tcombinations_set = map(lambda x:set(x),combinations_iter)\n\tfor int_values in combinations_set:\n\t\text_values = int_values ^ set(map(lambda x: x+1, range(2*N)))\n\t\tint_values_permut = list(permutations(int_values))\n\t\text_values_permut = list(permutations(ext_values))\n\t\t\n\t\tfor int_value in int_values_permut:\n\t\t\tfor ext_value in ext_values_permut:\n\t\t\t\tif min(ext_value)!=ext_value[0]:\n\t\t\t\t\tcontinue\n\t\t\t\tthe_sum = None\n\t\t\t\tfor index in range(N):\n\t\t\t\t\tthe_sum_tmp = int_value[index] + \\\n\t\t\t\t\tint_value[(index+1)%N] + \\\n\t\t\t\t\text_value[index]\n\t\t\t\t\tif the_sum == None:\n\t\t\t\t\t\tthe_sum = the_sum_tmp\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telif the_sum != the_sum_tmp:\n\t\t\t\t\t\tthe_sum = None\n\t\t\t\t\t\tbreak\n\t\t\t\tif the_sum != None:\n\t\t\t\t\tpossibility = []\n\t\t\t\t\tfor index in range(N):\n\t\t\t\t\t\tpossibility.append(\\\n\t\t\t\t\t\t\tstr(ext_value[index]) + \\\n\t\t\t\t\t\t\tstr(int_value[index]) + \\\n\t\t\t\t\t\t\tstr(int_value[(index+1)%N]))\n\t\t\t\t\tpossibility = \"\".join(possibility)\n\t\t\t\t\tall_possibilities.append(possibility)\n\t\n\tprint(max(all_possibilities))\t\t\t\t","sub_path":"unsorted/euler68.py","file_name":"euler68.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"193753695","text":"# Definition for singly-linked list.\r\nclass ListNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.next = None\r\n\r\nclass Solution(object):\r\n def reverse(self, item, tail=None):\r\n nextNode = item.next\r\n item.next = tail\r\n if nextNode is None:\r\n return item\r\n else:\r\n return self.reverse(nextNode, item)\r\n \r\n def reverseBetween(self, head, m, n):\r\n \"\"\"\r\n :type head: ListNode\r\n :type m: int\r\n :type n: int\r\n :rtype: ListNode\r\n \"\"\"\r\n if m == n:\r\n return head \r\n p1, p2 = head, head\r\n while m > 1:\r\n p1 = p1.next\r\n m -= 1\r\n while n > 1:\r\n p2 = p2.next\r\n n -= 1\r\n r2 = p2.next\r\n p2.next = None\r\n \r\n L = head\r\n if L != p1:\r\n while L.next != p1:\r\n L = L.next\r\n \r\n L.next = None\r\n newL = self.reverse(p1)\r\n p1.next = r2\r\n L.next = newL\r\n return head\r\n else:\r\n \r\n newL = self.reverse(p1)\r\n p1.next = r2\r\n return newL\r\n\r\nn1 = ListNode(1)\r\nn2 = ListNode(2)\r\nn3 = ListNode(3)\r\nn4 = ListNode(4)\r\nn5 = ListNode(5)\r\nn6 = ListNode(6)\r\nn1.next = n2\r\nn2.next = n3\r\nn3.next = n4\r\nn4.next = n5\r\nn5.next = n6\r\nMy = Solution()\r\nm = 1\r\nn = 6\r\n\r\nH = My.reverseBetween(n1, m, n)\r\nwhile H:\r\n print(H.val)\r\n H = H.next\r\n","sub_path":"src/ReverseLinkedListII/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"67015753","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\n\nimport logging\nfrom datetime import datetime\n_logger = logging.getLogger(__name__)\n\n\nclass ProjectForecast(models.Model):\n _inherit = 'project.forecast'\n\n department_id = fields.Many2one(\n 'hr.department',\n related='employee_id.department_id',\n string='Department',\n store=True,\n readonly=True\n )\n\n hourly_rate = fields.Float(\n readonly=True,\n default=False,\n )\n\n task_id = fields.Many2one('project.task', string=\"Task\", group_expand='_read_forecast_tasks_vcls')\n start_date = fields.Date(compute='_get_start_end_date', store=True)\n end_date = fields.Date(compute='_get_start_end_date', store=True)\n deliverable_id = fields.Many2one(\n 'product.deliverable',\n readonly=True, store=True,\n related='task_id.sale_line_id.product_id.deliverable_id'\n )\n\n comment = fields.Html()\n\n rate_id = fields.Many2one(\n comodel_name='product.template',\n default = False,\n readonly = True,\n )\n\n @api.multi\n def get_rate(self,project,employee):\n self.ensure_one()\n map_line = project.sale_line_employee_ids.filtered(lambda l: l.employee_id == employee)\n if map_line:\n return map_line[0].sale_line_id.product_id.product_tmpl_id\n else:\n return False\n\n @api.onchange('employee_id')\n def _onchange_employee_id(self):\n self.ensure_one()\n self.rate_id = self.get_rate(self.project_id,self.employee_id)\n \n @api.model\n def update_rate_id(self):\n to_update = self.search([('rate_id','=',False)])\n for forecast in to_update:\n forecast._onchange_employee_id()\n _logger.info(\"Forecast update Rate_id {} for employee {}\".format(forecast.rate_id.name,forecast.employee_id.name))\n\n @api.depends('task_id.date_start', 'task_id.date_end')\n def _get_start_end_date(self):\n for forecast in self:\n task_date_start = forecast.task_id.date_start\n task_date_end = forecast.task_id.date_end\n if task_date_start and task_date_end:\n forecast.start_date = task_date_start.date()\n forecast.end_date = task_date_end.date()\n else:\n forecast.start_date = self._default_start_date()\n forecast.end_date = self._default_end_date()\n\n # planned_hours on a task must be equal to the sum of forecast hours related to this task\n # only if this sum it is superior to zero.\n @api.multi\n def _force_forecast_hours(self):\n self = self.with_context(tracking_disable=True)\n for forecast in self:\n if not forecast.task_id:\n continue\n total_resource_hours = sum(self.search([('task_id', '=', forecast.task_id.id)]).mapped('resource_hours'))\n if total_resource_hours > 0:\n forecast.task_id.planned_hours = total_resource_hours\n \n @api.multi\n def _project_forecasted_amount(self):\n self.mapped('order_line_id')._compute_forecasted_amount()\n\n @api.multi\n def write(self, values):\n result = super(ProjectForecast, self).write(values)\n for forecast in self:\n employee_id = forecast.employee_id.id\n project_id = forecast.project_id.id\n hourly_rate = forecast._get_hourly_rate(employee_id, project_id)\n super(ProjectForecast, forecast).write({\n 'hourly_rate': hourly_rate,\n })\n self.sudo()._force_forecast_hours()\n self.sudo()._project_forecasted_amount()\n return result\n\n @api.model\n def create(self, vals):\n \n if vals.get('project_id',False) and vals.get('employee_id',False):\n #if we create a forecast, we update the project mapping accordingly\n self.env['account.analytic.line']._update_project_soline_mapping({\n 'employee_id':vals['employee_id'],\n 'project_id':vals['project_id'],\n })\n \n if not vals.get('rate_id',False):\n #if the rate_id is not provided we look for the related employee in the mapping table\n project = self.env['project.project'].browse(vals['project_id'])\n employee = self.env['rh.employee'].browse(vals['employee_id'])\n rate = self.get_rate(project,employee)\n if rate:\n vals['rate_id']=rate.id\n \n forecast = super(ProjectForecast, self).create(vals)\n \n forecast.sudo()._force_forecast_hours()\n forecast.sudo()._project_forecasted_amount()\n\n if forecast.task_id.date_start and forecast.task_id.date_end:\n forecast.start_date = forecast.task_id.date_start.date()\n forecast.end_date = forecast.task_id.date_end.date()\n\n return forecast\n\n @api.model\n def _read_forecast_tasks_vcls(self, tasks, domain, order):\n search_domain = [('id', 'in', tasks.ids)]\n if 'default_project_id' in self.env.context:\n search_domain = ['|', ('project_id', 'child_of', [self.env.context['default_project_id']])] + search_domain\n return tasks.sudo().search(search_domain, order=order)\n \n @api.model\n def _get_hourly_rate(self, employee_id, project_id):\n if project_id and employee_id:\n rate_map = self.env['project.sale.line.employee.map'].search([\n ('employee_id', '=', employee_id),\n ('project_id', '=', project_id)],\n limit=1\n )\n if rate_map:\n return rate_map.price_unit\n return 0.0\n\n # Tis server action is meant to return a window action with proper model and active id\n # This is a solution to allow getting the right computed domain when page is being refreshed,\n @api.model\n def _action_server_forecast(self, server_action_id, active_model=False):\n active_id = self._context.get('active_id') or self._context.get('params', {}).get('active_id')\n if active_id and active_model:\n action = self.env[active_model].browse(active_id).action_view_forecast()\n # fake id to force coming back to the server action that triggers this method,\n # when user refreshes the page\n action['id'] = server_action_id\n return action\n return self.env.ref('vcls-project.project_forecast_action').read()[0]\n\n @api.model\n def _action_server_forecast_from_order(self):\n server_action_id = self.env.ref('vcls-project.action_server_project_forecast_from_order').id\n return self._action_server_forecast(server_action_id, 'sale.order')\n\n @api.multi\n def button_form_from_list(self):\n self.ensure_one()\n view = {\n 'name': _('Details'),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'project.forecast',\n 'view_id': self.env.ref('vcls-project.project_forecast_view_form').id,\n 'type': 'ir.actions.act_window',\n 'target': 'new',\n 'res_id': self.id,\n }\n return view\n","sub_path":"vcls-project/models/project_forecast.py","file_name":"project_forecast.py","file_ext":"py","file_size_in_byte":7211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"127204954","text":"PATH = '~/.pui/'\n\nDEFAULT_PRIORITY = 1\nDEFAULT_TASK_DURATION = 60\nDEFAULT_DEADLINE_DELTA = 24*60\n\n# RESOLVE PATH\nimport os\nPATH = os.path.expanduser(PATH)\nPATH = os.path.normpath(PATH)\ndel os\n\n# Terminal formatation constants\nBOLD = 1\nDIM = 2\nITALIC = 3\nUNDERLINE= 4\nBLINK = 5\nREVERSE = 6\t\nHIDDEN = 7\nCROSSEDOUT = 9\n\nRESET = 0\nNOT_BOLD = 21\nNOT_DIM = 22\nNOT_ITALIC = 23\nNOT_UNDERLINE = 24\nNOT_BLINK = STEADY = 25\nNOT_REVERSE = POSITIVE = 26\nNOT_HIDDEN = VISIBLE = 27\nNOT_CROSSEDOUT = 29\n\nF_DEFAULT = 39\nF_BLACK = 30\nF_RED = 31\nF_GREEN = 32\nF_YELLOW = 33\nF_BLUE = 34\nF_MAGENTA = 35\nF_CYAN = 36\nF_LIGHTGRAY = 37\nF_DARKGRAY = 90\nF_LIGHTRED = 91\nF_LIGHTGREEN = 92\nF_LIGHTYELLOW = 93\nF_LIGHTBLUE = 94\nF_LIGHTMAGENTA = 95\nF_LIGHTCYAN = 96\nF_WHITE = 97\n\nB_DEFAULT = 49\nB_BLACK = 40\nB_RED = 41\nB_GREEN = 42\nB_YELLOW = 43\nB_BLUE = 44\nB_MAGENTA = 45\nB_CYAN = 46\nB_LIGHTGRAY = 47\nB_DARKGRAY = 100\nB_LIGHTRED = 101\nB_LIGHTGREEN = 102\nB_LIGHTYELLOW = 103\nB_LIGHTBLUE = 104\nB_LIGHTMAGENTA = 105\nB_LIGHTCYAN = 106\nB_WHITE = 107\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n CROSS = '\\033[9m'\n","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"445151986","text":"\"\"\"Collection of utility methods used by the modules.\"\"\"\r\n\r\nimport os\r\nimport re\r\nimport urllib2\r\n\r\nimport values as values_module\r\n\r\n\r\nclass ContentType:\r\n JPG = 'image/jpeg'\r\n PNG = 'image/png'\r\n\r\n EXTENSIONS = {\r\n JPG: '.jpg',\r\n PNG: '.png',\r\n }\r\n\r\n\r\ndef create_images_dir(epub_dir):\r\n \"\"\"Creates an images directory for an epub.\r\n \r\n Args:\r\n epub_dir (str): Directory of the unzipped epub.\r\n \"\"\"\r\n images_dir = os.path.join(epub_dir, values_module.IMAGES_DIR)\r\n if not os.path.isdir(images_dir):\r\n os.mkdir(images_dir)\r\n return images_dir\r\n\r\n\r\ndef http_get_request(url):\r\n \"\"\"Makes a GET request to the url.\r\n \r\n Args:\r\n url (str): URL to send GET request to.\r\n \r\n Returns:\r\n Response from the server.\r\n \"\"\"\r\n request = urllib2.Request(url, headers={'User-Agent':'Mozilla'})\r\n return urllib2.urlopen(request)\r\n\r\n\r\ndef download_image(image_url, image_dir, image_filename=None):\r\n \"\"\"Downloads an image to the specified URL.\r\n \r\n Args:\r\n image_url (str): URL of the image to download.\r\n image_dir (str): Directory to save the image to.\r\n image_filename (str): Filename of the image to save as.\r\n \r\n Returns:\r\n A dictionary containing the content/media type and the filename.\r\n \"\"\"\r\n if not image_filename:\r\n image_filename = image_url.rsplit('/', 1)[1]\r\n \r\n response = http_get_request(image_url)\r\n \r\n content_type = response.headers.get('content-type')\r\n extension = ContentType.EXTENSIONS[content_type]\r\n \r\n # If the filename doesn't have an extension, add one.\r\n if not re.search('\\.\\w{3}$', image_filename):\r\n image_filename += extension\r\n \r\n with open(os.path.join(image_dir, image_filename), 'wb') as image_file:\r\n image_file.write(response.read())\r\n \r\n return {'content_type': content_type, 'filename': image_filename}\r\n\r\ndef encode(xml):\r\n return xml.encode('utf-8').strip()\r\n\r\ndef encode_xml(doc):\r\n return encode(doc.toxml())\r\n\r\ndef correct_meta(epub_dir):\r\n \"\"\"Corrects common issues with epub meta files.\r\n \r\n Args:\r\n epub_dir (str): Directory of the unzipped epub.\r\n \"\"\" \r\n def correct_common(filename):\r\n with open(filename, 'r+') as f:\r\n data = f.read()\r\n data = re.sub(r'(>[^\\<]*?)&([^>]*?<)', r'\\1&\\2', data)\r\n\r\n f.seek(0)\r\n f.write(data)\r\n f.truncate()\r\n \r\n for filename in ['book.ncx', 'book.opf']:\r\n correct_common(os.path.join(epub_dir, filename))\r\n","sub_path":"lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"412954714","text":"import tensorflow as tf\n\nwith tf.gfile.FastGFile(\"./save_models_frozen/frozen_model.pb\", 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n xinput, xout = tf.import_graph_def(graph_def, return_elements=[\"in:0\", \"out:0\"])\n\nwith tf.Session() as sess:\n print(sess.run(xout, feed_dict={xinput: 10}))\n print(tf.get_default_graph().collections)\n # print(tf.get_collection('trainable_variables'))\n\n# writer = tf.summary.FileWriter(\"./graphy/saved_model_restore\", tf.get_default_graph())\n","sub_path":"test/save_restore/saved_model_restore.py","file_name":"saved_model_restore.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"315248474","text":"# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the datalad package for the\n# copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Tests for cmdline.helpers\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nfrom io import StringIO\nfrom os import mkdir\nfrom os.path import (\n join as opj,\n)\n\nfrom nose.tools import assert_raises, assert_equal\n\nfrom ..helpers import get_repo_instance, fail_with_short_help, _fix_datalad_ri\nfrom ..helpers import strip_arg_from_argv\n\nfrom datalad.tests.utils import (\n assert_is_instance,\n eq_,\n assert_cwd_unchanged,\n with_testrepos,\n)\nfrom ...support.annexrepo import AnnexRepo\nfrom ...support.gitrepo import GitRepo\nfrom ...utils import chpwd, getpwd\nfrom ...utils import Path\n\n\n@assert_cwd_unchanged\n@with_testrepos('^basic_git$', flavors=['clone'])\ndef test_get_repo_instance_git(path):\n real_path = Path(path).resolve()\n\n # get instance from path\n repo = get_repo_instance(path, GitRepo)\n assert_is_instance(repo, GitRepo)\n eq_(repo.pathobj, real_path)\n\n old_pwd = getpwd()\n\n # get instance from current dir\n chpwd(path)\n repo = get_repo_instance()\n assert_is_instance(repo, GitRepo)\n eq_(repo.pathobj, real_path)\n\n # get instance from current subdir\n new_subdir = opj(path, \"subdir\")\n mkdir(new_subdir)\n chpwd(new_subdir)\n eq_(new_subdir, getpwd())\n repo = get_repo_instance()\n assert_is_instance(repo, GitRepo)\n eq_(repo.pathobj, real_path)\n\n chpwd(old_pwd)\n\n\n@assert_cwd_unchanged\n@with_testrepos('.*annex.*', flavors=['clone'])\ndef test_get_repo_instance_annex(path):\n real_path = Path(path).resolve()\n\n # get instance from path\n repo = get_repo_instance(path, AnnexRepo)\n assert_is_instance(repo, AnnexRepo)\n eq_(repo.pathobj, real_path)\n\n old_pwd = getpwd()\n\n # get instance from current dir\n chpwd(path)\n repo = get_repo_instance()\n assert_is_instance(repo, AnnexRepo)\n eq_(repo.pathobj, real_path)\n\n # get instance from current subdir\n new_subdir = opj(path, \"subdir\")\n mkdir(new_subdir)\n chpwd(new_subdir)\n eq_(new_subdir, getpwd())\n repo = get_repo_instance()\n assert_is_instance(repo, AnnexRepo)\n eq_(repo.pathobj, real_path)\n\n chpwd(old_pwd)\n\n\ndef test_strip_arg_from_argv():\n eq_(strip_arg_from_argv(['-s', 'value'], 'value', ('-s',)), [])\n eq_(strip_arg_from_argv(['-s', 'value'], 'value', ('-s', '--long-s')), [])\n eq_(strip_arg_from_argv(\n ['cmd', '-s', 'value', '--more'], 'value', ('-s', '--long-s')),\n ['cmd', '--more'])\n\n\ndef test_fail_with_short_help():\n out = StringIO()\n with assert_raises(SystemExit) as cme:\n fail_with_short_help(exit_code=3, out=out)\n assert_equal(cme.exception.code, 3)\n assert_equal(out.getvalue(), \"\")\n\n out = StringIO()\n with assert_raises(SystemExit) as cme:\n fail_with_short_help(msg=\"Failed badly\", out=out)\n assert_equal(cme.exception.code, 1)\n assert_equal(out.getvalue(), \"error: Failed badly\\n\")\n\n # Suggestions, hint, etc\n out = StringIO()\n with assert_raises(SystemExit) as cme:\n fail_with_short_help(\n msg=\"Failed badly\",\n known=[\"mother\", \"mutter\", \"father\", \"son\"],\n provided=\"muther\",\n hint=\"You can become one\",\n exit_code=0, # no one forbids\n what=\"parent\",\n out=out)\n assert_equal(cme.exception.code, 0)\n assert_equal(out.getvalue(),\n \"error: Failed badly\\n\"\n \"datalad: Unknown parent 'muther'. See 'datalad --help'.\\n\\n\"\n \"Did you mean any of these?\\n\"\n \" mutter\\n\"\n \" mother\\n\"\n \" father\\n\"\n \"Hint: You can become one\\n\")\n\n\ndef test_fix_datalad_ri():\n assert_equal(_fix_datalad_ri('/'), '/')\n assert_equal(_fix_datalad_ri('/a/b'), '/a/b')\n assert_equal(_fix_datalad_ri('//'), '///')\n assert_equal(_fix_datalad_ri('///'), '///')\n assert_equal(_fix_datalad_ri('//a'), '///a')\n assert_equal(_fix_datalad_ri('///a'), '///a')\n assert_equal(_fix_datalad_ri('//a/b'), '///a/b')\n assert_equal(_fix_datalad_ri('///a/b'), '///a/b')","sub_path":"datalad/cmdline/tests/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"45274648","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views import View\n\nfrom .forms import *\nfrom policy.models import *\nfrom mkform.models import aForm\n\nclass FilterPolicy(View):\n template_name = \"viewpolicy.html\"\n def get(self,req,*args,**kwargs):\n form = FilterPolicyForm()\n context = {\n \"form\":form,\n }\n return render(req,self.template_name,context)\n\n\nclass ViewPolicy(View):\n template_name = \"viewpolicy_all.html\"\n\n def get(self,req,*args,**kwargs):\n policy_name = req.GET.get('policy_name',\"\")\n search_substring = req.GET.get('search_substring',\"\")\n af = None\n try:\n af = aForm.objects.get(form_name=policy_name)\n except:\n return HttpResponse(\"

Bad URL!

\")\n\n allids = aPolicy.objects.values_list('id',flat = True)\n\n allres = []\n for id in allids:\n if id.find(search_substring)<0: continue\n obj = aPolicy.objects.get(id=id)\n if (obj.policy_name!=policy_name): continue\n res = { 'id':id }\n res['data'] =[]\n for i in range(aForm.num_fields):\n value = getattr(obj,\"key%d\"%i)\n if len(value)<=0: continue\n ftype = getattr(af,\"field_type%d\" % i)\n fname = getattr(af, \"field_name%d\" % i)\n r = {}\n r['name'] = fname\n r['type'] = ftype\n r['value'] =value\n res['data'].append(r)\n\n allres.append(res)\n\n return render(req, self.template_name, {'data':allres, 'policy_name':policy_name, 'search_substring':search_substring })\n\n","sub_path":"brite/viewpol/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"409042413","text":"from selenium import webdriver\nimport time\n\n# Not displaying the browser\noption = webdriver.ChromeOptions()\noption.add_argument(\"headless\")\n\n# Specifying the path of my Chrome driver\nbrowser = webdriver.Chrome(\"C:\\Program Files\\chromedriver\\chromedriver.exe\")\n\n# Getting to Free Chegg.com Website\nurl = \"https://techlacarte.com/how-to-get-chegg-answers-for-free/\"\nbrowser.get(url)\ntime.sleep(8)\n\n# Declaring the path of the needed elements\nuserNamePath = browser.find_element_by_xpath('//*[@id=\"wpforms-13116-field_1\"]')\nquestionLinkPath = browser.find_element_by_xpath('//*[@id=\"wpforms-13116-field_4\"]')\nemailAddressPath = browser.find_element_by_xpath('//*[@id=\"wpforms-13116-field_2\"]')\nsendButtonPath = browser.find_element_by_xpath('//*[@id=\"wpforms-submit-13116\"]')\n\nuserName = input(\"What is your name? \")\nemailAddress = input(f\"Dear, {userName} please write your email address where the answer will be sent: \")\n\nwhile True:\n # Asking for the question link from the user\n questionLink = input(f\"Dear, {userName} Please paste your Chegg question link and click enter: \")\n\n # Sending the input one-by-one\n time.sleep(1)\n userNamePath.send_keys(userName)\n time.sleep(0.25)\n questionLinkPath.send_keys(questionLink)\n time.sleep(0.25)\n emailAddressPath.send_keys(emailAddress)\n time.sleep(0.25)\n\n # Finally sending all the result, and waiting for the answer\n sendButtonPath.click()\n\n for i in range(6):\n print(\"Working on it\" + i*\".\")\n time.sleep(1)\n\n print(\"Please check your main within 15-45 minutes to get your answer!\")\n print(\"Made by Vusal with the help of TchLaCarte <3\")\n browser.refresh()\n","sub_path":"Public Account/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"247957891","text":"#func for finding min no\n\ndef min_no (numlist):\n min = numlist[0]\n for val in numlist :\n if val < min :\n min = val\n return min\n \n#func for finding max no\n\ndef max_no (numlist):\n max = numlist[0]\n for val in numlist :\n if val > max :\n max = val\n return max\n\nlist1 = [4,5,7,-1,18,9]\nprint (\"List = \", list1)\nprint (\"Min = \", min_no(list1))\nprint (\"Max = \", max_no(list1))\n","sub_path":"min_max.py","file_name":"min_max.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372038997","text":"# !/usr/bin/env python\n# coding:utf-8\nfrom collections import Counter\n\n\ndef letter_frequency(sentence):\n s_list = sentence.split()\n freq = {}\n for letter in s_list:\n frequency = freq.setdefault(letter, 0)\n freq[letter] = frequency + 1\n return freq\n\n\nwith open('0004.txt') as f:\n lines = f.readlines()\n dic = {}\n for line in lines:\n X, Y = Counter(dic), Counter(letter_frequency(line))\n dic = dict(X+Y)\n print(dic)\n","sub_path":"code/0004.py","file_name":"0004.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377358194","text":"# This file is part of Indico.\n# Copyright (C) 2002 - 2019 CERN\n#\n# Indico is free software; you can redistribute it and/or\n# modify it under the terms of the MIT License; see the\n# LICENSE file for more details.\n\nfrom __future__ import print_function, unicode_literals\n\nimport os\nimport re\nimport subprocess\nimport sys\nfrom datetime import date\n\nfrom indico.util.console import cformat\n\n\nHEADERS = {\n 'indico': \"\"\"\n {comment_start} This file is part of Indico.\n{comment_middle} Copyright (C) 2002 - {end_year} CERN\n{comment_middle}\n{comment_middle} Indico is free software; you can redistribute it and/or\n{comment_middle} modify it under the terms of the MIT License; see the\n{comment_middle} LICENSE file for more details.\n{comment_end}\n\"\"\",\n 'plugins': \"\"\"\n {comment_start} This file is part of the Indico plugins.\n{comment_middle} Copyright (C) 2002 - {end_year} CERN\n{comment_middle}\n{comment_middle} The Indico plugins are free software; you can redistribute\n{comment_middle} them and/or modify them under the terms of the MIT License;\n{comment_middle} see the LICENSE file for more details.\n{comment_end}\n\"\"\",\n 'plugins-cern': \"\"\"\n {comment_start} This file is part of the CERN Indico plugins.\n{comment_middle} Copyright (C) 2014 - {end_year} CERN\n{comment_middle}\n{comment_middle} The CERN Indico plugins are free software; you can redistribute\n{comment_middle} them and/or modify them under the terms of the MIT License; see\n{comment_middle} the LICENSE file for more details.\n{comment_end}\n\"\"\",\n}\n\n\n# Dictionary listing the files for which to change the header.\n# The key is the extension of the file (without the dot) and the value is another\n# dictionary containing two keys:\n# - 'regex' : A regular expression matching comments in the given file type\n# - 'format': A dictionary with the comment characters to add to the header.\n# There must be a `comment_start` inserted before the header,\n# `comment_middle` inserted at the beginning of each line except the\n# first and last one, and `comment_end` inserted at the end of the\n# header. (See the `HEADER` above)\nSUPPORTED_FILES = {\n 'py': {\n 'regex': re.compile(br'((^#|[\\r\\n]#).*)*'),\n 'format': {'comment_start': b'#', 'comment_middle': b'#', 'comment_end': b''}},\n 'wsgi': {\n 'regex': re.compile(br'((^#|[\\r\\n]#).*)*'),\n 'format': {'comment_start': b'#', 'comment_middle': b'#', 'comment_end': b''}},\n 'js': {\n 'regex': re.compile(br'/\\*(.|[\\r\\n])*?\\*/|((^//|[\\r\\n]//).*)*'),\n 'format': {'comment_start': b'//', 'comment_middle': b'//', 'comment_end': b''}},\n 'jsx': {\n 'regex': re.compile(br'/\\*(.|[\\r\\n])*?\\*/|((^//|[\\r\\n]//).*)*'),\n 'format': {'comment_start': b'//', 'comment_middle': b'//', 'comment_end': b''}},\n 'css': {\n 'regex': re.compile(br'/\\*(.|[\\r\\n])*?\\*/'),\n 'format': {'comment_start': b'/*', 'comment_middle': b' *', 'comment_end': b' */'}},\n 'scss': {\n 'regex': re.compile(br'/\\*(.|[\\r\\n])*?\\*/|((^//|[\\r\\n]//).*)*'),\n 'format': {'comment_start': b'//', 'comment_middle': b'//', 'comment_end': b''}},\n}\n\n\n# The substring which must be part of a comment block in order for the comment to be updated by the header.\nSUBSTRING = b'This file is part of'\n\n\nUSAGE = \"\"\"\npython bin/maintenance/update_header.py [YEAR] [PATH]\n\nUpdates all the headers in the supported files ({supported_files}).\nBy default, all the files tracked by git in the current repository are updated\nto the current year.\n\nYou need to specify which project it is (one of {projects}) to the correct\nheaders are used.\n\nYou can specify a year (1000-2999) to update to as well as a file or directory.\nThis will update all the supported files in the scope including those not tracked\nby git. If the directory does not contain any supported files (or if the file\nspecified is not supported) nothing will be updated.\n\"\"\".format(supported_files=', '.join(SUPPORTED_FILES), projects=', '.join(HEADERS)).strip()\n\n\ndef gen_header(project, data, end_year):\n data['end_year'] = end_year\n return '\\n'.join(line.rstrip() for line in HEADERS[project].format(**data).strip().splitlines()).encode('ascii')\n\n\ndef _update_header(project, file_path, year, substring, regex, data):\n found = False\n with open(file_path, 'rb') as file_read:\n content = orig_content = file_read.read()\n if not content.strip():\n return\n shebang_line = None\n if content.startswith(b'#!/'):\n shebang_line, content = content.split('\\n', 1)\n for match in regex.finditer(content):\n if substring in match.group():\n found = True\n content = content[:match.start()] + gen_header(project, data, year) + content[match.end():]\n if shebang_line:\n content = shebang_line + '\\n' + content\n if content != orig_content:\n print(cformat('%{green!}Updating header of %{blue!}{}').format(os.path.relpath(file_path)))\n with open(file_path, 'wb') as file_write:\n file_write.write(content)\n elif not found:\n print(cformat('%{yellow}Missing header in %{yellow!}{}').format(os.path.relpath(file_path)))\n\n\ndef update_header(project, file_path, year):\n ext = file_path.rsplit('.', 1)[-1]\n if ext not in SUPPORTED_FILES or not os.path.isfile(file_path):\n return\n if os.path.basename(file_path)[0] == '.':\n return\n _update_header(project, file_path, year, SUBSTRING, SUPPORTED_FILES[ext]['regex'], SUPPORTED_FILES[ext]['format'])\n\n\ndef _process_args(args):\n year_regex = re.compile('^[12][0-9]{3}$') # Year range 1000 - 2999\n year = date.today().year\n\n project = args[0]\n args = args[1:]\n if project not in HEADERS:\n print(USAGE)\n sys.exit(1)\n\n # Take year argument if we have one\n if args and year_regex.match(args[0]):\n year = int(args[0])\n args = args[1:]\n if not args:\n return project, year, None, None\n elif os.path.isdir(args[0]):\n return project, year, args[0], None\n elif os.path.isfile(args[0]):\n return project, year, None, args[0]\n else:\n print(USAGE)\n sys.exit(1)\n\n\ndef blacklisted(root, path, _cache={}):\n orig_path = path\n if path not in _cache:\n _cache[orig_path] = False\n while (path + os.path.sep).startswith(root):\n if os.path.exists(os.path.join(path, '.no-headers')):\n _cache[orig_path] = True\n break\n path = os.path.normpath(os.path.join(path, '..'))\n return _cache[orig_path]\n\n\ndef main():\n if '-h' in sys.argv[1:] or '--help' in sys.argv[1:] or not sys.argv[1:]:\n print(USAGE)\n sys.exit(1)\n\n project, year, path, file_ = _process_args(sys.argv[1:])\n\n if path is not None:\n print(cformat(\"Updating headers to the year %{yellow!}{year}%{reset} for all the files in \"\n \"%{yellow!}{path}%{reset}...\").format(year=year, path=path))\n for root, _, filenames in os.walk(path):\n for filename in filenames:\n if not blacklisted(path, root):\n update_header(project, os.path.join(root, filename), year)\n elif file_ is not None:\n print(cformat(\"Updating headers to the year %{yellow!}{year}%{reset} for the file \"\n \"%{yellow!}{file}%{reset}...\").format(year=year, file=file_))\n update_header(project, file_, year)\n else:\n print(cformat(\"Updating headers to the year %{yellow!}{year}%{reset} for all \"\n \"git-tracked files...\").format(year=year))\n try:\n for path in subprocess.check_output(['git', 'ls-files']).splitlines():\n path = os.path.abspath(path)\n if not blacklisted(os.getcwd(), os.path.dirname(path)):\n update_header(project, path, year)\n except subprocess.CalledProcessError:\n print(cformat('%{red!}[ERROR] you must be within a git repository to run this script.'), file=sys.stderr)\n print(USAGE)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/maintenance/update_header.py","file_name":"update_header.py","file_ext":"py","file_size_in_byte":8167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"138961553","text":"import math\n\ndef num_ways_fib(n):\n fib_list = [None]*(n+2)\n fib_list[0] = 0\n fib_list[1] = 1\n for i in range(n):\n if i == n:\n break\n fib_list[i+2] = fib_list[i]+fib_list[i+1]\n\n print(fib_list)\n\n return(fib_list[n+1])\n\ndef num_ways(n):\n new_n = n + 1\n res = 0\n for i in range(int((new_n/2).__floordiv__(1)+1)):\n seq_length = new_n - i\n twos = i\n ones = seq_length - i\n res += dimension_triangle(ones, twos-1)\n\n return(res)\n\ndef new_num_ways(n):\n res = 0\n for i in range(int(((n)/2).__floordiv__(1)+1)):\n res += dimension_triangle(n-2*i,i-1)\n return res\n\n\ndef dimension_triangle(x, d):\n resss = 0\n if d == -1:\n return 1\n if d == 0:\n return x\n for i in range(x+1):\n resss += dimension_triangle(i, d-1)\n return resss\n\nnum_ways_fib(50)\nfor i in range(1,50):\n print(new_num_ways(i))\n\n# F_n = \\sum_{i=0}^{\\lfloor n/2\\rfloor}f(n-2i,i-1)\n# f(x,y) = \\begin{cases}1 & if\\space y = -1\\\\x & if\\space y = 0\\\\\\sum_{k=0}^x f(k,y-1) & if\\space y>1\\space and\\space y\\in N \\end{cases}\n","sub_path":"Python/small_projects/Fib_algorithm/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"638589601","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 27 22:55:21 2015\n\n@author: Allan\n\"\"\"\n\nimport numpy as np\n\nclass SimpleDecoder(object):\n \n def __init__(self, **_KwargsVariableDict):\n \n #parameters\n self.__dict__.update(_KwargsVariableDict)\n \n \n #Build connectivity\n self.lamda = 1/float(self.tc)\n self.D = np.random.normal(10, self.sigma/float(self.N), (self.M, \n self.N))\n self.W = np.dot(self.D.T,self.D)\n \n #Dynamics of the membrane potential\n def dv(self, v, O, c): \n return (-self.lamda*v*self.dt - np.dot(\n self.W,\n O\n ) + self.dt*np.dot(\n self.D.T, \n c)\n )\n \n #Dynamics of the decoder\n def dG(self, G, O):\n return (-self.lamda*G*self.dt + np.dot(\n self.D, O)\n )\n \n \n def run(self):\n \n #variables\n self.t1 = self.t_final/4\n self.t2 = 3*self.t_final/4\n self.bins_int = self.t_final/self.dt\n self.t_span = np.linspace(0, self.t_final, self.bins_int)\n \n #Input command c\n self.c = self.c0a*np.ones([self.M, self.bins_int])\n IndexIntList = range(int(self.t1/self.dt), int(self.t2/self.dt))\n self.c[:, IndexIntList]= self.c0b\n if self.c1a>0.:\n self.c[:,IndexIntList] += self.c1a*self.amp*np.sin(2.*np.pi*self.f1a*0.001*\n self.t_span[IndexIntList])\n \n #Initialising the system\n self.O = np.zeros((self.N, self.bins_int))\n self.v = np.zeros((self.N, self.bins_int))\n self.G = np.zeros((self.M, self.bins_int))\n \n #Threshold for each neuron\n self.Theta = (np.sum(self.D*self.D/2, axis=0))\n \n #Implementing Euler menthod\n for i in xrange(int(self.bins_int)-1):\n spiking_neuron = np.greater_equal(self.v[:,i],self.Theta.T)\n self.O[spiking_neuron, i] = 1\n \n #decoder\n self.G[:,i+1] = self.G[:,i] + self.dG(self.G[:,i], self.O[:, i])\n \n #membrane potential\n self.v[:, i+1] = self.v[:, i]+ self.dv(self.v[:, i], self.O[:,i],\n self.c[:, i])\n \n self.v[spiking_neuron, i+1] = -self.Theta[spiking_neuron]\n \n \n ","sub_path":"DecoderSimple.py","file_name":"DecoderSimple.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"119738379","text":"# *-* coding utf-8 *-*\nfrom __future__ import unicode_literals\nfrom collections import defaultdict\n\nfrom lingpy import *\n\n\nclass Tests(object):\n # get all segments\n models = ['sca', 'dolgo', 'art', 'color', 'asjp', 'cv']\n _model = dict([(model, Model(model)) for model in models])\n segments = set()\n for model in models:\n for segment in _model[model].converter:\n segments.add(segment)\n failures = defaultdict(list)\n for model in models:\n values = list(_model[model].converter.keys())\n for segment in segments:\n if segment not in values and segment != '-':\n failures[model] += [segment]\n if failures:\n error_message = '\\n'\n for model in failures:\n error_message += model+'\\n'\n error_message += ' // '.join(['\"'+x+'\"' for x in failures[model]])+'\\n\\n'\n print(error_message)\n raise ValueError(error_message)\n","sub_path":"MA-Code/venv/lib/python3.5/site-packages/lingpy/tests/data/test_sound_class_models.py","file_name":"test_sound_class_models.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"443640222","text":"import csv\n\ndef save_to_file(jobs):\n file =open(\"jobs.csv\", mode=\"w\", encoding=\"utf8\") #파일열어 변수에 저장했고\n writer = csv.writer(file) #writer를 만들어줌\n writer.writerow([\"title\",\"company\",\"location\",\"link\"])\n #리스트로 안넣으면 한글자씩 인식함 \n for job in jobs: #밸류가 필요함\n writer.writerow(list(job.values()))\n return","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72784855","text":"\"\"\"\r\nHelper functions and data types.\r\n\"\"\"\r\n\r\nfrom collections import namedtuple\r\nfrom itertools import tee, izip\r\nimport math\r\nimport pandas as pd\r\nfrom operator import eq\r\nimport numpy as np\r\n\r\n# mean earth radius in kilometers\r\n# https://en.wikipedia.org/wiki/Earth_radius\r\nearth_radius = 6371.0\r\n\r\ndef great_circle_dist(a, b, unit=\"kilometers\"):\r\n \"\"\"\r\n compute great circle distance between two latitude/longitude coordinate pairs.\r\n Returns great cirlce distance in kilometers (default) or meters.\r\n https://en.wikipedia.org/wiki/Great-circle_distance\r\n \"\"\"\r\n lat1, lon1 = a\r\n lat2, lon2 = b\r\n if (lat1==92) or (lat2==92):\r\n return -1 # invalid location gives invalid distance\r\n dlat = math.radians(lat2 - lat1)\r\n dlon = math.radians(lon2 - lon1)\r\n a = (math.sin(dlat / 2.0) * math.sin(dlat / 2.0) +\r\n math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * \r\n math.sin(dlon / 2.0) * math.sin(dlon / 2.0))\r\n c = 2.0 * math.asin(math.sqrt(a))\r\n dist_km = earth_radius * c\r\n if unit == \"kilometers\":\r\n return dist_km\r\n elif unit == \"meters\":\r\n return dist_km * 1000\r\n else:\r\n raise ValueError(\"Unknown unit: %s\" % unit)\r\n\r\n \r\ndef dist_to_radians(x):\r\n return (x / earth_radius) * (180.0 / math.pi)\r\n\r\n\r\ndef sliding_window(iterable, size):\r\n \"\"\" Yield moving windows of size 'size' over the iterable object.\r\n \r\n Example:\r\n >>> for each in window(xrange(6), 3):\r\n >>> print list(each)\r\n [0, 1, 1]\r\n [1, 2, 2]\r\n [2, 3, 3]\r\n [3, 4, 4]\r\n\r\n \"\"\"\r\n iters = tee(iterable, size)\r\n for i in xrange(1, size):\r\n for each in iters[i:]:\r\n next(each, None)\r\n return izip(*iters)\r\n \r\n \r\ndef print_full_dataframe(df):\r\n pd.set_option('display.max_rows', len(df))\r\n print(df)\r\n pd.reset_option('display.max_rows')\r\n\r\n\r\ndef chunks(iterable, include_values=False, equal=eq):\r\n \"\"\"Given an iterable, yield tuples of (start, end) indices for chunks\r\n with equal items. If inlcude_values is True, each tuple will have\r\n the value of that chunk as a third element.\r\n\r\n Example:\r\n >>> list(chunks([1, 1, 1, 2, 2, 1]))\r\n [(0, 3), (3, 5), (5, 6)]\r\n\r\n \"\"\"\r\n idx = None\r\n start_idx = 0\r\n for idx, item in enumerate(iterable):\r\n if idx == 0:\r\n previous = item\r\n continue\r\n if not equal(item, previous):\r\n if include_values:\r\n yield (start_idx, idx, previous)\r\n else:\r\n yield (start_idx, idx)\r\n start_idx = idx\r\n previous = item\r\n if idx is not None:\r\n if include_values:\r\n yield (start_idx, idx+1, previous)\r\n else:\r\n yield (start_idx, idx+1)\r\n\r\ndef moving_ave ( data_vec, window_size ):\r\n \"\"\" calculates moving average of a given vecter with given window_size\r\n \"\"\"\r\n if type(data_vec) is not np.ndarray:\r\n data_vec = np.array(data_vec)\r\n ave_data_vec = []\r\n for idx in xrange(0,len(data_vec)):\r\n if idx 0) and (count > 0):\n end_state = round(sum/count*25)\n\n context = {\n 'survey' : survey,\n 'capability_list' : results,\n 'end_state' : end_state\n }\n return render(request, self.template_name, context)\n","sub_path":"django/site/socat/views/assessment.py","file_name":"assessment.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"508858770","text":"#!/usr/bin/python\r\n# -*- coding: iso-8859-15 -*-\r\n#\r\n# 2012-10-10 - Aggiunto TIMEOUT parameter\r\n\r\nimport sys, os\r\nimport http.client\r\nimport urllib.request, urllib.parse, urllib.error\r\nimport urllib.request, urllib.error, urllib.parse\r\n\r\n###########################################################################\r\n# - get(url, logger=None, type=None)\r\n# - params:\r\n# - url: URL ( \"http://esil610.ac.bankit.it:8080/json-console/JsonResponder\")\r\n# - logger: loggerPointer\r\n# - type: 'JSON' per avere la conversione della pagina JSON in un DICT\r\n###########################################################################\r\ndef httpGet(gv, url, timeOUT=5.0, logger=None, type=None):\r\n LN = gv.LN\r\n logger = LN.LnLogger\r\n calledBy = gv.LN.sys.calledBy\r\n logger.debug('entered - [called by:%s]' % (calledBy(1)))\r\n\r\n bRetVal = False\r\n sStatus = False\r\n htmlPage = None\r\n\r\n logger.info('url %s - HCJ' % (url))\r\n\r\n try:\r\n urllib2.socket.setdefaulttimeout(timeOUT) #Bad page, timeout in 1s.\r\n usock = urllib.request.urlopen(url)\r\n\r\n except urllib.error.URLError as e:\r\n\r\n if hasattr(e, 'reason'):\r\n logger.info('We failed to reach a server: <%s>. Reason: %s' % (url, e.reason))\r\n bRetVal = False\r\n\r\n elif hasattr(e, 'code'):\r\n logger.info('The server <%s> couldn\\'t fulfill the request. Error code: %s' % (url, e.code))\r\n bRetVal = False\r\n\r\n else: # everything is fine\r\n sStatus = 'RUNNING'\r\n htmlPage = usock.read() # contiene la pagina HTML\r\n usock.close()\r\n bRetVal = True\r\n\r\n logger.info('%s' % (sStatus))\r\n\r\n # ---------------------------------------------------------------------\r\n # Python can parse json into a dict/array using the eval\r\n # statement as long as you set true/false/null to the right values.\r\n # convert to a native python object\r\n # ---------------------------------------------------------------------\r\n if bRetVal:\r\n if type == 'JSON':\r\n (true,false,null) = (True,False,None)\r\n htmlPage = eval(htmlPage)\r\n # print types(htmlPage)\r\n\r\n logger.debug('exiting - [called by:%s]' % (calledBy(1)))\r\n return bRetVal, htmlPage\r\n\r\ndef main():\r\n sys.exit()\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"LnNet/Samples/LnHttp_Prev.py","file_name":"LnHttp_Prev.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"385662747","text":"import sys, math\nimport numpy as np\n\nf = open(sys.argv[1],'r')\nd = np.array(f.read().strip().split(),np.float)\nf.close()\n# with open() as f: d = np.array(f.read().strip().split(),np.float)\n\ndim = int(math.sqrt(len(d)))\nassert dim**2 == len(d)\nd -= d.mean()\nd /= d.std()\nd = d.reshape((dim,dim))\n\nf = open(sys.argv[2],'w')\nf.write('\\n'.join(['\\t'.join([str(d[i,j]) for j in range(dim)]) for i in range(dim)]) + '\\n')\nf.close()\n# with open(sys.argv[2],'w') as f: f.write('\\n'.join(['\\t'.join([str(d[i,j]) for j in range(dim)]) for i in range(dim)]) + '\\n')","sub_path":"a3m_generation/AlignZTM/normalize_ccmpred.py","file_name":"normalize_ccmpred.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"186408248","text":"import json, re, os\n\n# For each file in the current directory, open only page* files.\npage_files = [x for x in os.listdir('.') if re.fullmatch('page[0-9]+', x)]\n\n# Merge all page files together.\nforks = []\nfor filename in page_files:\n\twith open(filename) as file:\n\t\tdata = json.load(file)\n\t\tforks = forks + data\n\n\n# All of these can be derived automatically from \"full_name\", let's keep this list clean.\nfor fork in forks:\n\tfor uninteresting_stuff in [\"git_url\", \"ssh_url\", \"clone_url\", \"svn_url\", \"homepage\", \"html_url\", \"url\", \"forks_url\", \"keys_url\", \"collaborators_url\", \"teams_url\", \"hooks_url\", \"issue_events_url\", \"events_url\", \"assignees_url\", \"branches_url\", \"tags_url\", \"blobs_url\", \"git_tags_url\", \"git_refs_url\", \"trees_url\", \"statuses_url\", \"languages_url\", \"stargazers_url\", \"contributors_url\", \"subscribers_url\", \"subscription_url\", \"commits_url\", \"git_commits_url\", \"comments_url\", \"issue_comment_url\", \"contents_url\", \"compare_url\", \"merges_url\", \"archive_url\", \"downloads_url\", \"issues_url\", \"pulls_url\", \"milestones_url\", \"notifications_url\", \"labels_url\", \"releases_url\", \"deployments_url\"]:\n\t\t\tdel fork[uninteresting_stuff]\n\n\tfor uninteresting_owner_stuff in [\"url\", \"html_url\", \"followers_url\", \"following_url\", \"gists_url\", \"starred_url\", \"subscriptions_url\", \"organizations_url\", \"repos_url\", \"events_url\", \"received_events_url\"]:\n\t\t\tdel fork['owner'][uninteresting_owner_stuff]\n\n\t# These can't be derived, but are still useless for extracting interesting forks...\n\tfor useless_owner_stuff in [\"avatar_url\", \"gravatar_id\", \"site_admin\"]:\n\t\tdel fork['owner'][useless_owner_stuff]\n\nwith open(\"forks.json\", 'w') as file:\n\tjson.dump(forks, file)\n","sub_path":"merge_pages.py","file_name":"merge_pages.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"280386136","text":"\"\"\"\nZAG Spider created on the top of ATSSpider\n\nscrapy crawl zag -a mining_job_id=9999 -a iteration=1 -a extract=1\\\n-a url=\"http://www.zag.de/fuer-bewerber/stellenmarkt.html?tx_vczagstellenmarkt_pi1%5Bsearch_data%5D%5Btext%5D=+&tx_vczagstellenmarkt_pi1%5Bsearch_data%5D%5Boccupational_group%5D=0&tx_vczagstellenmarkt_pi1%5Bsearch_data%5D%5Baddress%5D=\"\n\nSeed URL:\n http://www.zag.de/fuer-bewerber/stellenmarkt.html?tx_vczagstellenmarkt_pi1[search_data][text]=+&tx_vczagstellenmarkt_pi1[search_data][occupational_group]=0&tx_vczagstellenmarkt_pi1[search_data][address]=\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import ConvertDateString, Prefix\nfrom brightcorp.lib.utils import extract_first\n\npattern = {\n 'location': compile(r'^(\\d+)\\s*([^$]*)'),\n 'ref_number': compile(r'-(\\d+)\\.html'),\n}\n\n\nclass ZAG(ATSSpider):\n\n name = 'zag'\n\n def parse(self, response):\n \"\"\"\n Parse search jobs list.\n Call GET method to each job urls.\n \"\"\"\n sel = Selector(response)\n # set expected job count\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n '//form[@id=\"sort-jobs\"]/fieldset/label[1]/text()'\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count[0]\n\n for li in sel.xpath('//div/ul[@class=\"job-list\"]/li'):\n job_url = li.xpath('./a/@href').extract()\n\n if job_url:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'posted_date': extract_first(li.xpath(\n './a/span/text()'\n )),\n 'location': extract_first(li.xpath(\n './a/em/text()'\n )),\n },\n url=urljoin(response.url, '/%s' % job_url[0])\n )\n # pagination\n next_page = sel.xpath(\n '//ul[@class=\"job-list\"]/following-sibling::div[1]//a[contains(text(), \">>\")]/@href'\n ).extract()\n if next_page:\n yield Request(\n callback=self.parse,\n url=urljoin(response.url, '/%s' % next_page[0])\n )\n\n def parse_job(self, response):\n \"\"\"\n Extract all required information.\n \"\"\"\n sel = Selector(response)\n raw_location = response.meta.get('location')\n location = ''\n zip_code = ''\n # match the location with defined pattern\n # if found, seperate zip_code and location\n # ex: 30159 Hannover\n if raw_location:\n match = pattern['location'].search(raw_location)\n if match:\n location = match.group(2)\n zip_code = match.group(1)\n\n loader = BrightcorpItemLoader(selector=sel)\n\n loader.add_xpath(\n 'title', '//div[@id=\"content\"]/div/h1/text()'\n )\n loader.add_value(\n 'date',\n response.meta.get('posted_date'),\n ConvertDateString('%d.%m.%Y')\n )\n loader.add_value(\n 'url', response.url\n )\n loader.add_xpath(\n 'company',\n '//div[@class=\"button-wrapper\"]/ancestor::div[1]//table/tr/td[1]/text()[1]'\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n Prefix('%s-' % self.name),\n re=pattern['ref_number']\n )\n loader.add_value('location', location)\n loader.add_value('zip_code', zip_code)\n loader.add_xpath(\n 'description',\n '//div[@id=\"content\"]/div/h1/following-sibling::*[following-sibling::h2[contains(text(), \"So bewerben Sie sich\")]]'\n )\n loader.add_value(\n 'apply_url', response.url\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/zag.py","file_name":"zag.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"89790276","text":"n, lst = input(), list(map(int, input().split())) # n = 리스트 항목의 수, lst = 주어진 리스트 \ncnt = 0 # 소수의 개수\nfor ele in lst : # list의 element 꺼내오기\n sqrt = int(ele**(1/2)) # 소수 판별을 위해 제곱근 구하기\n # 2부터 시작해서 제곱근 까지 수 중에 나눠지는 수가 있는지 판별\n if ele >= 4 :\n for i in range(2, sqrt+1):\n if ele % i == 0:\n cnt -= 1\n break\n cnt += 1\n elif ele == 2 or ele == 3:\n cnt += 1\nprint(cnt)\n\n","sub_path":"Baekjoon/연습/Baekjoon-소수 찾기.py","file_name":"Baekjoon-소수 찾기.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"224882264","text":"import os\nfrom functools import partial\nfrom configparser import ConfigParser\nfrom clidemo.platform import Platform\n\nglobal_config = ConfigParser()\n\n\nclass Config:\n SECTION = None\n\n def __init__(self, path=None, section=None):\n if path:\n self.parser = ConfigParser()\n self.parser.read(path)\n else:\n self.parser = global_config\n self.section = section or self.SECTION\n\n def __getattribute__(self, name):\n if name in {\"get\", \"getboolean\", \"getfloat\", \"getint\"}:\n if name == \"getboolean\":\n fallback = False\n elif name in \"getfloat\":\n fallback = 0.0\n elif name == \"getint\":\n fallback = 0\n else:\n fallback = None\n return partial(\n getattr(self.parser, name), self.section, fallback=fallback)\n return super().__getattribute__(name)\n\n\nclass CliConfig(Config):\n SECTION = \"MAIN\"\n\n CONFIG_NAME = \".clidemo\"\n config_dir = os.path.join(Platform.home_directory, CONFIG_NAME)\n config_file = os.getenv(\n f\"CLI_{SECTION}__config_file\",\n default=os.path.join(config_dir, \"cli.conf\"))\n\n @property\n def log_directory(self):\n return self.get(\"log_directory\", fallback=os.path.join(\n self.config_dir, \"logs\"))\n\n\nglobal_config.read(CliConfig.config_file)\nos.makedirs(CliConfig.config_dir, exist_ok=True)\nos.makedirs(CliConfig().log_directory, exist_ok=True)\n","sub_path":"src/clidemo/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"188838985","text":"import matplotlib.pyplot as plt\n\nx = [1,2,3,4,5,6,7,8]\ny = [5,2,4,2,1,4,5,2]\n\n\nplt.scatter(x, y, label=\"skitscat\", color=\"k\", marker=\"*\", s=100)\n\n\nplt.xlabel(\"Plot Number\")\nplt.ylabel(\"Important var\")\nplt.title(\"Interesting Graph\\nCheck it out\")\nplt.legend()\n\nplt.show()\n","sub_path":"MatPlotLib/ScatterPlots.py","file_name":"ScatterPlots.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"327565658","text":"# Filename: UpdateParcelData.py\n# Purpose: Update LGIM parcel data from BS&A\n# Copyright (c) Scott Stopyak 2014\n# Distributed under the terms of the GNU GPL.\nimport os, arcpy\n\n\ndef UpdateParcelData():\n import csv, os, arcpy, pyodbc, shutil, datetime, time, sys\n\n # Create folders\n if os.path.exists(r'C:\\ParcelUpdates'):\n shutil.rmtree(r'C:\\ParcelUpdates')\n if not os.path.exists(r'C:\\ParcelUpdates'):\n os.mkdir(r'C:\\ParcelUpdates')\n ts = time.time()\n now = datetime.datetime.fromtimestamp(ts).strftime('%Y_%m_%d_%H_%M_%S')\n\n topfolder = r'C:\\ParcelUpdates'\n\n os.mkdir(os.path.join(topfolder, now))\n oldFiles=[]\n\n outfolder =os.path.join(topfolder, now)\n\n # Export MSSQL tables to csv\n print(\"Exporting tables to csv.\")\n connection = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'BSANET\\BSA', database = 'D004County-13')\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM dbo.Taxes')\n with open(os.path.join(outfolder,'Taxes.csv'), 'wb') as fout:\n writer = csv.writer(fout)\n writer.writerow([ i[0] for i in cursor.description ]) # heading row\n writer.writerows(cursor.fetchall())\n connection = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'BSANET\\BSA', database = 'D001Eaton County 2015 ')\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM dbo.LGIMTaxParcels')\n with open(os.path.join(outfolder,'ParcelData.csv'), 'wb') as fout:\n writer = csv.writer(fout)\n writer.writerow([ i[0] for i in cursor.description ]) # heading row\n writer.writerows(cursor.fetchall())\n connection = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'BSANET\\BSA', database = 'D020PRE2013')\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM dbo.pre')\n with open(os.path.join(outfolder,'PRE.csv'), 'wb') as fout:\n writer = csv.writer(fout)\n writer.writerow([ i[0] for i in cursor.description ]) # heading row\n writer.writerows(cursor.fetchall())\n # Environment settings and variables\n arcpy.env.overwriteOutput = True\n\n taxcsv = os.path.join(outfolder,'Taxes.csv')\n parcelcsv = os.path.join(outfolder,'ParcelData.csv')\n precsv = os.path.join(outfolder,'PRE.csv')\n\n # Create scratch workspace and import tables\n print(\"Creating scratch workspace and importing tables.\")\n if not os.path.exists(os.path.join(outfolder, 'ParcelUpdate.gdb')):\n arcpy.CreateFileGDB_management(outfolder, 'ParcelUpdate')\n gdb = os.path.join(outfolder, 'ParcelUpdate.gdb')\n arcpy.env.workspace = gdb\n arcpy.TableToGeodatabase_conversion(taxcsv, gdb)\n arcpy.TableToGeodatabase_conversion(parcelcsv, gdb)\n arcpy.TableToGeodatabase_conversion(precsv, gdb)\n # Join parcel data and tax tables on LPARCEL Field\n print(\"Joining table fields.\")\n arcpy.JoinField_management('ParcelData', 'LPARCEL', 'Taxes', 'LPARCEL')\n arcpy.JoinField_management('ParcelData', 'LPARCEL', 'PRE', 'LPARCEL')\n arcpy.DeleteField_management('ParcelData', ('LPARCEL_1','LPARCEL_2'))\n arcpy.Delete_management('Taxes')\n\n # Import current parcels to scratch geodatabase\n print(\"Importing parcel polys.\")\n\n currentParcels = r'E:\\Geo\\LGIMParcelUpdater\\YearlyParcels.gdb\\ParcelsApril2014'\n\n\n\n #######Field Mapping for current Parcel polygons.###################################################################\n fms = arcpy.FieldMappings()\n fm_SPARCEL = arcpy.FieldMap()\n fm_LPARCEL = arcpy.FieldMap()\n fm_PID = arcpy.FieldMap()\n fm_SUB = arcpy.FieldMap()\n\n\n fm_LPARCEL.addInputField(currentParcels,'LPARCEL')\n fm_PID.addInputField(currentParcels,'PID')\n fm_SPARCEL.addInputField(currentParcels,'SPARCEL')\n fm_SUB.addInputField(currentParcels,'SUB_NAME')\n\n PID_name = fm_PID.outputField\n PID_name.name = 'PARCELID'\n fm_PID.outputField = PID_name\n\n SUB_name = fm_SUB.outputField\n SUB_name.name = 'CNVYNAME'\n fm_SUB.outputField = SUB_name\n\n SPARCEL_name = fm_SPARCEL.outputField\n SPARCEL_name.name = 'LOWPARCELID'\n fm_SPARCEL.outputField = SPARCEL_name\n\n fms.addFieldMap(fm_PID)\n fms.addFieldMap(fm_SPARCEL)\n fms.addFieldMap(fm_LPARCEL)\n fms.addFieldMap(fm_SUB)\n ########################################################################################################################\n\n arcpy.FeatureClassToFeatureClass_conversion(currentParcels,gdb, 'Parcels','', fms)\n\n # Join parcel data to polygons\n print(\"Joining tables to polygons.\")\n arcpy.JoinField_management('Parcels', 'LPARCEL', 'ParcelData', 'LPARCEL')\n arcpy.DeleteField_management('Parcels', 'LPARCEL_1')\n arcpy.RefreshCatalog(gdb)\n\n # Calculate school description\n print(\"Calculating school descriptions.\")\n arcpy.AddField_management('Parcels', 'SCHLDSCRP', 'TEXT')\n try:\n arcpy.AddField_management('Parcels', 'SCHLTXCD', 'TEXT')\n except:\n pass\n exp_school_code = '''str(!SCHLTXCD_INT!)'''\n arcpy.CalculateField_management('Parcels', 'SCHLTXCD', exp_school_code, 'PYTHON')\n fields = ('SCHLTXCD', 'SCHLDSCRP')\n with arcpy.da.UpdateCursor('Parcels',fields) as cursor:\n for row in cursor:\n if (row[0] == '13120'):\n row[1] = 'Pennfield Schools'\n elif (row[0] == '23010'):\n row[1] = 'Bellevue Community Schools'\n elif (row[0] == '23030'):\n row[1] = 'Charlotte Public Schools'\n elif (row[0] == '23050'):\n row[1] = 'Eaton Rapids Public Schools'\n elif (row[0] == '23060'):\n row[1] ='Grand Ledge Public Schools'\n elif (row[0] == '23065'):\n row[1] = 'Maple Valley Schools'\n elif (row[0] == '23080'):\n row[1] = 'Olivet Community Schools'\n elif (row[0] == '23090'):\n row[1] = 'Potterville Public Schools'\n elif (row[0] == '23490'):\n row[1] = 'Oneida Township S/D #3'\n elif (row[0] == '33020'):\n row[1] = 'Lansing Public School District'\n elif (row[0] == '33070'):\n row[1] = 'Holt Public Schools'\n elif (row[0] == '33130'):\n row[1] = 'Mason Public Schools (Ingham)'\n elif (row[0] == '33215'):\n row[1] = 'Waverly Community Schools'\n elif (row[0] == '34090'):\n row[1] = 'Lakewood Public Schools'\n elif (row[0] == '38150'):\n row[1] = 'Springport Public Schools'\n\n cursor.updateRow(row)\n\n del cursor\n del fields\n\n # Update tax district codes\n print(\"Calculating tax district descriptions.\")\n arcpy.AddField_management('PARCELS', 'CVTTXCD', 'TEXT')\n exp_tax_code = '''str(!CVTTXCD_INT!)'''\n arcpy.CalculateField_management('Parcels', 'CVTTXCD', exp_tax_code, 'PYTHON')\n\n arcpy.AddField_management('PARCELS', 'CVTTXDSCRP', 'TEXT')\n fields = ('CVTTXCD', 'CVTTXDSCRP')\n with arcpy.da.UpdateCursor('Parcels',fields) as cursor:\n for row in cursor:\n if (row[0] == '10'):\n row[1] = 'Sunfield Township'\n elif (row[0] == '11'):\n row[1] = 'Village of Sunfield'\n elif (row[0] == '20'):\n row[1] = 'Roxand Township'\n elif (row[0] == '21'):\n row[1] = 'Village of Mulliken'\n elif (row[0] == '30'):\n row[1] = 'Oneida Charter Township'\n elif (row[0] == '40'):\n row[1] = 'Delta Charter Township'\n elif (row[0] == '50'):\n row[1] = 'Vermontville Township'\n elif (row[0] == '51'):\n row[1] = 'Village of Vermontville'\n elif (row[0] == '60'):\n row[1] = 'Chester Township'\n elif (row[0] == '70'):\n row[1] = 'Benton Township'\n elif (row[0] == '80'):\n row[1] = 'Windsor Charter Township'\n elif (row[0] == '81'):\n row[1] = 'Village of Dimondale'\n elif (row[0] == '90'):\n row[1] = 'Kalamo Township'\n elif (row[0] == '100'):\n row[1] = 'Carmel Township'\n elif (row[0] == '110'):\n row[1] = 'Eaton Township'\n elif (row[0] == '120'):\n row[1] = 'Eaton Rapids Township'\n elif (row[0] == '130'):\n row[1] = 'Bellevue Township'\n elif (row[0] == '131'):\n row[1] = 'Village of Bellevue'\n elif (row[0] == '140'):\n row[1] = 'Walton Township'\n elif (row[0] == '150'):\n row[1] = 'Brookfield Township'\n elif (row[0] == '160'):\n row[1] = 'Hamlin Township'\n elif (row[0] == '200'):\n row[1] = 'Charlotte'\n elif (row[0] == '300'):\n row[1] = 'Eaton Rapids'\n elif (row[0] == '400'):\n row[1] = 'Grand Ledge'\n elif (row[0] == '500'):\n row[1] = 'Lansing'\n elif (row[0] == '600'):\n row[1] = 'Olivet'\n elif (row[0] == '700'):\n row[1] = 'Potterville'\n\n cursor.updateRow(row)\n del cursor\n del fields\n\n # Calculating annual taxes\n print(\"Adding up the annual taxes.\")\n annualexp = '''!CNTWNTTXOD! + !CNTSMRTXOD! + !VillageTax!'''\n arcpy.AddField_management('Parcels', 'TOTCNTTXOD', 'DOUBLE')\n arcpy.CalculateField_management('Parcels', 'TOTCNTTXOD', annualexp, 'PYTHON')\n arcpy.RefreshCatalog(outfolder)\n\n # Pushing update to LGIM\n print(\"Pushing changes to LGIM.\")\n\n oldParcels = r'Database Connections\\ARCSDESQL10_LGIM@GisOwner.sde\\LGIM.GISOWNER.ParcelPublishing\\LGIM.GISOWNER.TaxParcel'\n oldPts = r'Database Connections\\ARCSDESQL10_LGIM@GisOwner.sde\\LGIM.GISOWNER.ParcelPublishing\\LGIM.GISOWNER.TaxParcelPoint'\n arcpy.DeleteFeatures_management(oldParcels)\n arcpy.Append_management('Parcels', oldParcels, 'NO_TEST')\n arcpy.RefreshCatalog(outfolder)\n\n # Updating points.\n print(\"Updating TaxParcelPoints.\")\n arcpy.FeatureToPoint_management(oldParcels, os.path.join(\"in_memory\", 'pts'), \"INSIDE\")\n arcpy.DeleteFeatures_management(oldPts)\n arcpy.Append_management(os.path.join(\"in_memory\", 'pts'), oldPts, 'NO_TEST')\n arcpy.RefreshCatalog(topfolder)\n shutil.rmtree(outfolder)\n print('Update is complete.')\n\nif __name__ == \"__main__\":\n UpdateParcelData()\n\n\n\n","sub_path":"UpdateParcelDataAndPoints.py","file_name":"UpdateParcelDataAndPoints.py","file_ext":"py","file_size_in_byte":10550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"371194574","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018-08-12 15:08:53.496487\n# @Author : CoderZ\n# @File : \n# @Software: PyCharm\n# @Description: paramiko模块学习(用于ssh连接)\n\nimport paramiko\n\nssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nssh.connect('10.132.226.100', 22, 'root', 'root123')\n\nstdin, stdout, stderr = ssh.exec_command('df -h')\na = stdout.read()\n\nprint(str(a, encoding='utf-8'))\nssh.close()\n","sub_path":"python学习笔记/21_4_paramiko模块(ssh连接).py","file_name":"21_4_paramiko模块(ssh连接).py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"436920190","text":"\"\"\"show_spanning_tree.py\n supported commands:\n * show lldp\n * show lldp entry [|*]\n * show lldp interface []\n * show lldp neighbors detail\n * show lldp traffic\n\"\"\"\nimport re\n\nfrom genie.metaparser import MetaParser\nfrom genie.metaparser.util.schemaengine import Schema, \\\n Any, \\\n Optional, \\\n Or, \\\n And, \\\n Default, \\\n Use\n\n# import parser utils\nfrom genie.libs.parser.utils.common import Common\n\n\nclass ShowLldpSchema(MetaParser):\n \"\"\"Schema for show lldp\"\"\"\n schema = {\n 'status': str,\n 'enabled': bool,\n 'hello_timer': int,\n 'hold_timer': int,\n 'reinit_timer': int\n }\n\n\nclass ShowLldp(ShowLldpSchema):\n \"\"\"Parser for show lldp\"\"\"\n\n cli_command = 'show lldp'\n\n def cli(self, output=None):\n if output is None:\n out = self.device.execute(self.cli_command)\n else:\n out = output\n # initial return dictionary\n ret_dict = {}\n\n # initial regexp pattern\n p1 = re.compile(r'^Status: +(?P\\w+)$')\n p2 = re.compile(r'^LLDP +(?P[\\w\\s]+) +(?P\\d+) +seconds$')\n\n for line in out.splitlines():\n line = line.strip()\n \n # Status: ACTIVE\n m = p1.match(line)\n if m:\n status = m.groupdict()['status'].lower()\n ret_dict['status'] = status\n ret_dict['enabled'] = True if 'active' in status else False\n continue\n\n # LLDP advertisements are sent every 30 seconds\n # LLDP hold time advertised is 120 seconds\n # LLDP interface reinitialisation delay is 2 seconds\n m = p2.match(line)\n if m:\n group = m.groupdict()\n if re.search('(advertisements +are +sent +every)', group['pattern']):\n key = 'hello_timer'\n elif re.search('(hold +time +advertised +is)', group['pattern']):\n key = 'hold_timer'\n elif re.search('(interface +reinitialisation +delay +is)', group['pattern']):\n key = 'reinit_timer'\n else:\n continue\n ret_dict[key] = int(group['value'])\n continue\n return ret_dict\n\n\nclass ShowLldpEntrySchema(MetaParser):\n \"\"\"Schema for show lldp entry [|*]\"\"\"\n schema = {\n 'total_entries': int,\n Optional('interfaces'): {\n Any(): {\n 'if_name': str,\n 'neighbors': {\n Any(): { \n 'chassis_id': str,\n 'port_id': str,\n 'neighbor_id': str,\n Optional('port_description'): str,\n Optional('system_description'): str,\n Optional('system_name'): str,\n 'time_remaining': int,\n Optional('capabilities'): {\n Any():{\n Optional('system'): bool,\n Optional('enabled'): bool,\n 'name': str,\n }\n },\n Optional('management_address'): str,\n Optional('auto_negotiation'): str,\n Optional('physical_media_capabilities'): list,\n Optional('unit_type'): int,\n Optional('vlan_id'): int\n }\n }\n }\n }\n }\n\n\nclass ShowLldpEntry(ShowLldpEntrySchema):\n \"\"\"Parser for show lldp entry [|*]\"\"\"\n\n CAPABILITY_CODES = {'R': 'router',\n 'B': 'mac_bridge',\n 'T': 'telephone',\n 'C': 'docsis_cable_device',\n 'W': 'wlan_access_point',\n 'P': 'repeater',\n 'S': 'station_only',\n 'O': 'other'}\n\n cli_command = 'show lldp entry {entry}'\n\n def cli(self, entry='*',output=None):\n if output is None:\n # get output from device\n if hasattr(self, 'CMD'):\n out = self.device.execute(self.CMD)\n else:\n out = self.device.execute(self.cli_command.format(entry=entry))\n else:\n out = output\n # initial return dictionary\n ret_dict = {}\n\n # initial regexp pattern\n p1 = re.compile(r'^Local +Intf: +(?P[\\w\\/\\.\\-]+)$')\n p1_1 = re.compile(r'^Port +id: +(?P[\\w\\/\\.\\-]+)$')\n\n p2 = re.compile(r'^Chassis +id: +(?P[\\w\\.]+)$')\n\n p3 = re.compile(r'^Port +Description: +(?P[\\w\\/\\.\\-]+)$')\n\n p4 = re.compile(r'^System +Name: +(?P\\w+)$')\n\n p5 = re.compile(r'^System +Description:$')\n p5_1 = re.compile(r'^(?PCisco +IOS +Software.*)$')\n p5_2 = re.compile(r'^(?PCopyright.*)$')\n p5_3 = re.compile(r'^(?PCompile.*)$')\n p5_4 = re.compile(r'^(?PTechnical Support.*)$')\n\n p6 = re.compile(r'^Time +remaining: +(?P\\w+) +seconds$')\n\n p7 = re.compile(r'^System +Capabilities: +(?P[\\w\\,\\s]+)$')\n\n p8 = re.compile(r'^Enabled +Capabilities: +(?P[\\w\\,\\s]+)$')\n\n p9 = re.compile(r'^IP: +(?P[\\w\\.]+)$')\n\n p10 = re.compile(r'^Auto +Negotiation +\\- +(?P[\\w\\s\\,]+)$')\n\n p11 = re.compile(r'^Physical +media +capabilities:$')\n p11_1 = re.compile(r'^(?P\\d+base[\\w\\-\\(\\)]+)$')\n\n p12 = re.compile(r'^Media +Attachment +Unit +type: +(?P\\d+)$')\n\n p13 = re.compile(r'^Vlan +ID: +(?P\\d+)$')\n\n p14 = re.compile(r'^Total +entries +displayed: +(?P\\d+)$')\n\n for line in out.splitlines():\n line = line.strip()\n \n # Local Intf: Gi2/0/15\n m = p1.match(line)\n if m:\n intf = Common.convert_intf_name(m.groupdict()['intf'])\n intf_dict = ret_dict.setdefault('interfaces', {}).setdefault(intf, {})\n intf_dict['if_name'] = intf\n sub_dict = {}\n continue\n\n # Chassis id: 843d.c638.b980\n m = p2.match(line)\n if m:\n sub_dict = {}\n chassis_id = m.groupdict()['chassis_id']\n sub_dict.setdefault('chassis_id', chassis_id)\n continue\n\n # Port id: Gi1/0/4\n m = p1_1.match(line)\n if m:\n sub_dict.setdefault('port_id',\n Common.convert_intf_name(m.groupdict()['port_id']))\n continue\n\n # Port Description: GigabitEthernet1/0/4\n m = p3.match(line)\n if m:\n sub_dict.setdefault('port_description', m.groupdict()['desc'])\n continue\n\n # System Name: R5\n m = p4.match(line)\n if m:\n name = m.groupdict()['name']\n sub_dict['system_name'] = name\n continue\n\n\n # System Description: \n m = p5.match(line)\n if m:\n sub_dict['system_description'] = ''\n continue\n\n # Cisco IOS Software, C3750E Software (C3750E-UNIVERSALK9-M), Version 12.2(58)SE2, RELEASE SOFTWARE (fc1)\n m = p5_1.match(line)\n if m:\n item = sub_dict.get('system_description', '') + m.groupdict()['msg'] + '\\n'\n sub_dict['system_description'] = item\n continue\n\n # Technical Support: http://www.cisco.com/techsupport \n m = p5_4.match(line)\n if m:\n item = sub_dict.get('system_description', '') + m.groupdict()['msg'] + '\\n'\n sub_dict['system_description'] = item\n continue\n\n # Copyright (c) 1986-2011 by Cisco Systems, Inc.\n m = p5_2.match(line)\n if m:\n item = sub_dict.get('system_description', '') + m.groupdict()['msg'] + '\\n'\n sub_dict['system_description'] = item\n continue\n\n # Compiled Thu 21-Jul-11 01:23 by prod_rel_team\n m = p5_3.match(line)\n if m:\n item = sub_dict.get('system_description', '') + m.groupdict()['msg']\n sub_dict['system_description'] = item\n continue\n\n # Time remaining: 112 seconds\n m = p6.match(line)\n if m:\n nei = sub_dict.get('system_name', '') if sub_dict.get('system_name', '') else \\\n sub_dict.get('chassis_id', '')\n nei_dict = intf_dict.setdefault('neighbors', {}).setdefault(nei, {})\n nei_dict.update(sub_dict)\n nei_dict['time_remaining'] = int(m.groupdict()['time_remaining'])\n nei_dict['neighbor_id'] = nei\n continue\n\n # System Capabilities: B,R\n m = p7.match(line)\n if m:\n cap = [self.CAPABILITY_CODES[n] for n in m.groupdict()['capab'].split(',')]\n for item in cap:\n cap_dict = nei_dict.setdefault('capabilities', {}).\\\n setdefault(item, {})\n cap_dict['name'] = item\n cap_dict['system'] = True\n continue\n\n # Enabled Capabilities: B,R\n m = p8.match(line)\n if m:\n cap = [self.CAPABILITY_CODES[n] for n in m.groupdict()['capab'].split(',')]\n for item in cap:\n cap_dict = nei_dict.setdefault('capabilities', {}).\\\n setdefault(item, {})\n cap_dict['name'] = item\n cap_dict['enabled'] = True\n continue\n\n # Management Addresses:\n # IP: 10.9.1.1\n m = p9.match(line)\n if m:\n nei_dict['management_address'] = m.groupdict()['ip']\n continue\n\n # Auto Negotiation - supported, enabled\n m = p10.match(line)\n if m:\n nei_dict['auto_negotiation'] = m.groupdict()['auto_negotiation']\n continue\n\n # Physical media capabilities:\n m = p11.match(line)\n if m:\n nei_dict['physical_media_capabilities'] = []\n continue\n\n # 1000baseT(FD)\n # 100base-TX(HD)\n m = p11_1.match(line)\n if m: \n item = nei_dict.get('physical_media_capabilities', [])\n item.append(m.groupdict()['physical_media_capabilities'])\n nei_dict['physical_media_capabilities'] = item\n continue\n\n # Media Attachment Unit type: 30\n m = p12.match(line)\n if m:\n nei_dict['unit_type'] = int(m.groupdict()['unit_type'])\n continue\n\n # Vlan ID: 1\n m = p13.match(line)\n if m:\n nei_dict['vlan_id'] = int(m.groupdict()['vlan_id'])\n continue\n\n # Total entries displayed: 4\n m = p14.match(line)\n if m:\n ret_dict['total_entries'] = int(m.groupdict()['entry'])\n continue\n\n return ret_dict\n\n\nclass ShowLldpNeighborsDetail(ShowLldpEntry):\n '''Parser for show lldp neighbors detail'''\n CMD = 'show lldp neighbors detail'\n\n\nclass ShowLldpTrafficSchema(MetaParser):\n \"\"\"Schema for show lldp traffic\"\"\"\n schema = {\n \"frame_in\": int,\n \"frame_out\": int,\n \"frame_error_in\": int,\n \"frame_discard\": int,\n \"tlv_discard\": int,\n 'tlv_unknown': int,\n 'entries_aged_out': int\n }\n\n\nclass ShowLldpTraffic(ShowLldpTrafficSchema):\n \"\"\"Parser for show lldp traffic\"\"\"\n\n cli_command = 'show lldp traffic'\n\n def cli(self,output=None):\n if output is None:\n out = self.device.execute(self.cli_command)\n else:\n out = output\n\n # initial return dictionary\n ret_dict = {}\n\n # initial regexp pattern\n p1 = re.compile(r'^(?P[\\w\\s]+): +(?P\\d+)$')\n\n for line in out.splitlines():\n line = line.strip()\n \n # Total frames out: 20372\n # Total entries aged: 34\n # Total frames in: 13315\n # Total frames received in error: 0\n # Total frames discarded: 14\n # Total TLVs discarded: 0\n # Total TLVs unrecognized: 0\n m = p1.match(line)\n if m:\n group = m.groupdict()\n if re.search('(Total +frames +out)', group['pattern']):\n key = 'frame_out'\n elif re.search('(Total +entries +aged)', group['pattern']):\n key = 'entries_aged_out'\n elif re.search('(Total +frames +in)', group['pattern']):\n key = 'frame_in'\n elif re.search('(Total +frames +received +in +error)', group['pattern']):\n key = 'frame_error_in'\n elif re.search('(Total +frames +discarded)', group['pattern']):\n key = 'frame_discard'\n elif re.search('(Total +TLVs +discarded)', group['pattern']):\n key = 'tlv_discard'\n elif re.search('(Total +TLVs +unrecognized)', group['pattern']):\n key = 'tlv_unknown'\n else:\n continue\n ret_dict[key] = int(group['value'])\n continue\n return ret_dict\n\n\nclass ShowLldpInterfaceSchema(MetaParser):\n \"\"\"Schema for show lldp interface []\"\"\"\n schema = {\n 'interfaces': {\n Any(): {\n 'tx': str,\n 'rx': str,\n 'tx_state': str,\n 'rx_state': str,\n },\n }\n }\n\n\nclass ShowLldpInterface(ShowLldpInterfaceSchema):\n \"\"\"Parser for show lldp interface []\"\"\"\n\n cli_command = ['show lldp interface {interface}','show lldp interface']\n\n def cli(self, interface='',output=None):\n if output is None:\n if interface:\n cmd = self.cli_command[0].format(interface=interface)\n else:\n cmd = self.cli_command[1]\n out = self.device.execute(cmd)\n else:\n out = output\n\n # initial return dictionary\n ret_dict = {}\n\n # initial regexp pattern\n p1 = re.compile(r'^(?P[\\w\\/\\-\\.]+):$')\n p2 = re.compile(r'^(?P[\\w\\s]+): +(?P[\\w\\s]+)$')\n\n for line in out.splitlines():\n line = line.strip()\n\n # GigabitEthernet1/0/15\n m = p1.match(line)\n if m:\n intf_dict = ret_dict.setdefault('interfaces', {}).\\\n setdefault(m.groupdict()['intf'], {})\n continue\n \n # Tx: enabled\n # Rx: enabled\n # Tx state: IDLE\n # Rx state: WAIT FOR FRAME\n m = p2.match(line)\n if m:\n group = m.groupdict()\n key = '_'.join(group['key'].lower().split())\n intf_dict[key] = group['value'].lower()\n continue\n return ret_dict\n\n","sub_path":"src/genie/libs/parser/iosxe/show_lldp.py","file_name":"show_lldp.py","file_ext":"py","file_size_in_byte":15787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"254053193","text":"print(\"Input : \")\r\nnums = list(map(int, input().split()))\r\n\r\ndef sorteNum(nums):\r\n for i in range(0,len(nums)):\r\n for j in range(i+1,len(nums)):\r\n nums.sort()\r\n print(nums)\r\n\r\nprint(\"After sorting :\")\r\nsorteNum(nums)","sub_path":"internship/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"573719797","text":"janeiro=1\nfevereiro=2\nmarco=3\nabril=4\nmaio=5\njunho=6\njulho=7\nagosto=8\nsetembro=9\noutubro=10\nnovembro=11\ndezembro=12\nlista=[janeiro, fevereiro, marco, abril, maio, junho, julho, agosto, setembro, outubro, novembro, dezembro]\nlista_i=[]\ni=0\nwhile i < len(lista):\n print (lista[i])\n i+=1","sub_path":"backup/user_051/ch44_2020_08_17_16_40_05_005355.py","file_name":"ch44_2020_08_17_16_40_05_005355.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377852633","text":"#!/usr/bin/env python \n\n__author__ = 'Patrick Campbell'\n__email__ = 'patrick.c.campbell@noaa.gov'\n__license__ = 'GPL'\n\n#Simple MONET utility to command line pair model vs. observations \n\nimport os\nfrom glob import glob\nimport sys\n\nimport subprocess\nfrom distutils.spawn import find_executable\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n\nimport monet\nfrom monet.util.tools import long_to_wide\nimport pandas as pd\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(\n description='combines paired data files for multiple model runs',\n formatter_class=ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n '-p',\n '--paired_files',\n help='string input paired data files (>=2)',\n nargs='+',\n type=str,\n required=True)\n parser.add_argument(\n '-s',\n '--model_species',\n help='string/list input for obs species-variables to pair',\n type=str,\n nargs='+',\n required=False,\n default=['O3', 'PM25_TOT'])\n parser.add_argument(\n '-mdf',\n '--mergedf',\n help='boolean operator to merge entire dataframes (slow)',\n type=bool,\n required=False,\n default=False)\n parser.add_argument(\n '-o',\n '--output',\n help='string output path/filename for combined paired dataframe',\n type=str,\n required=False,\n default='./AIRNOW_CMAQ_merged_pair')\n parser.add_argument(\n '-v',\n '--verbose',\n help='print debugging information',\n action='store_true',\n required=False)\n args = parser.parse_args()\n\n paired_files = args.paired_files\n species = args.model_species\n output = args.output\n verbose = args.verbose\n mergedf = args.mergedf\n\n print('combining paired files...')\n print(paired_files)\n count=0\n for i in paired_files:\n df=pd.read_hdf(i) \n if count == 0:\n df_merge=df\n else: \n if mergedf is False:\n \tdf_species=df[species]\n \tdf_species = df_species.add_suffix('_'+str(count+1))\n \tprint('joining model data columns...')\n \tdf_merge=df_merge.join(df_species)\n else:\n \tdf[species] = df[species].add_suffix('_'+str(count+1))\n \tprint('merging entire dataframes...slow...')\n \tdf_merge=df_merge.merge(df,on='time')\n count=count+1\n print('final merged data frame...')\n print(df_merge.keys())\n\n df_merge.to_hdf(output+'.hdf',\n 'df_merge',\n format='table',\n mode='w')\n df_merge.to_csv(output+'.csv')\n sys.exit(0)\n","sub_path":"10.verify_combine_pair.py","file_name":"10.verify_combine_pair.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"21214047","text":"import matplotlib.pyplot as plt\nimport csv\n\nx_all = []\ny_all = []\nx = []\ny = []\n\ndata_x = open('/Users/sreyapt/Documents/GitHub/Intro-python-final/dataX.csv')\ndata_y = open('/Users/sreyapt/Documents/GitHub/Intro-python-final/dataY.csv')\n\nx_reader = csv.reader(data_x)\ncount = 0;\nfor row in x_reader:\n if ('X values of sin' in row ):\n continue\n for field in row:\n x_all.append(float(field))\n if (count < 251):\n x.append(float(field))\n count +=1\n\ny_reader = csv.reader(data_y)\ncount = 0;\nfor row in y_reader:\n if ('Y values of sin' in row ):\n continue\n for field in row:\n y_all.append(float(field))\n if (count <251):\n y.append(float(field))\n count += 1\n\narea = 0.0\ndelta = x[1]-x[0]\nfor i in range(250):\n area += y[i]*delta\n\nplt.plot(x_all, y_all)\nplt.fill_between(x, y)\nplt.text(0.25, 0, \"area = \" + str(area))\nplt.show()\n\n","sub_path":"FInal_Project.py","file_name":"FInal_Project.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"563605936","text":"from prettytable import PrettyTable\r\nfrom bdCiudades import (\r\n connection,\r\n getCiudadBD,\r\n insertCiudadBD,\r\n searchCiudadById,\r\n updateCiudadBD,\r\n deleteCiudadBD,\r\n)\r\nfrom paises_view import tablaPaises\r\n\r\n\r\nclass TablaCiudades:\r\n def __init__(self):\r\n self.getAllCiudades()\r\n\r\n def getAllCiudades(self):\r\n result = getCiudadBD()\r\n\r\n table = PrettyTable()\r\n table.field_names = [\r\n \"Id\",\r\n \"Nombre\",\r\n \"IdPais\",\r\n \"Nombre del País\",\r\n ]\r\n\r\n for ciudad in result:\r\n table.add_row(\r\n [\r\n ciudad[\"idCiudades\"],\r\n ciudad[\"nombre\"],\r\n ciudad[\"idPaises\"],\r\n ciudad[\"nombrePais\"],\r\n ]\r\n )\r\n print(table)\r\n table.clear()\r\n\r\n def addNewCiudad(self):\r\n print(\"Se está añadiendo una nueva ciudad: \")\r\n nombre = input(\"Nombre: \")\r\n print(\"--Tabla Países--\")\r\n tablaPaises()\r\n idPais = input(\"Id del país: \")\r\n insertCiudadBD(nombre, idPais)\r\n print(\" \")\r\n print(\"-----------Se agregó correctamente la ciudad----------\")\r\n print(\" \")\r\n self.getAllCiudades()\r\n\r\n def updateCiudad(self):\r\n print(\"Se está actualizando la información de una ciudad: \")\r\n self.getAllCiudades()\r\n idCiudad = int(input(\"Id de la ciudad a actualizar: \"))\r\n ciudad = searchCiudadById(idCiudad)\r\n\r\n update = int(input(\"¿Desea actualizar el nombre? 0.No, 1.Sí: \"))\r\n if update == 1:\r\n print(f\"Nombre anterior: {ciudad['nombre']}\")\r\n nombre = input(\"Nuevo nombre: \")\r\n else:\r\n nombre = ciudad[\"nombre\"]\r\n\r\n update = int(input(\"¿Desea actualizar el Id del país? 0.No, 1.Sí: \"))\r\n if update == 1:\r\n print(\"--Tabla Países--\")\r\n tablaPaises()\r\n print(f\"Id anterior: {ciudad['idPaises']}\")\r\n idPais = input(\"Nuevo Id: \")\r\n else:\r\n idPais = ciudad[\"idPaises\"]\r\n updateCiudadBD(nombre, idPais, idCiudad)\r\n print(\" \")\r\n print(\"-----------Se actualizó correctamente la ciudad----------\")\r\n print(\" \")\r\n self.getAllCiudades()\r\n\r\n def deleteCiudad(self):\r\n print(\"Se está eliminando una ciudad: \")\r\n self.getAllCiudades()\r\n idCiudad = int(input(\"Id de la ciudad a eliminar: \"))\r\n deleteCiudadBD(idCiudad)\r\n print(\" \")\r\n print(\"-----------Se eliminó correctamente la ciudad----------\")\r\n print(\" \")\r\n self.getAllCiudades()\r\n","sub_path":"ciudades_view.py","file_name":"ciudades_view.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"464405136","text":"EMPTY= 0\nBLACK=1\nWHITE=2\n\nclass WrongRow(Exception):\n\t'Raised with a non-existant row'\n\tpass\n\nclass WrongColumn(Exception):\n\t'Raised with an non-existant column'\n\tpass\n\nclass game_state:\n\n\tdef __init__(self, numRows: int, numCols: int, firstMove: str,\n\t\t\t\t topLeftDisc: str, winCondition: str):\n\t\tgame_state.won= False\n\t\tgame_state.rows= numRows\n\t\tgame_state.columns= numCols\n\t\tgame_state.turn= firstMove\n\t\tgame_state.topLeft= topLeftDisc\n\t\tgame_state.winCon= winCondition\n\t\tgame_state.board=[]\n\t\tfor x in range(game_state.rows):\n\t\t\tgame_state.board.append([])\n\t\tfor element in game_state.board:\n\t\t\tfor y in range(game_state.columns):\n\t\t\t\telement.append(0)\n\n\tdef startPositions(self)->None:\n\t\t'Initializes the board to have the correct starting position'\n\t\ttopRow= int((self.rows/2)-1)\n\t\tbottomRow= int((self.rows/2))\n\t\tleftColumn= int((self.columns/2)-1)\n\t\trightColumn= int((self.columns/2))\n\t\tif self.topLeft == 'B':\n\t\t\tself.board[topRow][leftColumn]=1\n\t\t\tself.board[topRow][rightColumn]=2\n\t\t\tself.board[bottomRow][rightColumn]=1\n\t\t\tself.board[bottomRow][leftColumn]=2\n\t\tif self.topLeft == 'W':\n\t\t\tself.board[topRow][leftColumn]=2\n\t\t\tself.board[topRow][rightColumn]=1\n\t\t\tself.board[bottomRow][rightColumn]=2\n\t\t\tself.board[bottomRow][leftColumn]=1\n\n\tdef getBlacks(self)->int:\n\t\t'Returns the number of black pieces on the board'\n\t\tnumBlacks=0\n\t\tfor x in self.board:\n\t\t\tfor y in x:\n\t\t\t\tif y==1:\n\t\t\t\t\tnumBlacks +=1\n\t\treturn numBlacks\n\n\tdef getWhites(self)->int:\n\t\t'Returns the number of black pieces on the board'\n\t\tnumWhites=0\n\t\tfor x in self.board:\n\t\t\tfor y in x:\n\t\t\t\tif y==2:\n\t\t\t\t\tnumWhites +=1\n\t\treturn numWhites\n\n\tdef getTurn(self, count_iteration: int)->int:\n\t\t'Determines if its black\\'s or white\\'s turn'\n\t\tif self.turn== 'B':\n\t\t\tif (count_iteration%2==0):\n\t\t\t\treturn 1\n\t\t\tif (count_iteration%2==1):\n\t\t\t\treturn 2\n\t\tif self.turn=='W':\n\t\t\tif (count_iteration%2==0):\n\t\t\t\treturn 2\n\t\t\tif (count_iteration%2==1):\n\t\t\t\treturn 1\n\n\tdef otherPiece(self, count)->int:\n\t\t'Returns the integer of the opposite team'\n\t\tif self.getTurn(count)==1:\n\t\t\treturn 2\n\t\tif self.getTurn(count)==2:\n\t\t\treturn 1\n\n\n\tdef make_move(self, count_iteration: int,\n\t\t\t row_input: int, col_input: int)-> None:\n\t\t'Drops a piece on the board'\n\t\tself.board[row_input][col_input]=self.getTurn(count_iteration)\n\n\tdef iter_flipped(self, count_iter:int, row: int, col:int)->[(int,int)]:\n\t\t'Returns a list of pieces that should be flipped, given a move'\n\t\tself._need_valid_col(col)\n\t\tself._need_valid_row(row)\n\t\tif self.board[row][col]!=EMPTY:\n\t\t\treturn []\n\t\tpieces=[]\n\t\tdirects= [[0,1],[1,0],[0,-1],[-1,0],[1,1],[1,-1],[-1,1],[-1,-1]]\n\t\tfor element in directs:\n\t\t\tpieces.extend(self._list_flipped(element, row, col, count_iter))\n\t\treturn (pieces)\n\n\tdef _list_flipped(self, direction: [int], row: int, col: int, count_iter: int)->[(int,int)]:\n\t\t'Finds pieces that should be flipped given a direction'\n\t\tflipped=[]\n\n\t\tif (self._valid_col(col+direction[1]) and self._valid_row(row+direction[0])):\n\n\t\t\tif self.board[row+direction[0]][col+direction[1]] != self.otherPiece(count_iter):\n\n\t\t\t\treturn []\n\t\tn=1\n\t\twhile True:\n\t\t\tif not (self._valid_col(col+direction[1]*n)and self._valid_row(row+direction[0]*n)):\n\t\t\t\treturn []\n\t\t\tif self.board[row+direction[0]*n][col+direction[1]*n] == EMPTY:\n\t\t\t\treturn []\n\t\t\tif self.board[row+direction[0]*n][col+direction[1]*n] == self.getTurn(count_iter):\n\t\t\t\tfor x in range(1,n):\n\t\t\t\t\tflipped.append(((row+direction[0]*x),(col+direction[1]*x)))\n\t\t\t\treturn flipped\n\t\t\t#searches for cell to end chain of not cells\n\t\t\tn+=1\n\t\treturn flipped\n\n\tdef flip_pieces(self, pieces: [(int, int)], count)->None:\n\t\t'Flips pieces given a list'\n\t\tfor element in pieces:\n\t\t\trow= element[0]\n\t\t\tcol= element[1]\n\t\t\tself.board[row][col] = self.getTurn(count)\n\n\tdef has_move(self, count: int)->bool:\n\t\t'Returns whether or not a player has a valid move'\n\t\tfor row in range(self.rows):\n\t\t\tfor col in range(self.columns):\n\t\t\t\tif len(self.iter_flipped(count, row, col))>0:\n\t\t\t\t\treturn True\n\t\treturn False\n\n\tdef game_over(self)-> bool:\n\t\t'returns true when neither player has a move'\n\t\treturn not(self.has_move(0) or self.has_move(1))\n\n\tdef winner(self)->None:\n\t\t'Prints out the winner'\n\t\twinner= ''\n\t\tif self.getWhites()== self.getBlacks():\n\t\t\twinner = 'NONE'\n\t\tif self.winCon =='>':\n\t\t\tif (self.getWhites()> self.getBlacks()):\n\t\t\t\twinner = 'White'\n\t\t\tif (self.getBlacks()> self.getWhites()):\n\t\t\t\twinner= 'Black'\n\t\tif self.winCon == '<':\n\t\t\tif (self.getWhites()< self.getBlacks()):\n\t\t\t\twinner = 'White'\n\t\t\tif (self.getBlacks()< self.getWhites()):\n\t\t\t\twinner= 'Black'\n\t\treturn winner\n\n\n\tdef _need_valid_row(self, row_num: int)-> None:\n\t\tif type(row_num) != int or not self._valid_row(row_num):\n\t\t\traise WrongRow('row must be int between 1 and {}'.format(self.rows))\n\n\tdef _need_valid_col(self, col_num: int)-> None:\n\t\tif type(col_num) != int or not self._valid_col(col_num):\n\t\t\traise WrongColumn('row must be int between 1 and {}'.format(self.columns))\n\n\tdef _valid_col(self, col_num:int)->bool:\n\t\t'Determins if a column being checked is valid'\n\t\treturn 0<=col_numbool:\n\t\t'Determines if a row being checked is valid'\n\t\treturn 0<=row_numstr:\n\t'Adds color to integers'\n\tif color== EMPTY:\n\t\treturn '.'\n\tif color== BLACK:\n\t\treturn 'B'\n\tif color== WHITE:\n\t\treturn 'W'\n","sub_path":"othello/new_logic.py","file_name":"new_logic.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"555090696","text":"from collections import defaultdict\n\ndef del_if_zero(dict, char):\n if dict[char] == 0:\n del dict[char]\n \ndef anagram_indices(word, s):\n result = []\n \n freq = defaultdict(int)\n for char in word:\n freq[char] += 1\n \n for char in s[:len(word)]:\n freq[char] -= 1\n del_if_zero(freq, char)\n \n if not freq:\n result.append(0)\n \n for i in range(len(word), len(s)):\n start_char, end_char = s[i - len(word)], s[i]\n \n freq[start_char] += 1\n del_if_zero(freq, start_char)\n \n freq[end_char] -= 1\n del_if_zero(freq, end_char)\n \n if not freq:\n beginning_index = i - len(word) + 1\n result.append(beginning_index)\n \n return result","sub_path":"anagram/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"194769538","text":"# 931. Minimum Falling Path Sum\n\n# code:\nclass Solution:\n def minFallingPathSum(self, arr: List[List[int]]) -> int:\n \n # Edge cases\n if not arr or len(arr[0])==0:\n return 0\n \n # Iterate over the entire grid and keep checking with the above row.\n for i in range(1, len(arr)):\n for j in range(0, len(arr[0])):\n if j==0:\n arr[i][j] += min(arr[i-1][j],arr[i-1][j+1])\n elif j==len(arr[0])-1:\n arr[i][j] += min(arr[i-1][j],arr[i-1][j-1])\n else:\n arr[i][j] += min(arr[i-1][j], min(arr[i-1][j-1],arr[i-1][j+1]))\n \n # Initalizing min to maximum value.\n res = float('inf')\n \n # Iterative over the last row to ge the minimum\n for i in arr[-1]:\n if i'\nfile = \"io.txt\"\n\nresult = 'FindeINC.py'\n\nf = open('login.txt','r')\nfor line in f.readlines(): line\n\nmore = big + '%s' \nalfa = (line[1]) + '%s'\nlogin = line + '%s'\n\nlogins = re.sub(\"\\s*\\n\\s*\", ' ', login.strip()) \n\n#commands\nstroka = str(scan % path % alfa % logins % more % file)\noperationCheck = scan % path % alfa % logins % more % file\noperationSend = 'mail -s \"Virus Monitor\" bigcaches@yandex.ru < io.txt'\noperationRemove = 'rm io.txt'\n#print stroka\nresultCheck = commands.getoutput(operationCheck)\nfile_io = open('io.txt' , 'a')\nfile_io.write(logins)\nfile_io.close()\nresultSend = commands.getoutput(operationSend)\nresultRemove = commands.getoutput(operationRemove)\nf.close() \n\n\n","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"606124319","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 22 15:36:16 2019\n\n@author: alpha\n\"\"\"\n\n\nimport argparse\nimport sys\nfrom enum import Enum\nimport multiprocessing as mp\nimport logging\nimport os\n\n\nimport myenv\nimport gym #倒立振子(cartpole)の実行環境\nfrom gym import wrappers #gymの画像保存\nimport numpy as np\nimport time\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nimport chainer.initializers as I\nfrom chainer import serializers\n\nimport chainerrl\nfrom chainerrl import agent\nfrom chainerrl import links\n#from chainerrl.q_function import StateQFunction\nimport chainerrl.q_functions as Qfunc\nfrom chainerrl.action_value import DiscreteActionValue\nfrom chainerrl.agents import dqn\n\nimport success_buffer_replay\nimport SuccessRateEpsilonGreedy\nimport twn_model_base\n\n\nclass Qfunc_FC_TWN2_Vision(chainer.ChainList):\n \"\"\"AEによるレーダー情報分析層\n\n Args:\n num_ray: TWNセンサーでとらえた周囲の状況を表すレーダーの本数\n n_clasfy_ray: レーダー情報の分析結果の出力要素数\n \"\"\"\n\n class Qfunc_FC_TWN_model_AECNN_for_Ray:\n \"\"\" \n AutoEncoder of CNN for ray input\n レーダーセンサーの入力情報に対する畳み込み層のモデル\n 畳み込み層は、特徴抽出ための層となるので、AutoEncoderの手法を利用して、学習を行う。\n よって、この層は、強化学習の対象とはならない。\n \n \"\"\"\n \n def calc_num_out_elements1D(self, num_element, in_channel, out_channel, filter_size, slide_size, pooling_size):\n '''\n num_element: number of input elements per input channel\n in_channel: number of input channel\n out_channel: number of output channel\n filter_size: filter size of convolution\n slide_size: slide size of filter\n pooling_size: pooling size for output\n \n return of 1st: number of elements of convolution output\n return of 2nd: number of elements of pooling output\n '''\n num_of_conv_out_elements = (num_element - filter_size)//slide_size + 1\n num_of_pooling_out_elements = num_of_conv_out_elements//pooling_size\n if (num_of_conv_out_elements%pooling_size) != 0:\n num_of_pooling_out_elements += 1\n \n return num_of_conv_out_elements, num_of_pooling_out_elements\n \n def calc_num_out_elementsND(self, num_element, pad_size, in_channel, out_channel, filter_size, slide_size, pooling_size):\n '''\n num_element: list type [180, 10]\n pad_size: list type [1, 1]\n \n return: type is np array\n '''\n np_num_element = np.array(num_element)\n np_pad_size = np.array(pad_size)\n num_of_conv_out_elements = ((np_num_element + np_pad_size) - filter_size)//slide_size + 1\n num_of_pooling_out_elements = num_of_conv_out_elements//pooling_size\n num_of_pooling_out_elements[num_of_conv_out_elements%pooling_size != 0] += 1\n \n return num_of_conv_out_elements, num_of_pooling_out_elements\n \n def __init__(self, num_in_elements, num_in_channel=1, out_channel=16, filter_size=5, slide_size=1, pooling_size=2, name=None):\n '''\n num_in_elements: number of input elements per input channel\n num_in_channel: number of input channel\n out_channel: number of output channel\n filter_size: filter size of convolution\n slide_size: slide size of filter\n pooling_size: pooling size for output\n Name: name of this layer\n dropout_rate: dropout ratio of output layer\n '''\n \n self.num_in_elements = num_in_elements\n \n self.in_channel = num_in_channel\n self.out_channel = out_channel\n self.filter_size = filter_size\n self.slide_size = slide_size\n self.pooling_size = pooling_size\n \n self.num_of_conv_out_elements, self.num_of_pooling_out_elements = self.calc_num_out_elements1D(self.num_in_elements, self.in_channel, self.out_channel, self.filter_size, self.slide_size, self.pooling_size)\n\n print('Layer {}: in: {} out: conv out {} pooling out {}'.format(name, self.num_in_elements, self.num_of_conv_out_elements, self.num_of_pooling_out_elements))\n\n self.conv = L.ConvolutionND(1, self.in_channel, self.out_channel, ksize=self.filter_size, stride=self.slide_size)\n self.dcnv = L.DeconvolutionND(1, self.out_channel, self.in_channel, ksize=self.filter_size, stride=self.slide_size)\n # self.bnorm = L.BatchNormalization(self.out_channel)\n \n\n def gen_clasify_link(self, num_in_elements, num_in_channel, n_clasfy_ray, intermidiate_layers=[], dropout_rate=[], name=None):\n '''\n num_in_elements: number of output elements per output channel of CNN as input\n num_in_channel: number of output channel of CNN as input\n n_clasfy_ray: number of clasify\n intermidiate_layers: the list of intermidiate units rasio to the number of input units\n Name: name of this layer\n dropout_rate: dropout ratio of output layer. this is experimental purpose.\n '''\n\n self.cl_num_in_elements = num_in_elements\n self.cl_num_in_channel = num_in_channel\n\n self.dropout_rate_list = []\n\n self.n_clasfy_ray = n_clasfy_ray\n\n forward_layer_unit_seq = [self.cl_num_in_elements*self.cl_num_in_channel]\n for r, d in zip(intermidiate_layers, dropout_rate):\n ne = int(forward_layer_unit_seq[0] * (r/(1.0-d)))\n forward_layer_unit_seq.append(ne)\n self.dropout_rate_list.append(d)\n forward_layer_unit_seq.append(self.n_clasfy_ray)\n self.dropout_rate_list.append(0.0) # 最終層は、ドロップアウトなし\n\n i = 0\n for ie, oe, d in zip(forward_layer_unit_seq, forward_layer_unit_seq[1:], self.dropout_rate_list):\n nfl = L.Linear(ie, oe)\n nrl = L.Linear(oe, ie)\n bn = L.BatchNormalization(oe)\n self.fwd_links.append(nfl)\n self.rev_links.append(nrl)\n self.bnorm_clasify.append(bn)\n print('Rader analysis Layer {} {}: in: element {}, out: {}/{}'.format(name, i, ie, int(oe*(1.0-d)), oe))\n i += 1\n \n\n def __init__(self, num_ray, n_clasfy_ray):\n self.conv_dcnv_links = []\n self.bnorm_conv = []\n self.fwd_links = []\n self.rev_links = []\n self.bnorm_clasify = []\n\n\n self.num_ray = num_ray\n self.n_clasfy_ray = n_clasfy_ray\n\n self.in_channel_1st = 1\n out_channel_1st = 16\n filter_size_1st = 5\n slide_size_1st = 1\n self.pooling_size_1st = 2\n\n out_channel_2nd = 64\n filter_size_2nd = 3\n slide_size_2nd = 1\n self.pooling_size_2nd = 4\n \n self.conv_dcnv_links.append( Qfunc_FC_TWN2_Vision.Qfunc_FC_TWN_model_AECNN_for_Ray(\n num_ray,\n num_in_channel=self.in_channel_1st,\n out_channel=out_channel_1st,\n filter_size=filter_size_1st,\n slide_size=slide_size_1st,\n pooling_size=self.pooling_size_1st,\n name=\"1st conv\") )\n self.conv_dcnv_links.append( Qfunc_FC_TWN2_Vision.Qfunc_FC_TWN_model_AECNN_for_Ray(\n self.conv_dcnv_links[0].num_of_pooling_out_elements,\n num_in_channel=out_channel_1st,\n out_channel=out_channel_2nd,\n filter_size=filter_size_2nd,\n slide_size=slide_size_2nd,\n pooling_size=self.pooling_size_2nd,\n name=\"2nd conv\") )\n\n self.gen_clasify_link(\n self.conv_dcnv_links[1].num_of_pooling_out_elements,\n out_channel_2nd,\n self.n_clasfy_ray,\n [0.5, 0.1],\n [0.0, 0.0],\n name=\"Clasify\")\n\n self.debug_info = {}\n\n super().__init__()\n for cdl in self.conv_dcnv_links:\n self.add_link(cdl.conv)\n self.add_link(cdl.dcnv)\n # self.add_link(cdl.bnorm)\n for fl, rl, bn in zip(self.fwd_links, self.rev_links, self.bnorm_clasify):\n self.add_link(fl)\n self.add_link(rl)\n self.add_link(bn)\n\n\n def fwd(self, x):\n h_inout = x\n for cdl in self.conv_dcnv_links:\n # h_inout = F.relu(cdl.bnorm(cdl.conv(h_inout)))\n h_inout = F.relu(cdl.conv(h_inout))\n h_inout = F.max_pooling_nd(h_inout, cdl.pooling_size)\n\n for l, d, bn in zip(self.fwd_links, self.dropout_rate_list, self.bnorm_clasify):\n h_inout = F.leaky_relu(bn(l(h_inout)))\n if d != 0.0:\n h_inout = F.dropout(h_inout, d)\n \n self.debug_info['clasify_out'] = h_inout.array\n \n return h_inout\n\n\n def __call__(self, x):\n '''\n 強化学習用のQ関数ではないので、普通にlossを返す\n '''\n self.debug_info['cnn_ae_out'] = []\n self.debug_info['clasify_ae_out'] = []\n loss = None\n h_in = x\n for cdl in self.conv_dcnv_links:\n # h_out = F.relu(cdl.bnorm(cdl.conv(h_in)))\n h_out = F.relu(cdl.conv(h_in))\n dcnv_out = cdl.dcnv(h_out)\n ls = F.mean_squared_error(dcnv_out, h_in)\n if loss is None:\n loss = ls\n else:\n loss = loss + ls # 計算グラフ上は、正しいはず。\n\n self.debug_info['cnn_ae_out'].append([h_out, ls, dcnv_out, h_in]) # デバッグ用に処理過程の情報を残す\n \n h_in = F.max_pooling_nd(chainer.Variable(h_out.array), cdl.pooling_size)\n\n for fl, rl, d, bn in zip(self.fwd_links, self.rev_links, self.dropout_rate_list, self.bnorm_clasify):\n h_out = F.leaky_relu(bn(fl(h_in)))\n #h_out = F.sigmoid(fl(h_in))\n if d != 0.0:\n h_out = F.dropout(h_out, d)\n h_rout = F.reshape(rl(h_out), h_in.shape)\n ls = F.mean_squared_error(h_rout, h_in)\n loss = loss + ls # 計算グラフ上は、正しいはず。\n\n self.debug_info['clasify_ae_out'].append([h_out, ls, h_rout, h_in]) # デバッグ用に処理過程の情報を残す\n\n h_in = chainer.Variable(h_out.array) # 後段の層からの逆伝搬が伝わらないように、次の層の入力データを改めて生成する\n\n return loss\n \n\n\nclass Qfunc_FC_TWN_RL(Qfunc.SingleModelStateQFunctionWithDiscreteAction, agent.AttributeSavingMixin):\n \"\"\"行動価値関数 = Q関数\n\n Args:\n n_size_twn_status: TWN自身の状態\n num_ray: TWNセンサーでとらえた周囲の状況\n n_size_eb_status: TWNセンサーでとらえた、EBの情報\n n_actions: 離散アクション空間\n explor_rate=0.0: 探索行動比率(現時点で未使用)\n \"\"\"\n\n class Qfunc_FC_TWN_model_RLLayer(chainer.Chain, agent.AttributeSavingMixin):\n \"\"\" \n 強化学習の対象となる層\n \"\"\"\n \n saved_attributes = ('l4','l5','action_chain_list','bn1','bn2','bn3')\n \n def __init__(self, n_in_elements, n_actions, explor_rate=0.0):\n '''\n Q値の範囲が報酬体系によって負の値をとる場合、F.reluは負の値をとれないので、学習に適さない。\n 活性化関数は、負の値も取ることが可能なものを選択する必要がある。\n 例えば、F.leaky_relu等。勾配消失問題を考えると、これが良い感じ。\n \n n_size_twn_status: TWN自身の状態\n num_ray_out: TWNセンサーをCNN層で処理した結果得られるデータ数のタプル (CNN層の出力要素数, CNN層の出力チャンネル数)\n n_size_eb_status: TWNセンサーでとらえた、EBの情報\n n_actions: 離散アクション空間\n explor_rate=0.0: 探索行動比率(現時点で未使用)\n '''\n\n super().__init__()\n with self.init_scope():\n self.bn1 = L.BatchNormalization(n_in_elements)\n self.l4 = links.MLP(n_in_elements, int(n_in_elements*1.2), (n_in_elements*2, int(n_in_elements*1.8), int(n_in_elements*1.5)), nonlinearity=F.leaky_relu)\n self.bn2 = L.BatchNormalization(int(n_in_elements*1.2))\n self.l5 = links.MLP(int(n_in_elements*1.2)+4, 4, (n_in_elements, int(n_in_elements*0.8), (n_in_elements*2)//3), nonlinearity=F.leaky_relu)\n self.bn3 = L.BatchNormalization(4)\n local_action_links_list = []\n for i in range(n_actions):\n action_links = links.MLP(4, 1, (n_in_elements//2,), nonlinearity=F.leaky_relu)\n local_action_links_list.append(action_links)\n self.action_chain_list = chainer.ChainList(*local_action_links_list)\n\n self.explor_rate = explor_rate\n \n self.debug_info = None\n \n \n def __call__(self, x):\n '''\n return:\n type: Variable of Chainer\n Q values of all actions\n '''\n\n ss = list(x.shape)\n ss[1] = 1\n noise0 = np.random.normal( 0.0, 0.5, ss)\n noise1 = np.random.normal(-1.0, 0.5, ss)\n noise2 = np.random.normal( 1.0, 0.5, ss)\n noise3 = np.random.uniform(low=-1.0, high=1.0, size=ss)\n \n rdata = np.hstack([noise0, noise1, noise2, noise3]).astype(np.float32)\n\n h4 = self.bn2(self.l4(self.bn1(x)))\n h4_c = F.concat([h4, chainer.Variable(rdata)], axis=1)\n h5 = self.bn3(self.l5(h4_c))\n action_Qvalues = []\n for act_mlp in self.action_chain_list:\n qout = act_mlp(h5)\n action_Qvalues.append(qout)\n \n h7 = F.concat(action_Qvalues, axis=1)\n \n self.debug_info = (h7)\n \n return h7\n\n\n saved_attributes = ('model',)\n\n def __init__(self, n_in_elements, n_actions, explor_rate=0.0):\n super().__init__(\n model = Qfunc_FC_TWN_RL.Qfunc_FC_TWN_model_RLLayer(\n n_in_elements,\n n_actions,\n explor_rate=0.0\n )\n )\n\n\nclass MMAgent_DDQN(agent.Agent, agent.AttributeSavingMixin, twn_model_base.TWNAgentMixin):\n \"\"\"エージェント本体\n\n Args:\n num_ray: TWNセンサーでとらえた周囲の状況を表すレーダーの本数\n n_clasfy_ray: レーダー情報の分析結果の出力要素数\n \"\"\"\n saved_attributes = ('agent', 'cnn_ae', 'cnn_ae_opt')\n\n def __init__(self, args, env, load_flag=False, explor_rate=None):\n super().__init__()\n\n self.n_size_twn_status = env.obs_size_list[0]\n self.num_ray = env.obs_size_list[1]\n self.n_size_eb_status = env.obs_size_list[2]\n\n self.update_interval = 10\n self.target_update_interval = 200\n self.replay_start_size = 1000\n self.minibatch_size = 512\n\n self.success_rate = 1.0\n\n gamma = 0.985\n alpha = 0.5\n \n n_clasfy_ray = 32\n\n# self.q_func = Qfunc_FC_TWN2_Vision(env.obs_size_list[0], env.obs_size_list[1], env.obs_size_list[2], env.action_space.n)\n self.cnn_ae = Qfunc_FC_TWN2_Vision(self.num_ray, n_clasfy_ray)\n self.cnn_ae_opt = chainer.optimizers.Adam()\n self.cnn_ae_opt.setup(self.cnn_ae)\n self.replay_buffer_cnn_ae = success_buffer_replay.SuccessPrioReplayBuffer(capacity=10 ** 6)\n\n self.q_func = Qfunc_FC_TWN_RL(self.n_size_twn_status + n_clasfy_ray + self.n_size_eb_status, env.action_space.n)\n self.q_func_opt = chainer.optimizers.Adam(eps=1e-2)\n self.q_func_opt.setup(self.q_func)\n self.explorer = None\n if load_flag:\n if explor_rate is None:\n self.explorer = chainerrl.explorers.ConstantEpsilonGreedy(epsilon=0.05, random_action_func=env.action_space.sample)\n else:\n self.explorer = SuccessRateEpsilonGreedy.SuccessRateEpsilonGreedy(start_epsilon=explor_rate, end_epsilon=0.0, decay_steps=50000, random_action_func=env.action_space.sample)\n else:\n self.explorer = SuccessRateEpsilonGreedy.SuccessRateEpsilonGreedy(start_epsilon=0.5, end_epsilon=0.0, decay_steps=50000, random_action_func=env.action_space.sample)\n \n #replay_buffer = chainerrl.replay_buffer.ReplayBuffer(capacity=10 ** 6)\n #replay_buffer = chainerrl.replay_buffer.PrioritizedReplayBuffer(capacity=10 ** 6)\n #replay_buffer = chainerrl.replay_buffer.PrioritizedEpisodicReplayBuffer(capacity=10 ** 6)\n replay_buffer_q_func = success_buffer_replay.ActionFareSamplingReplayBuffer(capacity=10 ** 6)\n \n phi = lambda x: x.astype(np.float32, copy=False)\n self.agent = chainerrl.agents.DoubleDQN(\n self.q_func, self.q_func_opt, replay_buffer_q_func, gamma, self.explorer,\n average_q_decay=0.01, average_loss_decay=0.01,\n update_interval=self.update_interval,\n target_update_interval=self.target_update_interval,\n phi=phi,\n replay_start_size=self.replay_start_size,\n minibatch_size=self.minibatch_size,\n #replay_start_size=5, minibatch_size=3, episodic_update=True, episodic_update_len=64\n )\n \n self.t = 0\n\n def set_success_rate(self, rate):\n self.success_rate = rate\n\n def obs_split_twn(self, obs):\n state32 = obs.astype(np.float32)\n\n twn_status = state32[0:self.n_size_twn_status]\n x_ray = state32[self.n_size_twn_status:self.n_size_twn_status+self.num_ray]\n x = x_ray.reshape(1, self.num_ray)\n eb_status = state32[self.n_size_twn_status+self.num_ray:self.n_size_twn_status+self.num_ray+self.n_size_eb_status]\n \n return twn_status, x, eb_status\n \n def update(self):\n sample_obs = self.replay_buffer_cnn_ae.sample(self.minibatch_size)\n obs_np = np.array([elem['state'] for elem in sample_obs])\n \n self.cnn_ae.cleargrads()\n self.cnn_ae_last_loss = self.cnn_ae(obs_np)\n self.cnn_ae_last_loss.backward()\n self.cnn_ae_opt.update()\n\n def act_and_train(self, obs, reward):\n \"\"\"Select an action for training.\n\n Returns:\n ~object: action\n \"\"\"\n self.t += 1\n \n twn_status, x, eb_status = self.obs_split_twn(obs)\n\n with chainer.using_config(\"train\", False):\n with chainer.no_backprop_mode():\n self.replay_buffer_cnn_ae.append(x, None, reward)\n \n ch, element = x.shape\n x_ray_out = self.cnn_ae.fwd(x.reshape(1,ch,element))\n x_ray_out_np = x_ray_out.data.reshape(-1)\n \n h3_c = np.hstack([twn_status, x_ray_out_np, eb_status])\n\n self.explorer.set_success_rate(self.success_rate)\n \n action = self.agent.act_and_train(h3_c, reward)\n \n if (self.t % self.minibatch_size) == 0:\n if self.t > self.replay_start_size:\n self.update()\n \n return action\n\n def act(self, obs):\n \"\"\"Select an action for evaluation.\n\n Returns:\n ~object: action\n \"\"\"\n twn_status, x, eb_status = self.obs_split_twn(obs)\n \n with chainer.using_config(\"train\", False):\n with chainer.no_backprop_mode():\n ch, element = x.shape\n x_ray_out = self.cnn_ae.fwd(x.reshape(1,ch,element))\n x_ray_out_np = x_ray_out.data.reshape(-1)\n \n h3_c = np.hstack([twn_status, x_ray_out_np, eb_status])\n \n action = self.agent.act(h3_c)\n \n return action\n \n\n def stop_episode_and_train(self, state, reward, done=False):\n \"\"\"Observe consequences and prepare for a new episode.\n\n Returns:\n None\n \"\"\"\n self.t += 1\n\n twn_status, x, eb_status = self.obs_split_twn(state)\n \n with chainer.using_config(\"train\", False):\n with chainer.no_backprop_mode():\n self.replay_buffer_cnn_ae.append(x, None, reward, next_state=None, next_action=None, is_state_terminal=done)\n \n ch, element = x.shape\n x_ray_out = self.cnn_ae.fwd(x.reshape(1,ch,element))\n x_ray_out_np = x_ray_out.data.reshape(-1)\n \n h3_c = np.hstack([twn_status, x_ray_out_np, eb_status])\n \n self.replay_buffer_cnn_ae.stop_current_episode()\n self.agent.stop_episode_and_train(h3_c, reward, done)\n \n if self.t > self.replay_start_size:\n self.update()\n\n def stop_episode(self):\n \"\"\"Prepare for a new episode.\n\n Returns:\n None\n \"\"\"\n self.replay_buffer_cnn_ae.stop_current_episode()\n self.agent.stop_episode()\n\n def save(self, dirname):\n agent.AttributeSavingMixin.save(self, dirname)\n\n def load(self, dirname):\n agent.AttributeSavingMixin.load(self, dirname)\n\n\n def get_statistics(self):\n \"\"\"Get statistics of the agent.\n\n Returns:\n List of two-item tuples. The first item in a tuple is a str that\n represents the name of item, while the second item is a value to be\n recorded.\n\n Example: [('average_loss': 0), ('average_value': 1), ...]\n \"\"\"\n ans = []\n # if self.hist_ana_ae.debug_info is not None:\n # ans = [di[1] for di in self.hist_ana_ae.debug_info]\n # #print(ans)\n # else:\n # ans = []\n# if self.last_losses is not None:\n# ans.extend([('cnn1_loss', self.last_losses[0].data), ('cnn2_loss', self.last_losses[1].data), ('clasify_loss', self.last_losses[2].data)])\n ans.extend(self.agent.get_statistics())\n return ans\n\n def get_statistics_formated_string(self):\n stat = self.get_statistics()\n stat_strings = []\n # count = 1\n # for t in stat:\n # stat_strings.append('({} layer:{: >7.2f})'.format(count, t[1]))\n # count += 1\n if hasattr(self.explorer, 'compute_epsilon'):\n stat_strings.append('(explorer rate({: >6}): {:>7.3%})'.format(self.agent.t, self.explorer.compute_epsilon(self.agent.t) ) )\n else:\n stat_strings.append('(explorer rate({: >6}): XX.X)'.format(self.agent.t) )\n\n ans = ','.join(stat_strings)\n\n return ans\n\n\n\n\n\n\ndef func_agent_generation(args, env, load_flag=False, explor_rate=None, load_name=None):\n \n agent = MMAgent_DDQN(args, env, load_flag, explor_rate)\n\n #if len(args.load) > 0:\n if load_flag:\n #agent.load(args.load)\n agent.load('agent_{}'.format(load_name))\n #logger.debug('load: {}'.format(args.load) )\n print('load: {}'.format('agent') )\n\n return agent\n\n","sub_path":"twn_DDQN_agent_Type11.py","file_name":"twn_DDQN_agent_Type11.py","file_ext":"py","file_size_in_byte":23441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"354665190","text":"\"\"\"\nTests for the deploy method of the Cloudvomation class.\n\"\"\"\n\nimport unittest\n\nfrom mock import patch\n\nfrom cloudvomation import Cloudvomation\nfrom cloudvomation.exceptions import NotReadyError, ValidationError\n\nCLASS_IMPORT = 'cloudvomation.Cloudvomation.'\n\n\nclass WhenCreatingStackTestCase(unittest.TestCase):\n \"\"\" Tests for the case when stack will be created. \"\"\"\n\n @classmethod\n @patch(CLASS_IMPORT + '_create_stack')\n @patch(CLASS_IMPORT + '_describe', return_value=None)\n @patch(CLASS_IMPORT + '_is_ready_to_update')\n @patch(CLASS_IMPORT + '_update_stack')\n @patch(CLASS_IMPORT + '_validate', return_value=(True, None))\n def setUpClass(cls, # pylint: disable=arguments-differ, too-many-arguments\n mock_validate, # pylint: disable=unused-argument\n mock_update,\n mock_ready,\n mock_describe, # pylint: disable=unused-argument\n mock_create):\n\n cls.create = mock_create\n cls.ready = mock_ready\n cls.update = mock_update\n\n cloudvomation = Cloudvomation(region='eu-west-2',\n stack_name='my-stack-name',\n template_body='{\"x\":\"y\"}')\n cloudvomation.deploy()\n\n def test_ready_is_not_invoked(self):\n \"\"\" Assert that _is_ready_to_update is not invoked. \"\"\"\n self.ready.assert_not_called()\n\n def test_create_is_invoked(self):\n \"\"\" Assert that _create_stack is invoked. \"\"\"\n self.create.assert_called_with()\n\n def test_update_is_not_invoked(self):\n \"\"\" Assert that _update_stack is not invoked. \"\"\"\n self.update.assert_not_called()\n\n\nclass WhenStackIsNotReadyToUpdateTestCase(unittest.TestCase):\n \"\"\" Tests for the case when the existing stack is not ready. \"\"\"\n\n @classmethod\n @patch(CLASS_IMPORT + '_create_stack')\n @patch(CLASS_IMPORT + '_describe', return_value='response')\n @patch(CLASS_IMPORT + '_is_ready_to_update', return_value=(False, 'no'))\n @patch(CLASS_IMPORT + '_update_stack')\n @patch(CLASS_IMPORT + '_validate', return_value=(True, None))\n def setUpClass(cls, # pylint: disable=arguments-differ, too-many-arguments\n mock_validate, # pylint: disable=unused-argument\n mock_update,\n mock_ready,\n mock_describe, # pylint: disable=unused-argument\n mock_create):\n\n cls.create = mock_create\n cls.ready = mock_ready\n cls.update = mock_update\n\n cls.not_ready_raised = False\n\n cls.cv = Cloudvomation(region='eu-west-2',\n stack_name='my-stack-name',\n template_body='{\"x\":\"y\"}')\n try:\n cls.cv.deploy()\n except NotReadyError:\n cls.not_ready_raised = True\n\n def test_not_ready_is_raised(self):\n \"\"\" Assert that NotReadyError is raised. \"\"\"\n self.assertTrue(self.not_ready_raised)\n\n def test_create_is_not_invoked(self):\n \"\"\" Assert that _create_stack is not invoked. \"\"\"\n self.create.assert_not_called()\n\n def test_update_is_not_invoked(self):\n \"\"\" Assert that _update_stack is not invoked. \"\"\"\n self.update.assert_not_called()\n\n\nclass WhenTemplateIsInvalidTestCase(unittest.TestCase):\n \"\"\" Tests for the case when the template is invalid. \"\"\"\n\n @classmethod\n @patch(CLASS_IMPORT + '_create_stack')\n @patch(CLASS_IMPORT + '_update_stack')\n @patch(CLASS_IMPORT + '_validate', return_value=(False, 'invalid'))\n def setUpClass(cls, # pylint: disable=arguments-differ\n mock_validate,\n mock_update,\n mock_create):\n\n cls.create = mock_create\n cls.update = mock_update\n cls.validate = mock_validate\n\n cls.validation_error_raised = False\n\n cloudvomation = Cloudvomation(region='eu-west-2',\n stack_name='my-stack-name',\n template_body='{\"x\":\"y\"}')\n\n try:\n cloudvomation.deploy()\n except ValidationError:\n cls.validation_error_raised = True\n\n def test_validate_is_invoked(self):\n \"\"\" Assert that _validate is invoked. \"\"\"\n self.validate.assert_called_with()\n\n def test_validation_error_is_raised(self):\n \"\"\" Assert that ValidationError is raised. \"\"\"\n self.assertTrue(self.validation_error_raised)\n\n def test_create_is_not_invoked(self):\n \"\"\" Assert that _create_stack is not invoked. \"\"\"\n self.create.assert_not_called()\n\n def test_update_is_not_invoked(self):\n \"\"\" Assert that _update_stack is not invoked. \"\"\"\n self.update.assert_not_called()\n\n\nclass WhenUpdatingStackTestCase(unittest.TestCase):\n \"\"\" Tests for the case when stack will be updated. \"\"\"\n\n @classmethod\n @patch(CLASS_IMPORT + '_create_stack')\n @patch(CLASS_IMPORT + '_describe', return_value='response')\n @patch(CLASS_IMPORT + '_is_ready_to_update', return_value=(True, None))\n @patch(CLASS_IMPORT + '_update_stack')\n @patch(CLASS_IMPORT + '_validate', return_value=(True, None))\n def setUpClass(cls, # pylint: disable=arguments-differ, too-many-arguments\n mock_validate, # pylint: disable=unused-argument\n mock_update,\n mock_ready,\n mock_describe,\n mock_create):\n\n cls.create = mock_create\n cls.describe = mock_describe\n cls.ready = mock_ready\n cls.update = mock_update\n\n cloudvomation = Cloudvomation(region='eu-west-2',\n stack_name='my-stack-name',\n template_body='{\"x\":\"y\"}')\n cloudvomation.deploy()\n\n def test_ready_is_invoked(self):\n \"\"\" Assert that _is_ready_to_update is invoked. \"\"\"\n self.ready.assert_called_with(self.describe.return_value)\n\n def test_create_is_not_invoked(self):\n \"\"\" Assert that _create_stack is not_invoked. \"\"\"\n self.create.assert_not_called()\n\n def test_update_is_invoked(self):\n \"\"\" Assert that _update_stack is invoked. \"\"\"\n self.update.assert_called_with()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cloudvomation/classes/test_cloudvomation/test_deploy.py","file_name":"test_deploy.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"206196158","text":"#! /usr/bin/env python\n\"\"\"\nSoftware for parsing array configuration file and dealing with physical array parameters, eg. antenna positions, etc.\n\"\"\"\n\nimport xmlParser\nimport numpy as n\n\nclass Array:\n def __init__(self, config_file):\n self.config = xmlParser.xmlObject(config_file).xmlobj #python object containing all the information from the xml file\n self.config_file = config_file\n\n self.n_ants=len(self.config.antennas.ant)\n self.ants=self.config.antennas.ant\n self.ref_ant=self.config.antennas.reference\n self.receiver = self.config.receiver\n\n def loc(self,ant_index):\n '''Return the location of an antenna element in list format'''\n pos = self.ants[ant_index].position\n return [pos.x, pos.y, pos.z]\n\n def get_input_num(self,ant_index):\n '''Return the ADC input channel number of an antenna'''\n if self.ants[ant_index].pols == 1:\n return {'x':int(self.ants[ant_index].adc_chan.data)}\n #elif self.ants[ant_index].pols == 2:\n # if self.ants[ant_index].adc_chan[0].pol=='x':\n # return {'x':int(self.ants.[ant_index].adc_chan[0].data),\n # 'y':int(self.ants.[ant_index].adc_chan[1].data)}\n # else:\n # return {'x':int(self.ants.[ant_index].adc_chan[0].data),\n # 'y':int(self.ants.[ant_index].adc_chan[1].data)}\n else:\n raise IndexError('Only 1 or 2 polarisations supported')\n\n def get_ref_loc(self):\n '''Return the lat and long of the reference point in degrees'''\n lat = self.ref_ant.position.lat\n lon = self.ref_ant.position.long\n if lat[-1]=='N':\n mult=1\n lat=lat.rstrip('N')\n elif lat[-1]=='S':\n mult=-1\n lat=lat.rstrip('S')\n else:\n mult=1\n lat = lat.split(':')\n lat_degs=0.0\n for vn,val in enumerate(lat):\n lat_degs += ((float(val)/(60**vn)))\n if lon[-1]=='E':\n mult=1\n lon=lon.rstrip('E')\n elif lon[-1]=='W':\n mult=-1\n lon=lon.rstrip('W')\n else:\n mult=1\n lon = lon.split(':')\n lon_degs=0.0\n for vn,val in enumerate(lon):\n lon_degs += ((float(val)/(60**vn)))\n return [lat_degs,lon_degs]\n","sub_path":"poxy/scripts/sandbox/ant_array.py","file_name":"ant_array.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"28807654","text":"# 同步IO和异步IO\n# 第一种是CPU等着,也就是程序暂停执行后续代码,等100M的数据在10秒后写入磁盘,再接着往下执行,这种模式称为同步IO\n# 另一种方法是CPU不等待,只是告诉磁盘,“您老慢慢写,不着急,我接着干别的事去了”,于是,后续代码可以立刻接着执行,这种模式称为异步IO\n# 异步IO来编写程序性能会远远高于同步IO,但是异步IO的缺点是编程模型复杂\n# 回调模式和轮询模式\n\n\n# 1.文件读写\nf = open(\"D:/read.txt\", \"r\")\nprint(f.read())\n# 文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,\n# 并且操作系统同一时间能打开的文件数量也是有限的\nf.close()\n\n# with语句自动帮忙调用close方法\nwith open(\"D:/read.txt\", \"r\") as f2:\n print(f2.read())\n# 以上等同于\ntry:\n f = open(\"D:/read.txt\",\"r\")\n print(f.read())\nfinally:\n if f:\n f.close()\n# read会一次性读取全部内容\n# 如果文件很小,read()一次性读取最方便;\n# 如果不能确定文件大小,反复调用read(size)比较保险;\n# 如果是配置文件,调用readlines()最方便\nprint(\"****************\")\nf = open(\"D:/read.txt\", \"r\")\nfor line in f.readlines():\n print(line.strip())\nf.close()\n\n# 像open()函数返回的这种有个read()方法的对象,在Python中统称为file-like Object\n# 除了file外,还可以是内存的字节流,网络流,自定义流等等。\n# file-like Object不要求从特定类继承,只要写个read()方法就行。\n# StringIO就是在内存中创建的file-like Object,常用作临时缓冲\n\n# 二进制文件\nf = open(\"D:\\BACKUP\\projects\\AndroidTestDemo\\ic_launcher-web.png\", \"rb\")\nprint(f.readlines())\nf.close()\n# 编码\nf = open(\"D:/read.txt\", \"r\", encoding=\"gbk\")\nprint(f.read())\nf.close()\n\n# 写文件\nf = open(\"D:/read.txt\", \"w\")\nf.write(\"write txt\")\nf.close()\nprint(\"*****************\")\nf = open(\"D:/read.txt\", \"r\")\nprint(f.read())\n# 当我们写文件时,操作系统往往不会立刻把数据写入磁盘,\n# 而是放到内存缓存起来,空闲的时候再慢慢写入。\n# 只有调用close()方法时,操作系统才保证把没有写入的数据全部写入磁盘。\n# 忘记调用close()的后果是数据可能只写了一部分到磁盘,剩下的丢失了\n","sub_path":"weblearn/04fourthbasic/33IOprogram.py","file_name":"33IOprogram.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"165124520","text":"# make an index of feature vectors of every photo in a dataset\n# including all sub directories\n# the search uses that index to find images\n\n# python3 index.py\n# python3 index.py -d photos -i index.csv\n\nfrom imgsearch.colordescriptor import ColorDescriptor\nfrom imutils import paths\nimport argparse\nimport glob\nimport cv2\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", type=str, default=\"photos\")\nap.add_argument(\"-i\", \"--index\", type=str, default=\"index.csv\")\nargs = vars(ap.parse_args())\n\nimagePaths = paths.list_images(args[\"dataset\"])\ncd = ColorDescriptor((8, 12, 3))\noutput = open(args[\"index\"], \"w\")\n\nfor imagePath in imagePaths:\n\timageID = imagePath\n\timage = cv2.imread(imagePath)\n\tfeatures = cd.describe(image)\n\tfeatures = [str(f) for f in features]\n\toutput.write(\"%s,%s\\n\" % (imageID, \",\".join(features)))\n\tprint(imageID)\n\noutput.close()\n\n\n\n","sub_path":"Reverse Image Search/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"42191511","text":"#!/usr/bin/env python\n\n\"\"\"Test the gcode creating functions.\"\"\"\n\nimport StringIO\nimport numpy as np\n\nimport logging\nimport pytest\nfrom octoprint.util import dict_merge\nfrom octoprint_mrbeam.gcodegenerator import img2gcode\n\n# from os.path import dirname, basename, join, split, realpath\n\n\nclass TestG0Generation:\n def setup_method(self, method):\n \"\"\"Setup to allow each function to have a generic image processor.\"\"\"\n self.fh = StringIO.StringIO()\n\n # with open(\"/tmp/test_img2gcode.gco\", \"w\") as self.fh:\n self.ip = img2gcode.ImageProcessor(\n output_filehandle=self.fh,\n workingAreaWidth=500,\n workingAreaHeight=390,\n beam_diameter=0.1,\n backlash_x=0,\n overshoot_distance=1,\n intensity_black=999,\n intensity_white=111,\n intensity_black_user=77,\n intensity_white_user=11,\n speed_black=222,\n speed_white=1111,\n dithering=False,\n pierce_time=0,\n engraving_mode=img2gcode.ImageProcessor.ENGRAVING_MODE_PRECISE,\n extra_overshoot=True,\n eng_compressor=100,\n material=None,\n )\n\n # basics\n self.log = logging.getLogger()\n\n def teardown_method(self, method):\n self.fh.close()\n pass\n\n def test_get_gcode_g0(self):\n assert \"G0S0\" == self.ip._get_gcode_g0(x=None, y=None, comment=None)\n assert \"G0X0.00Y0.00S0\" == self.ip._get_gcode_g0(x=0, y=0, comment=None)\n assert \"G0Y1.00S0; Linefeed\" == self.ip._get_gcode_g0(\n x=None, y=1, comment=\"Linefeed\"\n )\n assert \"G0Y0.00S0; Ymax, Y set to 390, was 391\" == self.ip._get_gcode_g0(\n x=None, y=391, comment=\"Y>max\"\n )\n assert \"G0X0.00S0; Xmax, X set to 500, was 501\" == self.ip._get_gcode_g0(\n x=501, y=None, comment=\"X>max\"\n )\n with pytest.raises(ValueError) as exception:\n self.ip._get_gcode_g0(x=float(\"NaN\"), y=None, comment=None)\n assert \"Coordinate is NaN\" in str(exception.value)\n with pytest.raises(ValueError) as exception:\n self.ip._get_gcode_g0(x=None, y=float(\"NaN\"), comment=None)\n assert \"Coordinate is NaN\" in str(exception.value)\n\n def test_get_gcode_g1(self):\n assert \"G1X0.00Y0.00\" == self.ip._get_gcode_g1(\n x=0, y=0, s=None, f=None, comment=None\n )\n assert \"G1Y1.00; Linefeed\" == self.ip._get_gcode_g1(\n x=None, y=1, s=None, f=None, comment=\"Linefeed\"\n )\n assert \"G1Y0.00; Ymax, Y set to 390, was 391\" == self.ip._get_gcode_g1(\n x=None, y=391, s=None, f=None, comment=\"Y>max\"\n )\n assert \"G1X0.00; Xmax, X set to 500, was 501\" == self.ip._get_gcode_g1(\n x=501, y=None, s=None, f=None, comment=\"X>max\"\n )\n assert \"G1X1.00S100; Intensity\" == self.ip._get_gcode_g1(\n x=1, y=None, s=100, f=None, comment=\"Intensity\"\n )\n assert \"G1X1.00S0; Intensity<0, S set to 0, was -1\" == self.ip._get_gcode_g1(\n x=1, y=None, s=-1, f=None, comment=\"Intensity<0\"\n )\n assert (\n \"G1X1.00S1300; Intensity>max, S set to 1300, was 99999\"\n == self.ip._get_gcode_g1(\n x=1, y=None, s=99999, f=None, comment=\"Intensity>max\"\n )\n )\n\n with pytest.raises(ValueError) as exception:\n self.ip._get_gcode_g1(x=None, y=None, s=None, f=None, comment=None)\n assert \"GCode 'G1' at least requires one literal.\" in str(exception.value)\n\n with pytest.raises(ValueError) as exception:\n self.ip._get_gcode_g1(x=float(\"NaN\"), y=None, comment=None)\n assert \"Coordinate is NaN\" in str(exception.value)\n\n with pytest.raises(ValueError) as exception:\n self.ip._get_gcode_g1(x=None, y=float(\"NaN\"), comment=None)\n assert \"Coordinate is NaN\" in str(exception.value)\n\n def test_overshoot(self):\n for size in [0, 0.0, 1.123456, 30]:\n for dy in [0, 0.001, 0.5, 3, 50]:\n # for dx in [0, .001, .5, 3, 50]:\n dx = 0 # change when the overshoot can change with a higher dx\n self.ip.backlash_x = size\n start = np.array([2, 2])\n end = start + np.array([dx, dy])\n gc = self.ip.get_overshoot(start, end, 1, size, offset_counter=0)\n self.log.debug(\"{} - size {} -> {}\\n{}\".format(start, size, end, gc))\n assert \"nan\" not in gc.lower()\n # assert gc == \"foo\"\n\n def test_generate_gcode(self):\n from PIL import Image\n\n black10x3 = Image.new(\"L\", (10, 3), (0))\n imgArray = [{\"i\": black10x3, \"x\": 0, \"y\": 0, \"id\": \"black10x3\"}]\n xMM = 495\n yMM = 2.3\n wMM = 1\n hMM = 0.3\n file_id = \"generic black 10x3 px\"\n self.ip.generate_gcode(imgArray, xMM, yMM, wMM, hMM, file_id)\n gc = self.fh.getvalue()\n self.log.debug(\"\\n\" + gc)\n # assert gc == \"foo\"\n","sub_path":"tests/gcodegenerator/img2gcode/test_img2gcode.py","file_name":"test_img2gcode.py","file_ext":"py","file_size_in_byte":5633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"481193266","text":"class Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n ## dp bottom-up:f[i][j]表示三角形从底部走到(i,j)的最小路径\n # pro(i,j) is min length path of i,j. pro(i,j)=min(sub(i+1,j), sub(i+1, j+1))+a(i,j)\n a = triangle\n for i in range(len(a)-2, -1, -1):\n for j in range(i+1):\n a[i][j] += min(a[i+1][j], a[i+1][j+1])\n print(a)\n \n return a[0][0]\n \n \n ## dp top-down","sub_path":"Week_06/120 triangle.py","file_name":"120 triangle.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"301335505","text":"import collections\n\n# Deprecated\n\ndef chunks(iter, n):\n arr = []\n for x in iter:\n arr.append(x)\n if len(arr) == n:\n yield arr\n arr = []\n \n if arr: yield arr\n\ndef group(arr, fn):\n res = collections.defaultdict(list)\n\n for ob in arr:\n res[fn(ob)].append(ob)\n \n return list(res.values())\n\ndef counts(arr):\n res = collections.defaultdict(int)\n\n for ob in arr:\n res[ob] += 1\n \n return res\n\ndef listify(x):\n if isinstance(x, str): return x\n\n ret = []\n for v in x:\n if isinstance(v, (str, list, tuple, dict)):\n ret.append(v)\n continue\n\n try:\n ret.append(listify(iter(v)))\n except TypeError:\n ret.append(v)\n \n return ret\n\n\n# orders by fn(x), allows computation, and then converts to original order\nclass Reorderer:\n def __init__(self, arr, fn):\n self.size = len(arr)\n arr = list(enumerate(arr))\n arr = group(arr, lambda x: fn(x[1]))\n arr = [\n ([y[0] for y in x], x[0][1]) for x in arr\n ]\n arr.sort(key=lambda x: fn(x[1]))\n\n self.arr = arr\n \n \n def get_reordered(self):\n return [x[1] for x in self.arr]\n \n def get_original(self, newarr):\n res = [None] * self.size\n cov = [False] * self.size\n\n for (inds, _), v in zip(self.arr, newarr):\n for ind in inds: \n res[ind] = v\n cov[ind] = True\n \n assert all(cov)\n \n return res\n\n","sub_path":"pyfra/functional/iterators.py","file_name":"iterators.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"360400301","text":"os.chdir(\"Y:\\WORK\\WAPLES\\Stacks_mapping\\Python\")\n\nimport cPickle as pickle\nimport numpy\n\nimport Stacks_SQL_class\nfrom models_to_test import models_to_test\n\n\n\n# Load data created with export_sql.pl \n\nmykiss_fams = Stacks_SQL_class.Stacks_SQL(path = \"Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_fams_RW_v2.txt\", \n name = 'chum',\n num_parents = 14, \n num_offspring = 497, \n parent_offspring = (77, 75, 78, 19, 40, 20, 20, 20, 18, 18, 30, 33, 43, 6)\n )\n \n# Add TaqMan Data\n#chum_fams.add_external_genotypes(filepath = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/genotypes/taqMan_01H.tsv\", parent = 'CMUW10X_0001')\n#chum_fams.add_external_genotypes(filepath = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/genotypes/taqMan_08H.tsv\", parent = 'CMUW10X_0008')\n#chum_fams.add_external_genotypes(filepath = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/genotypes/taqMan_09H.tsv\", parent = 'CMUW10X_0009')\n\n# Kick out Loci (within families) with too many missing genotypes\ntoo_many_missing_01 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_1')\ntoo_many_missing_02 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_2')\ntoo_many_missing_03 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_3')\ntoo_many_missing_04 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_4')\ntoo_many_missing_05 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_5')\ntoo_many_missing_06 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_6')\ntoo_many_missing_07 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_7')\ntoo_many_missing_08 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_8')\ntoo_many_missing_09 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_9')\ntoo_many_missing_10 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_10')\ntoo_many_missing_11 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_11')\ntoo_many_missing_12 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_12')\ntoo_many_missing_13 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_13')\ntoo_many_missing_14 = mykiss_fams.remove_missing_within_cross(max_miss = .25, parent = 'parent_14')\n\n\n# Kick out loci (within families) with too many alleles\n#too_many_alleles_01 = chum_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'CMUW10X_0001')\ntoo_many_alleles_01 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_1')\ntoo_many_alleles_02 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_2')\ntoo_many_alleles_03 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_3')\ntoo_many_alleles_04 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_4')\ntoo_many_alleles_05 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_5')\ntoo_many_alleles_06 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_6')\ntoo_many_alleles_07 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_7')\ntoo_many_alleles_08 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_8')\ntoo_many_alleles_09 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_9')\ntoo_many_alleles_10 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_10')\ntoo_many_alleles_11 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_11')\ntoo_many_alleles_12 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_12')\ntoo_many_alleles_13 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_13')\ntoo_many_alleles_14 = mykiss_fams.remove_max_alleles_within_cross(max_alleles = 4, parent = 'parent_14')\n\n# Purge CatIDs that failed previous tests in all families\npurged = mykiss_fams.purge_absent_catIDs()\n\n# Calculate model results using models found in in \"models_to_test.py\"\nprint(\"Calculating PSV Model Likelihoods\")\nmykiss_fams.set_model_results(to_test = models_to_test, epsilon_bound_high = 0.1, epsilon_bound_low = 0.01)\n\n\n## STOPPED HERE 4/18/2014\n## We may want to exclude certain individuals and re-run the above analyses\n\n#mappable_01, stats_01 = chum_fams.find_mappable_markers(parent = 'CMUW10X_0001', models_to_test = models_to_test)\nmappable_01, stats_01 = mykiss_fams.find_mappable_markers(parent = 'parent_1', models_to_test = models_to_test)\nmappable_02, stats_02 = mykiss_fams.find_mappable_markers(parent = 'parent_2', models_to_test = models_to_test)\nmappable_03, stats_03 = mykiss_fams.find_mappable_markers(parent = 'parent_3', models_to_test = models_to_test)\nmappable_04, stats_04 = mykiss_fams.find_mappable_markers(parent = 'parent_4', models_to_test = models_to_test)\nmappable_05, stats_05 = mykiss_fams.find_mappable_markers(parent = 'parent_5', models_to_test = models_to_test)\nmappable_06, stats_06 = mykiss_fams.find_mappable_markers(parent = 'parent_6', models_to_test = models_to_test)\nmappable_07, stats_07 = mykiss_fams.find_mappable_markers(parent = 'parent_7', models_to_test = models_to_test)\nmappable_08, stats_08 = mykiss_fams.find_mappable_markers(parent = 'parent_8', models_to_test = models_to_test)\nmappable_09, stats_09 = mykiss_fams.find_mappable_markers(parent = 'parent_9', models_to_test = models_to_test)\nmappable_10, stats_10 = mykiss_fams.find_mappable_markers(parent = 'parent_10', models_to_test = models_to_test)\nmappable_11, stats_11 = mykiss_fams.find_mappable_markers(parent = 'parent_11', models_to_test = models_to_test)\nmappable_12, stats_12 = mykiss_fams.find_mappable_markers(parent = 'parent_12', models_to_test = models_to_test)\nmappable_13, stats_13 = mykiss_fams.find_mappable_markers(parent = 'parent_13', models_to_test = models_to_test)\nmappable_14, stats_14 = mykiss_fams.find_mappable_markers(parent = 'parent_14', models_to_test = models_to_test)\n\ndef write_stats(filename, stats):\n with open(filename, 'w') as OUTFILE:\n for catID, values in stats.items():\n OUTFILE.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(\n catID, \n values.epsilon,\n values.best_model,\n values.best_likelihood,\n values.second_best_model,\n values.second_best_likelihood,\n values.x1_seg_pval,\n values.x2_seg_pval\n )\n )\n#from psv_working import stats_08\n#write_stats('/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/psv/chum_01.stats', stats_01)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_01.stats', stats_01)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_02.stats', stats_02)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_03.stats', stats_03)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_04.stats', stats_04)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_05.stats', stats_05)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_06.stats', stats_06)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_07.stats', stats_07)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_08.stats', stats_08)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_09.stats', stats_09)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_10.stats', stats_10)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_11.stats', stats_11)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_12.stats', stats_12)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_13.stats', stats_13)\nwrite_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_14.stats', stats_14)\n\n# Conduct filtering on loci and catIDs\n# Kick out failed loci\n# segregation testing\nimport mne\nimport collections\ndef filter_mappable_segregation(stats, alpha = .05):\n stats_of_locus = dict()\n loci = list()\n raw_p_vals = list()\n for catID in stats:\n if stats[catID].x1_seg_pval == \"NA\":\n pass\n else:\n raw_p_vals.append(stats[catID].x1_seg_pval)\n loci.append(catID + \"_x1\")\n if stats[catID].x2_seg_pval == \"NA\":\n pass\n else:\n raw_p_vals.append(stats[catID].x2_seg_pval)\n loci.append(catID + \"_x2\")\n reject, pval_corrected = mne.stats.fdr_correction(pvals = raw_p_vals, alpha = alpha, method = 'indep')\n seg_test_fdr = collections.namedtuple('seg_test_fdr', ['reject', 'pval_corrected', 'pval_raw'])\n for locus, rej, pvc, pvr in zip(loci, reject, pval_corrected, raw_p_vals):\n stats_of_locus[locus] = seg_test_fdr(rej, pvc, pvr)\n return(stats_of_locus)\n# do segregation testing with FDR \n\n\nseg_test_01 = filter_mappable_segregation(stats_01, alpha = 0.05)\nseg_test_02 = filter_mappable_segregation(stats_02, alpha = 0.05)\nseg_test_03 = filter_mappable_segregation(stats_03, alpha = 0.05)\nseg_test_04 = filter_mappable_segregation(stats_04, alpha = 0.05)\nseg_test_05 = filter_mappable_segregation(stats_05, alpha = 0.05)\nseg_test_06 = filter_mappable_segregation(stats_06, alpha = 0.05)\nseg_test_07 = filter_mappable_segregation(stats_07, alpha = 0.05)\nseg_test_08 = filter_mappable_segregation(stats_08, alpha = 0.05)\nseg_test_09 = filter_mappable_segregation(stats_09, alpha = 0.05)\nseg_test_10 = filter_mappable_segregation(stats_10, alpha = 0.05)\nseg_test_11 = filter_mappable_segregation(stats_11, alpha = 0.05)\nseg_test_12 = filter_mappable_segregation(stats_12, alpha = 0.05)\nseg_test_13 = filter_mappable_segregation(stats_13, alpha = 0.05)\nseg_test_14 = filter_mappable_segregation(stats_14, alpha = 0.05)\n\n\n# Print how many *would be* excluded\nprint(\"Reject {} out of {} loci in fam_01\".format(sum([x.reject for x in seg_test_01.values()]), len([x.reject for x in seg_test_01.values()])))\nprint(\"Reject {} out of {} loci in fam_08\".format(sum([x.reject for x in seg_test_08.values()]), len([x.reject for x in seg_test_08.values()])))\nprint(\"Reject {} out of {} loci in fam_09\".format(sum([x.reject for x in seg_test_09.values()]), len([x.reject for x in seg_test_09.values()])))\n\nfailed_seg_test_01 = [k for k,v in seg_test_01.items() if v.reject]\nfailed_seg_test_02 = [k for k,v in seg_test_02.items() if v.reject]\nfailed_seg_test_03 = [k for k,v in seg_test_03.items() if v.reject]\nfailed_seg_test_04 = [k for k,v in seg_test_04.items() if v.reject]\nfailed_seg_test_05 = [k for k,v in seg_test_05.items() if v.reject]\nfailed_seg_test_06 = [k for k,v in seg_test_06.items() if v.reject]\nfailed_seg_test_07 = [k for k,v in seg_test_07.items() if v.reject]\nfailed_seg_test_08 = [k for k,v in seg_test_08.items() if v.reject]\nfailed_seg_test_09 = [k for k,v in seg_test_09.items() if v.reject]\nfailed_seg_test_10 = [k for k,v in seg_test_10.items() if v.reject]\nfailed_seg_test_11 = [k for k,v in seg_test_11.items() if v.reject]\nfailed_seg_test_12 = [k for k,v in seg_test_12.items() if v.reject]\nfailed_seg_test_13 = [k for k,v in seg_test_13.items() if v.reject]\nfailed_seg_test_14 = [k for k,v in seg_test_14.items() if v.reject]\n\n# Epsilon\n#hist([x.epsilon for x in stats_01.values()])\n#hist([x.epsilon for x in stats_08.values()])\n#hist([x.epsilon for x in stats_09.values()])\n\nfailed_epsilon_test_01 = [k for k,v in stats_01.items() if v.epsilon > .2]\nfailed_epsilon_test_02 = [k for k,v in stats_02.items() if v.epsilon > .2]\nfailed_epsilon_test_03 = [k for k,v in stats_03.items() if v.epsilon > .2]\nfailed_epsilon_test_04 = [k for k,v in stats_05.items() if v.epsilon > .2]\nfailed_epsilon_test_05 = [k for k,v in stats_05.items() if v.epsilon > .2]\nfailed_epsilon_test_06 = [k for k,v in stats_06.items() if v.epsilon > .2]\nfailed_epsilon_test_07 = [k for k,v in stats_07.items() if v.epsilon > .2]\nfailed_epsilon_test_08 = [k for k,v in stats_08.items() if v.epsilon > .2]\nfailed_epsilon_test_09 = [k for k,v in stats_09.items() if v.epsilon > .2] \nfailed_epsilon_test_10 = [k for k,v in stats_10.items() if v.epsilon > .2]\nfailed_epsilon_test_11 = [k for k,v in stats_11.items() if v.epsilon > .2]\nfailed_epsilon_test_12 = [k for k,v in stats_12.items() if v.epsilon > .2] \nfailed_epsilon_test_13 = [k for k,v in stats_13.items() if v.epsilon > .2]\nfailed_epsilon_test_14 = [k for k,v in stats_14.items() if v.epsilon > .2]\n\n# What is going on with 'Oke_ROA1-209', is family_01??\n\n# missingness per locus\n#miss_stats_01 = zip(mappable_01.keys(), [xx.count('-')/float(len(xx)) for xx in mappable_01.values()])\n#miss_stats_08 = zip(mappable_08.keys(), [xx.count('-')/float(len(xx)) for xx in mappable_08.values()])\n#miss_stats_09 = zip(mappable_09.keys(), [xx.count('-')/float(len(xx)) for xx in mappable_09.values()])\n\n\n#hist([y for x,y in miss_stats_01])\n#hist([y for x,y in miss_stats_08])\n#hist([y for x,y in miss_stats_09])\n\nfailed_missing_test_01 = [k for k,v in mappable_01.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_02 = [k for k,v in mappable_02.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_03 = [k for k,v in mappable_03.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_04 = [k for k,v in mappable_04.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_05 = [k for k,v in mappable_05.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_06 = [k for k,v in mappable_06.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_07 = [k for k,v in mappable_07.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_08 = [k for k,v in mappable_08.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_09 = [k for k,v in mappable_09.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_10 = [k for k,v in mappable_10.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_11 = [k for k,v in mappable_11.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_12 = [k for k,v in mappable_12.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_13 = [k for k,v in mappable_13.items() if v.count('-')/float(len(v)) > .25]\nfailed_missing_test_14 = [k for k,v in mappable_14.items() if v.count('-')/float(len(v)) > .25]\n\n\n\n\ndef remove_locus(mappable, locus):\n if locus in mappable:\n del mappable[locus]\n return(1)\n else:\n return(0)\n \ndef remove_catID(mappable, catID):\n removed_count = 0\n if catID+\"_x1\" in mappable:\n del mappable[ catID+\"_x1\"]\n removed_count +=1\n if catID+\"_x2\" in mappable:\n del mappable[ catID+\"_x2\"]\n removed_count +=1\n return(removed_count)\n\ndef remove_catIDs(mappable, catIDs):\n num_removed = 0\n for catID in catIDs:\n num_removed += remove_catID(mappable, catID)\n print(\"Removed {} loci\".format(num_removed))\n \ndef remove_loci(mappable, loci):\n num_removed = 0\n for locus in loci:\n num_removed += remove_locus(mappable, locus)\n print(\"Removed {} loci\".format(num_removed)) \n \n \nremove_catIDs(mappable_01, failed_epsilon_test_01)\nremove_catIDs(mappable_02, failed_epsilon_test_02)\nremove_catIDs(mappable_03, failed_epsilon_test_03)\nremove_catIDs(mappable_04, failed_epsilon_test_04)\nremove_catIDs(mappable_05, failed_epsilon_test_05)\nremove_catIDs(mappable_06, failed_epsilon_test_06)\nremove_catIDs(mappable_07, failed_epsilon_test_07)\nremove_catIDs(mappable_08, failed_epsilon_test_08)\nremove_catIDs(mappable_09, failed_epsilon_test_09)\nremove_catIDs(mappable_10, failed_epsilon_test_10)\nremove_catIDs(mappable_11, failed_epsilon_test_11)\nremove_catIDs(mappable_12, failed_epsilon_test_12)\nremove_catIDs(mappable_13, failed_epsilon_test_13)\nremove_catIDs(mappable_14, failed_epsilon_test_14)\n\nremove_catIDs(mappable_01, failed_missing_test_01)\nremove_catIDs(mappable_02, failed_missing_test_02)\nremove_catIDs(mappable_03, failed_missing_test_03)\nremove_catIDs(mappable_04, failed_missing_test_04)\nremove_catIDs(mappable_05, failed_missing_test_05)\nremove_catIDs(mappable_06, failed_missing_test_06)\nremove_catIDs(mappable_07, failed_missing_test_07)\nremove_catIDs(mappable_08, failed_missing_test_08)\nremove_catIDs(mappable_09, failed_missing_test_09)\nremove_catIDs(mappable_10, failed_missing_test_10)\nremove_catIDs(mappable_11, failed_missing_test_11)\nremove_catIDs(mappable_12, failed_missing_test_12)\nremove_catIDs(mappable_13, failed_missing_test_13)\nremove_catIDs(mappable_14, failed_missing_test_14)\n\nremove_catIDs(mappable_01, failed_seg_test_01)\nremove_catIDs(mappable_02, failed_seg_test_02)\nremove_catIDs(mappable_03, failed_seg_test_03)\nremove_catIDs(mappable_04, failed_seg_test_04)\nremove_catIDs(mappable_05, failed_seg_test_05)\nremove_catIDs(mappable_06, failed_seg_test_06)\nremove_catIDs(mappable_07, failed_seg_test_07)\nremove_catIDs(mappable_08, failed_seg_test_08)\nremove_catIDs(mappable_09, failed_seg_test_09)\nremove_catIDs(mappable_10, failed_seg_test_10)\nremove_catIDs(mappable_11, failed_seg_test_11)\nremove_catIDs(mappable_12, failed_seg_test_12)\nremove_catIDs(mappable_13, failed_seg_test_13)\nremove_catIDs(mappable_14, failed_seg_test_14)\n\ndef write_mappable_stats(filename, stats, mappable):\n with open(filename, 'w') as OUTFILE:\n for catID, values in stats.items():\n locally_mappable = sum((catID+\"_x1\" in mappable, catID+\"_x2\" in mappable))\n OUTFILE.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(\n \n )\n )\n\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_01.stats', stats_01, mappable_01)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_02.stats', stats_02, mappable_02)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_03.stats', stats_03, mappable_03)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_04.stats', stats_04, mappable_04)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_05.stats', stats_05, mappable_05)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_06.stats', stats_06, mappable_06)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_07.stats', stats_07, mappable_07)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_08.stats', stats_08, mappable_08)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_09.stats', stats_09, mappable_09)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_10.stats', stats_10, mappable_10)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_11.stats', stats_11, mappable_11)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_12.stats', stats_12, mappable_12)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_13.stats', stats_13, mappable_13)\nwrite_mappable_stats('Y:/DATA/PROJECTS/MYKISS/OmykissDomestication/mykiss_14.stats', stats_14, mappable_14)\n\n# TODO\n# Could also filter for difference in likelihoods.\n\n# Write loci to MSTmap format\nchum_fams.write_mstmap('CMUW10X_0001', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/mst/chum_01_mstmap.txt', mappable_01)\nchum_fams.write_mstmap('CMUW10X_0008', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/mst/chum_08_mstmap.txt', mappable_08)\nchum_fams.write_mstmap('CMUW10X_0009', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/mst/chum_09_mstmap.txt', mappable_09)\n\n# Set inital map\nchum_fams.set_map(parent = 'CMUW10X_0001', mappable_loci = mappable_01, source_file = None, source_format = None)\nchum_fams.set_map(parent = 'CMUW10X_0008', mappable_loci = mappable_08, source_file = None, source_format = None)\nchum_fams.set_map(parent = 'CMUW10X_0009', mappable_loci = mappable_09, source_file = None, source_format = None)\n\n# Write loci to Rqtl format\nchum_fams.write_Rqtl('CMUW10X_0001', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/rqtl/chum_01_Rqtl.txt', mappable_01)\nchum_fams.write_Rqtl('CMUW10X_0008', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/rqtl/chum_08_Rqtl.txt', mappable_08)\nchum_fams.write_Rqtl('CMUW10X_0009', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/rqtl/chum_09_Rqtl.txt', mappable_09)\n\n\n# pickle 'chum_fams' here, as very costly to generate\nchum_fams_pickle_file = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/pkl/chum_fams.pkl\"\nwith open(chum_fams_pickle_file, 'wb') as OUTFILE:\n pickle.dump(chum_fams, OUTFILE)\n\nmap_01_pickle_file = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/pkl/mappable_01.pkl\"\nwith open(map_01_pickle_file, 'wb') as OUTFILE:\n pickle.dump(mappable_01, OUTFILE)\n \nmap_08_pickle_file = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/pkl/mappable_08.pkl\"\nwith open(map_08_pickle_file, 'wb') as OUTFILE:\n pickle.dump(mappable_08, OUTFILE)\n \nmap_09_pickle_file =\"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/pkl/mappable_09.pkl\"\nwith open(map_09_pickle_file, 'wb') as OUTFILE:\n pickle.dump(mappable_09, OUTFILE)\n \n## Can't pickle stats_0X files because of namedTuple \n#map_01_stats_pickle_file = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/pkl/stats_01.pkl\"\n#with open(map_01_stats_pickle_file, 'wb') as OUTFILE:\n# pickle.dump(stats_01, OUTFILE)\n# \n#map_08_stats_pickle_file = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/pkl/stats_08.pkl\"\n#with open(map_08_stats_pickle_file, 'wb') as OUTFILE:\n# pickle.dump(stats_08, OUTFILE)\n# \n#map_09_stats_pickle_file = \"/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/pkl/stats_09.pkl\"\n#with open(map_09_stats_pickle_file, 'wb') as OUTFILE:\n# pickle.dump(stats_09, OUTFILE)\n \n##Load Pickle \nINFILE = open(chum_fams_pickle_file, 'rb')\nchum_fams = pickle.load(INFILE)\nINFILE.close() \n\n\n \n\n########################\n\n\nfrac_missing = numpy.array([xx.count('-')/float(len(xx)) for xx in mappable_08.values()])\nfrac_pass = frac_missing > .25\n[miss_stats[xx] if frac_pass[xx] else None for xx in range(len(frac_missing))]\n# Perhaps the code that evaluates which splits catIDs could be made more tolerant, so that one could 'split' into one genotype rather than two\n\n# Print how many *would be* excluded\nprint(\"Reject {} out of {} loci in fam_01\".format(numpy.sum(numpy.array([xx.count('-')/float(len(xx)) for xx in mappable_01.values()]) > 0.25), len(mappable_01)))\nprint(\"Reject {} out of {} loci in fam_08\".format(numpy.sum(numpy.array([xx.count('-')/float(len(xx)) for xx in mappable_08.values()]) > 0.25), len(mappable_08)))\nprint(\"Reject {} out of {} loci in fam_09\".format(numpy.sum(numpy.array([xx.count('-')/float(len(xx)) for xx in mappable_09.values()]) > 0.25), len(mappable_09)))\n \n# Write loci to MSTmap format\nchum_fams.write_mstmap('CMUW10X_0001', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/mst/chum_01_mstmap.txt', mappable_01)\nchum_fams.write_mstmap('CMUW10X_0008', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/mst/chum_08_mstmap.txt', mappable_08)\nchum_fams.write_mstmap('CMUW10X_0009', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/mst/chum_09_mstmap.txt', mappable_09)\n\n\n\n\n\n# Set inital map\nchum_fams.set_map(parent = 'CMUW10X_0001', mappable_loci = mappable_01, source_file = None, source_format = None)\nchum_fams.set_map(parent = 'CMUW10X_0008', mappable_loci = mappable_08, source_file = None, source_format = None)\nchum_fams.set_map(parent = 'CMUW10X_0009', mappable_loci = mappable_09, source_file = None, source_format = None)\n\n# Write loci to Rqtl format\nchum_fams.write_Rqtl('CMUW10X_0001', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/rqtl/chum_01_Rqtl.txt', mappable_01)\nchum_fams.write_Rqtl('CMUW10X_0008', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/rqtl/chum_08_Rqtl.txt', mappable_08)\nchum_fams.write_Rqtl('CMUW10X_0009', '/olympus/WORK/WAPLES/Stacks_mapping/Chum_data/rqtl/chum_09_Rqtl.txt', mappable_09)\n\n\n#chum fams\nchum_fams_pickle_file = \"Z:/HOME/Waples/Stacks_mapping/Chum_data/pkl/chum_fams.pkl\"\nwith open(chum_fams_pickle_file, 'wb') as OUTFILE:\n pickle.dump(chum_fams, OUTFILE)\n\n#mappable loci\n\n\n\n\n\n\n\n\n\n#\n#\n#mapped_08 = dict()\n#for key, value in mappable_08[0].items():\n# mapped_08[key] = value\n#for key, value in mappable_08[1].items():\n# mapped_08[key] = value\n# \n##mapped_08 = dict()\n##for key, value in switched_mappable_08[0].items():\n## mapped_08[key] = value\n##for key, value in switched_mappable_08[1].items():\n## mapped_08[key] = value \n#\n# \n##take a map, and examine RF and lod across LGs,\n## here i take rqtl map, TODO:use mst map output\n#ini_map_filename = \"Z:/HOME/Waples/Stacks_mapping/Chum_data/rqtl/chum08_ini_map.tsv\"\n##ini_map_filename = \"Z:/HOME/Waples/Stacks_mapping/Chum_data/rqtl/chum08_switched1_map.tsv\"\n#loci = list()\n#lgs = list()\n#loci_on_lg = collections.OrderedDict()\n#positions = list() \n#with open (ini_map_filename, 'r') as INFILE:\n# for line in INFILE:\n# locus, lg, pos = line.strip().split()\n# loci.append(locus)\n# lgs.append(lg)\n# if lg in loci_on_lg:\n# loci_on_lg[lg] = loci_on_lg[lg]+1\n# else:\n# loci_on_lg[lg] = 1\n# positions.append(pos)\n#ini_map = zip(loci, lgs, positions)\n#\n#mapped_genotypes = list()\n#for locus_tuple in ini_map:\n# locus_name = locus_tuple[0]\n# mapped_genotypes.append(mapped_08[locus_name]) #nested list\n# \n#geno_arr = numpy.array(mapped_genotypes)\n#my_a = numpy.where(geno_arr == 'a')\n#my_b = numpy.where(geno_arr == 'b')\n#my_m = numpy.where(geno_arr == '-')\n#int_arr = numpy.empty(shape = (geno_arr.shape), dtype = numpy.int)\n#int_arr[my_a] = 1 # allele 1\n#int_arr[my_b] = 2 # allele 2\n#int_arr[my_m] = 0 # missing\n# \n#pairs = itertools.combinations(int_arr, 2)\n#\n#def getR(pairs):\n# for x, y in pairs:\n# mult = x * y\n# yield sum(mult == 2)\n# \n#def getNR(pairs):\n# for x, y in pairs:\n# mult = x * y\n# yield (sum(mult == 1) + sum(mult == 4))\n# \n#def getM(pairs):\n# for x, y in pairs:\n# mult = x * y\n# yield (sum(mult == 0))\n#\n#pairs = itertools.combinations(int_arr, 2)\n## recombinants\n#R = numpy.fromiter(getR(pairs), dtype = numpy.float)\n#pairs = itertools.combinations(int_arr, 2)\n## non-recombinants\n#NR = numpy.fromiter(getNR(pairs), dtype =numpy.float)\n#pairs = itertools.combinations(int_arr, 2)\n## missing\n#M = numpy.fromiter(getM(pairs), dtype =numpy.float)\n#\n## R_frac\n#ml_R_frac = R / (R + NR)\n#\n## lod score\n#Z = log10(\n# (power((1-ml_R_frac), NR) * power(ml_R_frac, R)) / power(.5, (R + NR))\n# )\n#\n##scipy.spatial.distance.squareform(M)\n#rf = scipy.spatial.distance.squareform(ml_R_frac)\n#numpy.fill_diagonal(rf, np.nan)\n#\n#lod = scipy.spatial.distance.squareform(Z)\n#numpy.fill_diagonal(lod, np.nan)\n#\n## to get the mean of a region:\n## scipy.stats.nanmean(array_slice.flatten())\n#\n#\n#index_of_lg = collections.OrderedDict()\n#index = 0\n#for lg, num_loci in loci_on_lg.items():\n# start = index\n# stop = start + num_loci\n# index = stop\n# index_of_lg[lg] = start, stop\n# print lg, start, stop \n#\n# \n#def get_mean(pairs, array):\n# for x, y in pairs:\n# lg_a_start = index_of_lg[x][0]\n# lg_a_stop = index_of_lg[x][1]\n# lg_b_start = index_of_lg[y][0]\n# lg_b_stop = index_of_lg[y][1]\n# mean = numpy.mean(array[lg_a_start:lg_a_stop, lg_b_start:lg_b_stop].flatten())\n# yield (mean)\n# \n#def get_sum(pairs, array):\n# for x, y in pairs:\n# lg_a_start = index_of_lg[x][0]\n# lg_a_stop = index_of_lg[x][1]\n# lg_b_start = index_of_lg[y][0]\n# lg_b_stop = index_of_lg[y][1]\n# my_sum = numpy.sum(array[lg_a_start:lg_a_stop, lg_b_start:lg_b_stop].flatten())\n# yield (my_sum) \n# \n# \n#ordered_lgs = index_of_lg.keys()\n#lgs_longer_than_1 = list()\n#for xx in ordered_lgs:\n# if loci_on_lg[xx] > 1:\n# lgs_longer_than_1.append(xx)\n#\n## all lgs\n##pairs_of_lgs = itertools.combinations(ordered_lgs, 2) \n##mean_rf = numpy.fromiter(get_mean(pairs_of_lgs, rf), dtype = numpy.float)\n##pairs_of_lgs = itertools.combinations(ordered_lgs, 2)\n##mean_lod = numpy.fromiter(get_mean(pairs_of_lgs, lod), dtype = numpy.float)\n##pairs_of_lgs = itertools.combinations(ordered_lgs, 2)\n##sum_lod = numpy.fromiter(get_sum(pairs_of_lgs, lod), dtype = numpy.float)\n#\n##lgs with more than 1 locus\n#pairs_of_lgs = itertools.combinations(lgs_longer_than_1, 2) \n#mean_rf = numpy.fromiter(get_mean(pairs_of_lgs, rf), dtype = numpy.float)\n#pairs_of_lgs = itertools.combinations(lgs_longer_than_1, 2)\n#mean_lod = numpy.fromiter(get_mean(pairs_of_lgs, lod), dtype = numpy.float)\n#pairs_of_lgs = itertools.combinations(lgs_longer_than_1, 2)\n#sum_lod = numpy.fromiter(get_sum(pairs_of_lgs, lod), dtype = numpy.float)\n#\n##change to square_matrix\n#sq_sum_lod = scipy.spatial.distance.squareform(sum_lod)\n#upper_tri = numpy.triu_indices(len(lgs_longer_than_1))\n#sq_sum_lod[upper_tri] = 0\n#\n#where_pairs = numpy.where(sq_sum_lod>15000)\n#\n# \n# \n#\n##Select LG that appears in most switched pairs, if tied pick one\n## Add that LG to switch list\n## remove all pairs contianing that LG from the initial list\n## repeat until no pairs remain, return switch list\n#\n#def find_LGs_to_switch(where_pairs):\n# matched_pairs = zip(*where_pairs)\n# LGs_to_switch = list()\n# while len(matched_pairs) > 0:\n# count_switched = collections.defaultdict(int)\n# for ii, jj in matched_pairs:\n# count_switched[ii] += 1\n# count_switched[jj] += 1\n# sorted_switched = sorted(count_switched.items(),key=operator.itemgetter(1), reverse = True)\n# most_common_LG = sorted_switched.pop()[0]\n# LGs_to_switch.append(most_common_LG)\n# to_remove = list()\n# for index in range(len(matched_pairs)):\n# xx, yy = matched_pairs[index]\n# if most_common_LG == xx or most_common_LG == yy:\n# to_remove.append((xx, yy))\n# for ii in to_remove: \n# matched_pairs.remove(ii)\n# return(LGs_to_switch)\n# \n#LGs_to_switch = find_LGs_to_switch(where_pairs)\n#\n## Now to turn this list of LGs into a a list of locus names\n#list_of_loci_on_LG = collections.defaultdict(list) \n#for locus, LG, pos in ini_map:\n# #convert to int\n# LG = int(LG)\n# list_of_loci_on_LG[LG].append(locus)\n# \n#loci_to_switch = list()\n#for LG in LGs_to_switch:\n# loci_to_switch += list_of_loci_on_LG[LG]\n# \n#loci_to_switch \n# \n# \n#def switch_alleles(loci_to_switch, mappable):\n# x1, x2 = mappable\n# for jj in loci_to_switch:\n# if jj in x1:\n# original_genotypes = x1[jj]\n# switched_genotpyes = ['a' if xx is 'b' else 'b' if xx is 'a' else xx for xx in original_genotypes]\n# x1[jj] = switched_genotpyes\n# for jj in loci_to_switch:\n# if jj in x2:\n# original_genotypes = x2[jj]\n# switched_genotpyes = ['a' if xx is 'b' else 'b' if xx is 'a' else xx for xx in original_genotypes]\n# x2[jj] = switched_genotpyes\n# return(x1, x2)\n#\n#switched_mappable_08 = switch_alleles(loci_to_switch, mappable_08)\n# \n#chum_fams.write_Rqtl('CMUW10X_0008', 'Z:/HOME/Waples/Stacks_mapping/Chum_data/psv/chum_08_switched_Rqtl.txt', switched_mappable_08[0], switched_mappable_08[1])\n#chum_fams.write_mstmap('CMUW10X_0008', 'Z:/HOME/Waples/Stacks_mapping/Chum_data/psv/chum_08_switched_mstmap.txt', switched_mappable_08[0], switched_mappable_08[1])\n# \n# \n# \n# \n#len(find_LGs_to_switch(where_pairs))\n#\n#\n#\n#print(len(find_LGs_to_switch(where_pairs, False)))\n#\n#\n#\n#\n#selected_pairs = zip(*numpy.where(sq_sum_lod>10000))\n#for \n#\n#\n#\n#\n#\n#\n#max(sum_lod)\n#min(sum_lod)\n#numpy.where(sum_lod>1000)\n#\n#scatter(mean_rf, sum_lod)\n# \n#scipy.spatial.distance.squareform(sum_lod)\n#\n#\n#################### \n#\n# \n# \n# \n#\n#\n##get pairwise R fraction\n#mapr = mapped_08[0].values() # just singly mappable loci for now\n##nl = [[ii for ii in xx] for xx in mapr.values()]\n#\n#my_arr = numpy.array(mapr)\n#my_a = numpy.where(my_arr == 'a')\n#my_b = numpy.where(my_arr == 'b')\n#my_m = numpy.where(my_arr == '-')\n#int_arr = numpy.empty(shape = (my_arr.shape), dtype = numpy.int)\n#int_arr[my_a] = 1 # allele 1\n#int_arr[my_b] = 2 # allele 2\n#int_arr[my_m] = 0 # missing\n#\n## remove values where all missing, should likely be done earlier\n#aa = numpy.array([sum(x)> 0 for x in int_arr])\n#cleaned_arr = int_arr[aa]\n#\n#\n#pairs = itertools.combinations(cleaned_arr, 2)\n#\n#def getR(pairs):\n# for x, y in pairs:\n# mult = x * y\n# yield sum(mult == 2)\n# \n#def getNR(pairs):\n# for x, y in pairs:\n# mult = x * y\n# yield (sum(mult == 1) + sum(mult == 4))\n# \n#def getM(pairs):\n# for x, y in pairs:\n# mult = x * y\n# yield (sum(mult == 0))\n#\n#pairs = itertools.combinations(cleaned_arr, 2)\n## recombinants\n#R = numpy.fromiter(getR(pairs), dtype = numpy.float)\n#pairs = itertools.combinations(cleaned_arr, 2)\n## non-recombinants\n#NR = numpy.fromiter(getNR(pairs), dtype =numpy.float)\n#pairs = itertools.combinations(cleaned_arr, 2)\n## missing\n#M = numpy.fromiter(getM(pairs), dtype =numpy.float)\n#\n#ml_R_frac = R / (R + NR)\n#\n#Z = log10(\n# (power((1-ml_R_frac), NR) * power(ml_R_frac, R)) / power(.5, (R + NR))\n# )\n#switched_Z = -log10(\n# (power(1-ml_R_frac, R) * power((ml_R_frac), NR)) / power(.5, (R + NR))\n# )\n#\n#hexbin(Z, switched_Z,\n#mincnt = 1)\n#matplotlib.pyplot.xlim([-0.04, 1.04])\n##matplotlib.pyplot.ylim([-0.3, max(Z)*1.04])\n#cb = matplotlib.pyplot.colorbar()\n#cb.set_label('count')\n#matplotlib.pyplot.show()\n#\n#\n#\n#\n## convert to square, check diagonal\n#scipy.spatial.distance.squareform(R).shape\n#scipy.spatial.distance.squareform(NR).shape\n#scipy.spatial.distance.squareform(M).shape\n#\n#\n## really slow\n#R = numpy.empty(shape = (len(int_arr), len(int_arr)), dtype = numpy.int) #recombinants\n#NR = numpy.empty(shape = (len(int_arr), len(int_arr)), dtype = numpy.int) # non\n#for ii in range(len(int_arr)):\n# for jj in range(len(int_arr)):\n# if jj >= ii:\n# mult = int_arr[ii] * int_arr[jj]\n# R[ii, jj] = sum(mult == 2)\n# NR[ii, jj] = sum(mult == 1) + sum(mult == 4)\n# \n#\n#\n#\n#\n#\n#chum_fams.find_psvs(parent = 'CMUW10X_0001', outfile = 'Z:/HOME/Waples/Stacks_mapping/Chum_data/psv/chum_01.psvlikes.tsv')\n#chum_fams.find_psvs(parent = 'CMUW10X_0008', outfile = 'Z:/HOME/Waples/Stacks_mapping/Chum_data/psv/chum_08.psvlikes.tsv')\n#chum_fams.find_psvs(parent = 'CMUW10X_0009', outfile = 'Z:/HOME/Waples/Stacks_mapping/Chum_data/psv/chum_09.psvlikes.tsv')","sub_path":"General_Scripts/run_psv_pipeline.py","file_name":"run_psv_pipeline.py","file_ext":"py","file_size_in_byte":34680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"522029495","text":"import proc_temperature as pt\nimport pandas as pd\n\ndef calc_ts_feat(df_dto):\n '''\n :param df_dto:Feature dataframe\n :return: Feature dataframe converted into a timeseries\n '''\n df_ts = df_dto.groupby(['DeliveryCustomerAccountKey']).apply(lambda x: create_time_series(x))\n df_ts = df_ts.reset_index().drop(['level_1'], axis=1)\n df_ts = pt.cum_hd_cd(df_ts)\n return df_ts\n\ndef create_time_series(df):#, df_hdd):\n '''\n Converts the original order data for each customer into a time series for each customer.\n The time series also includes heating degree days for the time period\n :param df: Data frame containing order history for each customer\n :param df_hdd: Data frame containing heating degree days\n :return: Time series cotaining features for every customer\n '''\n st_date = df['MovementDateKey'].min()\n en_date = df['MovementDateKey'].max()\n ord_date = df['MovementDateKey'].tolist()\n time_inx = pd.date_range(start=st_date, end=en_date, freq='D')\n df1 = pd.DataFrame(None,index=time_inx)\n df_ord = df.set_index('MovementDateKey')\n df1 = df1.join(df_ord.loc[:,['DispensedWeight', 'DispensedWeight1']])\n df1 = df1.reset_index()\n df1['DateKey'] = df1['index']\n del df1['index']\n df1['Order'] = 0\n df1.loc[df1['DateKey'].isin(ord_date), 'Order'] = 1\n return df1","sub_path":"Train/crt_ts.py","file_name":"crt_ts.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"307390132","text":"MODULE_WHITE_LIST = [\n 'aids',\n 'airlines',\n 'art_institute_metadata',\n 'billionaires',\n 'broadway',\n 'cancer',\n 'cars',\n 'classics',\n 'construction_permits',\n 'construction_spending',\n 'county_crime',\n 'county_demographics',\n 'drugs',\n 'drug_bank',\n 'earthquakes',\n 'education',\n 'election',\n 'energy',\n 'finance',\n 'food',\n 'food_access',\n 'global_development',\n 'graduates',\n 'health',\n 'hospitals',\n 'hydropower',\n 'immigration',\n 'injuries',\n 'labor',\n 'medal_of_honor',\n 'music',\n 'publishers',\n 'real_estate',\n 'retail_services',\n 'school_scores',\n 'skyscrapers',\n 'slavery',\n 'state_crime',\n 'state_demographics',\n 'state_fragility',\n 'suicide_attacks',\n 'supreme_court',\n 'tate',\n 'weather'\n]\n","sub_path":"controllers/ast_finder/module_white_list.py","file_name":"module_white_list.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"499719746","text":"# 2 dimension of system of DNA-base and Au-particles;\n# regular or random postion\n# force:morse and lj(vander val)//constraint planar\n# method: brownian update\nimport poisson_disc\nimport hoomd\nimport hoomd.md\nimport fresnel\nimport numpy as np\nimport ex_render\nimport matplotlib.pyplot as plt\n\n\n\nif __name__ == '__main__':\n\n hoomd.context.initialize(\"\")\n base_params = dict()\n np.random.seed(1) # fixed num\n\n ex_render.display_movie(ex_render.render_disk_frame, 'trajectory.gsd')\n L = 50\n r = 0.5\n space = 1.4\n base_params['rd'] = 0.1\n #N_base = m\n\n\n #\n #x = np.linspace(-L / 2, L / 2, m, endpoint=False)\n #position = list(itertools.product(x, repeat=3))\n # the position of base\n #pos = L*np.random.rand(base_params['N'],10)\n\n pos = 0.95*L * poisson_disc.Bridson_sampling(dims=np.array([1.0,1.0]),\n radius=5*7*2*base_params['rd']/L) - np.array([L/2,L/2])\n plt.scatter(pos[:,0],pos[:,1],s=20)\n plt.show()\n base_params['N'] = len(pos)\n pos_z = np.zeros([base_params['N'],1])\n base_params['pos'] = tuple(map(tuple, np.hstack([pos,pos_z])))\n #base_params['pos'] = tuple(map(tuple, pos))\n\n\n snapshot = hoomd.data.make_snapshot(N = base_params['N'],\n box=hoomd.data.boxdim(Lx=L,Ly=L,dimensions=2),\n particle_types=['A','B'],\n )\n\n snapshot.particles.position[:] = base_params['pos']\n\n idx = np.random.choice(base_params['N'], int(3*base_params['N']/4), replace=False)\n\n snapshot.particles.typeid[:] = 1\n snapshot.particles.typeid[idx] = 0\n #snapshot.particles.typeid[int(base_params['N']/4):] = 1 # which sorted by position\n snapshot.particles.diameter[:] = 2*base_params['rd'] * snapshot.particles.diameter\n\n\n hd = hoomd.init.read_snapshot(snapshot)\n\n\n #define the force\n nl = hoomd.md.nlist.cell()\n #nl.add_exclusions(hd.system.particles[0].tag, hd.system.particles[1].tag)\n lj = hoomd.md.pair.lj(r_cut=1.0,nlist=nl)\n lj.pair_coeff.set(['A','B'],['A','B'],r_on = r)\n lj.pair_coeff.set('A','A',epsilon=0.003974, sigma=0.1)\n lj.pair_coeff.set('A','B',epsilon=0.3974, sigma=0.1)\n lj.pair_coeff.set('B', 'B', epsilon=0, sigma=0.1)\n #hoomd.md.constrain.\n\n morse = hoomd.md.pair.morse(r_cut=1.0,nlist=nl)\n morse.pair_coeff.set(['A','B'],['A','B'],r_on = r)\n morse.pair_coeff.set('A', 'B',D0=1.0, alpha=1.0, r0=1.25*r)\n morse.pair_coeff.set('A', 'A', D0=0.001, alpha=1.0, r0=1.25*r,r_cut = 0)\n morse.pair_coeff.set('B', 'B', D0=0.001, alpha=1.0, r0=1.25*r,r_cut = 0)\n\n nl.reset_exclusions(exclusions=[])\n\n ## set the constrain\n groupA = hoomd.group.type('A')\n\n hoomd.md.integrate.mode_standard(dt=1e-3)\n\n integrator = hoomd.md.integrate.brownian(group=groupA,kT=0.1,dscale=2,seed=1)\n\n\n hoomd.dump.gsd(\"trajectory.gsd\", period=5e2, group=hoomd.group.all(), overwrite=True)\n\n hoomd.run(1e4)\n\n #rigid = hoomd.md.constrain.rigid()\n\n print('finished')\n","sub_path":"attractive_force.py","file_name":"attractive_force.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"549629179","text":"#-*-coding:utf-8-*-\nimport os\nimport torch\nimport numpy as np\nimport pickle\nfrom bson import ObjectId\ndef predict_bpr_bloom(user_id,customer_id,k=-1):\n model_path = \"model/%s_model.pkl\"%(str(customer_id))\n if os.path.exists(model_path):\n model = torch.load(model_path)\n predictions = model.predict(np.array([user_id]))\n result = np.argsort(-predictions)[:k]\n return result\n else:\n return np.empty((0))\n\ndef transition_cid(customer_id,indexs):\n index_file = \"index/{}_{}_index.pkl\".format(str(customer_id),\"content_id\")\n if not os.path.exists(index_file):\n return None\n with open(index_file,'rb') as f:\n data = pickle.load(f)\n cindex = np.array(data['content_ids_list'])\n return cindex[indexs-1].tolist()\n\ndef mongo_push_usercf(pymongo,customer_id):\n user_db = pymongo.cont[pymongo.USER_DB]\n cursor = user_db[customer_id].find({})\n\n for t in cursor:\n ind = int(t[\"index\"])\n id = t['_id']\n indics = predict_bpr_bloom(user_id=ind, customer_id=customer_id)\n dids = \"\"\n if indics.any():\n dids = transition_cid(customer_id,indics)[:100]\n user_db[customer_id].update_one({\"_id\":ObjectId(id)},{\"$set\":{\"usercfval\":dids}})\n\ndef push_cache(customer_ids,pymodb):\n for customer_id in customer_ids:\n if customer_id.isdigit():\n mongo_push_usercf(pymodb,customer_id)\n\ndef start_queue(pyredis,pymodb,event):\n db = pymodb.cont[pymodb.USER_DB]\n customer_ids = db.list_collection_names()\n while True:\n push_cache(customer_ids,pymodb)\n event.wait()\n\nif __name__ == '__main__':\n from pymongo import MongoClient\n constr = \"mongodb://10.0.1.110:27017\"\n user_db = MongoClient(constr)\n ss = user_db[\"user_db\"].list_collection_names()\n for i in ss:\n if i.isdigit():\n print(i)\n\n cursor = user_db[\"user_db\"][\"165\"].find({})\n\n for t in cursor:\n print(t)","sub_path":"hogedata/usercf_recommend_list.py","file_name":"usercf_recommend_list.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"221021817","text":"# -*- coding: utf-8 -*-\n__author__ = 'Brice Olivier'\n\nimport os\nfrom setuptools import setup\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\nsetup(name='meta-word-embedding',\n version='0.2a0',\n description='A Python tool for aggregating multiple word embeddings and computing adjusted cosine similarities.',\n install_requires=requirements,\n author='Brice Olivier',\n author_email='briceolivier1409@gmail.com',\n url='https://github.com/PyENE/meta-word-embedding/',\n packages=['metawordembedding'],\n license=read('LICENSE'),\n long_description=read('README.md'))\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"635316537","text":"import os\n\nimport datetime\nfrom PIL import ImageFont\nfrom brother_ql.devicedependent import label_type_specs\n\nfrom printer_helpers import print_bar_code\n\n#label_type = \"29x90\"\n#rotate = True\n#barcode_value = \"7050122105438\"\n#barcode_text = \"Chips\"\n#printer_type = \"QL-700\"\n\n\nfrom PIL import Image, ImageMode, ImageDraw\n\n\ndef print_name_label(text, margin=10, rotate=False, label_type=\"62\", printer_type=\"QL-700\",):\n if not rotate:\n width, height = label_type_specs[label_type]['dots_printable']\n else:\n height, width = label_type_specs[label_type]['dots_printable']\n\n font_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"ChopinScript.ttf\")\n fs = 2000\n tw, th = width, height\n if width == 0:\n while th + 2*margin > height:\n font = ImageFont.truetype(font_path, fs)\n tw, th = font.getsize(text)\n fs -= 1\n width = tw+2*margin\n elif height == 0:\n while tw + 2*margin > width:\n font = ImageFont.truetype(font_path, fs)\n tw, th = font.getsize(text)\n fs -= 1\n height = th+2*margin\n else:\n while tw + 2*margin > width or th + 2*margin > height:\n font = ImageFont.truetype(font_path, fs)\n tw, th = font.getsize(text)\n fs -= 1\n\n xp = (width//2)-(tw//2)\n yp = (height//2)-(th//2)\n\n im = Image.new(\"RGB\", (width, height), (255, 255, 255))\n dr = ImageDraw.Draw(im)\n\n dr.text((xp, yp), text, fill=(0, 0, 0), font=font)\n now = datetime.datetime.now()\n date = now.strftime(\"%Y-%m-%d\")\n dr.text((0, 0), date, fill=(0, 0, 0))\n\n base_path = os.path.dirname(os.path.realpath(__file__))\n fn = os.path.join(base_path, \"bar_codes\", text + \".png\")\n\n im.save(fn, \"PNG\")\n\nprint_name_label(\"chrivi\", label_type=\"29x90\", rotate=True)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"90671015","text":"import spacy\nimport pandas as pd\nfrom collections import Counter\nfrom tqdm import tqdm\nimport json\nimport re, os\nfrom itertools import accumulate\n\nclass NToken:\n def __init__(self, idx, i, text):\n self.idx = idx\n self.i = i\n self.text = text\n\n def __len__(self):\n return len(self.text)\n\n\nclass NSpan:\n def __init__(self, start_char_id, end_char_id, toks, text):\n self.start_char = start_char_id\n self.end_char = end_char_id\n self.toks = toks\n self.text = text\n\n def __iter__(self):\n return iter(self.toks)\n\n\n# different models split sentences differently, so found different number of relations within sentence.\nnlp = spacy.load(\"en_core_sci_sm\") # tokenizer, \"en_core_sci_md\" is bigger\nadd_id = [0]\n\n####################\n\n# Process entities and relations for a given abstract.\n\ndef get_entities_in_sent(sent, entities):\n start, end = sent.start_char, sent.end_char\n start_ok = entities[\"char_start\"] >= start\n end_ok = entities[\"char_end\"] <= end\n keep = start_ok & end_ok\n res = entities[keep]\n return res\n\n\ndef align_one(sent, row):\n # Don't distinguish b/w genes that can and can't be looked up in database.\n lookup = {\"GENE-Y\": \"GENE\",\n \"GENE-N\": \"GENE\",\n \"CHEMICAL\": \"CHEMICAL\"}\n\n start_tok = None\n end_tok = None\n\n for tok in sent:\n if tok.idx == row[\"char_start\"]:\n start_tok = tok\n if tok.idx + len(tok) == row[\"char_end\"]:\n end_tok = tok\n\n if start_tok is None or end_tok is None:\n # print(\"sent: \", sent.text, \" entity: \", row.text)\n # print(\"en_start: \", row[\"char_start\"], \" en_end: \", row[\"char_end\"])\n # print(\"sent toks: \", [(tok.idx, tok.text) for tok in sent])\n return None\n else:\n expected = sent.text[start_tok.idx - sent.start_char:end_tok.idx - sent.start_char + len(end_tok)]\n if expected != row.text:\n # print(\"expected: \", expected, \" row tex: \", row.text)\n # print(\"ent_start: \", row[\"char_start\"], \" ent_end: \", row[\"char_end\"])\n # print(\"sent toks: \", [(tok.idx, tok.text) for tok in sent])\n raise Exception(\"Entity mismatch\")\n\n return (start_tok.i, end_tok.i, lookup[row[\"label\"]])\n\n\ndef align_entities(sent, entities_sent):\n aligned_entities = {}\n missed_entities = {}\n for _, row in entities_sent.iterrows():\n aligned = align_one(sent, row)\n if aligned is not None:\n aligned_entities[row[\"entity_id\"]] = aligned\n else:\n missed_entities[row[\"entity_id\"]] = None\n\n return aligned_entities, missed_entities\n\n\ndef format_relations(relations):\n # Convert to dict.\n all_rels = [] # one entity-pair may has multiple relation types\n res = {} # we only store one relation type for an entity-pair\n for _, row in relations.iterrows():\n ent1 = row[\"arg1\"].replace(\"Arg1:\", \"\")\n ent2 = row[\"arg2\"].replace(\"Arg2:\", \"\")\n key = (ent1, ent2)\n res[key] = row[\"cpr_group\"] # the label of standard relation is cpr_group\n all_rels.append(f\"{ent1}_{ent2}_{row['cpr_group']}\")\n\n return res, all_rels\n\n\ndef get_relations_in_sent(aligned, relations):\n res = []\n keys = set()\n # Loop over the relations, and keep the ones relating entities in this sentences.\n for ents, label in relations.items():\n if ents[0] in aligned and ents[1] in aligned:\n ent1 = aligned[ents[0]]\n ent2 = aligned[ents[1]]\n to_append = ent1[:2] + ent2[:2] + (label,)\n res.append(to_append)\n keys.add(f\"{ents[0]}_{ents[1]}_{label}\")\n\n return res, keys\n\ndef re_sent_token(doc):\n # all_entity_ids = set()\n # for _, entity in entities.iterrows():\n # ids = re.split('[\\s;]', entity[\"char_start_end_ids\"])\n # all_entity_ids |= set(ids)\n\n # re-sentence: merge and sep\n new_sents_list = []\n sent_number = len(list(doc.sents))\n # print(\"Before sents number: \", sent_number)\n dump_sent = None\n for sent in doc.sents:\n # print(\"add_id: \", add_id)\n if not sent.text[0].islower():\n if dump_sent is not None:\n find_end = re.search('[.!?\\\"\\'\\s]', dump_sent.text[-1])\n # print(\"last char\", dump_sent.text[-1])\n if find_end:\n # make sure dump_sent is a sentence\n new_sents_list.append(dump_sent)\n dump_sent = re_sent(sent)\n else:\n dump_sent = merge_sent(dump_sent, sent)\n else:\n dump_sent = re_sent(sent)\n else:\n if dump_sent is None:\n dump_sent = re_sent(sent)\n else:\n dump_sent = merge_sent(dump_sent, sent)\n # print(\"dump_sent: \", dump_sent.text)\n # add last sent\n new_sents_list.append(dump_sent)\n # for sent in new_sents_list:\n # print(sent.text)\n # print([tok.text for tok in sent])\n\n merge_sent_number = len(new_sents_list)\n # print(\"After sents number: \", merge_sent_number)\n add_id[0] = 0\n return new_sents_list\n\ndef merge_sent(sent1, sent2):\n # print(\"sent1: \", sent1.text, \"\\nsent2: \", sent2.text)\n # print(\"sent1 id: \", sent1.end_char, \" sent2 id:\", sent2.start_char)\n diff_id = sent2.start_char-sent1.end_char\n new_toks = []\n for tok in sent1: # sent1 is dump_sent\n new_toks.append(tok)\n for tok in sent2:\n new_toks.extend(re_token(tok))\n new_sent = NSpan(sent1.start_char, sent2.end_char, new_toks, sent1.text + ' ' * diff_id + sent2.text)\n return new_sent\n\ndef re_sent(sent):\n new_toks = []\n for tok in sent:\n new_toks.extend(re_token(tok))\n\n new_sent = NSpan(sent.start_char, sent.end_char, new_toks, sent.text)\n return new_sent\n\ndef re_token(tok):\n new_toks = []\n\n toks = None\n # Chemprot text contains many '(' and ')'. To limit the number of tokens in one sentence,\n # we do not split '(' and ')' in token\n if re.search('([-/])', tok.text):\n toks = re.split('([-/])', tok.text)\n # elif re.search('(\\d+)', tok.text):\n # toks = re.split('(\\d+)', tok.text) # one special tok\n if toks is not None:\n toks = [tok for tok in toks if tok is not '']\n lens = [0] + list(accumulate([len(t) for t in toks[:-1]]))\n # print('tok: ', tok.text, ' idx: ', tok.idx, ' tok.i: ', tok.i, ' toks: ', toks)\n for i in range(len(toks)):\n t_idx = tok.idx + lens[i]\n ntok = NToken(t_idx, tok.i + i + add_id[0], toks[i])\n # print('tok: ', ntok.text, ' idx: ', ntok.idx, ' tok.i: ', ntok.i)\n new_toks.append(ntok)\n\n # print(\"tok: \", tok.text, ' tok split: ', toks)\n add_id[0] += len(toks) - 1\n\n # break # only once\n if len(new_toks) == 0:\n new_toks.append(NToken(tok.idx, tok.i + add_id[0], tok.text))\n\n return new_toks\n\n####################\n\n# Manage a single document and a single fold.\n\ndef one_abstract(row, df_entities, df_relations):\n doc = row[\"title\"] + \" \" + row[\"abstract\"]\n doc_key = row[\"doc_key\"]\n # print(\"doc_key: \", doc_key)\n entities = df_entities.query(f\"doc_key == '{doc_key}'\")\n relations, all_rels = format_relations(df_relations.query(f\"doc_key == '{doc_key}'\"))\n\n processed = nlp(doc)\n processed_doc = re_sent_token(processed)\n\n entities_seen = set()\n entities_alignment = set()\n entities_no_alignment = set()\n relations_found = set()\n\n scierc_format = {\"doc_key\": doc_key, \"dataset\": \"chemprot\", \"sentences\": [], \"ner\": [],\n \"relations\": []}\n\n for sent in processed_doc:\n # Get the tokens.\n toks = [tok.text for tok in sent]\n\n # Align entities.\n entities_sent = get_entities_in_sent(sent, entities)\n aligned, missed = align_entities(sent, entities_sent)\n\n # Align relations.\n relations_sent, keys_found = get_relations_in_sent(aligned, relations)\n\n # Append to result list\n scierc_format[\"sentences\"].append(toks)\n entities_to_scierc = [list(x) for x in aligned.values()]\n scierc_format[\"ner\"].append(entities_to_scierc)\n scierc_format[\"relations\"].append(relations_sent)\n\n # Keep track of which entities and relations we've found and which we haven't.\n entities_seen |= set(entities_sent[\"entity_id\"])\n entities_alignment |= set(aligned.keys())\n entities_no_alignment |= set(missed.keys())\n relations_found |= keys_found\n\n # Update counts.\n entities_missed = set(entities[\"entity_id\"]) - entities_seen\n relations_missed = set(all_rels) - relations_found\n # entities_gene_y = df_entities.query(\"label == 'GENE-Y'\")\n # entities_gene_n = df_entities.query(\"label == 'GENE-N'\")\n # rel_cpr3 = df_relations.query(\"cpr_group == 'CPR:3'\")\n # rel_cpr4 = df_relations.query(\"cpr_group == 'CPR:4'\")\n # rel_cpr5 = df_relations.query(\"cpr_group == 'CPR:5'\")\n # rel_cpr6 = df_relations.query(\"cpr_group == 'CPR:6'\")\n # rel_cpr9 = df_relations.query(\"cpr_group == 'CPR:9'\")\n #\n # print(\"Chemical entities:\", len(entities_gene_n) + len(entities_gene_y),\n # \" CPR:3:\", len(rel_cpr3),\n # ' CPR:4:', len(rel_cpr4),\n # \" CPR:5:\", len(rel_cpr5),\n # \" CPR:6:\", len(rel_cpr6),\n # \" CPR:9:\", len(rel_cpr9))\n\n COUNTS[\"entities_correct\"] += len(entities_alignment)\n COUNTS[\"entities_misaligned\"] += len(entities_no_alignment)\n COUNTS[\"entities_missed\"] += len(entities_missed)\n COUNTS[\"entities_total\"] += len(entities)\n COUNTS[\"relations_found\"] += len(relations_found)\n COUNTS[\"relations_missed\"] += len(relations_missed)\n COUNTS['relations_total'] += len(all_rels)\n\n return scierc_format\n\n\ndef one_fold(fold):\n directory = \"data/chemprot\"\n print(f\"Processing fold {fold}.\")\n raw_subdirectory = \"raw_data/ChemProt_Corpus\"\n df_abstracts = pd.read_table(f\"{directory}/{raw_subdirectory}/chemprot_{fold}/chemprot_{fold}_abstracts.tsv\",\n header=None, keep_default_na=False, quoting=3, # keep quotechar\n names=[\"doc_key\", \"title\", \"abstract\"])\n # one_doc = df_abstracts.query(\"doc_key=='23194825'\")\n # print(one_doc['title'])\n # print(one_doc['abstract'])\n # char_start_end_id may contain two spans (discontiguous entity) divided by \";\", check if it can get all span ids\n\n df_entities = pd.read_table(f\"{directory}/{raw_subdirectory}/chemprot_{fold}/chemprot_{fold}_entities.tsv\",\n header=None, keep_default_na=False,\n names=[\"doc_key\", \"entity_id\", \"label\", \"char_start\", \"char_end\", \"text\"])\n df_relations = pd.read_table(f\"{directory}/{raw_subdirectory}/chemprot_{fold}/chemprot_{fold}_gold_standard.tsv\",\n header=None, keep_default_na=False,\n names=[\"doc_key\", \"cpr_group\", \"arg1\", \"arg2\"])\n\n res = []\n for _, abstract in tqdm(df_abstracts.iterrows(), total=len(df_abstracts)):\n to_append = one_abstract(abstract, df_entities, df_relations)\n res.append(to_append)\n\n # Write to file.\n name_out = f\"{directory}/processed_data/standard/{fold}.jsonl\"\n if not os.path.exists(f\"{directory}/processed_data/standard\"):\n os.makedirs(f\"{directory}/processed_data/standard\")\n with open(name_out, \"w\") as f_out:\n for line in res:\n print(json.dumps(line), file=f_out)\n\n\n####################\n\n# Driver\n\nCOUNTS = Counter()\n\nfor fold in [\"training\"]: # \"training\", \"development\", \"test\"\n one_fold(fold)\n\ncounts = pd.Series(COUNTS)\nprint()\nprint(\"Some entities were missed due to tokenization choices in SciSpacy. Here are the stats:\")\nprint(counts)\n","sub_path":"scripts/data/chemprot/02_chemprot_standard_to_input.py","file_name":"02_chemprot_standard_to_input.py","file_ext":"py","file_size_in_byte":11848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"218500359","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('profile/', views.profile, name='profile'),\n path('create/', views.quiz_create, name='create'),\n path('details//', views.quiz_detail, name='details'),\n path('game//', views.quiz_game, name='game'),\n path('game_', views.validate_answers, name='validate')\n]\n","sub_path":"quiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"206403985","text":"#!/ usr/bin/env\n# coding=utf-8\n#\n# Copyright 2019 ztosec & https://www.zto.com/\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"\nauthor: b5mali4\n\"\"\"\nimport sys\nimport json\nimport threading\nfrom Crypto.Cipher import AES\nfrom binascii import b2a_hex, a2b_hex\n\n\ndef synchronized(func):\n func.__lock__ = threading.Lock()\n\n def synced_func(*args, **kwargs):\n with func.__lock__:\n return func(*args, **kwargs)\n\n return synced_func\n\n\nclass prpcrypt():\n \"\"\"\n 加密类\n \"\"\"\n __single_instance = None\n\n @synchronized\n def get_single_instance(key, refresh=False):\n \"\"\"\n 获得单例\n :return: \n \"\"\"\n if refresh or prpcrypt.__single_instance is None or prpcrypt.__single_instance.key != key:\n prpcrypt.__single_instance = prpcrypt(key)\n\n return prpcrypt.__single_instance\n\n def __init__(self, key):\n self.key = key\n self.mode = AES.MODE_CBC\n self.cipher_text = None\n\n def encrypt(self, text):\n \"\"\"\n 加密函数,如果text不足16位就用空格补足为16位,\n 如果大于16当时不是16的倍数,那就补足为16的倍数。\n :param text: \n :return: \n \"\"\"\n cryptor = AES.new(self.key, self.mode, b'0000000000000000')\n length = 16\n count = len(text)\n if count < length:\n add = (length - count)\n text = text + ('\\0' * add)\n elif count > length:\n add = (length - (count % length))\n text = text + ('\\0' * add)\n self.cipher_text = cryptor.encrypt(text)\n return b2a_hex(self.cipher_text)\n\n def decrypt(self, text):\n \"\"\"\n 解密函数,去掉补足的空格用strip() 去掉\n :param text: \n :return: \n \"\"\"\n cryptor = AES.new(self.key, self.mode, b'0000000000000000')\n plain_text = cryptor.decrypt(a2b_hex(text))\n return plain_text.decode(\"utf-8\").rstrip('\\0')\n\n\ndef generate_access_key(task_id, username):\n \"\"\"\n 将 其他三个参数组合成 {\"task_id\":\"1\", \"username\":\"lilie\", \"create_time\":\"2018-12992\"} 后用ase加密\n :param private_key: \n :param task_id: \n :param username: \n :param create_time: \n :return: \n \"\"\"\n import datetime\n from model.system_config import SystemConfigService\n\n create_time = str(datetime.datetime.now())\n private_key = SystemConfigService.get_single_instance().task_access_private_key\n clear_data = {\"task_id\": task_id, \"username\": username, \"create_time\": create_time}\n return prpcrypt.get_single_instance(private_key, False).encrypt(json.dumps(clear_data))\n","sub_path":"HunterCelery/common/aes_util.py","file_name":"aes_util.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"395224531","text":"import os\nimport sys\nfrom django.conf import settings\n\nBASE_PATH = os.path.dirname(__file__)\n\n\ndef main():\n \"\"\"\n Standalone django model test with a 'memory-only-django-installation'.\n You can play with a django model without a complete django app installation.\n http://www.djangosnippets.org/snippets/1044/\n \"\"\"\n settings.configure(\n INSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.sessions',\n 'django.contrib.contenttypes',\n 'django_upyun',\n ),\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:',\n }\n },\n ROOT_URLCONF='beproud.django.authutils.tests.test_urls',\n DEFAULT_FILE_STORAGE = 'django_upyun.UpYunStorage',\n UPYUN_ACCOUNT=os.getenv('UPYUN_ACCOUNT'),\n UPYUN_PASSWORD=os.getenv('UPYUN_PASSWORD'),\n UPYUN_BUCKET=os.getenv('UPYUN_BUCKET'),\n MEDIA_URL=\"http://%s.b0.upaiyun.com/\" % os.getenv('UPYUN_BUCKET'),\n )\n\n from django.test.utils import get_runner\n test_runner = get_runner(settings)(verbosity=2, interactive=True)\n failures = test_runner.run_tests(['django_upyun'])\n sys.exit(failures)\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"153613699","text":"import sys\nimport shutil\nimport os\nimport string\nimport socket\n\n\n# Felipe Osiel Pineda\n# 730132665\n\ndef checkConnect(request):\n # Function split the serverhost and serverport and checks the individually.\n alphabetList = list(string.ascii_lowercase)\n alphabetList.append(\".\")\n digitList = list(range(0,10))\n serverHost = \"\"\n serverPort = \"\"\n serverHostError = False\n serverPortError = False\n serverPortNotInRange = False\n serverPortNotDigits = False\n if len(request) == 1:\n request = request[0].lstrip(\" \").split(\" \",1) #['classroom.cs.unc.edu', '9000\\n']\n if len(request) == 2:\n serverHost = request[0].lstrip(\" \")\n serverPort = request[1].lstrip(\" \").rstrip(\"\\n\")\n if serverHost[0] == \".\" or serverHost[0] in digitList: # to check if the server hosts starts with a period\n serverHostError = True\n for char in serverHost.lower():\n if char not in digitList and char not in alphabetList:\n serverHostError = True\n break\n if not 0 <= int(serverPort) <= 65535:\n serverPortNotInRange = True\n try: \n for num in serverPort:\n if int(num) not in digitList:\n serverPortNotDigits = True\n except Exception as err:\n serverPortNotDigits = True\n if serverPortNotInRange == True or serverPortNotDigits == True:\n serverPortError = True\n else:\n serverHostError = True\n else:\n serverHostError = True\n return serverHost, serverPort, serverHostError, serverPortError\n\ndef checkGet(request):\n # Function checks the request to see if the the pathname is all ASCII characters.\n pathnameError = False\n pathname = \"\"\n foundLetter = False\n if len(request) == 1:\n request[0] = request[0].lstrip(\" \")\n if len(request) == 1:\n for letter in request[0]:\n if ord(letter) != 32 and ord(letter) != 10: # checks if there is a letter present, pathnames can't be all spaces\n foundLetter = True\n if ord(letter) > 127:\n pathnameError = True\n break\n else:\n pathnameError = True\n else:\n pathnameError = True\n if foundLetter == False:\n pathnameError = True\n if pathnameError == False:\n pathname = request[0].rstrip(\"\\n\") # strips newlines because the prints in the tests adds them automatically\n return pathnameError, pathname\n\ndef isErrorConnect(rDict, request): \n errorConnect = False\n requestList = [\"get\", \"quit\"]\n if request in requestList and \"connect\" not in rDict:\n errorConnect = True\n return errorConnect\n\n### FTPclient2.py functions\ndef checkCode(code):\n # Function is given the code part of reply and parses it to see if it is indeed a value between 100 and 599 and\n # also if all the characters in the code are digits\n digitList = list(range(0,10))\n codeNotDigits = False\n codeNotInRange = False\n codeError = False\n try:\n if not 100 <= int(code) <= 599:\n codeNotInRange = True\n except Exception as err:\n codeNotInRange = True\n try: \n for num in code:\n if int(num) not in digitList:\n codeNotDigits = True\n except Exception as err:\n codeNotDigits = True\n if codeNotInRange == True or codeNotDigits == True:\n codeError = True\n return code, codeError\n\ndef checkreplytext(text):\n # Function is given the text part of the reply to see if the characters inside are indeed any of the 128 ASCII\n # characters except for and \n replyTextError = False\n crlfError = False\n foundLetter = False\n for letter in text:\n if ord(letter) != 32 and ord(letter) != 13 and ord(letter) != 10: # checks if username/password contains ascii letter\n foundLetter = True\n if ord(letter) > 127: # checks username to see if it fits ASCII standard\n replyTextError = True\n break\n if foundLetter == False:\n replyTextError = True\n if \"\\r\\n\" not in text:\n crlfError = True \n return text, replyTextError, crlfError\n\ndef receiveReplies(str):\n splitReply = str.split(\" \",1)\n if len(splitReply) > 1:\n code, codeError = checkCode(splitReply[0])\n text, replyTextError, crlfError = checkreplytext(splitReply[1])\n if codeError:\n print(\"ERROR -- reply-code\")\n elif replyTextError:\n print(\"ERROR -- reply-text\")\n elif crlfError:\n print(\"ERROR -- \")\n else:\n print(\"FTP reply \"+code+\" accepted. Text is: \"+text.rstrip(\"\\r\\n\"))\n else:\n print(\"ERROR -- reply-code\")\n\n\ndef assure_path_exists(path):\n # used to check if a certain path (directory/file) exists. If not then create it\n if not os.path.exists(path):\n os.makedirs(path)\n\nretrCount = 0\n# Takes in the requests and loops throught them. It takes them one by one to see if it falls under connect, get, or quit\n# once there it will do the appropriate checks.\nrequestDict = {}\nfor request in sys.stdin:\n sys.stdout.write(request)\n splitRequest = request.split(\" \",1)\n if splitRequest[0].lower().rstrip(\"\\n\") == \"connect\": \n serverHost, serverPort, serverHostError ,serverPortError = checkConnect(splitRequest[1:])\n if serverHostError:\n print(\"ERROR -- server-host\") \n elif serverPortError:\n print(\"ERROR -- server-port\") \n else: \n try:\n # create control socket (FTP-control connection)\n # Ex: CONNECT classroom.cs.unc.edu 9000\n print(\"CONNECT accepted for FTP server at host \"+serverHost+\" and port \"+serverPort)\n control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n control_socket.connect((serverHost, int(serverPort)))\n except:\n print(\"CONNECT failed\")\n continue\n if \"connect\" in requestDict:\n del requestDict[\"connect\"]\n requestDict[\"connect\"] = sys.argv[1] # records port number provided in command line assoc with connect command\n \n received_data = control_socket.recv(1024).decode()\n receiveReplies(received_data)\n\n # USER-PASS-SYST-TYPE being sent after CONNECT command\n sys.stdout.write(\"USER anonymous\\r\\n\")\n control_socket.send(\"USER anonymous\\r\\n\".encode())\n received_data = control_socket.recv(1024).decode()\n receiveReplies(received_data)\n\n sys.stdout.write(\"PASS guest@\\r\\n\")\n control_socket.send(\"PASS guest@\\r\\n\".encode())\n received_data = control_socket.recv(1024).decode()\n receiveReplies(received_data)\n\n sys.stdout.write(\"SYST\\r\\n\")\n control_socket.send(\"SYST\\r\\n\".encode())\n received_data = control_socket.recv(1024).decode()\n receiveReplies(received_data)\n\n sys.stdout.write(\"TYPE I\\r\\n\")\n control_socket.send(\"TYPE I\\r\\n\".encode())\n received_data = control_socket.recv(1024).decode()\n receiveReplies(received_data)\n\n elif splitRequest[0].lower().rstrip(\"\\n\") == \"get\":\n errorConnect = isErrorConnect(requestDict, \"get\")\n pathnameError, pathname = checkGet(splitRequest[1:])\n if pathnameError:\n print(\"ERROR -- pathname\")\n elif errorConnect:\n print(\"ERROR -- expecting CONNECT\")\n else:\n requestDict[\"get\"] = pathname\n my_ip = socket.gethostbyname(socket.gethostname()).replace(\".\",\",\")\n portNumber = str(int(requestDict.get(\"connect\"))//256)+\",\"+str(int(requestDict.get(\"connect\"))%256)\n hostPort = my_ip+\",\"+portNumber\n print(\"GET accepted for \"+pathname)\n try:\n # create welcome socket (FTP-data connection)\n data_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n data_client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # #caled before bind to allow reusing the same port.\n data_client_socket.bind((socket.gethostbyname(socket.gethostname()), int(requestDict.get(\"connect\")))) #client hostname, command line arguement port number\n data_client_socket.listen(1)\n except:\n print(\"GET failed, FTP-data port not allocated\")\n continue\n \n sys.stdout.write(\"PORT \"+hostPort+\"\\r\\n\")\n control_socket.send(str(\"PORT \"+hostPort+\"\\r\\n\").encode())\n received_data = control_socket.recv(1024).decode()\n receiveReplies(received_data)\n requestDict[\"connect\"] = int(requestDict.get(\"connect\")) + 1\n\n sys.stdout.write(\"RETR \"+pathname+\"\\r\\n\")\n control_socket.send(str(\"RETR \"+pathname+\"\\r\\n\").encode())\n received_data = control_socket.recv(1024).decode()\n receiveReplies(received_data)\n \n if received_data == \"150 File status okay.\\r\\n\":\n # if int(received_data[0:4]) < 400:\n assure_path_exists(\"./retr_files\") # Checks if retr_files exits, if not create, otherwise do nothing\n connection_socket, addr = data_client_socket.accept()\n str_retrCount = str(retrCount)\n if retrCount < 10:\n str_retrCount = \"00\" + str_retrCount\n elif 10 <= retrCount < 100:\n str_retrCount = \"0\"+ str_retrCount\n else:\n str_retrCount = str(retrCount)\n merchandise_client = open(\"retr_files/file\"+str_retrCount, \"w+\")\n merchandise_client_chunk = connection_socket.recv(1024)\n while merchandise_client_chunk:\n merchandise_client.write(merchandise_client_chunk.decode())\n merchandise_client_chunk = connection_socket.recv(1024)\n merchandise_client.close() \n connection_socket.close()\n retrCount += 1\n else:\n continue\n\n elif splitRequest[0].lower().rstrip(\"\\n\") == \"quit\":\n errorConnect = isErrorConnect(requestDict, \"quit\")\n if len(splitRequest) > 1:\n print(\"ERROR -- request\") \n elif errorConnect:\n print(\"ERROR -- expecting CONNECT\")\n else:\n requestDict = {}\n print(\"QUIT accepted, terminating FTP client\")\n sys.stdout.write(\"QUIT\\r\\n\")\n control_socket.send(\"QUIT\\r\\n\".encode())\n received_data = control_socket.recv(1024).decode()\n receiveReplies(received_data)\n control_socket.close()\n\n else:\n print(\"ERROR -- request\")\n","sub_path":"Backups/FTPClient.py","file_name":"FTPClient.py","file_ext":"py","file_size_in_byte":10973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"233530616","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nfrom builtins import (ascii, bytes, chr, dict, filter, hex, input,\n int, map, next, oct, open, pow, range, round,\n str, super, zip)\nfrom future.builtins.disabled import (apply, cmp, coerce, execfile,\n file, long, raw_input, reduce, reload,\n unicode, xrange, StandardError)\n\nimport sys, random, math, os\nimport itertools as it\nimport collections as col\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport forgi.threedee.model.coarse_grain as ftmc\nimport forgi.projection.projection2d as ftmp\nimport forgi.threedee.utilities.vector as ftuv\n\nimport argparse\n\n#################### MAIN FUNCTION #####################################\n\ndef main(args): \n files=args.cgfiles\n\n #Uncomment the following line to display the files in a random order.\n #random.shuffle(files)\n\n #Prepare the pyplot figure\n totalFigures=len(files)\n figuresPerLine=int(math.ceil(math.sqrt(totalFigures)))\n fig, ax=plt.subplots(int(math.ceil(totalFigures/figuresPerLine)),figuresPerLine, squeeze=False, figsize=(8,8))\n \n #Background color of figure (not plot)\n if args.style==\"WOB\":\n fig.patch.set_facecolor('black')\n\n #Plot one projection per file.\n for i, file_ in enumerate(files):\n #get the subplot axes (Note: axes != axis in matplotlib)\n current_axes=ax[i//figuresPerLine, i%figuresPerLine]\n\n #Parse the file\n cg=ftmc.CoarseGrainRNA(file_)\n\n # Random projection direction, if no direction present in the file\n if args.proj_direction:\n direction=list(map(float, args.proj_direction.split(\",\")))\n elif cg.project_from is not None:\n direction=cg.project_from\n else:\n direction=ftuv.get_random_vector()\n\n #Generate the projection object\n proj=ftmp.Projection2D(cg, direction, rotation=180, project_virtual_atoms=args.virtual_atoms) \n\n #Simulate a reduced resolution of the image.\n if args.condense:\n proj.condense(args.condense)\n\n target_elems=[]\n if args.show_distances: \n\n try:\n num_elems=int(args.show_distances)\n except:\n target_elems=args.show_distances.split(\",\")\n else:\n if num_elems>len(proj._coords.keys()):\n raise ValueError(\"--show-distances must not be greater {} for the current projection ({}:'{}')\".format(len(proj._coords.keys()), i, file_))\n elems=list(proj._coords.keys())\n random.shuffle(elems)\n while len(target_elems)= 1:\n vidlink = data['items'][0]['id']['videoId']\n bot.sendMessage(chat_id=chat_id, text=(user + ': ' if not user == '' else '') +\n 'https://www.youtube.com/watch?v=' + vidlink + '&type=video')\n return True\n else:\n bot.sendMessage(chat_id=chat_id, text='I\\'m sorry ' + (user if not user == '' else 'Dave') +\n ', I\\'m afraid I can\\'t do that.\\n(Video not found)')\n else:\n bot.sendMessage(chat_id=chat_id, text='I\\'m sorry ' + (user if not user == '' else 'Dave') +\n ', ' + data['error'])","sub_path":"commands/getvid.py","file_name":"getvid.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"582266577","text":"\"\"\"\n.. module:: activate\n :platform: Darwin, Linux, Unix, Windows\n :synopsis: Module that is utilized by test files to ensure the test environment is initialized in\n the correct order.\n\n.. moduleauthor:: Myron Walker \n\"\"\"\n\n__author__ = \"Myron Walker\"\n__copyright__ = \"Copyright 2020, Myron W Walker\"\n__credits__ = []\n__version__ = \"1.0.0\"\n__maintainer__ = \"Myron Walker\"\n__email__ = \"myron.walker@gmail.com\"\n__status__ = \"Development\" # Prototype, Development or Production\n__license__ = \"MIT\"\n\nimport os\n\nfrom datetime import datetime\n\nfrom akit.xtime import parse_datetime\n\n# =======================================================================================\n# The way we start up the test framework and the order which things come up in is a very\n# important part of the automation process. It effects whether or not logging is brought\n# up consistently before all modules start using it. It ensures that no matter how we\n# enter into an automation process, whether via a test runner, terminal, or debugging a single\n# file that we properly parse arguments and settings and launch the automation process\n# consistently.\n#\n# Because of these necessities, we setup the activate module so it is the first thing\n# scripts and tests files that consume the test framework will import to ensure the\n# startup process is always consistent\n#\n# The framework has a special activation module :module:`akit.environment.console` that is\n# used when bringing up the test framework in a console. This special method redirects\n\n# Step 1 - Force the default configuration to load if it is not already loaded\nfrom akit.environment.configuration import RUNTIME_CONFIGURATION\n\n# Step 2 - Process the environment variables that are used to overwride the\n# default configuration\nfrom akit.environment.variables import VARIABLES, LOG_LEVEL_NAMES\n\n# Step 3 - Load the user configuration and add it to the RUNTIME_CONFIGURATION 'ChainMap' so\n# the user settings take precedence over the runtime default settings.\nfrom akit.environment.configuration import load_runtime_configuration\n\nruntime_config = load_runtime_configuration()\nRUNTIME_CONFIGURATION.update(runtime_config)\n\nif VARIABLES.AKIT_CONSOLE_LOG_LEVEL is not None and VARIABLES.AKIT_CONSOLE_LOG_LEVEL in LOG_LEVEL_NAMES:\n console_level = VARIABLES.AKIT_CONSOLE_LOG_LEVEL\nelse:\n console_level = \"INFO\"\n\nif VARIABLES.AKIT_FILE_LOG_LEVEL is not None and VARIABLES.AKIT_FILE_LOG_LEVEL in LOG_LEVEL_NAMES:\n logfile_level = VARIABLES.AKIT_FILE_LOG_LEVEL\nelse:\n logfile_level = \"DEBUG\"\n\n# Step 5 - Force the context to load with defaults ifz it is not already loaded\n# and setup the run type if not already set\nfrom akit.environment.context import Context # pylint: disable=wrong-import-position\n\nctx = Context()\n\n# The environment element holds the resulting variables that are a result of the\n# startup process\nenv = ctx.lookup(\"/environment\")\n\nenv[\"branch\"] = VARIABLES.AKIT_BRANCH\nenv[\"build\"] = VARIABLES.AKIT_BUILD\nenv[\"flavor\"] = VARIABLES.AKIT_FLAVOR\n\nif VARIABLES.AKIT_STARTTIME is not None:\n starttime = parse_datetime(VARIABLES.AKIT_STARTTIME)\n env[\"starttime\"] = starttime\nelse:\n env[\"starttime\"] = datetime.now()\nenv[\"runid\"] = VARIABLES.AKIT_RUNID\n\n\nconf = ctx.lookup(\"/environment/configuration\")\n\nfill_dict = {\n \"starttime\": str(env[\"starttime\"]).replace(\" \", \"T\")\n}\n\njobtype = env[\"jobtype\"]\nif jobtype == \"console\":\n outdir_template = conf.lookup(\"/paths/consoleresults\")\n outdir_full = os.path.abspath(os.path.expandvars(os.path.expanduser(outdir_template % fill_dict)))\n env[\"output_directory\"] = outdir_full\nelse:\n env[\"jobtype\"] = \"testrun\"\n outdir_template = conf.lookup(\"/paths/testresults\")\n outdir_full = os.path.abspath(os.path.expandvars(os.path.expanduser(outdir_template % fill_dict)))\n env[\"output_directory\"] = outdir_full\n env[\"behaviors\"] = {\n \"log-landscape-declaration\": True,\n \"log-landscape-scan\": True\n }\n\nloglevels = conf.lookup(\"/logging/levels\")\nloglevels[\"console\"] = console_level\nloglevels[\"logfile\"] = logfile_level\n\n# Step 5 - Import the logging module so we get an initial configuration that\n# points to standard out\nimport akit.xlogging.foundations # pylint: disable=unused-import,wrong-import-position\n","sub_path":"packages/akit/environment/activate.py","file_name":"activate.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"249879077","text":"import os\n\nfrom flask import Flask, render_template, app, send_file, request, jsonify, flash, redirect, url_for\nfrom livereload import Server\nfrom werkzeug.utils import secure_filename\nfrom pandas import read_csv\nfrom flask_cors import CORS, cross_origin\n\n\napp = Flask(__name__)\ncors = CORS(app, resorces={r'/*': {\"origins\": '*'}})\napp.config['CORS_HEADER'] = 'Content-Type'\n\n\nUPLOAD_FOLDER = 'static/uploads'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n@app.route('/', methods=['GET', 'POST'])\n@cross_origin(origin='*', headers=['Content-Type', 'Authorization'])\ndef upload_file():\n return send_file('static/html/index.html')\n\n\n@app.route('/upload', methods=['POST'])\n@cross_origin(origin='*', headers=['Content-Type', 'Authorization'])\ndef uploadFile():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file:\n filename = secure_filename(file.filename)\n full_filename = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n file.save(full_filename)\n df = read_csv(full_filename, error_bad_lines=False, warn_bad_lines=False)\n return str(df.to_json())\n #return redirect(url_for('upload_file', file=filename))\n\n\nif __name__ == \"__main__\":\n app.debug = True\n server = Server(app.wsgi_app)\n #server.serve()\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124846349","text":"from PySide6 import QtGui, QtWidgets, QtCore\nimport pyqtgraph as pg\nimport sys, math, time\nfrom collections import deque\nimport libmapper as mpr\nimport os\n\nsignals = {}\nsigs_to_free = []\n\ndisplay_sec = 10.0\n\nuse_2d = False\n\nicon_path = os.getcwd() + '/clear.png'\n\nprint('icon_path', icon_path)\n\nclass TimeAxisItem(pg.AxisItem):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def tickStrings(self, values, scale, spacing):\n return [time.strftime('%H:%M:%S', time.localtime(value)) for value in values]\n\ndef sig_handler(sig, event, id, val, tt):\n now = tt.get_double()\n\n if event == mpr.Signal.Event.REL_UPSTRM:\n sig.instance(id).release()\n elif event != mpr.Signal.Event.UPDATE:\n return\n\n # Find signal\n try:\n match = signals[sig['name']]\n except:\n print('signal not found')\n return\n\n vec_len = match['vec_len']\n\n if id not in match['vals']:\n # don't bother recording and instance release\n if val != None:\n if isinstance(val, list):\n match['vals'][id] = [deque([val[el]]) for el in range(vec_len)]\n else:\n match['vals'][id] = [deque([val])]\n match['tts'][id] = deque([now])\n match['curves'][id] = None\n return\n elif val == None:\n for el in range(vec_len):\n match['vals'][id][el].append(float('nan'))\n elif isinstance(val, list):\n for el in range(vec_len):\n match['vals'][id][el].append(val[el])\n else:\n match['vals'][id][0].append(val)\n match['tts'][id].append(now)\n\ndef on_map(type, map, event):\n src = map.signals(mpr.Location.SOURCE)[0]\n dst = map.signals(mpr.Location.DESTINATION)[0]\n if src['is_local']:\n map.release()\n return\n elif not dst['is_local']:\n return\n srcname = src.device()['name']+'/'+src['name']\n dstname = dst['name']\n if event == mpr.Graph.Event.NEW:\n if dstname == srcname:\n return\n\n # check if this plot already exists\n match = dev.signals().filter(mpr.Property.NAME, srcname)\n if match:\n print('plot already exists')\n map.release()\n return\n\n vec_len = src[mpr.Property.LENGTH]\n num_inst = src[mpr.Property.NUM_INSTANCES]\n newsig = dev.add_signal(mpr.Direction.INCOMING, srcname, vec_len, mpr.Type.FLOAT,\n None, None, None, num_inst, sig_handler, mpr.Signal.Event.ALL)\n if not newsig:\n print(' error creating signal', srcnamefull)\n return\n\n newsig[mpr.Property.USE_INSTANCES] = True\n newsig[mpr.Property.EPHEMERAL] = True\n\n signals[srcname] = {'sig' : newsig,\n 'vec_len' : vec_len,\n 'vals' : {},\n 'tts' : {},\n 'pens' : [pg.mkPen(color=i, width=3) for i in range(vec_len)],\n 'curves' : {},\n 'label' : 0 }\n mpr.Map(src, newsig).push()\n map.release()\n elif event == mpr.Graph.Event.REMOVED or event == mpr.Graph.Event.EXPIRED:\n if dstname == 'connect_here' or dstname != srcname:\n return\n if dstname in signals:\n print(' freeing local signal', dstname)\n sigs_to_free.append(signals.pop(dstname))\n\ngraph = mpr.Graph()\ngraph.add_callback(on_map, mpr.Type.MAP)\n\ndev = mpr.Device('signal_plotter', graph)\ndummy = dev.add_signal(mpr.Direction.INCOMING, 'connect_here')\n\nclass CloseButton(pg.ButtonItem):\n def __init__(self, parentItem):\n super(CloseButton, self).__init__(pg.icons.getGraphPixmap('auto'), 14, parentItem)\n\n self.setImageFile(icon_path)\n self.setScale(0.1)\n self.setOpacity(1)\n\nclass Plotter(pg.GraphicsLayoutWidget):\n def __init__(self):\n # TODO: pass in graph ref\n super(Plotter, self).__init__(show=True)\n self.setAcceptDrops(True)\n\n def add_plot(self, r, c, label):\n # TODO: pass in signal ref\n plot = self.addPlot(row=r, col=c)\n\n plot.setAxisItems({'bottom': TimeAxisItem(orientation='bottom')})\n plot.closeButton = CloseButton(plot)\n\n plot.showGrid(x=True, y=True)\n plot.setLabel('left', 'value')\n plot.setTitle(label)\n\n # TODO: add map display?\n\n return plot\n\n def remove_plot(self, plot):\n self.removeItem(plot)\n\n def next_row(self):\n self.nextRow()\n\nclass HLine(QtWidgets.QFrame):\n def __init__(self):\n super(HLine, self).__init__()\n self.setFrameShape(QtWidgets.QFrame.HLine)\n self.setFrameShadow(QtWidgets.QFrame.Sunken)\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n\n self.setAcceptDrops(True)\n\n time_label = QtWidgets.QLabel('Time Window:')\n\n time_spinbox = QtWidgets.QSpinBox(self)\n time_spinbox.setRange(1, 60)\n time_spinbox.setValue(10)\n time_spinbox.setSuffix(' seconds')\n time_spinbox.valueChanged.connect(self.update_time)\n\n button_use_2d = QtWidgets.QCheckBox('Draw 2D vectors on canvas', self)\n button_use_2d.stateChanged.connect(self.update_use_2d)\n\n self.plotter = Plotter()\n\n# addBelow = QtWidgets.QPushButton('+', self)\n# addBelow.setStyleSheet(\"font: 22px; border-radius: 5\")\n# addBelow.clicked.connect(self.add_plot_below)\n#\n# addRight = QtWidgets.QPushButton('+', self)\n# addRight.setStyleSheet(\"font: 22px; border-radius: 5\")\n# addRight.clicked.connect(self.add_plot_right)\n\n self.setWindowTitle('libmapper signal plotter')\n\n grid = QtWidgets.QGridLayout()\n grid.setSpacing(10)\n grid.addWidget(time_label, 0, 0, QtCore.Qt.AlignmentFlag.AlignLeft)\n grid.addWidget(time_spinbox, 0, 1, QtCore.Qt.AlignmentFlag.AlignLeft)\n grid.addWidget(button_use_2d, 0, 3, QtCore.Qt.AlignmentFlag.AlignRight)\n grid.addWidget(HLine(), 1, 0, 1, 4)\n grid.addWidget(self.plotter, 2, 0, 1, 4)\n\n grid.setColumnStretch(0, 0)\n grid.setColumnStretch(1, 0)\n grid.setColumnStretch(2, 1)\n grid.setColumnStretch(3, 0)\n grid.setRowStretch(0, 0)\n grid.setRowStretch(1, 0)\n grid.setRowStretch(2, 1)\n\n centralWidget = QtWidgets.QWidget()\n centralWidget.setLayout(grid)\n self.setCentralWidget(centralWidget)\n\n self.timer = QtCore.QTimer()\n self.timer.setInterval(25)\n self.timer.timeout.connect(self.timer_event)\n self.timer.start()\n\n def dragEnterEvent(self, e):\n if e.mimeData().hasFormat(\"text/plain\"):\n e.accept()\n\n def dropEvent(self, e):\n text = e.mimeData().text()\n\n if text.startswith('libmapper://signal '):\n e.setDropAction(QtCore.Qt.CopyAction)\n e.accept()\n\n # try extracting id first\n text = text[19:].split(' @id ')\n if len(text) == 2:\n id = int(text[1])\n print('id:', id)\n s = graph.signals().filter(mpr.Property.ID, id)\n if s:\n s = s.next()\n if s and not s[mpr.Property.IS_LOCAL]:\n print('found signal by id')\n mpr.Map(s, dummy).push()\n return;\n text = text[0]\n\n # fall back to using device and signal names\n names = text.split('/')\n print('names:', names)\n if len(names) != 2:\n print('error retrieving device and signal names')\n return\n\n d = graph.devices().filter(mpr.Property.NAME, names[0])\n if not d:\n print('error: could not find device', names[0])\n return\n s = d.next().signals().filter(mpr.Property.NAME, names[1])\n if not s:\n print('error: could not find signal', names)\n return\n s = s.next()\n if s[mpr.Property.IS_LOCAL]:\n print('error: plotting local signals is not allowed')\n return\n mpr.Map(s, dummy).push()\n\n def update_time(self, value):\n print('updating time window to', value)\n global display_sec\n display_sec = value\n\n def update_use_2d(self, value):\n print('updating use_2d to', value != 0)\n global use_2d\n use_2d = (value != 0)\n\n # TODO: clear and replot if necessary\n# for s in signals:\n# data = signals[s]\n# if data['vec_len'] == 2 and data['plot']:\n# data['plot'].clear()\n# for inst in data['vals']:\n# del data['curves'][inst]\n# data['curves'][inst] = None\n\n def add_plot_below(self):\n print('add plot below!')\n\n def add_plot_right(self):\n print('add plot right!')\n\n def closePlot(self, signame):\n sigs_to_free.append(signals.pop(signame))\n\n def update_graph(self):\n now = mpr.Time().get_double()\n then = now - display_sec # 10 seconds ago\n for s in signals:\n data = signals[s]\n\n if 'plot' in data:\n plot = data['plot']\n else:\n plot = self.plotter.add_plot(self.plotter.next_row(), 0, data['sig'][mpr.Property.NAME])\n plot.closeButton.clicked.connect(lambda: self.closePlot(s))\n data['plot'] = plot\n\n if not len (data['vals']):\n # no active instances? remove this?\n continue\n\n updated = False\n for inst in data['vals']:\n tts = data['tts'][inst]\n vals = data['vals'][inst]\n vec_len = data['vec_len']\n\n # pop samples older than window\n # TODO: use numpy to handle instances, vectors?\n to_pop = 0\n for tt in tts:\n if tt > (then - 1):\n break\n to_pop += 1\n for el in range(vec_len):\n for j in range(to_pop):\n vals[el].popleft()\n for j in range(to_pop):\n tts.popleft()\n\n if not len(tts):\n continue\n\n if signals[s]['curves'][inst] == None:\n if vec_len == 2 and use_2d == True:\n signals[s]['curves'][inst] = [plot.plot(vals[0], vals[1], pen=pg.mkPen(color=inst, width=3), connect='finite')]\n else:\n signals[s]['curves'][inst] = [plot.plot(tts, vals[el], pen=pg.mkPen(color=inst*el+el, width=3), connect='finite') for el in range(vec_len)]\n else:\n if vec_len == 2 and use_2d == True:\n signals[s]['curves'][inst][0].setData(vals[0], vals[1], connect='finite')\n else:\n for el in range(vec_len):\n signals[s]['curves'][inst][el].setData(tts, vals[el], connect='finite')\n updated = True\n\n if vec_len != 2 or use_2d == False:\n plot.setXRange(then, now)\n elif not updated:\n signals[s]['plot'].clear()\n\n def timer_event(self):\n dev.poll(10)\n\n while len(sigs_to_free):\n var = sigs_to_free.pop()\n self.plotter.remove_plot(var['plot'])\n dev.remove_signal(var['sig'])\n\n if len(signals):\n self.update_graph()\n\ndef remove_dev():\n global dev\n dev.free()\n\nimport atexit\natexit.register(remove_dev)\n\napp = QtWidgets.QApplication(sys.argv)\nmain = MainWindow()\nmain.show()\napp.exec()\n","sub_path":"visualisation/pySignalPlotter/pySignalPlotter.py","file_name":"pySignalPlotter.py","file_ext":"py","file_size_in_byte":11880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"577539837","text":"import matplotlib.pyplot as plt\nimport pandas as pd #impordin pandas andmetöötluslibrary\nfrom easygui import * #toon easygui sisse, et ei peaks konsooli jälgima\n\ndef taienda_tabelit(andmedfail): #defineerin tabelitäiendusfunktsiooni esimesena, sest teda on vaja kasutada järgmise funktsiooni sees\n eemaldatud = andmedfail.pop('2012') #viskan veeru(kolonni) 2012 minema, tegelikult salvestub argumendina \"eemaldatud\" alla\n andmedfail['Keskmine'] = andmedfail.mean(axis=1) #kasutan üldist käsklust, et ridade (rows) keskmised võtta mean() funktsiooniga ja panna uue \"keskmine\" veeru alla\n return andmedfail #tagastan muudetud andmedfaili, et kasutada edasi funktsioonis raamatukogud()\ndef raamatukogud(andmed): #kasutan argumendiga andmete failinime sisaldavat muutujat, et töödelda andmeid seal sees\n andmedfail = pd.read_csv(andmed, delimiter=';', index_col=' ') #loeme pandasesse sisse andmed, eeldades, et nad on eraldatud semikooloni \";\"-ga. indexcol muudab\n #esimese veeru rea pealkirjadeks.\n andmedfail = pd.DataFrame(andmedfail) #muudame need andmed dataFrameks, et töödelda paremini Pandase käsklustega\n taienda_tabelit(andmedfail) #rakendame täiendusfunktsiooni, argumendina dataFrame (\"andmeFreim\")\n print(andmedfail) #printisime lihtsalt et kontrollida andmeid\n #andmedfail.to_csv(andmed.strip('.csv') + '_uus.csv', sep=';', encoding='utf-8') #salvestame faili uuena, kasutades andmete failinime algset kuju ja lisades\n #_uus sinna juurde, endiselt eraldades \";\"-ga\n print(andmedfail) #prindime et kontrollida\n andmedfail = andmedfail.cumsum()\n\n andmedfail.plot()\n plt.show()\n \nraamatukogud(\"raamatukogud.csv\")","sub_path":"LTAT.TK.001_yl_5.3_raamatukogud_Pandas_dataframe_esitus.py","file_name":"LTAT.TK.001_yl_5.3_raamatukogud_Pandas_dataframe_esitus.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"529816580","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 11 01:32:44 2019\r\n\r\n@author: Ankit Goyal\r\n\"\"\"\r\nimport pandas as pd\r\nfrom sklearn.cluster import KMeans\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\nfrom keras.models import Sequential\r\nfrom IPython.display import Image\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler \r\nfrom sklearn.externals.six import StringIO \r\nfrom sklearn.tree import export_graphviz\r\nimport pydotplus\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom matplotlib.legend_handler import HandlerLine2D\r\nfrom sklearn import tree\r\nfrom keras.layers import Dense\r\nimport numpy as np\r\nimport os\r\nimport time\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom sklearn import preprocessing\r\nfrom sklearn.neural_network import MLPClassifier\r\n\r\n\r\n\r\n\r\n\r\nos.getcwd()\r\nos.chdir('C:/Users/Ankit Goyal/Desktop/OMSCS program/Pre-Reqs_Data_Science/Course ML/Assignment 1/Dataset/nba')\r\ndata=pd.read_csv('nba.csv')\r\ndata=data.dropna()\r\nprint(data.info())\r\nfields_to_drop=['TARGET_5Yrs','Name']\r\nX = data.drop(fields_to_drop,axis=1)\r\ny = data['TARGET_5Yrs']\r\ny.index=range(len(y))\r\n#X=pd.DataFrame(X) \r\n#min_max_scaler = preprocessing.MinMaxScaler()\r\n#np_scaled = min_max_scaler.fit_transform(X)\r\n#X = pd.DataFrame(np_scaled)\r\n#y.index=range(len(y))\r\n\r\n\r\n\r\n#print(kmeans.score(X))\r\ndef matchfn(y_true,y_pred):\r\n s=0\r\n for i in range(len(y_true)):\r\n if (y_true[i]==y_pred[i]):\r\n s=s+1\r\n else:\r\n s=s\r\n return s/len(y_pred)\r\ndef elbow_curve():\r\n Sum_of_squared_distances = []\r\n K = range(1,15)\r\n for k in K:\r\n km = KMeans(n_clusters=k)\r\n km = km.fit(X)\r\n Sum_of_squared_distances.append(km.inertia_)\r\n plt.plot(K, Sum_of_squared_distances, 'bx-',marker='o')\r\n plt.xlabel('k')\r\n plt.ylabel('Sum_of_squared_distances')\r\n plt.title('Elbow curve Optimal k')\r\n plt.show()\r\n return None\r\n \r\nelbow_curve() \r\n\r\nprint(X.head())\r\nkmeans = KMeans(n_clusters=4, random_state=0,max_iter=10000,tol=1e-5).fit(X)\r\nans=kmeans.predict(X)\r\nprint(matchfn(y,ans)) \r\n#print(X[ans==0][0])\r\nfig = plt.figure()\r\nax = Axes3D(fig)\r\nax.scatter(X[ans==0]['MIN'],X[ans==0]['FGM'],X[ans==0]['FG%'],label='Class1',c='red') \r\nax.scatter(X[ans==1]['MIN'],X[ans==1]['FGM'],X[ans==1]['FG%'],label='Class2',c='blue')\r\nax.scatter(X[ans==2]['MIN'],X[ans==2]['FGM'],X[ans==2]['FG%'],label='Class2',c='green') \r\nax.scatter(X[ans==3]['MIN'],X[ans==3]['FGM'],X[ans==3]['FG%'],label='Class2',c='orange') \r\n\r\n\r\n#ax.scatter(X[ans==2][0],X[ans==2][6],X[ans==2][27],label='Class2',c='green') \r\nax.set_xlabel('1')\r\nax.set_ylabel('3')\r\nax.set_zlabel('5')\r\n\r\n#ax.legend()\r\nplt.show()\r\n\r\nplt.scatter(X[ans==0]['MIN'],X[ans==0]['FGM'],label='Class1',c='red') \r\nplt.scatter(X[ans==1]['MIN'],X[ans==1]['FGM'],label='Class2',c='blue')\r\nplt.scatter(X[ans==2]['MIN'],X[ans==2]['FGM'],label='Class2',c='green') \r\nplt.scatter(X[ans==3]['MIN'],X[ans==3]['FGM'],label='Class2',c='orange') \r\n\r\nplt.xlabel('3')\r\nplt.ylabel('5')\r\n#print(X.head())\r\nplt.show()\r\n\r\ndef components(K):\r\n Sum_of_squared_distances = []\r\n k=[]\r\n accuracy_train=[]\r\n accuracy_test=[]\r\n score=[]\r\n for i in range(1,K):\r\n print(i)\r\n agglo=KMeans(n_clusters=i)\r\n #X_new_train,y_new_train=transformer.fit(X_train,y_train) \r\n #X_new_test,y_new_test = transformer.transform(X_test,y_test)\r\n agglo.fit(X)\r\n X_reduced=agglo.transform(X)\r\n X_train, X_test, y_train, y_test = train_test_split(X_reduced, y, test_size=0.20)\r\n km =MLPClassifier(solver='lbfgs',alpha=1e-5,hidden_layer_sizes=[8,8,8,8,8],random_state=1)\r\n km.fit(X_train,y_train)\r\n km.fit(X_test,y_test)\r\n #transformer1 = GaussianRandomProjection(n_components=i,eps=0.5)\r\n #transformer2 = GaussianRandomProjection(n_compo\r\n label_train=km.predict(X_train)\r\n label_test=km.predict(X_test)\r\n accu_train=km.score(X_test,y_test)\r\n accu_test=km.score(X_train,y_train)\r\n #score_train1=metrics.silhouette_score(X_new,label, metric='euclidean')\r\n #Sum_of_squared_distances.append(km.inenents=i,eps=0.6) \r\n #label=transformer.predicn)rtia_)\r\n k.append(i)\r\n accuracy_train.append(accu_train)\r\n accuracy_test.append(accu_test)\r\n #score.append(score_train1)\r\n #print(accuracy)\r\n k=np.array(k)\r\n Sum_of_squared_distances=np.array(Sum_of_squared_distances)\r\n score=np.array(score)\r\n accuracy_train=np.array(accuracy_train)\r\n accuracy_test=np.asarray(accuracy_test)\r\n #line1,=plt.plot(k, Sum_of_squared_distances, 'bx-',marker='o')\r\n #line2,=plt.plot(k,score,color='g',marker='o')\r\n line3,=plt.plot(k,accuracy_train,color='r',marker='o',label='train_accuracy')\r\n line4,=plt.plot(k,accuracy_test,color='g',marker='o',label='test_accuracy')\r\n #plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)})\r\n plt.xlabel('k')\r\n plt.legend()\r\n plt.ylabel('accuracy')\r\n #plt.ylim(0,1)\r\n plt.show()\r\n return None\r\n\r\ncomponents(14)\r\n","sub_path":"K means cluseter_nba.py","file_name":"K means cluseter_nba.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"263816931","text":"from __future__ import print_function, division, absolute_import\n\nfrom contextlib import contextmanager\nfrom multiprocessing import Process\nimport socket\n\nfrom distributed.core import connect_sync, write_sync, read_sync\nfrom distributed.utils import ignoring\n\n\ndef inc(x):\n return x + 1\n\n\ndef run_center(port):\n from distributed import Center\n from tornado.ioloop import IOLoop\n import logging\n logging.getLogger(\"tornado\").setLevel(logging.CRITICAL)\n center = Center('127.0.0.1', port)\n center.listen(port)\n IOLoop.current().start()\n IOLoop.current().close() # Never reached. TODO: clean shutdown of IOLoop\n\n\ndef run_worker(port, center_port, **kwargs):\n from distributed import Worker\n from tornado.ioloop import IOLoop\n import logging\n logging.getLogger(\"tornado\").setLevel(logging.CRITICAL)\n worker = Worker('127.0.0.1', port, '127.0.0.1', center_port, **kwargs)\n worker.start()\n IOLoop.current().start()\n IOLoop.current().close() # Never reached. TODO: clean shutdown of IOLoop\n\n\n_port = [8010]\n\n@contextmanager\ndef cluster(nworkers=2):\n _port[0] += 1\n cport = _port[0]\n center = Process(target=run_center, args=(cport,))\n workers = []\n for i in range(nworkers):\n _port[0] += 1\n port = _port[0]\n proc = Process(target=run_worker, args=(port, cport), kwargs={'ncores': 1})\n workers.append({'port': port, 'proc': proc})\n\n center.start()\n for worker in workers:\n worker['proc'].start()\n\n sock = connect_sync('127.0.0.1', cport)\n while True:\n write_sync(sock, {'op': 'ncores'})\n ncores = read_sync(sock)\n if len(ncores) == nworkers:\n break\n\n try:\n yield {'proc': center, 'port': cport}, workers\n finally:\n for port in [cport] + [w['port'] for w in workers]:\n with ignoring(socket.error):\n sock = connect_sync('127.0.0.1', port)\n write_sync(sock, dict(op='terminate', close=True))\n response = read_sync(sock)\n sock.close()\n for proc in [center] + [w['proc'] for w in workers]:\n with ignoring(Exception):\n proc.terminate()\n\n\nimport pytest\nslow = pytest.mark.skipif(\n not pytest.config.getoption(\"--runslow\"),\n reason=\"need --runslow option to run\")\n\n\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\n\ndef _test_cluster(f):\n from .center import Center\n from .worker import Worker\n @gen.coroutine\n def g():\n c = Center('127.0.0.1', 8017)\n c.listen(c.port)\n a = Worker('127.0.0.2', 8018, c.ip, c.port, ncores=2)\n yield a._start()\n b = Worker('127.0.0.3', 8019, c.ip, c.port, ncores=1)\n yield b._start()\n\n while len(c.ncores) < 2:\n yield gen.sleep(0.01)\n\n try:\n yield f(c, a, b)\n finally:\n with ignoring():\n yield a._close()\n with ignoring():\n yield b._close()\n c.stop()\n\n IOLoop.current().run_sync(g)\n","sub_path":"distributed/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"512447091","text":"from definitions.ir.dfg_node import *\n\nclass Cat(DFGNode):\n def __init__(self, inputs, outputs, com_name, com_category,\n com_options = [], com_redirs = [], com_assignments=[]):\n assert(str(com_name) == \"cat\")\n assert(com_category == \"stateless\")\n super().__init__(inputs, outputs, com_name, com_category,\n com_options=com_options, \n com_redirs=com_redirs, \n com_assignments=com_assignments)\n\ndef make_cat_node(inputs, output):\n com_name = Arg(string_to_argument(\"cat\"))\n com_category = \"stateless\"\n return Cat(inputs,\n [output],\n com_name, \n com_category)\n","sub_path":"compiler/definitions/ir/nodes/cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"386532304","text":"from prefect import task\n\n\n@task\ndef extract():\n \"\"\"Get a list of data\"\"\"\n return [1, 2, 3]\n\n\n@task\ndef transform(data):\n \"\"\"Multiply the input by 10\"\"\"\n return [i * 10 for i in data]\n\n\n@task\ndef load(data):\n \"\"\"Print the data to indicate it was received\"\"\"\n import prefect\n logger = prefect.context.get(\"logger\")\n logger.info(\"Here\")\n print(\"Here's your data: {}\".format(data))\n\n\nfrom prefect import Flow\n\nwith Flow(\"ETL\") as flow:\n e = extract()\n t = transform(e)\n l = load(t)\n\nfrom prefect.engine.executors import DaskExecutor\n\n# from dask.distributed import LocalCluster\n# cluster = LocalCluster()\n\nexecutor = DaskExecutor(address=\"localhost:8786\")\nflow.run(executor=executor)","sub_path":"etl_dask.py","file_name":"etl_dask.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"335692012","text":"import logging\nimport os\nimport uuid\n\nfrom django.conf import settings\nfrom django.core.files.storage import default_storage\nfrom django.forms.widgets import ClearableFileInput\nfrom django.utils.functional import cached_property\n\nlogger = logging.getLogger('s3file')\n\n\nclass S3FileInputMixin:\n \"\"\"FileInput that uses JavaScript to directly upload to Amazon S3.\"\"\"\n\n needs_multipart_form = False\n upload_path = getattr(settings, 'S3FILE_UPLOAD_PATH', os.path.join('tmp', 's3file'))\n expires = settings.SESSION_COOKIE_AGE\n\n @property\n def bucket_name(self):\n return default_storage.bucket.name\n\n @property\n def client(self):\n return default_storage.connection.meta.client\n\n def build_attrs(self, *args, **kwargs):\n attrs = super().build_attrs(*args, **kwargs)\n\n accept = attrs.get('accept')\n response = self.client.generate_presigned_post(\n self.bucket_name, os.path.join(self.upload_folder, '${filename}'),\n Conditions=self.get_conditions(accept),\n ExpiresIn=self.expires,\n )\n\n defaults = {\n 'data-fields-%s' % key: value\n for key, value in response['fields'].items()\n }\n defaults['data-url'] = response['url']\n defaults.update(attrs)\n\n try:\n defaults['class'] += ' s3file'\n except KeyError:\n defaults['class'] = 's3file'\n return defaults\n\n def get_conditions(self, accept):\n conditions = [\n {\"bucket\": self.bucket_name},\n [\"starts-with\", \"$key\", self.upload_folder],\n {\"success_action_status\": \"201\"},\n ]\n if accept:\n accept = accept.replace(' ', '') # remove whitespaces\n mime_types = accept.split(',') if accept else [] # catch empty string\n for mime_type in mime_types:\n top_type, sub_type = mime_type.split('/', 1)\n if sub_type == '*':\n conditions.append([\"starts-with\", \"$Content-Type\", \"%s/\" % top_type])\n else:\n conditions.append({\"Content-Type\": mime_type})\n else:\n conditions.append([\"starts-with\", \"$Content-Type\", \"\"])\n\n return conditions\n\n @cached_property\n def upload_folder(self):\n return os.path.join(\n self.upload_path,\n uuid.uuid4().hex,\n )\n\n class Media:\n js = (\n 's3file/js/s3file.js',\n )\n","sub_path":"s3file/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"15644405","text":"#from Grille import *\r\nimport Entity.Hero as mHero\r\nimport Entity.Ennemis as mEnnemis\r\n\r\nclass tire:\r\n\r\n def __init__(self, hero):\r\n #Constructeur\r\n self.posX = hero.posX#Position en X du héro.\r\n self.posY = hero.posY#Position en Y du héro.\r\n self.posXTire = 0#Position en X du tire.\r\n self.posYTire = 0#Position en Y du tire.\r\n\r\n def tirer(self, maGrille):\r\n self.posXTire = self.posX - 1 #Défini la position en X du tire.\r\n self.posYTire = self.posY#Défini la postion en Y du tire.\r\n maGrille.grid[self.posXTire][self.posYTire] = \"|\"#Place le tire.\r\n\r\n def tire(self, maGrille, ennemis):\r\n #Si le tire dépasse la hauteur de la grille il vaut \"-\".\r\n if self.posXTire == 0:\r\n maGrille.grid[self.posXTire][self.posYTire] = \"-\"#Remplace l'ancienne position par un nul.\r\n\r\n #Si le tire touche un \"0\" alors la position du tire vaut désormais la position du zéro et le tire disparrait.\r\n #Il est remplacé par un \"-\"\r\n\r\n if self.posXTire == ennemis.posX:\r\n ennemis.posX = \"-\"\r\n self.posXTire += 1#Décremente la position actuelle.\r\n maGrille.grid[self.posXTire][self.posYTire] = \"-\"#Remplace l'ancienne position par un nul.\r\n\r\n #Déroule le tire correctement.\r\n else:\r\n maGrille.grid[self.posXTire][self.posYTire] = \"-\"#Remplace l'ancienne position par un nul.\r\n self.posXTire -= 1#Décremente la position actuelle.\r\n maGrille.grid[self.posXTire][self.posYTire] = \"|\"#Réajuste la position du tire.\r\n def collision(lTires, lEnnemis): #Test de collision, si oui on remplace l'objet par une chaine \"del\"\r\n for Tir in lTires:#On parcours pour tout les tir\r\n for Enn in lEnnemis:\r\n #if Tir isinstance (Tire,tire) and Enn isinstance (mEnnemis,ennemis):\r\n if tir.posXTire == shoot.posX:\r\n if tir.posY + 1 == enn.posY:\r\n enn,tir = \"del\"\r\n if \"del\" in lEnnemis:#On test dans une liste OU l'autre car dans tous les cas si on a un \"del\", il y en aura forcement un dans l'autre\r\n supress_del(lTires)# On pourra réduire le mot del par la suite ou le garde en exclu.\r\n supress_del(lEnnemis)\r\n\r\n def supress_del(liste): #Suprime tout les del de la liste\r\n liste = [i for i in liste if i != \"del\"]\r\n\r\n\r\n#OPTIMISER LE CODE TIRE/COLLISION/SUPRESS_DEL\r\n","sub_path":"aubry_ragot_diallo_berthier/aubry_ragot_diallo_berthier/branches/Tire.py","file_name":"Tire.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"91383746","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.utils import resample\n\nfrom feature_builder import build_features\nfrom utils import load_config\n\n\ndef select_feats(df):\n \"\"\"\n Select features based on configuration\n \"\"\"\n cols = list(df)\n for col in cols:\n if col not in config[\"feats\"] and col != \"label\":\n df = df.drop(columns=col)\n return df\n\n\ndef resample_train(df):\n \"\"\"\n Resample training data\n \"\"\"\n # Separate majority and minority classes\n df_agree = df[df.label == \"agree\"]\n df_disagree = df[df.label == \"disagree\"]\n df_discuss = df[df.label == \"discuss\"]\n df_unrelated = df[df.label == \"unrelated\"]\n\n # Upsample \"disagree\"\n n = round(len(df_agree) / 2)\n df_disagree_up = resample(df_disagree, replace=True, n_samples=n)\n\n # Combine original and resampled data\n df_up = pd.concat([\n df_agree,\n df_disagree_up,\n df_discuss,\n df_unrelated,\n ])\n print(df_up.label.value_counts())\n return df_up\n\n\ndef train():\n \"\"\"\n Train XGBoost classifier\n \"\"\"\n # Load and select training features\n train_df = pd.read_csv(config[\"train_feats\"])\n train_df = select_feats(train_df)\n\n # Resample training data\n train_df = resample_train(train_df)\n\n # Split features and labels\n X_train, y_train = np.split(train_df, [-1], axis=1)\n # Encode labels\n y_train = le.transform(y_train.as_matrix())\n # Build DMatrix\n dtrain = xgb.DMatrix(X_train.as_matrix(), label=y_train)\n\n # Hyperparameter settings\n params = {\n \"learning_rate\": 0.019,\n \"n_estimators\": 1000,\n \"max_depth\": 7,\n \"min_child_weight\": 1,\n \"gamma\": 0.4,\n \"subsample\": 0.9,\n \"colsample_bytree\": 0.9,\n \"scale_pos_weight\": 1,\n \"objective\": \"multi:softprob\",\n \"num_class\": 4,\n }\n\n # Train model\n model = xgb.train(params, dtrain, 20)\n return model\n\n\ndef main(rebuild_features=False):\n \"\"\"\n Run 1-stage classifier\n \"\"\"\n global config\n config = load_config()\n\n global le\n le = LabelEncoder()\n # Fit labels\n le.fit([\"agree\", \"disagree\", \"discuss\", \"unrelated\"])\n\n # Build features\n if rebuild_features:\n for split in (\"train\", \"test\"):\n build_features(split, config)\n\n # Train model\n model = train()\n\n # Load and select testing features\n test_df = pd.read_csv(config[\"test_feats\"])\n test_df = select_feats(test_df)\n\n # Split features and labels\n X_test, y_test = np.split(test_df, [-1], axis=1)\n # Encode labels\n y_test = le.transform(y_test.as_matrix())\n # Build DMatrix\n dtest = xgb.DMatrix(X_test.as_matrix(), label=y_test)\n\n # Get predictions\n pred = model.predict(dtest).argmax(axis=1)\n # Decode labels\n pred_labels = le.inverse_transform(pred)\n\n # Load unlabeled test set\n df = pd.read_csv(config[\"test_unlabeled\"])\n\n # Write output file\n assert(len(df) == len(pred_labels))\n df[\"Stance\"] = pred_labels\n df.to_csv(\"predictions.1stage.csv\", index=False)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/run_1stage.py","file_name":"run_1stage.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"29043567","text":"import tensorflow as tf\na = tf.placeholder(tf.int16) #占位符\nb = tf.placeholder(tf.int16)\nadd = tf.add(a, b)\nmul = tf.multiply(a, b)\nwith tf.Session() as sess:\n #计算\n print(\"add: %i\" % sess.run(add, feed_dict = {a: 3, b: 4}))\n print(\"multiply: %i\" % sess.run(mul, feed_dict = {a: 3, b: 4}))\n\n print(sess.run([mul, add], feed_dict = {a: 3, b: 4}))\n","sub_path":"withsession_feed.py","file_name":"withsession_feed.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"128594012","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.6-i386/egg/Products/LinguaFace/events/handlers.py\n# Compiled at: 2010-11-30 09:59:25\nfrom urllib import quote, unquote\nfrom OFS import Moniker\nfrom zlib import compress, decompress\nfrom marshal import loads, dumps\nfrom OFS.CopySupport import CopyContainer\nfrom Products.CMFPlone.interfaces.Translatable import ITranslatable\nfrom Products.CMFPlone.utils import base_hasattr\nmanage_pasteObjects = CopyContainer.manage_pasteObjects\n\ndef _cb_encode(d):\n return quote(compress(dumps(d), 9))\n\n\ndef _cb_decode(s):\n return loads(decompress(unquote(s)))\n\n\ndef objectCopiedEvent(object, event=None):\n \"\"\" Is used to pass the original object to objectClonedEvent.\n \"\"\"\n ob = object.object\n ob.original = object.original\n\n\ndef objectClonedEvent(object, event=None):\n \"\"\" This event is notified during the manage_pasteObjects and is used in\n in order to copy all the translations of an object at once.\n \"\"\"\n ob = object.object\n orig_ob = ob.original\n del ob.original\n if base_hasattr(ob, '_first_object_to_paste'):\n orig_ob._first_object_to_paste._copy[orig_ob] = ob\n del orig_ob._first_object_to_paste\n del ob._first_object_to_paste\n elif base_hasattr(ob, 'getOtherTranslations'):\n ob._copy = {}\n ob._copy[orig_ob] = ob\n oblist = orig_ob.getOtherTranslations()\n for object in oblist:\n object._first_object_to_paste = ob\n\n new_oblist = []\n for object in oblist:\n m = Moniker.Moniker(object)\n new_oblist.append(m.dump())\n\n oblist = new_oblist\n cb_copy_data = _cb_encode((0, oblist))\n manage_pasteObjects(ob.aq_parent, cb_copy_data)\n copy = ob._copy\n del ob._copy\n for translation in copy:\n if not translation.isCanonical():\n copy[translation].addTranslationReference(copy[translation.getCanonical()])\n\n\ndef objectMovedEvent(object, event=None):\n \"\"\" This event is notified during the manage_pasteObjects and is used in\n in order to cut/paste all the translations of an object at once.\n \"\"\"\n ob = object.object\n oldParent = object.oldParent\n oldName = object.oldName\n newParent = object.newParent\n newName = object.newName\n dont_move = False\n if base_hasattr(newParent, '_v__dont_move_translations__'):\n dont_move = True\n if oldParent == None and oldName == None:\n return\n if newName == None and newParent == None:\n return\n if oldParent == newParent:\n return\n if base_hasattr(ob, '_v__translation_to_remove__'):\n del ob._v__translation_to_remove__\n return\n if base_hasattr(ob, 'getOtherTranslations') and not dont_move:\n oblist = ob.getOtherTranslations()\n for object in oblist:\n object._v__translation_to_remove__ = False\n\n new_oblist = []\n for object in oblist:\n m = Moniker.Moniker(object)\n new_oblist.append(m.dump())\n\n oblist = new_oblist\n cb_copy_data = _cb_encode((1, oblist))\n manage_pasteObjects(newParent, cb_copy_data)\n return\n\n\ndef objectWillBeRemovedEvent(object, event=None):\n \"\"\"This handler is called before deleting object\"\"\"\n if not ITranslatable.isImplementedBy(object):\n return\n if not object.isCanonical():\n return\n object._v_translations = object.getTranslations()\n\n\ndef objectRemovedEvent(object, event=None):\n \"\"\"This handler is called after object has been deleted\"\"\"\n if not ITranslatable.isImplementedBy(object):\n return\n translations = getattr(object, '_v_translations', {})\n if not translations:\n return\n for (lang, value) in translations.items():\n translation = value[0]\n if translation is object:\n continue\n translation.reindexObject(idxs=['getCanonicalPath'])\n\n delattr(object, '_v_translations')","sub_path":"pycfiles/Products.LinguaFace-3.0.0-py2.4/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"360891608","text":"# For the following list of numbers:\n\nnumbers = [1, 6, 2, 2, 7, 1, 6, 13, 99, 7]\n\n# 1. Print out a list of the even integers:\n\nfor num in numbers:\n if num % 2 == 0:\n print(num)\n\n\n\n# 2. Print the difference between the largest and smallest value:\n\nnumbers.sort()\nprint(numbers[-1] - numbers[0])\n\n# 3. Print True if the list contains a 2 next to a 2 somewhere.\n# def has22(nums):\n# for x in range(0, len(nums) - 1, 1):\n# if (nums[x] == 2) and (nums[x + 1] == 2):\n# return True\n# return False\n\n\n# for i in range(0, len(numbers) - 1, 1):\n# if (numbers[i] == 2) and (numbers[i + 1] == 2):\n# print(True)\n\nresult = False\nindex = 0\nfor number in numbers:\n if (number == 2 and numbers[index-1] == 2):\n result = True\n index +=1\nprint(result)\n\n\n\n# 4. Print the sum of the numbers, \n# BUT ignore any section of numbers starting with a 6 and extending to the next 7.\n# \n# So [11, 6, 4, 99, 7, 11] would have sum of 22\n\ntotal = 0\nfound_6 = False\nfor number in numbers:\n if number == 6:\n found_6 = True\n elif found_6:\n if number == 7:\n found_6 = False\n else:\n total += number\nprint(number)\n\n\n# 5. HARD! Print the sum of the numbers. \n# Except the number 13 is very unlucky, so it does not count.\n# And numbers that come immediately after a 13 also do not count.\n# HINT - You will need to track the index throughout the loop.\n#\n# So [5, 13, 2] would have sum of 5. \n\nindex = 0\ntotal = 0\nfor number in numbers:\n if number == 13 or numbers[index-1] == 13:\n pass\n else:\n total += number\n index += 1\nprint(total)\n\n\n\n\n\n\n\n\n","sub_path":"start_point/extension_loops.py","file_name":"extension_loops.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"49389614","text":"\nimport pymongo as pymongo\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import ScalarFormatter\nimport gridfs\nimport io\nimport os\nimport logging\nimport json\nimport math\nimport requests\nimport time\nimport numpy as np\nimport pandas as pd\nfrom .functions_Universal_v3 import parse_headers\n\nlogger = logging.getLogger(\"nta_app.ms1\")\nlogger.setLevel(logging.INFO)\n\nDSSTOX_API = os.environ.get('UBERTOOL_REST_SERVER')\n#DSSTOX_API = 'http://127.0.0.1:7777'\n\n\ndef connect_to_mongoDB(address):\n mongo = pymongo.MongoClient(host=address)\n mongo_db = mongo['nta_runs']\n mongo.nta_runs.Collection.create_index([(\"date\", pymongo.DESCENDING)], expireAfterSeconds=86400)\n # ALL entries into mongo.nta_runs must have datetime.utcnow() timestamp, which is used to delete the record after 86400\n # seconds, 24 hours.\n return mongo_db\n\n\ndef connect_to_mongo_gridfs(address):\n db = pymongo.MongoClient(host=address).nta_storage\n print(\"Connecting to mongodb at {}\".format(address))\n fs = gridfs.GridFS(db)\n return fs\n\n# function to remove columns from a given dataframe, df_in. The columns to be removed are determined by the\n# a given list of strings.\ndef remove_columns(df_in, list_of_columns2remove):\n df = df_in.copy()\n df.drop(list_of_columns2remove, axis=1, inplace=True)\n return df\n\ndef reduced_file(df_in):\n df = df_in.copy()\n headers = parse_headers(df, 0)\n keeps_str = ['MB_', 'blank', 'blanks', 'BLANK', 'Blank', 'Median', 'Sub']\n to_drop = [item for sublist in headers for item in sublist if\n (len(sublist) > 1) & (not any(x in item for x in keeps_str))]\n to_drop.extend(df.columns[(df.columns.str.contains(pat ='CV_|N_Abun_|Mean_|STD_')==True)].tolist())\n to_drop.extend(df.columns[(df.columns.str.contains(pat ='Median_') == True) &\n (df.columns.str.contains(pat ='MB|blank|blanks|BLANK|Blank|Sub')==False)].tolist())\n if 'Median_ALLMB' in df.columns.values.tolist():\n to_drop.extend(['Median_ALLMB'])\n df.drop(to_drop, axis=1, inplace=True)\n return df\n\ndef response_log_wrapper(api_name:str):\n def api_log_decorator(request_func):\n def wrapper(*args, **kwargs):\n logger.info(f\"============ calling REST API: {api_name}\" )\n start_time = time.perf_counter()\n response = request_func(*args, **kwargs)\n logger.info(f\"Response: {response} Run time: {time.perf_counter() - start_time}\")\n return response\n return wrapper\n return api_log_decorator\n\n@response_log_wrapper('DSSTOX')\ndef api_search_masses(masses, accuracy, jobid = \"00000\"):\n input_json = json.dumps({\"search_by\": \"mass\", \"query\": masses, \"accuracy\": accuracy}) # assumes ppm\n #if \"edap-cluster\" in DSSTOX_API:\n api_url = '{}/rest/ms1/batch/{}'.format(DSSTOX_API, jobid)\n #else:\n # api_url = '{}/nta/rest/ms1/batch/{}'.format(DSSTOX_API, jobid)\n logger.info(api_url)\n http_headers = {'Content-Type': 'application/json'}\n return requests.post(api_url, headers=http_headers, data=input_json)\n\ndef api_search_masses_batch(masses, accuracy, batchsize = 50, jobid = \"00000\"):\n n_masses = len(masses)\n logging.info(\"Sending {} masses in batches of {}\".format(n_masses, batchsize))\n i = 0\n while i < n_masses:\n end = i + batchsize-1\n if end > n_masses-1:\n end = n_masses-1\n response = api_search_masses(masses[i:end+1], accuracy, jobid)\n dsstox_search_json = io.StringIO(json.dumps(response.json()['results']))\n if i == 0:\n dsstox_search_df = pd.read_json(dsstox_search_json, orient='split',\n dtype={'TOXCAST_NUMBER_OF_ASSAYS/TOTAL': 'object'})\n else:\n new_search_df = pd.read_json(dsstox_search_json, orient='split',\n dtype={'TOXCAST_NUMBER_OF_ASSAYS/TOTAL': 'object'})\n dsstox_search_df = pd.concat([dsstox_search_df, new_search_df], ignore_index = True) #Added ignore index, may not be needed 11/2 MWB\n i = i + batchsize\n \n return dsstox_search_df\n\n@response_log_wrapper('DSSTOX')\ndef api_search_formulas(formulas, jobID = \"00000\"):\n input_json = json.dumps({\"search_by\": \"formula\", \"query\": formulas}) # assumes ppm\n if \"edap-cluster\" in DSSTOX_API:\n api_url = '{}/rest/ms1/batch/{}'.format(DSSTOX_API, jobID)\n else:\n api_url = '{}/nta/rest/ms1/batch/{}'.format(DSSTOX_API, jobID)\n logger.info(api_url)\n http_headers = {'Content-Type': 'application/json'}\n return requests.post(api_url, headers=http_headers, data=input_json)\n\n@response_log_wrapper('HCD')\ndef api_search_hcd(dtxsid_list):\n post_data = {\"chemicals\":[], \"options\": {\"cts\": None, \"minSimilarity\": 0.95, \"analogsSearchType\": None}}\n headers = {'content-type': 'application/json'}\n url = 'https://hazard.sciencedataexperts.com/api/hazard'\n for dtxsid in dtxsid_list: \n post_data['chemicals'].append({'chemical': {'sid': dtxsid, \"checked\": True}, \"properties\": {}})\n return requests.post(url, data=json.dumps(post_data), headers=headers)\n \ndef batch_search_hcd(dtxsid_list, batchsize = 150):\n result_dict = {}\n logger.info(f\"Search {len(dtxsid_list)} DTXSIDs in HCD\")\n for i in range(0, len(dtxsid_list), batchsize):\n logger.info(f\"HCD Query: {i//batchsize} of {len(dtxsid_list)//batchsize} batches\")\n response = api_search_hcd(dtxsid_list[i:i+batchsize])\n chem_data_list = json.loads(response.content)['hazardChemicals']\n for chemical in chem_data_list:\n chemical_id = chemical['chemicalId'].split('|')[0]\n result_dict[chemical_id] = {}\n for data in chemical['scores']:\n result_dict[chemical_id][f'{data[\"hazardName\"]}_score'] = data['finalScore']\n result_dict[chemical_id][f'{data[\"hazardName\"]}_authority'] = data['finalAuthority'] if 'finalAuthority' in data.keys() else ''\n return pd.DataFrame(result_dict).transpose().reset_index().rename(columns = {'index':'DTXSID'})\n\ndef format_tracer_file(df_in):\n df = df_in.copy()\n df = df.drop(columns=['Compound', 'Score'])\n rt_diff = df['Observed_Retention_Time'] - df['Retention_Time']\n mass_diff = ((df['Observed_Mass'] - df['Monoisotopic_Mass']) / df['Monoisotopic_Mass']) * 1000000\n df.insert(7, 'Mass_Error_PPM', mass_diff)\n df.insert(9, 'Retention_Time_Difference', rt_diff)\n return df\n\ndef create_tracer_plot(df_in):\n mpl_logger = logging.getLogger('matplotlib')\n mpl_logger.setLevel(logging.WARNING)\n headers = parse_headers(df_in, 0)\n abundance = [item for sublist in headers for item in sublist if len(sublist) > 1]\n fig, ax = plt.subplots()\n for i, tracer in df_in.iterrows():\n y = tracer[abundance]\n x = abundance\n ax.plot(x, y, marker='o',label=tracer[0])\n ax.set_ylabel('Log abundance')\n ax.set_xlabel('Sample name')\n #plt.title('Tracers {} mode')\n plt.yscale('log')\n plt.xticks(rotation=-90)\n plt.legend()\n plt.tight_layout()\n sf = ScalarFormatter()\n sf.set_scientific(False)\n ax.yaxis.set_major_formatter(sf)\n ax.margins(x=0.3)\n buffer = io.BytesIO()\n plt.savefig(buffer)#, format='png')\n #plt.show()\n plt.close()\n return buffer.getvalue()\n\n","sub_path":"app/ms1/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"113455506","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n# Time complexity: O(n)\n# Space complexity: O(n)\n\nclass Solution:\n def numberToWords(self, num: int) -> str:\n if num == 0:\n return 'Zero'\n to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \\\n 'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()\n tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()\n\n def word(n):\n if n < 20:\n return to19[n - 1:n]\n if n < 100:\n return [tens[n // 10 - 2]] + word(n % 10)\n if n < 1000:\n return [to19[n // 100 - 1]] + ['Hundred'] + word(n % 100)\n for i, j in enumerate(['Thousand', 'Million', 'Billion'], 1):\n if n < 1000 ** (i + 1):\n return word(n // (1000 ** i)) + [j] + word(n % (1000 ** i))\n\n return ' '.join(word(num))\n\n# 自己写的啰嗦版本\n\nclass Solution:\n def numberToWords(self, num: int) -> str:\n\n # 1 2 3 4 5 6 7\n\n # 1,000,000\n\n # //10^0 [123...9]\n # //10^1 [20, ,90]\n # //10^2 [123..9] + 'hundred'\n\n # //10^3 [123..9] + 'thousand'\n # //10^4 [10, 20, ,90] + 'thousand'\n # //10^5 [123..9] + 'hundred' + 'thousand'\n\n # //10^6 [123..9] + 'million'\n # //10^7 [10, 20, ,90] + 'million'\n # //10^8 [123..9] + 'hundred' + 'million'\n\n # //10^9 [123..9] + 'billion'\n # //10^10 [10,20, ,90] + 'billion'\n # //10^11 [123..9] + 'hundred' + 'billion'\n\n to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \\\n 'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()\n tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()\n\n def word(n, res):\n if n == 0:\n if res:\n return res\n else:\n return 'Zero'\n if n < 20:\n if res:\n return res + ' ' + to19[n - 1]\n else:\n return to19[n - 1]\n if n < 100:\n if res:\n res += ' ' + tens[n // 10 - 2]\n else:\n res = tens[n // 10 - 2]\n return word(n % 10, res)\n if n < 1000:\n if res:\n res += ' ' + to19[n // 100 - 1] + ' Hundred'\n else:\n res = to19[n // 100 - 1] + ' Hundred'\n return word(n % 100, res)\n for i, unit in enumerate(['Thousand', 'Million', 'Billion'], 1):\n if n < 1000 ** (i + 1):\n res = word(n // (1000 ** i), res)\n res += ' ' + unit\n return word(n % (1000 ** i), res)\n\n res = ''\n return word(num, res)\n return res\n\n\nclass Solution:\n def numberToWords(self, num: int) -> str:\n thousands = [\"\", \"Thousand\", \"Million\", \"Billion\"]\n if num == 0:\n return 'Zero'\n res = ''\n for i in range(4):\n if num % 1000 != 0:\n res = self.helper(num % 1000) + thousands[i] + ' ' + res\n num //= 1000\n\n return res.strip()\n\n def helper(self, num):\n lessThan20 = [\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\",\n \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"]\n tens = [\"\", \"Ten\", \"Twenty\", \"Thirty\", \"Forty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"]\n if num == 0:\n return ''\n elif num < 20:\n return lessThan20[num] + ' '\n elif num < 100:\n return tens[num // 10] + ' ' + self.helper(num % 10)\n else:\n return lessThan20[num // 100] + ' Hundred ' + self.helper(num % 100)\n\n\n\n","sub_path":"leetcode_python/273.Integer_to_English_Words.py","file_name":"273.Integer_to_English_Words.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"252620931","text":"from functools import wraps\n\nfrom flask import (Blueprint, render_template, get_flashed_messages,\n _app_ctx_stack, session, redirect, request)\nfrom jinja2 import Markup\nfrom flask_modals import turbo\nfrom flask_modals.parser import parse_html\n\n\ndef modal_messages():\n '''This will be available in the app templates for use in the modal\n body.\n '''\n return Markup(render_template('modals/modalMessages.html'))\n\n\ndef render_template_modal(*args, **kwargs):\n '''Call this function instead of render_template when the page\n contains a modal form.\n\n It accepts all the arguments passed to render_template and 3 others:\n\n modal: id of the modal\n turbo: Set this to False if modal is not be displayed. It should be\n True for initial page loads and for modal display.\n redirect: Set this to False if you want to render templates and not\n redirect.\n '''\n\n ctx = _app_ctx_stack.top\n modal = kwargs.pop('modal', None)\n replace = kwargs.pop('turbo', True)\n update = False\n redirect = kwargs.pop('redirect', True)\n show_modal = False\n\n # When redirecting from another modal route with `turbo` set to True\n # and `redirect` set to False, don't stream a response.\n if not redirect:\n if request.method == 'POST':\n modal_flag = True\n else:\n modal_flag = False\n else:\n modal_flag = True\n\n if turbo.can_stream():\n if replace:\n show_modal = modal_flag\n # prevent flash messages from showing both outside and\n # inside the modal\n ctx._modal = modal_flag\n else:\n update = False if redirect else True\n\n setup_for_reload()\n\n html, stream, target = parse_html(\n render_template(*args, **kwargs),\n modal,\n redirect,\n update,\n show_modal\n )\n\n if show_modal:\n return turbo.stream(turbo.replace(stream, target=target))\n\n if update:\n return turbo.stream(turbo.update(stream, target='turbo-stream__body'))\n\n return html\n\n\ndef redirect_to(*args, **kwargs):\n '''Use this function instead of Flask's `redirect` if you want to do\n a full reload of the page on form submit. Turbo Drive normally does\n an ajax load of the page.\n '''\n\n session['_keep_flashes'] = True\n return redirect(*args, **kwargs)\n\n\ndef render_template_redirect(*args, **kwargs):\n '''Reload the page if session variable is set, i.e. the route is the\n target of the `redirect_to` function.\n '''\n\n setup_for_reload()\n return render_template(*args, **kwargs)\n\n\ndef setup_for_reload():\n '''Setup for reload conditionally. App context variable `_reload`\n causes the reload to happen - see template `turbo.html`. Flashes\n need to be saved so that they are again available on reload.\n '''\n\n if '_keep_flashes' in session:\n del session['_keep_flashes']\n ctx = _app_ctx_stack.top\n ctx._reload = True\n session['_flashes'] = get_flashed_messages(with_categories=True)\n\n\ndef response(template=None):\n '''Use this decorator if coding `render_template_modal` in a number\n of places in a view function looks verbose.\n '''\n def decorator(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n template_name = template\n if template_name is None:\n template_name = f\"{request.endpoint.replace('.', '/')}.html\"\n ctx = f(*args, **kwargs)\n if ctx is None:\n ctx = {}\n elif not isinstance(ctx, dict):\n return ctx\n return render_template_modal(template_name, **ctx)\n return decorated_function\n return decorator\n\n\nclass Modal:\n def __init__(self, app=None):\n\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n '''Initialize the extension.\n\n Call method for blueprint and register template globals for app.\n '''\n\n self.register_blueprint(app)\n app.add_template_global(modal_messages)\n app.jinja_env.globals['modals'] = self.load\n app.jinja_env.globals['show_flashed_messages'] = \\\n self.show_flashed_messages\n\n def register_blueprint(self, app):\n\n bp = Blueprint('modals', __name__, template_folder='templates',\n static_folder='static',\n static_url_path='/modals/static')\n\n app.register_blueprint(bp)\n\n @staticmethod\n def show_flashed_messages(*args, **kwargs):\n '''Delegate to get_flashed_messages if _modal is set on the\n app context. If it is not set, it means modal is not being\n displayed and so we do not flash messages in it.\n '''\n\n ctx = _app_ctx_stack.top\n if not getattr(ctx, '_modal', None):\n return\n\n return get_flashed_messages(*args, **kwargs)\n\n def load(self, url=None):\n '''Load the following markup:\n\n 1. turbo.html - Hotwire Turbo library\n 2. nprogress.html - NProgress js library for progress bar\n 3. jstemplate.html - Remove extra modal-backdrop divs, control\n progress bar, add body attribute\n `data-turbo=\"false\"`.\n '''\n\n ctx = _app_ctx_stack.top\n reload = getattr(ctx, '_reload', None)\n\n turbo_html = render_template(\n 'modals/turbo.html',\n turbo=turbo.load,\n url=url,\n reload=reload\n )\n nprogress_html = render_template('modals/nprogress.html')\n main_html = render_template('modals/jstemplate.html')\n\n html = Markup(turbo_html + nprogress_html + main_html)\n\n return html\n","sub_path":"flask_modals/modal.py","file_name":"modal.py","file_ext":"py","file_size_in_byte":5759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"154261236","text":"__author__ = 'Ricardo Del Rio'\n# *** VERSION MODIFICADA PARA TAREA 02 DE PRORAMACION AVANZADA ***\n# Libre de estructuras python\n\nfrom estructuras_propias import ListaLigada, split, join\n\ndef es_csv(archivo_csv):\n '''\n Recibe un archivo csv y comprueba que termine en \".csv\". De ser asi retorna True. De lo contrario False.\n '''\n return archivo_csv[-4:] == '.csv'\n\n\ndef importar_datos(archivo_csv, simbolo=','):\n '''\n Recibe como parametro el directorio o el nombre de un archivo \".csv\"\n Retorna una lista de listas (matriz) con los datos del arhivo.\n '''\n with open(archivo_csv, 'r') as archivo:\n lista_archivo = ListaLigada()\n for linea in archivo:\n # esta funcion retorna una ListaLigada\n lista_linea = split(linea.strip('\\n'), simbolo)\n lista_archivo.append(lista_linea)\n return lista_archivo\n\n\ndef exportar(matriz, archivo_csv, sobreescribir=False):\n '''\n Recibe una lista de listas de datos que se transforma en un string separado con comas y filas.\n Estas son guardadas en un archivo \".csv\" con el nombre indicado.\n Se puede optar por sobreescribir un archivo o agregar los datos al final.\n '''\n if sobreescribir:\n modo = 'w'\n else:\n modo = 'a'\n\n with open(archivo_csv, modo) as archivo:\n for f in matriz:\n linea = join(', ', f)\n archivo.write(linea + '\\n')\n\n#-------------------------------------------------------------------------\n\n\nif __name__ == '__main__':\n\n matriz = ListaLigada(ListaLigada(1, 2, 3, 4, 5, 6, 7, 8, 9),\n ListaLigada('a', 'b', 'c', 'd', 'e', 'f'),\n ListaLigada('g', 'h', 'i', 'j', 'k', 'l'),\n ListaLigada('m', 'n', 'o', 'p', 'q', 'r'),\n ListaLigada('s', 't', 'u', 'v', 'w', 'x'))\n exportar(matriz, 'prueba.csv', 1)\n\n '''\n lista = importar_datos('population.csv')\n print(lista)\n '''\n","sub_path":"Tareas/T02/manejo_csv.py","file_name":"manejo_csv.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"506745131","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 3 17:21:25 2019\r\n@author: ddengca@gmail.com\r\n\"\"\"\r\n\r\nimport os\r\nimport shutil\r\nimport tempfile\r\n\r\n\r\ndef copy_dir_names(directory, out_filename):\r\n '''\r\n copy names of all sub-dir of directory,\r\n append to out_filename\r\n '''\r\n # use utf-8 when open the file, as the name including utf charactors\r\n out_file = open(out_filename, 'at', encoding=\"utf-8\")\r\n for item in os.listdir(directory):\r\n if os.path.isdir(os.path.join(directory, item)):\r\n out_file.write(item + '\\n')\r\n out_file.close()\r\n\r\n\r\ndef rename_dir(directory):\r\n '''\r\n if a sub-dir of directory is like \"【7】*\",\r\n rename it to \"【07】*\"\r\n '''\r\n os.chdir(directory)\r\n for item in os.listdir(directory):\r\n if os.path.isdir(os.path.join(directory, item)) and '】' in item:\r\n h, t = item.split('】')\r\n if len(h) == 2 and h[0] == '【':\r\n item_new = '【0' + h[1] + '】' + t\r\n os.rename(item, item_new)\r\n\r\n\r\ndef del_dir(directory):\r\n '''\r\n to delete all sub-directories in directory\r\n\r\n os.remove(): delete a file\r\n os.rmdir(): delete an empty directory\r\n shutil.rmtree(): deletes a directory and all its contents\r\n '''\r\n os.chdir(directory)\r\n for item in os.listdir(directory):\r\n if os.path.isdir(os.path.join(directory, item)):\r\n shutil.rmtree(item)\r\n\r\n\r\ndef rename_file(directory):\r\n '''\r\n rename all files in directory, to remove the \"【*】\" part\r\n Note that os.rename() a file to a name under another directory\r\n actually moves it\r\n '''\r\n os.chdir(directory)\r\n for item in os.listdir():\r\n if os.path.isfile(item) and '】' in item:\r\n h, item_new = item.split('】')\r\n os.rename(item, item_new)\r\n\r\n\r\ndef move_files_from_subdir(directory, type):\r\n '''\r\n move files with a certain type from all sub-dir to current directory\r\n '''\r\n for item in os.listdir(directory):\r\n if os.path.isdir(os.path.join(directory, item)):\r\n os.chdir(os.path.join(directory, item))\r\n for file in os.listdir():\r\n if os.path.isfile(file) and file.endswith(type):\r\n os.rename(file, os.path.join(directory, file))\r\n\r\n\r\ndef treat_png():\r\n # to move and rename *.png files from all sub-dirs\r\n for item in os.listdir(dir_working):\r\n if os.path.isdir(os.path.join(dir_working, item)):\r\n os.chdir(os.path.join(dir_working, item))\r\n for file in os.listdir():\r\n if os.path.isfile(file) and file.endswith('png'):\r\n file_new = os.path.join(dir_working, item + '.png')\r\n os.rename(file, file_new)\r\n\r\n\r\ndef copy_book_name(dir_base, o_filename):\r\n # to copy book names to o_filename\r\n # insert under each corresponding categories\r\n # open an tempfile.NamedTemporaryFile()\r\n # then replace o_filename when finish inserting book names\r\n with open(o_filename, encoding='utf-8') as o_file, \\\r\n tempfile.NamedTemporaryFile(\r\n 'w+t', encoding='utf-8', delete=False) as o_tmp:\r\n for line in o_file:\r\n o_tmp.write(line)\r\n dir_cat = line[:-1] # remove EOL in line\r\n os.chdir(os.path.join(dir_base, dir_cat))\r\n for book in os.listdir():\r\n # remove the starting 【*】 part in the dir name\r\n if '】' in book:\r\n book_new = book.split('】')[1]\r\n os.rename(book, book_new)\r\n book = book_new\r\n os.chdir(os.path.join(dir_base, dir_cat, book))\r\n w_bookname = False\r\n for file in os.listdir():\r\n if os.path.isdir(file):\r\n continue\r\n # remove the starting 【*】 part in the filename\r\n if '】' in file:\r\n file_new = file.split('】')[1]\r\n os.rename(file, file_new)\r\n file = file_new\r\n # copy filename to o_tmp under corresponding category\r\n if not w_bookname:\r\n # remove extension from filename using os.path.splitext\r\n bookname2write = os.path.splitext(file)[0]\r\n o_tmp.write(bookname2write + '\\n')\r\n w_bookname = True\r\n continue\r\n # move azw3 or epub files to dir_base\r\n # if file.endswith('azw3') or file.endswith('epub'):\r\n # os.rename(file, os.path.join(dir_base, file))\r\n o_tmp.write('\\n')\r\n os.replace(o_tmp.name, o_filename)\r\n\r\n\r\ndef copy_all_books(dir_base, o_filename, types):\r\n \"\"\" Copy books from all sub-folders to dir_base\r\n Only copy books whose extension is in types\r\n \"\"\"\r\n with open(o_filename, encoding='utf-8') as f:\r\n booknames = f.readlines()\r\n os.chdir(dir_base)\r\n for cat in os.listdir(): # category names like '【01】2018年度高分图书'\r\n if os.path.isdir(os.path.join(dir_base, cat)):\r\n os.chdir(os.path.join(dir_base, cat))\r\n for book in os.listdir():\r\n os.chdir(os.path.join(dir_base, cat, book))\r\n for file in os.listdir():\r\n if os.path.isdir(file):\r\n continue\r\n file_name, file_ext = os.path.splitext(file)\r\n if file_ext[1:] in types:\r\n for line in booknames:\r\n if file_name in line and ',' in line:\r\n file_name = line.rpartition(', ')[2][:-1]\r\n break\r\n try:\r\n os.rename(file, os.path.join(\r\n dir_base, file_name + file_ext))\r\n except FileExistsError:\r\n print('%s already moved!' % file)\r\n\r\n\r\ndef rename_file(dir_base, o_filename):\r\n \"\"\" For books in all sub-folders of dir_base,\r\n change files name according to lines in o_filename\r\n \"\"\"\r\n with open(o_filename, encoding='utf-8') as f:\r\n booknames = f.readlines()\r\n os.chdir(dir_base)\r\n for cat in os.listdir(): # category names like '【01】2018年度高分图书'\r\n if os.path.isdir(os.path.join(dir_base, cat)):\r\n os.chdir(os.path.join(dir_base, cat))\r\n for book in os.listdir():\r\n os.chdir(os.path.join(dir_base, cat, book))\r\n for file in os.listdir():\r\n if os.path.isdir(file):\r\n continue\r\n file_name, file_ext = os.path.splitext(file)\r\n for line in booknames:\r\n if file_name in line and ',' in line:\r\n # new name: the part after ', ' and removing EOL\r\n file_name = line.rpartition(', ')[2][:-1]\r\n break\r\n try:\r\n file_new = file_name + file_ext\r\n os.rename(file, file_new)\r\n print('Renamed %s to %s' % (file, file_new))\r\n except FileExistsError:\r\n print('%s already moved!' % file)\r\n\r\n\r\ndef clean_file(o_filename):\r\n ''' remove the old book names in o_filename\r\n '''\r\n with open(o_filename, encoding='utf-8') as o_file, \\\r\n tempfile.NamedTemporaryFile(\r\n 'w+t', encoding='utf-8', delete=False) as o_tmp:\r\n for line in o_file:\r\n if ', ' in line:\r\n line = line.rpartition(', ')[2]\r\n o_tmp.write(line)\r\n os.replace(o_tmp.name, o_filename)\r\n\r\n\r\ndef clean_up_dir(dir_base):\r\n ''' Walk through all sub-folders in dir_base,\r\n delete files duplicate with one in dir_base,\r\n delete empty sub-folders\r\n '''\r\n # get a list of all files at dir_base\r\n files_at_base = os.listdir(dir_base)\r\n files_at_base_loop = files_at_base.copy()\r\n for f in files_at_base_loop:\r\n if os.path.isdir(os.path.join(dir_base, f)):\r\n files_at_base.remove(f)\r\n\r\n for root, dirs, files in os.walk(dir_base):\r\n # skip scanning dir_base\r\n if root == dir_base:\r\n continue\r\n\r\n # delete empty dir\r\n if not dirs and not files:\r\n os.rmdir(root)\r\n continue\r\n\r\n # delete duplicate files\r\n for f in files:\r\n file_name, file_ext = os.path.splitext(f)\r\n if file_name + '.azw3' in files_at_base or \\\r\n file_name + '.epub' in files_at_base:\r\n print('DEL %s at %s...' % (f, root))\r\n os.remove(os.path.join(root, f))\r\n\r\n\r\ndef write_monthly_list(dir_month, o_file):\r\n ''' walk dir_month, copy book names of each month and\r\n append to o_file under each month\r\n '''\r\n with open(o_file, 'at', encoding='utf-8') as o_f:\r\n o_f.write('\\n【19】2018月度热门图书\\n')\r\n for root, dirs, files in os.walk(dir_month):\r\n if files:\r\n month = root.rpartition('\\\\')[2]\r\n o_f.write(month + ':\\n')\r\n # trim extension from each filename\r\n files_name = []\r\n for f in files:\r\n files_name.append(os.path.splitext(f)[0])\r\n # to remove duplicate filenames\r\n files_name = set(files_name)\r\n for f in files_name:\r\n o_f.write(' ' + f + '\\n')\r\n\r\n\r\ndef move_extra(dir_base, dir_copy):\r\n ''' walk all sub-dir of dir_copy;\r\n for each book files found, check if it's in dir_base\r\n if not, copy it to dir_base\r\n '''\r\n i = j = k = 0\r\n for root, dirs, files in os.walk(dir_copy):\r\n if not dirs and not files:\r\n os.rmdir(root)\r\n k += 1\r\n print('DEL: %s is empty!' % root)\r\n continue\r\n for f in files:\r\n try:\r\n os.rename(os.path.join(root, f),\r\n os.path.join(dir_base, f))\r\n print('Moved: %s.' % f)\r\n i += 1\r\n except FileExistsError:\r\n j += 1\r\n os.remove(os.path.join(root, f))\r\n print('Deleted: %s at %s already exists!' % (f, root))\r\n print('Totally moved %i books.' % i)\r\n print('There are total %i duplicates deleted.' % j)\r\n print('Totally deleted %i empty folders.' % k)\r\n\r\n\r\ndef find_missing(dir_base, o_file):\r\n ''' go through each books listed in o_file,\r\n find out anyone not in dir_base, then marked as (missing)\r\n '''\r\n\r\n\r\ndef treat_monthly():\r\n # to handle top books for each months\r\n i = 1\r\n while i < 13:\r\n dir = dir_working + '\\\\' + str(i) + '月'\r\n move_files_from_subdir(dir, 'epub')\r\n rename_file(dir)\r\n del_dir(dir)\r\n i += 1\r\n\r\n\r\ndir_working = \\\r\n 'C:\\\\Users\\\\zhid\\\\Documents\\\\private\\\\myebooks\\\\豆瓣2018年度读书榜单'\r\ndir_clancy = \\\r\n 'C:\\\\Users\\\\zhid\\\\Documents\\\\private\\\\myebooks\\\\Tom Clancy'\r\ndir_copy = \\\r\n 'C:\\\\Users\\\\zhid\\\\Documents\\\\private\\\\myebooks\\\\豆瓣2018年度读书榜单 - Copy'\r\ndir_month = os.path.join(dir_copy, '【19】2018月度热门图书')\r\nout_filename = os.path.join(dir_working, '_豆瓣2018年度读书榜单.txt')\r\n# copy_dir_names(dir_working, out_filename)\r\n# rename_dir(dir_working)\r\n\r\n\r\ndef main():\r\n # copy_book_name(dir_working, out_filename)\r\n # copy_all_books(dir_working, out_filename, ['azw3', 'epub'])\r\n # rename_file(dir_working, out_filename)\r\n # clean_up_dir(dir_working)\r\n # clean_file(out_filename)\r\n # write_monthly_list(dir_month, out_filename)\r\n # move_extra(dir_working, dir_copy)\r\n move_files_from_subdir(dir_clancy, 'mobi')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"py_tools/file_system/copy_dir_names.py","file_name":"copy_dir_names.py","file_ext":"py","file_size_in_byte":11993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"123132212","text":"from flask import Flask, render_template, session, url_for, request, redirect\nimport urllib.request, json\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef root():\n u = urllib.request.urlopen(\"https://api.nasa.gov/planetary/apod?api_key=vSKatn229WbHqpfCL8ZRTJo8zs1bh27bpMrmAW6u\")\n\n response = u.read()\n data = json.loads(response)\n return render_template(\"index.html\", pic=data['url'], explanation = data['explanation'])\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n\n\n#vSKatn229WbHqpfCL8ZRTJo8zs1bh27bpMrmAW6u\n","sub_path":"24_rest/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"21458048","text":"# アプリケーションの初期設定を行います\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\n# ORMを用意します\ndb = SQLAlchemy()\n\n# アプリケーションを作成する関数\n\n\ndef create_app(test_config=None):\n app = Flask(__name__)\n app.config.from_object('flask_blog.config') # 設定ファイルの読み込み\n if test_config: # テストモードであれば、テスト用設定で上書き\n app.config.from_mapping(test_config)\n db.init_app(app)\n # Blueprintで分割されているファイルを読み込み\n from flask_blog.views.views import view\n app.register_blueprint(view)\n from flask_blog.views.entries import entry\n app.register_blueprint(entry)\n return app\n","sub_path":"api/flask_blog/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"548676323","text":"from django.db import models\nfrom dgram.users import models as user_model\nfrom dgram.users.models import TimeStamedModel\n# Create your models here.\n\n\nclass Post(TimeStamedModel):\n author = models.ForeignKey(\n user_model.User, \n null=True, \n on_delete=models.CASCADE, \n related_name= 'post_author'\n )\n image = models.ImageField(blank=True)\n cpation = models.TextField(blank=True)\n image_likes = models.ManyToManyField(user_model.User, related_name='post_image_likes')\n\n\nclass Comment(TimeStamedModel):\n author = models.ForeignKey(\n user_model.User, \n null=True, \n on_delete=models.CASCADE, \n related_name= 'comment_author'\n )\n posts = models.ForeignKey(\n Post, \n null=True, \n on_delete=models.CASCADE, \n related_name= 'comment_post'\n )\n contents = models.TextField(blank=True)\n","sub_path":"dgram/dgram/posts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"238699020","text":"from model.cameraman import Cameraman\nfrom controller.main import MainController\n\nclass MainView:\n\n def showGreet(self):\n print(\"Hello!, Welcome to Phographer!\")\n\n def showCameraman(self):\n cameraman = Cameraman().showCameraman()\n for key, value in cameraman.items():\n print(f\"{key}: {value}\")\n \n def inputUserDetails(self):\n name = input(\"Enter Your Name: \")\n address = input(\"Enter Address: \")\n notel = input(\"Enter Your NoTel: \")\n age = input(\"Enter Your age: \")\n \n return MainController().getUserDetails(name, age, address, notel)","sub_path":"project/Booking-Camera/view/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"227160576","text":"import io\r\nimport os\r\nimport re\r\nimport tarfile\r\nimport traceback\r\nfrom contextlib import asynccontextmanager\r\nfrom typing import AsyncGenerator, AsyncIterator\r\n\r\nimport aiodocker\r\nfrom aiodocker import DockerError\r\nfrom aiodocker.stream import Stream\r\nfrom cuwais.config import config_file\r\n\r\nfrom runner.config import DEBUG\r\nfrom runner.logger import logger\r\nfrom shared.connection import Connection\r\nfrom shared.message_connection import MessagePrintConnection\r\n\r\nDOCKER_IMAGE_NAME = \"aiwarssoc/sandbox:latest\"\r\n\r\n\r\nclass InvalidEntryFile(RuntimeError):\r\n pass\r\n\r\n\r\nclass InvalidSubmissionError(RuntimeError):\r\n pass\r\n\r\n\r\n# Converts 100K into 102400, 1g into 1024**3, etc\r\ndef _to_bytes(s: str) -> int:\r\n s = s.strip().lower()\r\n if s[-1] in {\"b\", \"k\", \"m\", \"g\"}:\r\n e = {\"b\": 0, \"k\": 1, \"m\": 2, \"g\": 3}[s[-1]]\r\n return int(s[:-2].strip()) * (1024 ** e)\r\n\r\n return int(s)\r\n\r\n\r\ndef _get_env_vars() -> dict:\r\n env_vars = dict()\r\n env_vars['PYTHONPATH'] = \"/home/sandbox/\"\r\n env_vars['DEBUG'] = str(config_file.get(\"debug\"))\r\n\r\n return env_vars\r\n\r\n\r\nasync def _make_sandbox_container(client: aiodocker.docker.Docker, env_vars: dict) -> aiodocker.docker.DockerContainer:\r\n mem_limit = _to_bytes(config_file.get(\"submission_runner.sandbox_memory_limit\"))\r\n max_repo_size_bytes = int(config_file.get(\"max_repo_size_bytes\"))\r\n cpu_quota = int(100000 * float(config_file.get(\"submission_runner.sandbox_cpu_count\")))\r\n\r\n tmpfs_flags = \"rw,noexec,nosuid,noatime\" # See mount command\r\n\r\n # See https://docs.docker.com/engine/api/v1.30/#operation/ContainerCreate\r\n config = {\r\n \"Image\": DOCKER_IMAGE_NAME,\r\n # \"Cmd\": f\"ls -al /\",\r\n \"Tty\": True,\r\n \"User\": 'sandbox',\r\n \"Env\": [f\"{key}={env_vars[key]}\" for key in env_vars],\r\n \"NetworkDisabled\": True,\r\n \"HostConfig\": {\r\n # See https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities\r\n \"Capdrop\": [\r\n \"AUDIT_WRITE\",\r\n \"CHOWN\",\r\n \"DAC_OVERRIDE\",\r\n # \"FOWNER\", # Allows chmod\r\n \"FSETID\",\r\n \"KILL\",\r\n \"MKNOD\",\r\n \"NET_BIND_SERVICE\",\r\n \"NET_RAW\",\r\n \"SETFCAP\",\r\n \"SETGID\",\r\n \"SETPCAP\",\r\n \"SETUID\",\r\n \"SYS_CHROOT\"\r\n ],\r\n \"Tmpfs\": {\r\n '/tmp': f'{tmpfs_flags},size=1M',\r\n '/var/tmp': f'{tmpfs_flags},size=1M',\r\n '/run/lock': f'{tmpfs_flags},size=1M',\r\n '/var/lock': f'{tmpfs_flags},size=1M'\r\n },\r\n \"ShmSize\": 1 * 1024 * 1024,\r\n \"NetworkMode\": \"none\",\r\n \"CpuPeriod\": 100000,\r\n \"CpuQuota\": cpu_quota,\r\n \"Memory\": mem_limit // 2,\r\n \"MemorySwap\": mem_limit,\r\n \"OomKillDisable\": True,\r\n \"DiskQuota\": max_repo_size_bytes + 2*1024*1024,\r\n \"AutoRemove\": True,\r\n }\r\n }\r\n\r\n container = await client.containers.create(config)\r\n await container.start()\r\n\r\n return container\r\n\r\n\r\ndef _compress_sandbox_files(fh):\r\n with tarfile.open(fileobj=fh, mode='w') as tar:\r\n tar.add(\"./sandbox\", arcname=\"sandbox\")\r\n tar.add(\"./shared\", arcname=\"shared\")\r\n\r\n\r\nasync def _exec_root(container: aiodocker.docker.DockerContainer, command: str):\r\n logger.debug(f\"Container {container.id}: running {command}\")\r\n exec_ctxt = await container.exec(command, user='root', tty=True, stdout=True)\r\n exec_stream: Stream = exec_ctxt.start(timeout=30)\r\n output = b''\r\n while True:\r\n message: aiodocker.stream.Message = await exec_stream.read_out()\r\n if message is None:\r\n break\r\n output += message.data\r\n logger.debug(f\"Container {container.id}: result of command {command}: '{output.decode()}'\")\r\n\r\n\r\nasync def _copy_sandbox_scripts(container: aiodocker.docker.DockerContainer):\r\n _sandbox_scripts = io.BytesIO()\r\n # Compress files to tar\r\n _compress_sandbox_files(_sandbox_scripts)\r\n\r\n # Send\r\n _sandbox_scripts.seek(0)\r\n await container.put_archive(\"/home/sandbox/\", _sandbox_scripts.getvalue())\r\n\r\n\r\nasync def _copy_submission(container: aiodocker.docker.DockerContainer, submission_hash: str):\r\n submission_path = f\"/home/subrunner/repositories/{submission_hash}.tar\"\r\n # Ensure that submission is valid\r\n if not _is_submission_valid(submission_hash, submission_path):\r\n raise InvalidSubmissionError(submission_hash)\r\n\r\n # Make destination\r\n dest_path = \"/home/sandbox/submission\"\r\n await _exec_root(container, f\"mkdir {dest_path}\")\r\n\r\n # Make required init file for python\r\n init_path = os.path.join(dest_path, \"__init__.py\")\r\n await _exec_root(container, f\"touch {init_path}\")\r\n\r\n logger.debug(f\"Container {container.id}: opening submission {submission_hash}\")\r\n with open(submission_path, 'rb') as f:\r\n logger.debug(f\"Container {container.id}: reading submission {submission_hash}\")\r\n data = f.read()\r\n\r\n logger.debug(f\"Container {container.id}: putting submission {submission_hash}\")\r\n await container.put_archive(dest_path, data)\r\n\r\n\r\nasync def _lock_down(container: aiodocker.docker.DockerContainer):\r\n # Set write limits\r\n await _exec_root(container, \"chmod -R ugo=rx /home/sandbox/\") # TODO: Very slow (~2s) because of CoW?\r\n\r\n if DEBUG:\r\n await _exec_root(container, \"ls -alR /home/sandbox/\")\r\n\r\n\r\nasync def _get_lines(strings: AsyncGenerator[str, None]) -> AsyncGenerator[str, None]:\r\n line = []\r\n async for string in strings:\r\n if string is None or string == b'' or string == \"\":\r\n continue\r\n for char in string:\r\n if char == \"\\r\" or char == \"\\n\":\r\n if len(line) != 0:\r\n yield \"\".join(line)\r\n line = []\r\n else:\r\n line.append(char)\r\n\r\n if len(line) != 0:\r\n yield \"\".join(line)\r\n\r\n\r\ndef _is_script_valid(script_name: str):\r\n script_name_rex = re.compile(\"^[a-zA-Z0-9_/]*$\")\r\n return os.path.exists(\"./sandbox/\" + script_name + \".py\") and script_name_rex.match(script_name) is not None\r\n\r\n\r\ndef _is_submission_valid(submission_hash: str, submission_path: str):\r\n submission_hash_rex = re.compile(\"^[a-f0-9]+$\")\r\n return os.path.exists(submission_path) and submission_hash_rex.match(submission_hash) is not None\r\n\r\n\r\n@asynccontextmanager\r\nasync def run(submission_hash: str) -> AsyncIterator[Connection]:\r\n docker = None\r\n container = None\r\n\r\n try:\r\n # Attach to docker\r\n docker = aiodocker.Docker()\r\n\r\n # Create container\r\n logger.debug(f\"Creating container for hash {submission_hash}\")\r\n env_vars = _get_env_vars()\r\n try:\r\n container = await _make_sandbox_container(docker, env_vars)\r\n except DockerError:\r\n logger.error(traceback.format_exc())\r\n raise\r\n\r\n # Copy information\r\n logger.debug(f\"Container {container.id}: copying scripts\")\r\n await _copy_sandbox_scripts(container)\r\n logger.debug(f\"Container {container.id}: copying submission\")\r\n await _copy_submission(container, submission_hash)\r\n logger.debug(f\"Container {container.id}: locking down\")\r\n await _lock_down(container)\r\n\r\n # Start script\r\n logger.debug(f\"Container {container.id}: running script\")\r\n run_t = int(config_file.get('submission_runner.sandbox_run_timeout_seconds'))\r\n run_script_cmd = f\"./sandbox/run.sh 'play.py' {run_t}\"\r\n cmd_exec = await container.exec(cmd=run_script_cmd,\r\n user='read_only_user',\r\n stdin=True,\r\n stdout=True,\r\n stderr=True,\r\n tty=False,\r\n environment=env_vars,\r\n workdir=\"/home/sandbox/\")\r\n unrun_t = int(config_file.get('submission_runner.sandbox_unrun_timeout_seconds'))\r\n cmd_stream: Stream = cmd_exec.start(timeout=unrun_t)\r\n\r\n # Set up input to the container\r\n async def send_handler(m: str):\r\n logger.debug(f\"Container {container.id} <-- '{m.encode()}'\")\r\n await cmd_stream.write_in((m + \"\\n\").encode())\r\n\r\n # Set up output from the container\r\n async def receive_handler() -> AsyncGenerator[str, None]:\r\n while True:\r\n message: aiodocker.stream.Message = await cmd_stream.read_out()\r\n if message is None:\r\n break\r\n logger.debug(f\"Container {container.id} --> '{message}'\")\r\n yield bytes(message.data).decode()\r\n\r\n # Process output from the container\r\n logger.debug(f\"Container {container.id}: setting up output processing\")\r\n lines = _get_lines(receive_handler())\r\n\r\n logger.debug(f\"Container {container.id}: connecting\")\r\n yield MessagePrintConnection(send_handler, lines, container.id)\r\n\r\n finally:\r\n # Clean everything up\r\n if container is not None:\r\n logger.debug(f\"Container {container.id}: cleaning up\")\r\n await container.delete(force=True)\r\n if docker is not None:\r\n await docker.close()\r\n","sub_path":"runner/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":9482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"170053898","text":"import os\nimport time\nimport argparse\nimport importlib\nimport tensorflow as tf\nimport tensorflow.contrib as tc\nimport datetime\n\n\nfrom visualize import *\n\nimport matplotlib.pyplot as plt\n\nflags = tf.flags\nlogging = tf.logging\nlogging.set_verbosity(tf.logging.ERROR)\n\n\nflags.DEFINE_string(\"data\", \"mnist-2\", \"data set name\")\nflags.DEFINE_string(\"model\", \"sgan_mnist\", \"model file name\")\nflags.DEFINE_string(\"gpus\", \"0\", \"gpu id\")\nflags.DEFINE_integer(\"batch_size\", 100, \"batch size\")\nflags.DEFINE_integer(\"num_label\", 100, \"batch size\")\nflags.DEFINE_integer(\"image_size\", 28, \"image size\")\nflags.DEFINE_string(\"logdir\", datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), \"dir for tensorboard logs\")\nflags.DEFINE_integer(\"z_dim\", 64, \"dimension of z\")\nflags.DEFINE_float(\"lam\", 10.0, \"gradient penalty\")\n\nFLAGS = flags.FLAGS\n\nif __name__ == '__main__':\n os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpus\n model = importlib.import_module(FLAGS.data + '.' + FLAGS.model)\n data = importlib.import_module(FLAGS.data).dataset(FLAGS)\n \n c_net = model.Classifier()\n g_net = model.Generator_yz()\n c_new_net = model.Classifier_new()\n\n batch_size = FLAGS.batch_size\n image_size = data.image_size\n z_dim = FLAGS.z_dim\n y_dim = data.y_dim\n\n alpha = np.ones([y_dim], dtype = float)\n dirichlet = tc.distributions.Dirichlet(alpha)\n # u - unlabeled, l - labeled, f -fake\n xu = tf.placeholder(tf.float32, [batch_size / 2, image_size, image_size, data.channel], name='x_unlabeled')\n yu = tf.placeholder(tf.float32, [batch_size / 2, y_dim], name='y_labeled')\n yu_pred_prob = tf.nn.softmax(c_net(xu, dropout_keep = 1.0, reuse = False))\n yu_pred = tf.argmax(yu_pred_prob, 1)\n yu_pred_onehot = tf.one_hot(yu_pred, y_dim)\n confidence = tf.equal(yu_pred, tf.argmax(yu, 1))\n confidence = tf.reduce_mean(tf.cast(confidence, tf.float32))\n\n yg = tf.cast(dirichlet.sample([batch_size / 2], name = 'yg'), tf.float32)\n #yg = tf.one_hot(tf.reshape(tf.multinomial(tf.ones([1, y_dim]), num_samples = batch_size), [batch_size]), y_dim, name = 'yg')\n yg_onehot = tf.one_hot(tf.argmax(yg, axis = 1), y_dim, name = 'yg_onehot')\n zg = tf.random_normal([batch_size / 2, z_dim], name = 'zg')\n xg = g_net(yg_onehot, zg)\n \n x_merge = tf.concat([xg, xu], 0)\n y_merge = tf.concat([yg_onehot, yu_pred_onehot], 0)\n\n xl = tf.placeholder(tf.float32, [batch_size, image_size, image_size, data.channel], name='x_labeled')\n yl = tf.placeholder(tf.float32, [batch_size, y_dim], name='y_labeled')\n\n # L3: build the cross entropy loss using (xl, yl)\n c_loss = tf.nn.softmax_cross_entropy_with_logits(labels = y_merge, logits = c_new_net(x_merge, reuse = False))\n\n # then, utilize the generated data (xg, yg, zg) as training data\n # as yg is observables, we can only use is to train C, G, D_xy...\n\n #z_cond_gen = tf.random_normal([batch_size, z_dim], name = 'cond_gen_z')\n #y_cond_gen = np.zeros([batch_size, y_dim], dtype = float)\n ##y_cond_gen2 = np.zeros([100, y_dim], dtype = float)\n #for i in range(y_dim):\n # y_cond_gen[i*10:(i+1)*10, 9] = 1.0\n #print(y_cond_gen)\n #y_cond_gen = tf.Variable(y_cond_gen, trainable=False, dtype = tf.float32, name = 'cond_gen_y')\n #x_cond_gen = g_net(y_cond_gen, z_cond_gen)\n\n c_net_loss = tf.reduce_mean(c_loss)\n c_net_train_op = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(c_net_loss, var_list=c_new_net.vars)\n\n '''evaluation code'''\n # build test ops\n test_batch_size = 100\n xt = tf.placeholder(tf.float32, [test_batch_size, image_size, image_size, data.channel], name='x_test')\n yt = tf.placeholder(tf.float32, [test_batch_size, y_dim], name='y_test')\n pred = tf.equal(tf.argmax(tf.nn.softmax(c_new_net(xt, dropout_keep = 1.0, reuse = True)), 1), tf.argmax(yt, 1))\n num_correct = tf.reduce_sum(tf.cast(pred, tf.float32))\n\n # init some loss monitor variables\n c_net_loss_summary = tf.summary.scalar('c_net_loss', c_net_loss)\n merged = tf.summary.merge([c_net_loss_summary])\n saver = tf.train.Saver(g_net.vars + c_net.vars) \n gpu_options = tf.GPUOptions(allow_growth=True)\n with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n #tf.train.start_queue_runners(sess=sess)\n sess.run(tf.global_variables_initializer())\n path = 'logs/{}/{}/'.format(data.name, FLAGS.logdir)\n if not os.path.exists(path):\n os.makedirs(path)\n train_writer = tf.summary.FileWriter(path, sess.graph)\n \n saver.restore(sess, '/tmp/model-220000.ckpt')\n start_time = time.time()\n NUM_ITERS = 1000000\n #x_cond = sess.run(x_cond_gen) \n #x_cond = concat_multiple_images(x_cond)\n #scipy.misc.imsave('logs/{}/{}/{}.png'.format(data.name, FLAGS.logdir, 100), x_cond)\n\n #time.sleep(500)\n\n for t in range(0, NUM_ITERS):\n train_xu, train_yu = data.unlabeled_sampler(batch_size/2)\n _, conf = sess.run([c_net_train_op, confidence], feed_dict = {xu: train_xu, yu: train_yu})\n\n\n if t % 100 == 0:\n gen_x, gen_y = sess.run([xg, yg])\n x_gen = concat_multiple_images(gen_x)\n scipy.misc.imsave('logs/{}/{}/{}.png'.format(data.name, FLAGS.logdir, t), x_gen)\n gen_y_int = np.argmax(gen_y, axis = 1)\n print('confidence: [%.4f]' % conf)\n\n # do reporting\n if t % 100 == 0:\n test_x, test_y = data.test_sampler()\n N = test_x.shape[0]\n correct = 0\n for i in range(N/test_batch_size):\n start = i * test_batch_size\n end = (i + 1) * test_batch_size\n batch_x = test_x[start:end]\n batch_y = test_y[start:end]\n correct += num_correct.eval(feed_dict = {xt: batch_x, yt: batch_y})\n print('Iter [%8d] Time [%5.4f] test error [%8d]/[%.4f]' %\n (t + 1, time.time() - start_time, 10000 - correct, 1 - correct / N))\n train_writer.close()\n","sub_path":"test-generator-classifier.py","file_name":"test-generator-classifier.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"298113101","text":"# filename: send_mail.py\r\n# -*- coding: utf-8 -*-\r\n# !/usr/bin/env python\r\nimport os\r\nimport sys\r\nimport smtplib\r\nfrom email.mime.text import MIMEText\r\n\r\n# mail configure\r\nmail_to_list = [\"aa@qq.com\", \"bb@qq.com\" ]\r\nmail_host = \"smtp.qq.com\"\r\nmail_user = \"248745990@qq.com\"\r\nmail_pass = \"\" \r\nmail_postfix = \"qq.com\"\r\nmail_host_port = 465\r\n\r\n\r\n\r\n\r\ndef send_mail_core(mail_to_list, mail_title, mail_content):\r\n me = \"SHARER\" + \"<\" + mail_user + \"@\" + mail_postfix + \">\"\r\n msg = MIMEText(mail_content,_subtype='html',_charset='utf-8')\r\n\r\n msg[\"Subject\"] = mail_title\r\n msg[\"From\"] = me\r\n msg[\"To\"] = \";\".join(mail_to_list)\r\n try:\r\n s = smtplib.SMTP_SSL()\r\n s.connect(mail_host+':'+str(mail_host_port))\r\n s.login(mail_user, mail_pass)\r\n s.sendmail(me, mail_to_list, msg.as_string())\r\n s.close()\r\n return True\r\n except Exception as e:\r\n print(str(e))\r\n return False\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n if len(sys.argv) == 3:\r\n mail_title = sys.argv[1]\r\n mail_content = sys.argv[2]\r\n else:\r\n mail_content = \"May the force be with you!\"\r\n\r\n if send_mail_core(mail_to_list, mail_title, mail_content):\r\n print(\"[*] Send mail success: %s\") % (mail_title)\r\n sys.exit()\r\n else:\r\n print(\"[*] Send mail failed: %s\") % (mail_title)\r\n except Exception as e:\r\n print(str(e))\r\n raise\r\n","sub_path":"text_email.py","file_name":"text_email.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"110943391","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport logging, os\nfrom Configuration import Configuration\nclass Freeling:\n\n\tconfig \t\t\t= None\n\t__freeling_dir\t\t= None\n\t__freeling_config\t= None\n\t__commandDir\t\t= None\n\t__commandInput\t\t= None\n\t__commandOutput\t\t= None\n\t__commandMaked\t\t= None\n\n\n\tdef __init__(self):\n\t\tlogging.info('Freeling::Strating...')\n\t\tself.config \t\t= Configuration()\n\t\tself.__commandMaked\t\t= self.config.freel_dir+\"analyze -f \"+self.config.freel_conf_dir+\" <\"+self.config.freel_tmp_dir+self.config.freel_input+\"> \"+self.config.freel_tmp_dir+self.config.freel_output\n\n\t\tlogging.info(\"Command: \"+self.__commandMaked)\n\n\t# stringToContext\n\t#\tconvert a simple string at a structured data\n\t#\tto use.\n\t#\n\t#\tATENCTION.: The WS neeeds be active using MFS\n\t#\ton Freeling to work. See your .cfg\n\t#\t\t# Sense annotation options (none,all,mfs,ukb)\n\t#\t\tSenseAnnotation=mfs\n\t#\tReturn [ [word_origina, word_radica],...,[word_origina, word_radica, sense] ]\n\t#\n\tdef stringToContext(self,textSended,sentece=False):\n\t\tlogging.info('Freeling::StringToContext')\n\n\t\t# Open, clean and set the new text at input file\n\t\tfile_input = open(self.config.freel_tmp_dir+self.config.freel_input, 'w')\n\t\tfile_input.write(textSended.encode('utf-8').strip())\n\t\tfile_input.close()\n\n\t\t# Open an clean the file of output\n\t\tfile_output = open(self.config.freel_tmp_dir+self.config.freel_output, 'w')\n\t\tfile_output.close()\n\n\t\t# Execute command\n\t\tlogging.info('Freeling 3.1 executing...')\n\t\tos.system(self.__commandMaked)\n\n\t\tfile_input = open(self.config.freel_tmp_dir+self.config.freel_input, 'r')\n\n\t\ttokens \t= []\n\t\tlines \t= []\n\n\t\twith open(self.config.freel_tmp_dir+self.config.freel_output) as f:\n\t\t\tlines = f.readlines()\n\n\n\t\twords \t= []\n\n\t\t# mecamismo baixo é o seguide\n\t\t#\tpara cada linha retornada de dentro do output.txt\n\t\t#\tquebra-se em um lista pelo espaço e verifica se o\n\t\t#\túltimo tem ou não senset e tiver armazena o a palavra\n\t\t#\toriginal, seu radical e seu sense no WN. Caso nao\n\t\t#\ttenha sense, armazena-se apenas o sense e o original\n\t\tfor line in lines:\n\n\t\t\tline \t= line.replace('\\n','')\n\t\t\ttokens \t= line.split(\" \")\n\n\t\t\tif len(tokens) != 1:\n\t\t\t\ttokens[0] \t\t\t\t= tokens[0].replace('.','')\n\t\t\t\ttokens[1] \t\t\t\t= tokens[1].replace('.','')\n\t\t\t\ttokens[len(tokens)-1] \t= tokens[len(tokens)-1].replace('.','')\n\t\t\t\tif tokens[0] != \"\":\n\t\t\t\t\tif tokens[len(tokens)-1] == \"-\":\n\t\t\t\t\t\twords.append([tokens[0].replace('.',''),tokens[1].replace('.',''),tokens[2].replace('.','')])\n\t\t\t\t\telse:\n\t\t\t\t\t\twords.append([tokens[0].replace('.',''),tokens[1].replace('.',''),tokens[2].replace('.',''),tokens[len(tokens)-1].replace('.','')])\n\t\t\t\telse:\n\t\t\t\t\tlogging.info('A token empty!')\n\t\t\telse:\n\t\t\t\tlogging.info('New Sentece detected')\n\n\t\treturn words\n","sub_path":"Extender/Freeling.py","file_name":"Freeling.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336234832","text":"\"\"\"Reduces the number of anagrams of \"tmvoordle\" to a manageable number,\nincluding \"Voldemort. Employs the use of three filters to exclude certain\npermutations: consonant-vowel maps that have a low frequency of occurence,\nthe bottom 10% of trigrams that occur in English, and digrams (bigrams) that\noccur less than 0.1% of the time.\"\"\"\n\nfrom sys import exit\nfrom itertools import permutations\nfrom collections import Counter\nfrom load_dictionary import load as ld\n\n\ndef main():\n \"\"\"Load files and run filters. Makes anagrams viewable by first letter.\"\"\"\n name = \"tmvoordle\".lower()\n\n dictionary_file = ld(\"2of4brif.txt\")\n unlikely_trigrams = ld(\"least_likely_trigrams.txt\")\n\n words = prep_words(name, dictionary_file)\n cv_map = prep_cv_map(words)\n\n # Filter out unlikely c-v maps\n filtered1 = cv_map_filter(name, cv_map)\n # Filter out unlikely trigrams\n filtered2 = trigrams_filter(filtered1, unlikely_trigrams)\n # Filter out unlikely digrams\n filtered3 = digrams_filter(filtered2)\n\n view_by_letter(name, filtered3)\n\n\ndef cv_map_filter(name, pruned_cv_map):\n \"\"\"Remove C-V permutations of given name that do not conform to any of the\n most common patterns found with the prep_cv_map function.\"\"\"\n name_permutations = {\"\".join(i) for i in permutations(name)}\n print(f\"Number of permutations of name {name}: {len(name_permutations)}\")\n\n vowels = \"aeiouy\"\n filtered = set()\n for perm in name_permutations:\n perm_map = \"\"\n for letter in perm:\n if letter in vowels:\n perm_map += \"v\"\n else:\n perm_map += \"c\"\n if perm_map in pruned_cv_map:\n filtered.add(perm)\n\n print(f\"Number of choices after C-V map filter: {len(filtered)}\")\n return filtered\n\n\ndef digrams_filter(permutations_list):\n \"\"\"Remove unlikely digrams from permutations of name. Unlikely digrams\n taken from a pre-generated table.\n Some digrams are removed if they occur anywhere within the permutation.\n Others are removed only if they occur as the first two letters of the\n permutation.\"\"\"\n unlikely_perms = set() # Holds permutations containing unlikely digrams\n unlikely_digrams_anywhere = [\n \"dt\", \"lr\", \"md\", \"ml\", \"mr\", \"mt\", \"mv\", \"td\", \"tv\", \"vd\", \"vl\",\n \"vm\", \"vr\", \"vt\"\n ]\n unlikely_first_letters = [\n \"ld\", \"lm\", \"lt\", \"lv\", \"rd\", \"rl\", \"rm\", \"rt\", \"rv\", \"tl\", \"tm\"\n ]\n for perm in permutations_list:\n for digram in unlikely_digrams_anywhere:\n if digram in perm:\n unlikely_perms.add(perm)\n for digram in unlikely_first_letters:\n if perm.startswith(digram):\n unlikely_perms.add(perm)\n filtered = permutations_list - unlikely_perms\n\n print(f\"Number of choices after digram filter: {len(filtered)}\")\n if \"voldemort\" in filtered:\n print(\"Volemort found!\")\n return filtered\n\n\ndef trigrams_filter(permutations_list, unlikely_trigrams):\n \"\"\"Remove permutations of a name that contain unlikely trigrams (passed as\n second parameter) from a list of name permutations.\"\"\"\n unlikely_perms = set() # Holds permutations containing unlikely trigrams\n for perm in permutations_list:\n for trigram in unlikely_trigrams:\n if trigram.lower() in perm:\n unlikely_perms.add(perm)\n filtered = permutations_list - unlikely_perms\n\n print(f\"Number of choices after trigrams filter: {len(filtered)}\")\n return filtered\n\n\ndef prep_cv_map(words):\n \"\"\"Map letters in given list of words to consonants and vowels.\"\"\"\n vowels = \"aeiouy\"\n cv_mapped_words = []\n for word in words:\n cv_map = \"\"\n for letter in word:\n if letter in vowels:\n cv_map += \"v\"\n else:\n cv_map += \"c\"\n cv_mapped_words.append(cv_map)\n\n # Detemine number of unique c-v patterns\n total = len(set(cv_mapped_words))\n target = 0.05 # Prune 5% of patterns\n prune_total = int(total * target) # Number of words within target\n count_pruned = Counter(cv_mapped_words).most_common(total - prune_total)\n pruned_cv_map = set()\n for pattern, _ in count_pruned:\n pruned_cv_map.add(pattern)\n\n print(f\"Number of unique C-V patterns: {len(pruned_cv_map)}\")\n return pruned_cv_map\n\n\ndef prep_words(name, words):\n \"\"\"Prepare word list by including only words within dictionary file that\n have the same number of letters as the name value. Ensures lowercase for\n consistency.\"\"\"\n print(f\"Initial dictionary file: {len(words)} words\")\n name_length = len(name)\n prepped_words = [\n word.lower()\n for word in words\n if len(word) == name_length\n ]\n\n print(f\"Number of words equal to the length of {name}: \"\n f\"{len(prepped_words)}\")\n return prepped_words\n\n\ndef view_by_letter(name, filtered_permutations):\n \"\"\"Present fully-filtered permutations starting with a given letter to\n user.\"\"\"\n print(f\"\\nPresenting permutations for the following letters: {name}\")\n first_letter = input(\"To view all permutations beginning with a specific \"\n \"letter, enter the desired letter. To view all, \"\n \"permutations press ENTER. > \").lower()\n subset = (\n perm\n for perm in filtered_permutations\n if perm.startswith(first_letter)\n )\n count = 1\n for perm in subset:\n if count % 5 == 0: # Print in 5 columns\n print(perm)\n else:\n print(perm, end=\"\\t\")\n count += 1\n print(f\"\\n\\nNumber of choices starting with '{first_letter}': {count-1}\")\n\n restart = input(\"\\nQuit? (Y/N) \")\n if restart.lower() == \"n\":\n view_by_letter(name, filtered_permutations)\n else:\n exit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Chapter_3/voldemort_british.py","file_name":"voldemort_british.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"435125668","text":"import cv2\nimport numpy as np\ndef AM_mean(image,wind_size):\n i,j=wind_size\n div=i*j\n sum=0\n gray_image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY).astype(float)/255\n row,col=np.shape(gray_image)\n copy_image = np.zeros((row, col))\n image_padded = np.pad(gray_image,(1,1),'symmetric')\n patch_curr=[]\n for a in range(row):\n for b in range(col):\n patch_curr = image_padded[a:a + i, b:b + j]\n val = np.sum(patch_curr)/9\n copy_image[a,b]=((val))\n cv2.imshow(\"copy\",copy_image)\n cv2.imshow(\"oringal\",gray_image)\n cv2.waitKey(-2)\n\nim = cv2.imread('noisee.jpg')\n#im = cv2.imread('download.jpg')\nAM_mean(im,(3,3))","sub_path":"iMAGE_PROCESSING_CLASSWORK_PRACTISE/arthmatic_mean.py","file_name":"arthmatic_mean.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"212484786","text":"import tensorflow as tf\nimport numpy as np\n\ndata = np.loadtxt('./data.csv', dtype = 'float32', delimiter = ',',unpack = True)\n#unpack으로 행과 열을 바꾸는 이유는 ? 메모리 상 행들이 순서대로 묶여있고 그 안에 열들이 있다.\n#내가 원하는 것은 열들인데 열들은 메모리가 띄엄띄엄 떨어져 있으니 행을 열로, 열을 행으로 바꾸면\n#띄엄띄엄 떨어져 있던 열들이 한데묶인 행이 되어 데이터를 구분하기 쉬워진다.\nx_data = np.transpose(data[0:2])\ny_data = np.transpose(data[2:])\n#이렇게 data[0:2] 로 하면 실제 값은 0,1 행을 가져가는 거지만 unpack=True를 하여 행으로 바뀐 열을 내가 갖는 것이다\n#그리고 다시 transpose 하여 행이 열이 된다.\n#정리하면 열 -> 행 -> 열 화 한 것\n\n#학습횟수를 카운트 하는 변수 , 학습에 직접사용되는 것이 아니라(trainable = False) 학습횟수를 계속 누적시킴\nglobal_step = tf.Variable(0, trainable = False, name = 'global_step')\n\nX = tf.placeholder(tf.float32)\nY = tf.placeholder(tf.float32)\n\nwith tf.name_scope('layer1'):\n W1 = tf.Variable(tf.random_uniform([2,10],-1,1), name='W1')\n L1 = tf.matmul(X,W1)\n L1 = tf.nn.relu(L1)\n tf.summary.histogram(\"Weight1\", W1)\n\nwith tf.name_scope('layer2'):\n W2 = tf.Variable(tf.random_uniform([10,20],-1,1), name = 'W2')\n L2 = tf.matmul(L1,W2)\n L2 = tf.nn.relu(L2)\n tf.summary.histogram(\"Weight2\",W2)\n\nwith tf.name_scope('output'):\n W3 = tf.Variable(tf.random_uniform([20,3],-1,1))\n model = tf.matmul(L2, W3)\n tf.summary.histogram(\"Weight3\",W3)\n\nwith tf.name_scope('optimizer'):\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = Y, logits = model))\n\n optimizer = tf.train.AdamOptimizer(learning_rate = 0.1)\n train_op = optimizer.minimize(cost, global_step = global_step) #여기서 학습횟수를 기억한다 그래서 1씩 늘린다\n\n tf.summary.scalar('cost',cost) ##\n\n\n\n#돌리기 with 이전 자료가 있으면 불러들이기\nsess = tf.Session()\nsaver = tf.train.Saver(tf.global_variables())\n\n#checkPoint\nckpt = tf.train.get_checkpoint_state('./model')\nif ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):\n saver.restore(sess,ckpt.model_checkpoint_path)\nelse :\n sess.run(tf.global_variables_initializer())\n\n\nmerged = tf.summary.merge_all()\nwriter = tf.summary.FileWriter('./logs',sess.graph)\n\n\n\nfor step in range(2) :\n sess.run(train_op, feed_dict ={X:x_data, Y:y_data})\n\n print(\"step : %d,\" %sess.run(global_step),\n \"cost : %.3f\" %sess.run(cost, feed_dict={X:x_data, Y:y_data}))\n\n summary = sess.run(merged, feed_dict={X:x_data, Y:y_data})\n writer.add_summary(summary,global_step = sess.run(global_step))\nsaver.save(sess,'./model/dnn.ckpt', global_step = global_step)\n\n\nprediction = tf.argmax(model, 1)\ntarget = tf.argmax(Y,1)\n\nprint(\"예측값 :\", sess.run(prediction, feed_dict={X:x_data}))\nprint(\"실제값 :\", sess.run(target, feed_dict ={X:x_data, Y:y_data}))\n\nis_correct = tf.equal(prediction, target)\naccuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\nprint(\"정확도 : %.2f\" %sess.run(accuracy*100,feed_dict={X:x_data, Y:y_data}))\n","sub_path":"p90.py","file_name":"p90.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"422680111","text":"import bpy\nimport gpu\nimport bgl\nimport os\nimport blf\nfrom gpu_extras.batch import batch_for_shader\n\nvertex_shader = '''\n\n uniform mat4 ModelViewProjectionMatrix;\n\n in vec2 texCoord;\n in vec2 pos;\n out vec2 texCoord_interp;\n\n void main()\n {\n gl_Position = ModelViewProjectionMatrix * vec4(pos.xy, 0.0f, 1.0f);\n gl_Position.z = 1.0;\n texCoord_interp = texCoord;\n }\n\n '''\nfragment_shader = '''\n in vec2 texCoord_interp;\n out vec4 fragColor;\n \n uniform sampler2D image;\n\n\n void main()\n {\n fragColor = pow(texture(image, texCoord_interp), vec4(0.45f));\n }\n\n'''\n\nclass Help_Draw():\n \n def __init__(self,context):\n self.context = context\n\n def add_handle(self):\n self.handle = bpy.types.SpaceView3D.draw_handler_add(self.bind_image,(),'WINDOW', 'POST_PIXEL') \n \n def remove_handle(self):\n if self.handle:\n bpy.types.SpaceView3D.draw_handler_remove(self.handle, 'WINDOW') \n self.handle = None \n\n def update(self,x,y,width,height): \n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n global vertex_shader\n global fragment_shader\n\n self.shader = gpu.types.GPUShader(vertex_shader, fragment_shader)\n \n self.batch = batch_for_shader(\n self.shader, 'TRI_FAN',\n { \n \"pos\": ((self.x, self.y),(self.width, self.y),(self.width, self.height),(self.x,self.height)),\n \"texCoord\": ((0, 0), (1, 0), (1, 1), (0, 1)),\n },\n )\n \n def set_image(self, img_name):\n script_file = os.path.realpath(__file__)\n script_dir = os.path.dirname(script_file)\n \n rel_filepath = bpy.path.abspath(script_dir+\"//img/\"+img_name)\n try:\n self.image = bpy.data.images.load(rel_filepath, check_existing=True) \n self.image.gl_load()\n return self.image\n except:\n pass\n\n def get_image(self):\n return self.image\n \n\n def draw_text(self,text):\n font_id = 0\n blf.position(font_id, self.x, self.y, 0)\n blf.size(font_id, 50, 72)\n blf.draw(font_id, text)\n \n def bind_image(self):\n bgl.glEnable(bgl.GL_BLEND)\n if self.image is not None:\n try:\n bgl.glActiveTexture(bgl.GL_TEXTURE0)\n bgl.glBindTexture(bgl.GL_TEXTURE_2D,self.image.bindcode)\n\n self.shader.bind()\n self.shader.uniform_int(\"image\", 0)\n self.batch.draw(self.shader) \n return True\n except:\n pass\n bgl.glDisable(bgl.GL_BLEND)\n return False \n\n\nclass Help_Govie_Operator(bpy.types.Operator):\n bl_idname = \"scene.help_govie\"\n bl_label = \"Help\"\n bl_description = \"Description that shows in blender tooltips\"\n bl_options = {\"REGISTER\"}\n\n image_name : bpy.props.StringProperty(name=\"image_name\",description=\"Name of the Image that should be shown\")\n help_draw = None\n\n @classmethod\n def poll(cls, context):\n return True\n\n def execute(self, context):\n help_clicked = bpy.context.scene.help_govie_tools\n self.help_draw = self.__class__.help_draw\n\n if self.help_draw is None: \n self.help_draw = Help_Draw(context)\n self.__class__.help_draw = self.help_draw\n\n if help_clicked: \n self.help_draw.set_image(self.image_name)\n self.help_draw.add_handle()\n self.draw_image(50,30)\n else:\n self.help_draw.remove_handle()\n return{\"FINISHED\"}\n \n context.window_manager.modal_handler_add(self)\n return {\"RUNNING_MODAL\"}\n\n def modal(self, context, event):\n \n help_clicked = bpy.context.scene.help_govie_tools\n if event.type == 'MOUSEMOVE':\n try:\n context.area.tag_redraw()\n self.draw_image(50,30)\n except:\n pass\n\n if not help_clicked :\n return{'FINISHED'}\n\n return {'PASS_THROUGH'}\n\n def draw_image(self,margin_top, margin_buttom):\n # positioning\n try:\n view = [area for area in bpy.context.screen.areas if area.type == 'VIEW_3D'][0]\n region = [region for region in bpy.context.area.regions if region.type ==\"UI\"][0]\n\n image = self.help_draw.get_image()\n if image is not None:\n x1 = view.width-(region.width+image.size[0])\n y1 = view.height-(image.size[1]+margin_top)\n x2 = x1+image.size[0]\n y2 = y1+image.size[1]\n\n # prevent image bigger than view\n if y1 < 0:\n diff = y1\n y1 = 0 + margin_buttom\n x1 -= diff\n if x1 < 0:\n diff = x1\n x1 = 0\n y1 -= diff\n\n self.help_draw.update(x1,y1,x2,y2)\n\n except:\n pass\n\n\n","sub_path":"help_overlay.py","file_name":"help_overlay.py","file_ext":"py","file_size_in_byte":5066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"450495194","text":"\"\"\"\nThis module provides functionality for normalizing protein data.\n\nLevels can be extracted from supernatant or phosphotyrosine runs using median\nor mean peptide levels across multiple channels.\n\"\"\"\n\nfrom __future__ import absolute_import, division\n\n# Built-ins\nfrom collections import OrderedDict\nimport logging\nimport os\nimport warnings\n\n# Core data analysis libraries\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom scipy import stats\n\nimport pyproteome as pyp\n\nLOGGER = logging.getLogger(\"pyproteome.levels\")\nWARN_PEP_CUTOFF = 50\n\n\ndef get_channel_levels(\n data,\n folder_name=None,\n file_name=None,\n cols=2,\n):\n \"\"\"\n Calculate channel normalization levels. This value is calculated by\n selecting the peak of Gaussian KDE distribution fitted to channel ratio\n values.\n\n Parameters\n ----------\n data : :class:`pyproteome.data_sets.DataSet`\n folder_name : str, optional\n file_name : str, optional\n cols : int, optional\n Number of columns used when displaying KDE distributions.\n\n Returns\n -------\n dict of str, float\n \"\"\"\n if not file_name:\n file_name = \"channel_levels.png\"\n\n folder_name = pyp.utils.make_folder(\n data=data,\n folder_name=folder_name,\n sub=\"Normalization\",\n )\n\n channel_names = list(data.channels.keys())\n channels = list(data.channels.values())\n channel_levels = OrderedDict()\n base = channels[0]\n channel_levels[base] = 1\n\n rows = int(np.ceil(len(data.channels) / cols))\n f, axes = plt.subplots(\n rows, cols,\n sharex=True,\n sharey=True,\n figsize=(3 * cols, 3 * rows),\n )\n axes = [i for j in axes for i in j]\n ax_iter = iter(axes)\n\n means = data.psms[channels].mean(axis=1)\n # return {key: 1 for key in data.channels.values()}\n\n for col_name, col in zip(channel_names, channels):\n points = (data.psms[col] / means).dropna()\n\n if points.shape[0] < WARN_PEP_CUTOFF:\n LOGGER.warning(\n (\n \"{}: Too few peptides for normalization, \"\n \"quantification may be inaccurate \"\n \" ({} peptides for {}: {})\"\n ).format(data.name, points.shape[0], col_name, col)\n )\n\n if points.shape[0] < 1:\n channel_levels[col] = 1\n continue\n else:\n # Fit a guassian and find its maximum\n gaus = stats.kde.gaussian_kde(points)\n x = np.arange(0, 10, .01)\n y = np.array(gaus.pdf(x))\n med = x[y == y.max()][0]\n\n channel_levels[col] = med\n\n ax = next(ax_iter)\n\n # seaborn==0.9.0 throws a scipy.stats warning\n with warnings.catch_warnings():\n warnings.filterwarnings(\n 'ignore',\n '',\n FutureWarning,\n )\n sns.distplot(\n points,\n bins=25,\n ax=ax,\n )\n\n ax.set_title(\n \"{} ({})\".format(col_name, col)\n if isinstance(data.channels, dict) else\n col,\n )\n\n txt = \"center = {:.2f}\\n$\\\\sigma$ = {:.2f}\".format(\n med,\n points.std(ddof=1),\n )\n ax.axvline(med, color='k', linestyle='--')\n\n ax.text(\n s=txt,\n x=ax.get_xlim()[1] * .9,\n y=1,\n color='k',\n horizontalalignment='right',\n verticalalignment='center',\n ).set_bbox(\n dict(\n # facecolor=_get_color(txt, x, y),\n alpha=1,\n linewidth=0.5,\n facecolor=\"white\",\n zorder=1,\n edgecolor=\"black\",\n boxstyle=\"round\",\n )\n )\n\n for ax in ax_iter:\n ax.axis(\"off\")\n\n f.suptitle(\n \"{}\".format(data.name),\n fontsize=16,\n )\n\n if file_name:\n f.savefig(\n os.path.join(folder_name, file_name),\n bbox_inches=\"tight\",\n dpi=pyp.utils.DEFAULT_DPI,\n transparent=True,\n )\n\n return channel_levels\n","sub_path":"pyproteome/levels.py","file_name":"levels.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"419715867","text":"from flask import Flask, render_template, request, redirect\r\nfrom flask_sqlalchemy import SQLAlchemy\r\n\r\nfrom Forms.UserForm import UserForm\r\nfrom Forms.ContestForm import ContestForm\r\nfrom Forms.EventForm import EventForm\r\nfrom Forms.PlaceForm import PlaceForm\r\nfrom Forms.PeopleFormEdit import PeopleFormEdit\r\nfrom Forms.EventFormEdit import EventFormEdit\r\nfrom Forms.ContestFormEdit import ContestFormEdit\r\nfrom Forms.PlaceFormEdit import PlaceFormEdit\r\n\r\nfrom sqlalchemy.sql import func\r\nimport plotly\r\nimport plotly.graph_objs as go\r\n\r\nimport json\r\n\r\nfrom Forms.UserForm import UserForm\r\n\r\napp = Flask(__name__)\r\napp.secret_key = 'key'\r\n\r\nENV = 'prod'\r\n\r\nif ENV == 'dev':\r\n app.debug = True\r\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Trouble228@localhost/LABA2'\r\nelse:\r\n app.debug = False\r\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://jqmtgtltfxjxyw:5d4ed79bfdf9814b34a3483aa0bcfd112fae242e1b10692629464e2a72a470ba@ec2-174-129-253-101.compute-1.amazonaws.com:5432/daeiv5k0b4d4pp'\r\n\r\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\r\n\r\ndb = SQLAlchemy(app)\r\n\r\n\r\n\r\nclass Contest(db.Model):\r\n tablename = 'contest'\r\n contest_name = db.Column(db.String(20), primary_key=True)\r\n event_name = db.Column(db.String(20), db.ForeignKey('event.event_name'))\r\n\r\n\r\nclass People(db.Model):\r\n tablename = 'People'\r\n people_email = db.Column(db.String(20), primary_key=True)\r\n people_name = db.Column(db.String(20))\r\n people_phone = db.Column(db.String(20))\r\n people_birthday = db.Column(db.Date)\r\n\r\n people_event = db.relationship('Event')\r\n\r\n\r\nclass association(db.Model):\r\n __tablename__ = 'associate_table'\r\n left_name = db.Column(db.String(20), db.ForeignKey('event.event_name'), primary_key=True)\r\n right_name = db.Column(db.String(20), db.ForeignKey('place.place_name'), primary_key=True)\r\n\r\n\r\nclass Event(db.Model):\r\n __tablename__ = 'event'\r\n event_name = db.Column(db.String(20), primary_key=True)\r\n people_email = db.Column(db.String(20), db.ForeignKey('people.people_email'))\r\n event_date = db.Column(db.Date)\r\n\r\n place_name_fk = db.relationship(\"Place\", secondary='associate_table')\r\n event_contest = db.relationship('Contest')\r\n\r\n\r\nclass Place(db.Model):\r\n __tablename__ = 'place'\r\n place_name = db.Column(db.String(20), primary_key=True)\r\n place_adress = db.Column(db.String(100))\r\n\r\n event_name_fk = db.relationship(\"Event\", secondary='associate_table')\r\n\r\n\r\n# создание всех таблиц\r\ndb.create_all()\r\n\r\n\r\n\r\n# очистка всех таблиц\r\ndb.session.query(association).delete()\r\ndb.session.query(Contest).delete()\r\ndb.session.query(Event).delete()\r\ndb.session.query(People).delete()\r\ndb.session.query(Place).delete()\r\n\r\n\r\n# # # создане объектов\r\n#\r\n# insert into People (people_email, people_name, people_phone, people_birthday) values ('aaa@gmail.com', 'aaa', '+47447474774', '1835-1-23');\r\n#\r\n# insert into People (people_email, people_name, people_phone, people_birthday) values ('bbb@gmail.com', 'bbb', '+399489384334', '487-2-21');\r\n#\r\n# insert into People (people_email, people_name, people_phone, people_birthday) values ('ccc@gmail.com', 'ccc', '+23232332323', '1637-6-23');\r\n#\r\n# insert into People (people_email, people_name, people_phone, people_birthday) values ('ddd@gmail.com', 'ddd', '+39842349238492', '1-1-1');\r\n#\r\n# insert into People (people_email, people_name, people_phone, people_birthday) values ('eee@gmail.com', 'eee', '+304930432432', '1049-1-1');\r\n#\r\n\r\naaa = People(people_email = 'aaa@gmail.com',\r\n people_name = 'aaa',\r\n people_phone = '+47447474774',\r\n people_birthday = \"1835-01-23\"\r\n )\r\n\r\nbbb = People(people_email = 'bbb@gmail.com',\r\n people_name = 'bbb',\r\n people_phone = '+399489384334',\r\n people_birthday = '487-2-21'\r\n )\r\n\r\nccc = People(people_email = 'ccc@gmail.com',\r\n people_name = 'ccc',\r\n people_phone = '+23232332323',\r\n people_birthday = '1637-6-23'\r\n )\r\n\r\nddd = People(people_email = 'ddd@gmail.com',\r\n people_name = 'ddd',\r\n people_phone = '+39842349238492',\r\n people_birthday = '1-1-1'\r\n )\r\n\r\neee = People(people_email = 'eee@gmail.com',\r\n people_name = 'eee',\r\n people_phone = '+304930432432',\r\n people_birthday = '1049-1-1'\r\n )\r\n\r\n\r\n# insert into Event (event_name, people_email, event_date) values ('mg', 'ddd@gmail.com', '1051-1-4');\r\n#\r\n# insert into Event (event_name, people_email, event_date) values ('christmas', 'bbb@gmail.com', '1619-3-8');\r\n#\r\n# insert into Event (event_name, people_email, event_date) values ('new year', 'aaa@gmail.com', '1994-12-2');\r\n#\r\n# insert into Event (event_name, people_email, event_date) values ('oktoberfest', 'ddd@gmail.com', '538-10-29');\r\n#\r\n# insert into Event (event_name, people_email, event_date) values ('football', 'ddd@gmail.com', '1-1-1');\r\n\r\nmg = Event(event_name = 'mg',\r\n people_email = 'ddd@gmail.com',\r\n event_date = '1051-1-4')\r\n\r\nchristmas = Event(event_name = 'christmas',\r\n people_email = 'bbb@gmail.com',\r\n event_date = '1619-3-8'\r\n )\r\n\r\nnew_year = Event(event_name = 'new year',\r\n people_email = 'aaa@gmail.com',\r\n event_date = '1994-12-2'\r\n )\r\n\r\noktoberfest = Event(event_name = 'oktoberfest',\r\n people_email = 'ddd@gmail.com',\r\n event_date = '538-10-29'\r\n )\r\n\r\nfootball = Event(event_name = 'football',\r\n people_email = 'ddd@gmail.com',\r\n event_date = '1-1-1'\r\n )\r\n\r\n\r\n# insert into Place (place_name, place_adress) values ('museum', 'Киевская, Киев, Ковальський провулок, 5, 5-26');\r\n#\r\n# insert into Place (place_name, place_adress) values ('club', 'Hindenburgstraße 7a, 57072 Siegen');\r\n#\r\n# insert into Place (place_name, place_adress) values ('restaurant', 'Hindenburgstraße 12, 57072 Siegen');\r\n#\r\n# insert into Place (place_name, place_adress) values ('stadion', 'Leimbachstadion, Leimbachstraße 263, 57074 Siegen');\r\n#\r\n# insert into Place (place_name, place_adress) values ('theatre', 'Morleystraße 1, 57072 Siegen');\r\n\r\nmuseum = Place(place_name = 'museum',\r\n place_adress = 'Киевская, Киев, Ковальський провулок, 5, 5-26'\r\n )\r\n\r\nclub = Place(place_name = 'club',\r\n place_adress = 'Hindenburgstraße 7a, 57072 Siegen'\r\n )\r\n\r\nrestaurant = Place(place_name = 'restaurant',\r\n place_adress = 'Hindenburgstraße 12, 57072 Siegen'\r\n )\r\n\r\nstadion = Place(place_name = 'stadion',\r\n place_adress = 'Leimbachstadion, Leimbachstraße 263, 57074 Siegen'\r\n )\r\n\r\ntheatre = Place(place_name = 'theatre',\r\n place_adress = 'Morleystraße 1, 57072 Siegen')\r\n\r\n\r\n# insert into Contest (contest_name, event_name) values ('bier', 'football');\r\n#\r\n# insert into Contest (contest_name, event_name) values ('present', 'new year');\r\n#\r\n# insert into Contest (contest_name, event_name) values ('speed', 'christmas');\r\n#\r\n# insert into Contest (contest_name, event_name) values ('bottle of wine', 'christmas');\r\n#\r\n# insert into Contest (contest_name, event_name) values ('bierpong', 'oktoberfest');\r\n\r\nbier = Contest(contest_name = 'bier',\r\n event_name = 'football'\r\n )\r\n\r\npresent = Contest(contest_name = 'present',\r\n event_name = 'new year'\r\n )\r\n\r\nspeed = Contest(contest_name = 'speed',\r\n event_name = 'christmas'\r\n )\r\n\r\nbottle_of_wine = Contest(contest_name = 'bottle of wine',\r\n event_name = 'christmas'\r\n )\r\n\r\nbierpong = Contest(contest_name = 'bierpong',\r\n event_name = 'oktoberfest'\r\n )\r\n\r\n\r\nddd.people_event.append(mg)\r\nbbb.people_event.append(christmas)\r\naaa.people_event.append(new_year)\r\nddd.people_event.append(oktoberfest)\r\nddd.people_event.append(football)\r\n\r\nfootball.event_contest.append(bier)\r\nnew_year.event_contest.append(present)\r\nchristmas.event_contest.append(speed)\r\nchristmas.event_contest.append(bottle_of_wine)\r\noktoberfest.event_contest.append(bierpong)\r\n\r\nmg.place_name_fk.append(museum)\r\nchristmas.place_name_fk.append(club)\r\nnew_year.place_name_fk.append(restaurant)\r\noktoberfest.place_name_fk.append(stadion)\r\nfootball.place_name_fk.append(theatre)\r\n\r\n\r\ndb.session.add_all([aaa, bbb, ccc, ddd, eee,\r\n mg, christmas, new_year, oktoberfest, football,\r\n museum, club, restaurant, stadion, theatre,\r\n bier, present, speed, bottle_of_wine, bierpong\r\n])\r\n\r\ndb.session.commit()\r\n\r\n\r\n\r\n@app.route('/dashboard', methods=['GET', 'POST'])\r\ndef dashboard():\r\n query1 = (\r\n db.session.query(\r\n People.people_name,\r\n func.count(Event.event_name).label('event_name')\r\n ).join(Event, People.people_email == Event.people_email).\r\n group_by(People.people_name)\r\n ).all()\r\n\r\n print(query1)\r\n\r\n query2 = (\r\n db.session.query(\r\n Event.event_name,\r\n func.count(Contest.contest_name).label('contest_name')\r\n ).join(Contest, Event.event_name == Contest.event_name).\r\n group_by(Event.event_name)\r\n ).all()\r\n\r\n print(query2)\r\n\r\n people_name, event_name = zip(*query1)\r\n bar = go.Bar(\r\n x=people_name,\r\n y=event_name\r\n )\r\n\r\n event_name, contest_name = zip(*query2)\r\n pie = go.Pie(\r\n labels=event_name,\r\n values=contest_name\r\n )\r\n\r\n data = {\r\n \"bar\": [bar],\r\n \"pie\": [pie]\r\n }\r\n graphs_json = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)\r\n\r\n return render_template('dashboard.html', graphsJSON=graphs_json)\r\n\r\n@app.route('/edit_people/', methods=['GET', 'POST'])\r\ndef edit_people(email):\r\n form = PeopleFormEdit()\r\n result = db.session.query(People).filter(People.people_email == email).one()\r\n\r\n if request.method == 'GET':\r\n\r\n form.people_name.data = result.people_name\r\n form.people_email.data = result.people_email\r\n form.people_birthday.data = result.people_birthday\r\n form.people_phone.data = result.people_phone\r\n\r\n\r\n return render_template('edit_people.html', form=form, form_name=email)\r\n elif request.method == 'POST':\r\n\r\n result.people_name = form.people_name.data\r\n result.user_email = form.people_email.data\r\n result.people_birthday = form.people_birthday.data.strftime(\"%Y-%m-%d\"),\r\n result.people_phone = form.people_phone.data\r\n\r\n db.session.commit()\r\n return redirect('/people')\r\n\r\n\r\n@app.route('/edit_event/', methods=['GET', 'POST'])\r\ndef edit_event(name):\r\n form = EventFormEdit()\r\n result = db.session.query(Event).filter(Event.event_name == name).one()\r\n\r\n if request.method == 'GET':\r\n\r\n form.event_name.data = result.event_name\r\n form.event_date.data = result.event_date\r\n\r\n\r\n return render_template('edit_event.html', form=form, form_name=name)\r\n elif request.method == 'POST':\r\n\r\n result.event_name = form.event_name.data\r\n result.event_date = form.event_date.data.strftime(\"%Y-%m-%d\"),\r\n\r\n db.session.commit()\r\n return redirect('/event')\r\n\r\n\r\n\r\n@app.route('/edit_contest/', methods=['GET', 'POST'])\r\ndef edit_contest(name):\r\n form = ContestFormEdit()\r\n result = db.session.query(Contest).filter(Contest.contest_name == name).one()\r\n\r\n if request.method == 'GET':\r\n\r\n form.contest_name.data = result.contest_name\r\n\r\n\r\n return render_template('edit_contest.html', form=form, form_name='Edit Contest')\r\n elif request.method == 'POST':\r\n\r\n result.contest_name = form.contest_name.data\r\n\r\n db.session.commit()\r\n return redirect('/contest')\r\n\r\n\r\n@app.route('/edit_place/', methods=['GET', 'POST'])\r\ndef edit_place(name):\r\n form = PlaceFormEdit()\r\n result = db.session.query(Place).filter(Place.place_name == name).one()\r\n\r\n if request.method == 'GET':\r\n\r\n form.place_name.data = result.place_name\r\n form.place_adress.data = result.place_adress\r\n\r\n\r\n return render_template('edit_place.html', form=form, form_name='Edit Place')\r\n elif request.method == 'POST':\r\n\r\n result.place_name = form.place_name.data\r\n result.place_adress = form.place_adress.data\r\n\r\n db.session.commit()\r\n return redirect('/place')\r\n\r\n\r\n@app.route('/create_people', methods=['POST', 'GET'])\r\ndef create_people():\r\n form = UserForm()\r\n\r\n if request.method == 'POST':\r\n new_people = People(\r\n people_name=form.people_name.data,\r\n people_birthday=form.people_birthday.data.strftime(\"%Y-%m-%d\"),\r\n people_email=form.people_email.data,\r\n people_phone=form.people_phone.data,\r\n )\r\n db.session.add(new_people)\r\n db.session.commit()\r\n return redirect('/people')\r\n elif request.method == 'GET':\r\n return render_template('create_people.html', form=form)\r\n\r\n\r\n@app.route('/delete_people/', methods=['GET', 'POST'])\r\ndef delete_people(email):\r\n result = db.session.query(People).filter(People.people_email == email).one()\r\n\r\n db.session.delete(result)\r\n db.session.commit()\r\n\r\n return redirect('/people')\r\n\r\n\r\n\r\n@app.route('/create_contest', methods=['POST', 'GET'])\r\ndef create_contest():\r\n form = ContestForm()\r\n\r\n if request.method == 'POST':\r\n new_contest = Contest(\r\n contest_name=form.contest_name.data,\r\n )\r\n db.session.add(new_contest)\r\n db.session.commit()\r\n return redirect('/contest')\r\n elif request.method == 'GET':\r\n return render_template('create_contest.html', form=form)\r\n\r\n\r\n@app.route('/delete_contest/', methods=['GET', 'POST'])\r\ndef delete_contest(name):\r\n result = db.session.query(Contest).filter(Contest.contest_name == name).one()\r\n\r\n db.session.delete(result)\r\n db.session.commit()\r\n\r\n return redirect('/contest')\r\n\r\n\r\n@app.route('/create_event', methods=['POST', 'GET'])\r\ndef create_event():\r\n form = EventForm()\r\n\r\n if request.method == 'POST':\r\n new_event = Event(\r\n event_name=form.event_name.data,\r\n event_date=form.event_date.data.strftime(\"%Y-%m-%d\")\r\n )\r\n db.session.add(new_event)\r\n db.session.commit()\r\n return redirect('/event')\r\n elif request.method == 'GET':\r\n return render_template('create_event.html', form=form)\r\n\r\n\r\n@app.route('/delete_event/', methods=['GET', 'POST'])\r\ndef delete_event(name):\r\n result = db.session.query(Event).filter(Event.event_name == name).one()\r\n\r\n db.session.delete(result)\r\n db.session.commit()\r\n\r\n return redirect('/event')\r\n\r\n\r\n@app.route('/create_place', methods=['POST', 'GET'])\r\ndef create_place():\r\n form = PlaceForm()\r\n\r\n if request.method == 'POST':\r\n new_place = Place(\r\n place_name=form.place_name.data,\r\n place_adress=form.place_adress.data\r\n )\r\n db.session.add(new_place)\r\n db.session.commit()\r\n return redirect('/place')\r\n elif request.method == 'GET':\r\n return render_template('create_place.html', form=form)\r\n\r\n\r\n@app.route('/delete_place/', methods=['GET', 'POST'])\r\ndef delete_place(name):\r\n result = db.session.query(Place).filter(Place.place_name == name).one()\r\n\r\n db.session.delete(result)\r\n db.session.commit()\r\n\r\n return redirect('/place')\r\n\r\n\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef root():\r\n\r\n return render_template('index.html')\r\n\r\n@app.route('/people', methods=['GET'])\r\ndef all_peolpe():\r\n result = db.session.query(People).all()\r\n\r\n return render_template('all_people.html', result=result)\r\n\r\n\r\n@app.route('/contest', methods=['GET'])\r\ndef all_contest():\r\n result = db.session.query(Contest).all()\r\n\r\n return render_template('all_contest.html', result=result)\r\n\r\n\r\n@app.route('/event', methods=['GET'])\r\ndef all_event():\r\n result = db.session.query(Event).all()\r\n\r\n return render_template('all_event.html', result=result)\r\n\r\n\r\n@app.route('/place', methods=['GET'])\r\ndef all_place():\r\n result = db.session.query(Place).all()\r\n\r\n return render_template('all_place.html', result=result)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run()\r\n\r\n\r\n","sub_path":"Laboratory2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":16711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"173511166","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom store.models import Product, Variation\nfrom .models import Cart, CartItem\n\n\ndef _crat_id(request):\n cart = request.session.session_key\n if not cart:\n request.session.create()\n return cart\n\n\ndef add_cart(request, product_id):\n product = Product.objects.get(id=product_id)\n product_variation = []\n if request.method == 'POST':\n for item in request.POST:\n key = item\n value = request.POST[key]\n try:\n variation = Variation.objects.get(product=product, variation_category=key,\n variation_value=value)\n product_variation.append(variation)\n except:\n pass\n\n try:\n cart = Cart.objects.get(cart_id=_crat_id(request))\n except Cart.DoesNotExist:\n cart = Cart.objects.create(\n cart_id=_crat_id(request)\n )\n cart.save()\n is_cart_item_exists = CartItem.objects.filter(product=product, cart=cart).exists()\n if is_cart_item_exists:\n cart_item = CartItem.objects.filter(product=product, cart=cart)\n ex_var_list = []\n ids = []\n for item in cart_item:\n existing_variation = item.variations.all()\n ex_var_list.append(list(existing_variation))\n ids.append(item.id)\n if product_variation in ex_var_list:\n index = ex_var_list.index(product_variation)\n item_id = ids[index]\n item = CartItem.objects.get(product=product, id=item_id)\n item.quantity += 1\n item.save()\n else:\n item = CartItem.objects.create(product=product, quantity=1, cart=cart)\n if product_variation:\n item.variations.clear()\n item.variations.add(*product_variation)\n item.save()\n else:\n cart_item = CartItem.objects.create(\n product=product,\n cart=cart,\n quantity=1,\n )\n if product_variation:\n cart_item.variations.clear()\n cart_item.variations.add(*product_variation)\n cart_item.save()\n return redirect('cart')\n\n\ndef decrease_cart(request, product_id, cart_item_id):\n cart = Cart.objects.get(cart_id=_crat_id(request))\n product = get_object_or_404(Product, id=product_id)\n try:\n cart_item = CartItem.objects.get(product=product, cart=cart, id=cart_item_id)\n if cart_item.quantity > 1:\n cart_item.quantity -= 1\n cart_item.save()\n else:\n cart_item.delete()\n except:\n pass\n return redirect('cart')\n\n\ndef remove_cart(request, product_id, cart_item_id):\n cart = Cart.objects.get(cart_id=_crat_id(request))\n product = get_object_or_404(Product, id=product_id)\n cart_item = CartItem.objects.get(product=product, cart=cart, id=cart_item_id)\n cart_item.delete()\n\n return redirect('cart')\n\n\ndef cart(request, total=0, quantity=0, cart_item=None):\n try:\n cart = Cart.objects.get(cart_id=_crat_id(request))\n cart_item = CartItem.objects.filter(cart=cart)\n for item in cart_item:\n total += (item.product.price * item.quantity)\n quantity += item.quantity\n except:\n pass\n context = {\n 'total': total,\n 'quantity': quantity,\n 'cart_item': cart_item,\n }\n\n return render(request, 'store/cart.html', context)\n","sub_path":"cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"380274109","text":"import pandas as pd\nimport pandasql as ps\nimport math\nimport re\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\n\ndef ridge_kfoldCV(x, y, K, alph):\n subset_in = np.array_split(x, K)\n subset_out = np.array_split(y, K)\n cut_off_x = len(subset_in[K - 1])\n cut_off_y = len(subset_out[K - 1])\n t_mae = []\n c_mae = []\n for i in range(len(subset_in)):\n subset_in[i] = subset_in[i][0:cut_off_x]\n for i in range(len(subset_out)):\n subset_out[i] = subset_out[i][0:cut_off_y]\n type = Ridge(alpha=alph, fit_intercept=True)\n for i in range(K):\n validation_setin = np.array(subset_in[i])\n validation_setout = np.array(subset_out[i])\n if (i == 0):\n training_setin = np.concatenate(subset_in[1:])\n training_setout = np.concatenate(subset_out[1:])\n elif (i == K - 1):\n training_setin = np.concatenate(subset_in[0:i])\n training_setout= np.concatenate(subset_out[0:i])\n else:\n training_setin = np.concatenate(np.concatenate((subset_in[0:i], subset_in[i + 1:]), axis=0))\n training_setout = np.concatenate(np.concatenate((subset_out[0:i], subset_out[i + 1:]), axis=0))\n type.fit(X=training_setin, y=training_setout)\n y_pred_val = type.predict(validation_setin)\n y_pred_train = type.predict(training_setin)\n lst = []\n for n in range(len(y_pred_val)):\n tmp = abs(validation_setout[n] - y_pred_val[n])\n lst.append(tmp)\n c_mae.append(np.mean(lst))\n\n lst = []\n for i in range(len(y_pred_train)):\n tmp = abs(training_setout[i] - y_pred_train[i])\n lst.append(tmp)\n t_mae.append(np.mean(lst))\n\n train_error = np.mean(t_mae)\n cv_error = np.mean(c_mae)\n return cv_error, train_error\n\n\ndata = pd.read_csv(\"preprocessed_complete_2006_2016.csv\")\nsubset = data.loc[:, data.columns != 'STREET_NAME']\nsubset = subset.loc[:, subset.columns != 'PROPERTY_POSTAL_CODE']\nsubset = subset.loc[:, subset.columns != 'Unnamed: 0']\nsubset = subset.loc[:, subset.columns != 'PID']\nsubset = subset.loc[:, subset.columns != 'CURRENT_LAND_VALUE_x']\nsubset = subset.loc[:, subset.columns != 'CURRENT_IMPROVEMENT_VALUE_x']\nsubset = subset.loc[:, subset.columns != 'CURRENT_LAND_VALUE_y']\nsubset = subset.loc[:, subset.columns != 'CURRENT_IMPROVEMENT_VALUE_y']\nsubset = subset.loc[:, subset.columns != 'REPORT_YEAR_x']\nsubset = subset.loc[:, subset.columns != 'REPORT_YEAR_y']\nsubset = subset.loc[:, subset.columns != 'STREET_NAME']\nsubset = subset.loc[:, subset.columns != 'TAX_ASSESSMENT_YEAR']\nsubset = subset.loc[:, subset.columns != 'PREVIOUS_IMPROVEMENT_VALUE']\nsubset = subset.loc[:, subset.columns != 'PREVIOUS_LAND_VALUE']\n# subset = subset.loc[:, subset.columns != 'CURRENT_IMPROVEMENT_VALUE_DELTA']\nsubset = subset.loc[:, subset.columns != 'TAX_LEVY_x']\nsubset = subset.loc[:, subset.columns != 'TAX_LEVY_y']\nsubset = subset.loc[:, subset.columns != 'YEAR_BUILT']\nsubset = subset.loc[:, subset.columns != 'BIG_IMPROVEMENT_YEAR']\nsubset = subset.loc[:, subset.columns != ' Total - Age groups and average age of the population - 100% data ']\nsubset = subset.loc[:, subset.columns != ' Total population 15 years and over by presence of children and labour force activity ']\nsubset = subset.loc[:, subset.columns != 'family income']\nsubset = subset.loc[:, subset.columns != 'total martial status']\nsubset = subset.dropna(axis=0, how='any', inplace=False)\n\ntrain_ratio = 0.75\nnum_rows = subset.shape[0]\ntrain_set_size = int(train_ratio * num_rows)\n\ndata_in = subset.drop('CURRENT_LAND_VALUE_DELTA', axis=1, inplace=False)\ndata_out = subset.loc[:, 'CURRENT_LAND_VALUE_DELTA']\n\ntraining_data_in = data_in[:train_set_size]\ntraining_data_out = data_out[:train_set_size]\n\ntest_data_in = data_in[train_set_size:]\ntest_data_out = data_out[train_set_size:]\n\nridge_test = StandardScaler(with_mean=True, with_std=True).fit_transform(test_data_in)\nridge_train = StandardScaler(with_mean=True, with_std=True).fit_transform(training_data_in)\n\n# print(training_data_in.head(200).to_string())\n\nalpha = [10**-3, 10**-2, 10**-1, 10**0, 10**1, 10**2, 10**3, 10**4, 10**5, 10**6, 10**7, 10**8, 10**9, 10**10]\nalpha_plot = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nc_mae_array = []\nt_mae_array = []\nfor i in range(len(alpha)):\n mae_vals = ridge_kfoldCV(ridge_train, training_data_out, 3, alpha[i])\n c_mae_array.append(mae_vals[0])\n t_mae_array.append(mae_vals[1])\n\n\nplt.plot(alpha_plot, c_mae_array)\nplt.plot(alpha_plot, t_mae_array)\nplt.suptitle(\"Ridge regression on 5 fold-cross validation w/ alphas $10^{-3}$ to $10^{10}$\")\nplt.xlabel(\"λ = \")\nplt.ylabel(\"Errors\")\nplt.legend(['y = cv_error', 'y = train_error'], loc='upper left')\nplt.show()\n\nchosenLamb = Ridge(alpha=10**5)\nchosenLamb.fit(ridge_train, training_data_out)\ncoeffs = chosenLamb.coef_\nindex = np.argpartition(np.abs(coeffs), -20)[-20:]\nprint(\"\\nTop ten features for Ridge\\n: \")\nfor i in index:\n print(data_in.columns[i])\n print(coeffs[i])\n\nprint(training_data_in.columns)","sub_path":"ridgepred.py","file_name":"ridgepred.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"560125054","text":"#Email:fanyucai1@126.com\n#2019.3.13\nimport argparse\nimport pandas as pd\nimport subprocess\nimport os\nimport pymrmr\nblca=\"/home/fanyucai/low_CNV/test_data/blca_CNA_data.txt\"\nucec=\"/home/fanyucai/low_CNV/test_data/ucec_CNA_data.txt\"\nprint(\"blca download from: http://cbio.mskcc.org/cancergenomics/pancan_tcga/cna/blca_CNA_data.txt\")\nprint(\"ucec downloda from: http://cbio.mskcc.org/cancergenomics/pancan_tcga/cna/ucec_CNA_data.txt\")\nout=pd.DataFrame()\n\ndf = pd.read_csv(blca,sep=\"\\t\")\ndata=df.T\ndata=data.iloc[3:,]\nprint(\"blca contains %s samples and %s genes\" %(data.shape[0],data.shape[1]))\ndata.insert(0,'class',0)\nout=out.append(data)\n\n\ndf = pd.read_csv(ucec,sep=\"\\t\")\ndata=df.T\ndata=data.iloc[3:,]\nprint(\"ucec contains %s samples and %s genes\" %(data.shape[0],data.shape[1]))\ndata.insert(0,'class',1)\nout=out.append(data)\nout=out.reset_index(drop=True)\nout.columns=\"v\"+out.columns.astype(str)\nout=out.rename(columns={'vclass':'class'})\ndf=pymrmr.mRMR(out, 'MIQ', 10)\nout.to_csv(\"/home/fanyucai/low_CNV/test_data/CNV.csv\",sep=\"\\t\",index=False)\n\nq=pymrmr.mRMR(df, 'MIQ', 30)\nprint(q)\n","sub_path":"CNV_prepare.py","file_name":"CNV_prepare.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"63790248","text":"from numpy import random\nimport math\n# picks numbers between 0 and 1\n# round ends when the sum of the numbers is greater than 1\n# sx is the sum of the numbers (x)\n# r is the rounds that each game lasted\n# rounds is a list of r for any given number of trials\n\nrounds = []\ndef game():\n\tsx, r = 0.0, 0.0\n\t#print('Your numbers:')\n\twhile sx <= 1:\n\t\tx = random.uniform(0,1)\n\t\tsx += x\n\t\tr += 1\n\t\t#print(x)\n\trounds.append(r)\n\t#print(rounds)\n\t#print('your game lasted ' + str(r) + ' rounds')\ntrials = 500000\nfor i in range(trials):\n\tgame()\nscore = sum(rounds)\navg = score/trials\nprint('Average rounds of games is ' + str(avg)) #comment out prints besides this line try with large trials\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"633406462","text":"from behave import given, when, then\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\nTOOLBAR_TEXT_BOLD = (By.CSS_SELECTOR, \"h1 span.a-text-bold\")\nCARD_ITEM_COUNT = (By.ID, 'nav-cart-count')\nEMAIL_FIELD = (By.CSS_SELECTOR, \"input[type='email']\")\nITEM_NAME = (By.CSS_SELECTOR, \"a[id='dealTitle']\")\nFIRST_ELEMENT_IN_DEALS = (By.CSS_SELECTOR, \"div[id='octopus-dlp-asin-stream'] [class='a-box a-box-normal a-color-base-background']\")\nCART_BUTTON = (By.ID, 'add-to-cart-button')\n\n@then('Search results for {product} is shown')\ndef verify_result(context, product):\n # result_text = context.driver.find_element(*TOOLBAR_TEXT_BOLD).text\n # assert product in result_text, \"Expected text is {product}, but got {result_text}\"\n context.app.search_results_page.verify_result_shown(product)\n\n@then('Verify cart has {expected_number} item')\ndef verify_number_of_item(context, expected_number):\n context.driver.wait.until(EC.element_to_be_clickable)\n actual_number_of_items = len(context.driver.find_element(*CARD_ITEM_COUNT).text)\n assert actual_number_of_items == int(\n expected_number), f'Expected {expected_number}, but got {actual_number_of_items}'\n\n\n@when('Put item in the cart')\ndef put_item_in_cart(context):\n context.driver.find_element(*ITEM_NAME).click()\n sleep(5)\n item_numbers = context.driver.find_elements(*FIRST_ELEMENT_IN_DEALS)\n if len(item_numbers) > 1:\n item_numbers[0].click()\n context.driver.find_element(*CART_BUTTON).click()\n\n\n@then('Verify Sign In page is opened')\ndef verify_signin_opened(context):\n context.driver.find_element(*EMAIL_FIELD)\n assert 'https://www.amazon.com/ap/signin' in context.driver.current_url\n #context.app.search_results_page.verify_sign_in_opened('https://www.amazon.com/ap/signin')\n","sub_path":"features/steps/product_results_page_steps.py","file_name":"product_results_page_steps.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"382951045","text":" # -*- coding: utf-8 -*-\n\nimport numpy as np \nimport matplotlib.pyplot as plt #2\n\ndef mans_funkcija(x):\n k = 1\n a = (-1)**2*x**2/(2*2)\n S = a\n\n while k < 500: \n k = k + 1\n R = (-1) * x**2/((2*k-1)*(2*k))\n a = a * R\n S = S + a\n return S\na=0\nb=20\ndelta_x = 0.5\nx = np.arange(a,b,delta_x)\ny = mans_funkcija(x)\nplt.plot(x,y)\nplt.grid()\n\n\n# funkcijas atvesinasana apreikins\nn = len(x)\ny_prim = []\nfor i in range(n-1): \n y_prim.append((y[i+1]-y[i])/(x[i+1]-x[i]))\nplt.plot(x[:n-1],y_prim)\n#plt.show() \n\n#n= len(x[:n-1])\ny_prim2= []\nfor i in range (n-2):\n y_prim2.append((y_prim[i+1]-y_prim[i])/(x[i]-x[i-1]))\nplt.plot(x[:n-2],y_prim2)\nplt.show()\n","sub_path":"PYTHON/individual_derivative.py","file_name":"individual_derivative.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"393407165","text":"import requests\nfrom flask import Flask, render_template\n\nfrom app.auth import views as auth_views\nfrom app.user import views as user_views\nfrom app.extensions import db, login_manager\n\n\ndef create_app(config):\n \"\"\"Returns an initialized Flask application.\"\"\"\n app = Flask(__name__, static_url_path='', static_folder='static')\n app.config.from_object(config)\n\n register_extensions(app)\n register_blueprints(app)\n register_errorhandlers(app)\n\n return app\n\n\ndef register_extensions(app):\n \"\"\"Register extensions with the Flask application.\"\"\"\n db.init_app(app)\n login_manager.init_app(app)\n\n\ndef register_blueprints(app):\n \"\"\"Register blueprints with the Flask application.\"\"\"\n app.register_blueprint(auth_views.blueprint)\n app.register_blueprint(user_views.blueprint)\n\n\ndef register_errorhandlers(app):\n \"\"\"Register error handlers with the Flask application.\"\"\"\n\n def render_error(e):\n return render_template('errors/%s.html' % e.code), e.code\n\n for e in [\n requests.codes.INTERNAL_SERVER_ERROR,\n requests.codes.NOT_FOUND,\n requests.codes.UNAUTHORIZED,\n ]:\n app.errorhandler(e)(render_error)\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"263219883","text":"import networkx as nx\nimport os\nimport sys\nimport dynetx as dn\nimport operator\nimport webbrowser\nfrom sortedcontainers import *\nfrom dynetx.utils.bidict import *\nimport numpy as np\n\n\ndef detectAutomaticallyFormat(networkFile):\n format = networkFile.split(\".\")[1]\n return format\n\n\ndef _write_network_file(graph, out_name, out_format=\"edges\", data=False):\n \"\"\"\n Write the graph representation on file using a user specified format\n\n :param graph: networkx graph\n :param out_name: pattern for the output filename\n :param out_format: output format. Accepted values: edgelist|ncol|gefx|gml|pajek\n \"\"\"\n\n if out_format==None:\n out_format=\"edges\"\n os.makedirs(os.path.dirname(out_name), exist_ok=True)\n print(\"writing graph of format \" + out_format + \" at \" + out_name)\n if out_format == 'edges':\n nx.write_edgelist(graph, \"%s\" % (out_name), data=data)\n elif out_format == 'gefx':\n nx.write_gexf(graph, \"%s.gefx\" % (out_name))\n elif out_format == 'gml':\n nx.write_gml(graph, \"%s.gml\" % (out_name))\n elif out_format == 'pajek':\n nx.write_pajek(graph, \"%s.pajek\" % (out_name))\n elif out_format == 'ncol':\n nx.write_edgelist(graph, \"%s.ncol\" % (out_name), delimiter='\\t')\n elif out_format == 'GraphML':\n g = nx.write_graphml(out_name)\n else:\n raise Exception(\"UNKNOWN FORMAT \" + out_format)\n\n\ndef _read_network_file(in_name, in_format=\"\", directed=False):\n \"\"\"\n Read the graph representation on file using a user specified format\n\n :param in_name: pattern for the output filename\n :param in_format: output format. Accepted values: edgelist|ncol|gefx|gml|pajek\n \"\"\"\n\n if in_format == 'edges':\n if directed:\n g = nx.read_edgelist(in_name, create_using=nx.DiGraph())\n else:\n g = nx.read_edgelist(in_name, data=False)\n elif in_format == 'gefx':\n g = nx.read_gexf(in_name)\n elif in_format == 'gml':\n g = nx.read_gml(in_name)\n elif in_format == 'graphml':\n g = nx.read_graphml(in_name)\n nodesInfo = g.nodes(data=True)\n node2Label = {nodeid: data[\"label\"].replace(\" \",\"_\") for (nodeid, data) in nodesInfo}\n g = nx.relabel_nodes(g, node2Label, copy=False)\n elif in_format == 'pajek':\n g = nx.read_pajek(in_name)\n elif in_format == 'ncol':\n g = nx.read_edgelist(in_name)\n else:\n raise Exception(\"UNKNOWN FORMAT \" + in_format)\n return g\n\n\n####################READ WRITE OPERATIONS##################\ndef readSnapshotsDir(inputDir, format=None):\n\n\n anSnGraph = dn.DynGraphSN()\n files = os.listdir(inputDir)\n visibleFiles = [f for f in files if f[0] != \".\"]\n\n if format==None:\n format=detectAutomaticallyFormat(visibleFiles[0])\n\n for f in visibleFiles:\n g = _read_network_file(inputDir + \"/\" + f, format) # type:nx.Graph\n anSnGraph.addSnaphsot(os.path.splitext(f)[0],g)\n\n\n return anSnGraph\n\n\ndef writeSnapshotsDir(dynGraph,outputDir,format=None):\n if format==None:\n format=\"edges\"\n allGraphs = dynGraph.snapshots()\n for g in allGraphs:\n _write_network_file(allGraphs[g],os.path.join(outputDir,str(g)+\".\"+format),out_format=format)\n\ndef write_SG(theDynGraph:dn.DynGraphTN,fileOutput):\n toWrite = []\n toWrite.append([\"LS\", theDynGraph.start, theDynGraph.end])\n for (n, intervs) in theDynGraph.nodesD().items():\n if type(n)is str:\n toAdd = [\"N\", n.replace(\" \",\"_\")]\n else:\n toAdd = [\"N\",n]\n #for interv in dataDic[n]:\n for interv in intervs.getIntervals():\n toAdd += [interv[0], interv[1]]\n toWrite.append(toAdd)\n\n\n for ((n1,n2),intervs) in theDynGraph.edgesD().items():\n toAdd = [\"E\",n1,n2]\n if type(n1) is str:\n toAdd = [\"E\", n1.replace(\" \",\"_\"), n2.replace(\" \",\"_\")]\n for interv in intervs.getIntervals():\n toAdd += [interv[0], interv[1]]\n toWrite.append(toAdd)\n dn.writeArrayOfArrays(toWrite, fileOutput, separator=\"\\t\")\n\n\ndef read_SG(fileInput):\n aDynGraph = dn.DynGraphTN()\n f = open(fileInput)\n for l in f: # for each line\n parts = l.split(\"\\t\")\n if parts[0]==\"N\":\n nodeName = parts[1]\n parts= parts[2:]\n for i in range(0,len(parts),2):\n start=int(parts[i])\n end = int(parts[i+1])\n aDynGraph.add_node(nodeName,start,end)\n\n if parts[0]==\"E\":\n n1 = parts[1]\n n2= parts[2]\n parts = parts[3:]\n for i in range(0,len(parts),2):\n start=int(parts[i])\n end = int(parts[i+1])\n aDynGraph.add_edge(n1,n2,start,end)\n return aDynGraph\n\n\ndef getAutomaticNodeOrder(theDynCom):\n node2Com = {}\n for n in theDynCom.nodes:\n belongings = theDynCom.belongingsT(n) # for each community, belonging duration\n ordered = sorted(belongings.items(), key=operator.itemgetter(1))\n ordered.reverse()\n node2Com[n.replace(\" \", \"_\")] = ordered[0][0] # assigne to each node its main com\n\n return node2Com\n\n\ndef writeNodeOrder(node2Com,fileOutput):\n allMainComs = sorted(set(node2Com.values()))\n\n thefile = open(fileOutput, 'w')\n for c in allMainComs:\n for n in node2Com:\n if node2Com[n] == c:\n thefile.write(n + \"\\n\")\n thefile.close()\n\ndef writeGoodNodeOrder(theDynCom,fileOutput):\n node2com = getAutomaticNodeOrder(theDynCom)\n writeNodeOrder(node2com,fileOutput)\n\ndef writeNaturalNodeOrder(theDynCom,fileOutput):\n nodesNames = sorted(theDynCom.nodes)\n thefile = open(fileOutput, 'w')\n for n in nodesNames:\n thefile.write(n + \"\\n\")\n thefile.close()\n\n\n\n\ndef show(dynCommunities,dynGraph,nodeOrder=\"automatic\"):#nodeOrder can be \"automatic\" or \"natural\"\n dir = os.path.dirname(__file__)\n\n savedEventGraph = dynCommunities.events #hack because currently there is an inconsistency with events in temporal networks\n\n if not isinstance(dynCommunities,dn.dynamicCommunitiesTN):\n dynCommunities = dynCommunities.convertToTNcommunities(convertTimeToInteger=True)\n if not isinstance(dynGraph,dn.DynGraphTN):\n dynGraph = dynGraph.toDynGraphTN()\n\n\n visuAddress = os.path.join(dir, \"visu/LinkStream.html\")\n\n dn.write_SG(dynGraph, os.path.join(dir,\"visu/networks/netData/network.sg\"))\n dynCommunities.writeAsSGC(os.path.join(dir,\"visu/networks/netData/Communities/coms.sgc\"))\n\n nx.write_edgelist(savedEventGraph,os.path.join(dir,\"visu/networks/netData/Communities/events.evts\"))\n #dynCommunities.writeEvents(os.path.join(dir,\"visu/networks/netData/Communities/events.evts\"))\n\n if nodeOrder==\"automatic\":\n dn.writeGoodNodeOrder(dynCommunities, os.path.join(dir,\"visu/networks/netData/nodeOrder\"))\n if nodeOrder==\"natural\":\n writeNaturalNodeOrder(dynCommunities, os.path.join(dir,\"visu/networks/netData/nodeOrder\"))\n\n visuAddress = \"file:///\" + visuAddress\n\n if sys.platform == \"darwin\":\n #visuAddress = \"http://127.0.0.1:8000/\" + visuAddress\n webbrowser.get(\"firefox\").open_new(visuAddress)\n else:\n if sys.platform== \"win32\":\n if webbrowser._tryorder == None or not \"firefox\" in webbrowser._tryorder:\n fpath = \"C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe\"\n webbrowser.register('firefox', None, webbrowser.BackgroundBrowser(fpath))\n #else:\n webbrowser.get(\"firefox\").open_new(visuAddress)\n\ndef writeAsOrderedModifList(dynNet:dn.DynGraphTN, fileOutput,dateEveryLine=False,nodeModifications=False,separator=\"\\t\",edgeIdentifier=\"l\"): #OML\n \"\"\"\n OML :ordered modif list with dates as #DATE and no nodes (Online Modification List)\n OMLN : with nodes\n OMLR : with repeated dates\n OMLRN : nodes and repeated dates\n :param dateEveryLine: if true, date is repeated for each modification (each line). If false, date modification is on its own line (#DATE)\n before the modifications happening at this date\n \"\"\"\n\n if type(dynNet) is dn.DynGraphSN:\n dynNet = dynNet.toDynGraphTN(convertTimeToInteger=False)\n\n timeOfActions = SortedDict()\n #NOTE : can be easily optimized ! one complete check to add and to remove nodes...\n dataDicNodes={}\n if nodeModifications: #note that we add nodes before edges, so that nodes are added before there edges...\n dataDicNodes = dynNet.nodesD()\n\n for (n,intervs) in dataDicNodes.items():\n #times = self.nodes[n]\n for interv in intervs.getIntervals():\n addDate = interv[0]\n\n #delDate = maxInterval(interv)\n timeOfActions.setdefault(addDate,[]).append(\"+n\" + separator + str(n))\n\n dataDicEdges = dynNet.edgesD()\n\n for (e,intervs) in dataDicEdges.items():\n #print(\"e\",e,intervs)\n #times = self.edges[e]\n for interv in intervs.getIntervals():\n addDate = interv[0]\n delDate = interv[1]\n (node1, node2) = list(e)\n if not addDate in timeOfActions:\n timeOfActions[addDate] = []\n if not delDate in timeOfActions:\n timeOfActions[delDate] = []\n timeOfActions[addDate].append(\"+\"+edgeIdentifier+separator + str(node1) + separator + str(node2))\n timeOfActions[delDate].append(\"-\"+edgeIdentifier+separator + str(node1) + separator + str(node2))\n\n if nodeModifications: # note that we remove nodes after edges,...\n for (n,intervs) in dataDicNodes.items():\n #times = self.nodes[n]\n for interv in intervs.getIntervals():\n delDate = interv[1]\n\n if not delDate in timeOfActions:\n timeOfActions[delDate] = []\n timeOfActions[delDate].append(\"-n\" + separator + str(n))\n\n #(orderedKeys, orderedValues) = fromDictionaryOutputOrderedKeysAndValuesByKey(timeOfActions)\n toWrite = []\n for k in timeOfActions: #sorted because sorteddict\n if not dateEveryLine:\n toWrite.append([\"#\" + str(k)])\n for val in timeOfActions[k]:\n if dateEveryLine:\n val+=separator+str(k)\n toWrite.append([val])\n\n dn.writeArrayOfArrays(toWrite, fileOutput, separator=\"\\t\")\n\n\ndef readListOfModifCOM(inputFile):\n dynCom = dn.dynamicCommunitiesTN()\n f = open(inputFile)\n endDate = -1\n date = -1\n setComsThisStep = set()\n for l in f:\n l = l.rstrip().split(\"\\t\")\n action = l[0]\n if \"#\" in action:\n setComsThisStep = set()\n date = float(action[1:])\n endDate = date\n\n if action == \"+nc\":\n node = l[1]\n com = l[2]\n #if not com in self.communities:\n # setComsThisStep.add(com)\n dynCom.addBelonging(node,com,date)\n\n if action == \"-nc\":\n node = l[1]\n com = l[2]\n dynCom.removeBelonging(node, com,date)\n\n if action == \"=\":\n conserved = l[1]\n removed = l[2]\n dynCom.addEvent(conserved+removed,conserved,date,date,\"merge\")\n\n # endDate = endDate+infoSN.getStepL()\n #if infoSN != None:\n # endDate += infoSN.getStepL()\n #self.endPeriod(endDate)\n\n return dynCom\n\n\ndef _readStaticSNByCom(inputFile, commentsChar=\"#\", nodeSeparator=\" \", nodeInBrackets=False,\n mainSeparator=\"\\t\", comIDposition=0, nodeListPosition=1):\n \"\"\"\n nodeSeparator: characters that separate the list of nodes\n nodeInBrackets : if true, list of nodes in the community is [x y z] instead of just x y z\n mainSeparator : character used to separate comID from nodesIDS\n \"\"\"\n\n #read community file from a static network\n # if asSN:\n # theDynCom = dn.dynamicCommunitiesSN()\n # if asTN:\n # theDynCom = dn.dynamicCommunitiesTN()\n coms = bidict()\n f = open(inputFile)\n\n for l in f: # for each line\n currentCom = set()\n if not l[0] == commentsChar: # if it is not a comment line\n l = l.rstrip().split(\"\\t\")\n comID = l[comIDposition]\n nodesIDs = l[nodeListPosition]\n if len(nodesIDs)>=1:\n # if nodeInBrackets:\n if \"[\" in nodesIDs:\n nodesIDs = nodesIDs[1:-1]\n if \", \" in nodesIDs:\n nodeSeparator = \", \"\n for n in nodesIDs.split(nodeSeparator):\n currentCom.add(n)\n # if asSN:\n # theDynCom.addBelonging(n,startTime,comID)\n # if asTN:\n # theDynCom.addBelonging(n,comID,startTime) #belongings without end\n coms[frozenset(currentCom)]=comID\n return coms\n\n\ndef readLinkStream(inputFile, toSN=True): # SOCIOPATTERN format\n \"\"\"\n this format is a variation of snapshots, in which all snapshots are in a single file, adapted for occasional observations\n at a high framerate (each SN is meaningless), Line Graph\n \"\"\"\n theDynGraph = dn.DynGraphSN()\n f = open(inputFile)\n\n for l in f:\n l = l.split(\"\\t\")\n date = int(l[0])\n n1 = l[1]\n n2 = l[2]\n #theDynGraph.add_interaction(n1,n2,date,date+intervalsToAdd)\n if toSN:\n theDynGraph.add_interaction(n1,n2,date)\n return theDynGraph\n\n\ndef readSNByCom(inputDir, nameFilter=None, **kwargs):\n \"\"\"\n\n :param inputDir:\n :param nameFilter: a function that takes a file name and decript it into a\n :param kwargs:\n :return:\n \"\"\"\n theDynCom = dn.dynamicCommunitiesSN()\n files = os.listdir(inputDir)\n visibleFiles = [f for f in files if f[0] != \".\"]\n timeIDs = SortedDict() #a dictionary associating timeIds to files\n if nameFilter!=None:\n for f in visibleFiles:\n timeID = nameFilter(f)\n if timeID!=None:\n timeIDs[timeID]=f\n\n #visibleFiles = timeIDs.keys()\n currentComIDs = 0\n\n for t in timeIDs: # for each file in order of their name\n f = inputDir + \"/\" + str(timeIDs[t])\n coms = _readStaticSNByCom(f,**kwargs)\n #print(coms)\n theDynCom.addBelongins_from(coms,t)\n return theDynCom\n\n\ndef readStaticSNByNode(inputFile,separator=\"\\t\"):\n coms = dict()\n f = open(inputFile)\n for l in f:\n\n l = l.rstrip().split(separator)\n for com in l[1:]:\n comID = com\n coms.setdefault(comID,set()).add(l[0])\n #self.addNodeComRelationship(l[0], comID, startTime, stepL)\n toReturn = bidict()\n for com,nodes in coms.items():\n toReturn[frozenset(nodes)]=com\n\n return toReturn\n","sub_path":"dynetx/readwrite/SNreader.py","file_name":"SNreader.py","file_ext":"py","file_size_in_byte":14986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"513911951","text":"import csv\nfrom mainRoot import MainRoot\n\n\ndef readCsv(file):\n l = MainRoot()\n f = csv.reader(open(file))\n i = 0\n a = []\n for d in f:\n a.append(d)\n\n dados = []\n for d in a:\n dados.append(d[0].split(';'))\n\n inicio = dados.pop(0)\n\n for i in range(len(inicio)):\n if ('\"' in inicio[i]):\n inicio[i] = inicio[i][1:-1]\n\n no = []\n for d in dados:\n nPais = d[0]\n if ('\"' in d[1]):\n d[1] = d[1][1:-1]\n code = d[1]\n s = 2\n while s < len(d):\n if (d[s] != ''):\n if ('\"' in d[s]):\n d[s] = d[s][1:-1]\n l.add(nPais, code, inicio[s], d[s])\n s += 1\n return l\n\n\ndef remover(l,pais=None, codPais=None, ano=None, val=None):\n if (not l.checkTreesEmpty()):\n l.remover(pais, codPais, ano, val)\n\n\ndef procurar(l, pais=None, codPais=None, ano=None, val=None):\n #ls = []\n (ls, tName) = l.search(pais, codPais, ano, val)\n\n if ls:\n print(ls.printNode(tName))\n\n\ndef inserir(l, pais, codPais, ano, val):\n l.add(pais, codPais, ano, val)\n\n\ndef editar(l,pais=None, codPais=None, ano=None, val=None, npais=None, ncodPais=None, nano=None, nval=None):\n l.edit(pais, codPais, ano, val, npais, ncodPais, nano, nval)\n\n\ndef main():\n l = readCsv('dados.csv')\n\n while (1):\n print(\"0: Sair\")\n print(\"1: Procurar\")\n print(\"2: Inserir\")\n print(\"3: Editar\")\n print(\"4: Remover\")\n option = eval(input(\"Insira a opcao que deseja: \"))\n if option == 0:\n print(\"Programa terminado.\")\n exit()\n elif option == 1:\n print(\n \"Para os seguintes pedidos preencha corretamente os dados que pretende ter como base da sua pesquisa e deixe em branco os restantes.\")\n pais = str(input(\"Insira o pais: \"))\n if pais == \"\":\n pais = None\n codigo = str(input(\"Insira o codigo: \"))\n if codigo == \"\":\n codigo = None\n ano = str(input(\"Insira o ano: \"))\n if ano == \"\":\n ano = None\n else:\n ano = int(ano)\n valor = str(input(\"Insira o valor: \"))\n if valor == \"\":\n valor = None\n else:\n valor = float(valor)\n procurar(l=l, codPais=codigo, pais=pais, ano=ano, val=valor)\n print(\"\\n(Resultados)\\n\")\n elif option == 2:\n print(\n \"Para os seguintes pedidos preencha corretamente os dados que pretende ter como base da sua pesquisa e deixe em branco os restantes.\")\n pais = str(input(\"Insira o pais: \"))\n if pais == \"\":\n pais = None\n codigo = str(input(\"Insira o codigo: \"))\n if codigo == \"\":\n codigo = None\n ano = str(input(\"Insira o ano: \"))\n if ano == \"\":\n ano = None\n else:\n ano = int(ano)\n valor = str(input(\"Insira o valor: \"))\n if valor == \"\":\n valor = None\n else:\n valor = float(valor)\n inserir(l=l, codPais=codigo, pais=pais, ano=ano, val=valor)\n print(\"\\nInserido.\\n\")\n elif option == 3:\n print(\n \"Para os seguintes pedidos preencha corretamente os dados que pretende ter como base da sua pesquisa e deixe em branco os restantes.\")\n pais = str(input(\"Insira o pais: \"))\n if pais == \"\":\n pais = None\n codigo = str(input(\"Insira o codigo: \"))\n if codigo == \"\":\n codigo = None\n ano = str(input(\"Insira o ano: \"))\n if ano == \"\":\n ano = None\n else:\n ano = int(ano)\n valor = str(input(\"Insira o valor: \"))\n if valor == \"\":\n valor = None\n else:\n valor = float(valor)\n npais = str(input(\"Insira o novo pais: \"))\n if npais == \"\":\n npais = None\n ncodigo = str(input(\"Insira o novo codigo: \"))\n if ncodigo == \"\":\n ncodigo = None\n nano = str(input(\"Insira o novo ano: \"))\n if nano == \"\":\n nano = None\n else:\n nano = int(nano)\n nvalor = str(input(\"Insira o novo valor: \"))\n if nvalor == \"\":\n nvalor = None\n else:\n nvalor = float(nvalor)\n editar(l=l, codPais=codigo, pais=pais, ano=ano, val=valor, ncodPais=ncodigo, npais=npais, nano=nano,\n nval=nvalor)\n print(\"\\nAlterado.\\n\")\n elif option == 4:\n print(\n \"Para os seguintes pedidos preencha corretamente os dados que pretende ter como base da sua pesquisa e deixe em branco os restantes.\")\n pais = str(input(\"Insira o pais: \"))\n if pais == \"\":\n pais = None\n codigo = str(input(\"Insira o codigo: \"))\n if codigo == \"\":\n codigo = None\n ano = str(input(\"Insira o ano: \"))\n if ano == \"\":\n ano = None\n else:\n ano = int(ano)\n valor = str(input(\"Insira o valor: \"))\n if valor == \"\":\n valor = None\n else:\n valor = float(valor)\n remover(l=l, codPais=codigo, pais=pais, ano=ano, val=valor)\n print(\"\\nRemovido.\\n\")\n else:\n print(\"Insira uma opcao correta: \")\n\nmain()\n","sub_path":"Trees/mainTrees.py","file_name":"mainTrees.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"111273185","text":"import tensorflow as tf \nimport numpy as np \n\nclass TextCNN(object):\n def __init__(self, sequence_length, num_classes, vocab_size, \n embedding_size=128, filter_sizes=[3, 4, 5], num_filters=128, l2_reg_lambda=0.0):\n \n #Placeholders\n self.input_x = tf.placeholder(tf.int32, [None, sequence_length])\n self.input_y = tf.placeholder(tf.float32, [None, num_classes])\n self.dropout_keep_prob = tf.placeholder(tf.float32)\n\n # Keeping track of l2 regularization loss (optional)\n l2_loss = tf.constant(0.0)\n\n # Embedding layer\n with tf.device('/cpu:0'), tf.name_scope(\"embedding\"):\n self.W = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0))\n self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)\n self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)\n\n #Create a convolution layer for each filter size\n conv_outputs = []\n for i, filter_size in enumerate(filter_sizes):\n conv_op = self.conv_layer(self.embedded_chars_expanded, sequence_length, filter_size, embedding_size, num_filters)\n conv_outputs.append(conv_op)\n\n # Combine the outputs of all convolution layers \n num_filters_total = num_filters * len(filter_sizes)\n self.conv_op_combined = tf.concat(conv_outputs, 3)\n self.conv_op_flattened = tf.reshape(self.conv_op_combined, [-1, num_filters_total])\n\n # Add dropout\n with tf.name_scope(\"dropout\"):\n self.h_drop = tf.nn.dropout(self.conv_op_flattened, self.dropout_keep_prob)\n\n # Final (unnormalized) scores and predictions\n with tf.name_scope(\"output\"):\n W = tf.get_variable(\"W\",shape=[num_filters_total, num_classes],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name=\"b\")\n l2_loss += tf.nn.l2_loss(W)\n l2_loss += tf.nn.l2_loss(b)\n\n self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name=\"scores\")\n self.predictions = tf.argmax(self.scores, 1, name=\"predictions\")\n\n # CalculateMean cross-entropy loss\n with tf.name_scope(\"loss\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)\n self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\n\n # Accuracy\n with tf.name_scope(\"accuracy\"):\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n\n \n def conv_layer(self, input, sequence_length,filter_size, embedding_size, num_filters):\n with tf.name_scope(\"conv_layer\"):\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n\n w = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W\")\n b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name=\"B\")\n\n conv = tf.nn.conv2d(input, w, strides=[1, 1, 1, 1], padding=\"VALID\", name=\"conv\")\n act = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\n op = tf.nn.max_pool(act, ksize=[1, sequence_length - filter_size + 1, 1, 1], strides=[1, 1, 1, 1],padding='VALID')\n\n return op","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13516681","text":"#!/usr/bin/env/ python3\n# -*- coding: utf-8 -*-\n\nfrom pathlib import Path\nfrom subprocess import call\nfrom time import sleep\nfrom itertools import product\n\nimport click\n\n__date__ = '21/12/2018'\n\n\ndef write_job(index, source):\n job = \"\"\"#!/usr/bin/env bash\n#SBATCH -p cpu\n#SBATCH -o \"{slurm}\"\n\nexport OMP_NUM_THREADS=1\n\nsource activate py3.6\n\nROOT=/home/imoto/crest_auto\nexport PYTHONPATH=/home/imoto/crest_auto/src\n\ncd ${{ROOT}}/src/features\npython light_curve_fitting.py Fit --index={index} --n-split=512 --source={source} --local-scheduler\n\"\"\"\n\n dir_name = 'template'\n name = dir_name\n job_dir = Path('slurm') / dir_name\n if not job_dir.exists():\n job_dir.mkdir(parents=True)\n slurm_dir = Path('slurm') / dir_name\n if not slurm_dir.exists():\n slurm_dir.mkdir(parents=True)\n\n tmp = '{0}-{1:02d}-{2}'.format(name, index, source)\n file_path = job_dir / '{}.sh'.format(tmp)\n slurm_path = slurm_dir / '%j-{0}.out'.format(tmp)\n\n job = job.format(slurm=slurm_path, index=index, source=source)\n with file_path.open(mode='w') as f:\n f.write(job)\n\n return file_path\n\n\ndef run(index, source):\n file_path = write_job(index=index, source=source)\n call(['sbatch', str(file_path)])\n sleep(1)\n\n\ndef check_file(source, index):\n path = (Path('/home/imoto/crest_auto/data/interim/features/test') /\n source / '{0:03d}.pickle'.format(index))\n return path.exists()\n\n\n@click.command()\ndef cmd():\n source_list = [\n 'salt2-extended', 'nugent-sn1bc', 's11-2005hl', 's11-2006fo',\n 'nugent-sn2p', 'nugent-sn2l', 'nugent-sn2n', 's11-2004hx',\n 'snana-2007ms', 'whalen-z15b',\n 'salt2', 'nugent-hyper', 's11-2006jo', 'snana-2004fe',\n 'snana-2007pg', 'snana-2006ix', 'whalen-z40g'\n ]\n # sleep(3600 * 4)\n for index in range(30, 100):\n run(index=index, source=source_list[0])\n\n # for previous, source in zip(source_list[:-1], source_list[1:]):\n # while True:\n # if (check_file(source=previous, index=450) or\n # check_file(source=previous, index=460) or\n # check_file(source=previous, index=470) or\n # check_file(source=previous, index=480)):\n # break\n # sleep(10)\n #\n # for index in range(512):\n # run(index=index, source=source)\n\n\ndef main():\n cmd()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/job/job_fitting.py","file_name":"job_fitting.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"581373407","text":"from signal_handler import Handler\nimport numpy as np\nimport fft_filter\nimport dlib\nimport cv2 as cv\nimport hr_calculator\n\nfreqs_min = 0.8\nfreqs_max = 1.8\n\n\ndef get_hr(ROI, fps):\n signal_handler = Handler(ROI)\n blue, green, red = signal_handler.get_channel_signal()\n matrix = np.array([blue, green, red])\n component = signal_handler.ICA(matrix, 3)\n fft, freqs = fft_filter.fft_filter(component[0], freqs_min, freqs_max, fps)\n heartrate_1 = hr_calculator.find_heart_rate(fft, freqs, freqs_min, freqs_max)\n fft, freqs = fft_filter.fft_filter(component[1], freqs_min, freqs_max, fps)\n heartrate_2 = hr_calculator.find_heart_rate(fft, freqs, freqs_min, freqs_max)\n fft, freqs = fft_filter.fft_filter(component[2], freqs_min, freqs_max, fps)\n heartrate_3 = hr_calculator.find_heart_rate(fft, freqs, freqs_min, freqs_max)\n return (heartrate_1 + heartrate_2 + heartrate_3) / 3\n\n\nif __name__ == '__main__':\n # video_path = 'videos/rohin_face.mov'\n ROI = []\n heartrate = 0\n camera_code = 0\n capture = cv.VideoCapture(camera_code)\n fps = capture.get(cv.CAP_PROP_FPS)\n detector = dlib.get_frontal_face_detector()\n while capture.isOpened():\n ret, frame = capture.read()\n if not ret:\n continue\n dects = detector(frame)\n for face in dects:\n left = face.left()\n right = face.right()\n top = face.top()\n bottom = face.bottom()\n\n h = bottom - top\n w = right - left\n roi = frame[top + h // 10 * 2:top + h // 10 * 7, left + w // 9 * 2:left + w // 9 * 8]\n cv.rectangle(frame, (left + w // 9 * 2, top + h // 10 * 3), (left + w // 9 * 8, top + h // 10 * 7),\n color=(0, 0, 255))\n cv.rectangle(frame, (left, top), (left + w, top + h), color=(0, 0, 255))\n ROI.append(roi)\n if len(ROI) == 300:\n heartrate = get_hr(ROI, fps)\n for i in range(30):\n ROI.pop(0)\n cv.putText(frame, '{:.1f}bps'.format(heartrate), (50, 300), cv.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 2)\n cv.imshow('frame', frame)\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"397884037","text":"'''\nCreated on Jan 28, 2011\n\n@author: yangwookkang\n'''\nfrom movie import Movie\nfrom sqlobject import *\nimport sys\nfrom sqlobject.sqlbuilder import ISNULL, ISNOTNULL, AND, OR, IN, CONTAINSSTRING\nfrom localdb_wrapper import LocalDBWrapper\nimport random\nfrom types import UnicodeType\nimport imdb\n\nclass IMDBWrapper:\n \n \n\n \"\"\"\n (person,Robert Dinero)(type,movieTitle)\n (person,Inception)\n (movieTitle,Inception)(type,plot)\n (type,movieTitle)\n (type,movieTitle)\n (type,movieTitle)\n (person,Inception)(type,director)\n (type,actor)\n (type,movieTitle)\n \n (type,plot)(movieTitle,Ocean 's 11)\n (person,Steven Segal)(type,movieTitle)\n (movieTitle,Ocean 's 11)(type,director)\n (person,Michael Bay)(type,movieTitle)\n (person,Meet The Parents)(type,plot)\n (person,iRobot)\n (movieTitle,Twilight)(type,director)\n \n Person, return type, \n \"\"\"\n def __init__(self):\n ## connect to the database\n #self.db = imdb.IMDb('sql', uri='mysql://maw_imdb_team_2:XJYULPEM@mysql.cse.ucsc.edu/maw_imdb')\n self.db = imdb.IMDb()\n self.genrelist = {'short':'0','adventure':'1','drama':'2','music':'3','sci-fi':'4','action':'5','fantasy':'6','horror':'7','biography':'8','comedy':'9','musical':'10','documentary':'11','animation':'12','crime':'13','mystery':'14','romance':'15','history':'16','war':'17','western':'18','family':'19','sport':'20','News':'21','reality-tv':'22','film-Noir':'23','talk-show':'24','game-show':'25'}\n \n #movies = db.search_movie(\"the lord of the ring\")\n self.conn = self.setConnection('mysql://maw_imdb_team_2:XJYULPEM@mysql.cse.ucsc.edu/maw_imdb').getConnection()\n #self.conn = self.setConnection('mysql://maw_imdb_team_2:XJYULPEM@127.0.0.1:9000/maw_imdb').getConnection()\n #for movie in movies:\n # print movie.summary()\n pass\n \n def escape(self, name):\n name = name.replace(\" '\", \"'\")\n return name.replace(\"'\", \"\\\\'\")\n \n def get_top250(self):\n return self.db.get_top250_movies()\n def get_bottom100(self):\n return self.db.get_bottom100_movies()\n\n def get_plot(self, title):\n plot = \"\"\n title = self.escape(title)\n cursor = self.conn.cursor ()\n cursor.execute (\"select title, info from movie_info i, title t where t.kind_id = 1 and i.movie_id = t.id and i.info_type_id = 195 and t.title like '%{title:s}%' limit 1\".format(title=title))\n rows = cursor.fetchall ()\n for row in rows:\n plot = row[1]\n break;\n\n cursor.close()\n\n return plot\n \n def get_castlist(self, title):\n cast = []\n title = self.escape(title)\n sql = \"select DISTINCT n.name from cast_info c, name n where n.id = c.person_id and c.movie_id = (select id from title where kind_id = 1 and title like '%{title:s}%' limit 1) and role_id in (1,3)\".format(title=title)\n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n for row in rows:\n cast.append(self.tounicode(row[0]))\n cursor.close()\n\n return cast\n \n \n def encodeName(self, name):\n name = name.strip()\n comma = name.find(\",\")\n space = name.find(\" \")\n \n if comma != -1:\n firstname = name[comma+1:].strip()\n lastname = name[:comma].strip()\n elif space != -1:\n firstname = name[:space].strip()\n lastname = name[space+1:].strip()\n else:\n return \"'\" + name + \"'\"\n \n return \"'\" + self.escape(lastname) + \", \" + self.escape(firstname) + \"'\"\n \n \n def find_searchCriteria(self, entities):\n people = []\n year = []\n directors = []\n genres = []\n people_str = \"\"\n year_str = \"\"\n director_str =\"\"\n genre_str = \"\"\n for k, v in entities.get_entityitems():\n if k == \"person\":\n people.append(self.encodeName(v))\n elif k == \"timespan\":\n index = v.find(\"s\")\n if index == -1:\n year.append(v)\n else:\n period = v[:index]\n if len(period) == 2: # 70s or 80s\n period = \"19\" + period\n \n if len(period) == 4: # 1990s or 2000s\n startyear = int(period)\n for i in range(0, 10):\n year.append(str(startyear + i))\n \n elif k == \"director\":\n directors.append(self.encodeName(v))\n \n elif k == \"genre\":\n genres.append(\"'\"+v+\"'\")\n \n if len(people) != 0:\n people_str = \",\".join(people)\n people_str = \"(\" + people_str + \")\"\n if len(year) != 0:\n year_str = \",\".join(year)\n year_str = \"(\" + year_str + \")\"\n \n if len(directors) != 0:\n director_str = \"(\" + \",\".join(directors) + \")\" \n \n if len(genres) != 0:\n genre_str = \"(\" + \",\".join(genres) + \")\"\n \n return people_str, year_str, director_str, genre_str\n \n \n def is_person_in_movie(self, person, title):\n count = 0\n title = self.escape(title)\n name = self.encodeName(person)\n sql = \"select count(*) from cast_info c, name n where n.name = {name:s} and n.id = c.person_id and c.movie_id = (select id from title where kind_id = 1 and title like '%{title:s}%' limit 1)\".format(title=title, name=name)\n \n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n if len(rows) != 0:\n count = rows[0][0]\n \n cursor.close()\n return (count > 0)\n \n \n def get_director(self, title):\n director = \"\"\n title = self.escape(title)\n sql = \"select n.name from cast_info c, name n where n.id = c.person_id and c.movie_id = (select id from title where kind_id = 1 and title like '%{title:s}%' limit 1) and role_id = 15\".format(title=title)\n \n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n if len(rows) != 0:\n director = rows[0][0]\n \n cursor.close()\n return director\n \"\"\"\n create table movie_score (\n movie_id INT,\n rate FLOAT,\n score FLOAT\n );\n\n \"\"\"\n def rate_to_score(self, rating, unit):\n score = (float(rating) -3) * float(unit)\n if rating <= 2:\n return score * -1\n else:\n return score\n \n def update_score(self, movielist, movie_id, score):\n if movielist.has_key(movie_id):\n movielist[movie_id] = movielist[movie_id] + score\n else:\n movielist[movie_id] = score\n\n def tounicode(self, s):\n \"\"\"Nicely print a string to sys.stdout.\"\"\"\n if not isinstance(s, UnicodeType):\n s = unicode(s, 'utf_8')\n s = s.encode(sys.stdout.encoding or 'utf_8', 'replace')\n return s\n \n # rating (1 hate, 2, 3 neutral, 4, 5 like)\n # score ( -2, -1, 0, 1, 2)\n \n # search only movies released in 2000s\n def get_recommendation_2000s(self, entities, userpref):\n if not entities.has_entity(\"timespan\"):\n entities.add_entity(\"timespan\", \"2000s\")\n \n return self.get_recommendation(entities, userpref)\n \n # do random sort\n def get_recommendation_randomlist(self, entities, userpref):\n return self.get_recommendation(entities, userpref, True)\n \n # pick one movie randomly\n def get_recommendation_onerandom(self, entities, userpref):\n movies = self.get_recommendation(entities, userpref, False)\n random_movie = random.randrange(0, len(movies), 1)\n return movies[random_movie]\n\n # pick the movie that has the best score \n def get_recommendation_onebest(self, entities, userpref):\n movies = self.get_recommendation(entities, userpref, False)\n return movies[0] \n \n # default recommendation routine\n def get_recommendation(self, entities, userpref, doshuffle = False):\n movielist = {}\n orderbyscore = \"yes\"\n # no preference\n \n w1 = float(userpref[\"w1\"])\n w2 = float(userpref[\"w2\"])\n w3 = float(userpref[\"w3\"])\n #print w1, w2, w3\n if len(userpref) == 0:\n orderbyscore = \"\"\n else:\n sql = \"update yarb_score set score = 0\"\n cursor = self.conn.cursor ()\n cursor.execute (sql)\n cursor.close() \n score = 0.0\n # 1. userpref\n for key, value in userpref.iteritems():\n if \tkey in (\"w1\", \"w2\", \"w3\", \"output\"):\n continue\n if value.startswith(\"movie\"):\n # 1.1 movie - extract directors, actors actress -> -0.6, -0.3, 0, +0.3, +0.6\n movietitle = self.escape(key)\n score = self.rate_to_score(value[len(value)-1], 0.5)\n #print movietitle\n personids = \"\"\n sql = \"select distinct GROUP_CONCAT(person_id) from cast_info c where c.movie_id = (select id from title where title like '%{title}%' and kind_id = 1 limit 1) and role_id in (1,3) limit 50\".format(title=movietitle)\n \n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n \n for row in rows:\n personids = row[0]\n \n if personids is not None and len(personids) > 0:\n personids = \"(\" + personids + \")\"\n sql = \"select distinct movie_id from cast_info where person_id in \" + personids + \" limit 250\"\n cursor.execute(sql)\n rows = cursor.fetchall ()\n #print sql\n for row in rows:\n movie_id = row[0] \n self.update_score(movielist, movie_id, score)\n \n cursor.close()\n elif value.startswith(\"genre\"):\n # 1.3 genre - directly update the table 0.6\n genre = self.escape(key)\n score = self.rate_to_score(value[len(value)-1], 0.7)\n genre_id = -1\n \n if self.genrelist.has_key(genre):\n genre_id = self.genrelist[genre]\n \n if genre_id != -1: \n sql = \"update yarb_score set score = score + (\" + str(score) + \") where genre_id = \" + genre_id\n cursor = self.conn.cursor ()\n cursor.execute (sql)\n cursor.close()\n \n elif value.startswith(\"director\"):\n # 1.4 director - 0.6\n \n score = self.rate_to_score(value[len(value)-1], 1)\n name = self.encodeName(key)\n sql = \"select distinct movie_id from cast_info c, name n where c.person_id = n.id and n.name = {name:s} and role_id = 15\".format(name = name)\n \n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n for row in rows:\n movie_id = row[0]\n self.update_score(movielist, movie_id, score)\n cursor.close()\n \n elif value.startswith(\"person\"):\n # 1.2 person - 0.6\n score = self.rate_to_score(value[len(value)-1], 1)\n name = self.encodeName(key)\n sql = \"select distinct movie_id from cast_info c, name n where c.person_id = n.id and n.name = {name:s}\".format(name = name)\n #print sql\n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n for row in rows:\n movie_id = row[0]\n self.update_score(movielist, movie_id, score)\n cursor.close()\n \n # 2. update movie_score table = rating + extra score \n cursor = self.conn.cursor ()\n score = score * w3\n \n if score != 0.0:\n for movie_id, score in movielist.iteritems():\n sql = \"update yarb_score set score = score + ({score}) where movie_id = {movie_id}\".format(score = score, movie_id=movie_id)\n cursor.execute (sql)\n \n cursor.close()\n # 3. select movie names, results\n return self.get_movielist(entities, orderbyscore, doshuffle, w1, w2)\n \n def get_movielist(self, entities, orderbyscore = \"\", doshuffle = False, w1 = 0.3, w2 = 1.0):\n person_id_str = \"\"\n movie_id_str = \"\"\n director_id_str = \"\"\n genre_str = \"\"\n people, year_str, director, genre = self.find_searchCriteria(entities)\n movies = []\n movie_ids = []\n ## Subquery performance of the MySQL database server we're using is horrible, \n ## so we split it into several queries\n if len(people) != 0:\n \n sql = \"select distinct GROUP_CONCAT(id) from name where name in \" + people\n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n if len(rows) == 0 or rows[0][0] is None:\n cursor.close()\n return []\n \n person_id_str = \"(\" + rows[0][0] + \")\"\n \n sql2 = \"select distinct movie_id from cast_info where person_id in \" + person_id_str + \" and role_id in (1,3, 7, 15)\";\n \n cursor.execute (sql2)\n rows = cursor.fetchall ()\n \n for row in rows:\n movie_ids.append(str(row[0]))\n \n #movie_id_str = \"movie_id in (\" + \",\".join(movie_ids) + \")\"\n \n cursor.close()\n\n \n \n if len(director) != 0:\n \n sql = \"select distinct GROUP_CONCAT(id) from name where name in \" + director\n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n if len(rows) == 0 or rows[0][0] is None:\n cursor.close()\n return []\n\n director_id_str = \"(\" + rows[0][0] + \")\"\n \n sql2 = \"select distinct movie_id from cast_info where person_id in \" + director_id_str + \" and role_id = 15\";\n \n cursor.execute (sql2)\n rows = cursor.fetchall ()\n for row in rows:\n movie_ids.append(str(row[0]))\n \n #movie_id_str = \"movie_id in (\" + \",\".join(movie_ids) + \")\"\n \n cursor.close()\n\n if len(genre) != 0:\n sql = \"select distinct movie_id from movie_info where info_type_id = 5 and info in {genre:s}\".format(genre=genre)\n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n for row in rows:\n movie_ids.append(str(row[0]))\n\n cursor.close()\n\n movie_id_str = \"s.movie_id in (\" + \",\".join(movie_ids) + \")\"\n \n sql = \"select title, production_year, (s.rating * \" + str(w1) + \") + (s.score *\"+ str(w2) +\") + s.norm_popularity as totalscore from title t, (select distinct movie_id, rating, score, norm_popularity from yarb_score) s where t.kind_id = 1 and s.movie_id = t.id \"\n \n if len(movie_ids) != 0:\n sql += \" and \" + movie_id_str\n \n if year_str != \"\":\n sql += \" and production_year in \" + year_str\n \n if not doshuffle:\n if orderbyscore == \"\":\n sql += \" order by production_year desc limit 200\"\n else:\n sql += \" order by totalscore desc, production_year desc limit 200\"\n else:\n sql += \" order by totalscore desc, production_year desc limit 200\"\n \n #print sql\n cursor = self.conn.cursor ()\n cursor.execute (sql)\n rows = cursor.fetchall ()\n \n for row in rows:\n movies.append(Movie(self.tounicode(row[0]), row[1], row[2]))\n\n if doshuffle:\n random.shuffle(movies)\n\n cursor.close()\n return movies\n \n \n def setConnection(self, uri, encoding='utf8', debug=False):\n kw = {}\n _uriLower = uri.lower()\n if _uriLower.startswith('mysql'):\n kw['use_unicode'] = 1\n #kw['sqlobject_encoding'] = encoding\n kw['charset'] = encoding\n conn = connectionForURI(uri, **kw)\n conn.debug = debug\n conn.paramstyle = conn.module.paramstyle\n return conn\n \n","sub_path":"dm/imdb_wrapper.py","file_name":"imdb_wrapper.py","file_ext":"py","file_size_in_byte":17343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"81125664","text":"#!/usr/bin/env python\n\n'''\n\n'''\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the dynamicArray function below.\ndef dynamicArray(n, queries):\n s = [[] for x in range(n)] \n lastAnswer = 0\n res = []\n for i in range(len(queries)):\n query = queries[i][0]\n x = queries[i][1]\n y = queries[i][2]\n if query == 1:\n # do this\n s[((x ^ lastAnswer) % n)].append(y)\n elif query == 2:\n # do this\n size = len(s[((x ^ lastAnswer) % n)])\n lastAnswer = s[((x ^ lastAnswer) % n)][y % size]\n print (lastAnswer)\n res.append(lastAnswer)\n\n return res\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nq = input().rstrip().split()\n\n n = int(nq[0])\n\n q = int(nq[1])\n\n queries = []\n\n for _ in range(q):\n queries.append(list(map(int, input().rstrip().split())))\n\n result = dynamicArray(n, queries)\n\n fptr.write('\\n'.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","sub_path":"problem_solving/dynamic_array.py","file_name":"dynamic_array.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"605412947","text":"from django.shortcuts import render_to_response, get_object_or_404, redirect\nfrom django.http import HttpResponse\nfrom localground.lib.api.decorators import process_identity, process_project\nfrom localground.lib.decorators import get_group_if_authorized\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom django.template import RequestContext \nimport simplejson as json\nfrom django.core.context_processors import csrf\nfrom localground.uploads.models import Scan\nfrom localground.prints.models import Print\nfrom localground.account.models import Project, View\nfrom django.core.exceptions import ObjectDoesNotExist\n\n@login_required()\n@process_identity\ndef init(request, identity=None):\n u = request.user\n context = RequestContext(request)\n username = identity.username if identity is not None else 'all'\n #set defaults:\n lat, lng, zoom, prints, groups = 21.698265, 14.765625, 3, [], []\n if u.is_authenticated():\n projects = Project.objects.get_objects(identity)\n if request.user.is_superuser and username == 'all':\n projects = Project.objects.all().order_by('name')\n projects = [p.to_dict() for p in projects]\n groups = [] #[g.to_dict() for g in MapGroup.objects.my_groups(u)]\n \n if u.get_profile().default_location is not None:\n lat = u.get_profile().default_location.y\n lng = u.get_profile().default_location.x\n zoom = 14\n context.update({\n 'lat': lat,\n 'lng': lng,\n 'zoom': zoom,\n 'projects': json.dumps(projects),\n 'num_projects': len(projects),\n 'groups': json.dumps(groups)\n })\n return render_to_response('twitter/viewer.html', context)\n \n \n'''TYPE_LU = {\n 'projects': Project,\n 'views': View\n}'''\n\n@get_group_if_authorized\ndef public_map(request, object_type, slug, group_object, access_key=None):\n u = request.user\n #ModelClass = TYPE_LU.get(object_type)\n #group_object = get_object_or_404(ModelClass, slug=slug)\n context = RequestContext(request)\n #set defaults:\n lat, lng, zoom, prints, groups = 21.698265, 14.765625, 3, [], []\n if u.is_authenticated() and u.get_profile().default_location is not None:\n lat = u.get_profile().default_location.y\n lng = u.get_profile().default_location.x\n zoom = 14\n context.update({\n 'lat': lat,\n 'lng': lng,\n 'zoom': zoom,\n 'group_object': group_object,\n 'basemap_id': group_object.basemap.id,\n 'num_projects': 1,\n 'read_only': True\n })\n if access_key is not None:\n context.update({\n 'access_key': access_key\n })\n context['%s_id' % group_object.model_name] = group_object.id \n return render_to_response('twitter/viewer_public.html', context)","sub_path":"viewer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"468715398","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse\nfrom django.template import loader\n\nimport json\nimport logging\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom website.models import UI_test_report_for_summary\nfrom website.models import API_test_report_for_summary\n\nlogger = logging.getLogger('mylogger')\n\n\n# 测试报告-UI测试报告\ndef ui_test_report(request):\n template = loader.get_template('website/pages/UITestReport.html')\n return HttpResponse(template.render({}, request))\n\ndef api_test_report(request):\n template = loader.get_template('website/pages/APITestReport.html')\n return HttpResponse(template.render({}, request))\n\n# # 列表数据\ndef get_test_report_for_summary(request):\n grid_data = {\"total\": 0, \"rows\": []}\n rows = [] # 用于存储记录行\n\n report_type = request.GET.get('reportType')\n if report_type == 'APITestReport':\n db_class = API_test_report_for_summary\n elif report_type == 'UITestReport':\n db_class = UI_test_report_for_summary\n\n # 获取总记录数\n records = db_class.objects.order_by('-id').values()\n grid_data[\"total\"] = len(records)\n\n page_num = request.GET.get('page') # 记录请求的是第几页数据\n rows_num = request.GET.get('rows') # 记录请求每页的记录数\n\n paginator = Paginator(records, rows_num) # 设置每页展示的数据\n\n try:\n page = paginator.page(page_num)\n except PageNotAnInteger as e: # 如果请求的页面编号不存在,返回第一页数据\n logger.warn('%s' % e)\n page = paginator.page(1)\n except EmptyPage as e: # 如果请求页面,超出页面范围,返回最后一页数据\n logger.warn('%s' % e)\n page = paginator.page(paginator.num_pages)\n\n records = page.object_list\n for record in records:\n rows.append(record)\n grid_data[\"rows\"] = rows\n grid_data = json.dumps(grid_data)\n return HttpResponse(grid_data)\n\n\n","sub_path":"AutotestPlatform/website/test_report_views.py","file_name":"test_report_views.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"380295678","text":"class FirstClass: # Определяет объект класса\n def setdata(self, value): # Определяет метод класса\n self.data = value # self - это экземпляр класса\n def display(self):\n print(self.data) # self.data: данные экземпляров\n\nx = FirstClass() # Создаются два экземпляра\ny = FirstClass() # Каждый является отдельным пространством имен\n\nx.setdata(\"King Artur\") # Вызов метода: self - это x\ny.setdata(3.1415) # Эквивалентно: FirstClass.setdata(y, 3.1415)\n\nx.display() # В каждом экземпляре свое значение self.data\ny.display()\n\nx.data = \"New value\" # Можно получать/записывать значения атрибутов за пределами класса\nx.display()\n\n\nclass SecondClass(FirstClass): # Наследует setdata\n def display(self): # Переопределяет display\n print(\"Current value =\", self.data)\n\nz = SecondClass()\nz.setdata(42) # Найдет метод setdata в FirstClass\nz.display() # Найдет переопределенный метод в SecondClass\n\n\nclass ThirdClass(SecondClass): # Наследует SecondClass\n def __init__(self, value): # Вызывается при создании экземпляра выражением ThirdClass(value)\n self.data = value\n def __add__(self, other): # Для выражения self + other\n return ThirdClass(self.data + other)\n def __str__(self): # Вызывается из print(self), str()\n return \"[ThirdClass: {0}]\".format(self.data)\n def mul(self, other): # Обычный метод класса\n self.data *= other\n\na = ThirdClass(\"abc\") # Вызовет __init__\na.display() # Унаследованый метод\nprint(a) # __str__: возвращает строку\nb = a + 'xyz' # Новый метод __add__: создается новый экземпляр класса\nprint(b) # __str__: возвращает строку\na.mul(3) # mul: изменяется сам экземпляр\nprint(a)","sub_path":"edu/5. classes/basics of class prog.py","file_name":"basics of class prog.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"598897563","text":"from __future__ import print_function, absolute_import\nimport s.colors\nimport s.func\nimport s.shell\nimport types\nimport argh\nimport s.bin.tests.lib\n\n\ndef _missing_funcs(test_file):\n test_module = s.shell.module_name(test_file)\n code_module = s.shell.module_name(s.bin.tests.lib.code_file(test_file))\n return [fn for fn in _list_functions(code_module)\n if not any(test_fn.endswith('_' + fn)\n for test_fn in _list_functions(test_module))]\n\n\ndef _print_code_module_name(test_file):\n return s.func.pipe(\n test_file,\n s.bin.tests.lib.code_file,\n s.shell.module_name,\n s.colors.yellow,\n print,\n )\n\n\ndef _print_cov_data(test_file):\n cov_data = s.bin.tests.lib._cover(test_file)\n print(getattr(s.colors, 'green' if cov_data['percent'] == '100' else 'red')(cov_data['percent'] + '% '))\n if cov_data['missing']:\n missing_text = ' missing lines: '\n missing_count = 5\n missing_text += (', '.join(cov_data['missing'][:missing_count]) +\n ('...' if len(cov_data['missing']) > missing_count else ''))\n print(missing_text)\n\n\ndef _print_missing_tests(test_file):\n missing_funcs = _missing_funcs(test_file)\n if missing_funcs:\n print(' missing tests:')\n for name in missing_funcs:\n print(' test_*_{name}'.format(**locals()))\n\n\ndef _print_missing_test_files():\n missing_test_files = []\n for code_file in s.bin.tests.lib.code_files():\n try:\n s.bin.tests.lib.test_file(code_file)\n except AssertionError:\n missing_test_files.append(s.bin.tests.lib._test_file(s.shell.rel_path(code_file)))\n if missing_test_files:\n print(s.colors.yellow('missing test files:'))\n for test_file in missing_test_files:\n print('', test_file)\n\n\ndef _list_functions(module_name):\n return [k\n for k, v in __import__(module_name, fromlist='*').__dict__.items()\n if isinstance(v, types.FunctionType)\n and v.__module__ == module_name]\n\n\n@argh.arg('grep_module', nargs='?', default=None)\ndef cover(grep_module, missing_tests=False):\n for test_file in s.bin.tests.lib.fast_test_files():\n try:\n s.bin.tests.lib.code_file(test_file)\n except AssertionError:\n continue\n\n module = s.shell.module_name(s.bin.tests.lib.code_file(test_file))\n if grep_module and grep_module not in module:\n continue\n\n _print_code_module_name(test_file)\n _print_cov_data(test_file)\n if missing_tests:\n _print_missing_tests(test_file)\n\n if not grep_module:\n _print_missing_test_files()\n","sub_path":"tools/tests/cover.py","file_name":"cover.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"208697740","text":"from django.urls import path, re_path\nfrom .import views\n\napp_name = 'tutorials'\nurlpatterns = [\n path('process//', views.pay_for_course, name='process'),\n path('done/', views.payment_done, name='payment_done'),\n path('canceled/', views.payment_canceled, name='payment_canceled'),\n re_path('^tutorial/(?P[-\\w]+)/$',views.VideoDetailView.as_view(), name='video-detail'),\n path('',views.VideoListView.as_view(), name='video-list'),\n]","sub_path":"tutorials/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"149242344","text":"from abc import ABC, abstractmethod\r\nimport json\r\nimport base64\r\nimport logging\r\nimport requests\r\nfrom netaddr import IPAddress\r\n\r\nlogging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', level=logging.INFO)\r\nlogger = logging.getLogger()\r\n\r\n\r\nclass Common(ABC):\r\n\r\n def __init__(self, ip=None, domain=None, url=None):\r\n if ip is not None:\r\n self.ip = ip\r\n elif domain is not None:\r\n self.domain = domain\r\n elif url is not None:\r\n self.url = url\r\n\r\n def read_config(self, section, key):\r\n \"\"\"\r\n\r\n :param section: For the TI feed selection\r\n :param key: For api key or urls\r\n :return: respective output\r\n \"\"\"\r\n with open('configuration.json', 'r') as config_file:\r\n data = json.load(config_file)\r\n return data.get(section)[key]\r\n\r\n def validate_ip(self, ip):\r\n \"\"\"\r\n\r\n :param ip: For validating the IP is private or public\r\n :return: return the respective output\r\n \"\"\"\r\n try:\r\n ipinfo = IPAddress(ip)\r\n if ipinfo.version in [4, 6]:\r\n if ipinfo.is_private():\r\n return False\r\n else:\r\n return True\r\n else:\r\n return False\r\n except Exception:\r\n return False\r\n\r\n def base_64(self):\r\n \"\"\"\r\n\r\n :return: It encode and decode the input and then return the value\r\n \"\"\"\r\n apikey = f'{self.read_config(section=\"IBMXFORCE\", key=\"apikey\")}'\r\n password = self.read_config(section=\"IBMXFORCE\", key=\"password\")\r\n string = f'{apikey}:{password}'\r\n string_bytes = string.encode(\"ascii\")\r\n base64_bytes = base64.b64encode(string_bytes)\r\n base64_string = base64_bytes.decode(\"ascii\")\r\n Auth_key = f'Basic {base64_string}'\r\n return Auth_key\r\n\r\n @abstractmethod\r\n def ip_check(self):\r\n pass\r\n\r\n @abstractmethod\r\n def domain_check(self):\r\n pass\r\n\r\n @abstractmethod\r\n def url_check(self):\r\n pass\r\n\r\n\r\nclass Virustotal(Common):\r\n\r\n def ip_check(self):\r\n \"\"\"\r\n\r\n :return: To check the reputation of IP and get required details\r\n \"\"\"\r\n if self.validate_ip(self.ip):\r\n url = f\"{self.read_config(section='virustotal', key='base_url')}{self.read_config(section='virustotal', key='ip_endpoint').replace('{ip}', self.ip)}\" # pylint: disable=line-too-long\r\n params = {'x-apikey': self.read_config(section='virustotal', key='apikey')}\r\n response = requests.get(url, headers=params)\r\n if response.status_code == 200:\r\n output = response.json()\r\n if output != 0:\r\n logger.info(f'regional_internet_registry={output[\"data\"][\"attributes\"][\"regional_internet_registry\"]}') # pylint: disable=line-too-long\r\n logger.info(f'as_owner={output[\"data\"][\"attributes\"][\"as_owner\"]}')\r\n logger.info(f'network={output[\"data\"][\"attributes\"][\"network\"]}')\r\n logger.info(f'country={output[\"data\"][\"attributes\"][\"country\"]}')\r\n stat_keys = output['data']['attributes']['last_analysis_results']\r\n list_stat_keys = list(stat_keys.keys())\r\n for i in list_stat_keys:\r\n category = output['data']['attributes']['last_analysis_results'][f'{i}']['category']\r\n harmless = \"harmless\"\r\n if category == harmless:\r\n continue\r\n else:\r\n logger.info(\"===========================================\")\r\n logger.info(f\"category is {output['data']['attributes']['last_analysis_results'][f'{i}']['category']}\") # pylint: disable=line-too-long\r\n logger.info(f\"result is {output['data']['attributes']['last_analysis_results'][f'{i}']['result']}\") # pylint: disable=line-too-long\r\n logger.info(f\"method is {output['data']['attributes']['last_analysis_results'][f'{i}']['method']}\") # pylint: disable=line-too-long\r\n logger.info(f\"engine name is {output['data']['attributes']['last_analysis_results'][f'{i}']['engine_name']}\") # pylint: disable=line-too-long\r\n logger.info(\"===========================================\")\r\n else:\r\n logger.info('nothing to display')\r\n else:\r\n logger.error(f'error status code={response.status_code} | reason={response.reason}')\r\n else:\r\n logger.warning(f'Provided IP {self.ip} is Invalid for Reputation check..!')\r\n\r\n\r\n def domain_check(self):\r\n \"\"\"\r\n\r\n :return: To chech the reputation of domain and retrieve the details\r\n \"\"\"\r\n url = f\"{self.read_config(section='virustotal', key='base_url')}{self.read_config(section='virustotal', key='domain_endpoint').replace('{domain}', self.domain)}\" # pylint: disable=line-too-long\r\n params = {'x-apikey': self.read_config(section='virustotal', key='apikey')}\r\n response = requests.get(url, headers=params)\r\n if response.status_code == 200:\r\n output = response.json()\r\n if output != 0:\r\n logger.info(f'whois_details={output[\"data\"][\"attributes\"][\"whois\"]}')\r\n list_stat_keys = list(output['data']['attributes']['last_analysis_results'].keys())\r\n for i in list_stat_keys:\r\n category = output['data']['attributes']['last_analysis_results'][f'{i}']['category']\r\n harmless = \"harmless\"\r\n if category == harmless:\r\n continue\r\n else:\r\n logger.info(f\"engine name is {output['data']['attributes']['last_analysis_results'][f'{i}']['engine_name']}\") # pylint: disable=line-too-long\r\n logger.info(f\"category is {output['data']['attributes']['last_analysis_results'][f'{i}']['category']}\") # pylint: disable=line-too-long\r\n logger.info(f\"result is {output['data']['attributes']['last_analysis_results'][f'{i}']['result']}\") # pylint: disable=line-too-long\r\n logger.info(f\"method is {output['data']['attributes']['last_analysis_results'][f'{i}']['method']}\") # pylint: disable=line-too-long\r\n else:\r\n logger.info('nothing to display')\r\n else:\r\n logger.error(f'error status code={response.status_code} | reason={response.reason}')\r\n\r\n\r\n def url_check(self):\r\n \"\"\"\r\n\r\n :return: To chech the reputation of URL and retrieve the details\r\n \"\"\"\r\n url_post = self.read_config(section='virustotal', key='url_post')\r\n payload = {'url': self.url}\r\n files = []\r\n headers = {'x-apikey': self.read_config(section='virustotal', key='apikey')}\r\n response_post = requests.post(url_post, headers=headers, data=payload, files=files)\r\n output1 = response_post.json()\r\n ids = output1['data']['id'].split(\"-\")\r\n url = f\"{self.read_config(section='virustotal', key='base_url')}{self.read_config(section='virustotal', key='url_endpoint')}/{ids[1]}\" # pylint: disable=line-too-long\r\n payload_get = {}\r\n response = requests.get(url, headers=headers, data=payload_get)\r\n if response.status_code == 200:\r\n output = response.json()\r\n if output != 0:\r\n logger.info(f'SHA256 = {output[\"data\"][\"attributes\"][\"last_http_response_content_sha256\"]}')\r\n logger.info(f'vary = {output[\"data\"][\"attributes\"][\"last_http_response_headers\"][\"vary\"]}')\r\n logger.info(f'Keep alive = {output[\"data\"][\"attributes\"][\"last_http_response_headers\"][\"keep-alive\"]}')\r\n logger.info(f'server = {output[\"data\"][\"attributes\"][\"last_http_response_headers\"][\"server\"]}')\r\n logger.info(f'content-type = {output[\"data\"][\"attributes\"][\"last_http_response_headers\"][\"content-type\"]}')\r\n logger.info(f'reputation = {output[\"data\"][\"attributes\"][\"reputation\"]}')\r\n threat_names = output[\"data\"][\"attributes\"][\"threat_names\"]\r\n if len(threat_names) == 0:\r\n logger.info(f'No threats detected')\r\n else:\r\n logger.info(f'threat_names = {output[\"data\"][\"attributes\"][\"threat_names\"]}')\r\n list_stat_keys = list(output['data']['attributes']['last_analysis_results'].keys())\r\n for i in list_stat_keys:\r\n category = output['data']['attributes']['last_analysis_results'][f'{i}']['category']\r\n harmless = \"harmless\"\r\n if category == harmless:\r\n continue\r\n else:\r\n logger.info(f\"=========================== engine details =============================\")\r\n logger.info(f\"engine name is {output['data']['attributes']['last_analysis_results'][f'{i}']['engine_name']}\") # pylint: disable=line-too-long\r\n logger.info(f\"category is {output['data']['attributes']['last_analysis_results'][f'{i}']['category']}\") # pylint: disable=line-too-long\r\n logger.info(f\"result is {output['data']['attributes']['last_analysis_results'][f'{i}']['result']}\") # pylint: disable=line-too-long\r\n logger.info(f\"method is {output['data']['attributes']['last_analysis_results'][f'{i}']['method']}\") # pylint: disable=line-too-long\r\n else:\r\n logger.info('nothing to display')\r\n else:\r\n logger.error(f'error status code={response.status_code} | reason={response.reason}')\r\n\r\n\r\nclass APIVoid(Common):\r\n\r\n def ip_check(self):\r\n \"\"\"\r\n\r\n :return: To chech the reputation of IP and retrieve the details\r\n \"\"\"\r\n if self.validate_ip(self.ip):\r\n url = f\"{self.read_config(section='apivoid', key='base_url')}{self.read_config(section='apivoid', key='ip_endpoint')}?key={self.read_config(section='apivoid', key='apikey')}&ip={self.ip}\" # pylint: disable=line-too-long\r\n response = requests.get(url)\r\n if response.status_code == 200:\r\n output = response.json()\r\n if len(output) != 0:\r\n value = output[\"data\"][\"report\"]\r\n logger.info(f'ip = {value[\"ip\"]}')\r\n logger.info(f'isp = {value[\"information\"][\"isp\"]}')\r\n logger.info(f'country_name = {value[\"information\"][\"country_name\"]}')\r\n logger.info(f'city_name = {value[\"information\"][\"city_name\"]}')\r\n logger.info(f'risk score is {value[\"risk_score\"][\"result\"]}')\r\n logger.info(f'is_proxy = {value[\"anonymity\"][\"is_proxy\"]}')\r\n logger.info(f'is_webproxy = {value[\"anonymity\"][\"is_webproxy\"]}')\r\n logger.info(f'is_vpn = {value[\"anonymity\"][\"is_vpn\"]}')\r\n logger.info(f'is_hosting = {value[\"anonymity\"][\"is_hosting\"]}')\r\n logger.info(f'is_tor = {value[\"anonymity\"][\"is_tor\"]}')\r\n engines = list(output[\"data\"][\"report\"][\"blacklists\"][\"engines\"])\r\n for i in range(len(engines)):\r\n detected = output[\"data\"][\"report\"][\"blacklists\"][\"engines\"][f'{i}'][\"detected\"]\r\n if detected is False:\r\n continue\r\n else:\r\n logger.info(f'reference link is {output[\"data\"][\"report\"][\"blacklists\"][\"engines\"][f\"{i}\"][\"reference\"]}') # pylint: disable=line-too-long\r\n else:\r\n logger.info('no data found')\r\n else:\r\n logger.info(f'error = {response.status_code}| reason = {response.reason}')\r\n else:\r\n logger.info(f'Provided IP {self.ip} is Invalid for Reputataion Check...!')\r\n\r\n def domain_check(self):\r\n \"\"\"\r\n\r\n :return: To chech the reputation of domain and retrieve the details\r\n \"\"\"\r\n url = f\"{self.read_config(section='apivoid', key='base_url')}{self.read_config(section='apivoid', key='domain_endpoint')}?key={self.read_config(section='apivoid', key='apikey')}&host={self.ip}\" # pylint: disable=line-too-long\r\n response = requests.get(url)\r\n if response.status_code == 200:\r\n output = response.json()\r\n if len(output) != 0:\r\n value = output[\"data\"][\"report\"]\r\n logger.info(f'ip = {value[\"server\"][\"ip\"]}')\r\n logger.info(f'isp = {value[\"server\"][\"isp\"]}')\r\n logger.info(f'country_name = {value[\"server\"][\"country_name\"]}')\r\n logger.info(f'city_name = {value[\"server\"][\"city_name\"]}')\r\n logger.info(f'risk score is {value[\"risk_score\"][\"result\"]}')\r\n logger.info(f'reverse DNS is {value[\"server\"][\"reverse_dns\"]}')\r\n logger.info(f'url shortner is {value[\"category\"][\"is_url_shortener\"]}')\r\n engines = list(output[\"data\"][\"report\"][\"blacklists\"][\"engines\"])\r\n for i in range(len(engines)):\r\n detected = output[\"data\"][\"report\"][\"blacklists\"][\"engines\"][f'{i}'][\"detected\"]\r\n if detected is False:\r\n continue\r\n else:\r\n logger.info(f'reference link is {output[\"data\"][\"report\"][\"blacklists\"][\"engines\"][f\"{i}\"][\"reference\"]}') # pylint: disable=line-too-long\r\n logger.info(f'confidence is {output[\"data\"][\"report\"][\"blacklists\"][\"engines\"][f\"{i}\"][\"confidence\"]}') # pylint: disable=line-too-long\r\n\r\n else:\r\n logger.info('no data found')\r\n else:\r\n logger.info(f'error = {response.status_code}| reason = {response.reason}')\r\n\r\n def url_check(self):\r\n \"\"\"\r\n\r\n :return: To chech the reputation of url and retrieve the details\r\n \"\"\"\r\n url = f\"{self.read_config(section='apivoid', key='base_url')}{self.read_config(section='apivoid', key='url_endpoint')}?key={self.read_config(section='apivoid', key='apikey')}&url={self.ip}\" # pylint: disable=line-too-long\r\n response = requests.get(url)\r\n if response.status_code == 200:\r\n output = response.json()\r\n if len(output) != 0:\r\n value = output[\"data\"][\"report\"]\r\n logger.info(f'signature = {value[\"file_type\"][\"signature\"]}')\r\n logger.info(f'extention = {value[\"file_type\"][\"extension\"]}')\r\n logger.info(f'headers = {value[\"file_type\"][\"headers\"]}')\r\n logger.info(f'status = {value[\"response_headers\"][\"status\"]}')\r\n logger.info(f'result is {value[\"risk_score\"][\"result\"]}')\r\n logger.info(f'cache status is {value[\"response_headers\"][\"cf-cache-status\"]}')\r\n logger.info(f'x-frame is {value[\"response_headers\"][\"x-frame-options\"]}')\r\n engines = list(output[\"data\"][\"report\"][\"domain_blacklist\"][\"engines\"])\r\n for i in range(len(engines)):\r\n detected = output[\"data\"][\"report\"][\"domain_blacklist\"][\"engines\"][i][\"detected\"]\r\n if detected is False:\r\n continue\r\n else:\r\n logger.info(f'reference link is {output[\"data\"][\"report\"][\"domain_blacklist\"][\"engines\"][i][\"reference\"]}') # pylint: disable=line-too-long\r\n logger.info(f'====================== ns Records ========================')\r\n NS_Records = value[\"dns_records\"][\"ns\"][\"records\"]\r\n for i in range(len(NS_Records)):\r\n logger.info(f'target is {NS_Records[i][\"target\"]}')\r\n logger.info(f'ip is {NS_Records[i][\"ip\"]}')\r\n logger.info(f'country is {NS_Records[i][\"country_name\"]}')\r\n logger.info(f'isp is {NS_Records[i][\"isp\"]}')\r\n logger.info(f'====================== mx Records ========================')\r\n MX_Records = value[\"dns_records\"][\"mx\"][\"records\"]\r\n for i in range(len(MX_Records)):\r\n logger.info(f'target is {MX_Records[i][\"target\"]}')\r\n logger.info(f'ip is {MX_Records[i][\"ip\"]}')\r\n logger.info(f'country is {MX_Records[i][\"country_name\"]}')\r\n logger.info(f'isp is {MX_Records[i][\"isp\"]}')\r\n else:\r\n logger.info('no data found')\r\n else:\r\n logger.info(f'error = {response.status_code}| reason = {response.reason}')\r\n\r\n\r\nclass IBMXFORCE(Common):\r\n\r\n def ip_check(self):\r\n \"\"\"\r\n\r\n :return: To chech the reputation of IP and retrieve the details\r\n \"\"\"\r\n if self.validate_ip(self.ip):\r\n url = f\"{self.read_config(section='IBMXFORCE', key='base_url')}{self.read_config(section='IBMXFORCE', key='ip_endpoint').replace('{ip}', self.ip)}\" # pylint: disable=line-too-long\r\n Headers = {'Authorization': f'{self.base_64()}'}\r\n response = requests.get(url, headers=Headers)\r\n if response.status_code == 200:\r\n output = response.json()\r\n if output != 0:\r\n IP = output['ip']\r\n history = output['history']\r\n country = history[0]['geo']['country']\r\n logger.info(f'IP is {IP}')\r\n logger.info(f'Geo location is {country}')\r\n for i in range(len(history)):\r\n logger.info(history[i]['reasonDescription'])\r\n try:\r\n logger.info(history[i]['categoryDescriptions']['Anonymisation Services'])\r\n except:\r\n logger.info('Anonymisation Services are not available')\r\n try:\r\n logger.info(f\"malware description is {history[i]['categoryDescriptions']['Malware']}\")\r\n except:\r\n logger.info('Malware info is not available')\r\n logger.info(f'score is {history[i][\"score\"]}')\r\n logger.info(\"\\n\")\r\n else:\r\n logger.info(\"No details are available for the provided input\")\r\n else:\r\n logger.error(f'error status code={response.status_code} | reason={response.reason}')\r\n else:\r\n logger.warning(f'Provided IP {self.ip} is Invalid for Reputation check..!')\r\n\r\n def domain_check(self):\r\n \"\"\"\r\n\r\n :return: To chech the reputation of domain/url and retrieve the details\r\n \"\"\"\r\n url = f\"{self.read_config(section='IBMXFORCE', key='base_url')}{self.read_config(section='IBMXFORCE', key='url_endpoint').replace('{domain}', self.ip)}\" # pylint: disable=line-too-long\r\n Headers = {'Authorization': f'{self.base_64()}'}\r\n response = requests.get(url, headers=Headers)\r\n if response.status_code == 200:\r\n output = response.json()\r\n url = output['url']\r\n score = output['score']\r\n created = output['created']\r\n cats = output['cats']\r\n cats_keys = list(cats.keys())\r\n print(f'url is {url}', f'time is {created}', f'score is {score}', sep=\"\\n\")\r\n confidence = output['cats'][f'{cats_keys[0]}']['confidence']\r\n description = output['cats'][f'{cats_keys[0]}']['description']\r\n ids = output['cats'][f'{cats_keys[0]}']['reasons'][0]['id']\r\n name = output['cats'][f'{cats_keys[0]}']['reasons'][0]['name']\r\n print(f'confidence is {confidence}', f'description is {description}', f'id is {ids}', f'reason is {name}',\r\n sep=\"\\n\")\r\n else:\r\n print(f'Error : {response.status_code} | Reason : {response.reason}')\r\n\r\n def url_check(self):\r\n self.domain_check()\r\n\r\n\r\nclass Engine:\r\n\r\n def main(self):\r\n \"\"\"\r\n\r\n :return: To select the respective operation as per the user\r\n \"\"\"\r\n print('Welcome to Threat Intel...!')\r\n print('1. Virustotal', '2. API Void', '3. IBMXFORCE', sep='\\n')\r\n choice = input('Enter choice : ')\r\n if choice == '1':\r\n print('1. IP Check', '2. Domain Check', '3. Url Check', sep='\\n')\r\n decision = input('Enter your IOC : ')\r\n if decision == '1':\r\n vt_obj = Virustotal(ip=input('Enter IP : '))\r\n vt_obj.ip_check()\r\n elif decision == '2':\r\n vt_obj = Virustotal(domain=input('Enter domain : '))\r\n vt_obj.domain_check()\r\n elif decision == '3':\r\n vt_obj = Virustotal(url=input('Enter url : '))\r\n vt_obj.url_check()\r\n elif choice == '2':\r\n print('1. IP Check', '2. Domain Check', '3. Url Check', sep='\\n')\r\n decision = input('Enter your IOC : ')\r\n if decision == '1':\r\n void_obj = APIVoid(ip=input('Enter IP : '))\r\n void_obj.ip_check()\r\n elif decision == '2':\r\n void_obj = APIVoid(ip=input('Enter domain : '))\r\n void_obj.domain_check()\r\n elif decision == '3':\r\n void_obj = APIVoid(ip=input('Enter url : '))\r\n void_obj.url_check()\r\n elif choice == '3':\r\n print('1. IP Check', '2. Domain Check', '3. Url Check', sep='\\n')\r\n decision = input('Enter your IOC : ')\r\n if decision == '1':\r\n IBM_obj = IBMXFORCE(ip=input('Enter IP : '))\r\n IBM_obj.ip_check()\r\n elif decision == '2':\r\n IBM_obj = IBMXFORCE(ip=input('Enter domain : '))\r\n IBM_obj.domain_check()\r\n elif decision == '3':\r\n IBM_obj = IBMXFORCE(ip=input('Enter url : '))\r\n IBM_obj.url_check()\r\n else:\r\n print('Invalid Selection, Please try again')\r\n\r\n\r\neng = Engine()\r\neng.main()","sub_path":"Reputation.py","file_name":"Reputation.py","file_ext":"py","file_size_in_byte":22396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"282232527","text":"from pathlib import Path\nfrom typing import Union\n\nimport torch\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nimport time\nimport os\n\nfrom torchvision.transforms.transforms import ConvertImageDtype\nfrom datasets.block import BlockDataset, LatentBlockDataset\nimport numpy as np\n\nfrom models.vqvae import VQVAE\n\n\ndef load_mnist():\n train = datasets.MNIST(root=\"data\", train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Lambda(lambda x: torch.cat([x], dim=0)),\n transforms.Normalize(\n (0.5,), (0.5,)),\n ]))\n\n val = datasets.MNIST(root=\"data\", train=False, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Lambda(lambda x: torch.cat([x], dim=0)),\n transforms.Normalize(\n (0.5,), (0.5,)),\n ]))\n return train, val\n\n\ndef load_cifar():\n train = datasets.CIFAR10(root=\"data\", train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]))\n\n val = datasets.CIFAR10(root=\"data\", train=False, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]))\n return train, val\n\n\ndef load_block():\n data_folder_path = os.getcwd()\n data_file_path = data_folder_path + \\\n '/data/randact_traj_length_100_n_trials_1000_n_contexts_1.npy'\n\n train = BlockDataset(data_file_path, train=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]))\n\n val = BlockDataset(data_file_path, train=False,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]))\n return train, val\n\n\ndef load_boots():\n data_folder_path = os.getcwd()\n data_file_path = data_folder_path + '/data/boots.npy'\n train = BlockDataset(data_file_path, train=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]), resize=False, crop=True)\n\n val = BlockDataset(data_file_path, train=False,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]), resize=False, crop=True)\n\n return train, val\n\n\ndef load_duckietown():\n data_folder_path = os.getcwd()\n data_file_path = data_folder_path + \\\n '/data/MultiMap-v0_dataset_x_1M_objects.npy'\n\n train = BlockDataset(data_file_path, train=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]), resize=False, crop=True)\n\n val = BlockDataset(data_file_path, train=False,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(\n (0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]), resize=False, crop=True)\n\n return train, val\n\n\ndef load_latent_block():\n data_folder_path = os.getcwd()\n data_file_path = data_folder_path + \\\n '/data/latent_e_indices.npy'\n\n train = LatentBlockDataset(data_file_path, train=True,\n transform=None)\n\n val = LatentBlockDataset(data_file_path, train=False,\n transform=None)\n return train, val\n\n\ndef data_loaders(train_data, val_data, batch_size):\n\n train_loader = DataLoader(train_data,\n batch_size=batch_size,\n shuffle=True,\n pin_memory=True)\n val_loader = DataLoader(val_data,\n batch_size=batch_size,\n shuffle=True,\n pin_memory=True)\n return train_loader, val_loader\n\n\ndef load_data_and_data_loaders(dataset, batch_size):\n if dataset == 'CIFAR10':\n training_data, validation_data = load_cifar()\n training_loader, validation_loader = data_loaders(\n training_data, validation_data, batch_size)\n x_train_var = np.var(training_data.data / 255.0)\n\n elif dataset == 'MNIST':\n training_data, validation_data = load_mnist()\n training_loader, validation_loader = data_loaders(\n training_data, validation_data, batch_size)\n x_train_var = np.var(np.expand_dims(training_data.data, -1) / 255.0)\n\n elif dataset == 'BLOCK':\n training_data, validation_data = load_block()\n training_loader, validation_loader = data_loaders(\n training_data, validation_data, batch_size)\n\n x_train_var = np.var(training_data.data / 255.0)\n elif dataset == 'LATENT_BLOCK':\n training_data, validation_data = load_latent_block()\n training_loader, validation_loader = data_loaders(\n training_data, validation_data, batch_size)\n\n x_train_var = np.var(training_data.data)\n\n elif dataset == 'DUCKIETOWN':\n training_data, validation_data = load_duckietown()\n training_loader, validation_loader = data_loaders(\n training_data, validation_data, batch_size)\n\n x_train_var = np.var(training_data.data)\n\n elif dataset == 'BOOTS':\n training_data, validation_data = load_boots()\n training_loader, validation_loader = data_loaders(\n training_data, validation_data, batch_size)\n\n x_train_var = np.var(training_data.data)\n\n else:\n raise ValueError(\n 'Invalid dataset: only CIFAR10 and BLOCK datasets are supported.')\n\n return training_data, validation_data, training_loader, validation_loader, x_train_var\n\n\ndef readable_timestamp():\n return time.ctime().replace(' ', ' ').replace(\n ' ', '_').replace(':', '_').lower()\n\n\ndef save_model_and_results(model, results, hyperparameters, name_suffix):\n SAVE_MODEL_PATH = os.getcwd() + '/results'\n\n results_to_save = {\n 'model': model.state_dict(),\n 'results': results,\n 'hyperparameters': hyperparameters\n }\n torch.save(results_to_save,\n SAVE_MODEL_PATH + '/vqvae_' + name_suffix + '.pth')\n\n\ndef load_vqvae(model_path: Union[str, Path], device: torch.device = None):\n model_path = Path(model_path)\n if device is None:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n if torch.cuda.is_available():\n data = torch.load(model_path)\n else:\n data = torch.load(model_path, map_location=lambda storage, loc: storage)\n\n params = data[\"hyperparameters\"]\n\n if 'channels' in params:\n channels = params['channels']\n else:\n channels = 1 if params['dataset'] == 'MNIST' else 3\n\n model = VQVAE(channels, params['n_hiddens'], params['n_residual_hiddens'],\n params['n_residual_layers'], params['n_embeddings'],\n params['embedding_dim'], params['beta']).to(device)\n\n model.load_state_dict(data['model'])\n\n return model, data\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"537608760","text":"from decisionTree import *\nfrom matplotlib import pyplot as plt \nimport numpy as np \nimport sys\nimport csv\nfrom inspection import inspectData\nimport copy\nimport math\n\n\n\n\n\n\ndef main():\n\n trainInput = sys.argv[1]\n testInput = sys.argv[2]\n #maxDepthTmp = sys.argv[3]\n \n \"\"\"\n outputTrainFile = sys.argv[4]\n outputTestFile = sys.argv[5]\n outputMetrics = sys.argv[6]\n \"\"\"\n\n\n tmpTrainData = csv.reader(open(trainInput), delimiter = \"\\t\")\n trainDataTmp = np.array(list(tmpTrainData))\n\n tmpTestData = csv.reader(open(testInput), delimiter = \"\\t\")\n testDataTmp = np.array(list(tmpTestData))\n\n attributesLstTrain = copy.deepcopy(trainDataTmp)[0, 0:-1]\n attributesLstTest = copy.deepcopy(testDataTmp)[0, 0:-1]\n\n trainData = np.reshape(trainDataTmp, (len(trainDataTmp), len(trainDataTmp[0])))\n testData = np.reshape(testDataTmp, (len(testDataTmp), len(testDataTmp[0])))\n \n currentDepth = 0\n #maxDepth = int(maxDepthTmp)\n \n trainDataCopy = copy.deepcopy(trainData)\n outputLst = trainDataCopy[1:,-1]\n\n class1 = outputLst[0]\n class2 = \"\"\n\n for row in outputLst:\n if row != class1:\n class2 = row\n\n classes = [class1, class2]\n \n\n \"\"\"\n node = Node(None, None, None, None, None, 0, 0)\n\n tree = buildDecisionTree(trainData, attributesLstTrain, maxDepth, currentDepth, classes, node)\n\n predictedTrainLabels = predictLabels(trainData, maxDepth, attributesLstTrain, tree)\n predictedTestLabels = predictLabels(testData, maxDepth, attributesLstTest, tree)\n\n #writeLabelsFile(predictedTrainLabels, outputTrainFile, predictedTestLabels, outputTestFile)\n\n trainingError = trainError(trainData, predictedTrainLabels)\n testingError = testError(testData, predictedTestLabels)\n\n \"\"\"\n\n errorTrainVals = []\n errorTestVals = []\n\n maxDepthValsTrain = []\n maxDepthValsTest = []\n\n\n for maxDepth in range(0, len(attributesLstTrain)):\n\n\n maxDepthValsTrain.append(maxDepth)\n\n node = Node(None, None, None, None, None, 0, 0)\n tree = buildDecisionTree(trainData, attributesLstTrain, maxDepth, currentDepth, classes, node)\n predictedTrainLabels = predictLabels(trainData, maxDepth, attributesLstTrain, tree)\n \n trainingError = trainError(trainData, predictedTrainLabels)\n errorTrainVals.append(trainingError)\n\n\n\n for maxDepth in range(0, len(attributesLstTest)):\n\n maxDepthValsTest.append(maxDepth)\n\n node = Node(None, None, None, None, None, 0, 0)\n tree = buildDecisionTree(trainData, attributesLstTrain, maxDepth, currentDepth, classes, node)\n\n predictedTestLabels = predictLabels(testData, maxDepth, attributesLstTest, tree)\n\n testingError = testError(testData, predictedTestLabels)\n errorTestVals.append(testingError)\n\n\n\n\n plt.figure()\n plt.suptitle(\"Training and Testing Error of Decision Trees of Varying Depths\\n(Evaluated on Politicians Datasets)\")\n plt.plot(maxDepthValsTrain, errorTrainVals, label = \"Train Error\")\n plt.plot(maxDepthValsTest, errorTestVals, label = \"Test Error\")\n\n plt.xlabel(\"Max Depth (<= numAttributes)\")\n plt.ylabel(\"Train/Test Error\")\n plt.legend(loc = \"lower right\")\n plt.show()\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"Decision Tree/hw2Empirical.py","file_name":"hw2Empirical.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"651756409","text":"import psycopg2\n\n## connect to the db\nhost = \"localhost\"\ndb = \"stock_selector_db\"\nuser = \"postgres\"\npw = \"123\"\n\nconn = psycopg2.connect(\n host = host,\n database = db,\n user = user,\n password = pw)\n\ncur = conn.cursor()\n\n## updating the company\nwhile True:\n company = input(\"what company do you want to update?\\n\")\n try:\n ## getting the id of the company\n cur.execute('''\n SELECT id FROM companies WHERE \"name\" = %s''', (company,))\n companies_id = cur.fetchone()[0]\n except TypeError:\n print(\"that company is not in the database\\n\")\n continue\n \n shares = int(input(\"shares outstanding:\\n\"))\n try:\n value = int(input(\"market cap:\\n\"))\n except ValueError:\n value = int(input(\"price:\\n\")) * shares\n update = input(\"date (yyyy/mm/dd):\\n\")\n \n print(\"are you sure you want to add these values to the database?\\n\",\n \"company:\",company,\"\\n\",\n \"shares outstanding\",shares,\"\\n\",\n \"market value:\",value,\"\\n\")\n \n answer = input(\"(y/n)\\n\")\n if answer == 'y':\n if update == '':\n cur.execute ('''\n UPDATE companies SET \"total market value\" = %s, \"shares outstanding\" = %s WHERE id = %s;\n ''', (value, shares, companies_id,))\n break\n else:\n cur.execute ('''\n UPDATE companies SET \"total market value\" = %s, \"shares outstanding\" = %s, \"last update\" = %s WHERE id = %s;\n ''', (value, shares, update, companies_id,))\n break\n else:\n continue\n\n## save the data in the database\nconn.commit()\nprint(\"company updated\\n\")\n\n## insert incomes\nanswer = input(\"do you want to register an income?\\n(y/n)\\n\")\nif answer == 'y':\n while True:\n net_income = int(input(\"net income:\\n\"))\n date = input(\"date of the income stament you get the net income from (yyyy/mm/dd):\\n\")\n \n print(\n \"are you sure you want to add these values to the database?\\n\",\n \"company:\",company,\"\\n\",\n \"net income:\",net_income,\"\\n\",\n \"date:\",date,\"\\n\"\n )\n answer = input(\"(y/n)\\n\")\n \n if answer == 'y':\n if date == '':\n cur.execute ('''\n INSERT INTO incomes (\"net income\", companies_id) VALUES (%s, %s);\n ''', (net_income, companies_id,))\n break\n else:\n cur.execute ('''\n INSERT INTO incomes (\"net income\", \"date\", companies_id) VALUES (%s, %s, %s);\n ''', (net_income, date, companies_id,))\n break\n else:\n continue\n\n ## save the data in the database\n conn.commit()\n print(\"income inserted\\n\")\nelse:\n print(\"income not inserted\\n\")\n\n## insert balance_sheets\nanswer = input(\"do you want to register a balance sheet?\\n(y/n)\\n\")\nif answer == 'y':\n while True: \n try:\n current_assets = int(input(\"current assets:\\n\"))\n except ValueError:\n current_assets = None\n try:\n tangible_assets = int(input(\"tangible assets:\\n\"))\n except ValueError:\n tangible_assets = None\n try:\n total_assets = int(input(\"total assets:\\n\"))\n except ValueError:\n total_assets = None\n try:\n current_lia = int(input(\"current liabilities:\\n\"))\n except ValueError:\n current_lia = None\n try:\n total_lia = int(input(\"total liabilities:\\n\"))\n except ValueError:\n total_lia = None\n try: \n total_equity = int(input(\"total equity:\\n\"))\n except ValueError:\n try:\n total_equity = total_assets - total_lia\n except TypeError:\n total_equity = None\n\n date = input(\"date of the balance sheet(yyyy/mm/dd):\\n\")\n \n print(\n \"are you sure you want to add these values to the database?\\n\",\n \"company:\",company,\"\\n\",\n \"current assets\",current_assets,\"\\n\",\n\t \"tangible assets\",tangible_assets,\"\\n\",\n\t \"total assets\",total_assets,\"\\n\",\n\t \"current liabilities\",current_lia,\"\\n\",\n\t \"total liabilities\",total_lia,\"\\n\",\n\t \"total equity\",total_equity,\"\\n\",\n \"date:\",date,\"\\n\",\n )\n answer = input(\"(y/n)\\n\")\n \n if answer == 'y':\n if date == '':\n cur.execute ('''\n INSERT INTO balance_sheets (\"current assets\", \"tangible assets\", \"total assets\", \n \"current liabilities\", \"total liabilities\", \"total equity\", companies_id) \n VALUES (%s, %s, %s, %s, %s, %s, %s);\n ''', (current_assets, tangible_assets, total_assets, current_lia, total_lia, total_equity, companies_id,))\n break\n else:\n cur.execute ('''\n INSERT INTO balance_sheets (\"current assets\", \"tangible assets\", \"total assets\", \n \"current liabilities\", \"total liabilities\", \"total equity\", \"date\", companies_id) \n VALUES (%s, %s, %s, %s, %s, %s, %s, %s);\n ''', (current_assets, tangible_assets, total_assets, current_lia, total_lia, total_equity, date, companies_id,))\n break\n else:\n continue\n\n ## save the data in the database\n conn.commit()\n print(\"balance sheet inserted\\n\")\nelse:\n print(\"balance sheet not inserted\\n\")\n\n## insert debt\nanswer = input(\"do you want to register debt?\\n(y/n)\\n\")\nif answer == 'y':\n while True: \n try:\n total_debt = int(input(\"total debt:\\n\"))\n except ValueError:\n total_debt = None \n if total_debt != None: \n try:\n debt_equity = round(total_debt / total_equity, 2) \n except TypeError:\n try:\n debt_equity = float(input(\"debt/equity ratio:\\n\"))\n except ValueError:\n debt_equity = None\n try:\n current_ratio = round(current_assets / current_lia, 2)\n except TypeError:\n try:\n current_ratio = float(input(\"current ratio:\\n\"))\n except ValueError:\n current_ratio = None\n \n print(\n \"are you sure you want to add these values to the database?\\n\",\n \"company:\",company,\"\\n\",\n \"total debt\",total_debt,\"\\n\",\n \"debt/equity ratio\",debt_equity,\"\\n\",\n \"current ratio\",current_ratio,\"\\n\",\n \"date:\",date,\"\\n\",\n )\n answer = input(\"(y/n)\\n\")\n \n if answer == 'y':\n if date == '':\n cur.execute ('''\n INSERT INTO debt (\"total debt\", \"debt/equity ratio\", \"current ratio\", companies_id) VALUES (%s, %s, %s, %s);\n ''', (total_debt, debt_equity, current_ratio, companies_id,))\n break\n else:\n cur.execute ('''\n INSERT INTO debt (\"total debt\", \"debt/equity ratio\", \"current ratio\", \"date\", companies_id) VALUES (%s, %s, %s, %s, %s);\n ''', (total_debt, debt_equity, current_ratio, date, companies_id,))\n break\n else:\n continue\n\n ## save the data in the database\n conn.commit()\n print(\"debt inserted\\n\")\nelse:\n print(\"debt not inserted\\n\")\n\n## insert shares\nanswer = input(\"do you want to register a share?\\n(y/n)\\n\")\nif answer == 'y':\n while True:\n ticker = input(\"ticker:\\n\")\n price = float(input(\"price:\\n\"))\n try:\n eps = round(net_income / shares, 2)\n except TypeError: \n try: \n eps = float(input(\"EPS ratio:\\n\"))\n except ValueError:\n eps = None\n try:\n pe = round(price / eps, 2)\n except TypeError:\n try:\n pe = float(input(\"PE ratio:\\n\"))\n except ValueError:\n pe = None \n try:\n book_value = round(total_equity / shares, 2)\n except TypeError:\n try: \n book_value = float(input(\"book value:\\n\"))\n except ValueError:\n book_value = None\n exchange = input(\"exchange:\\n\")\n date = input(\"date (yyyy/mm/dd):\\n\")\n \n print(\n \"are you sure you want to add these values to the database?\\n\",\n \"company:\",company,\"\\n\",\n \"ticker:\",ticker,\"\\n\",\n \"PE:\",pe,\"\\n\",\n \"EPS:\",eps,\"\\n\",\n \"book value:\",book_value,\"\\n\",\n \"exchange:\",exchange,\"\\n\",\n \"price:\",price,\"\\n\",\n \"date:\",date,\"\\n\",\n )\n answer = input(\"(y/n)\\n\")\n \n if answer == 'y':\n if date == '':\n cur.execute ('''\n INSERT INTO shares (\"ticker\", \"PE\", \"EPS\", \"book value\", \"exchange\", \"price\", companies_id) \n VALUES (%s, %s, %s, %s, %s, %s, %s);\n ''', (ticker, pe, eps, book_value, exchange, price, companies_id,))\n break\n else:\n cur.execute ('''\n INSERT INTO shares (\"ticker\", \"PE\", \"EPS\", \"book value\", \"exchange\", \"price\", \"date\", companies_id) \n VALUES (%s, %s, %s, %s, %s, %s, %s, %s);\n ''', (ticker, pe, eps, book_value, exchange, price, date, companies_id,))\n break\n else:\n continue\n\n ## save the data in the database\n conn.commit()\n print(\"share inserted\\n\")\nelse:\n print(\"share not inserted\\n\")\n\n## insert dividends\nanswer = input(\"do you want to register dividends?\\n(y/n)\\n\")\nif answer == 'y':\n while True:\n trailing_rate = float(input(\"trailing rate:\\n\"))\n forward_rate = float(input(\"forward rate:\\n\"))\n trailing_yield = float(input(\"trailing yield:\\n\"))\n forward_yield = float(input(\"forward yield:\\n\"))\n average = float(input(\"5 year average yield:\\n\"))\n date = input(\"date (yyyy/mm/dd):\\n\")\n \n print(\n \"are you sure you want to add these values to the database?\\n\",\n \"company:\",company,\"\\n\",\n \"trailing rate\",trailing_rate,\"\\n\",\n\t \"forward rate\",forward_rate,\"\\n\",\n\t \"trailing yield\",trailing_yield,\"\\n\",\n \"forward yield\",forward_yield,\"\\n\",\n \"5 year average yield\",average,\"\\n\"\n \"date:\",date,\"\\n\",\n )\n answer = input(\"(y/n)\\n\")\n\n if answer == 'y':\n if date == '':\n cur.execute ('''\n INSERT INTO dividends (\"trailing rate\", \"forward rate\", \"trailing yield\", \"forward yield\", \"5 year average yield\", companies_id) VALUES (%s, %s, %s, %s, %s, %s);\n ''', (trailing_rate, forward_rate, trailing_yield, forward_yield, average, companies_id,))\n break\n else:\n cur.execute ('''\n INSERT INTO dividends (\"trailing rate\", \"forward rate\", \"trailing yield\", \"forward yield\", \"5 year average yield\" \"date\", companies_id) VALUES (%s, %s, %s, %s, %s, %s, %s);\n ''', (trailing_rate, forward_rate, trailing_yield, forward_yield, average, date, companies_id,))\n break\n else:\n continue\n\n ## save the data in the database\n conn.commit()\n print(\"dividends inserted\\n\")\nelse:\n print(\"dividends not inserted\\n\")\n\n## close the connection\ncur.close()\nconn.close()\n\nprint('done')\n","sub_path":"data_insertion/insertion_with_prompt/update_to_db.py","file_name":"update_to_db.py","file_ext":"py","file_size_in_byte":11499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"213282310","text":"import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\nimport numpy as np\nimport pandas as pd\nimport re\n\nnltk.download('stopwords') #list of irrelevant words\n\nclass Utilities():\n\t@staticmethod\n\tdef convert_category(x):\n\t\tif (x == 'hockey'):\n\t\t\treturn 0\n\t\telif (x == 'movies'):\n\t\t\treturn 1\n\t\telif (x == 'nba'):\n\t\t\treturn 2\n\t\telif (x == 'news'):\n\t\t\treturn 3\n\t\telif (x == 'nfl'):\n\t\t\treturn 4\n\t\telif (x == 'politics'):\n\t\t\treturn 5\n\t\telif (x == 'soccer'):\n\t\t\treturn 6\n\t\telif (x == 'worldnews'):\n\t\t\treturn 7\n\t\telse:\n\t\t\treturn -1 #sentinel value for invalid category\n\n\t@staticmethod\n\tdef lemmatize(conversation):\n\t\twordnet_lemmatizer = WordNetLemmatizer()\n\t\tconversation = [wordnet_lemmatizer.lemmatize(word) for word in conversation if not word in set(stopwords.words('english'))]\n\t\tconversation = ' '.join(conversation)\n\t\treturn conversation \n\n\t@staticmethod\n\tdef remove_tags(conversation_with_tags):\n\t\treturn re.sub('<.*?>', ' ', conversation_with_tags)\n\n\t@staticmethod\n\tdef remove_punctuation(conversation):\n\t\treturn re.sub('[^a-zA-Z]', ' ', conversation)\n\n\t@staticmethod\n\tdef read_input_data():\n\t\ttraining_set_input = pd.read_csv('./train_data/train_input.csv')\n\t\ttraining_set_output = pd.read_csv('./train_data/train_output.csv')\n\t\ttraining_set_input_no_header = np.delete(np.array(training_set_input), [0], 1).ravel()\n\t\ttraining_set_output_no_header = np.delete(np.array(training_set_output), [0], 1).ravel()\n\t\treturn [training_set_input_no_header, training_set_output_no_header]\n\n\t@staticmethod\n\tdef stem(conversation):\n\t\tstemmer = PorterStemmer()\n\t\tconversation = [stemmer.stem(word) for word in conversation if not word in set(stopwords.words('english'))]\n\t\tconversation = ' '.join(conversation)\n\t\treturn conversation\n\n\t@staticmethod\n\tdef write_to_csv(corpus, frame):\n\t\tdf_conversation = pd.DataFrame(corpus) \n\t\tdf_conversation = df_conversation.rename(columns={0: 'conversation'})\n\t\tdf_categories = pd.DataFrame(right['category'])\n\t\tdf_categories_test = df_categories.head(2000)\n\t\tconcat_frames = [df_conversation, df_categories_test]\n\t\tjoined_frames = pd.concat(concat_frames, axis=1)\n\t\tjoined_frames.to_csv('./cleaned_data/CLEANED_DATA.csv', index = False)\n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"104160274","text":"import os\nimport datetime\nimport csv\nfrom tkinter import *\nfrom PIL import ImageTk,Image\n#needed to use messagebox\nfrom tkinter import messagebox\nfrom Data_class import *\nimport paho.mqtt.client as mqtt \n\n\nclass Testing:\n def __init__(self, calibration_status = \"not complete\"):\n ## MQTT Setup\n self.client = mqtt.Client(\"AED_rasp_pi\")\n self.client.username_pw_set(\"tuf53905@temple.edu\", password=\"GMPQTtw7\")\n self.client.connect(\"maqiatto.com\", 1883, 60 )\n \n #variables\n self.calibration_complete = calibration_status\n \n ##GUI attributes\n self.test_top = Toplevel()\n self.test_top.title(\"Testing\")\n \n #create labels and buttons\n self.title_label = Label(self.test_top, text=\"Testing State\", font=(\"Arial\", 16), width=50, borderwidth=5)\n self.calibration_button = Button(self.test_top, padx = 50, pady = 50, text=\"Calibrate the Motor\", command=self.calibrate)\n self.time_test_button = Button(self.test_top, padx = 50, pady = 50, text=\"Time Test the Motor\", command=self.time_test)\n\n #place labels and buttons\n self.title_label.grid(row=0,column=0, columnspan=3)\n self.calibration_button.grid(row=2,column=0, padx = (25,25), pady=(100,100))\n self.time_test_button.grid(row=2,column=2, padx = (25,25), pady=(100,100))\n \n \n \n \n \n \n \n #send a MQTT Message to calbrate the Machine \n def calibrate(self):\n self.client.publish(\"tuf53905@temple.edu/MotorControl\", \"calibrate\")\n self.calibration_complete = \"complete\"\n \n# testing = 0\n# self.client.start_loop()\n# while (testing == 0):\n# self.client.publish(\"tuf53905@temple.edu/MotorControl\", \"calibrate\")\n# self.client.wait_for_publish()\n# print(self.client.is_published())\n# if (self.client.is_published()):\n# testing = 1\n# self.client.stop_loop()\n return(\"calibration complete\")\n \n def time_test(self):\n self.client.publish(\"tuf53905@temple.edu/MotorControl\", \"testing\")\n self.calibration_complete = \"complete\"\n return \n \n \n \n \n \n \n \n ","sub_path":"testing_state.py","file_name":"testing_state.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"95055742","text":"#creation of variables\npt = input('Enter the text you want to encrypt: ')\nk = int (input('Enter a value for your key(integer): '))\net = '' \n\n\n#running the loop (algorithm)\nfor char in pt: \n a = ord(char) - 97\n a += k \n et += chr(a + 97)\n a = a % 26\n\n\n\n#printing results\nprint('Encrypted:', (et))\nprint ('Decrypted:', (pt))\n","sub_path":"ProblemSet9.3.py","file_name":"ProblemSet9.3.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"454871491","text":"import os\nimport re\nimport socket\nimport threading\nimport time\nimport tldextract\nimport requests\nimport urllib\nimport random\nfrom flask import Flask\nfrom flask import request\nfrom colorama import init, Fore, Back, Style\ninit(convert=True)\n\napp = Flask(__name__)\n\n\nclass GetProxy(threading.Thread):\n def __init__(self, proxy_, urlSite, threadNum):\n threading.Thread.__init__(self)\n self.api = \"34d266e5-4ef1-42c3-9bd3-077e41f5c21c\"\n\n self.urlSite = urlSite\n self.proxy_ = proxy_\n self.timeout = 10\n self.threadNum = threadNum\n self.headers = {\n 'accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n 'upgrade-insecure-requests': \"1\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36\",\n 'referer': \"https://www.yahoo.com/\",\n 'accept-encoding': \"gzip, deflate, sdch, br\",\n 'accept-language': \"en-US,en;q=0.8,hr;q=0.6\",\n 'cache-control': \"no-cache\",\n }\n self.found = False\n\n self.url = \"http://gimmeproxy.com/api/getProxy?api_key=%s\" % self.api\n\n self.lock = threading.Lock()\n self.retry_times = 0\n self.domainReadyList_max = 10\n self.domainReadyFull = False\n socket.setdefaulttimeout(10)\n\n\n def getIpFromResponse(self, content):\n pattern = re.search(r'\"ipPort\"\\s*:\\s*\"([^\"]+)\"', content, re.I | re.S)\n if pattern:\n proxy = pattern.group(1)\n proxy = \"http://%s\" % proxy\n return proxy\n else:\n print(\"Error response proxy no pattern match.\")\n return None\n\n def saveLinks(self, proxy):\n with open(\"ProxyListNotWorking.txt\", \"a+\") as l:\n l.write(\"%s\\n\" % proxy)\n l.flush()\n l.close()\n return\n\n def domainReadyList_filename(self, url):\n filename = \"\"\n urlElements = tldextract.extract(url)\n if urlElements.subdomain:\n filename = urlElements.subdomain + \"-\" + urlElements.domain\n else:\n filename = urlElements.domain\n return filename\n \n def domainReadyList_save(self, proxy, url):\n filename = self.domainReadyList_filename(url)\n exists = False;\n f = open(\"Tested_proxy/{}.txt\".format(filename),\"r+\")\n d = f.readlines()\n f.seek(0)\n for i in d:\n f.write(i)\n if i.strip() == proxy:\n exists = True;\n if not exists:\n f.write(proxy + \"\\r\") \n f.truncate()\n f.flush()\n f.close() \n\n def domainReadyList_count(self, url):\n filename = self.domainReadyList_filename(url)\n num_lines = sum(1 for line in open(\"Tested_proxy/{}.txt\".format(filename)))\n return num_lines\n\n def domainReadyList_getProxy(self, url):\n filename = self.domainReadyList_filename(url)\n if os.path.isfile(\"Tested_proxy/{}.txt\".format(filename)):\n f=open(\"Tested_proxy/{}.txt\".format(filename))\n lines=f.readlines()\n f.flush()\n f.close()\n if len(lines)>=1:\n return random.choice(lines).strip()\n else:\n return None\n else:\n open(\"Tested_proxy/{}.txt\".format(filename),\"w+\")\n return None\n\n def domainreadyList_delete(self, url, proxy_delete):\n filename = self.domainReadyList_filename(url)\n f = open(\"Tested_proxy/{}.txt\".format(filename),\"r+\")\n d = f.readlines()\n f.seek(0)\n for i in d:\n if i.strip() != proxy_delete:\n f.write(i)\n f.truncate()\n f.flush()\n f.close()\n \n def saveLink(self, proxy):\n with open(\"ProxyListWorking.txt\", \"a+\") as l:\n l.write(\"%s\\n\" % proxy)\n l.flush()\n l.close()\n return\n\n def run(self):\n # print('Running thread: %s' % self.urlSite)\n self.found = False\n if len(self.urlSite) > 60:\n url_to_print = self.urlSite[:60].strip()\n else:\n url_to_print = self.urlSite.strip()\n\n while not self.found:\n try:\n with self.lock:\n\n with requests.Session() as s:\n #####################################################\n \n try:\n ready_proxy = self.domainReadyList_getProxy(self.urlSite)\n if ready_proxy is not None:\n print(Fore.CYAN + 'Testing: %s for: %s' % (ready_proxy, url_to_print))\n proxies = {'http': ready_proxy, 'https': ready_proxy}\n r = s.get(self.urlSite, headers=self.headers, proxies=proxies, timeout=self.timeout, verify=True)\n if r.status_code == 200:\n print(Fore.GREEN + 'OK: %s' % ready_proxy.strip())\n self.proxy_ = ready_proxy \n self.found = True\n else:\n self.domainreadyList_delete(self.urlSite, ready_proxy)\n except Exception as e:\n self.domainreadyList_delete(self.urlSite, ready_proxy)\n \n ######################################################\n \n while not self.domainReadyFull:\n response = s.get(self.url, timeout=self.timeout)\n if response.status_code == 200:\n content = response.text\n\n proxy = self.getIpFromResponse(content)\n if re.match(r'http://[\\d.:]+', proxy):\n \n print(Fore.RED + 'Testing: %s -> %s' % (proxy, url_to_print))\n self.saveLinks(proxy)\n self.retry_times += 1\n if self.retry_times > 200:\n self.found = True\n\n try:\n proxies = {'http': proxy, 'https': proxy}\n r = s.get(self.urlSite, headers=self.headers, proxies=proxies, timeout=self.timeout, verify=True)\n if r.status_code == 200:\n print(Fore.GREEN + 'OK: %s' % proxy.strip())\n self.saveLink(proxy)\n self.domainReadyList_save(proxy, self.urlSite)\n except Exception as e:\n pass\n if self.domainReadyList_count(self.urlSite) >= self.domainReadyList_max:\n self.domainReadyFull = True \n \n\n except Exception as e:\n pass\n\n\n@app.route(\"/getProxy\", methods=['GET'])\ndef hello():\n url = request.args.get('url')\n if url:\n proxy = None\n time.sleep(2)\n try:\n th_list = []\n number_of_threads = 4\n for t in range(number_of_threads):\n th = GetProxy(proxy, url, t)\n th.daemon = True\n th.start()\n th_list.append(th)\n\n p = None\n found = False\n\n while not found:\n for thread in th_list:\n proxy_ = thread.proxy_\n if proxy_:\n p = proxy_\n found = True\n break\n time.sleep(0.5)\n\n for thread in th_list:\n if thread.isAlive():\n thread.found = True\n\n return p\n\n except Exception as e:\n print(e)\n\nif __name__ == '__main__':\n\n app.run(host=\"0.0.0.0\", port=50501, threaded=True)\n # app.run(host=\"127.0.0.1\", port=50501, threaded=True)\n print('Server has started on localhost port 50501 ..')\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"438947698","text":"'''\nIan Vernooy\nGraseck Block 5\nFinal Exam\n'''\n\nimport turtle\n\ndef dist(x1, y1, x2, y2): #The arguments are two points (x1, y1), and (x2, y2)\n distx = x2 - x1\n disty = y2 - y1\n distance = ((distx**2) + (disty**2))**(1/2)\n if distance < 4:\n print('The distance is ' + str(distance) + ', which is too short of a distance')\n elif distance > 25:\n print('The distance is ' + str(distance) + ', which is too long of a distance')\n else:\n print('The distance is ' + str(distance))\n #Instead of returning the distance, the program prints a statement about the distance\n \ndef finecalc(lim, spd):\n fine = 75 + 10*(spd - lim)\n if spd > 65:\n fine += 200\n print('For a car going ' + str(spd) + ' mph when the speed limit is ' + str(lim) + ', the fine would be $' + str(fine) + '.')\n #Once again, doesn't return a value, but uses the fine value within a sentence\n\ndef listsort():\n nums = []\n amount = eval(input('Enter the amount of numbers you will be entering:'))\n for i in range(1, amount + 1):\n nums.append(int(input('Enter your #' + str(i) + ' number: ')))\n nums = sorted(nums)\n numsrange = nums[amount - 1] - nums[0]\n print('Here is the sorted list:')\n print(nums)\n print('The range of the list is ' + str(numsrange))\n #Doesn't return a value, but prints out the sorted list and its range\n\ndef pentagon():\n turtle.speed(0)\n turtle.clear()\n turtle.home()\n turtle.setheading(0)\n for i in range(1, 31):\n turtle.forward(10*i)\n turtle.left(72)\n\ndef incometax(salary):\n if salary < 30000:\n return int(salary*0.11)\n elif salary <35000:\n return int(salary*0.18)\n elif salary < 65000:\n return int(salary*0.20)\n elif salary < 100000:\n return int(salary*0.23)\n else:\n return int(salary*0.26)\n #This method takes the salary and returns the tax, so you need to print out what the function\n #returns when you call it, or you could use it in some other way\n #NOTE: This method does not round to the nearest integer, it simply truncates the income tax to an integer\n #However, given more time, the output could easily be rounded instead...\n\ndef CenteredCircle(x, y, radius, color):\n turtle.penup()\n turtle.goto(x, y - radius)\n turtle.color(color)\n turtle.pendown()\n turtle.begin_fill()\n turtle.circle(radius)\n turtle.end_fill()\n turtle.penup()\n\ndef CenteredCircleNoFill(x, y, radius, color):\n turtle.penup()\n turtle.goto(x, y - radius)\n turtle.color(color)\n turtle.pendown()\n turtle.circle(radius)\n turtle.penup()\n\ndef arm(x, y, n):\n turtle.penup()\n turtle.color('brown')\n turtle.goto(x, y)\n turtle.setheading(n)\n turtle.pendown()\n turtle.begin_fill()\n for i in range(0, 2):\n turtle.forward(100)\n turtle.right(90)\n turtle.forward(5)\n turtle.right(90)\n turtle.end_fill()\n turtle.penup()\n\ndef smile():\n turtle.penup()\n turtle.color('red')\n turtle.goto(-15, 150)\n turtle.setheading(0)\n turtle.pendown()\n\n turtle.right(20)\n turtle.forward(10)\n turtle.left(20)\n turtle.forward(10)\n turtle.left(20)\n turtle.forward(10)\n \n turtle.penup()\n\ndef hat():\n turtle.penup()\n turtle.color('brown')\n turtle.goto(-40, 190)\n turtle.setheading(0)\n turtle.pendown()\n turtle.begin_fill()\n\n turtle.forward(20)\n turtle.right(270)\n turtle.forward(60)\n turtle.right(90)\n turtle.forward(40)\n turtle.right(90)\n turtle.forward(60)\n turtle.right(270)\n turtle.forward(20)\n turtle.right(90)\n turtle.forward(5)\n turtle.right(90)\n turtle.forward(80)\n turtle.right(90)\n turtle.forward(5)\n turtle.right(90)\n\n turtle.end_fill()\n turtle.penup()\n \ndef snowman():\n turtle.speed(0)\n turtle.clear()\n turtle.home()\n CenteredCircleNoFill(0, 0, 50, 'black')\n CenteredCircleNoFill(0, 90, 40, 'black')\n CenteredCircleNoFill(0, 160, 30, 'black')\n CenteredCircle(0, -15, 5, 'black')\n CenteredCircle(0, 15, 5, 'black')\n CenteredCircle(0, 75, 5, 'black')\n CenteredCircle(0, 105, 5, 'black')\n CenteredCircle(-10, 160, 3, 'blue')\n CenteredCircle(10, 160, 3, 'blue')\n arm(35, 90, 20)\n arm(-35, 90, 160)\n hat()\n smile()\n turtle.home()\n\ndef main():\n\n dist(0, 0, 3, 4)\n dist(0, 0, 9, 40)\n dist(0, 0, 1, 1)\n finecalc(65, 70)\n listsort()\n pentagon()\n print(incometax(50000))\n snowman()\n\nmain()\n","sub_path":"Ian Vernooy (Final Exam)/Vernooy_Ian_finalproject.py","file_name":"Vernooy_Ian_finalproject.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"20572249","text":"# -*- coding: utf-8 -*-\nimport json\nimport logging\nimport os\nimport random\n\nfrom .qa.base import Answerer\nfrom message.messageBuffer import messageBuffer\n\nclass Chatbot(object):\n\n def __init__(self, name=\"韩小喵\", threshold=50, debug=False):\n\n # The name of chatbot\n self.name = name\n self.threshold = threshold\n\n if debug:\n log_level = logging.DEBUG\n logFormat='%(asctime)s : %(levelname)s : [%(filename)15s:%(lineno)5s - %(funcName)10s()] %(message)s'\n else:\n log_level = logging.INFO\n logFormat='%(asctime)s : %(threadName)s : %(levelname)s : %(message)s'\n\n logging.basicConfig(level=log_level, format=logFormat)\n\n # For Question Answering\n try:\n self.answerer = Answerer()\n except Exception as e:\n self.answerer.database.close()\n logging.exception(\"[QA] 问答资料集未载入\")\n\n def run(self, speech):\n\n logging.info(\"检测到输入: '%s'\" % speech)\n\n # Init msgBuf, setting User and Query\n # TODO: Add timestamp info in msgBuf\n msgBuf = messageBuffer(user=\"defaultUser\", query=speech)\n logging.info(\"message buffer: '%s'\", msgBuf.getQuery())\n\n # Match for highest similarit above threshold\n self.analyse(msgBuf, self.threshold)\n\n # Get reply that will be passed to media consumer(outQueue)\n ret = msgBuf.getReply()\n\n # Save msgBuf per user\n # Log file at \"chat/data/msgHistory/.txt\"\n self.saveMsg(msgBuf)\n\n return str(ret)\n\n def searchVideoTag(self, speech):\n\n logging.info(\"检测到 searchVideoTag 输入: '%s'\" % speech)\n msgBuf = messageBuffer(user=\"defaultUser\", query=speech)\n self.answerer.getLabelResponse(msgBuf, self.threshold)\n self.saveMsg(msgBuf)\n return str(msgBuf.getReply())\n\n def searchVideoTitle(self, speech):\n\n logging.info(\"检测到 searchVideoTitle 输入: '%s'\" % speech)\n msgBuf = messageBuffer(user=\"defaultUser\", query=speech)\n self.answerer.getContainResponse(msgBuf, self.threshold)\n self.saveMsg(msgBuf)\n return str(msgBuf.getReply())\n\n def searchVideoName(self, speech):\n\n logging.info(\"检测到 searchVideoName 输入: '%s'\" % speech)\n msgBuf = messageBuffer(user=\"defaultUser\", query=speech)\n self.answerer.getContainResponse(msgBuf, self.threshold)\n self.saveMsg(msgBuf)\n return str(msgBuf.getReply())\n\n def searchTag(self, speech):\n\n logging.info(\"检测到 searchTag 输入: '%s'\" % speech)\n msgBuf = messageBuffer(user=\"defaultUser\", query=speech)\n self.answerer.getLabelResponse(msgBuf, self.threshold)\n self.saveMsg(msgBuf)\n return json.dumps(msgBuf.getJsonReply(), ensure_ascii=False)\n\n def analyse(self, msgBuf, threshold=0):\n #self.answerer.getResponse(msgBuf, threshold)\n self.answerer.getLabelResponse(msgBuf, threshold)\n self.answerer.getContainResponse(msgBuf, threshold)\n\n def saveMsg(self, msgBuf, path=\"./\"):\n path = os.path.join(os.path.dirname(__file__), \"data\", \"msgHistory\")\n if not os.path.exists(path):\n os.mkdir(path)\n\n if msgBuf.user:\n fileName = msgBuf.user + \".txt\"\n else:\n fileName = \"noUser.txt\"\n\n try:\n f = open(path + '/' + fileName, 'a+', encoding='utf-8')\n #msgBuf.setTargetIndex(list(msgBuf.getTargetIndex()))\n #f.write(json.dumps(msgBuf.__dict__))\n f.write('\\n')\n f.close()\n except Exception as e:\n logging.error(\"Save message error: %s\", e)\n","sub_path":"chat/chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"322717440","text":"import webapp2, os, jinja2, logging, sys\n\nfrom google.appengine.api import users, images\nfrom google.appengine.ext import ndb, blobstore\nfrom google.appengine.ext.webapp import blobstore_handlers\n\nsys.path.insert(0, 'libs') #this line is required to use external libs\n\nfrom models import Hat\n\njinja_env = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__))\n)\n\njinja_env.globals = {\n 'uri_for': webapp2.uri_for\n}\n\nlogging.getLogger().setLevel(logging.DEBUG)\n\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n self.redirect('overview') \n\nclass OverviewHandler(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n if user is not None:\n logout_url = users.create_logout_url(self.request.uri)\n template_context = {\n 'title': 'Overview',\n 'current_url': self.request.url,\n 'user': user.nickname(),\n 'logout_url': logout_url\n }\n \n self.response.out.write(self._render_template('templates/overview.html', template_context))\n else:\n login_url = users.create_login_url(self.request.uri)\n self.redirect(login_url) \n \n def _render_template(self, template_name, context=None):\n if context is None:\n context = {}\n \n user = users.get_current_user()\n ancestor_key = ndb.Key(\"User\", user.nickname())\n qry = Hat.query_hats_for_user(ancestor_key)\n context['hats'] = qry.fetch()\n \n template = jinja_env.get_template(template_name)\n return template.render(context)\n\nclass DetailHandler(webapp2.RequestHandler):\n \n def get(self, hat_id):\n user = users.get_current_user()\n if user is not None:\n logout_url = users.create_logout_url(self.request.uri)\n template_context = {\n 'title': 'Detail',\n 'hat_id': hat_id,\n 'current_url': self.request.url,\n 'user': user.nickname(),\n 'logout_url': logout_url\n }\n \n self.response.out.write(self._render_template('templates/detail.html', template_context))\n else:\n login_url = users.create_login_url(self.request.uri)\n self.redirect(login_url) \n \n def _render_template(self, template_name, context=None):\n if context is None:\n context = {}\n \n user = users.get_current_user()\n user_key = ndb.Key(\"User\", user.nickname())\n context['hat'] = Hat.query_hat(user_key, context['hat_id'])\n \n template = jinja_env.get_template(template_name)\n return template.render(context)\n\n\nclass HatUploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n \n user = users.get_current_user()\n\n if user is None:\n self.error(401)\n \n try:\n upload_blobs = self.get_uploads()\n \n photos = []\n for photo in upload_blobs:\n images.resize(photo, 400, 400)\n photos.append(str(photo.key()))\n \n self._create_hat(user, photos)\n \n except:\n self.error(500)\n \n \n @ndb.transactional\n def _create_hat(self, user, photos):\n #form\n if self.request.get('is-limited') == \"on\":\n is_limited_val=True\n else:\n is_limited_val=False\n \n if self.request.get('pri-color'):\n pri_col_val=int(self.request.get('pri-color'))\n else:\n pri_col_val=0\n \n if self.request.get('sec-color'):\n sec_col_val=int(self.request.get('sec-color'))\n else:\n sec_col_val=0\n \n hat = Hat(\n parent=ndb.Key(\"User\", user.nickname()),\n brand=self.request.get('brand'),\n name=self.request.get('name'),\n team=self.request.get('team'),\n is_limited=is_limited_val,\n pri_color=pri_col_val,\n sec_color=sec_col_val,\n description=self.request.get('description'),\n photos=photos\n )\n\n hat.put()\n \n self.redirect('overview') \n #self.redirect('/view_photo/%s' % upload.key())\n\n def _render_template(self, template_name, context=None):\n if context is None:\n context = {}\n \n user = users.get_current_user()\n user_key = ndb.Key(\"User\", user.nickname())\n qry = Hat.query_hats_for_user(user_key)\n context['hats'] = qry.fetch()\n \n template = jinja_env.get_template(template_name)\n return template.render(context)\n\nclass NewHatHandler(webapp2.RequestHandler):\n def get(self):\n upload_url = blobstore.create_upload_url('/upload_hat')\n \n user = users.get_current_user()\n if user is not None:\n logout_url = users.create_logout_url(self.request.uri)\n template_context = {\n 'title': 'Add',\n 'upload_url': upload_url,\n 'current_url': self.request.url,\n 'user': user.nickname(),\n 'logout_url': logout_url\n }\n \n self.response.out.write(self._render_template('templates/hatform.html', template_context))\n else:\n login_url = users.create_login_url(self.request.uri)\n self.redirect(login_url)\n\n\n def _render_template(self, template_name, context=None):\n if context is None:\n context = {}\n \n user = users.get_current_user()\n \n template = jinja_env.get_template(template_name)\n return template.render(context)\n\n\nclass ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):\n def get(self, photo_key):\n if not blobstore.get(photo_key):\n self.error(404)\n else:\n self.send_blob(photo_key)\n\napp = webapp2.WSGIApplication([\n webapp2.Route(r'/', handler=MainHandler, name='main'),\n webapp2.Route(r'/new', handler=NewHatHandler, name='new'),\n webapp2.Route(r'/overview', handler=OverviewHandler, name='overview'),\n webapp2.Route(r'/detail/', handler=DetailHandler, name='detail'),\n webapp2.Route(r'/upload_hat', handler=HatUploadHandler, name='upload_hat'),\n \n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"188516482","text":"import numpy as np\nimport pandas as pd\nimport psycopg2\n\nfrom bokeh.layouts import row, widgetbox\nfrom bokeh.models import Select\nfrom bokeh.palettes import Spectral5\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import curdoc, figure\nfrom bokeh.charts import TimeSeries\n\nfrom pmdatautils.imports import *\nimport pmdatautils.sandbox as ps\nimport datetime\n\ndef connection_to_redshift():\n connobj = psycopg2.connect(\n database=\"warehouse\",\n user=\"ds\",\n password=\"Ux3bh8avxKCfAHb2\",\n host=\"pmadness3.ce49qtomuo6o.us-east-1.redshift.amazonaws.com\",\n port=\"5439\")\n connobj.autocommit = True\n return connobj\n\nredconn = connection_to_redshift()\ndf = None\n\ndef get_all_loading_events():\n global redconn\n sql = '''\n select *\n from lookup_funnel_events\n order by loading_order\n '''\n df_events = pd.read_sql(sql, redconn)\n return df_events\n\ndef translate_client(client='iPad'):\n if client in ('Facebook', 'Web'):\n return ['web', 'any']\n return ['mobile', 'any']\n\ndef get_relevant_events(game='hov', client='iPhone'):\n df = get_all_loading_events()\n df_t = df[(df.game == game) & (df.client.isin(translate_client(client)) )]\n return list(df_t['action_type'].unique())\n\n\nargs = dict(start_date='2016-06-25',\n end_date='',\n game='ees',\n clients='iPad',\n events=['lobby_ready','lobby_loaded','new_visit', 'lobby_icon_ready'],\n events_condition='',\n sessions_condition='',\n time_resolution='day',\n exclusive_events=True,\n print_sql=False,\n )\n\n\ndef build_sql(args):\n\n args = ps.Map(args)\n if args.end_date == '':\n args.end_date = str(datetime.date.today())\n\n args.clients = pmc.validate_sql_list(args.clients)\n\n if args.exclusive_events:\n args.events_condition += 'and action_type in ' + pmc.validate_sql_list(args.events)\n\n sql = '''\n with loading_session as (\n SELECT\n game_account_id\n , visit_number\n , min(ts) as start_ts\n '''\n for e in args.events:\n sql += '''\n , max(CASE WHEN action_type = '{event}'\n THEN 1\n ELSE 0 END) AS {event}\n '''.format(event=e)\n\n sql += '''\n FROM {game}_events\n WHERE ts >= '{start_date}'::DATE - interval '3 hours'\n {events_condition}\n AND client in {clients}\n GROUP BY 1, 2\n )\n SELECT\n date_trunc('{time_resolution}',start_ts) as tm'''.format(**args)\n\n for e in args.events:\n sql += '\\n , sum({event})::FLOAT/count(1) as {event}'''.format(event=e)\n\n sql += '''\n FROM loading_session\n WHERE start_ts<'{end_date}' and start_ts>'{start_date}'\n {sessions_condition}\n GROUP BY 1\n ORDER BY 1\n '''.format(**args)\n return sql\n\n\ndef get_somethig():\n global df, redconn, args\n sql = build_sql(args)\n\n df = pd.read_sql(sql, redconn)\n return df\n\nsource = ColumnDataSource(data=dict(tm=[], new_visit=[]))\n\ndef create_figure():\n global df\n\n df = get_somethig()\n print(df)\n\n # p = figure(plot_height=600, plot_width=800, tools='pan,box_zoom,reset')\n # p.line('tm', 'new_visit', source=df)\n p = TimeSeries(df, 'tm', ['new_visit', 'lobby_loaded'])\n\n return p\n\nclients_options = ['iPhone', 'iPad', 'Android', 'Facebook', 'Amazon']\ngames_options = ['ees', 'hov']\nclients = Select(title='Client', value='Facebook', options=clients_options)\ngames = Select(title='Game', value='hov', options=games_options)\n\n\ndef update(attr, old, new):\n args['clients'] = clients.value\n args['game'] = games.value\n layout.children[1] = create_figure()\n\n\nclients.on_change('value', update)\ngames.on_change('value', update)\n\ncontrols = widgetbox([clients, games], width=200)\nlayout = row(controls, create_figure())\n\ncurdoc().add_root(layout)\ncurdoc().title = \"Loading Funnel\"\n","sub_path":"loading_funnel.py","file_name":"loading_funnel.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"231770129","text":"# https://programmers.co.kr/learn/courses/30/lessons/87694\n\ndef is_movable(prev, cur, rectangle):\n test_posX = (prev[0] + cur[0]) / 2\n test_posY = (prev[1] + cur[1]) / 2\n\n # border 위에 없으면 return False\n for rect in rectangle: # border_list = [[(x1,y1), (x2,y2)], [(), ()] ....]\n minX, minY, maxX, maxY = rect\n if minX == test_posX and minY <= test_posY <= maxY:\n break\n if maxX == test_posX and minY <= test_posY <= maxY:\n break\n if minY == test_posY and minX <= test_posX <= maxX:\n break\n if maxY == test_posY and minX <= test_posX <= maxX:\n break\n else:\n return False\n\n # 다른 사각형 안에 있으면 return False\n for rect in rectangle: # rect = [1,1,7,4]\n minX, minY, maxX, maxY = rect\n if (minX < test_posX < maxX) and (minY < test_posY < maxY):\n return False\n\n return True\n\n\ndef solution(rectangle, characterX, characterY, itemX, itemY):\n perimeter = float('inf')\n # dfs : 좀 다른 것 같다. 갈 수 있는 방향이 항상 하나밖에 없어. 맨 처음에는 2개.\n def dfs(prev, visited, dist):\n nonlocal perimeter\n for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # 일단 돌아보자\n cur = (prev[0] + dx, prev[1] + dy)\n if (not is_movable(prev, cur, rectangle)) or (cur in visited): # 가능성 없는 포지션\n continue\n\n # 가능성 있는 포지션에 대해 계속 탐색\n if cur == (itemX, itemY):\n perimeter = min(perimeter, dist + 1)\n break\n else:\n visited.add(cur)\n dfs(cur, visited, dist + 1)\n\n dfs((characterX, characterY), set([(characterX, characterY)]), 0)\n\n return perimeter\n\n\nif __name__ == '__main__':\n print(solution([[1, 1, 7, 4], [3, 2, 5, 5], [4, 3, 6, 9], [2, 6, 8, 8]], 1, 3, 7, 8))\n print(solution([[1, 1, 8, 4], [2, 2, 4, 9], [3, 6, 9, 8], [6, 3, 7, 7]], 9, 7, 6, 1))\n","sub_path":"프로그래머스연습문제/아이템줍기복습.py","file_name":"아이템줍기복습.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"498163867","text":"from . import fixtures\nfrom . import util\nimport time\nfrom utils.db import Invoice\n\n\ndef test_update(wd, factory):\n\n invoice1 = fixtures.INVOICE1.copy()\n invoice1.pop('customer_order_number')\n factory.insert('invoice', invoice1, 'invoice_id')\n\n util.click_button_by_id(wd, 'nav-sale')\n util.click_button_by_id(wd, 'customer-order-number')\n time.sleep(1)\n\n def matching(invoice_id):\n matches = wd.find_elements_by_id(invoice_id)\n return len(matches)\n\n id1 = invoice1['invoice_id']\n\n assert matching(str(id1)) == 1, 'expected one element with current id'\n\n # update value\n editables = wd.find_elements_by_css_selector('.edit-field')\n customer_order_number = '1234'\n util.fill_xeditable_field(wd, editables[0], customer_order_number)\n elems = wd.find_elements_by_class_name(\".edit_field\")\n\n # assert that the value has been updated\n inv = Invoice.get(id1)\n assert inv.customer_order_number == customer_order_number\n\n # reload and assert that the element is gone\n util.click_button_by_id(wd, 'nav-sale')\n util.click_button_by_id(wd, 'customer-order-number')\n time.sleep(1)\n\n assert matching(str(id1)) == 0, 'expected no elements with current id'\n","sub_path":"server/tests/test_customer_order_number.py","file_name":"test_customer_order_number.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"501593938","text":"import math\nimport time\nfrom typing import List\n\nimport arcade\n# Constants used to scale our sprites from their original size\nfrom arcade import SpriteList, Sprite\nfrom arcade.gui import UIManager\n\nimport game_over\nfrom background_handler import Background\nfrom constants import SCREEN_WIDTH, SCREEN_HEIGHT\nfrom equationGenerator import Equation\nfrom sprites.answer import Answer\nfrom sprites.bird import Bird\nfrom sprites.sky_scraper import SkyScraper\n\nCHARACTER_SCALING = 1\nTILE_SCALING = 0.4\nCOIN_SCALING = 0.5\n\n# Movement speed of player, in pixels per frame\nPLAYER_MOVEMENT_SPEED = 6\n\n# How many pixels to keep as a minimum margin between the character\n# and the edge of the screen.\nLEFT_VIEWPORT_MARGIN = 250\nRIGHT_VIEWPORT_MARGIN = SCREEN_WIDTH - LEFT_VIEWPORT_MARGIN\nBOTTOM_VIEWPORT_MARGIN = 50\nTOP_VIEWPORT_MARGIN = 100\nSTARTING_X_OFFSET = 500\n\n\nclass MyGame(arcade.View):\n \"\"\"\n Main application class.\n \"\"\"\n\n def __init__(self, level: int = 1):\n super().__init__()\n self.score: int = 0\n self.level = level\n # These are 'lists' that keep track of our sprites. Each sprite should\n # go into a list.\n self.wall_list = None\n self.wall_counter = 0\n\n self.bg_list = None\n self.answer_sprites = None\n self.sky_scraper_sprites = None\n\n # Separate variable that holds the player sprite\n self.player_sprite = None\n\n self.ui_manager = UIManager()\n\n # Our physics engine\n self.physics_engine = None\n\n # Used to keep track of our scrolling\n self.view_bottom = 0\n self.view_left = 0\n\n self.is_dead = False\n self.won = False\n self.sound = arcade.Sound(\"sound_files/dying2.mp3\", True)\n # keeps track of the player sprite's location from previous frame\n self.player_last_x = 0\n\n # Initialize equations\n self.equations: List[Equation] = None # First is current\n\n # Load sounds\n self.collect_coin_sound = arcade.load_sound(\":resources:sounds/coin1.wav\")\n self.jump_sound = arcade.load_sound(\":resources:sounds/jump1.wav\")\n self.courage_sound = arcade.load_sound(\"sound_files/courage screech.mp3\")\n self.dying_sound_1 = arcade.load_sound(\"sound_files/dying1.mp3\")\n self.dying_sound_2 = arcade.load_sound(\"sound_files/dying2.mp3\")\n self.music1 = arcade.load_sound(\"sound_files/music1.mp3\")\n\n arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)\n self.setup()\n\n def setup(self):\n self.is_dead = False\n \"\"\" Set up the game here. Call this function to restart the game. \"\"\"\n self.sky_scraper_sprites = SpriteList()\n self.answer_sprites = SpriteList()\n\n self.equations = []\n for i in range(3):\n self.equations.append(Equation(self.level))\n\n # Used to keep track of our scrolling\n self.view_bottom = 0\n self.view_left = 0\n\n # Create the Sprite lists\n self.wall_list = arcade.SpriteList()\n self.bg_list = Background(PLAYER_MOVEMENT_SPEED, self.level)\n\n # Set up the player, specifically placing it at these coordinates.\n image_source = \"assets-target/pixelbird2/\"\n self.player_sprite = Bird(image_source, CHARACTER_SCALING)\n self.player_sprite.center_x = 250\n self.player_sprite.center_y = SCREEN_HEIGHT // 2\n self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED\n\n # Load in walls (invisible)\n self.wall_list = SpriteList()\n wall_offset = STARTING_X_OFFSET + 830\n create_wall_list = lambda x_offset = 0: [\n Sprite(\"stoneMid.png\",\n scale=TILE_SCALING,\n center_x=wall_offset + x_offset,\n center_y=SCREEN_HEIGHT // 2 - 100),\n Sprite(\"stoneMid.png\",\n scale=TILE_SCALING,\n center_x=wall_offset + x_offset,\n center_y=SCREEN_HEIGHT // 2 + 100),\n ]\n self.wall_list.extend(create_wall_list())\n self.wall_list.extend(create_wall_list(1250))\n\n ys = [\n 116,\n 316,\n 516\n ]\n values = self.equations[0].answers\n for i in range(3):\n answer = Answer(COIN_SCALING)\n answer.center_x = 920 + STARTING_X_OFFSET\n answer.center_y = ys[i]\n answer.set_number(values[i])\n self.answer_sprites.append(answer)\n\n # create the sky scrapers\n center_x = STARTING_X_OFFSET + 920 - 1250 * 2\n center_y = SCREEN_HEIGHT // 2\n print([e.answers for e in self.equations])\n for i in range(3):\n values = self.equations[(i - 1) % len(self.equations)].answers\n sky_scraper = SkyScraper(values, id=self.wall_counter)\n self.wall_counter += 1\n sky_scraper.center_x = center_x\n sky_scraper.center_y = center_y\n center_x = sky_scraper.move_forward()\n print(\"hello!\")\n self.sky_scraper_sprites.append(sky_scraper)\n print(\"sky_scraper_sprites\", len(self.sky_scraper_sprites))\n if i == 0:\n # make the first invisible temporarily so it doesn't get in the way\n sky_scraper.scale = 0\n\n # Create the 'physics engine'\n self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite,\n self.wall_list,\n 0)\n\n def on_draw(self):\n \"\"\" Render the screen. \"\"\"\n\n # Clear the screen to the background color\n arcade.start_render()\n\n # Draw our sprites\n # self.wall_list.draw() # invisible\n # self.answer_sprites.draw() # invisible\n self.bg_list.draw()\n self.sky_scraper_sprites.draw()\n self.player_sprite.draw()\n self.draw_stats()\n w = 200\n h = 60\n arcade.draw_xywh_rectangle_filled(SCREEN_WIDTH // 2 - w // 2 + self.view_left, SCREEN_HEIGHT - h, width=w, height=h, color=arcade.color.BLACK)\n arcade.draw_text(self.equations[0].equationUnsolved(), self.view_left + SCREEN_WIDTH // 2, 600 + self.view_bottom, arcade.csscolor.WHITE, 18, anchor_x=\"center\")\n\n def on_key_press(self, key, modifiers):\n \"\"\"Called whenever a key is pressed. \"\"\"\n\n if key == arcade.key.UP or key == arcade.key.W:\n self.player_sprite.change_y = PLAYER_MOVEMENT_SPEED\n elif key == arcade.key.DOWN or key == arcade.key.S:\n self.player_sprite.change_y = -PLAYER_MOVEMENT_SPEED\n # elif key == arcade.key.LEFT:\n # self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED\n # elif key == arcade.key.RIGHT:\n # self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"Called when the user releases a key. \"\"\"\n\n if key == arcade.key.UP or key == arcade.key.W:\n self.player_sprite.change_y = 0\n elif key == arcade.key.DOWN or key == arcade.key.S:\n self.player_sprite.change_y = 0\n # elif key == arcade.key.LEFT:\n # self.player_sprite.change_x = 0\n # elif key == arcade.key.RIGHT:\n # self.player_sprite.change_x = 0\n\n def on_update(self, delta_time: float):\n\n # --- Manage Animations ---\n self.player_sprite.on_update(delta_time)\n\n def update(self, delta_time):\n if self.is_dead:\n print(\"CANCEELED\")\n return\n \"\"\" Movement and game logic \"\"\"\n # Stop the player from leaving the screen\n if self.player_sprite.center_y > 600:\n self.player_sprite.change_y = 0\n self.player_sprite.center_y = 599\n elif self.player_sprite.center_y < 25:\n self.player_sprite.change_y = 0\n self.player_sprite.center_y = 26\n\n # record the player's last location to get their true speed\n self.player_last_x = self.player_sprite.center_x\n\n # Move the player with the physics engine\n self.physics_engine.update()\n\n # get player's speed and update backgrounds\n player_speed = self.player_sprite.center_x - self.player_last_x\n self.bg_list.update(player_speed, self.player_sprite.center_x)\n\n # --- Manage Scrolling ---\n\n changed = False\n\n # Scroll left\n left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN\n if self.player_sprite.left < left_boundary:\n self.view_left -= left_boundary - self.player_sprite.left\n changed = True\n\n # Scroll right\n right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN\n if self.player_sprite.right > right_boundary:\n self.view_left += self.player_sprite.right - right_boundary\n changed = True\n\n if changed:\n # Only scroll to integers. Otherwise we end up with pixels that\n # don't line up on the screen\n self.view_bottom = int(self.view_bottom)\n self.view_left = int(self.view_left)\n\n # Do the scrolling\n arcade.set_viewport(self.view_left,\n SCREEN_WIDTH + self.view_left,\n self.view_bottom,\n SCREEN_HEIGHT + self.view_bottom)\n \n for wall in self.wall_list:\n if wall.center_x < self.player_sprite.center_x - 500:\n wall.center_x += 1250\n\n # if self.won:\n # arcade.play_sound(self.courage_sound)\n # time.sleep(1)\n # new_view = game_won.GameWon()\n # self.window.show_view(new_view)\n # if wall.center_x < self.player_sprite.center_x - 500:\n # wall.center_x += 2500\n\n # manage threads\n for i in range(len(self.sky_scraper_sprites)):\n ss: SkyScraper = self.sky_scraper_sprites[i]\n if not ss.thread.is_alive() and not ss.loaded:\n ss.load_image()\n current_equation = self.equations[0]\n closest_sprite: Sprite = arcade.get_closest_sprite(self.player_sprite, self.answer_sprites)[0]\n if type(closest_sprite) == Answer and self.player_sprite.left > closest_sprite.left:\n answer: Answer = closest_sprite\n\n # player hit the correct answer\n if answer.get_number() == current_equation.answer:\n self.score += 1\n # Reset the equation and answers\n self.get_new_equation()\n current_equation = self.equations[0]\n else:\n self.kill_bird()\n\n # move answers\n values = current_equation.answers\n for i in range(len(self.answer_sprites)):\n a: Answer = self.answer_sprites[i]\n a.center_x += 1250\n value = values[i]\n a.set_number(value)\n a.is_correct = current_equation.answer == value\n if len(self.sky_scraper_sprites) == 3:\n sprite: SkyScraper = self.sky_scraper_sprites.pop(0)\n center = (sprite.center_x, sprite.center_y)\n print(\"reloading\", [e.answers for e in self.equations])\n new_sprite = SkyScraper(self.equations[1].answers, id=self.wall_counter)\n self.wall_counter += 1\n new_sprite.center_x = center[0]\n new_sprite.center_y = center[1]\n new_sprite.move_forward(how_many=3)\n self.sky_scraper_sprites.append(new_sprite)\n\n # bird death detection\n if player_speed == 0:\n print(\"Bird hit the wall\")\n self.kill_bird()\n\n def kill_bird(self):\n self.is_dead = True\n print(\"Bird died\")\n arcade.play_sound(self.dying_sound_2)\n self.tear_down(self.sky_scraper_sprites)\n self.tear_down(self.answer_sprites)\n self.tear_down(self.wall_list)\n new_view = game_over.GameOver(self, self.score)\n self.window.show_view(new_view)\n\n def tear_down(self, sprite_list: SpriteList):\n for i in range(len(sprite_list)):\n sprite = sprite_list.pop()\n sprite.scale = 0\n\n def draw_stats(self):\n start_x = SCREEN_WIDTH + self.view_left\n start_y = SCREEN_HEIGHT\n font_size = 20\n if self.score > 0:\n number_width = math.floor(math.log10(self.score) + 1) * font_size\n else:\n number_width = 1 * font_size\n arcade.draw_xywh_rectangle_filled(start_x - number_width, start_y - 100, width=100, height=100, color=arcade.color.BLACK)\n arcade.draw_text(str(self.score), start_x, start_y, arcade.color.WHITE, font_size,\n anchor_x=\"right\", anchor_y=\"top\")\n\n def get_new_equation(self):\n self.equations.pop(0)\n self.equations.append(Equation(self.level))\n print(\"get_new_equation\", [e.answers for e in self.equations])\n","sub_path":"my_game_view.py","file_name":"my_game_view.py","file_ext":"py","file_size_in_byte":13010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"492192281","text":"################\n# Danny Schik\n# Lab #1\n# MPG calculator\n################\n\nmiles = int(input(\"How many miles?: \"))\ngallons = float(input(\"How many gallons of gas?: \"))\nprint(\"You drove\", miles, \"miles and used\", format(gallons, '.1f'), \"gallons\")\nmpg = miles / gallons\nprint(\"Your miles per gallon was\", format(mpg, '.1f'))\n","sub_path":"Python/HW/mpg.py","file_name":"mpg.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"556778026","text":"###############################################################################\n# Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC.\n#\n# Produced at the Lawrence Livermore National Laboratory\n#\n# LLNL-CODE-716457\n#\n# All rights reserved.\n#\n# This file is part of Ascent.\n#\n# For details, see: http://ascent.readthedocs.io/.\n#\n# Please also read ascent/LICENSE\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the disclaimer below.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the disclaimer (as noted below) in the\n# documentation and/or other materials provided with the distribution.\n#\n# * Neither the name of the LLNS/LLNL nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,\n# LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n###############################################################################\n\n\nimport conduit\nimport conduit.blueprint\nimport ascent\n\nimport math\nimport numpy as np\n\n# The conduit blueprint library provides several \n# simple builtin examples that cover the range of\n# supported coordinate sets, topologies, field etc\n# \n# Here we create a mesh using the braid example\n# (https://llnl-conduit.readthedocs.io/en/latest/blueprint_mesh.html#braid)\n# and modify one of its fields to create a time-varying\n# example\n\n# Define a function that will calcualte a time varying field\ndef braid_time_varying(npts_x, npts_y, npts_z, interp, res):\n if npts_z < 1:\n npts_z = 1\n\n npts = npts_x * npts_y * npts_z\n \n res[\"association\"] = \"vertex\"\n res[\"topology\"] = \"mesh\"\n vals = res[\"values\"]\n \n dx_seed_start = 0.0\n dx_seed_end = 5.0\n dx_seed = interp * (dx_seed_end - dx_seed_start) + dx_seed_start\n \n dy_seed_start = 0.0\n dy_seed_end = 2.0\n dy_seed = interp * (dy_seed_end - dy_seed_start) + dy_seed_start\n \n dz_seed = 3.0\n\n dx = (float) (dx_seed * math.pi) / float(npts_x - 1)\n dy = (float) (dy_seed * math.pi) / float(npts_y-1)\n dz = (float) (dz_seed * math.pi) / float(npts_z-1)\n \n idx = 0\n for k in range(npts_z):\n cz = (k * dz) - (1.5 * math.pi)\n for j in range(npts_y):\n cy = (j * dy) - (math.pi)\n for i in range(npts_x):\n cx = (i * dx) + (2.0 * math.pi)\n cv = math.sin( cx ) + \\\n math.sin( cy ) + \\\n 2.0 * math.cos(math.sqrt( (cx*cx)/2.0 +cy*cy) / .75) + \\\n 4.0 * math.cos( cx*cy / 4.0)\n \n if npts_z > 1:\n cv += math.sin( cz ) + \\\n 1.5 * math.cos(math.sqrt(cx*cx + cy*cy + cz*cz) / .75)\n vals[idx] = cv\n idx+=1\n\n# create a conduit node with an example mesh using conduit blueprint's braid function\n# ref: https://llnl-conduit.readthedocs.io/en/latest/blueprint_mesh.html#braid\nmesh = conduit.Node()\nconduit.blueprint.mesh.examples.braid(\"hexs\",\n 50,\n 50,\n 50,\n mesh)\n\na = ascent.Ascent()\n# open ascent\na.open()\n\n# create our actions\nactions = conduit.Node()\nadd_act =actions.append()\nadd_act[\"action\"] = \"add_scenes\"\n\n# declare a scene (s1) and plot (p1)\n# to render braid field \nscenes = add_act[\"scenes\"] \nscenes[\"s1/plots/p1/type\"] = \"pseudocolor\"\nscenes[\"s1/plots/p1/field\"] = \"braid\"\n\nprint(actions.to_yaml())\n\n# loop over a set of steps and \n# render a time varying version of the braid field\n\nnsteps = 20\ninterps = np.linspace(0.0, 1.0, num=nsteps)\ni = 0\n\nfor interp in interps:\n print(\"{}: interp = {}\".format(i,interp))\n # update the braid field\n braid_time_varying(50,50,50,interp,mesh[\"fields/braid\"])\n # update the mesh cycle\n mesh[\"state/cycle\"] = i\n # Set the output file name (ascent will add \".png\")\n scenes[\"s1/renders/r1/image_name\"] = \"out_ascent_render_braid_tv_%04d\" % i\n scenes[\"s1/renders/r1/camera/azimuth\"] = 25.0\n \n # publish mesh to ascent\n a.publish(mesh)\n\n # execute the actions\n a.execute(actions)\n \n i+=1\n\n# close ascent\na.close()\n\n","sub_path":"src/examples/tutorial/ascent_intro/python/blueprint_example3.py","file_name":"blueprint_example3.py","file_ext":"py","file_size_in_byte":5298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"32133502","text":"import os, inspect\r\n\r\nproblemName = 'B'\r\n# Options are 'large', 'small', and 'example'.\r\ntestCase = 'large'\r\n# Only relevant for small test case.\r\nattempt = 0\r\n\r\ndef solution(rows):\r\n values = {}\r\n for row in rows:\r\n for value in row:\r\n if value not in values:\r\n values[value] = 0\r\n values[value] += 1\r\n oddValues = [value for value in values if values[value] % 2 == 1]\r\n return map(str, sorted(oddValues))\r\n\r\ncurrentDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\r\nif testCase in ['large', 'example']:\r\n inputString = problemName + ('-%s' % testCase)\r\n outputString = problemName + ('-%s' % testCase)\r\nelse:\r\n inputString = problemName + ('-%s-attempt%d' % (testCase, attempt))\r\n outputString = problemName + ('-%s' % testCase)\r\n\r\ninFile = os.path.join(currentDir, 'inputfiles', '%s.in' % inputString)\r\noutFile = os.path.join(currentDir, 'outputfiles', '%s.out' % outputString)\r\n\r\nif os.path.exists(outFile):\r\n os.remove(outFile)\r\n\r\nwith open(inFile, 'r') as inputfile:\r\n numberOfCases = int(inputfile.readline())\r\n for case in xrange(1, numberOfCases + 1):\r\n N = int(inputfile.readline())\r\n rows = [map(int, inputfile.readline().split(' ')) for _ in xrange(2*N-1)]\r\n\r\n # Get the result here\r\n result = solution(rows)\r\n\r\n with open(outFile, 'a') as f:\r\n f.write('Case #%d: %s\\n' % (case, ' '.join(result)))\r\n","sub_path":"solutions_5630113748090880_1/Python/mrauen/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"201363366","text":"import glob\r\nimport sys\r\nimport os\r\nimport tensorflow as tf\r\nimport h5py as hf\r\nimport numpy as np\r\n\r\nsys.path.append(\"./kinetics-i3d\")\r\nimport i3d2\r\nimport video_rnn\r\nimport text_rnn_cudnn\r\n\r\nTOWER_NAME = 'tower'\r\n\r\n\r\n# def build_graph(FLAGS, rgb_input, flow_input, sub, q, ac, a, rgb_seq_len, flow_seq_len,sub_seq_len, q_seq_len):\r\ndef build_graph(FLAGS, vocab_embedding, flow_input, sub, q, a0, a1, a2, a3, a4, a, qid, flow_seq_len, sub_seq_len,\r\n q_seq_len, a0_seq_len, a1_seq_len, a2_seq_len, a3_seq_len, a4_seq_len, prob, text_prob, is_training):\r\n # with tf.device(\"/GPU:0\"):\r\n regularizer = tf.contrib.layers.l2_regularizer(scale=FLAGS.wd)\r\n vocab_embedding_tensor = tf.convert_to_tensor(vocab_embedding, dtype=tf.float32)\r\n sub_tensor = tf.nn.embedding_lookup(vocab_embedding_tensor, sub)\r\n q_tensor = tf.nn.embedding_lookup(vocab_embedding_tensor, q)\r\n a0_tensor = tf.nn.embedding_lookup(vocab_embedding_tensor, a0)\r\n a1_tensor = tf.nn.embedding_lookup(vocab_embedding_tensor, a1)\r\n a2_tensor = tf.nn.embedding_lookup(vocab_embedding_tensor, a2)\r\n a3_tensor = tf.nn.embedding_lookup(vocab_embedding_tensor, a3)\r\n a4_tensor = tf.nn.embedding_lookup(vocab_embedding_tensor, a4)\r\n sub_tensor = tf.cast(sub_tensor, tf.float32)\r\n q_tensor = tf.cast(q_tensor, tf.float32)\r\n a0_tensor = tf.cast(a0_tensor, tf.float32)\r\n a1_tensor = tf.cast(a1_tensor, tf.float32)\r\n a2_tensor = tf.cast(a2_tensor, tf.float32)\r\n a3_tensor = tf.cast(a3_tensor, tf.float32)\r\n a4_tensor = tf.cast(a4_tensor, tf.float32)\r\n '''\r\n with tf.variable_scope(\"RGB\"):\r\n rgb_model = i3d.InceptionI3d(FLAGS.num_classes, spatial_squeeze=True, final_endpoint='Logits')\r\n rgb_logits, _ = rgb_model(rgb_input, is_training=is_training[0][0], dropout_keep_prob=prob[0][0])\r\n # rgb_logits = tf.layers.dense(rgb_logits, 300, activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n # name=\"rgb_fc\")\r\n # rgb_logits = tf.nn.dropout(rgb_logits, prob[0][0])\r\n rgb_logits = tf.expand_dims(rgb_logits, 1)\r\n '''\r\n # with tf.device(\"/GPU:1\"):\r\n with tf.variable_scope(\"Flow\"):\r\n flow_model = i3d2.InceptionI3d(FLAGS.num_classes, spatial_squeeze=True, final_endpoint='Logits')\r\n flow_logits, _ = flow_model(flow_input, is_training=is_training[0][0], dropout_keep_prob=prob[0][0])\r\n # flow_logits = tf.layers.dense(flow_logits, 300, activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n # name=\"flow_fc\")\r\n # flow_logits = tf.nn.dropout(flow_logits, prob[0][0])\r\n # flow_logits = tf.expand_dims(flow_logits, 1)\r\n\r\n # with tf.device(\"/GPU:2\"):\r\n # with tf.variable_scope(\"Video_RNN\"):\r\n # rgb_rnn_model = video_rnn.vRNN(\"GRU\", FLAGS.num_hidden, 'rgb', FLAGS)\r\n # flow_rnn_model = video_rnn.vRNN(\"GRU\", FLAGS.num_hidden, 'flow', FLAGS)\r\n # rgb_rnn_logits = rgb_rnn_model.build(rgb_logits, is_training=FLAGS.is_training, seq_len=rgb_seq_len)\r\n # flow_rnn_logits = flow_rnn_model.build(flow_logits, is_training=FLAGS.is_training, seq_len=flow_seq_len)\r\n # rgb_rnn_logits = tf.layers.batch_normalization(rgb_rnn_logits)\r\n # flow_rnn_logits = tf.layers.batch_normalization(flow_rnn_logits)\r\n # rgb_rnn_logits = tf.reduce_mean(rgb_rnn_logits, axis=1, keepdims=True)\r\n # flow_rnn_logits = tf.reduce_mean(flow_rnn_logits, axis=1, keepdims=True)\r\n # rgb_rnn_logits = tf.nn.l2_normalize(rgb_rnn_logits, axis=2)\r\n # flow_rnn_logits = tf.nn.l2_normalize(flow_rnn_logits, axis=2)\r\n with tf.variable_scope(\"Text_LSTM\", reuse=tf.AUTO_REUSE):\r\n '''\r\n def apply_softmax(elem):\r\n pass\r\n\r\n def apply_attention(elem):\r\n previous = 0\r\n attention_sum_logit = tf.zeros(tf.shape(elem[0]))\r\n\r\n attention_sum_logit = tf.map_fn(lambda x: attention_sum_logit + tf.multiply())\r\n for i in elem[1]:\r\n attention_logit = elem[0][previous:i]\r\n attention_logit = tf.multiply(attention_logit, elem[2])\r\n attention_logit = tf.nn.softmax(attention_logit)\r\n attention_logit = tf.reduce_sum(attention_logit, axis=0, keepdims=True)\r\n if not attention_sum_logit:\r\n attention_sum_logit = attention_logit\r\n else:\r\n attention_sum_logit = tf.stack([attention_sum_logit, attention_logit], axis=0)\r\n\r\n return attention_sum_logit\r\n '''\r\n text_rnn_model = text_rnn_cudnn.tRNN(\"LSTM\", FLAGS.num_hidden, 'question')\r\n # question_rnn_model = text_rnn_cudnn.tRNN(\"LSTM\", FLAGS.num_hidden, 'question')\r\n # answer_rnn_model = text_rnn_cudnn.tRNN(\"LSTM\", FLAGS.num_hidden, 'answer')\r\n # answer_rnn_model = text_rnn_cudnn.tRNN_answer(\"GRU\", 200, 'answer')\r\n # subtitle_rnn_model = text_rnn_cudnn.tRNN(\"LSTM\", FLAGS.num_hidden, 'subtitle')\r\n question_rnn_logits = text_rnn_model.build(q_tensor, dropout_keep_prob=text_prob, seq_len=q_seq_len)\r\n subtitle_rnn_logits = text_rnn_model.build(sub_tensor, dropout_keep_prob=text_prob, seq_len=sub_seq_len)\r\n answer0_rnn_logits = text_rnn_model.build(a0_tensor, dropout_keep_prob=text_prob, seq_len=a0_seq_len)\r\n answer1_rnn_logits = text_rnn_model.build(a1_tensor, dropout_keep_prob=text_prob, seq_len=a1_seq_len)\r\n answer2_rnn_logits = text_rnn_model.build(a2_tensor, dropout_keep_prob=text_prob, seq_len=a2_seq_len)\r\n answer3_rnn_logits = text_rnn_model.build(a3_tensor, dropout_keep_prob=text_prob, seq_len=a3_seq_len)\r\n answer4_rnn_logits = text_rnn_model.build(a4_tensor, dropout_keep_prob=text_prob, seq_len=a4_seq_len)\r\n\r\n with tf.variable_scope(\"Text_BiDAF_subtitle_question\", reuse=tf.AUTO_REUSE):\r\n # subtitle_attention_ex = tf.expand_dims(subtitle_rnn_logits, 2)\r\n # subtitle_attention = tf.broadcast_to(subtitle_attention_ex, [tf.shape(subtitle_rnn_logits)[0],\r\n # tf.shape(subtitle_rnn_logits)[1],\r\n # tf.shape(question_rnn_logits)[1],\r\n # FLAGS.num_hidden * 2])\r\n # question_attention = tf.expand_dims(question_rnn_logits, 1)\r\n # question_attention = tf.broadcast_to(question_attention, [tf.shape(question_rnn_logits)[0],\r\n # tf.shape(subtitle_rnn_logits)[1],\r\n # tf.shape(question_rnn_logits)[1],\r\n # FLAGS.num_hidden * 2])\r\n # subtitle_question_mul = tf.multiply(subtitle_attention, question_attention)\r\n # subtitle_question_concat = tf.concat([subtitle_attention, question_attention, subtitle_question_mul],\r\n # axis=3)\r\n # subtitle_question_similarity = tf.layers.dense(subtitle_question_concat, 1, use_bias=False,\r\n # name='subtitle_question_similarity',\r\n # kernel_regularizer=regularizer)\r\n # subtitle_question_similarity = tf.squeeze(subtitle_question_similarity, axis=[3])\r\n subtitle_question_similarity = tf.matmul(subtitle_rnn_logits, tf.transpose(question_rnn_logits, perm=[0, 2, 1]))\r\n subtitle_question_c2q = tf.nn.softmax(subtitle_question_similarity)\r\n subtitle_question_c2q = tf.matmul(subtitle_question_c2q, question_rnn_logits)\r\n # subtitle_question_b = tf.nn.softmax(tf.reduce_max(subtitle_question_similarity, axis=2))\r\n # subtitle_question_b = tf.expand_dims(subtitle_question_b, 1)\r\n # subtitle_question_q2c = tf.matmul(subtitle_question_b, subtitle_rnn_logits)\r\n # subtitle_question_g = tf.concat([subtitle_rnn_logits, subtitle_question_c2q,\r\n # tf.multiply(subtitle_rnn_logits, subtitle_question_c2q),\r\n # tf.multiply(subtitle_rnn_logits, subtitle_question_q2c)], axis=2)\r\n\r\n with tf.variable_scope(\"Text_BiDAF_subtitle_answer\", reuse=tf.AUTO_REUSE):\r\n '''\r\n answer0_attention = tf.expand_dims(answer0_rnn_logits, 1)\r\n answer1_attention = tf.expand_dims(answer1_rnn_logits, 1)\r\n answer2_attention = tf.expand_dims(answer2_rnn_logits, 1)\r\n answer3_attention = tf.expand_dims(answer3_rnn_logits, 1)\r\n answer4_attention = tf.expand_dims(answer4_rnn_logits, 1)\r\n answer0_attention = tf.broadcast_to(answer0_attention, [tf.shape(answer0_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer0_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n answer1_attention = tf.broadcast_to(answer1_attention, [tf.shape(answer1_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer1_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n answer2_attention = tf.broadcast_to(answer2_attention, [tf.shape(answer2_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer2_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n answer3_attention = tf.broadcast_to(answer3_attention, [tf.shape(answer3_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer3_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n answer4_attention = tf.broadcast_to(answer4_attention, [tf.shape(answer4_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer4_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n subtitle_attention0 = tf.broadcast_to(subtitle_attention_ex, [tf.shape(subtitle_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer0_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n subtitle_attention1 = tf.broadcast_to(subtitle_attention_ex, [tf.shape(subtitle_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer1_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n subtitle_attention2 = tf.broadcast_to(subtitle_attention_ex, [tf.shape(subtitle_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer2_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n subtitle_attention3 = tf.broadcast_to(subtitle_attention_ex, [tf.shape(subtitle_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer3_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n subtitle_attention4 = tf.broadcast_to(subtitle_attention_ex, [tf.shape(subtitle_rnn_logits)[0],\r\n tf.shape(subtitle_rnn_logits)[1],\r\n tf.shape(answer4_rnn_logits)[1],\r\n FLAGS.num_hidden * 2])\r\n subtitle_answer0_mul = tf.multiply(subtitle_attention0, answer0_attention)\r\n subtitle_answer1_mul = tf.multiply(subtitle_attention1, answer1_attention)\r\n subtitle_answer2_mul = tf.multiply(subtitle_attention2, answer2_attention)\r\n subtitle_answer3_mul = tf.multiply(subtitle_attention3, answer3_attention)\r\n subtitle_answer4_mul = tf.multiply(subtitle_attention4, answer4_attention)\r\n subtitle_answer0_concat = tf.concat([subtitle_attention0, answer0_attention, subtitle_answer0_mul], axis=3)\r\n subtitle_answer1_concat = tf.concat([subtitle_attention1, answer1_attention, subtitle_answer1_mul], axis=3)\r\n subtitle_answer2_concat = tf.concat([subtitle_attention2, answer2_attention, subtitle_answer2_mul], axis=3)\r\n subtitle_answer3_concat = tf.concat([subtitle_attention3, answer3_attention, subtitle_answer3_mul], axis=3)\r\n subtitle_answer4_concat = tf.concat([subtitle_attention4, answer4_attention, subtitle_answer4_mul], axis=3)\r\n subtitle_answer0_similarity = tf.layers.dense(subtitle_answer0_concat, 1, use_bias=False,\r\n name='subtitle_answer_similarity',\r\n kernel_regularizer=regularizer)\r\n subtitle_answer0_similarity = tf.squeeze(subtitle_answer0_similarity, axis=[3])\r\n subtitle_answer1_similarity = tf.layers.dense(subtitle_answer1_concat, 1, use_bias=False,\r\n name='subtitle_answer_similarity', reuse=True,\r\n kernel_regularizer=regularizer)\r\n subtitle_answer1_similarity = tf.squeeze(subtitle_answer1_similarity, axis=[3])\r\n subtitle_answer2_similarity = tf.layers.dense(subtitle_answer2_concat, 1, use_bias=False,\r\n name='subtitle_answer_similarity', reuse=True,\r\n kernel_regularizer=regularizer)\r\n subtitle_answer2_similarity = tf.squeeze(subtitle_answer2_similarity, axis=[3])\r\n subtitle_answer3_similarity = tf.layers.dense(subtitle_answer3_concat, 1, use_bias=False,\r\n name='subtitle_answer_similarity', reuse=True,\r\n kernel_regularizer=regularizer)\r\n subtitle_answer3_similarity = tf.squeeze(subtitle_answer3_similarity, axis=[3])\r\n subtitle_answer4_similarity = tf.layers.dense(subtitle_answer4_concat, 1, use_bias=False,\r\n name='subtitle_answer_similarity', reuse=True,\r\n kernel_regularizer=regularizer)\r\n subtitle_answer4_similarity = tf.squeeze(subtitle_answer4_similarity, axis=[3])\r\n '''\r\n subtitle_answer0_similarity = tf.matmul(subtitle_rnn_logits, tf.transpose(answer0_rnn_logits, perm=[0, 2, 1]))\r\n subtitle_answer1_similarity = tf.matmul(subtitle_rnn_logits, tf.transpose(answer1_rnn_logits, perm=[0, 2, 1]))\r\n subtitle_answer2_similarity = tf.matmul(subtitle_rnn_logits, tf.transpose(answer2_rnn_logits, perm=[0, 2, 1]))\r\n subtitle_answer3_similarity = tf.matmul(subtitle_rnn_logits, tf.transpose(answer3_rnn_logits, perm=[0, 2, 1]))\r\n subtitle_answer4_similarity = tf.matmul(subtitle_rnn_logits, tf.transpose(answer4_rnn_logits, perm=[0, 2, 1]))\r\n subtitle_answer0_c2q = tf.nn.softmax(subtitle_answer0_similarity)\r\n subtitle_answer0_c2q = tf.matmul(subtitle_answer0_c2q, answer0_rnn_logits)\r\n subtitle_answer1_c2q = tf.nn.softmax(subtitle_answer1_similarity)\r\n subtitle_answer1_c2q = tf.matmul(subtitle_answer1_c2q, answer1_rnn_logits)\r\n subtitle_answer2_c2q = tf.nn.softmax(subtitle_answer2_similarity)\r\n subtitle_answer2_c2q = tf.matmul(subtitle_answer2_c2q, answer2_rnn_logits)\r\n subtitle_answer3_c2q = tf.nn.softmax(subtitle_answer3_similarity)\r\n subtitle_answer3_c2q = tf.matmul(subtitle_answer3_c2q, answer3_rnn_logits)\r\n subtitle_answer4_c2q = tf.nn.softmax(subtitle_answer4_similarity)\r\n subtitle_answer4_c2q = tf.matmul(subtitle_answer4_c2q, answer4_rnn_logits)\r\n # subtitle_answer0_b = tf.nn.softmax(tf.reduce_max(subtitle_answer0_similarity, axis=2))\r\n # subtitle_answer0_b = tf.expand_dims(subtitle_answer0_b, 1)\r\n # subtitle_answer1_b = tf.nn.softmax(tf.reduce_max(subtitle_answer1_similarity, axis=2))\r\n # subtitle_answer1_b = tf.expand_dims(subtitle_answer1_b, 1)\r\n # subtitle_answer2_b = tf.nn.softmax(tf.reduce_max(subtitle_answer2_similarity, axis=2))\r\n # subtitle_answer2_b = tf.expand_dims(subtitle_answer2_b, 1)\r\n # subtitle_answer3_b = tf.nn.softmax(tf.reduce_max(subtitle_answer3_similarity, axis=2))\r\n # subtitle_answer3_b = tf.expand_dims(subtitle_answer3_b, 1)\r\n # subtitle_answer4_b = tf.nn.softmax(tf.reduce_max(subtitle_answer4_similarity, axis=2))\r\n # subtitle_answer4_b = tf.expand_dims(subtitle_answer4_b, 1)\r\n # subtitle_answer0_q2c = tf.matmul(subtitle_answer0_b, subtitle_rnn_logits)\r\n # subtitle_answer1_q2c = tf.matmul(subtitle_answer1_b, subtitle_rnn_logits)\r\n # subtitle_answer2_q2c = tf.matmul(subtitle_answer2_b, subtitle_rnn_logits)\r\n # subtitle_answer3_q2c = tf.matmul(subtitle_answer3_b, subtitle_rnn_logits)\r\n # subtitle_answer4_q2c = tf.matmul(subtitle_answer4_b, subtitle_rnn_logits)\r\n concat_subtitle_query0 = tf.concat([subtitle_rnn_logits, subtitle_question_c2q, subtitle_answer0_c2q,\r\n tf.multiply(subtitle_rnn_logits, subtitle_question_c2q),\r\n tf.multiply(subtitle_rnn_logits, subtitle_answer0_c2q)], axis=2)\r\n concat_subtitle_query1 = tf.concat([subtitle_rnn_logits, subtitle_question_c2q, subtitle_answer1_c2q,\r\n tf.multiply(subtitle_rnn_logits, subtitle_question_c2q),\r\n tf.multiply(subtitle_rnn_logits, subtitle_answer1_c2q)], axis=2)\r\n concat_subtitle_query2 = tf.concat([subtitle_rnn_logits, subtitle_question_c2q, subtitle_answer2_c2q,\r\n tf.multiply(subtitle_rnn_logits, subtitle_question_c2q),\r\n tf.multiply(subtitle_rnn_logits, subtitle_answer2_c2q)], axis=2)\r\n concat_subtitle_query3 = tf.concat([subtitle_rnn_logits, subtitle_question_c2q, subtitle_answer3_c2q,\r\n tf.multiply(subtitle_rnn_logits, subtitle_question_c2q),\r\n tf.multiply(subtitle_rnn_logits, subtitle_answer3_c2q)], axis=2)\r\n concat_subtitle_query4 = tf.concat([subtitle_rnn_logits, subtitle_question_c2q, subtitle_answer4_c2q,\r\n tf.multiply(subtitle_rnn_logits, subtitle_question_c2q),\r\n tf.multiply(subtitle_rnn_logits, subtitle_answer4_c2q)], axis=2)\r\n\r\n # subtitle_answer0_g = tf.concat([subtitle_rnn_logits, subtitle_answer0_c2q,\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer0_c2q),\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer0_q2c)], axis=2)\r\n # subtitle_answer1_g = tf.concat([subtitle_rnn_logits, subtitle_answer1_c2q,\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer1_c2q),\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer1_q2c)], axis=2)\r\n # subtitle_answer2_g = tf.concat([subtitle_rnn_logits, subtitle_answer2_c2q,\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer2_c2q),\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer2_q2c)], axis=2)\r\n # subtitle_answer3_g = tf.concat([subtitle_rnn_logits, subtitle_answer3_c2q,\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer3_c2q),\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer3_q2c)], axis=2)\r\n # subtitle_answer4_g = tf.concat([subtitle_rnn_logits, subtitle_answer4_c2q,\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer4_c2q),\r\n # tf.multiply(subtitle_rnn_logits, subtitle_answer4_q2c)], axis=2)\r\n # with tf.device(\"/GPU:1\"):\r\n '''\r\n with tf.variable_scope(\"RGB_question_match\", reuse=tf.AUTO_REUSE):\r\n question_d = tf.reduce_max(question_rnn_logits, axis=1, keepdims=True)\r\n # question_rgb = tf.layers.dense(question_d, 300, name=\"RGB_question_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu)\r\n # question_rgb = tf.nn.dropout(question_rgb, prob[0][0])\r\n rgb_question_mul = tf.matmul(tf.transpose(question_d, perm=[0, 2, 1]), rgb_logits)\r\n rgb_question_similarity = tf.nn.softmax(rgb_question_mul)\r\n rgb_question_masked = tf.matmul(rgb_question_similarity, tf.transpose(rgb_logits, perm=[0, 2, 1]))\r\n\r\n with tf.variable_scope(\"RGB_answer_match\", reuse=tf.AUTO_REUSE):\r\n answer0_d = tf.reduce_max(answer0_rnn_logits, axis=1, keepdims=True)\r\n answer1_d = tf.reduce_max(answer1_rnn_logits, axis=1, keepdims=True)\r\n answer2_d = tf.reduce_max(answer2_rnn_logits, axis=1, keepdims=True)\r\n answer3_d = tf.reduce_max(answer3_rnn_logits, axis=1, keepdims=True)\r\n answer4_d = tf.reduce_max(answer4_rnn_logits, axis=1, keepdims=True)\r\n # answer0_rgb = tf.layers.dense(answer0_d, 300, name=\"RGB_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu)\r\n # answer1_rgb = tf.layers.dense(answer1_d, 300, name=\"RGB_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu, reuse=True)\r\n # answer2_rgb = tf.layers.dense(answer2_d, 300, name=\"RGB_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu, reuse=True)\r\n # answer3_rgb = tf.layers.dense(answer3_d, 300, name=\"RGB_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu, reuse=True)\r\n # answer4_rgb = tf.layers.dense(answer4_d, 300, name=\"RGB_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu, reuse=True)\r\n\r\n # answer0_rgb = tf.nn.dropout(answer0_rgb, prob[0][0])\r\n # answer1_rgb = tf.nn.dropout(answer1_rgb, prob[0][0])\r\n # answer2_rgb = tf.nn.dropout(answer2_rgb, prob[0][0])\r\n # answer3_rgb = tf.nn.dropout(answer3_rgb, prob[0][0])\r\n # answer4_rgb = tf.nn.dropout(answer4_rgb, prob[0][0])\r\n\r\n rgb_answer0_mul = tf.matmul(tf.transpose(answer0_d, perm=[0, 2, 1]), rgb_logits)\r\n rgb_answer1_mul = tf.matmul(tf.transpose(answer1_d, perm=[0, 2, 1]), rgb_logits)\r\n rgb_answer2_mul = tf.matmul(tf.transpose(answer2_d, perm=[0, 2, 1]), rgb_logits)\r\n rgb_answer3_mul = tf.matmul(tf.transpose(answer3_d, perm=[0, 2, 1]), rgb_logits)\r\n rgb_answer4_mul = tf.matmul(tf.transpose(answer4_d, perm=[0, 2, 1]), rgb_logits)\r\n\r\n rgb_answer0_similarity = tf.nn.softmax(rgb_answer0_mul)\r\n rgb_answer1_similarity = tf.nn.softmax(rgb_answer1_mul)\r\n rgb_answer2_similarity = tf.nn.softmax(rgb_answer2_mul)\r\n rgb_answer3_similarity = tf.nn.softmax(rgb_answer3_mul)\r\n rgb_answer4_similarity = tf.nn.softmax(rgb_answer4_mul)\r\n\r\n rgb_answer0_masked = tf.matmul(rgb_answer0_similarity, tf.transpose(rgb_logits, perm=[0, 2, 1]))\r\n rgb_answer1_masked = tf.matmul(rgb_answer1_similarity, tf.transpose(rgb_logits, perm=[0, 2, 1]))\r\n rgb_answer2_masked = tf.matmul(rgb_answer2_similarity, tf.transpose(rgb_logits, perm=[0, 2, 1]))\r\n rgb_answer3_masked = tf.matmul(rgb_answer3_similarity, tf.transpose(rgb_logits, perm=[0, 2, 1]))\r\n rgb_answer4_masked = tf.matmul(rgb_answer4_similarity, tf.transpose(rgb_logits, perm=[0, 2, 1]))\r\n\r\n with tf.variable_scope(\"RGB_question_answer_att_layer\", reuse=tf.AUTO_REUSE):\r\n rgb_question_answer0_att = tf.matmul(rgb_question_masked, tf.transpose(rgb_answer0_masked, perm=[0, 2, 1]))\r\n rgb_question_answer1_att = tf.matmul(rgb_question_masked, tf.transpose(rgb_answer1_masked, perm=[0, 2, 1]))\r\n rgb_question_answer2_att = tf.matmul(rgb_question_masked, tf.transpose(rgb_answer2_masked, perm=[0, 2, 1]))\r\n rgb_question_answer3_att = tf.matmul(rgb_question_masked, tf.transpose(rgb_answer3_masked, perm=[0, 2, 1]))\r\n rgb_question_answer4_att = tf.matmul(rgb_question_masked, tf.transpose(rgb_answer4_masked, perm=[0, 2, 1]))\r\n\r\n\r\n rgb_question_answer0_cnn = tf.layers.conv1d(rgb_question_answer0_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n kernel_initializer=tf.initializers.random_normal, name=\"rgb_conv\")\r\n rgb_question_answer1_cnn = tf.layers.conv1d(rgb_question_answer1_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n name=\"rgb_conv\", reuse=True)\r\n rgb_question_answer2_cnn = tf.layers.conv1d(rgb_question_answer2_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n name=\"rgb_conv\", reuse=True)\r\n rgb_question_answer3_cnn = tf.layers.conv1d(rgb_question_answer3_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n name=\"rgb_conv\", reuse=True)\r\n rgb_question_answer4_cnn = tf.layers.conv1d(rgb_question_answer4_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n name=\"rgb_conv\", reuse=True)\r\n\r\n rgb_question_answer0_cnn = tf.nn.dropout(rgb_question_answer0_cnn, prob[0][0])\r\n rgb_question_answer1_cnn = tf.nn.dropout(rgb_question_answer1_cnn, prob[0][0])\r\n rgb_question_answer2_cnn = tf.nn.dropout(rgb_question_answer2_cnn, prob[0][0])\r\n rgb_question_answer3_cnn = tf.nn.dropout(rgb_question_answer3_cnn, prob[0][0])\r\n rgb_question_answer4_cnn = tf.nn.dropout(rgb_question_answer4_cnn, prob[0][0])\r\n\r\n rgb_question_answer0_cnn = tf.squeeze(rgb_question_answer0_cnn, 2)\r\n rgb_question_answer1_cnn = tf.squeeze(rgb_question_answer1_cnn, 2)\r\n rgb_question_answer2_cnn = tf.squeeze(rgb_question_answer2_cnn, 2)\r\n rgb_question_answer3_cnn = tf.squeeze(rgb_question_answer3_cnn, 2)\r\n rgb_question_answer4_cnn = tf.squeeze(rgb_question_answer4_cnn, 2)\r\n\r\n\r\n rgb_question_answer0_fc = tf.layers.dense(rgb_question_answer0_att, 1, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name='rgb_mask_fc')\r\n rgb_question_answer1_fc = tf.layers.dense(rgb_question_answer1_att, 1, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name='rgb_mask_fc', reuse=True)\r\n rgb_question_answer2_fc = tf.layers.dense(rgb_question_answer2_att, 1, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name='rgb_mask_fc', reuse=True)\r\n rgb_question_answer3_fc = tf.layers.dense(rgb_question_answer3_att, 1, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name='rgb_mask_fc', reuse=True)\r\n rgb_question_answer4_fc = tf.layers.dense(rgb_question_answer4_att, 1, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name='rgb_mask_fc', reuse=True)\r\n\r\n rgb_question_answer0_fc = tf.nn.dropout(rgb_question_answer0_fc, prob[0][0])\r\n rgb_question_answer1_fc = tf.nn.dropout(rgb_question_answer1_fc, prob[0][0])\r\n rgb_question_answer2_fc = tf.nn.dropout(rgb_question_answer2_fc, prob[0][0])\r\n rgb_question_answer3_fc = tf.nn.dropout(rgb_question_answer3_fc, prob[0][0])\r\n rgb_question_answer4_fc = tf.nn.dropout(rgb_question_answer4_fc, prob[0][0])\r\n\r\n rgb_question_answer0_fc = tf.squeeze(rgb_question_answer0_fc, 2)\r\n rgb_question_answer1_fc = tf.squeeze(rgb_question_answer1_fc, 2)\r\n rgb_question_answer2_fc = tf.squeeze(rgb_question_answer2_fc, 2)\r\n rgb_question_answer3_fc = tf.squeeze(rgb_question_answer3_fc, 2)\r\n rgb_question_answer4_fc = tf.squeeze(rgb_question_answer4_fc, 2)\r\n '''\r\n with tf.variable_scope(\"Flow_train_question_match\", reuse=tf.AUTO_REUSE):\r\n flow_logits = tf.layers.dense(flow_logits, 400, name=\"Flow_text_fc\", kernel_regularizer=regularizer,\r\n activation=tf.nn.leaky_relu)\r\n flow_logits = tf.nn.dropout(flow_logits, prob[0][0])\r\n flow_logits = tf.layers.batch_normalization(flow_logits, training=is_training[0][0])\r\n\r\n question_flow = tf.layers.dense(question_rnn_logits, 400, name=\"Flow_question_dense\", kernel_regularizer=regularizer,\r\n activation=tf.nn.leaky_relu)\r\n # question_d = tf.reduce_max(question_rnn_logits, axis=1, keepdims=True)\r\n # question_flow = tf.layers.dense(question_d, 300, name=\"flow_question_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu)\r\n question_flow = tf.nn.dropout(question_flow, prob[0][0])\r\n question_flow = tf.layers.batch_normalization(question_flow, training=is_training[0][0])\r\n flow_question_mul = tf.matmul(flow_logits, tf.transpose(question_flow, perm=[0, 2, 1]))\r\n flow_question_similarity = tf.nn.softmax(flow_question_mul)\r\n flow_question_masked = tf.matmul(flow_question_similarity, question_flow)\r\n # flow_question_masked = tf.matmul(flow_question_similarity, tf.transpose(flow_logits, perm=[0, 2, 1]))\r\n # flow_question_masked = tf.squeeze(flow_question_masked, axis=2)\r\n\r\n with tf.variable_scope(\"Flow_train_answer_match\", reuse=tf.AUTO_REUSE):\r\n # answer0_d = tf.reduce_max(answer0_rnn_logits, axis=1, keepdims=True)\r\n # answer1_d = tf.reduce_max(answer1_rnn_logits, axis=1, keepdims=True)\r\n # answer2_d = tf.reduce_max(answer2_rnn_logits, axis=1, keepdims=True)\r\n # answer3_d = tf.reduce_max(answer3_rnn_logits, axis=1, keepdims=True)\r\n # answer4_d = tf.reduce_max(answer4_rnn_logits, axis=1, keepdims=True)\r\n # answer0_flow = tf.layers.dense(answer0_d, 300, name=\"flow_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu)\r\n # answer1_flow = tf.layers.dense(answer1_d, 300, name=\"flow_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu)\r\n # answer2_flow = tf.layers.dense(answer2_d, 300, name=\"flow_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu)\r\n # answer3_flow = tf.layers.dense(answer3_d, 300, name=\"flow_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu)\r\n # answer4_flow = tf.layers.dense(answer4_d, 300, name=\"flow_answer_dense\", kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu)\r\n\r\n answer0_flow = tf.layers.dense(answer0_rnn_logits, 400, name=\"Flow_answer_dense\", kernel_regularizer=regularizer,\r\n activation=tf.nn.leaky_relu)\r\n answer1_flow = tf.layers.dense(answer1_rnn_logits, 400, name=\"Flow_answer_dense\", kernel_regularizer=regularizer,\r\n activation=tf.nn.leaky_relu, reuse=True)\r\n answer2_flow = tf.layers.dense(answer2_rnn_logits, 400, name=\"Flow_answer_dense\", kernel_regularizer=regularizer,\r\n activation=tf.nn.leaky_relu, reuse=True)\r\n answer3_flow = tf.layers.dense(answer3_rnn_logits, 400, name=\"Flow_answer_dense\", kernel_regularizer=regularizer,\r\n activation=tf.nn.leaky_relu, reuse=True)\r\n answer4_flow = tf.layers.dense(answer4_rnn_logits, 400, name=\"Flow_answer_dense\", kernel_regularizer=regularizer,\r\n activation=tf.nn.leaky_relu, reuse=True)\r\n\r\n answer0_flow = tf.nn.dropout(answer0_flow, prob[0][0])\r\n answer1_flow = tf.nn.dropout(answer1_flow, prob[0][0])\r\n answer2_flow = tf.nn.dropout(answer2_flow, prob[0][0])\r\n answer3_flow = tf.nn.dropout(answer3_flow, prob[0][0])\r\n answer4_flow = tf.nn.dropout(answer4_flow, prob[0][0])\r\n\r\n answer0_flow = tf.layers.batch_normalization(answer0_flow, training=is_training[0][0])\r\n answer1_flow = tf.layers.batch_normalization(answer1_flow, training=is_training[0][0])\r\n answer2_flow = tf.layers.batch_normalization(answer2_flow, training=is_training[0][0])\r\n answer3_flow = tf.layers.batch_normalization(answer3_flow, training=is_training[0][0])\r\n answer4_flow = tf.layers.batch_normalization(answer4_flow, training=is_training[0][0])\r\n\r\n flow_answer0_mul = tf.matmul(flow_logits, tf.transpose(answer0_flow, perm=[0, 2, 1]))\r\n flow_answer1_mul = tf.matmul(flow_logits, tf.transpose(answer1_flow, perm=[0, 2, 1]))\r\n flow_answer2_mul = tf.matmul(flow_logits, tf.transpose(answer2_flow, perm=[0, 2, 1]))\r\n flow_answer3_mul = tf.matmul(flow_logits, tf.transpose(answer3_flow, perm=[0, 2, 1]))\r\n flow_answer4_mul = tf.matmul(flow_logits, tf.transpose(answer4_flow, perm=[0, 2, 1]))\r\n # flow_answer0_mul = tf.matmul(tf.transpose(answer0_d, [0, 2, 1]), flow_logits)\r\n # flow_answer1_mul = tf.matmul(tf.transpose(answer1_d, [0, 2, 1]), flow_logits)\r\n # flow_answer2_mul = tf.matmul(tf.transpose(answer2_d, [0, 2, 1]), flow_logits)\r\n # flow_answer3_mul = tf.matmul(tf.transpose(answer3_d, [0, 2, 1]), flow_logits)\r\n # flow_answer4_mul = tf.matmul(tf.transpose(answer4_d, [0, 2, 1]), flow_logits)\r\n\r\n flow_answer0_similarity = tf.nn.softmax(flow_answer0_mul)\r\n flow_answer1_similarity = tf.nn.softmax(flow_answer1_mul)\r\n flow_answer2_similarity = tf.nn.softmax(flow_answer2_mul)\r\n flow_answer3_similarity = tf.nn.softmax(flow_answer3_mul)\r\n flow_answer4_similarity = tf.nn.softmax(flow_answer4_mul)\r\n\r\n flow_answer0_masked = tf.matmul(flow_answer0_similarity, answer0_flow)\r\n flow_answer1_masked = tf.matmul(flow_answer1_similarity, answer1_flow)\r\n flow_answer2_masked = tf.matmul(flow_answer2_similarity, answer2_flow)\r\n flow_answer3_masked = tf.matmul(flow_answer3_similarity, answer3_flow)\r\n flow_answer4_masked = tf.matmul(flow_answer4_similarity, answer4_flow)\r\n\r\n # flow_answer0_mask = tf.matmul(flow_answer0_similarity, tf.transpose(flow_logits, perm=[0, 2, 1]))\r\n # flow_answer1_mask = tf.matmul(flow_answer1_similarity, tf.transpose(flow_logits, perm=[0, 2, 1]))\r\n # flow_answer2_mask = tf.matmul(flow_answer2_similarity, tf.transpose(flow_logits, perm=[0, 2, 1]))\r\n # flow_answer3_mask = tf.matmul(flow_answer3_similarity, tf.transpose(flow_logits, perm=[0, 2, 1]))\r\n # flow_answer4_mask = tf.matmul(flow_answer4_similarity, tf.transpose(flow_logits, perm=[0, 2, 1]))\r\n\r\n # flow_answer0_mask = tf.squeeze(flow_answer0_mask, axis=2)\r\n # flow_answer1_mask = tf.squeeze(flow_answer1_mask, axis=2)\r\n # flow_answer2_mask = tf.squeeze(flow_answer2_mask, axis=2)\r\n # flow_answer3_mask = tf.squeeze(flow_answer3_mask, axis=2)\r\n # flow_answer4_mask = tf.squeeze(flow_answer4_mask, axis=2)\r\n\r\n with tf.variable_scope(\"Flow_train_question_answer_att_layer\", reuse=tf.AUTO_REUSE):\r\n flow_question_answer0_att = tf.concat([flow_logits, flow_question_masked, flow_answer0_masked,\r\n tf.multiply(flow_logits, flow_question_masked),\r\n tf.multiply(flow_logits, flow_answer0_masked)], axis=2)\r\n flow_question_answer1_att = tf.concat([flow_logits, flow_question_masked, flow_answer1_masked,\r\n tf.multiply(flow_logits, flow_question_masked),\r\n tf.multiply(flow_logits, flow_answer1_masked)], axis=2)\r\n flow_question_answer2_att = tf.concat([flow_logits, flow_question_masked, flow_answer2_masked,\r\n tf.multiply(flow_logits, flow_question_masked),\r\n tf.multiply(flow_logits, flow_answer2_masked)], axis=2)\r\n flow_question_answer3_att = tf.concat([flow_logits, flow_question_masked, flow_answer3_masked,\r\n tf.multiply(flow_logits, flow_question_masked),\r\n tf.multiply(flow_logits, flow_answer3_masked)], axis=2)\r\n flow_question_answer4_att = tf.concat([flow_logits, flow_question_masked, flow_answer4_masked,\r\n tf.multiply(flow_logits, flow_question_masked),\r\n tf.multiply(flow_logits, flow_answer4_masked)], axis=2)\r\n\r\n #flow_rnn_model = video_rnn.vRNN('LSTM', 1000, 'Flow')\r\n #flow_question_answer0_att = flow_rnn_model.build(flow_question_answer0_att, prob, flow_seq_len)\r\n #flow_question_answer1_att = flow_rnn_model.build(flow_question_answer1_att, prob, flow_seq_len)\r\n #flow_question_answer2_att = flow_rnn_model.build(flow_question_answer2_att, prob, flow_seq_len)\r\n #flow_question_answer3_att = flow_rnn_model.build(flow_question_answer3_att, prob, flow_seq_len)\r\n #flow_question_answer4_att = flow_rnn_model.build(flow_question_answer4_att, prob, flow_seq_len)\r\n\r\n #flow_question_answer0_att = tf.reduce_max(flow_question_answer0_att, 1)\r\n #flow_question_answer1_att = tf.reduce_max(flow_question_answer1_att, 1)\r\n #flow_question_answer2_att = tf.reduce_max(flow_question_answer2_att, 1)\r\n #flow_question_answer3_att = tf.reduce_max(flow_question_answer3_att, 1)\r\n #flow_question_answer4_att = tf.reduce_max(flow_question_answer4_att, 1)\r\n\r\n # flow_question_answer0_att = tf.concat([flow_question_masked, flow_answer0_mask], axis=1)\r\n # flow_question_answer1_att = tf.concat([flow_question_masked, flow_answer1_mask], axis=1)\r\n # flow_question_answer2_att = tf.concat([flow_question_masked, flow_answer2_mask], axis=1)\r\n # flow_question_answer3_att = tf.concat([flow_question_masked, flow_answer3_mask], axis=1)\r\n # flow_question_answer4_att = tf.concat([flow_question_masked, flow_answer4_mask], axis=1)\r\n # flow_question_answer0_att = tf.matmul(flow_question_masked, tf.transpose(flow_answer0_mask, perm=[0, 2, 1]))\r\n # flow_question_answer1_att = tf.matmul(flow_question_masked, tf.transpose(flow_answer1_mask, perm=[0, 2, 1]))\r\n # flow_question_answer2_att = tf.matmul(flow_question_masked, tf.transpose(flow_answer2_mask, perm=[0, 2, 1]))\r\n # flow_question_answer3_att = tf.matmul(flow_question_masked, tf.transpose(flow_answer3_mask, perm=[0, 2, 1]))\r\n # flow_question_answer4_att = tf.matmul(flow_question_masked, tf.transpose(flow_answer4_mask, perm=[0, 2, 1]))\r\n\r\n '''\r\n flow_question_answer0_cnn = tf.layers.conv1d(flow_question_answer0_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n kernel_initializer=tf.initializers.random_normal, name=\"flow_conv\")\r\n flow_question_answer1_cnn = tf.layers.conv1d(flow_question_answer1_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n name=\"flow_conv\", reuse=True)\r\n flow_question_answer2_cnn = tf.layers.conv1d(flow_question_answer2_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n name=\"flow_conv\", reuse=True)\r\n flow_question_answer3_cnn = tf.layers.conv1d(flow_question_answer3_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n name=\"flow_conv\", reuse=True)\r\n flow_question_answer4_cnn = tf.layers.conv1d(flow_question_answer4_att, 1, 1, padding='same',\r\n activation=tf.nn.leaky_relu, kernel_regularizer=regularizer,\r\n name=\"flow_conv\", reuse=True)\r\n\r\n flow_question_answer0_cnn = tf.nn.dropout(flow_question_answer0_cnn, prob[0][0])\r\n flow_question_answer1_cnn = tf.nn.dropout(flow_question_answer1_cnn, prob[0][0])\r\n flow_question_answer2_cnn = tf.nn.dropout(flow_question_answer2_cnn, prob[0][0])\r\n flow_question_answer3_cnn = tf.nn.dropout(flow_question_answer3_cnn, prob[0][0])\r\n flow_question_answer4_cnn = tf.nn.dropout(flow_question_answer4_cnn, prob[0][0])\r\n\r\n flow_question_answer0_cnn = tf.squeeze(flow_question_answer0_cnn, 2)\r\n flow_question_answer1_cnn = tf.squeeze(flow_question_answer1_cnn, 2)\r\n flow_question_answer2_cnn = tf.squeeze(flow_question_answer2_cnn, 2)\r\n flow_question_answer3_cnn = tf.squeeze(flow_question_answer3_cnn, 2)\r\n flow_question_answer4_cnn = tf.squeeze(flow_question_answer4_cnn, 2)\r\n '''\r\n '''\r\n flow_question_answer0_fc = tf.layers.dense(flow_question_answer0_att, 2000, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name=\"Flow_mask_fc\")\r\n flow_question_answer1_fc = tf.layers.dense(flow_question_answer1_att, 2000, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name=\"Flow_mask_fc\", reuse=True)\r\n flow_question_answer2_fc = tf.layers.dense(flow_question_answer2_att, 2000, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name=\"Flow_mask_fc\", reuse=True)\r\n flow_question_answer3_fc = tf.layers.dense(flow_question_answer3_att, 2000, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name=\"Flow_mask_fc\", reuse=True)\r\n flow_question_answer4_fc = tf.layers.dense(flow_question_answer4_att, 2000, activation=tf.nn.leaky_relu,\r\n kernel_regularizer=regularizer, name=\"Flow_mask_fc\", reuse=True)\r\n\r\n flow_question_answer0_fc = tf.nn.dropout(flow_question_answer0_fc, keep_prob=prob[0][0])\r\n flow_question_answer1_fc = tf.nn.dropout(flow_question_answer1_fc, keep_prob=prob[0][0])\r\n flow_question_answer2_fc = tf.nn.dropout(flow_question_answer2_fc, keep_prob=prob[0][0])\r\n flow_question_answer3_fc = tf.nn.dropout(flow_question_answer3_fc, keep_prob=prob[0][0])\r\n flow_question_answer4_fc = tf.nn.dropout(flow_question_answer4_fc, keep_prob=prob[0][0])\r\n '''\r\n\r\n #flow_question_answer0_fc = tf.reduce_max(flow_question_answer0_att, 1)\r\n #flow_question_answer1_fc = tf.reduce_max(flow_question_answer1_att, 1)\r\n #flow_question_answer2_fc = tf.reduce_max(flow_question_answer2_att, 1)\r\n #flow_question_answer3_fc = tf.reduce_max(flow_question_answer3_att, 1)\r\n #flow_question_answer4_fc = tf.reduce_max(flow_question_answer4_att, 1)\r\n\r\n # flow_question_answer0_fc = tf.squeeze(flow_question_answer0_fc, 2)\r\n # flow_question_answer1_fc = tf.squeeze(flow_question_answer1_fc, 2)\r\n # flow_question_answer2_fc = tf.squeeze(flow_question_answer2_fc, 2)\r\n # flow_question_answer3_fc = tf.squeeze(flow_question_answer3_fc, 2)\r\n # flow_question_answer4_fc = tf.squeeze(flow_question_answer4_fc, 2)\r\n\r\n with tf.variable_scope(\"video_fc\", reuse=tf.AUTO_REUSE):\r\n # rgb_answer0_g_logits = tf.layers.dense(rgb_question_answer0_fc, 1, name=\"RGB_fc\",\r\n # kernel_regularizer=regularizer, activation=tf.nn.leaky_relu)\r\n # rgb_answer1_g_logits = tf.layers.dense(rgb_question_answer1_fc, 1, name=\"RGB_fc\",\r\n # kernel_regularizer=regularizer, activation=tf.nn.leaky_relu, reuse=True)\r\n # rgb_answer2_g_logits = tf.layers.dense(rgb_question_answer2_fc, 1, name=\"RGB_fc\",\r\n # kernel_regularizer=regularizer, activation=tf.nn.leaky_relu, reuse=True)\r\n # rgb_answer3_g_logits = tf.layers.dense(rgb_question_answer3_fc, 1, name=\"RGB_fc\",\r\n # kernel_regularizer=regularizer, activation=tf.nn.leaky_relu, reuse=True)\r\n # rgb_answer4_g_logits = tf.layers.dense(rgb_question_answer4_fc, 1, name=\"RGB_fc\",\r\n # kernel_regularizer=regularizer, activation=tf.nn.leaky_relu, reuse=True)\r\n\r\n # rgb_answer0_g_logits = tf.nn.dropout(rgb_answer0_g_logits, prob[0][0])\r\n # rgb_answer1_g_logits = tf.nn.dropout(rgb_answer1_g_logits, prob[0][0])\r\n # rgb_answer2_g_logits = tf.nn.dropout(rgb_answer2_g_logits, prob[0][0])\r\n # rgb_answer3_g_logits = tf.nn.dropout(rgb_answer3_g_logits, prob[0][0])\r\n # rgb_answer4_g_logits = tf.nn.dropout(rgb_answer4_g_logits, prob[0][0])\r\n\r\n flow_answer0_g_logits = tf.layers.dense(flow_question_answer0_att, 1, name=\"Flow_fc\",\r\n kernel_regularizer=regularizer, activation=tf.nn.leaky_relu)\r\n flow_answer1_g_logits = tf.layers.dense(flow_question_answer1_att, 1, name=\"Flow_fc\",\r\n kernel_regularizer=regularizer, activation=tf.nn.leaky_relu, reuse=True)\r\n flow_answer2_g_logits = tf.layers.dense(flow_question_answer2_att, 1, name=\"Flow_fc\",\r\n kernel_regularizer=regularizer, activation=tf.nn.leaky_relu, reuse=True)\r\n flow_answer3_g_logits = tf.layers.dense(flow_question_answer3_att, 1, name=\"Flow_fc\",\r\n kernel_regularizer=regularizer, activation=tf.nn.leaky_relu, reuse=True)\r\n flow_answer4_g_logits = tf.layers.dense(flow_question_answer4_att, 1, name=\"Flow_fc\",\r\n kernel_regularizer=regularizer, activation=tf.nn.leaky_relu, reuse=True)\r\n\r\n flow_answer0_g_logits = tf.nn.dropout(flow_answer0_g_logits, prob[0][0])\r\n flow_answer1_g_logits = tf.nn.dropout(flow_answer1_g_logits, prob[0][0])\r\n flow_answer2_g_logits = tf.nn.dropout(flow_answer2_g_logits, prob[0][0])\r\n flow_answer3_g_logits = tf.nn.dropout(flow_answer3_g_logits, prob[0][0])\r\n flow_answer4_g_logits = tf.nn.dropout(flow_answer4_g_logits, prob[0][0])\r\n\r\n flow_answer0_g_logits = tf.layers.batch_normalization(flow_answer0_g_logits, training=is_training[0][0])\r\n flow_answer1_g_logits = tf.layers.batch_normalization(flow_answer1_g_logits, training=is_training[0][0])\r\n flow_answer2_g_logits = tf.layers.batch_normalization(flow_answer2_g_logits, training=is_training[0][0])\r\n flow_answer3_g_logits = tf.layers.batch_normalization(flow_answer3_g_logits, training=is_training[0][0])\r\n flow_answer4_g_logits = tf.layers.batch_normalization(flow_answer4_g_logits, training=is_training[0][0])\r\n\r\n flow_answer0_g_logits = tf.reduce_max(flow_answer0_g_logits, 1)\r\n flow_answer1_g_logits = tf.reduce_max(flow_answer1_g_logits, 1)\r\n flow_answer2_g_logits = tf.reduce_max(flow_answer2_g_logits, 1)\r\n flow_answer3_g_logits = tf.reduce_max(flow_answer3_g_logits, 1)\r\n flow_answer4_g_logits = tf.reduce_max(flow_answer4_g_logits, 1)\r\n\r\n with tf.variable_scope(\"post_rnn\", reuse=tf.AUTO_REUSE):\r\n # subtitle_question_g_rnn_model = text_rnn_cudnn.tRNN(\"LSTM\", FLAGS.num_hidden, \"subtitle_question_g\")\r\n subtitle_answer_g_rnn_model = text_rnn_cudnn.tRNN(\"LSTM\", FLAGS.num_hidden * 5, \"subtitle_answer_g\")\r\n # subtitle_question_g_rnn_logits = subtitle_question_g_rnn_model.build(subtitle_question_g,\r\n # is_training=FLAGS.is_training,\r\n # seq_len=sub_seq_len)\r\n subtitle_answer0_g_rnn_logits = subtitle_answer_g_rnn_model.build(concat_subtitle_query0,\r\n dropout_keep_prob=text_prob,\r\n seq_len=sub_seq_len)\r\n subtitle_answer1_g_rnn_logits = subtitle_answer_g_rnn_model.build(concat_subtitle_query1,\r\n dropout_keep_prob=text_prob,\r\n seq_len=sub_seq_len)\r\n subtitle_answer2_g_rnn_logits = subtitle_answer_g_rnn_model.build(concat_subtitle_query2,\r\n dropout_keep_prob=text_prob,\r\n seq_len=sub_seq_len)\r\n subtitle_answer3_g_rnn_logits = subtitle_answer_g_rnn_model.build(concat_subtitle_query3,\r\n dropout_keep_prob=text_prob,\r\n seq_len=sub_seq_len)\r\n subtitle_answer4_g_rnn_logits = subtitle_answer_g_rnn_model.build(concat_subtitle_query4,\r\n dropout_keep_prob=text_prob,\r\n seq_len=sub_seq_len)\r\n # subtitle_question_g_rnn_logits = tf.reduce_max(subtitle_question_g_rnn_logits, axis=1)\r\n # subtitle_question_g_logits = tf.layers.dense(subtitle_question_g_rnn_logits, 1,\r\n # name=\"subtitle_question_g_logits\")\r\n subtitle_answer0_g_rnn_logits = tf.reduce_max(subtitle_answer0_g_rnn_logits, axis=1)\r\n subtitle_answer1_g_rnn_logits = tf.reduce_max(subtitle_answer1_g_rnn_logits, axis=1)\r\n subtitle_answer2_g_rnn_logits = tf.reduce_max(subtitle_answer2_g_rnn_logits, axis=1)\r\n subtitle_answer3_g_rnn_logits = tf.reduce_max(subtitle_answer3_g_rnn_logits, axis=1)\r\n subtitle_answer4_g_rnn_logits = tf.reduce_max(subtitle_answer4_g_rnn_logits, axis=1)\r\n\r\n subtitle_answer0_g_logits = tf.layers.dense(subtitle_answer0_g_rnn_logits, 1,\r\n name=\"subtitle_answer_g_logits\",\r\n activation=tf.nn.leaky_relu)\r\n subtitle_answer1_g_logits = tf.layers.dense(subtitle_answer1_g_rnn_logits, 1,\r\n name=\"subtitle_answer_g_logits\", reuse=True,\r\n activation=tf.nn.leaky_relu)\r\n subtitle_answer2_g_logits = tf.layers.dense(subtitle_answer2_g_rnn_logits, 1,\r\n name=\"subtitle_answer_g_logits\", reuse=True,\r\n activation=tf.nn.leaky_relu)\r\n subtitle_answer3_g_logits = tf.layers.dense(subtitle_answer3_g_rnn_logits, 1,\r\n name=\"subtitle_answer_g_logits\", reuse=True,\r\n activation=tf.nn.leaky_relu)\r\n subtitle_answer4_g_logits = tf.layers.dense(subtitle_answer4_g_rnn_logits, 1,\r\n name=\"subtitle_answer_g_logits\", reuse=True,\r\n activation=tf.nn.leaky_relu)\r\n\r\n # subtitle_answer_g_concat = tf.concat([subtitle_answer0_g_rnn_logits, subtitle_answer1_g_rnn_logits,\r\n # subtitle_answer2_g_rnn_logits, subtitle_answer3_g_rnn_logits,\r\n # subtitle_answer4_g_rnn_logits], axis=1)\r\n\r\n # subtitle_answer_embed = tf.layers.dense(subtitle_answer_g_concat, 5, kernel_regularizer=regularizer,\r\n # activation=tf.nn.leaky_relu, name=\"text_classifier\")\r\n\r\n '''\r\n subtitle_answer0_g_logits = tf.layers.dropout(subtitle_answer0_g_logits, training=is_training)\r\n subtitle_answer1_g_logits = tf.layers.dropout(subtitle_answer1_g_logits, training=is_training)\r\n subtitle_answer2_g_logits = tf.layers.dropout(subtitle_answer2_g_logits, training=is_training)\r\n subtitle_answer3_g_logits = tf.layers.dropout(subtitle_answer3_g_logits, training=is_training)\r\n subtitle_answer4_g_logits = tf.layers.dropout(subtitle_answer4_g_logits, training=is_training)\r\n '''\r\n subtitle_answer0_g_logits = tf.nn.dropout(subtitle_answer0_g_logits, text_prob[0][0])\r\n subtitle_answer1_g_logits = tf.nn.dropout(subtitle_answer1_g_logits, text_prob[0][0])\r\n subtitle_answer2_g_logits = tf.nn.dropout(subtitle_answer2_g_logits, text_prob[0][0])\r\n subtitle_answer3_g_logits = tf.nn.dropout(subtitle_answer3_g_logits, text_prob[0][0])\r\n subtitle_answer4_g_logits = tf.nn.dropout(subtitle_answer4_g_logits, text_prob[0][0])\r\n\r\n with tf.variable_scope(\"Embed\"):\r\n # subtitle_question_embed = tf.concat([subtitle_question_g_logits, subtitle_question_g_logits,\r\n # subtitle_question_g_logits, subtitle_question_g_logits,\r\n # subtitle_question_g_logits], axis=1)\r\n subtitle_answer_embed = tf.concat([subtitle_answer0_g_logits, subtitle_answer1_g_logits,\r\n subtitle_answer2_g_logits, subtitle_answer3_g_logits,\r\n subtitle_answer4_g_logits], axis=1)\r\n subtitle_text_embed = subtitle_answer_embed\r\n\r\n # rgb_answer_embed = tf.concat([rgb_answer0_g_logits, rgb_answer1_g_logits, rgb_answer2_g_logits,\r\n # rgb_answer3_g_logits, rgb_answer4_g_logits], axis=1)\r\n\r\n flow_answer_embed = tf.concat([flow_answer0_g_logits, flow_answer1_g_logits, flow_answer2_g_logits,\r\n flow_answer3_g_logits, flow_answer4_g_logits], axis=1)\r\n '''\r\n with tf.variable_scope(\"RGB_text_embed\"):\r\n rgb_rnn_logits = tf.reshape(tf.cast(rgb_rnn_logits, tf.float64), [-1, FLAGS.num_hidden*2, 1])\r\n rgb_question_embed_logits = tf.matmul(question_rnn_logits, rgb_rnn_logits)\r\n rgb_question_embed_logits = tf.concat([rgb_question_embed_logits, rgb_question_embed_logits,\r\n rgb_question_embed_logits, rgb_question_embed_logits,\r\n rgb_question_embed_logits], axis=1)\r\n rgb_answer_embed_logits = tf.matmul(answer_rnn_logits, rgb_rnn_logits)\r\n rgb_text_embed = rgb_question_embed_logits + rgb_answer_embed_logits\r\n\r\n with tf.variable_scope(\"flow_text_embed\"):\r\n flow_rnn_logits = tf.reshape(tf.cast(flow_rnn_logits, tf.float64), [-1, FLAGS.num_hidden*2, 1])\r\n flow_question_embed_logits = tf.matmul(question_rnn_logits, flow_rnn_logits)\r\n flow_question_embed_logits = tf.concat([flow_question_embed_logits, flow_question_embed_logits,\r\n flow_question_embed_logits, flow_question_embed_logits,\r\n flow_question_embed_logits], axis=1)\r\n flow_answer_embed_logits = tf.matmul(answer_rnn_logits, flow_rnn_logits)\r\n flow_text_embed = flow_question_embed_logits + flow_answer_embed_logits\r\n '''\r\n # with tf.device(\"/GPU:1\"):\r\n with tf.variable_scope(\"prediction\"):\r\n\r\n def loss_calc(elem):\r\n correct = elem[0][tf.argmax(elem[1])]\r\n\r\n # loss1 = tf.maximum(tf.cast(0.0, tf.float32), FLAGS.margin - correct + elem[0][0])\r\n # loss2 = tf.maximum(tf.cast(0.0, tf.float32), FLAGS.margin - correct + elem[0][1])\r\n # loss3 = tf.maximum(tf.cast(0.0, tf.float32), FLAGS.margin - correct + elem[0][2])\r\n # loss4 = tf.maximum(tf.cast(0.0, tf.float32), FLAGS.margin - correct + elem[0][3])\r\n # loss5 = tf.maximum(tf.cast(0.0, tf.float32), FLAGS.margin - correct + elem[0][4])\r\n # not_loss = FLAGS.margin\r\n loss1 = tf.exp(elem[0][0] - correct)\r\n loss2 = tf.exp(elem[0][1] - correct)\r\n loss3 = tf.exp(elem[0][2] - correct)\r\n loss4 = tf.exp(elem[0][3] - correct)\r\n loss5 = tf.exp(elem[0][4] - correct)\r\n # return loss1 + loss2 + loss3 + loss4 + loss5 - not_loss\r\n return tf.log(loss1 + loss2 + loss3 + loss4 + loss5)\r\n\r\n video_logits = flow_answer_embed\r\n total_logits = tf.nn.softmax(subtitle_text_embed, axis=1) + tf.scalar_mul(0.5,\r\n tf.nn.softmax(video_logits, axis=1))\r\n train_i3d_var_list = []\r\n train_match_var_list = []\r\n #reg_var_list = []\r\n for v in tf.trainable_variables():\r\n if v.name.startswith(u\"Flow_train\") or v.name.startswith(u\"video\"):\r\n train_match_var_list.append(v)\r\n if v.name.startswith(u\"Flow\") and not u\"train\" in v.name:\r\n train_i3d_var_list.append(v)\r\n #if not ('bias' in v.name) and ('bidirectional_rnn' in v.name) and \"Flow\" in v.name:\r\n # reg_var_list.append(v)\r\n # zero_tensor = tf.zeros([FLAGS.batch_size, 5], tf.int32)\r\n # bool_mask = tf.equal(zero_tensor, a)\r\n # margin_tensor = tf.constant(0.2, shape=[FLAGS.batch_size])\r\n # ranking_pos = tf.gather(total_logits, tf.argmax(a, axis=1), axis=1)\r\n # ranking_pos = tf.reduce_sum(ranking_pos, axis=1)\r\n # ranking_neg = tf.boolean_mask(total_logits, bool_mask)\r\n # ranking_neg = tf.reshape(ranking_neg, [-1, 4])\r\n # ranking_neg = tf.reduce_sum(ranking_neg, axis=1)\r\n # zero_tensor2 = tf.zeros([FLAGS.batch_size], tf.float32)\r\n # loss = tf.map_fn(loss_calc, (total_logits, a), dtype=tf.float32)\r\n\r\n video_loss = tf.map_fn(loss_calc, (video_logits, a), dtype=tf.float32)\r\n # video_loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=a, logits=video_logits)\r\n # loss = tf.maximum(zero_tensor2, margin_tensor - ranking_pos + ranking_neg)\r\n reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\r\n # cost = tf.reduce_mean(loss)\r\n cost = tf.reduce_mean(video_loss) + tf.cast(tf.contrib.layers.apply_regularization(regularizer, reg_losses),\r\n tf.float32)\r\n # tf.add_to_collection('losses', cost)\r\n # optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.lr)\r\n # op = optimizer.minimize(cost, var_list=train_var_list)\r\n comparison = tf.equal(tf.argmax(total_logits, axis=1), tf.argmax(a, axis=1))\r\n video_comparison = tf.equal(tf.argmax(video_logits, axis=1), tf.argmax(a, axis=1))\r\n accuracy = tf.reduce_mean(tf.cast(comparison, tf.float32), name=\"accuracy\")\r\n video_accuracy = tf.reduce_mean(tf.cast(video_comparison, tf.float32), name=\"accuracy\")\r\n # loss_summary = tf.summary.scalar(\"loss\", cost)\r\n # accuracy_summary = tf.summary.scalar(\"accuracy\", accuracy)\r\n # summary_op = tf.summary.merge([loss_summary, accuracy_summary])\r\n # train_var_list = []\r\n # for v in tf.trainable_variables():\r\n # if v.name.startswith(u\"RGB\") or v.name.startswith(u\"Flow\"):\r\n # train_var_list.append(v)\r\n '''\r\n prediction = tf.nn.softmax(total_logits, axis=1)\r\n train_var_list = []\r\n for v in tf.trainable_variables():\r\n if not (v.name.startswith(u\"RGB\") or v.name.startswith(u\"Flow\")):\r\n train_var_list.append(v)\r\n #a = 3\r\n #a = tf.squeeze(a, axis=[1])\r\n #cost = tf.reduce_mean(-tf.reduce_sum(tf.cast(a, tf.float64) * tf.log(prediction), 1))\r\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=a, logits=total_logits))\r\n optimizer = tf.train.MomentumOptimizer(learning_rate=FLAGS.lr, momentum=0.9)\r\n op = optimizer.minimize(cost, var_list=train_var_list)\r\n\r\n comparison = tf.equal(tf.argmax(prediction, axis=1), tf.argmax(a, axis=1))\r\n accuracy = tf.reduce_mean(tf.cast(comparison, tf.float64), name=\"accuracy\")\r\n\r\n loss_summary = tf.summary.scalar(\"loss\", cost)\r\n accuracy_summary = tf.summary.scalar(\"accuracy\", accuracy)\r\n summary_op = tf.summary.merge([loss_summary, accuracy_summary])\r\n '''\r\n return cost, accuracy, video_accuracy, qid, comparison, train_i3d_var_list, train_match_var_list","sub_path":"network_tower_flow.py","file_name":"network_tower_flow.py","file_ext":"py","file_size_in_byte":63151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"315895973","text":"import sys\nimport re\nimport json\nimport urllib.parse\nimport os.path\n\nimport argparse\n\n\ndef read_external_fasta(file_name):\n fasta = {}\n with open(file_name) as fp:\n lines = fp.read().splitlines()\n current_fasta = ''\n for line in lines:\n if line[0] == '>':\n current_fasta = line[1:]\n elif len(line) > 5:\n fasta[current_fasta] = line\n return fasta\n\ndef main():\n parser = argparse.ArgumentParser(description='convert gff file format to json')\n\n parser.add_argument('--fasta',\n help='user external fasta file')\n\n parser.add_argument('--out',\n help='specify the output name')\n\n parser.add_argument('gff_file', help='gff file')\n\n args = parser.parse_args()\n\n src_filename = args.gff_file\n if args.out:\n dst_filename = args.out\n else:\n dst_filename = os.path.splitext(src_filename)[0]+'.json'\n\n fasta = {}\n if args.fasta:\n fasta = read_external_fasta(args.fasta)\n\n f = open(src_filename)\n fastaSection = False\n records = []\n \n currentFasta = ''\n sequence = ''\n for line in f.readlines():\n if args.fasta and re.match('##FASTA', line):\n fastaSection = True\n if line[0] == '#':\n continue\n if not fastaSection:\n segment = re.split('\\t| ', line)\n attributesString = re.split('\\n|;', segment[8])\n attributes = {}\n for s in attributesString:\n e = s.split('=')\n if len(e) >= 2 :\n attributes[e[0]] = urllib.parse.unquote(e[1])\n record = {\n 'seqName': segment[0],\n 'source': segment[1],\n 'feature': segment[2],\n 'start': int(segment[3])-1,\n 'end': int(segment[4]),\n 'score': segment[5],\n 'strand': segment[6],\n 'frame': segment[7],\n 'attribute': attributes,\n }\n records.append(record)\n else:\n if re.match(r'^>', line):\n print(line)\n if currentFasta != '':\n fasta[currentFasta]=sequence\n currentFasta = re.findall('[a-zA-Z0-9]+', line[1:])[0]\n sequence = ''\n else:\n sequence += re.match(r'\\S+', line).group()\n else:\n fasta[currentFasta]=sequence\n f.close()\n with open(dst_filename, 'w') as f2:\n json.dump({'records': records, 'fasta': fasta}, f2, indent=4, separators=(',', ': '))\n\nif __name__ == \"__main__\":\n main()","sub_path":"gff2json/gff2json.py","file_name":"gff2json.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"580424079","text":"# Input : [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]\n# \n# Output : [(0, 1), (3, 8), (9, 12)]\n# \n# Write a function merge_ranges() that takes a list of multiple\n# meeting time ranges and returns a list of condensed ranges.\n# \n# Do not assume the meetings are in order. \n# \n# The meeting times are coming from multiple teams.\n# \n# \n# \n# Solution : First, we sort our input list of meetings by start time so any meetings \n# that might need to be merged are now next to each other.\n#\n# Then we walk through our sorted meetings from left to right. At each step, either:\n#\n# 1. We can merge the current meeting with the previous one, so we do.\n# 2. We can't merge the current meeting with the previous one, so we know the previous meeting \n# can't be merged with any future meetings and we throw the current meeting into merged_meetings.\n#\n#\n# Complexity\n# O(nlgn) time and O(n) space.\n#\n# Even though we only walk through our list of meetings once to merge them, we sort all the meetings first, \n# giving us a runtime of O(nlgn). It's worth noting that if our input were sorted, we could skip the sort and do this in O(n) time!\n#\n# We create a new list of merged meeting times. In the worst case, none of the meetings overlap, giving us a list \n# identical to the input list. Thus we have a worst-case space cost of O(n).\n\n\ndef merge_ranges(meetings):\n\n # Sort by start time\n sorted_meetings = sorted(meetings)\n\n # Initialize merged_meetings with the earliest meeting\n merged_meetings = [sorted_meetings[0]]\n\n for current_meeting_start, current_meeting_end in sorted_meetings[1:]:\n last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1]\n\n # If the current meeting overlaps with the last merged meeting, use the\n # later end time of the two\n if (current_meeting_start <= last_merged_meeting_end):\n merged_meetings[-1] = (last_merged_meeting_start,\n max(last_merged_meeting_end,\n current_meeting_end))\n else:\n # Add the current meeting since it doesn't overlap\n merged_meetings.append((current_meeting_start, current_meeting_end))\n\n return merged_meetings","sub_path":"merge_ranges.py","file_name":"merge_ranges.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47389637","text":"from setuptools import setup, find_packages\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\n__version__ = \"0.0.1\"\n\nsetup(\n author='Jeff Wang',\n author_email='jeffwji@test.com',\n\n version_command='git describe --always --long --dirty=-dev',\n\n name = \"my_microservice_customer\",\n packages = find_packages(\n exclude=['tests', '*.tests', '*.tests.*']\n ),\n\n package_data = {\n '':[ 'config/*.properties', '*.md', 'requirements.txt' ],\n },\n\n install_requires=requirements,\n)\n","sub_path":"Customer/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"347641846","text":"import sys ; sys.path.insert(0, '..') ; sys.path.insert(0, '../..') \n\nfrom model.deeplab import DeepLab\n\nfrom reproducibility import set_reproducibility\n\nfrom data.loader import XrayDataset\nimport pickle\n\nfrom tqdm import tqdm \nimport torch\nfrom torch import optim\nfrom torch import nn\nimport adabound\n\nimport argparse \nimport pandas as pd \nimport numpy as np \nimport glob, os \n\nfrom utils.aug import simple_aug, resize_aug, pad_image\nfrom utils.helper import LossTracker, preprocess_input\n\nfrom torch.utils.data import DataLoader\nfrom functools import partial \n\ndef parse_args():\n parser = argparse.ArgumentParser()\n \n parser.add_argument('model', type=str)\n parser.add_argument('model_folder', type=str, help=\"Path to folder containing snapsnot ensemble models.\") \n parser.add_argument('data_dir', type=str, help=\"Directory to load image data from.\") \n parser.add_argument('save_file', type=str)\n parser.add_argument('--class-mode', action='store_true')\n parser.add_argument('--gpu', type=int, default=0)\n parser.add_argument('--imsize-x', type=int, default=384)\n parser.add_argument('--imsize-y', type=int, default=384)\n parser.add_argument('--imratio', type=float, default=1)\n parser.add_argument('--batch-size', type=int, default=16)\n parser.add_argument('--tta', action='store_true', help='Enable test-time augmentation')\n parser.add_argument('--dropout-p', type=float, default=0.2)\n parser.add_argument('--gn', action='store_true')\n parser.add_argument('--output-stride', type=int, default=16)\n parser.add_argument('--verbosity', type=int, default=100)\n parser.add_argument('--num-workers', type=int, default=1)\n parser.add_argument('--seed', type=int, default=88)\n \n args = parser.parse_args()\n return args \n\n\ndef main():\n args = parse_args()\n\n set_reproducibility(args.seed)\n\n resize_me = resize_aug(imsize_x=args.imsize_x, imsize_y=args.imsize_y)\n pad_func = partial(pad_image, ratio=args.imratio)\n\n print (\"Predicting the PNEUMOTHORAX SEGMENTATION model...\")\n\n torch.cuda.set_device(args.gpu) ; torch.backends.cudnn.benchmark = True \n\n if not os.path.exists(os.path.dirname(args.save_file)):\n os.makedirs(os.path.dirname(args.save_file))\n\n print(\"Reading images from directory {}\".format(args.data_dir))\n test_images = glob.glob(os.path.join(args.data_dir, '*.png'))\n print ('TEST: n={}'.format(len(test_images)))\n test_sops = [_.split('/')[-1].replace('.png', '') for _ in test_images]\n num_classes = 2\n \n # Get models in snapshot ensemble\n snapshots = glob.glob(os.path.join(args.model_folder, '*.pth'))\n\n num_snapshots = 3\n weights = np.asarray([3.,1.,1.])\n weights = weights / np.sum(weights)\n # Pick best 3 models, then weight based on Kaggle metric: 3, 1, 1\n # This assumes a certain formatting of the checkpoint file name\n # in order to extract the Kaggle metric \n if args.class_mode:\n def extract_kag(ckpt):\n ckpt = ckpt.split('/')[-1]\n _kag = ckpt.split('_')[4]\n _kag = _kag.split('-')[-1]\n return float(_kag)\n else:\n def extract_kag(ckpt):\n ckpt = ckpt.split('/')[-1]\n _kag = ckpt.split('_')[2]\n _kag = _kag.split('-')[-1]\n return float(_kag)\n\n snapshot_kags = [extract_kag(_) for _ in snapshots]\n kag_order = np.argsort(snapshot_kags)[::-1][:num_snapshots]\n snapshots = list(np.asarray(snapshots)[kag_order])\n\n def load_model(ckpt):\n model = DeepLab(args.model, args.output_stride, args.gn, classifier=False)\n model.load_state_dict(torch.load(ckpt))\n model = model.cuda()\n model.eval()\n return model\n\n # Get models\n print ('Loading checkpoints ...')\n model_list = []\n for ss in snapshots:\n model_list.append(load_model(ss))\n\n # Set up preprocessing function with model \n ppi = partial(preprocess_input, model=model_list[0])\n\n print ('Setting up data loaders ...')\n\n params = {'batch_size': 1 if args.tta else args.batch_size, \n 'shuffle': False, \n 'num_workers': args.num_workers}\n\n test_set = XrayDataset(imgfiles=test_images,\n dicom=False,\n labels=[0]*len(test_images),\n preprocess=ppi, \n pad=pad_func,\n resize=resize_me,\n test_mode=True)\n test_gen = DataLoader(test_set, **params) \n\n # Test\n def get_test_predictions(mod):\n with torch.no_grad():\n list_of_pred_dicts = []\n for data in tqdm(test_gen, total=len(test_gen)):\n pred_dict = {}\n if args.tta: \n # should be batch size = 1\n batch, _ = data\n batch = batch[0]\n output = mod(batch.cuda())\n pred_dict['pred_mask'] = torch.softmax(output, dim=1).cpu().numpy()[:,1]\n else:\n batch, _ = data\n output = mod(batch.cuda())\n output_flipped = mod(torch.flip(batch, dims=(-1,)).cuda())\n output_flipped = torch.flip(output_flipped, dims=(-1,))\n pred_dict['pred_mask'] = (torch.softmax(output, dim=1).cpu().numpy()[:,1] + torch.softmax(output_flipped, dim=1).cpu().numpy()[:,1]) / 2.\n list_of_pred_dicts.append(pred_dict)\n return list_of_pred_dicts\n\n y_pred_list = []\n for model in tqdm(model_list, total=len(model_list)):\n tmp_y_pred = get_test_predictions(model)\n y_pred_list.append(tmp_y_pred)\n\n # Need to average predictions across models\n for each_indiv_pred in range(len(y_pred_list[0])):\n indiv_pred = np.zeros_like(y_pred_list[0][each_indiv_pred]['pred_mask'])\n for each_model_pred in range(len(y_pred_list)):\n indiv_pred += weights[each_model_pred]*y_pred_list[each_model_pred][each_indiv_pred]['pred_mask']\n #indiv_pred /= float(len(y_pred_list))\n assert np.min(indiv_pred) >= 0 and np.max(indiv_pred) <= 1\n y_pred_list[0][each_indiv_pred]['pred_mask'] = (indiv_pred * 100).astype('uint8')\n\n def get_top_X(segmentation, tops=[0,0.5,1.0,2.5,5.0]):\n # Assumes segmentation.shape is (1, H, W)\n assert segmentation.shape[0] == 1\n scores = []\n segmentation = segmentation.reshape(segmentation.shape[0], -1).astype('int8')\n segmentation = -np.sort(-segmentation, axis=1)\n for t in tops:\n size = int(t / 100. * np.prod(segmentation.shape)) if t > 0 else 1\n scores.append(np.mean(segmentation[:,:size]) / 100.)\n return scores\n\n if args.class_mode:\n # Turn segmentation output into class scores\n tops = [0,0.5,1.0,2.5,5.0]\n class_scores = []\n for i in range(len(y_pred_list[0])):\n class_scores.append(get_top_X(y_pred_list[0][i]['pred_mask'], tops))\n # Make a DataFrame\n class_scores = np.vstack(class_scores)\n class_scores = pd.DataFrame(class_scores)\n class_scores.columns = ['Top{}'.format(t) for t in tops]\n class_scores['sop'] = test_sops\n class_scores.to_csv(args.save_file, index=False)\n else:\n\n y_pred_to_pickle = y_pred_list[0]\n y_pred_to_pickle = {test_sops[_] : y_pred_to_pickle[_] for _ in range(len(test_sops))}\n\n with open(args.save_file, 'wb') as f: \n pickle.dump(y_pred_to_pickle, f)\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"segment/scripts/PredictDeepLabSnapshot.py","file_name":"PredictDeepLabSnapshot.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"479721101","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/1/23 10:41 \r\n# @Author : for \r\n# @File : 03_part_test.py \r\n# @Software: PyCharm\r\nimport smtplib,time\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.application import MIMEApplication\r\n#构造发送这 接受者\r\nuser = '3403073998@qq.com'\r\npwd = 'ihenvpgtjinqchbd'\r\nto = '3403073998@qq.com'\r\n#创建一个实例,想想成一个画布\r\nmsg= MIMEMultipart()\r\n#画布上添加主题,发送者 接受者\r\nmsg['Subject'] = '这是一个附件的测试'\r\nmsg['From'] = user\r\nmsg['To'] = to\r\n#画布上画上正文内容\r\npart = MIMEText('这是一个文本内容')\r\nmsg.attach(part)\r\n#添加附件\r\npart = MIMEApplication(open('1.mp4','rb').read())\r\n#邮箱明白我们发哦送的数据是什么格式\r\npart.add_header('content-disposition', 'attachment', filename='1.mp4')\r\nmsg.attach(part)\r\n#构造自己服务器并且发送\r\ntry:\r\n s = smtplib.SMTP('smtp.qq.com',timeout=30)\r\n s.login(user,pwd)\r\n s.sendmail(user,to,msg.as_string())\r\nexcept Exception as e:\r\n print(e)\r\ntime.sleep(2)\r\n#关闭服务器\r\ns.close()\r\n\r\n\r\n\r\n","sub_path":"2019_1_23_pub_test/03_part_test.py","file_name":"03_part_test.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"349364322","text":"import tkinter as tk\nfrom tkinter import tix\nfrom ftplib import FTP\nimport os\nimport os.path\nimport datetime\nimport time\nimport pandas as pd\nimport numpy as np\nimport io\nimport threading\nimport queue\nfrom time import sleep\n\npath = 'C:/Users/praktykant/Desktop/bupapp/FTP_IP.csv'\nData = pd.read_csv(path, sep=';')\nData = pd.DataFrame(Data)\n\n\nASS_List1 = [['Lin1', 'Rob1', 'IP1'], ['Lin2', 'Rob2', 'IP2'],\n ['Lin3', 'Rob3', 'IP3'], ['Lin4', 'Rob4', 'IP4'],\n ['Lin5', 'Rob5', 'IP5'], ['Lin8', 'Rob8', 'IP8'],\n ['Lin9', 'Rob9', 'IP9'], ['Lin10', 'Rob10', 'IP10']]\n\nASS_List2 = [['Lin6-1', 'Rob6-1', 'IP6-1'], ['Lin6-2', 'Rob6-2', 'IP6-2'], \n ['Lin7', 'Rob7', 'IP7']]\n\nAL = pd.DataFrame(ASS_List1 + ASS_List2)\n\nRob_Mat=[]\nfor index in (ASS_List1 + ASS_List2):\n ass = Data.loc[:, index]\n for i in range(0, ass.count()[0]):\n Rob_Mat.append(ass.iloc[i, :])\ndf = pd.DataFrame(Rob_Mat)\n \ndef init_date():\n my_date = datetime.date.today()\n year,week,day = my_date.isocalendar()\n save_dir = r'backup' + str(year) + 'WEEK' + str(week)\n return save_dir\n\ndef connect_ftp(ip):\n try:\n ftp = FTP(ip, timeout=1)\n ftp.login('STUDENCI1', '3344')\n ftp.pwd()\n print(ftp.getwelcome())\n except Exception as e:\n print(e)\n return False, e\n return True, ftp\n\ndef get_robot_info(location):\n robot = location.split('.')\n # eg. robot[0] == Lin1 ; robot[1] == R1\n #print(robot)\n LINE = robot[0]\n ROBOT = robot[1]\n Line_num = df.columns.get_loc(robot[0])\n Rob_num = Line_num + 1\n Ip_num = Line_num + 2 \n robots_col = df.iloc[:, Rob_num]\n index = robots_col.isin([robot[1]])\n IP = df.iloc[:, Ip_num][index]\n # remove index and spacebars\n IP = IP.to_string(index=False).replace(' ', '')\n print('Laczenie z ', LINE, ROBOT, IP)\n return LINE, ROBOT, IP\n\n######################################################################################################\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.pack()\n self.create_widgets()\n self.makeCheckList(ASS_List=ASS_List1)\n self.makeCheckList2(ASS_List=ASS_List2)\n self.cl.pack()\n self.location = ''\n self.LT = tk.Label(leftFrame, text=0)\n self.LT.pack(side='bottom')\n self.LT.after(1000, self.refresh_LT)\n def create_widgets(self):\n\n #RADIOBUTTONS\n #initialise variables for 2 groups of radiobuttons\n self.var1 = tk.IntVar()\n self.var2 = tk.IntVar()\n self.var1.set(0)\n self.var2.set(0)\n\n self.A1 = tk.Radiobutton(leftFrame, text='NETWORK 1', variable=self.var1, value=0, command=self.choose_n1)\n self.A1.pack(side = 'top')\n self.A2 = tk.Radiobutton(leftFrame, text='NETWORK 2', variable=self.var1, value=1, command=self.choose_n2)\n self.A2.pack(side = 'top')\n \n self.B4 = tk.Radiobutton(rightFrame, text='CMOS & FILES', variable=self.var2, value=3)\n self.B4.pack()\n self.B3 = tk.Radiobutton(rightFrame, text='Pobierz cmos', variable=self.var2, value=1)\n self.B3.pack()\n self.B2 = tk.Radiobutton(rightFrame, text='pobierz pliki ', variable=self.var2, value=2)\n self.B2.pack()\n self.B1 = tk.Radiobutton(rightFrame, text='Check connec', variable=self.var2, value=0)\n self.B1.pack()\n\n #button\n self.select_all = tk.Button(topFrame, text='Select All', command=self.press_select_all)\n self.select_all.pack(side='bottom')\n\n self.test = tk.Button(rightFrame, text='Run', command=self.press_test)\n self.test.pack(side='bottom')\n\n #text\n # Create text widget and specify size. \n self.T = tk.Text(rightBotFrame, height = 20, width = 50, highlightcolor='blue')\n #output = buffer.getvalue()\n self.T.pack(side='bottom', pady=5)\n #self.T.insert(tk.END, robot_list) \n\n # error text\n self.TE = tk.Text(leftBotFrame, height = 20, width =50, fg='red', highlightcolor='red')\n self.TE.pack(side='bottom', pady=5)\n\n #label & button\n self.L1 = tk.Label(leftBotFrame, text=' NOT OK', font='Helvetica 18 bold')\n self.L1.pack(side='left')\n self.B1 = tk.Button(leftBotFrame, text='save log', command=self.press_log_errors)\n self.B1.pack(side='right')\n\n self.L2 = tk.Label(rightBotFrame, text=' OK', font='Helvetica 18 bold' )\n self.L2.pack(side='left')\n self.B2 = tk.Button(rightBotFrame, text='save log', command=self.press_log)\n self.B2.pack(side='right')\n\n #self.threads_running = tk.IntVar()\n #self.LT = tk.Label(leftFrame, textvariable=self.threads_running)\n #self.threads_running.set(threading.active_count())\n #self.LT.pack(side='bottom')\n\n\n def refresh_LT(self):\n self.LT.configure(text='Aktywne połączenia: %i' %(threading.active_count() - 1))\n self.LT.after(1000, self.refresh_LT)\n\n\n def press_log_errors(self):\n with open(save_dir + '//' + 'error_log.txt', 'a') as f:\n f.write(self.TE.get('1.0', 'end'))\n self.TE.delete('1.0', 'end')\n\n def press_log(self):\n with open(save_dir + '//' + 'log.txt', 'a') as f:\n f.write(self.T.get('1.0', 'end'))\n self.T.delete('1.0', 'end')\n\n\n # RadioButtons LEFT\n def choose_n1(self):\n self.cl2.pack_forget()\n self.cl.pack()\n \n def choose_n2(self):\n self.cl.pack_forget()\n self.cl2.pack()\n \n # CHECKLIST\n\n def makeCheckList(self, ASS_List):\n self.cl = tix.CheckList(topFrame, browsecmd=self.selectItem, width=200, height=250,\n options='hlist.columns 1', highlightthickness=1, highlightcolor='#B7D9ED')\n #self.cl.pack()\n self.cl.hlist.config(bg='white', bd=0, selectmode='none', selectbackground='white',\n selectforeground='black', drawbranch=True, pady=1)\n\n for line in ASS_List:\n self.cl.hlist.add(line[0], text=line[0])\n self.cl.setstatus(line[0], 'off')\n for robot in df.loc[:,line[1]].dropna():\n self.cl.hlist.add(str(line[0]) + '.' + str(robot), text=robot)\n self.cl.setstatus(str(line[0]) + '.' + str(robot), 'off')\n \n self.cl.autosetmode()\n\n def makeCheckList2(self, ASS_List):\n self.cl2 = tix.CheckList(topFrame, browsecmd=self.selectItem, width=200, height=250,\n options='hlist.columns 1', highlightthickness=1, highlightcolor='#B7D9ED')\n #self.cl.pack()\n self.cl2.hlist.config(bg='white', bd=0, selectmode='none', selectbackground='white',\n selectforeground='black', drawbranch=True, pady=1)\n\n for line in ASS_List:\n self.cl2.hlist.add(line[0], text=line[0])\n self.cl2.setstatus(line[0], 'off')\n for robot in df.loc[:,line[1]].dropna():\n self.cl2.hlist.add(str(line[0]) + '.' + str(robot), text=robot)\n self.cl2.setstatus(str(line[0]) + '.' + str(robot), 'off')\n \n self.cl2.autosetmode()\n\n ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\n def check_connection(self):\n if self.location not in (list(AL.iloc[:, 0])):\n LINE, ROBOT, IP = get_robot_info(self.location)\n ftp_status, ftp = connect_ftp(IP)\n if ftp_status == True:\n print(f'CONNECTED: {LINE}/{ROBOT} ({IP})')\n self.T.insert(tk.END,f'CONNECTED: {LINE}/{ROBOT} ({IP})\\n')\n ftp.quit()\n else:\n print(f'FTP ERROR: {ftp} {LINE}/{ROBOT} ({IP})')\n self.TE.insert(tk.END, f'FTP ERROR: {ftp} {LINE}/{ROBOT} ({IP})\\n')\n\n def get_cmos(self):\n loc = self.location\n if loc not in (list(AL.iloc[:, 0])):\n LINE, ROBOT, IP = get_robot_info(loc)\n\n save_dir_full = os.path.join(save_dir, LINE, ROBOT)\n if not(os.path.exists(save_dir_full +'/'+'cmosbk.bin')):\n try:\n os.makedirs(save_dir_full)\n except:\n #print('katalog juz istnieje')\n pass\n ftp_status, ftp = connect_ftp(IP)\n if ftp_status == True:\n try:\n ftp.cwd('ROBOT/')\n ftp.cwd('/spdrv')\n except Exception as e:\n self.TE.insert(tk.END, f'CWD ERROR: {e} {LINE}/{ROBOT} ({IP})\\n')\n print(f'CWD ERROR: {e} {LINE}/{ROBOT} ({IP})')\n return -1\n with open(save_dir_full + '//' + 'cmosbk.bin', 'wb') as lf:\n try:\n ftp.retrbinary('RETR ' + 'cmosbk.bin', lf.write)\n self.T.insert(tk.END, (f'SAVED ON: {save_dir_full}\\n'))\n print(f'SAVED ON: {save_dir_full}')\n except Exception as e:\n self.TE.insert(tk.END, f'CMOSBK.BIN ERROR: {e} {LINE}/{ROBOT} ({IP})\\n')\n print(f'CMOSBK.BIN ERROR: {e} {LINE}/{ROBOT} ({IP})')\n ftp.quit()\n else:\n self.TE.insert(tk.END, f'FTP ERROR: {ftp} {LINE}/{ROBOT} ({IP})\\n')\n print(f'FTP ERROR: {ftp} {LINE}/{ROBOT} ({IP})')\n else:\n self.T.insert(tk.END, f'BACKUP EXISTS: {LINE}/{ROBOT} ({IP})\\n')\n print(f'BACKUP EXISTS: {LINE}/{ROBOT} ({IP})')\n\n def get_files(self):\n loc = self.location\n if loc not in (list(AL.iloc[:, 0])):\n LINE, ROBOT, IP = get_robot_info(loc)\n\n save_dir_full = os.path.join(save_dir, LINE, ROBOT)\n if not(os.path.exists(save_dir_full +'/'+'LOG')):\n ftp_status, ftp = connect_ftp(IP)\n if ftp_status == True:\n try:\n ftp.cwd('ROBOT/')\n except Exception as e:\n self.TE.insert(tk.END, f'CWD ERROR: {e} {LINE}/{ROBOT} ({IP})\\n')\n print(f'CWD ERROR: {e} {LINE}/{ROBOT} ({IP})')\n return -1 \n Folder_List = ftp.nlst()\n for folder in Folder_List:\n if not(os.path.exists(save_dir_full +'/'+folder)):\n try:\n os.makedirs(save_dir_full +'/'+folder)\n except:\n #print('katalog juz istnieje')\n pass\n ftp.cwd(folder)\n filenames = ftp.nlst() # get filenames within the directory\n #print('...pobieranie folderu ', folder)\n for filename in filenames:\n local_filename = os.path.join(save_dir_full +'/'+folder+'/'+ filename)\n file = open(local_filename, 'wb')\n try:\n ftp.retrbinary('RETR '+ filename, file.write)\n except Exception as e:\n #self.TE.insert(tk.END, f'DIR ERROR: {e} {LINE}/{ROBOT} ({IP})\\n')\n print(f'DIR ERROR: {e} {LINE}/{ROBOT} ({IP}) : {filename}')\n \n file.close()\n ftp.cwd('..')\n #handle cases when downloading files is blocked:\n\n #good route:\n self.T.insert(tk.END, f'SAVED ON: {save_dir_full}\\n')\n print(f'SAVED ON: {save_dir_full}')\n ftp.quit()\n else:\n self.TE.insert(tk.END, f'FTP ERROR: {ftp} {LINE}/{ROBOT} ({IP})\\n')\n print(f'FTP ERROR: {ftp} {LINE}/{ROBOT} ({IP})')\n else:\n self.T.insert(tk.END, f'FILES EXISTS: {LINE}/{ROBOT} ({IP})\\n')\n print(f'FILES EXISTS: {LINE}/{ROBOT} ({IP})')\n\n def selectItem(self, item):\n if self.cl.winfo_ismapped():\n for line in (ASS_List1):\n if item == line[0]:\n for robot in df.loc[:,line[1]].dropna():\n if self.cl.getstatus(item) == 'on':\n self.cl.setstatus(str(line[0]) + '.' + str(robot), 'on')\n container.add(str(line[0]) + '.' + str(robot))\n if self.cl.getstatus(item) == 'off':\n self.cl.setstatus(str(line[0]) + '.' + str(robot), 'off')\n container.discard(str(line[0]) + '.' + str(robot))\n # Single clicks:\n if self.cl.getstatus(item) == 'on':\n container.add(item)\n if self.cl.getstatus(item) == 'off':\n container.discard(item)\n \n if self.cl2.winfo_ismapped():\n for line in (ASS_List2):\n if item == line[0]:\n for robot in df.loc[:,line[1]].dropna():\n if self.cl2.getstatus(item) == 'on':\n self.cl2.setstatus(str(line[0]) + '.' + str(robot), 'on')\n container.add(str(line[0]) + '.' + str(robot))\n if self.cl2.getstatus(item) == 'off':\n self.cl2.setstatus(str(line[0]) + '.' + str(robot), 'off')\n container.discard(str(line[0]) + '.' + str(robot))\n # Single clicks: \n if self.cl2.getstatus(item) == 'on':\n container.add(item)\n if self.cl2.getstatus(item) == 'off':\n container.discard(item)\n \n def press_select_all(self):\n #check if cl widget is visible\n if self.cl.winfo_ismapped():\n for line in ASS_List1:\n for robot in df.loc[:,line[1]].dropna():\n self.cl.setstatus(str(line[0]), 'on') # check all lines\n self.selectItem(str(line[0]))\n if self.cl2.winfo_ismapped():\n for line in ASS_List2:\n for robot in df.loc[:,line[1]].dropna():\n self.cl2.setstatus(str(line[0]), 'on')\n self.selectItem(str(line[0])) \n \n\n def press_test(self):\n robot_list = list(container)\n # CHECK CONNECTION\n if self.var2.get() == 0:\n for location in robot_list:\n self.location = location\n thread = threading.Thread(target=self.check_connection)\n thread.start()\n\n # GET CMOS \n if self.var2.get() == 1:\n for location in robot_list:\n self.location = location\n thread = threading.Thread(target=self.get_cmos)\n thread.start()\n\n # GET FILES \n if self.var2.get() == 2:\n for location in robot_list:\n self.location = location\n thread = threading.Thread(target=self.get_files)\n thread.start()\n time.sleep(0.01)\n \n # FILES & CMOS\n if self.var2.get() == 3:\n for location in robot_list:\n self.location = location\n thread1 = threading.Thread(target=self.get_cmos)\n thread2 = threading.Thread(target=self.get_files)\n thread1.start()\n thread2.start()\n #self.get_cmos()\nsave_dir = init_date()\ncontainer = set()\n\nbuffer = io.StringIO()\noutput = buffer.getvalue()\nprint (save_dir)\nroot = tix.Tk()\nroot.title('BACKUP MANAGER')\n\ntopFrame = tk.Frame(root)\ntopFrame.pack(side='top')\n\nbottomFrame = tk.Frame(root)\nbottomFrame.pack(side='bottom')\n\nleftBotFrame = tk.Frame(bottomFrame)\nleftBotFrame.pack(side='left')\n\nrightBotFrame = tk.Frame(bottomFrame)\nrightBotFrame.pack(side='right')\n\nleftFrame = tk.Frame(topFrame)\nleftFrame.pack(side='left')\n\nrightFrame = tk.Frame(topFrame)\nrightFrame.pack(side='right')\n\nroot.geometry('1000x800')\n\napp = Application(master=root)\n\n\napp.mainloop()\n","sub_path":"buapp.py","file_name":"buapp.py","file_ext":"py","file_size_in_byte":16475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"634118574","text":"# Product of Array Except Self\n# Given an array nums of n integers where n > 1, return an array output\n# such that output[i] is equal to the product of all the elements of nums except nums[i].\n\n# Example:\n# Input: [1,2,3,4]\n# Output: [24,12,8,6]\n# Constraint: It's guaranteed that the product of the elements of any prefix or suffix\n# of the array (including the whole array) fits in a 32 bit integer.\n\n# Note: Please solve it without division and in O(n).\n# Follow up:\n# Could you solve it with constant space complexity?\n# (The output array does not count as extra space for the purpose of space complexity analysis.)\n# ========================================================================================\n# Algorithm:\n# TC: O(n)\n# SC:\n# ========================================================================================\n\n\n# TC: O(n*n)\n# SC: O(1)\ndef product_except_self_1(nums):\n\n res = []\n\n if not nums:\n return res\n\n for i in range(len(nums)):\n mul = 1\n nums[0], nums[i] = nums[i], nums[0]\n for j in range(1, len(nums)):\n mul *= nums[j]\n res.append(mul)\n return res\n\n\n# Using division\n# TC: O(n)\n# SC: O(1)\ndef product_except_self_2(nums):\n\n res = []\n\n if not nums:\n return res\n\n mul = 1\n for i in range(len(nums)):\n mul *= nums[i]\n\n for i in range(len(nums)):\n mul = mul//nums[i]\n res.append(mul)\n\n return res\n\n\n# Calculating and multiplying left product array and right product array at index i\n# TC: O(n)\n# SC: O(n)\ndef product_except_self_3(nums):\n\n res = []\n\n if not nums:\n return res\n\n left = [nums[0]]\n right = [nums[-1]]\n\n for i in range(1, len(nums)):\n left.append(left[i-1] * nums[i])\n\n nums.reverse()\n for i in range(1, len(nums)):\n right.append(right[i-1] * nums[i])\n\n right.reverse()\n for i in range(len(nums)):\n\n if i == 0:\n res.append(right[i+1])\n if i == len(nums)-1:\n res.append(left[i-1])\n if 0 < i < len(nums)-1:\n res.append(left[i-1] * right[i+1])\n return res\n\n\n# Calculating and multiplying left product array and rigth product array at index i: inplace\n# TC: O(n)\n# SC: O(1)\ndef product_except_self(nums):\n\n if not nums:\n return []\n\n res = [nums[0]]\n # Traverse from left and update output array res\n for i in range(1, len(nums)):\n res.append(res[i-1] * nums[i])\n\n print(res)\n # Traverse from right and update output array res\n product = 1\n for i in range(len(nums)-1, 0, -1):\n res[i] = res[i-1] * product\n product *= nums[i]\n\n res[0] = product\n\n return res\n\n\nif __name__ == \"__main__\":\n\n input_list = [1, 2, 3, 4] # [24, 12, 8, 6]\n print(product_except_self(input_list))\n\n","sub_path":"code/set_1_array/238_product_of_array_except_self.py","file_name":"238_product_of_array_except_self.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"653435002","text":"#AtCoder Beginner Contest 155 class\nN=int(input())\nS=[]\nfor _ in range(N):\n S.append(input())\nS1=list(set(S))\nC=[]\nfor i in S1:\n C.append(S.count(i))\nD=[x for x in S1 if S.count(x) >=max(C)]\nD.sort()\nfor i in D:\n print(i)\n","sub_path":"AtCoder/AtCoder/atcoder8.py","file_name":"atcoder8.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"455947965","text":"from django.contrib import admin\nfrom .models import Empleado, Habilidades\n# Register your models here.\n\nadmin.site.register(Habilidades)\n\nclass EmpleadoAdmin(admin.ModelAdmin): #ordena los campos a mostras en el panel de admin \n list_display =(\n 'id',\n 'first_name',\n 'last_name',\n 'departamento',\n 'job',\n 'full_name', #este campo no existe ene l modelo de bd pero sirve para concatener campos de la tabla ej: nombre y apellido\n )\n\n #\n def full_name(self, obj): #crea el contenido para mostrar en full_name\n #toda la operacion\n print(obj.first_name)\n return obj.first_name + ' ' + obj.last_name\n\n search_fields =('first_name',)#teminamos con una coma // agrega un buscador \n list_filter = ('departamento','job','habilidades',) #agrega un filtro por trajo y habilidades\n #\n filter_horizontal = ('habilidades',) #agrega un buscador a las habilidades //habilidaes viene del modelo persona\n\n\nadmin.site.register(Empleado,EmpleadoAdmin )","sub_path":"applications/personas/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"544454739","text":"from builtins import staticmethod\nimport logging\nimport zlib\n\nfrom mqtt import MqttMessage\n\nfrom workers.base import BaseWorker\nimport logger\n\nREQUIREMENTS = [\"bluepy\"]\n_LOGGER = logger.get(__name__)\n\nSTATE_ON = \"ON\"\nSTATE_OFF = \"OFF\"\n\n\nclass SwitchbotWorker(BaseWorker):\n def _setup(self):\n\n _LOGGER.info(\"Adding %d %s devices\", len(self.devices), repr(self))\n for name, obj in self.devices.items():\n _LOGGER.info(\"Adding %s device '%s' (%s)\", repr(self), name, obj)\n if isinstance(obj, str):\n self.devices[name] = {\"bot\": None, \"state\": STATE_OFF, \"mac\": obj}\n elif isinstance(obj, dict):\n data = obj.get(\"pw\").encode()\n crc = zlib.crc32(data)\n pw = crc.to_bytes(4, 'big')\n self.devices[name] = {\n \"mac\": obj[\"mac\"],\n \"bot\": None,\n \"pw\": pw,\n \"state\": STATE_OFF}\n\n def format_state_topic(self, *args):\n return \"/\".join([self.state_topic_prefix, *args])\n\n def status_update(self):\n from bluepy import btle\n\n ret = []\n _LOGGER.debug(\"Updating %d %s devices\", len(self.devices), repr(self))\n for name, bot in self.devices.items():\n _LOGGER.debug(\"Updating %s device '%s' (%s)\", repr(self), name, bot[\"mac\"])\n try:\n ret += self.update_device_state(name, bot[\"state\"])\n except btle.BTLEException as e:\n logger.log_exception(\n _LOGGER,\n \"Error during update of %s device '%s' (%s): %s\",\n repr(self),\n name,\n bot[\"mac\"],\n type(e).__name__,\n suppress=True,\n )\n return ret\n\n def on_command(self, topic, value):\n from bluepy import btle\n from bluepy.btle import Peripheral\n\n _, _, device_name, _ = topic.split(\"/\")\n\n bot = self.devices[device_name]\n\n value = value.decode(\"utf-8\")\n\n # It needs to be on separate if because first if can change method\n\n _LOGGER.debug(\n \"Setting %s on %s device '%s' (%s)\",\n value,\n repr(self),\n device_name,\n bot[\"mac\"],\n )\n try:\n bot[\"bot\"] = Peripheral(bot[\"mac\"], \"random\")\n hand_service = bot[\"bot\"].getServiceByUUID(\n \"cba20d00-224d-11e6-9fb8-0002a5d5c51b\"\n )\n hand = hand_service.getCharacteristics(\n \"cba20002-224d-11e6-9fb8-0002a5d5c51b\"\n )[0]\n if bot[\"pw\"]:\n cmd = b'\\x57\\x11' + bot[\"pw\"]\n else:\n cmd = b'\\x57\\x01'\n if value == STATE_ON:\n cmd += b'\\x01'\n hand.write(cmd)\n elif value == STATE_OFF:\n cmd += b'\\x02'\n hand.write(cmd)\n elif value == \"PRESS\":\n hand.write(cmd)\n bot[\"bot\"].disconnect()\n except btle.BTLEException as e:\n logger.log_exception(\n _LOGGER,\n \"Error setting %s on %s device '%s' (%s): %s\",\n value,\n repr(self),\n device_name,\n bot[\"mac\"],\n type(e).__name__,\n )\n return []\n\n try:\n return self.update_device_state(device_name, value)\n except btle.BTLEException as e:\n logger.log_exception(\n _LOGGER,\n \"Error during update of %s device '%s' (%s): %s\",\n repr(self),\n device_name,\n bot[\"mac\"],\n type(e).__name__,\n suppress=True,\n )\n return []\n\n def update_device_state(self, name, value):\n return [MqttMessage(topic=self.format_state_topic(name), payload=value)]\n","sub_path":"workers/switchbot.py","file_name":"switchbot.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72658933","text":"from networkx import *\nimport itertools as it\n\n\ndef quick_copy(G, include_isolated=True):\n if G.is_directed():\n if G.is_multigraph():\n H = MultiDiGraph()\n else:\n H = DiGraph()\n else:\n if G.is_multigraph():\n H = MultiGraph()\n else:\n H = Graph()\n\n if ignore_isolated:\n H.add_nodes_from(G.nodes_iter())\n H.add_edges_from(G.edges_iter())\n\n return H\n\n\ndef bfs(G, n):\n return it.chain([n], (e[1] for e in bfs_edges(G, n)))\n\n\ndef dfs(G, n):\n return dfs_preorder_nodes(G, n)\n","sub_path":"solutions/helpers/CodeJam-0.3.0/codejam/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"221256746","text":"import item_db, towns_db, time, combat, functions\r\n#TODO\r\n\r\n\"\"\"\r\n\tNPC/PLAYER STATS:\r\n\t\tStamina = HP, resistance to disease\r\n\t\tCharisma: Dialogue options, persuasion, buy/sell-value.\r\n\t\tAgility: Dodge, better chance to attack first, crit percent\r\n\t\tStrength: Damage with melee, block-chance with shields.\r\n\t\tIntelligence: Damage with spells, crit damage\r\n\t\tAttunement: Buff duration/strength\r\n\t\tStealth: Chance to not be attacked during travel, Chance to sneak into town with weapons equipped, some abilities require this.\r\n\r\n\t\tUpcoming(Maybe):\r\n\r\n\t\tAlchemy: Be able to craft potions etc at crafting stations in certain towns. Includes the ability to search for plants during travel (And in some forest-towns etc)\r\n\t\tBlacksmithing: Be able to craft Armor/weapons at smithing stations in certain towns. Includes the ability to mine ore in certain dungeons.\r\n\t\tTailoring: Be able to craft armor/weapons at tailor stations in certain towns. Includes the ability to tear down cloth armor from enemies to renew into armor.\r\n\t\tLeatherworking: Be able to craft armor/weapons at tanner stations in certain towns. Includes the ability to skin beast / certain enemies.\r\n\t\tEnchanting: Be able to infuse gear with properties such as [Stun on first attack of battle, damage, heal per hit, etc]. Includes being able to disenchant gear for materials.\r\n\t\tPickpocketing: stealing stuff without people noticing (limited per times you can use it).\r\n\r\n\t\tHousekeeping: Being able to rent a vacant plot in a town and stash items, keep a garden, maybe comes with a mine\r\n\r\n\r\n\"\"\"\r\n\r\n\r\n\r\n## SUPER CLASSES ##\r\nclass Human():\r\n\tdef __init__(self, name, health, race):\r\n\t\tself.name = name\r\n\t\tself.health = health\r\n\t\tself.gold = 100\r\n\t\tself.race = race\r\n\t\tself.quests = []\r\n\t\tself.flags = []\r\n\t\tself.boons = []\r\n\t\tself.conditions = []\r\n\t\tself.level = 1\r\n\t\tself.experience = 0\r\n\t\tself.spells_attack = []\r\n\t\tself.spells_buff = []\r\n\t\tself.aligned = \"\"\r\n\t\tself.combat_settings = {\"style\": \"aggressive\",\r\n\t\t\t\t\t\t\t\t\"attack hand\": \"right\",\r\n\t\t\t\t\t\t\t\t\"type\": \"melee\"}\r\n\r\n\tdef speak(self, tone, message):\r\n\t\tif tone == 1:\r\n\t\t\treturn functions.backcolor(\"yellow\", \"{} whispers: {}\".format(self.name, message), fore=True)\r\n\t\tif tone == 2:\r\n\t\t\treturn functions.backcolor(\"yellow\", \"{} says: {}\".format(self.name, message), fore=True)\r\n\t\tif tone == 3:\r\n\t\t\treturn functions.backcolor(\"yellow\", \"{} yells: {}\".format(self.name, message), fore=True, bright=True)\r\n\t\telse:\r\n\t\t\treturn \"SPEAK ERROR SPEAK ERROR SPEAK ERROR\"\r\n\r\n\tdef talk(self, player):\r\n\t\tprint(\"This person doesn't like to speak.\")\r\n\r\nclass Vendor(Human):\r\n\tdef __init__(self, name, health, race):\r\n\t\tself.trade_opener = \"\"\r\n\r\n\t\tsuper().__init__(name, health, race)\r\n\r\n\tdef trade(self, player):\r\n\t\tprint(self.trade_opener)\r\n\t\tprint(\"What would you like to have a look at?\")\r\n\t\twhile True:\r\n\t\t\tprint()\r\n\t\t\tback = False\r\n\t\t\tfor place, item in enumerate([\"Armor\", \"Weapons\", \"Consumables\", \"Misc\"]):\r\n\t\t\t\tprint(place + 1, \": \", item)\r\n\t\t\tprint()\r\n\t\t\task_slot = input(\"> \")\r\n\t\t\tif ask_slot.lower() in [\"exit\", \"e\"]:\r\n\t\t\t\tbreak\r\n\t\t\ttry:\r\n\t\t\t\task_slot = int(ask_slot)\r\n\t\t\t\tif ask_slot not in [1,2,3,4]:\r\n\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\tcontinue\r\n\t\t\texcept ValueError:\r\n\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\tcontinue\r\n\t\t\tif ask_slot == 1:\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tif not self.armor_list:\r\n\t\t\t\t\t\tprint(\"No armor for sale.\")\r\n\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tfor place, item in enumerate(self.armor_list):\r\n\t\t\t\t\t\tprint(\"{}: {} - {} gold.\".format(place, item.name, item.value * 2))\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\task_buy = input(\"Type the index of the item you want to look at.\\n >\")\r\n\t\t\t\t\tif ask_buy in [\"exit\", \"e\"]:\r\n\t\t\t\t\t\treturn\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\task_buy = int(ask_buy)\r\n\t\t\t\t\t\tif ask_buy not in range(0,len(self.armor_list)):\r\n\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tprint(self.armor_list[ask_buy])\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\task_do = int(input(\"Do you want to buy this item? (You have {} gold)\\n1: Yes\\n2: No\\n> \".format(player.gold)))\r\n\t\t\t\t\t\t\tif ask_do not in [1,2]:\r\n\t\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\t\tif ask_do == 1:\r\n\t\t\t\t\t\t\t\tif player.gold >= self.armor_list[ask_buy].value * 2:\r\n\t\t\t\t\t\t\t\t\tplayer.inventory_armor.append(self.armor_list[ask_buy])\r\n\t\t\t\t\t\t\t\t\tplayer.gold -= self.armor_list[ask_buy].value * 2\r\n\t\t\t\t\t\t\t\t\tprint(\"Purchase completed\")\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tprint(\"You cannot afford that.\")\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\tif ask_do == 2:\r\n\t\t\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tbreak\r\n\t\t\t\tif back:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\treturn\r\n\t\t\tif ask_slot == 2:\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tif not self.weapons_list:\r\n\t\t\t\t\t\tprint(\"No weapons for sale.\")\r\n\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tfor place, item in enumerate(self.weapons_list):\r\n\t\t\t\t\t\tprint(\"{}: {} - {} gold.\".format(place, item.name, item.value * 2))\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\task_buy = input(\"Type the index of the item you want to look at.\\n >\")\r\n\t\t\t\t\tif ask_buy in [\"exit\", \"e\"]:\r\n\t\t\t\t\t\treturn\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\task_buy = int(ask_buy)\r\n\t\t\t\t\t\tif ask_buy not in range(0,len(self.weapons_list)):\r\n\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tprint(self.weapons_list[ask_buy])\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\task_do = int(input(\"Do you want to buy this item? (You have {} gold)\\n1: Yes\\n2: No\\n> \".format(player.gold)))\r\n\t\t\t\t\t\t\tif ask_do not in [1,2]:\r\n\t\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\t\tif ask_do == 1:\r\n\t\t\t\t\t\t\t\tif player.gold >= self.weapons_list[ask_buy].value * 2:\r\n\t\t\t\t\t\t\t\t\tplayer.inventory_weapons.append(self.weapons_list[ask_buy])\r\n\t\t\t\t\t\t\t\t\tplayer.gold -= self.weapons_list[ask_buy].value * 2\r\n\t\t\t\t\t\t\t\t\tprint(\"Purchase completed\")\r\n\t\t\t\t\t\t\t\t\task_more = input(\"Want to keep shopping?\")\r\n\t\t\t\t\t\t\t\t\tif ask_more == \"yes\":\r\n\t\t\t\t\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tprint(\"You cannot afford that.\")\r\n\t\t\t\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\t\tif ask_do == 2:\r\n\t\t\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tbreak\r\n\t\t\t\tif back:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\treturn\r\n\t\t\tif ask_slot == 3:\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tif not self.consumables_list:\r\n\t\t\t\t\t\tprint(\"No consumables for sale.\")\r\n\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tfor place, item in enumerate(self.consumables_list):\r\n\t\t\t\t\t\tprint(\"{}: {} - {} gold.\".format(place, item.name, item.value * 2))\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\task_buy = input(\"Type the index of the item you want to look at.\\n >\")\r\n\t\t\t\t\tif ask_buy in [\"exit\", \"e\"]:\r\n\t\t\t\t\t\treturn\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\task_buy = int(ask_buy)\r\n\t\t\t\t\t\tif ask_buy not in range(0,len(self.consumables_list)):\r\n\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tprint(self.consumables_list[ask_buy])\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\task_do = int(input(\"Do you want to buy this item? (You have {} gold)\\n1: Yes\\n2: No\\n> \".format(player.gold)))\r\n\t\t\t\t\t\t\tif ask_do not in [1,2]:\r\n\t\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\t\tif ask_do == 1:\r\n\t\t\t\t\t\t\t\tif player.gold >= self.consumables_list[ask_buy].value * 2:\r\n\t\t\t\t\t\t\t\t\tplayer.inventory_consumables.append(self.consumables_list[ask_buy])\r\n\t\t\t\t\t\t\t\t\tplayer.gold -= self.consumables_list[ask_buy].value * 2\r\n\t\t\t\t\t\t\t\t\tprint(\"Purchase completed\")\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tprint(\"You cannot afford that.\")\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\tif ask_do == 2:\r\n\t\t\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tbreak\r\n\t\t\t\tif back:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\treturn\r\n\t\t\tif ask_slot == 3:\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tif not self.misc_list:\r\n\t\t\t\t\t\tprint(\"No other things for sale.\")\r\n\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tfor place, item in enumerate(self.misc_list):\r\n\t\t\t\t\t\tprint(\"{}: {} - {} gold.\".format(place, item.name, item.value * 2))\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\task_buy = input(\"Type the index of the item you want to look at.\\n >\")\r\n\t\t\t\t\tif ask_buy in [\"exit\", \"e\"]:\r\n\t\t\t\t\t\treturn\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\task_buy = int(ask_buy)\r\n\t\t\t\t\t\tif ask_buy not in range(0,len(self.misc_list)):\r\n\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tprint(self.misc_list[ask_buy])\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\twhile True:\r\n\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\task_do = int(input(\"Do you want to buy this item? (You have {} gold)\\n1: Yes\\n2: No\\n> \".format(player.gold)))\r\n\t\t\t\t\t\t\tif ask_do not in [1,2]:\r\n\t\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\t\tif ask_do == 1:\r\n\t\t\t\t\t\t\t\tif player.gold >= self.misc_list[ask_buy].value * 2:\r\n\t\t\t\t\t\t\t\t\tplayer.inventory_misc.append(self.misc_list[ask_buy])\r\n\t\t\t\t\t\t\t\t\tplayer.gold -= self.misc_list[ask_buy].value * 2\r\n\t\t\t\t\t\t\t\t\tprint(\"Purchase completed\")\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tprint(\"You cannot afford that.\")\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\tif ask_do == 2:\r\n\t\t\t\t\t\t\t\tback = True\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\tbreak\r\n\t\t\t\tif back:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\treturn\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n######################### PLAYER CLASSES ##############################\r\nclass_list = [\"Warrior\", \"Mage\", \"Thief\"] #strings only, needed for choosing class in functions.py\r\nclass Warrior(Human):\r\n\tdef __init__(self, name, race):\r\n\t\tself.name = name\r\n\t\tself.class_name = \"Warrior\"\r\n\t\tself.current_place = towns_db.StarterTownCentre_Start()\r\n\r\n\t\t# ARMOR & WEAPONS #\r\n\t\tself.eq_head = False\r\n\t\tself.eq_chest = item_db.PlateArmor()\r\n\t\tself.eq_legs = item_db.PlateLegs()\r\n\t\tself.eq_feet = item_db.PlateBoots()\r\n\t\tself.eq_glove = item_db.PlateGloves()\r\n\t\tself.eq_right_hand = item_db.WoodenSword()\r\n\t\tself.eq_left_hand = item_db.WoodenShield()\r\n\t\tself.eq_list = [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]\r\n\r\n\t\t# INVENTORY #\r\n\t\tself.inventory_weapons = [item_db.WoodenSword_2h()]\r\n\t\tself.inventory_armor = [item_db.PlateHelmet()]\r\n\t\tself.inventory_consumables = [item_db.Bread()]\r\n\t\tself.inventory_misc = []\r\n\t\tself.inventory_list = [self.inventory_weapons, self.inventory_armor, self.inventory_consumables, self.inventory_misc]\r\n\r\n\t\t# ATTRIBUTES #\r\n\t\tself.stamina = 2\r\n\t\tself.charisma = 2\r\n\t\tself.agility = 1\r\n\t\tself.strength = 4\r\n\t\tself.intelligence = 1\r\n\t\tself.attunement = 0\r\n\t\tself.stealth = 0\r\n\r\n\t\t# SPELLS #\r\n\t\tself.eq_spells = [combat.SpellsHeavyStrike()]\r\n\t\tself.spells = [combat.SpellsHeavyStrike()]\r\n\t\t\r\n\t\tsuper().__init__(self.name, self.stamina * 10, race)\r\n\r\n\tdef get_damage(self):\r\n\t\tlista = []\r\n\t\tfor item in [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]:\r\n\t\t\tif item == False:\r\n\t\t\t\tcontinue\r\n\t\t\telse:\r\n\t\t\t\tlista.append(item.damage)\r\n\r\n\t\treturn sum(lista)\r\n\r\n\tdef get_defence(self):\r\n\t\tlista = []\r\n\t\tfor item in [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]:\r\n\t\t\tif item == False:\r\n\t\t\t\tcontinue\r\n\t\t\telse:\r\n\t\t\t\tlista.append(item.defence)\r\n\r\n\t\treturn sum(lista)\r\n\r\n\tdef get_max_health(self):\r\n\t\treturn self.stamina * 10\r\n\r\nclass Mage(Human):\r\n\tdef __init__(self, name, race):\r\n\t\tself.name = name\r\n\t\tself.class_name = \"Mage\"\r\n\t\tself.current_place = towns_db.StarterTownCentre_Start()\r\n\r\n\t\t# ARMOR & WEAPONS #\r\n\t\tself.eq_head = False\r\n\t\tself.eq_chest = item_db.ClothRobe()\r\n\t\tself.eq_legs = item_db.ClothPants()\r\n\t\tself.eq_feet = item_db.LeatherBoots()\r\n\t\tself.eq_glove = item_db.ClothGloves()\r\n\t\tself.eq_right_hand = item_db.WoodenWand()\r\n\t\tself.eq_left_hand = item_db.BasicTome()\r\n\t\tself.eq_list = [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]\r\n\r\n\t\t# INVENTORY #\r\n\t\tself.inventory_weapons = [item_db.WoodenStaff()]\r\n\t\tself.inventory_armor = [item_db.ClothFurCap()]\r\n\t\tself.inventory_consumables = [item_db.Apple()]\r\n\t\tself.inventory_misc = []\r\n\t\tself.inventory_list = [self.inventory_weapons, self.inventory_armor, self.inventory_consumables, self.inventory_misc]\r\n\r\n\t\t# ATTRIBUTES #\r\n\t\tself.stamina = 1\r\n\t\tself.charisma = 1\r\n\t\tself.agility = 0\r\n\t\tself.strength = 1\r\n\t\tself.intelligence = 4\r\n\t\tself.attunement = 2\r\n\t\tself.stealth = 1\r\n\r\n\t\t# SPELLS #\r\n\t\tself.eq_spells = [combat.SpellsArcaneStrike()]\r\n\t\tself.spells = [combat.SpellsArcaneStrike()]\r\n\r\n\t\tsuper().__init__(self.name, self.stamina * 10, race)\r\n\r\n\tdef get_damage(self):\r\n\t\tlista = []\r\n\t\tfor item in [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]:\r\n\t\t\tif item == False:\r\n\t\t\t\tcontinue\r\n\t\t\telse:\r\n\t\t\t\tlista.append(item.damage)\r\n\r\n\t\treturn sum(lista)\r\n\r\n\tdef get_defence(self):\r\n\t\tlista = []\r\n\t\tfor item in [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]:\r\n\t\t\tif item == False:\r\n\t\t\t\tcontinue\r\n\t\t\telse:\r\n\t\t\t\tlista.append(item.defence)\r\n\r\n\t\treturn sum(lista)\r\n\r\n\tdef get_max_health(self):\r\n\t\treturn self.stamina * 10\r\n\r\nclass Thief(Human):\r\n\tdef __init__(self, name, race):\r\n\t\tself.name = name\r\n\t\tself.class_name = \"Thief\"\r\n\t\tself.current_place = towns_db.StarterTownCentre_Start()\r\n\r\n\t\t# ARMOR & WEAPONS #\r\n\t\tself.eq_head = False\r\n\t\tself.eq_chest = item_db.LeatherArmor()\r\n\t\tself.eq_legs = item_db.LeatherPants()\r\n\t\tself.eq_feet = item_db.LeatherHardBoots()\r\n\t\tself.eq_glove = item_db.LeatherGloves()\r\n\t\tself.eq_right_hand = item_db.WoodDagger()\r\n\t\tself.eq_left_hand = item_db.WoodDagger()\r\n\t\tself.eq_list = [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]\r\n\r\n\t\t# INVENTORY #\r\n\t\tself.inventory_weapons = []\r\n\t\tself.inventory_armor = [item_db.LeatherHelmet()]\r\n\t\tself.inventory_consumables = [item_db.Bread()]\r\n\t\tself.inventory_misc = []\r\n\t\tself.inventory_list = [self.inventory_weapons, self.inventory_armor, self.inventory_consumables, self.inventory_misc]\r\n\r\n\t\t# ATTRIBUTES #\r\n\t\tself.stamina = 1\r\n\t\tself.charisma = 0\r\n\t\tself.agility = 4\r\n\t\tself.strength = 3\r\n\t\tself.intelligence = 0\r\n\t\tself.attunement = 0\r\n\t\tself.stealth = 2\r\n\r\n\t\t# SPELLS #\r\n\t\tself.eq_spells = []\r\n\t\tself.spells = []\r\n\r\n\r\n\t\tsuper().__init__(self.name, self.stamina * 10, race)\r\n\r\n\tdef get_damage(self):\r\n\t\tlista = []\r\n\t\tfor item in [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]:\r\n\t\t\tif item == False:\r\n\t\t\t\tcontinue\r\n\t\t\telse:\r\n\t\t\t\tlista.append(item.damage)\r\n\r\n\t\treturn sum(lista)\r\n\r\n\tdef get_defence(self):\r\n\t\tlista = []\r\n\t\tfor item in [self.eq_head, self.eq_chest, self.eq_legs, self.eq_feet, self.eq_glove, self.eq_right_hand, self.eq_left_hand]:\r\n\t\t\tif item == False:\r\n\t\t\t\tcontinue\r\n\t\t\telse:\r\n\t\t\t\tlista.append(item.defence)\r\n\r\n\t\treturn sum(lista)\r\n\r\n\tdef get_max_health(self):\r\n\t\treturn self.stamina * 10\r\n\r\n\r\n\r\n######################### NPC CLASSES ##############################\r\n\r\n# STARTER TOWN #\r\n\r\n# VENDORS #\r\n\r\nclass VendorKerBeros(Vendor):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Ker Beros\"\r\n\t\tself.title = \"The Rugged Mage\"\r\n\t\tself.description = \"A rugged old mage, looks like he is upon the brink of death, but according to him he is as fit as ever.\"\r\n\t\tself.armor_list = [item_db.ClothFurCap()]\r\n\t\tself.weapons_list = [item_db.WoodenStaff()]\r\n\t\tself.consumables_list = [item_db.Apple()]\r\n\t\tself.misc_list = [item_db.ShinyRock()]\r\n\t\tsuper().__init__(self.name, 100, \"Human\")\r\n\r\n\tdef talk(self, player):\r\n\t\tif \"KerBeros_Done\" in player.quests:\r\n\t\t\tprint(self.speak(2, \"#TODO QUEST DONE TEXT\"))\r\n\t\telse:\r\n\t\t\tprint(self.speak(2, \"I can feel your magic aura friend, mind helping me out with a mission, I could use someone like you.\"))\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint()\r\n\t\t\task_start_quest = functions.validate_input(\"> \", [\"Yes\", \"No\"])\r\n\t\t\tprint(ask_start_quest)\r\n\r\nclass VendorTheRock(Vendor):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Osk 'The Rock' Ghar\"\r\n\t\tself.title = \"Blacksmith\"\r\n\t\tself.description = \"A burly orc with a passion for smithing, the first orc to voluntarily venture into town in peace for over a hundred years!\"\r\n\t\tself.armor_list = [item_db.PlateHelmet(), item_db.PlateArmor(), item_db.PlateLegs(), item_db.PlateGloves(), item_db.PlateBoots()]\r\n\t\tself.weapons_list = [item_db.WoodenSword_2h()]\r\n\t\tself.consumables_list = []\r\n\t\tself.misc_list = []\r\n\t\tsuper().__init__(self.name, 100, \"Orc\")\r\n\r\n\tdef talk(self, player):\r\n\t\tif \"TheRock_Done\" in player.quests:\r\n\t\t\tprint(self.speak(2, \"Thanks for helping me get rid of those 'murderous ghouls' before.\"))\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint()\r\n\t\t\tprint(self.speak(2, \"I'll let you take an item from the chest over there in the corner as a reward for your help.\"))\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint()\r\n\t\t\tprint(functions.context(\"\t\t[Osk'Ghar walks over and opens the lock on the chest.]\"))\r\n\t\t\tprint()\r\n\r\n\t\telif \"TheRock_Started\" in player.quests:\r\n\t\t\tprint(self.speak(2, \"Have you had time to look at the 'monster' problem yet?\"))\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint(self.speak(2, \"It's starting to sound like I have a whole horde of ghouls down there with all the hustling around.\"))\r\n\t\t\tprint()\r\n\t\telse:\r\n\t\t\tprint(self.speak(2,\"Hi there traveler, looking for some wares?\"))\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint(self.speak(2,\"I've developed an addiction for smithing, so there's always armors and weapons to buy.\"))\r\n\t\t\ttime.sleep(1)\r\n\t\t\tif player.class_name == \"Warrior\":\r\n\t\t\t\tprint(self.speak(2,\"Say, you seem like a brute guy, would you mind helping me out with this monster problem I have in my cellar?\"))\r\n\t\t\t\ttime.sleep(1)\r\n\t\t\t\twhile True:\r\n\t\t\t\t\task_start_quest = input(\"1: Yes\\n2: No\\n> \")\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\tif ask_start_quest in [\"exit\", \"e\"]:\r\n\t\t\t\t\t\treturn\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\task_start_quest = int(ask_start_quest)\r\n\t\t\t\t\t\tif ask_start_quest == 1:\r\n\t\t\t\t\t\t\tplayer.quests.append(\"TheRock_Started\")\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\tif ask_start_quest == 2:\r\n\t\t\t\t\t\t\tprint(self.speak(2, \"That's too bad, I'm a bit embarrased and I could really use some help.\"))\r\n\t\t\t\t\t\t\tprint()\r\n\t\t\t\t\t\t\treturn\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\tprint(\"Please type a number\")\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\tprint(self.speak(2,\"Wonderful, so here the problem...\"))\r\n\t\t\t\ttime.sleep(1)\r\n\t\t\t\tprint(functions.context(\"\t\t[Osk hesitates and looks around him to make sure you are alone before he continues to speak]\"))\r\n\t\t\t\ttime.sleep(1)\r\n\t\t\t\tprint(self.speak(1,\"There are rats, everywhere.\"))\r\n\t\t\t\ttime.sleep(1)\r\n\t\t\t\tprint(self.speak(1,\"An orc can't speak out loud that he's afraid rats, but I swear I saw one as big as a sheep down there!\"))\r\n\t\t\t\ttime.sleep(1)\r\n\t\t\t\tprint(self.speak(2,\"You can always find me here when you are done, or perhaps to buy some weapons to help slay them!\"))\r\n\t\t\t\ttime.sleep(1)\r\n\r\n\r\nclass VendorEvanKripter(Vendor):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Evan Kripter\"\r\n\t\tself.title = \"Leatherworker\"\r\n\t\tself.description = \"His family has lived in this small town since generations back, his father was the first one pick up the art of leatherworking after the War 40 years ago killed the last one.\"\r\n\t\tself.armor_list = [item_db.LeatherHelmet(), item_db.LeatherArmor(), item_db.LeatherPants(), item_db.LeatherGloves(), item_db.LeatherBoots()]\r\n\t\tself.weapons_list = []\r\n\t\tself.consumables_list = []\r\n\t\tself.misc_list = []\r\n\t\tsuper().__init__(self.name, 100, \"Human\")\r\n\r\nclass VendorAlanPryvot(Vendor):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Alan Pryvot\"\r\n\t\tself.title = \"Bakingstall owner.\"\r\n\t\tself.description = \"The jolly baker in town, sells all things made from bread.\"\r\n\t\tself.armor_list = []\r\n\t\tself.weapons_list = []\r\n\t\tself.consumables_list = [item_db.Bread()]\r\n\t\tself.misc_list = []\r\n\t\tsuper().__init__(self.name, 100, \"Human\")\r\n\r\n# TOWNSFOLK #\r\n\r\n# GUARDS #\r\nclass GuardErolKipman(Human):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Erol Kipman\"\r\n\t\tself.title = \"Borderguard\"\r\n\t\tself.description = \"One of the fiercer guards here in STARTER_TOWN, don't mess with the law if he is close.\"\r\n\t\tsuper().__init__(self.name, 100, \"Human\")\r\n\r\n# HALL OF JUSTICE #\r\nclass HOJBeccaLithe(Human):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Becca Lithe\"\r\n\t\tself.title = \"HoJ Receptionist\"\r\n\t\tself.description = \"Receptionist at the Hall of Justice\"\r\n\t\tsuper().__init__(self.name, 100, \"Human\")\r\n\r\nclass HOJLeifDunder(Human):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Leif Dunder\"\r\n\t\tself.title = \"HOJ Minister\"\r\n\t\tself.description = \"Minister at the Hall of Justice. An old man wearing a black robe in contrast to his grey, bushy, beard.\"\r\n\t\tsuper().__init__(self.name, 100, \"Human\")\r\n\r\n# MARKET #\r\nclass CitizenAbbyroQuatz(Human):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Abyrro Quatz\"\r\n\t\tself.title = \"Traveler\"\r\n\t\tself.description = \"Rugged traveler from far away, god knows what he is doing here in small STARTER TOWN.\"\r\n\t\tsuper().__init__(self.name, 100, \"Human\")\r\n\r\n\tdef talk(self, player):\r\n\t\tif \"AbyrroQuatz_Done\" in player.quests:\r\n\t\t\tprint(self.speak(2, \"Thanks for getting that bread for me earlier, it really helped a lot.\")) # ADD VALUABLE INFORMATION HERE AFTER Q IS DONE\r\n\t\t\tprint()\r\n\r\n\t\telif \"AbyrroQuatz_Started\" in player.quests:\r\n\t\t\tprint(self.speak(2, \"Have you had the time to get me that bread yet?\"))\r\n\t\t\tprint()\r\n\t\t\ttime.sleep(1)\r\n\t\t\twhile True:\r\n\t\t\t\task_done_quest = input(\"1: Yes\\n2: No\\n> \")\r\n\t\t\t\tif ask_done_quest in [\"exit\", \"e\"]:\r\n\t\t\t\t\treturn\r\n\t\t\t\ttry:\r\n\t\t\t\t\task_done_quest = int(ask_done_quest)\r\n\t\t\t\t\tif ask_done_quest == 1:\r\n\t\t\t\t\t\tif \"Bread\" in [x.name for x in player.inventory_consumables]:\r\n\t\t\t\t\t\t\tfor place, item in enumerate(player.inventory_consumables):\r\n\t\t\t\t\t\t\t\tif item.name == \"Bread\":\r\n\t\t\t\t\t\t\t\t\tdel player.inventory_consumables[place]\r\n\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\tplayer.quests.remove(\"AbyrroQuatz_Started\")\r\n\t\t\t\t\t\t\tplayer.quests.append(\"AbyrroQuatz_Done\")\r\n\t\t\t\t\t\t\tprint()\r\n\t\t\t\t\t\t\ttime.sleep(1)\r\n\t\t\t\t\t\t\tprint(functions.backcolor(\"magenta\",\"\t\t[1 piece of bread has been removed from your inventory.]\", fore=True))\r\n\t\t\t\t\t\t\tprint()\r\n\t\t\t\t\t\t\ttime.sleep(1)\r\n\t\t\t\t\t\t\tprint(self.speak(2, \"I am very grateful for this.\"))\r\n\t\t\t\t\t\t\tbreak\r\n\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tprint(self.speak(2, \"I do not see any bread with you, are you trying to decieve me?\"))\r\n\t\t\t\t\t\t\treturn\r\n\t\t\t\texcept ValueError:\r\n\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\tcontinue\r\n\t\t\t\tbreak\r\n\r\n\t\telse:\r\n\t\t\tprint(self.speak(2, \"You look just as much as an outsider here as I do, would you mind helping me out with something?\"))\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint()\r\n\t\t\twhile True:\r\n\t\t\t\task_start_quest = input(\"1: Yes\\n2: No\\n> \")\r\n\t\t\t\tprint()\r\n\t\t\t\tif ask_start_quest in [\"exit\", \"e\"]:\r\n\t\t\t\t\treturn\r\n\t\t\t\ttry:\r\n\t\t\t\t\task_start_quest = int(ask_start_quest)\r\n\t\t\t\t\tif ask_start_quest == 1:\r\n\t\t\t\t\t\tplayer.quests.append(\"AbyrroQuatz_Started\")\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tif ask_start_quest == 2:\r\n\t\t\t\t\t\tprint(self.speak(2, \"That's a shame, I was really hoping you would help me out.\"))\r\n\t\t\t\t\t\tprint()\r\n\t\t\t\t\t\treturn\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\texcept ValueError:\r\n\t\t\t\t\tprint(\"Please type a number\")\r\n\t\t\t\t\tcontinue\r\n\t\t\tprint(self.speak(2, \"You know the breadmaker in town, Alan whats-his-name, he has taken a disliking to me.\"))\r\n\t\t\tprint()\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint(self.speak(2, \"So I was wondering, could you buy some bread for me, that'll keep me fed for a couple of days atleast.\"))\r\n\t\t\tprint()\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint(self.speak(2, \"Here, take this gold, I won't make you buy it with your own money, meet me here afterwards.\"))\r\n\t\t\tprint()\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint(\"\t\t[Abyrro hands you 2 gold coins he dug up from inside his robe.]\")\r\n\t\t\tprint()\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint(self.speak(1, \"But don't tell him I sent you...\"))\r\n\t\t\ttime.sleep(1)\r\n\t\t\tprint()\r\n\t\t\tif \"Bread\" in [x.name for x in player.inventory_consumables]:\r\n\t\t\t\tprint(self.speak(2, \"Oh, you already have a loaf of bread with you?\"))\r\n\t\t\t\tprint()\r\n\t\t\t\ttime.sleep(1)\r\n\t\t\t\tprint(self.speak(2, \"Would you be able to give me that? I have already paid you.\"))\r\n\t\t\t\twhile True:\r\n\t\t\t\t\task_give = input(\"1: Yes\\n2: No\\n> \")\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\task_give = int(ask_give)\r\n\t\t\t\t\t\tif ask_give == 1:\r\n\t\t\t\t\t\t\tfor place, item in enumerate(player.inventory_consumables):\r\n\t\t\t\t\t\t\t\tif item.name == \"Bread\":\r\n\t\t\t\t\t\t\t\t\tdel player.inventory_consumables[place]\r\n\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\tprint(self.speak(2, \"Thank you so much!\"))\r\n\t\t\t\t\t\t\tprint()\r\n\t\t\t\t\t\t\tplayer.quests.remove(\"AbyrroQuatz_Started\")\r\n\t\t\t\t\t\t\tplayer.quests.append(\"AbyrroQuatz_Done\")\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\tif ask_give == 2:\r\n\t\t\t\t\t\t\tprint(self.speak(2, \"I am sorry to have asked you. \"))\r\n\t\t\t\t\t\t\tprint()\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tprint(\"Please type a valid number.\")\r\n\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\tprint(\"Please type a number.\")\r\n\t\t\t\t\t\tcontinue\r\n\t\treturn\r\n\r\n\r\n## CHURCH ##\r\n\r\nclass StarterTownChurchStatue(Human):\r\n\tdef __init__(self):\r\n\t\tself.name = \"Statue of Mux'Ton, God of Terror\"\r\n\t\tself.title = \"Statue\"\r\n\t\tself.description = \"Statue in honor of Mux'Ton, the God of Terror which \\nsupposedly helped the people in this town during \\nthe War 40 years ago.\"\r\n\t\tsuper().__init__(self.name, 100, \"Human\")\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tg = globals().copy()\r\n\r\n\tfor name, obj in g.items():\r\n\t\tif isinstance(obj, type):\r\n\t\t\ttry:\r\n\t\t\t\tprint(obj().name)\r\n\t\t\texcept TypeError:\r\n\t\t\t\tpass\r\n","sub_path":"alpha/npc_db.py","file_name":"npc_db.py","file_ext":"py","file_size_in_byte":25356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"487631961","text":"#a python script that performs creation of table and insert, select, delete and update operations on that created table\n\nimport MySQLdb\n\ndef createtable():\n # Open database connection\n db = MySQLdb.connect(\"localhost\", \"USERNAME\", \"PASWORD\", \"DATABASENAME\")\n\n # prepare a cursor object using cursor() method\n cursor = db.cursor()\n\n # Drop table if it already exist using execute() method.\n cursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\n\n # Create table as per requirement\n sql = \"\"\"CREATE TABLE EMPLOYEE (\n FIRST_NAME CHAR(50),\n LAST_NAME CHAR(50),\n AGE INT, \n SEX CHAR(1) )\"\"\"\n\n cursor.execute(sql)\n # disconnect from server\n db.close()\n\ndef insertrecord():\n # Open database connection\n db = MySQLdb.connect(\"localhost\", \"USERNAME\", \"PASWORD\", \"DATABASENAME\")\n\n # prepare a cursor object using cursor() method\n cursor = db.cursor()\n\n # Prepare SQL query to INSERT a record into the database.\n sql = \"\"\"INSERT INTO EMPLOYEE(FIRST_NAME,\n LAST_NAME, AGE, SEX)\n VALUES ('Ketul', 'Patel', 25, 'M')\"\"\"\n try:\n # Execute the SQL command\n cursor.execute(sql)\n # Commit your changes in the database\n db.commit()\n except:\n # Rollback in case there is any error\n db.rollback()\n\n # disconnect from server\n db.close()\n\ndef readrecord():\n db = MySQLdb.connect(\"localhost\", \"USERNAME\", \"PASWORD\", \"DATABASENAME\")\n\n cursor = db.cursor()\n\n sql = \"SELECT * FROM EMPLOYEE WHERE AGE > '%d'\" % (20)\n try:\n # Execute the SQL command\n cursor.execute(sql)\n # Fetch all the rows in a list of lists.\n results = cursor.fetchall()\n for row in results:\n fname = row[0]\n lname = row[1]\n age = row[2]\n sex = row[3]\n # Now print fetched result\n print(\"fname={0},lname={1},age={2},sex={3}\".format(fname, lname, age, sex))\n except:\n print (\"Error: unable to fecth data\")\n\n db.close()\n\ndef deletedata():\n db = MySQLdb.connect(\"localhost\", \"USERNAME\", \"PASWORD\", \"DATABASENAME\")\n\n cursor = db.cursor()\n\n # Prepare SQL query to DELETE required records\n sql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (50)\n try:\n cursor.execute(sql)\n db.commit()\n except:\n db.rollback()\n\n db.close()\n\ndef updaterecord():\n db = MySQLdb.connect(\"localhost\", \"USERNAME\", \"PASWORD\", \"DATABASENAME\")\n cursor = db.cursor()\n\n # Prepare SQL query to UPDATE required records\n sql = \"UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'\" % ('M')\n\n\n try:\n cursor.execute(sql)\n db.commit()\n except:\n db.rollback()\n\n db.close()\n\n\ncreatetable()\ninsertrecord()\nreadrecord()\nupdaterecord()\ndeletedata()\n\n#I actually dont have MySql Database on my mac so just wrote the program as per my knowledge.\n#You might need to provide Username User Password and Database Name\n","sub_path":"ThirdAssignment/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"80554588","text":"import time\nimport unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\nclass PythonOrSearch(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome(r'C:\\_Software\\chromedriver.exe')\n self.driver.implicitly_wait(5)\n\n def test_search_in_python_org(self):\n driver = self.driver\n driver.get(\"http://localhost/VK6/Login.aspx?tc=singapore\")\n print('Page Title: ', driver.title)\n elem = driver.find_element_by_id(\"idUserName\")\n elem.send_keys(\"admin\", Keys.TAB)\n elem.send_keys(Keys.TAB)\n elem = driver.find_element_by_id(\"idPassword\")\n elem.send_keys(\"pw\")\n elem = driver.find_element_by_id(\"idSignin\")\n elem.click()\n\n wait = WebDriverWait(driver, 10)\n elements = wait.until(\n EC.element_to_be_clickable((By.CLASS_NAME, 'dropdown-toggle')))\n print('Page Title: ', driver.title)\n print('element: ', elements)\n # logout = driver.find_element_by_xpath(\n # \"//ul[li[a/@href='/VK6/Logout.aspx']]]\")\n # logout.click()\n driver.get(\"http://localhost/VK6/Logout.aspx\")\n logout = wait.until(EC.element_to_be_clickable(\n (By.ID, 'ctl00_ContentPlaceHolder1_btnLogout')))\n logout.click()\n time.sleep(5)\n\n def tearDown(self):\n self.driver.quit()\n\n\nclass element_has_css_class(object):\n \"\"\"An expectation for checking that an element has a particular css class.\n\n locator - used to find the element\n returns the WebElement once it has the particular css class\n \"\"\"\n\n def __init__(self, locator, css_class):\n self.locator = locator\n self.css_class = css_class\n\n def __call__(self, driver):\n # Finding the referenced element\n element = driver.find_element(*self.locator)\n if self.css_class in element.get_attribute(\"class\"):\n return element\n else:\n return False\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Python/Advance/Selenium_0412.py","file_name":"Selenium_0412.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"195996979","text":"import requests as r\nfrom bs4 import BeautifulSoup\n\n\nclass Crawler:\n \"\"\"\n Generator that continuously yields the next link. Note that it does not check for loops, so infinite loops\n need to be prevented elsewhere.\n \"\"\"\n\n def __init__(self, start, maximum_number_of_hops=100, full_text=False, user_agent=None,\n destination='Philosophy', base_url=\"https://en.wikipedia.org/w/api.php\", random=False, ):\n self.current_page = start\n self.maximum_number_of_hops = maximum_number_of_hops\n self.destination = destination\n self.hop_count = 0\n self.base_url = base_url\n self.full_text = full_text\n self.path = [start]\n if random:\n self.current_page = self.random_title()\n\n if user_agent is None:\n self.headers = {\n 'User-Agent': 'getting to philosophy bot',\n 'From': 'bortentrichter@yandex.com'\n }\n\n self.unimportant_html_tags = ('table', 'div')\n\n def random_title(self):\n params = {\n 'action': 'query',\n 'generator': 'random',\n 'grnnamespace': 0,\n 'format': 'json'\n }\n\n page = r.get(self.base_url, params=params).json()['query']['pages']\n\n return page[next(iter(page))]['title']\n\n def request(self, page):\n\n params = {\n 'action': 'parse',\n 'page': page,\n 'prop': 'text',\n 'format': 'json',\n 'redirects': 1,\n 'noimages': True,\n }\n\n try:\n return r.get(self.base_url, headers=self.headers, params=params).json()['parse']['text']['*']\n except r.HTTPError:\n raise AttributeError(\"Cannot fetch article data for {}. Article is mostly not existing\".format(page))\n\n @staticmethod\n def is_valid_link(link: str):\n if not link.get('href').startswith('/wiki'):\n return False\n link = link.get('href').replace('/wiki/', '')\n INVALID_LINKS = ['Book:'\n 'File:',\n 'File talk:',\n 'Wikipedia:',\n 'Wikipedia talk:',\n 'Project:',\n 'Project talk:',\n 'Portal:',\n 'Portal talk:',\n 'Special:',\n 'Help:',\n 'Help talk:',\n 'Template:',\n 'Template talk:',\n 'Talk:',\n 'Category:',\n 'Category talk:']\n\n return all(not link.startswith(invalid_link) for invalid_link in INVALID_LINKS)\n\n @staticmethod\n def remove_parentheses(raw_soup):\n \"\"\"\n removes all parentheses from html while ignoring parentheses inside of tags (<>)\n :param raw_soup: soup object with parentheses\n :return: same soup object without parentheses\n \"\"\"\n raw_html = str(raw_soup)\n parentheses_level = tag_level = 0\n cleared_html = ''\n for c in raw_html:\n # not inside of parentheses and a tag begins\n if parentheses_level < 1:\n if c == '<':\n tag_level += 1\n if c == '>':\n tag_level -= 1\n\n # if the tag level is zero, all tags have been closed.\n if tag_level < 1:\n if c == '(':\n parentheses_level += 1\n if parentheses_level < 1:\n cleared_html += c\n if c == ')':\n parentheses_level -= 1\n else:\n cleared_html += c\n\n return BeautifulSoup(str(cleared_html), 'html.parser')\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.hop_count < self.maximum_number_of_hops and self.current_page != self.destination:\n\n self.hop_count += 1\n\n # request side content\n raw_html = self.request(self.current_page)\n soup = BeautifulSoup(raw_html, 'html.parser')\n\n # remove everything which is not needed from body\n soup = soup.find('div', {'class': 'mw-parser-output'})\n for tag in self.unimportant_html_tags:\n for child in soup.find_all(tag):\n child.decompose()\n\n soup = Crawler.remove_parentheses(soup)\n\n for a in soup.find_all('a'):\n\n if Crawler.is_valid_link(a):\n a = a.get('title')\n if a not in self.path:\n self.current_page = a\n self.path.append(self.current_page)\n return self.current_page\n\n else:\n raise StopIteration\n","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"564395227","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponse\nfrom django.urls import reverse_lazy, reverse\nfrom django.contrib.auth.views import login\nfrom django.views.generic import FormView, ListView, DetailView, CreateView, DeleteView, UpdateView\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom game.models import *\nfrom django.views.decorators.http import require_http_methods\nfrom datetime import datetime\n\n\nclass GameListView(LoginRequiredMixin, ListView):\n model = Game\n template_name = \"games/game-list.html\"\n # login_url = 'user:login'\n\n def get_queryset(self):\n return Game.objects.filter(user=self.request.user)\n\nclass GameCreateView(LoginRequiredMixin, CreateView):\n model = Game\n fields = ['story']\n template_name = \"games/game-create.html\"\n login_url = 'user:login'\n success_url = reverse_lazy('game:home')\n\n def form_valid(self, form):\n \"\"\"\n Tras escoger el juego, comenzamos el mismo. Obtenemos su id desde form.instance.story ...\n \"\"\"\n form.instance.user = self.request.user\n super(GameCreateView, self).form_valid(form)\n return HttpResponseRedirect(reverse('game:play-game', kwargs={'game_id': form.instance.id}))\n\nclass GameDeleteView(LoginRequiredMixin, DeleteView):\n model = Game\n template_name = \"games/game-delete.html\"\n success_url = reverse_lazy('game:home')\n\nclass GameQuestionListView(LoginRequiredMixin, ListView):\n model = Question\n template_name = \"question/question-list.html\"\n login_url = 'login'\n\n def get_queryset(self):\n return Question.objects.filter(story__in=\n Game.objects.filter(pk__in=self.kwargs['pk']).values('story'))\n\nclass RankingListView(LoginRequiredMixin, ListView):\n model = Game\n template_name = \"games/ranking-list.html\"\n login_url = 'login'\n queryset = Game.objects.all().order_by('-points')\n\n\n# Inicializa y recupera previas partidas del juego\n@require_http_methods([\"POST\", \"GET\"])\ndef play_game(request, game_id):\n # TODO Comprobar si la partida existe realmente y está asociada a este usuario\n game = get_object_or_404(Game, pk=game_id)\n story = game.story\n\n if(story.questions_number == 0):\n return HttpResponseRedirect(reverse('game:home', )) # TODO Devolver errores\n\n request.session[\"game_id\"] = game.id\n request.session[\"story_id\"] = story.id\n request.session[\"actual_question\"] = game.actual_question # Pregunta actual, inicializada a 0\n request.session['attemps_made'] = 0\n\n return redirect('game:game-controller')\n\n\n\n@require_http_methods([\"POST\", \"GET\"])\ndef game_controller(request):\n \"\"\" Controla la ejecución secuencial de las preguntas \"\"\"\n # El juego termina cuando la pregunta actual es igual al número total de preguntas\n actual_question = request.session[\"actual_question\"]\n story_id = request.session[\"story_id\"]\n\n story = get_object_or_404(Story, pk=story_id)\n # Accedemos a la pregunta que le toca al usuario\n question = Question.objects.filter(story=story).order_by('order')[actual_question]\n\n # Guardamos el id de la pregunta actual (necesario para enlazar la respuesta)\n request.session[\"actual_question_id\"] = question.id\n\n # Si la pregunta es de tipo test, pasamos el cuestionario\n answers = list()\n if question.type == \"CUESTIONARIO\":\n answers = TestOption.objects.filter(question=question)\n\n # Inicializamos el penalizador de preguntas a 0\n request.session[\"penalty\"] = 0\n\n\n\n # Y también enviamos el número de pistas que tiene la pregunta\n cheat_number = Cheat.objects.filter(question=question).count()\n return render(request, 'question/question.html', {\n 'question': question,\n 'answers': answers,\n 'cheat_number': cheat_number,\n 'progress': 10, # TODO Calcular el progreso y mostrarlo en un porcentaje?\n })\n\n\n# Control del guardado de respuestas\n# El usuario llega aquí via post tras hacer click en \"siguiente pregunta\"\n@require_http_methods([\"POST\"])\ndef save_response(request):\n \"\"\" Sólo se guarda la respuesta y se avanza en la pregunta si el usuario la ha respondido \"\"\"\n actual_question = request.session[\"actual_question\"]\n story_id = request.session[\"story_id\"]\n game_id = request.session[\"game_id\"]\n actual_question_id = request.session[\"actual_question_id\"]\n\n question = get_object_or_404(Question, pk=actual_question_id)\n story = get_object_or_404(Story, pk=story_id)\n game = get_object_or_404(Game, pk=game_id)\n\n # Aumentamos el número de intentos\n request.session['attemps_made'] += 1\n attemps = request.session['attemps_made']\n max_attemps = question.attempts\n\n # Enlazamos respuesta del usuario y calculamos puntos sólo si la pregunta anterior no era una viñeta\n if question.type != \"VINETA\":\n points = 0\n post_answer = \"\"\n\n # Comprobamos que el usuario haya incluido una respuesta\n # En caso negativo, la puntuación de la pregunta será cero\n\n if request.POST.get(\"answer\", ):\n post_answer = request.POST.get(\"answer\", )\n points = 0\n real_answer = \"\"\n\n # Buscamos la respuesta real\n if question.type == \"TEXTO\":\n # answer = get_object_or_404(TextQuestionAnswer, question=question)\n if TextQuestionAnswer.objects.get(question=question):\n answer = TextQuestionAnswer.objects.get(question=question)\n\n # Ponemos ambas, la respuesta del usuario y la original en minúsculas\n real_answer = answer.answer.lower()\n post_answer = post_answer.lower()\n else:\n print(\"¡Pregunta de texto sin solución!\")\n\n if question.type == \"CUESTIONARIO\":\n if TestOption.objects.filter(question=question, is_answer=True):\n answer = TestOption.objects.filter(question=question, is_answer=True).first()\n real_answer = str(answer.id)\n\n else:\n print(\"Respuesta tipo test sin definir!\")\n\n\n\n # Comprobamos intentos\n if attemps < max_attemps and real_answer != post_answer:\n return HttpResponseRedirect(reverse('game:game-controller', ))\n\n if real_answer == post_answer:\n points = question.points\n else:\n points = 0\n\n # Restamos los puntos de penalización por haber usado (o no) las pistas y lo reseteamos\n points -= request.session[\"penalty\"]\n request.session[\"penalty\"] = 0\n\n\n else:\n if attemps < max_attemps:\n return HttpResponseRedirect(reverse('game:game-controller', ))\n\n UserAnswer.objects.create_answer(game=game, question=question, answer=post_answer, points=points)\n\n\n\n\n actual_question += 1\n request.session[\"actual_question\"] = actual_question\n\n # Guardamos el progreso en la base de datos por si el usuario quiere continuar más tarde\n game.actual_question = actual_question\n game.save()\n\n if actual_question >= story.get_questions_number():\n\n # Recopilamos los puntos obtenidos y marcamos variables del final del juego\n game.points = get_game_points_view(game.id)\n game.is_finished = True # Guardando este valor, esta partida será guardada como completada, aunque en un futuro se alteren las preguntas del test\n\n game.end_date = datetime.now()\n game.save()\n\n return HttpResponseRedirect(reverse('game:home', ))\n\n request.session[\"attemps_made\"] = 0\n return HttpResponseRedirect(reverse('game:game-controller', ))\n\n\n@require_http_methods([\"GET\"])\ndef get_cheat(request, question_id, cheat_count):\n question = get_object_or_404(Question, pk=question_id)\n if Cheat.objects.filter(question=question)[int(cheat_count)]:\n # TODO Quitar 1 punto de la pregunta por pista pedida\n print(cheat_count)\n request.session[\"penalty\"] += 1\n cheat = Cheat.objects.filter(question=question)[int(cheat_count)]\n return HttpResponse(cheat.text, status=200)\n else:\n return HttpResponse(status=404)\n\n# Función que comprueba si una respuesta es o no correcta en función a la historia y el tipo de pregunta\n@require_http_methods([\"POST\"])\ndef check_simple_answer(request, answer_text):\n pass\n\ndef get_game_points_view(game_id):\n game = get_object_or_404(Game, pk=game_id)\n if UserAnswer.objects.filter(game=game):\n answers = UserAnswer.objects.filter(game=game)\n questions_number = game.story.questions_number\n sum = 0\n\n for answer in answers:\n sum += answer.points\n sum = sum / questions_number\n return sum # Devuelve la media de puntuaciones de esta partida en concreto\n else:\n return 0\n\n\n# Obtiene la puntuación de un juego ya acabado\n@require_http_methods([\"GET\"])\ndef get_game_points(request, game_id):\n game = get_object_or_404(Game, pk=game_id)\n if UserAnswer.objects.filter(game=game):\n answers = UserAnswer.objects.filter(game=game)\n questions_number = game.story.questions_number\n sum = 0\n\n for answer in answers:\n sum += answer.points\n sum = sum / questions_number\n return HttpResponse(sum, status=200) # Devuelve la media de puntuaciones de esta partida en concreto\n else:\n return HttpResponse(status=404)","sub_path":"game/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"516522237","text":"# -*- coding: utf-8 -*-\nimport os,sys\nfrom imp import reload\nimport re\nimport yaml\nimport shutil\nimport distutils.dir_util\n# ------------------------------\nenv_key = 'ND_TOOL_PATH_PYTHON'\nND_TOOL_PATH = os.environ.get(env_key, 'Y:/tool/ND_Tools/python')\nfor path in ND_TOOL_PATH.split(';'):\n path = path.replace('\\\\', '/')\n if path in sys.path:\n continue\n sys.path.append(path)\n\nimport ND_lib.util.path as util_path\nimport ND_lib.env as util_env\nimport ND_lib.shotgun.sg_scriptkey as sg_scriptkey\nimport ND_lib.shotgun.shotgun_api3.shotgun as shotgun\nimport ND_lib.shotgun.sg_util as sg_util\nsg = sg_scriptkey.scriptKey()\n# ------------------------------\nEXPORTER_PATH = os.path.dirname(os.path.dirname(os.path.dirname(\n os.path.abspath(__file__))).replace('\\\\', '/'))\nif EXPORTER_PATH.split('/')[-1] == 'ND_AssetExporter':\n TOOLNAME = 'ND_AssetExporter'\nif EXPORTER_PATH.split('/')[-1] == 'ND_AssetExporter_dev':\n TOOLNAME = 'ND_AssetExporter_dev'\n\n# ND_TOOL_PATH = \"Y:/tool/ND_Tools/DCC/ND_AssetExporter_dev/pycode\"\ntry:\n import PySide.QtCore as QtCore\n import PySide.QtGui as QtGui\n from PySide.QtCore import *\n from PySide.QtGui import *\n from PySide.QtUiTools import QUiLoader\nexcept:\n # try:\n # import PySide6.QtCore as QtCore\n # import PySide6.QtGui as QtGui\n # from PySide6.QtCore import *\n # from PySide6.QtGui import *\n # from PySide6.QtWidgets import *\n # from PySide6.QtUiTools import QUiLoader\n # except Exception as e:\n import PySide2.QtCore as QtCore\n import PySide2.QtGui as QtGui\n from PySide2.QtCore import *\n from PySide2.QtGui import *\n from PySide2.QtWidgets import *\n from PySide2.QtUiTools import QUiLoader\n \n\nimport subprocess\n# import shotgun_api3\n\ndef symlink(source, link_name):\n import os\n os_symlink = getattr(os, \"symlink\", None)\n if callable(os_symlink):\n os_symlink(source, link_name)\n else:\n import ctypes\n csl = ctypes.windll.kernel32.CreateSymbolicLinkW\n csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n csl.restype = ctypes.c_ubyte\n flags = 1 if os.path.isdir(source) else 0\n if csl(link_name, source, flags) == 0:\n raise ctypes.WinError()\n \nclass outputPathConf(object):\n def __init__(self, input_path, export_type=None, debug=False):\n self.input_path = input_path.replace('\\\\', '/')\n self.export_type = export_type\n self.debug = debug\n\n self.root_dir = \"charSet\"\n if self.export_type==\"camera\":\n self.root_dir = \"Cam\"\n if self.debug == True:\n self.root_dir = \"test_\" + self.root_dir\n dic = util_path.get_path_dic(self.input_path)\n self.pro_name = dic['project_name']\n self.shot = dic['shot']\n self.sequence = dic['sequence']\n self.shot_path = ''\n for path_parts in self.input_path.split('/'):\n self.shot_path = self.shot_path + path_parts+'/'\n if path_parts == self.shot:\n break\n\n def set_char(self, char):\n self._publish_char_path = os.path.join(self.shot_path, 'publish', self.root_dir, char)\n if self.export_type == \"camera\":\n self._publish_char_path = os.path.join(self.shot_path, 'publish', self.root_dir)\n if not os.path.exists(self.publish_current_path):\n os.makedirs(self.publish_current_path)\n vers = os.listdir(self.publish_char_path)\n if len(vers) == 1:\n self.current_ver = 'v001'\n else:\n vers.sort()\n current_ver = vers[-1]\n current_ver_num = int(current_ver[1:])\n self.current_ver = 'v' + str(current_ver_num).zfill(3)\n\n def ver_inc(self):\n vers = os.listdir(self.publish_char_path)\n if len(vers) == 1:\n self.current_ver = 'v001'\n else:\n vers.sort()\n current_ver = vers[-1]\n current_ver_num = int(current_ver[1:])\n next_ver_num = current_ver_num + 1\n next_ver = 'v' + str(next_ver_num).zfill(3)\n self.current_ver = next_ver\n try:\n if not os.path.isdir(self.publish_ver_path):\n os.makedirs(self.publish_ver_path)\n if self.export_type == \"anim\":\n if not os.path.isdir(self.publish_ver_anim_path):\n os.makedirs(self.publish_ver_anim_path)\n elif self.export_type == \"abc\":\n if not os.path.isdir(self.publish_ver_abc_path):\n os.makedirs(self.publish_ver_abc_path)\n # elif export_type == \"cam\":\n # os.mkdir(self.publish_ver_cam_path)\n except Exception as e:\n print(e)\n\n def copy_ver2current(self):\n distutils.dir_util.copy_tree(self.publish_ver_path, self.publish_current_path)\n current_info = os.path.join(self.publish_current_path, 'current_info.txt')\n with open(current_info, 'w') as f:\n f.write(\"current ver:\"+ str(self.current_ver)+\"\\n\")\n\n\n def remove_dir(self):\n ver_files = os.listdir(self.publish_ver_path) # 最新verの検索\n for f in ver_files:\n if '.ma' in f:\n return\n shutil.rmtree(self.publish_ver_path)\n # その後currentの空ならcharから削除\n current_files = os.listdir(self.publish_current_path)\n if len(current_files)==0:\n shutil.rmtree(self.publish_char_path)\n\n '''\n def set_cache(self, char):\n self.publish_char_path = os.path.join(self.shot_path, 'publish', 'cache', char)\n if os.path.exists(self.publish_char_path):\n self.inc_ver()\n else:\n try:\n os.makedirs(self.publish_char_path)\n self.inc_ver()\n except:\n pass\n try:\n vers = os.listdir(self.publish_char_path)\n except WindowsError as e:\n raise ValueError\n if len(vers) == 0:\n raise ValueError\n else:\n vers.sort()\n self.current_ver = vers[-1]\n if vers[0] > vers[-1]:\n self.current_ver = vers[0]\n self.publish_ver_path = os.path.join(self.publish_char_path, self.current_ver)\n self.publish_ver_abc_path = os.path.join(self.publish_ver_path, 'abc')\n self.publish_ver_anim_path = os.path.join(self.publish_ver_path, 'anim')\n self.publish_ver_cam_path = os.path.join(self.publish_ver_path, 'cam')\n self.publish_current_path = os.path.join(self.publish_char_path, 'current') \n '''\n \n def overrideShotpath(self, shotpath):\n self.shot_path = shotpath.replace('\\\\', '/')\n\n @property\n def publish_char_path(self):\n return self._publish_char_path.replace(os.path.sep, '/')\n\n @property\n def publish_ver_path(self):\n self._publish_ver_path = os.path.join(self.publish_char_path, self.current_ver)\n return self._publish_ver_path.replace(os.path.sep, '/')\n\n @property\n def publish_ver_abc_path (self):\n self._publish_ver_abc_path = os.path.join(self.publish_ver_path, 'abc')\n return self._publish_ver_abc_path.replace(os.path.sep, '/')\n\n @property\n def publish_ver_anim_path (self):\n self._publish_ver_anim_path = os.path.join(self.publish_ver_path, 'anim')\n return self._publish_ver_anim_path.replace(os.path.sep, '/') \n\n @property\n def publish_ver_cam_path (self):\n self._publish_ver_cam_path = os.path.join(self.publish_ver_path, 'cam')\n return self._publish_ver_cam_path.replace(os.path.sep, '/')\n\n @property\n def publish_current_path (self):\n self._publish_current_path = os.path.join(self.publish_char_path, 'current')\n return self._publish_current_path.replace(os.path.sep, '/')\n\n @property\n def publish_current_anim_path (self):\n self._publish_current_anim_path = os.path.join(self.publish_current_path, 'anim')\n return self._publish_current_anim_path.replace(os.path.sep, '/')\n\n @property\n def publish_current_abc_path (self):\n self._publish_current_abc_path = os.path.join(self.publish_current_path, 'abc')\n return self._publish_current_abc_path.replace(os.path.sep, '/') \n\n @property\n def publish_current_cam_path(self):\n self.publish_current_cam_path = os.path.join(self.publish_current_path, 'cam')\n return self._publish_current_cam_path.replace(os.path.sep, '/')\n\n\n def addTimeLog(self):\n from datetime import datetime\n try:\n with open(os.path.join(self.publish_char_path, 'timelog.txt'), 'a') as f:\n f.write(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))\n f.write(' ' + self.current_ver)\n f.write(' ' + self.input_path)\n f.write(' ' + os.environ['USERNAME'])\n f.write('\\n')\n except Exception as e:\n print(e)\n \n ''' \n #publish_char_path = ...publish/char_set/{char_name}\n #publish_ver_path = ...publish/char_set/{char_name}/{ver}\n #publish_ver_abc_path = ...publish/char_set/{char_name}/{ver} /abc\n #publish_ver_anim_path = ...publish/char_set/{char_name}/{ver} /anim\n #publish_ver_cam_path = ...publish/char_set/{char_name}/{ver} /cam\n #publish_current_path = ...publish/char_set/{char_name}/current\n #publish_current_abc_path = ...publish/char_set/{char_name}/current /abc\n #publish_current_anim_path = ...publish/char_set/{char_name}/current /anim\n #publish_current_cam_path = ...publish/char_set/{char_name}/current /cam \n '''\n\nclass ProjectInfo():\n def __init__(self, url):\n import ND_lib.util.path as util_path\n url_parsedict = util_path.get_path_dic(url)\n self.path = url_parsedict['path']\n self.path_type = url_parsedict['path_type']\n self.project_name = url_parsedict['project_name']\n self.shot = url_parsedict['shot']\n self.sequence = url_parsedict['sequence']\n self.shot_code = url_parsedict['shot_code']\n\n def get_camera_rig_info(self):\n project_conf = util_path.get_conf_dic(self.project_name.lower())\n try:\n self.camera_rig_export = (\n project_conf.get(\"preferences\").get(\"camera_rig_export\")\n )\n except AttributeError:\n self.camera_rig_export = False\n return self.camera_rig_export\n\nclass DeadlineMod():\n def __init__(self, **kwargs):\n #jobFile\n self.target_py = \"Y:/tool/ND_Tools/DCC/{}/pycode/back_starter.py\".format(TOOLNAME)\n #infoFile\n self.argsdict = kwargs\n # self.executer = r\"C:\\Users\\k_ueda\\AppData\\Local\\Programs\\Python\\Python310\\python.exe\"\n self.executer = 'Y:\\\\tool\\\\MISC\\\\Python2710_amd64_vs2010\\\\python.exe'\n self.stg_dir = \"Y:/tool/ND_Tools/DCC/{}/pycode\".format(TOOLNAME)\n self.tmp_dir = os.environ.get('TEMP', 'E:/TEMP')\n self.job_dict = self.job_content()\n self.info_dict = self.info_content()\n\n def job_content(self):\n job_dict = {}\n job_dict[\"Frames\"] = 1\n job_dict[\"Group\"] = self.argsdict['group']\n job_dict[\"MachineName\"] = os.environ.get(\"COMPUTERNAME\")\n job_dict[\"Name\"] = \"ND_AssetExporter_{pool}_{shot}{sequence}_{asset_name}\".format(**self.argsdict) # シーンの情報を入れる\n job_dict[\"OverrideTaskExtraInfoNames\"] = False\n job_dict[\"Plugin\"] = \"CommandLine\"\n job_dict[\"Pool\"] = self.argsdict['pool']\n job_dict[\"Priority\"] = str(self.argsdict['priority'])\n job_dict[\"SecondaryPool\"] = \"normal\"\n job_dict[\"UserName\"] = os.environ.get(\"USERNAME\")\n # job_dict[\"Whitelist\"] = \"ws023\"\n job_dict[\"BatchName\"] = \"Exporter_{pool}_{shot}{sequence}\".format(**self.argsdict)\n return job_dict\n\n def info_content(self):\n info_dict = {}\n info_dict[\"Arguments\"] = self.target_py + ' ' + str(self.argsdict)\n info_dict[\"Executable\"] = self.executer\n info_dict[\"Shell\"] = \"default\"\n info_dict[\"ShellExecute\"] = False\n info_dict[\"SingleFramesOnly\"] = False\n info_dict[\"StartupDirectory\"] = self.stg_dir\n\n return info_dict\n\n def file_maker(self, file_type, file_number):\n import codecs\n file_txt = ''\n target_dict = {}\n if file_type == 'job':\n target_dict = self.job_dict\n elif file_type == 'info':\n target_dict = self.info_dict\n for key,value in target_dict.items():\n file_txt += '{}={}\\r'.format(key, value)\n deadline_tmpfile = r'{}\\ND_AssetExporter_deadline_{}_{}.job'.format(self.tmp_dir, file_type, file_number)\n with codecs.open(deadline_tmpfile, 'w', 'utf-8') as output_file:\n output_file.write(file_txt)\n return deadline_tmpfile\n\n def make_submit_files(self, file_number, farm=\"Deadline\", version=\"10\"):\n job_file = self.file_maker('job', file_number)\n info_file = self.file_maker('info', file_number)\n tmp_dict = {}\n tmp_dict[\"job\"] = job_file\n tmp_dict[\"info\"] = info_file\n return tmp_dict\n\n def submit_to_deadlineJob(self, farm=\"Deadline\", version=\"10\", file_number=1):\n import subprocess\n job_file = self.file_maker('job', file_number)\n info_file = self.file_maker('info', file_number)\n if farm == \"Deadline\":\n deadline_cmd = r\"{}\\bin\\deadlinecommand.exe\".format(util_env.deadline_path)\n jobid = \"\"\n command = '{deadline_cmd} \"{job_file}\" \"{info_file}\"'.format(**vars())\n process = subprocess.Popen(command, stdout=subprocess.PIPE)\n lines_iterator = iter(process.stdout.readline, b\"\")\n for line in lines_iterator:\n if 'JobID' in line:\n jobid = line.replace('JobID=', '')\n sys.stdout.flush()\n return jobid\n\n\ndef submit_to_deadlineJobs(jobs, farm=\"Deadline\", version=\"10\"):\n arg_file_path = '{}/args.txt'.format(util_env.env_temp)\n submit_text = \"-SubmitMultipleJobs\"\n for job in jobs:\n submit_text = \"{}\\n-job\\n{}\\n{}\".format(submit_text, job[\"job\"], job[\"info\"])\n f = open(arg_file_path, \"w\")\n f.write(submit_text)\n f.close()\n deadline_cmd = r\"{}\\bin\\deadlinecommand.exe\".format(util_env.deadline_path)\n command = '{deadline_cmd} {arg_file_path}'.format(**vars())\n devnull = open(os.devnull, \"wb\")\n process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=devnull)\n lines_iterator = iter(process.stdout.readline, b\"\")\n return lines_iterator\n\n\nclass ExporterTableModel(QAbstractTableModel):\n def __init__(\n self, table_data, headers=[],\n check_row=[], executed_row=[],\n parent=None):\n\n QAbstractTableModel.__init__(self, parent)\n self.check_row = check_row\n self.table_data = table_data\n self.headers = headers\n self.executed_row = executed_row\n\n def rowCount(self, parent):\n return len(self.table_data)\n\n def columnCount(self, parent):\n return len(self.table_data[0])\n\n def flags(self, index):\n return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable\n\n def data(self, index, role=Qt.BackgroundRole):\n row = index.row()\n column = index.column()\n\n if role == Qt.EditRole:\n return self.table_data[row][column]\n if role == Qt.DisplayRole:\n row = index.row()\n column = index.column()\n if column == 0:\n if row in self.executed_row:\n x = \"◎\"\n try:\n value = x.decode(\"utf-8\", errors=\"ignore\")\n except:\n value = x\n else:\n if row in self.check_row:\n x = \"◎\"\n try:\n value = x.decode(\"utf-8\", errors=\"ignore\")\n except:\n value = x\n else:\n value = self.table_data[row][column]\n else:\n try:\n value = self.table_data[row][column]\n except:\n value = \"\"\n return value\n\n elif role == Qt.BackgroundRole:\n if \"{Empty!}\" in self.table_data[row]:\n return QColor(\"#AA0000\")\n if row in self.executed_row:\n return QColor(\"#BBBBBB\")\n else:\n if row in self.check_row:\n return QColor(\"#226666\")\n else:\n return QColor(\"#888888\")\n\n def setData(self, index, value, role=Qt.DisplayRole):\n row = index.row()\n column = index.column()\n if role == Qt.EditRole:\n self.table_data[row][column] = value\n self.dataChanged.emit(index, index)\n return True\n return False\n\n def headerData(self, section, orientation, role):\n if role == Qt.DisplayRole:\n if orientation == Qt.Horizontal:\n if section < len(self.headers):\n return self.headers[section]\n else:\n return \"not implemented\"\n else:\n return \"%d\" % (section + 1)\n\n\ndef tabledata_builder(headers, convert_dic, target_assets):\n '''\n SGからきたasset_dicを表示用の二次元配列に直す\n convert_dic: ヘッダーとcodesの対応表\n target_asset: targetassetのdicのリスト\n '''\n tabledata = []\n for target_asset in target_assets:\n td_row = ['']\n for header in headers:\n if header != 'Export Item':\n sg_code = convert_dic[header]\n if sg_code == 'sg_export_type':\n if target_asset[sg_code] == 'anim':\n td_row.append(\"anim\")\n sg_code = 'sg_anim_export_list'\n elif target_asset[sg_code] == 'abc':\n td_row.append(\"abc\")\n sg_code = 'sg_abc_export_list'\n elif target_asset[sg_code] == 'abc_anim':\n td_row.append(\"abc_anim\")\n anim_item = target_asset[\"sg_anim_export_list\"]\n abc_item = target_asset[\"sg_abc_export_list\"]\n # td_row.append(\"{{anim:{}, abc:{}}})\".format(anim_item, abc_item))\n export_item_dic = {}\n export_item_dic['anim']=anim_item\n export_item_dic['abc'] =abc_item\n td_row.append(yaml.safe_dump(export_item_dic))\n continue\n else:\n td_row.append('{Empty!}')\n # td_row.append('{Empty!}')\n anim_item = target_asset[\"sg_anim_export_list\"]\n abc_item = target_asset[\"sg_abc_export_list\"]\n # td_row.append(\"{{anim:{}, abc:{}}})\".format(anim_item, abc_item))\n export_item_dic = {}\n export_item_dic['anim']=anim_item\n export_item_dic['abc'] =abc_item\n td_row.append(yaml.safe_dump(export_item_dic))\n # td_row.append(\"{{anim:{}, abc:{}}}\".format(anim_item, abc_item))\n continue\n if target_asset[sg_code] is None:\n td_row.append(\"{Empty!}\")\n else:\n td_row.append(target_asset[sg_code].replace(\"\\n\", \"\"))\n\n tabledata.append(td_row)\n return tabledata\n\ndef add_camera_row(headers_item, tabledata, camera_rig_export):\n if camera_rig_export == 'True':\n pass\n else:\n td_row = ['']\n for header in headers_item:\n if header == 'Asset name':\n td_row.append('Camera')\n elif header == 'Export Type':\n td_row.append('camera')\n else:\n td_row.append('')\n tabledata.append(td_row)\n return tabledata\n\ndef execExporter_maya(**kwargs):\n import back_starter\n reload(back_starter)\n back_starter.back_starter(kwargs=kwargs[\"kwargs\"])\n\ndef is_arnold(project):\n import yaml\n project_name = project\n toolkit_path = \"Y:\\\\tool\\\\ND_Tools\\\\shotgun\"\n app_launcher_path = \"config\\\\env\\\\includes\\\\app_launchers.yml\"\n project_app_launcher = \"%s\\\\ND_sgtoolkit_%s\\\\%s\" % (toolkit_path, project_name, app_launcher_path)\n f = open(project_app_launcher, \"r\")\n data = yaml.load(f)\n f.close()\n for version in data[\"launch_maya\"][\"versions\"]:\n if \"(_MtoA_)\" in version:\n return True\n return False\n\n\nclass SGProjectClass(object):\n def __init__(self, project, field_codes):\n self.SGFieldDict = {} \n self.project_name = project\n self.project_code = sg_util.get_project(project)\n self.filters = [[\"project\", \"is\", self.project_code]]\n if field_codes == None:\n self.field_codes = [\"code\"]\n else:\n self.field_codes = field_codes\n\n def get_dict(self, category):\n try:\n field_dict = sg.find(category, self.filters, self.field_codes)\n except shotgun.Fault:\n raise ValueError('Coudn\\'t get from Shotgun....')\n self.SGFieldDict[category] = field_dict\n return field_dict\n\n def sg_write(self, category, attribute_name, field_code, new_data):\n item_id = self.codekeyed_dict[attribute_name]['id']\n sg.update(category, item_id, {field_code: new_data})\n\n def get_keying_dict(self, category, priority_field):\n '''\n 特定のコードをキーに格納\n '''\n two_fold_dict = {}\n for dict_piece in self.SGFieldDict[category]:\n pri_item = dict_piece[priority_field]\n two_fold_dict[pri_item] = dict_piece\n return two_fold_dict\n\n def get_keying_list(self, category, target_field, topic_item):\n '''\n 特定のキー:アイテムのリストを返す(重複がありうるので)\n '''\n sp_ls = []\n for dict_piece in self.SGFieldDict[category]:\n pri_item = dict_piece[target_field]\n if pri_item == topic_item:\n sp_ls.append(dict_piece)\n return sp_ls\n\n\nif __name__ == '__main__':\n py_file = sys.argv[0] \n argsdic = yaml.safe_load(sys.argv[1])\n execExporter(argsdic)\n sys.exit()\n","sub_path":"pycode/shell_lib/util_exporter.py","file_name":"util_exporter.py","file_ext":"py","file_size_in_byte":22649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"37653902","text":"import numpy as np\r\n\r\n\r\ndef fun_square(x):\r\n y = x**2\r\n return y\r\n\r\nufunc_square = np.frompyfunc(fun_square, 1, 1)\r\na = np.arange(10)\r\nprint(a)\r\nb = ufunc_square(a)\r\nprint(b)\r\n","sub_path":"PythonProj/112233/BigData/2.2 ufunc函数/ex_2.2.3.py","file_name":"ex_2.2.3.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"261291624","text":"import sys\nfrom collections import deque\nread = sys.stdin.readline\n\ndef bfs(cur) :\n q = deque()\n q.append(cur)\n dist = [0 for _ in range(N+1)]\n\n while q :\n here = q.popleft()\n\n visited[here] = 1\n\n for n,d in adjs[here] :\n if visited[n] == 0 :\n q.append(n)\n dist[n] = dist[here] + d\n\n idx = dist.index(max(dist))\n \n return idx,dist[idx]\n\n\nN = int(read())\nadjs = [[] for _ in range(N+1)]\nfor _ in range(N-1) :\n x,y,c = map(int,read().split())\n\n adjs[x].append([y,c])\n adjs[y].append([x,c])\n\nvisited = [0 for _ in range(N+1)]\nidx, _ = bfs(1)\n\nvisited = [0 for _ in range(N+1)]\n_, ans = bfs(idx)\n\nprint(ans)","sub_path":"BOJ/28_트리/1967_트리의지름.py","file_name":"1967_트리의지름.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"453616249","text":"#!/usr/bin/env python\n#encoding: utf-8\n#description: get local ip address\n\nimport os\n\nfrom aip import AipSpeech\n\"\"\" 你的 APPID AK SK \"\"\"\n#App ID: 10351927\n#API Key: VWgKFTtRGdeviVbZ0AP80SfZ\n#Secret Key: 1945bd34ec52542c48a4864b76bda2ca\n\n#语音合成百度文档地址:http://yuyin.baidu.com/docs/tts/196\n\nAPP_ID = '10351927'\nAPI_KEY = 'VWgKFTtRGdeviVbZ0AP80SfZ'\nSECRET_KEY = '1945bd34ec52542c48a4864b76bda2ca'\naipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\n\n# 读取文件\ndef get_file_content(filePath):\n with open(filePath, 'rb') as fp:\n return fp.read()\n\n# 从URL获取文件识别\n# aipSpeech.asr('', 'pcm', 16000, {\n# 'url': 'http://121.40.195.233/res/16k_test.pcm',\n# 'callback': 'http://xxx.com/receive',\n# })\n\nif __name__ == \"__main__\":\n # 识别本地文件\n str = aipSpeech.asr(get_file_content('test.wav'), 'wav', 16000, {\n 'lan': 'zh',\n })\n print(str)\n","sub_path":"DuerOS/百度语音合成/aip-python-sdk-1.6.1/test_3.py","file_name":"test_3.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"534068813","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('register', views.register, name=\"register\"),\n path('login', views.login, name=\"login\"),\n path('logout', views.logout, name=\"logout\"),\n path('buying', views.buying, name=\"buying\"),\n path('selling', views.selling, name=\"selling\"),\n path('contacts', views.contacts, name=\"contacts\"),\n\n]","sub_path":"PMSProject/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"320017361","text":"import turtle\n\ndef main():\n window = turtle.Screen()\n victor = turtle.Turtle()\n\n make_square(victor)\n\n turtle.mainloop()\n\ndef make_square(victor):\n length = int(input('Square size: '))\n\n for i in range(4):\n make_line_and_turn(victor, length)\n\ndef make_line_and_turn(victor, length):\n victor.forward(length)\n victor.left(90)\n\nif __name__ == '__main__':\n main()","sub_path":"turtles.py","file_name":"turtles.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"161461407","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport json\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n# First, we make a dictionary of words used in the posts\nfilehandles={}\n\n\ndef split_by_lang(dirname, filename, ext):\n\n with open(dirname + filename + \".\" + ext) as myFile:\n for i, line in enumerate(myFile):\n \n logging.disable(logging.INFO)\n post = json.loads(line)\n logging.info(\"post: \" + str(post) + \"\\n\")\n try:\n attrib = post[\"language\"]\n\n logging.info(\"language \" + attrib + \"\\n\")\n try:\n filehandle = filehandles[attrib]\n logging.info(\"got a filehandle from the collection\\n\")\n \n except:\n filehandle = open(\"./temp/Posts_\" + attrib + \".\" + ext, \"w\")\n logging.info(\"got a filehandle from open command\\n\")\n filehandles[attrib]=filehandle\n logging.info(\"put a filehandle into the collection\\n\")\n \n filehandle.write(json.dumps(post) + \"\\n\")\n except:\n logging.info(\"No language?\")\n\n\nsplit_by_lang(\"./temp/\", \"testPostsLanguage\", \"json\") \nsplit_by_lang(\"./temp/\", \"trainPostsLanguage\",\"json\") \n\nfor filehandle in filehandles:\n filehandles[str( filehandle)].close()\n","sub_path":"languagesplit.py","file_name":"languagesplit.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"498094227","text":"# Funktion Highscore anzeigen\ndef hs_anzeigen():\n # Highscore nicht vorhanden\n if not hs_liste:\n print(\"Keine Highscores vorhanden\")\n return\n\n # Ausgabe Highscore\n print(\" P. Name Zeit\")\n for i in range(len(hs_liste)):\n print(f\"{i+1:2d}. {hs_liste[i][0]:10}\"\n f\" {hs_liste[i][1]:5.2f} sec\")\n if i >= 9:\n break\n","sub_path":"exercise/spiel_datei_8_27_T2_v_T5.py","file_name":"spiel_datei_8_27_T2_v_T5.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474802642","text":"import sys\nimport networkx as nx\nimport os\n#import json\n#wrapper functions for nx methods here\n\ndef degree(G):\n return dict(G.degree)\n\n#stats is just a list of functions to apply to the graph. They should take as input a networkx graph or digraph but may have any output.\nstats = [degree,nx.clustering,nx.betweenness_centrality]\n\ndef produce_statistics(G: nx.Graph,s=None) -> dict:\n global stats\n if s != None:\n stats = s\n d = dict()\n for s in stats:\n sname = s.__name__\n d[sname] = s(G)\n return d\n\ndef load_graph(path: str,directed=False) -> nx.Graph:\n #try:\n if not directed:\n G = nx.read_edgelist(path,data=(('rank',float),))\n else:\n # note - self-edges are not allowed in DiGraphs.\n G = nx.read_edgelist(path,data=(('rank',float),),create_using=nx.DiGraph)\n #except:\n # print('file format not yet supported. submit a feature request if it ought to be!')\n return G\n\ndef save_json(data,pth):\n with open(pth,'w') as f:\n json.dump(data,f)\n\ndef save(data,pth):\n fout = open (pth,'w')\n fout.write('#node\\t%s\\n' % '\\t'.join([s.__name__ for s in stats]))\n for node in data[stats[0].__name__]:\n row = [data[s.__name__][node] for s in stats]\n fout.write('%s\\t%s\\n'% (node,'\\t'.join([str(d) for d in row])))\n fout.close()\n\n'''\nrun function that wraps above functions.\n'''\ndef run(infile:str,outfile:str,directed=False) -> None:\n ## if output directory doesn't exist, make it.\n outdir = os.path.dirname(outfile)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n ## load graph, produce stats, and write to human-readable file.\n G = load_graph(infile,directed=directed)\n dat = produce_statistics(G)\n save(dat,outfile)\n\n return\n\n\n'''\nfor testing\n'''\ndef main(argv):\n G = load_graph(argv[1])\n print(G.nodes)\n dat = produce_statistics(G)\n print(dat)\n save(dat,argv[2])\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"src/analysis/summary/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"100294482","text":"data=open('i020.TXFA8').readlines()\ndata=[ i.strip('\\n').split(',') for i in data ]\n\nall_date= set([ i[0] for i in data ])\nall_date= sorted(all_date)\n# set 把所有重複資料唯一化\n\nfor date in all_date:\n # 單獨把每一天的資料都抓出來\n print(date)\n cdata=[ i for i in data if i[0]==date ]\n print(cdata[0])\n print(cdata[-1])\n \n\n\n\n\n\n","sub_path":"20210521_期貨逐筆資料.py","file_name":"20210521_期貨逐筆資料.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"615290031","text":"import numpy as np \nimport cv2\nimport sys\nsys.path.insert(0,'JPEG-Compression')\nimport encoder as e\nimport main as m\nimport decoder as d\n\n## The following functions will be called in the main.py of the video compression\n\ndef get_video_frames(path, no_frames = 1000,Resolution=1):\n \"\"\"\n Gets a path to the video to be read\n Args:\n path: string to the path of the video\n no_frames: int, specifies the number of frames to be read from the video\n Returns:\n a list of complete frames. Each complete frame is a list containing the Y,Cb,Cr components of each frame\n \"\"\"\n vid = cv2.VideoCapture(path)\n # Initialize a np array to hold all frames.\n vid_frame = []\n # Read until video is completed\n for i in range(no_frames):\n if vid.isOpened() == 0:\n print(\"couldn't open video\")\n # Capture frame-by-frame\n ret, frameRGB = vid.read()\n #Resize in case subpixel estimation is needed\n frameRGB=cv2.resize(frameRGB,(frameRGB.shape[1]*Resolution,frameRGB.shape[0]*Resolution))\n if ret == True:\n # Convert frame to YUV with 4:2:0 sampling\n frameYUV = cv2.cvtColor(frameRGB, cv2.COLOR_RGB2YUV_I420)\n\n # Get frame components\n rows, cols = frameYUV.shape \n Y_row = np.int(rows - rows*1/3)\n frame_Y = frameYUV[0:Y_row, :]\n\n frame_Cb1 = frameYUV[Y_row:np.int(Y_row*1.25),0: np.int(cols/2)]\n frame_Cr1 = frameYUV[np.int(Y_row*1.25):np.int(Y_row*1.5), 0: np.int(cols/2)]\n\n frame_Cb2 = frameYUV[Y_row:np.int(Y_row*1.25), np.int(cols/2):]\n frame_Cr2 = frameYUV[np.int(Y_row*1.25):np.int(Y_row*1.5), np.int(cols/2):]\n\n complete_frame = np.array([frame_Y,frame_Cb1,frame_Cr1,frame_Cb2,frame_Cr2])\n\n # Add frame to list of frames\n vid_frame.append(complete_frame)\n # Break the loop\n else: \n break\n return vid_frame\n\ndef reshape_image(image, box_size = 16):\n \"\"\"\n Gets an image of arbitrary size\n and returns a reshaped array of (box_size, box_size) elements\n Args:\n image (np arrat): original image that needs to be reshaped \n box_size (int): Size of the box sub images\n Returns:\n image_array (numpy ndarray, dtype = \"uint8\"): image reshaped to m x m\n np array.\n \"\"\"\n n_rows = np.int(np.floor(image.shape[0]/box_size))\n n_cols = np.int(np.floor(image.shape[1]/box_size))\n\n image_array = cv2.resize(image, dsize=(n_cols*box_size, n_rows*box_size))\n return image_array\n\ndef get_sub_images(image_array, box_size=16):\n \"\"\"\n Gets a grayscale image and returns an array of (box_size, box_size) elements\n Args:\n image_array (numpy ndarray): Image input we want to divide to box\n sub_images.\n Should have shape (length, width, n_channels) where length = width\n e. g. n_channels = 3 for RGB\n box_size (int): Size of the box sub images\n Returns:\n divided_image (numpy ndarray, dtype = \"uint8\"): array of divided images\n - should have a shape of (X, box_size, box_size, n_channels).\n n_rows: number of rows or blocks\n n_cols: number of columns in image\n the number of blocks is n_rows*n_cols\n \"\"\"\n n_rows = np.int(image_array.shape[0]/box_size)\n n_cols = np.int(image_array.shape[1]/box_size)\n\n # make the image into a square to simplify operations based\n # on the smaller dimension\n # d = min(n_cols, n_rows)\n\n # Note: images are converted to uint8 datatypes since they range between\n # 0-255. different datatypes might misbehave (based on my trials)\n image_blocks = np.asarray([np.zeros((box_size, box_size), dtype='uint8')\n for i in range(n_rows*n_cols)], dtype='uint8')\n\n # break down the image into blocks\n c = 0\n for i in range(n_rows):\n for j in range(n_cols):\n image_blocks[c] = image_array[i*box_size: i*box_size+box_size,\n j*box_size:j*box_size+box_size]\n c += 1\n\n # If you want to reconvert the output of this function into images,\n # use the following line:\n # block_image = Image.fromarray(output[idx])\n\n return image_blocks, n_rows, n_cols\n\n\ndef predict(image_blocks, motion_vecs, p_rows, p_cols):\n \"\"\"\n Gets: An array of serial image blocks with each block of size 16, 16 and constructs an image of each block moved by\n a corresponding motion vector.\n Args: \n image_blocks: 1D array of image 16x16 blocks \n motion_vecs: motion vectors corresponding to the blocks in image_blocks.\n p_rows: rows of predicted frame (constant for all frames)\n p_cols: columns of predicted frame (constant for all frames)\n Returns: \n predicted_image: an image where each block has been moved to its predicted place according to its motion vector\n \"\"\"\n predicted_image = get_reconstructed_image(image_blocks, np.int(p_rows/16), np.int(p_cols/16), box_size=16)\n image_blocks = image_blocks.reshape(np.int(p_rows/16),np.int(p_cols/16),16,16) #contruct the image first with no movements\n \n for i in range(np.int(p_rows/16)):\n for j in range(np.int(p_cols/16)):\n vector = motion_vecs[i,j]\n # checking for image boundaries to avoid any out of bound indecies \n if i*16 + vector[1] + 16 <= p_rows and i*16 + vector[1] >=0 and j*16 + vector[0] + 16 <= p_cols and j*16 + vector[0] >= 0:\n # move only the blocks where motion vector is not 0 \n if vector[0] != 0 or vector[1] != 0:\n predicted_image[i*16 + vector[1] : i*16 + vector[1] + 16, j*16 + vector[0] : j*16 + vector[0] + 16] = image_blocks[i,j]\n \n return predicted_image\n\n\n\ndef residual(current_frame, predicted_frame):\n \"\"\"\n Gets the current frame and predicted_frame and subtracts them to return the residual frame.\n Args: current_frame: current frame image divided into 16x16 macroblocks.\n - should have a shape of (X, macroblock_size, macroblock_size)\n predicted_frame: np array of the predicted frame\n Returns: \n residual_frame: np array of the residual macroblock\n \"\"\" \n return current_frame.astype(int) - predicted_frame.astype(int)\n \n \n \ndef spatial_model(residual_frame):\n \"\"\"\n Gets the residual frame and applies DCT to it and returns the DCT coefficients.\n Args:\n residual_frame: np array of the residual frame of shape (X, macroblock_size, macroblock_size) that will be encoded\n Returns:\n serialized_coeff (numpy ndarray): 1d array representing the residual frame\n \"\"\"\n \n coeff = e.apply_dct_to_all(residual_frame)\n quantized_coeff = e.quantize(coeff, m.table_16_high)\n #serialized_coeff=e.serialize(quantized_coeff)\n return quantized_coeff\n\ndef spatial_inverse_model(quantized_coeff):\n #quantized_coeff=d.deserialize(serialized_coeff,1,nrows,ncols)\n dequantized_coeff=d.dequantize(quantized_coeff, m.table_16_high)\n return d.apply_idct_to_all(dequantized_coeff)\n\ndef get_reconstructed_image(divided_image, n_rows, n_cols, box_size=8):\n \"\"\"\n Gets an array of (box_size,box_size) pixels\n and returns the reconstructed image\n Args:\n divided_image (numpy ndarray, dtype = \"uint8\"): array of divided images\n n_rows: number of rows or blocks\n n_cols: number of columns in image\n the number of blocks is n_rows*n_cols\n box_size (int): Size of the box sub images\n Returns:\n reconstructed_image (numpy ndarray): Image reconstructed from the array\n of divided images.\n\n \"\"\"\n image_reconstructed = np.zeros((n_rows*box_size, n_cols*box_size), dtype=np.uint8)\n c = 0\n # break down the image into blocks\n for i in range(n_rows):\n for j in range(n_cols):\n image_reconstructed[i*box_size: i*box_size+box_size,\n j*box_size: j*box_size+box_size] = divided_image[c]\n c += 1\n \n # If you want to reconvert the output of this function into images,\n # use the following line:\n # block_image = Image.fromarray(output[idx])\n\n return image_reconstructed\n\ndef conv_decom_YUV2RGB(complete_frame):\n \"\"\"\n Gets a list containing all the components of a YUV in this order [Y, Cb1, Cr1, Cb2, Cr2], then combine them all together\n and convert them to their RGB equivilant\n Args:\n complete_frame: a list of the 5 YUV components\n Returns:\n an RGB OpenCV frame (3d numpy array) that is ready to be shown with cv2.imshow()\n \"\"\"\n rows, cols = complete_frame[0].shape[0]+complete_frame[1].shape[0]*2, complete_frame[0].shape[1]\n Y_row = np.int(rows - rows*1/3)\n \n frame1 = np.zeros((rows,cols), dtype= np.uint8)\n frame1[0:Y_row, : ] = complete_frame[0]\n frame1[Y_row:np.int(Y_row*1.25),0: np.int(cols/2)] = complete_frame[1]\n frame1[np.int(Y_row*1.25):np.int(Y_row*1.5), 0: np.int(cols/2)] = complete_frame[2]\n frame1[Y_row:np.int(Y_row*1.25), np.int(cols/2):] = complete_frame[3]\n frame1[np.int(Y_row*1.25):np.int(Y_row*1.5), np.int(cols/2):] = complete_frame[4]\n \n return cv2.cvtColor(frame1, cv2.COLOR_YUV2RGB_I420)\n\ndef reconstructed(predicted_frame, quantized_coeff):\n \"\"\"\n Gets the predicted_frame and quantized_coefficients and transforms back the coefficients to residual frame \n and gets the reconstructed image by adding the predicted_frame to the reconstructed residual frame.\n Args:\n predicted_frame: np array of the predicted frame\n quantized_coeff (numpy ndarray): 1d array representing the residual frame\n Returns:\n reconstructed_current\n \"\"\"\n #return reconstructed_current\n","sub_path":"Encoder.py","file_name":"Encoder.py","file_ext":"py","file_size_in_byte":9928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"566072219","text":"import socket\n\nimport sys, time, os\nfrom datetime import datetime\n\nfrom model import Scheduling, database\nfrom logger import Logger\n\nlogger = Logger('socket')\n\nclass ClientSocket:\n\n ''' Classe que implmenta o cliente de comunicação socket. '''\n\n FEEDBACK_OK = \"CODE_OK\"\n FEEDBACK_FAIL = \"CODE_FAIL\"\n SOCKET_BUFFER = 1024\n\n def __init__(self, host, port):\n\n '''\n Keyword arguments:\n host -- endereço do servidor\n port -- porta de comunicação do servidor\n ''' \n\n self._addr = (host, port) \n self._setup() \n\n def accept(self):\n \n '''Mantém o cliente em um estado de espera de novas mensagens.''' \n\n return self._serv_socket.accept() \n\n def close(self):\n\n '''Encerra o cliente.''' \n\n self._serv_socket.shutdown(1)\n self._serv_socket.close() \n\n def _setup(self):\n\n '''Configura os cliente socket.''' \n\n self._serv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._serv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self._serv_socket.bind(self._addr)\n self._serv_socket.listen(10) \n\nclass SocketRunning:\n\n '''Classe que controla a comunicação via socket com o servidor, por onde é possível\n receber mensagens referentes aos agendamentos feitos no servidor e,\n pelo gerenciamento dos mesmos no banco de dados local.''' \n\n def __init__(self):\n self._client_socket = ClientSocket(\"\", int(os.environ.get('socket_port')))\n \n def run(self): \n\n '''Inicia o cliente socket, atualizando o banco de dados com as informações recebidas.'''\n\n while True: \n try:\n con, client = self._client_socket.accept() \n if con: # conexão recebida do servidor \n \n logger.add_info(\"Conexao via socket com {}\".format(client[0])) \n data = self._get_data(con.recv(ClientSocket.SOCKET_BUFFER))\n \n if data.get(\"ADD\"):\n from_time, to_time, server_id = data.get(\"ADD\")\n scheduling = Scheduling(from_time=from_time, \n to_time=to_time,\n created_at=datetime.now(), \n server_id=server_id) \n self._save_scheduling_in_database(scheduling)\n con.send(ClientSocket.FEEDBACK_OK.encode())\n logger.add_info(\"scheduling {} received\".format(server_id))\n\n elif data.get(\"STOP\"): \n scheduling = Scheduling.get(data.get(\"STOP\"))\n scheduling.stop = True\n scheduling.completed_at = datetime.now()\n self._save_scheduling_in_database(scheduling)\n con.send(ClientSocket.FEEDBACK_OK.encode())\n logger.add_info(\"stoped signal received to scheduling {} \".format(data.get(\"STOP\")))\n\n elif data.get(\"DEL\"): \n self._delete_scheduling_from_database(data.get(\"DEL\"))\n con.send(ClientSocket.FEEDBACK_OK.encode())\n logger.add_info(\"deleted signal received to scheduling {} \".format(data.get(\"DEL\")))\n\n # close database\n if not database.is_closed(): database.close()\n\n except BaseException as error: pass\n \n if os.environ.get('STOP_SIGNAL'): break\n time.sleep(int(os.environ.get('app_time_refresh')))\n\n def stop(self):\n\n '''Finaliza a comunicação via socket com o servidor.'''\n\n self._client_socket.close()\n \n def _get_data(self, data): \n\n '''Extra a informações dos dados recebidos.\n \n Keyword arguments:\n data -- dados vindos do servidor'''\n\n action, content = data.decode().split(\" \") \n if(action == \"ADD\"): \n # obtém os dados do agendamento\n from_time, to_time, server_id = content.split(\";\")\n return {\"ADD\":\n (datetime.strptime(from_time,'%d%m%Y%H%M%S'), \n datetime.strptime(to_time,'%d%m%Y%H%M%S'),\n int(server_id))\n }\n elif action == \"STOP\":\n # obtém o ID do scheduling\n return {\"STOP\":int(content)}\n elif action == \"DEL\":\n # obtém o ID do scheduling\n return {\"DEL\":int(content)}\n\n def _save_scheduling_in_database(self, scheduling):\n\n '''Salva os dados do scheduling editado no banco de dados.'''\n\n while True:\n try: \n scheduling.save()\n break \n except BaseException as error:\n logger.add_erro(\"on socket: {} \".format(str(error)))\n time.sleep(0.5) # 0.5 segundos\n continue\n \n return True\n\n def _delete_scheduling_from_database(self, id):\n\n '''Apage um scheduling do banco de dados.'''\n\n while True:\n try: \n query = Scheduling.delete().where(Scheduling.server_id == id)\n query.execute() \n break \n except BaseException as error:\n logger.add_erro(\"on socket: {} \".format(str(error)))\n time.sleep(0.5) # 0.5 segundos\n continue\n \n return True\n","sub_path":"client/jabilclient/lib/clientsocket.py","file_name":"clientsocket.py","file_ext":"py","file_size_in_byte":5887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"570948899","text":"#!/bin/env python3\n#SBATCH -N 1\n#SBATCH -n 1\n#SBATCH --mem=8G\n#SBATCH -p short\n#SBATCH -t 24:00:00\n#SBATCH --gres=gpu:0\n\nimport os, sys, socket\nimport numpy as np\nimport itertools\nimport tensorflow as tf\nimport dill\nimport itertools\nfrom collections import OrderedDict\nfrom pdb import set_trace as st\nfrom dovebirdia.deeplearning.networks.hilbert_filter import HilbertFilter\nfrom dovebirdia.deeplearning.regularizers.base import orthonormal_regularizer\nimport dovebirdia.utilities.dr_functions as drfns\nimport dovebirdia.stats.distributions as distributions\n\n####################################\n# Test Name and Description\n####################################\nscript = '/home/mlweiss/Documents/wpi/research/code/dovebirdia/scripts/dl_model.py'\nproject = 'hilbert'\nexperiment_name = 'hilbert_legendre_ncv_mask_percent_1_value_1000_samples_100_ALPHA'\nexperiment_dir = '/Documents/wpi/research/code/dovebirdia/experiments/' + project + '/' + experiment_name + '/'\nmachine = socket.gethostname()\n####################################\n\nmeta_params = dict()\nds_params = dict()\nkf_params = dict()\nmodel_params = dict()\n\nparams_dicts = OrderedDict([\n ('meta',meta_params),\n ('model',model_params),\n ('ds',ds_params),\n ('kf',kf_params),\n])\n\n####################################\n# Meta Parameters\n####################################\n\nmeta_params['network'] = HilbertFilter\n\n####################################\n# Important Parameters\n####################################\n\nmodel_params['hidden_dims'] = (128,32,) # [(512,128,64),(128,64),(128,64,32),(512,128)]\nmodel_params['coeff_dim'] = 5\nmodel_params['learning_rate'] = 1e-2 #list(np.logspace(-3,-5,12))\nmodel_params['optimizer'] = tf.train.AdamOptimizer #[tf.train.MomentumOptimizer,tf.train.AdamOptimizer]\nmodel_params['mbsize'] = 10\n\n# model params\n\nmodel_params['results_dir'] = '/results/'\nmodel_params['input_dim'] = 100\nmodel_params['output_dim'] = model_params['input_dim']\n\nmodel_params['output_activation'] = None\nmodel_params['activation'] = tf.nn.leaky_relu # [None,tf.nn.tanh]\nmodel_params['use_bias'] = True\nmodel_params['weight_initializer'] = tf.initializers.glorot_normal\nmodel_params['bias_initializer'] = tf.initializers.ones\nmodel_params['weight_regularizer'] = None #[tf.keras.regularizers.l1,tf.keras.regularizers.l2]\nmodel_params['weight_regularizer_scale'] = 0.0 #[1e-4,1e-5]\nmodel_params['bias_regularizer'] = None\nmodel_params['activity_regularizer'] = None\nmodel_params['weight_constraint'] = None\nmodel_params['bias_constraint'] = None\nmodel_params['input_dropout_rate'] = 0.0\nmodel_params['dropout_rate'] = 0.0\nmodel_params['R_model'] = 'learned' # learned, identity+\nmodel_params['R_activation'] = None\nmodel_params['train_ground'] = False\n\n# loss\nmodel_params['loss'] = tf.losses.mean_squared_error\n\n# training\nmodel_params['epochs'] = 10000\nmodel_params['momentum'] = 0.96\nmodel_params['use_nesterov'] = True\nmodel_params['decay_steps'] = 100\nmodel_params['decay_rate'] = 0.96\nmodel_params['staircase'] = False\n\n####################################\n# Domain Randomization Parameters\n####################################\n\nds_params['ds_type'] = 'train'\nds_params['x_range'] = (-1,1)\nds_params['n_trials'] = 10\nds_params['n_baseline_samples'] = 0\nds_params['n_samples'] = model_params['input_dim']\nds_params['n_features'] = model_params['input_dim']\nds_params['n_noise_features'] = ds_params['n_features']\nds_params['standardize'] = False\nds_params['feature_range'] = None\nds_params['baseline_shift'] = None\nds_params['param_range'] = 1.0\nds_params['max_N'] = 7\nds_params['min_N'] = 3\nds_params['missing_percent'] = 0.0\nds_params['missing_value'] = 1000.0\nds_params['with_mask'] = False\nds_params['metric_sublen'] = model_params['epochs'] // 100 # 1 percent\nds_params['fns'] = (\n #['zeros', drfns.zeros, []],\n # ['exponential', drfns.exponential, [1.0,(0.02,0.045),-1.0]],\n #['sigmoid', drfns.sigmoid, [(0.0,100.0),0.15,60.0]],\n #['sine', drfns.sine, [(0,10.0),(0.01,0.01)]],\n #['taylor_poly', drfns.taylor_poly, [(-ds_params['param_range'],ds_params['param_range'])]*(ds_params['max_N']+1)],\n ['legendre_poly', drfns.legendre_poly, [(-ds_params['param_range'],ds_params['param_range'])]*(ds_params['max_N']+1)],\n #['trig_poly', drfns.trig_poly, [(-ds_params['param_range'],ds_params['param_range'])]*(2*ds_params['max_N']+1)],\n)\n\nds_params['noise'] = [\n [None, None, None],\n #['gaussian', np.random.normal, {'loc':0.0, 'scale':0.1}],\n #['bimodal', distributions.bimodal, {'loc1':0.05, 'scale1':0.03, 'loc2':-0.05, 'scale2':0.03}],\n #['cauchy', np.random.standard_cauchy, {}],\n #['stable', distributions.stable, {'alpha':(1.0,2.0),'scale':1.0}], # alpha = 2 Gaussian, alpha = 1 Cauchy\n #['stable', distributions.stable, {'alpha':(1.75), 'scale':1.0}],\n]\n\n########################################\n# Determine scaler and vector parameters\n########################################\n\nconfig_params_dicts = OrderedDict()\n\nfor dict_name, params_dict in params_dicts.items():\n\n # number of config files\n n_cfg_files = 1\n\n # keys for parameters that have more than one value\n vector_keys = []\n\n # determine vector keys and number of config files\n for k,v in params_dict.items():\n\n if isinstance(v, (list,)) and len(v) > 1:\n\n n_cfg_files *= len(v)\n vector_keys.append(k)\n\n # dictionary of scalar parameters\n scalar_params = { k:v for k,v in params_dict.items() if k not in vector_keys}\n vector_params = { k:v for k,v in params_dict.items() if k in vector_keys}\n\n ######################################\n # Generate dictionaries for each test\n ######################################\n\n # list of test dictionaries\n test_dicts = []\n\n if vector_params:\n\n # find all enumerations of the vector parameters\n vector_params_product = (dict(zip(vector_params, x)) for x in itertools.product(*vector_params.values()))\n\n # create separate dictionary for each vector parameter value\n for d in vector_params_product:\n\n test_dicts.append(d)\n test_dicts[-1].update(scalar_params)\n\n else:\n\n test_dicts.append(scalar_params)\n\n config_params_dicts[dict_name] = test_dicts\n\n#######################\n# Write Config Files\n#######################\n\ncfg_ctr = 1\n\nfor config_params in itertools.product(config_params_dicts['meta'],\n config_params_dicts['model'],\n config_params_dicts['ds'],\n config_params_dicts['kf']):\n\n # Create Directories\n model_dir_name = experiment_name + '_model_' + str(cfg_ctr) + '/'\n model_dir = os.environ['HOME'] + experiment_dir + model_dir_name\n results_dir = model_dir + '/results/'\n out_dir = model_dir + '/out'\n config_dir = model_dir + '/config/'\n\n if not os.path.exists(results_dir): os.makedirs(results_dir)\n if not os.path.exists(out_dir): os.makedirs(out_dir)\n if not os.path.exists(config_dir): os.makedirs(config_dir)\n\n # Write Config Files\n for name, config_param in zip(config_params_dicts.keys(), config_params):\n\n cfg_file_name = model_dir_name[:-1] + '_' + name + '.cfg'\n\n with open(config_dir + cfg_file_name, 'wb') as handle:\n\n dill.dump(config_param, handle)\n\n out_file_name = model_dir_name[:-1] + '.out'\n res_file_name = model_dir_name[:-1]\n\n # bash-batch script\n if machine == 'pengy':\n\n batch_string_prefix = 'python3 '\n\n else:\n\n batch_string_prefix = 'sbatch -o ./out/' + out_file_name + ' '\n\n batch_str = batch_string_prefix + script + ' -c ./config/' + ' -r ./results//\\n'\n batch_file_name = model_dir + 'train_model.sh'\n batch_file = open(batch_file_name, 'w')\n batch_file.write(batch_str)\n batch_file.close()\n\n cfg_ctr += 1\n","sub_path":"scripts/hilbert_experiment_generator_dr.py","file_name":"hilbert_experiment_generator_dr.py","file_ext":"py","file_size_in_byte":7825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"235621870","text":"import pandas as pd\nimport numpy as np\nimport os\nimport sys\n\n\n# Maintains all of the data and handles the data manipulation for this\n# application\nclass DataModel:\n def __init__(self):\n self.input_fname = None\n self.output_fname = None\n self.inpput_df = None\n self.output_df = None\n self.display_df = None\n self.save_df = None\n self.note_key = None\n self.current_row_index = None\n self.num_notes = None\n self.annotation_key = 'ANNOTATION'\n\n def rpdr_to_csv(self):\n csvfile = ''.join(\n self.input_fname.split('.')[\n :-1]) + '.csv'\n # corresponding CSV file exist\n if os.path.isfile(csvfile) and ('report_text' in pd.read_csv(\n csvfile).columns.values.tolist() or 'comments' in pd.read_csv(\n csvfile).columns.values.tolist()):\n self.input_fname = csvfile\n # reformat RPDR to CSV file\n else:\n with open(self.input_fname, 'r') as file:\n data, header, fields = [], [], []\n for line in file:\n line = line.rstrip()\n if line.strip() == '':\n continue\n if not header:\n if line.count('|') < 8:\n messagebox.showerror(\n title=\"Error\",\n message=\"Something went wrong, did you select an appropriately formatted RPDR file to perform the Regex on?\")\n return\n header = [field.lower().strip()\n for field in line.split('|')]\n continue\n if not fields and '|' in line:\n fields = [field.lower().strip()\n for field in line.split('|')]\n fields[-1] = line\n report = []\n elif 'report_end' in line:\n report.append(line)\n fields[-1] += '\\n'.join(report)\n data.append(fields)\n fields = []\n else:\n report.append(line)\n self.input_fname = csvfile\n data = pd.DataFrame(data, columns=header)\n data.to_csv(self.input_fname, index=False)\n\n def write_to_annotation(self):\n if self.save_df is None or self.current_row_index is None:\n return\n pathname = os.path.dirname(sys.argv[0])\n self.save_df.to_csv(\n os.path.join(\n pathname,\n '/'.join(self.input_fname.split('/')[:-1]),\n self.output_fname),\n index=False)\n self.save_df.drop(columns=[self.note_key]).to_csv(\n os.path.join(\n pathname,\n '/'.join(self.input_fname.split('/')[:-1]),\n 'norpt_' + self.output_fname),\n index=False)\n\n def get_annotation(self):\n if self.annotation_key in self.output_df:\n current_row_index = self.display_df.index[self.current_row_index]\n val = self.output_df.at[current_row_index, self.annotation_key]\n if val is not None and not pd.isnull(val):\n try:\n return int(float(val))\n except BaseException:\n return val\n return ''\n","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"527063729","text":"from ProvModel import Object, File, Document, Module\nfrom ProvModel import err\nfrom Operators import jsonify\nimport time\nfrom random import randint\n\n\nclass FastQC(Module):\n def body(self):\n import subprocess\n\n\n cmd = 'FastQC/./fastqc ' + str(self.P[0].ref.name)\n returned_value = subprocess.call(cmd, shell=True)\n\n r1 = File(open(str(self.P[0].ref.name)[:-3] + '_fastqc.html'))\n r2 = File(open(str(self.P[0].ref.name)[:-3] + '_fastqc.zip'))\n\n #print r1, r2\n\n return r1, r2\n\nclass DNALetterCount(Module):\n def body(self):\n\n\n filename = self.P[0].ref.name\n\n n = 0.0\n a = 0\n t = 0\n c = 0\n g = 0\n\n with open(filename) as f:\n for line in f:\n n = float(len(line))\n\n #print line\n\n for letter in line:\n if letter == 'A':\n a = a+1\n elif letter == 'T':\n t = t+1\n elif letter == 'C':\n c = c+1\n elif letter == 'G':\n g = g+1\n\n\n\n r1 = ('a', a/n)\n r2 = ('c', t/n)\n r3 = ('t', c/n)\n r4 = ('g', g/n)\n r5 = ('Len', n)\n\n return Object(r1), Object(r2), Object(r3), Object(r4), Object(r5)\n\nclass Entropy(Module):\n def body(self):\n\n\n import math\n\n aprob = self.P[0].ref[1]\n cprob = self.P[1].ref[1]\n tprob = self.P[2].ref[1]\n gprob = self.P[3].ref[1]\n\n\n\n H = aprob*math.log(aprob, 4) + cprob*math.log(cprob, 4) + tprob*math.log(tprob, 4) + gprob*math.log(gprob, 4)\n\n #print H\n\n return Object(H)\n\nclass MaxMinProb(Module):\n def body(self):\n\n b1 = self.P[0].ref\n b2 = self.P[1].ref\n b3 = self.P[2].ref\n b4 = self.P[3].ref\n\n data = (b1, b2, b3, b4)\n\n #print data\n maxval = 0\n maxname = ''\n\n minval = 1\n minname = ''\n\n for i in data:\n\n if i[1] >= maxval:\n maxval = i[1]\n maxname = i[0]\n\n if i[1] <= minval:\n minval = i[1]\n minname = i[0]\n\n return Object((maxname, maxval)), Object((minname, minval))\n","sub_path":"bin/v3.1.0-viz/Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"85067528","text":"from app import app\nfrom flask import jsonify, request\nfrom controllers.UsersApi import users_api\n\n# Register each api here\napp.register_blueprint(users_api)\n\n@app.errorhandler(404)\ndef not_found(error=None):\n message = {\n 'status': 404,\n 'message': 'Not Found: ' + request.url,\n }\n resp = jsonify(message)\n resp.status_code = 404\n return resp\n\nif __name__ == \"__main__\":\n app.run(debug=True,\n host='0.0.0.0',\n port=5010)","sub_path":"web/api_rest/mini_facebook/python_users_service_api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"394605976","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport sys\n\nclass WrongIfdefError(Exception):\n\tdef __init__(self):\n\t\tpass\n\tdef __str__(self):\n\t\treturn (\"Didn't find \\\"ifdef\\\" or \\\"ifndef\\\" as macro\")\n\ndef rewriteFile(fname):\n\tfd = open(fname, 'r')\n\n\tfor line in fd:\n\t\tif line.startswith('#ifdef') or line.startswith('#ifndef'):\n\t\t\tifdef, identifier = line.split(None, 1)\n\t\t\tidentifier = identifier.strip()\n\n\t\t\tif ifdef == '#ifdef':\n\t\t\t\tprint('#if defined(' + identifier + ')')\n\t\t\t\tcontinue\n\t\t\tif ifdef == '#ifndef':\n\t\t\t\tprint('#if !defined(' + identifier + ')')\n\t\t\t\tcontinue\n\t\t\traise WrongIfdefError()\n\t\telse:\n\t\t\tprint(line.strip())\n\n\tfd.close()\n\n\n##################################################\nif __name__ == '__main__':\n\tif (len(sys.argv) != 2):\n\t\tprint(\"usage: \" + sys.argv[0] + \" \")\n\telse:\n\t\trewriteFile(sys.argv[1])\n","sub_path":"rewriteifdefs.py","file_name":"rewriteifdefs.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"595060667","text":"\n# coding: utf-8\n\n# In[1]:\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n\nfrom flask import Flask,jsonify\nimport json\nfrom flask_cors import CORS\nfrom scipy.spatial import distance\n\napp = Flask(__name__)\n\ndata = pd.read_csv(\"./data/kc_house_data.csv\")\n\n\ndate = data['date'] # Only consider year of sale date\nfor i in range(len(date)):\n year = date[i][0:4]\n data.iloc[i,1] = year\nyr_renovated = data['yr_renovated'] # If there is a renovation, consider it as time of built\nfor i in range(len(yr_renovated)):\n if(yr_renovated[i] != 0):\n data.loc[i,'yr_built'] = yr_renovated[i]\ndata = data.dropna() # Drop all observations containing na\ndummy_data = pd.get_dummies(data, columns = ['date','bedrooms','waterfront','view','condition','grade','zipcode']) # Dummy data\nprice = dummy_data['price'] # Price is target\nnewdata = dummy_data.drop(['id','yr_renovated','lat','long','price'],axis = 1) # id lat long is not relevant to our model\n\n\n\nmin_max_scaler = preprocessing.MinMaxScaler()\nd = min_max_scaler.fit_transform(newdata) #Normalized data matrix\n\nX_train, X_test, y_train, y_test = train_test_split(d, price, test_size=0.2, random_state=42)\n\n\n\n\ndef KNN(data, sqft, zipcode, year, bedroom, bathroom): #input sqft, zipcode, year, bedroom, bathroom to do prediction\n ob = pd.DataFrame(np.matrix([sqft, year, bedroom, bathroom]), columns=['sqft_living','yr_built','bedrooms','bathrooms'])\n df_zipcode = data[['sqft_living','zipcode','yr_built','bedrooms','bathrooms']] #filter by zipcode\n df_zipcode = df_zipcode[df_zipcode['zipcode'] == zipcode][['sqft_living','yr_built','bedrooms','bathrooms']]\n df_zipcode = df_zipcode.append(ob)\n df_norm = min_max_scaler.fit_transform(df_zipcode)\n dist = []\n observation = df_norm[len(df_norm)-1,:]\n for i in range(len(df_norm)-1):\n dist.append(distance.euclidean(df_norm[i,:],observation)) #find the observations with smallest distance\n index = np.argsort(dist)[:10]\n df_10 = df_zipcode.iloc[index,:]\n return df_10 #return index of dataframe\n\n\n\ndef predict(clf,data,newdata,sqft,zipcode, year, bedroom, bathroom): #data:original data #newdata:dummydata\n temp = KNN(data, sqft, zipcode, year, bedroom, bathroom)\n index = temp.index\n df = newdata[newdata.index.isin(index)]\n min_max_scaler.fit(newdata) #normalize \n df_norm = min_max_scaler.transform(df)\n top_prediction = clf.predict(df_norm) #do predition\n return np.median(top_prediction) \n\n\n\nfrom sklearn import linear_model\nclf = linear_model.Lasso(alpha=0.1) \nclf.fit(X_train,y_train)\n\n\n# In[13]:\n\n\nwidth = max(list(data['price'])) - min(list(data['price']))\nlength = 300\nseg = 5000\nprice = []\nnum = []\na = 75000\nb = a + seg\nfor i in range(length):\n num.append(len(data[data['price'].between(a,b-1)]))\n price.append(a)\n a = a + seg\n b = b + seg\n\n\n# In[14]:\n\n\nwidth = max(list(data['sqft_living'])) - min(list(data['sqft_living']))\nlength = 300\nseg = 20\nsqft_l = []\nnumm = []\na = 290\nb = a + seg\nfor i in range(length):\n numm.append(len(data[data['sqft_living'].between(a,b-1)]))\n sqft_l.append(a)\n a = a + seg\n b = b + seg\n\n\ndef sqft_range_sample(data,a,b):\n data_fil = data[(data['sqft_living'] > a) & (data['sqft_living'] < b)]\n return data_fil\n\n\ndef price_range_sample(data,a,b):\n data_fil = data[(data['price'] > a) & (data['price'] < b)]\n return data_fil\n\n\n\n\nCORS(app)\n@app.route('/project/status=&sqft=&zipcode=&year=&bedroom=&bathroom=&mi=&ma=&mis=&mas=', methods=['GET'])\ndef server(status,sqft,zipcode,year,bedroom,bathroom,mi,ma,mis,mas): \n status = int(status)\n sqft = float(sqft)\n zipcode = int(zipcode)\n year = int(year)\n bedroom = float(bedroom)\n bathroom = float(bathroom)\n mi = float(mi)\n ma = float(ma)\n mis = float(mis)\n mas = float(mas)\n if(status == 1): # st = 1 means we want to do a prediction\n price_pred = predict(clf,data,newdata,sqft,zipcode,year,bedroom,bathroom)\n return json.dumps(price_pred)\n if(status == 2): # return sample data\n dict_2 = []\n d = data.sample(100)\n d = d[['sqft_living','zipcode','yr_built','bedrooms','bathrooms','lat','long','price']]\n return d.to_json(orient='split')\n if(status == 3): #return data zipcode vs average price\n zipcode = list(Counter(data.iloc[:,16]).keys())\n count = list(Counter(data.iloc[:,16]).values())\n a_list = []\n for i in range(len(zipcode)):\n temp = data[data['zipcode'] == zipcode[i]]\n s = np.sum(temp['price'])\n average = s / count[i]\n a_list.append({'zipcode':float(zipcode[i]),'average':average})\n return json.dumps(a_list)\n if(status == 4): #return observations with price between mi and ma, with sqft between mis and mas\n d = price_range_sample(data,mi,ma)\n d = sqft_range_sample(d,mis,mas)\n d = d[['sqft_living','zipcode','yr_built','bedrooms','bathrooms','lat','long','price']]\n if(len(d) > 50):\n d = d.sample(50)\n return d.to_json(orient='split')\n if(status == 5): #return most similar\n index = KNN(data, sqft,zipcode,year,bedroom,bathroom).index\n df = data[data.index.isin(index)]\n d = df[['sqft_living','zipcode','yr_built','bedrooms','bathrooms','lat','long','sqft_basement','condition','floors','price']]\n return d.to_json(orient='split')\n\n\n# In[ ]:\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"493014225","text":"from unittest import TestCase\nimport numpy as np\n\nimport qcodes\nfrom qcodes.data.hdf5_format import HDF5Format, HDF5FormatMetadata\nfrom qcodes.data.gnuplot_format import GNUPlotFormat\n\nfrom qcodes.tests.data_mocks import DataSet2D\n\n\n#%%\nclass TestFormatters(TestCase):\n\n def setUp(self):\n self.formatters = [GNUPlotFormat, HDF5Format, HDF5FormatMetadata]\n self.metadata = {'subdict': {'stringlist': ['P1']}, 'string': 'P1',\n 'int': 1, 'list': [1, 2], 'numpyarray': np.array([1])}\n\n def test_read_write(self):\n for f in self.formatters:\n print('test formatter %s' % f)\n dataset = DataSet2D()\n dataset.formatter = f()\n\n dataset.add_metadata(self.metadata)\n dataset.write(write_metadata=True)\n\n dataset2 = qcodes.load_data(dataset.location, formatter=f())\n self.assertEqual(list(dataset.arrays.keys()),\n list(dataset2.arrays.keys()))\n # strings should be read and written identically\n self.assertEqual(dataset.metadata['string'],\n dataset2.metadata['string'])\n","sub_path":"qcodes/tests/test_generic_formatter.py","file_name":"test_generic_formatter.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"95587657","text":"\"\"\"main.py\nGame starting point.\n\"\"\"\n\nimport logging; logging.basicConfig(level=logging.DEBUG)\nimport os\nimport pygame\n\n\nfrom crashlib.config import Config\nfrom crashlib.scene import Director\nfrom crashlib.resources import ResourceManager\n# from home import HomeScene\nfrom title_screen import TitleScreenScene\n\nlogger = logging.getLogger('main')\n\ndef main():\n # configuring the resource folder\n resource_path = os.path.join(\n os.path.split(os.path.dirname(os.path.realpath(__file__)))[0],\n 'assets'\n )\n ResourceManager.set_resource_path(resource_path)\n\n Config.load_file() # loading config\n\n director = Director()\n # scene = HomeScene(director)\n scene = TitleScreenScene(director)\n director.change_scene(scene)\n director.loop()\n\ndef initialize_joysticks():\n joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]\n for j in joysticks:\n j.init()\n\nif __name__ == '__main__':\n logger.info('Started')\n pygame.joystick.init()\n pygame.init()\n initialize_joysticks()\n main()\n logger.info('Finished')\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"258644622","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 9 21:07:11 2016\n\n@author: Yura\n\"\"\"\n\n\nimport numpy as np\nimport math as mt\nimport scipy as sc\nfrom numpy import matrix\nfrom numpy import random\nfrom numpy import linalg\nimport sympy\nimport scipy.linalg as sl\nimport matplotlib.pyplot as plt\n#import lsqfit as it\t\t\t\t\t\t\t\t\nimport scipy.optimize as opt\nimport pandas\n\n\nn = 100 #number of traders\n#information structure dD dG dI\nad = 0.1 #alpha for dividends, mean reversion rate of divivdends\nag = 0.02 #alpha for growth rate, mean reversion rate of growth rate\nsd = 0.5 #sigma for dividends\nsg = 0.1#sigma for growth rate\ntaL = 0 #precision of others' signals \ntaH = 1.366 #precision of itself signals of trader\nr = 0.01\n#utility coefficients\nA = 1 #risk aversion\nrho = 0.001 \n\n\n########Supplementary constansts#############\n##### tau0, tau and Omega ########\nNtaL = (n-1)*taL\n## tau0, Omega, tau can be expressed from system with 3 equation and 3 variables (look at KOW)\nta0 = (-(2*ag + taH + NtaL) + np.sqrt( (2*ag + taH + NtaL)**2 + 4*((sg/sd)**2) ) )/2\nprint (\"tau_0 =\", ta0)\ntau = ta0 + taH + NtaL\nprint (\"tau = \", tau)\nOm = np.power(2*ag + tau,-1) # Omega\nOm1 = 2*ag + tau # inverse Omega \n\n################# technical supplementary constants##### \nAh = np.sqrt(ta0) / (np.sqrt(taH) + (n-1)*np.sqrt(taL))\n\nOm12 = np.sqrt(Om)\nta012 = np.sqrt(ta0)\ntaL12 = np.sqrt(taL)\ntaH12 = np.sqrt(taH)\nNtaL12 = (n-1)*np.sqrt(taL) # Let us use index N when we multiply by (N-1) Nxxxx = (N-1)*xxxx \nOm12 = np.sqrt(Om)\n\n########################## Matrices Q and S#######################\nS = np.zeros((3,3))\nQ = np.zeros((3,3))\nQ[0][:] = np.array([-ad, sg*Om12*taH12 , sg*Om12*NtaL12 ])\nQ[1][:] = np.array([0 , -ag - tau + (taH12 + Ah*ta012) *taH12 , (taH12 + Ah*ta012) *NtaL12 ])\nQ[2][:] = np.array([0 , (taL12 + Ah*ta012) * taH12 , -ag - tau + (taL12 + Ah*ta012) * NtaL12 ])\n#as dX = - QXdt + SdB_t \nQ = -Q \nprint(Q)\n\nQt = np.transpose(Q)\n#print(np.linalg.eig(Q))\n#print(\"\\n\", ad, ag + tau, ag )\nQ2 = np.dot(Q,Q)\n#print(sg*Om12*tau/(ad-ag), taH12+Ah*ta012, taL12+Ah*ta012)\nv1 = 1, 0, 0\nv2 = 0, (n-1)*taL12, -taH12\nv3 = sg*Om12*tau/(ad-ag), taH12+Ah*ta012, taL12+Ah*ta012\n\nV, D = np.zeros((3,3)), np.zeros((3,3))\nV[:,0], V[:,1], V[:,2], D[0,0], D[1,1], D[2,2] = v1, v2, v3, ad, ag+tau, ag \n#print(\"V\\n\", V)\n#print(np.linalg.eig(Q)[1][:,2]/v3)\n#print(v2/np.linalg.eig(Q)[1][:,1])\n#print(\"VDV - Q\\n\", np.dot(V, np.dot(D, np.linalg.inv(V))) - Q)\ndetV = np.linalg.det(V)\nV1S, V1SSV1, V1, RRR = np.zeros((3,3)), np.zeros((3,3)), np.zeros((3,3)), np.zeros((3,3))\nSS = sg*Om12*tau/(ad - ag)\nsn1 = np.sqrt(n-1)\n\nV1[0,:] = np.array([1, - SS*taH12/detV, - SS*taL12/detV *(n-1) ])\nV1[1,:] = np.array([ 0, (taL12+Ah*ta012)/detV, -(taH12+Ah*ta012)/detV ])\nV1[2,:] = np.array([ 0, taH12/detV, (n-1)*taL12/detV ])\n\n#print(\"V1 - V1\\n\",V1 - np.linalg.inv(V) )\nprint(V1)\n\nV1S[0][:] = np.array([ sd - SS*ta012/detV, - SS*taH12/detV, - SS*taL12/detV *sn1 ])\nV1S[1][:] = np.array([ Ah* (taL12 - taH12)/detV, (taL12+Ah*ta012)/detV, -(taH12+Ah*ta012)/detV/sn1 ])\nV1S[2][:] = np.array([ ta012/detV, taH12/detV, sn1*taL12/detV ])\n\nS[0][:] = np.array([ sd, 0, 0 ])\nS[1][:] = np.array([ Ah, 1, 0 ])\nS[2][:] = np.array([ Ah, 0, np.power(n-1, -0.5) ])\n\nV1SSV1[0][:] = np.array([sd**2 - (2*detV*sd*ta012*SS - SS*SS*tau)/detV/detV, \n sd*Ah*(taL12 - taH12)/detV, (detV*sd*ta012 - SS*tau)/detV/detV ])\nV1SSV1[1][:] = np.array([sd*Ah*(taL12 - taH12)/detV , tau/(n-1)/detV/detV *(1 + n*Ah*Ah), 0 ])\nV1SSV1[2][:] = np.array([ (detV*sd*ta012 - SS*tau)/detV/detV, 0, tau/detV/detV ])\n\n\n\n#print(\"V1S - V1S\\n\", V1S - np.dot(np.linalg.inv(V), S))\n#print(\"V1S (V1S)'\\n\", np.dot(V1S,np.transpose(V1S)) - V1SSV1)\n#print(\"V1S (V1S)'\\n\", V1SSV1)\n\n\nh=100000\n\nRRR[0][:] = np.array([ (1 - np.exp(-h*2*ad))/2/ad, \n (1 - np.exp(-h*(ad+ag+tau)))/(ad+ag+tau),\n (1 - np.exp(-h*(ad+ag)))/ (ad+ag) ])\nRRR[1][:] = np.array([ (1 - np.exp(-h*(ad+ag+tau)))/(ad+ag+tau), \n (1 - np.exp(-h*2*(ag+tau)))/2/(ag+tau),\n 0 ])\nRRR[2][:] = np.array([ (1 - np.exp(-h*(ad+ag)))/(ad+ag),\n 0,\n (1 - np.exp(-h*2*ag))/2/ag ])\n\nh=0.0000001\n\n#print(RRR)\n#print(RRR/h)\n#print(2*ad)\n#print(ad+ag)\n#print(ad+ag+tau)\n\n\niV1SSV1 = V1SSV1*RRR\nVARX = np.dot(V, np.dot(iV1SSV1, np.transpose(V)))\nprint(VARX)\n\n\n\n\nSS = np.dot(S, np.transpose(S)) \nI, SSQ, QSS = np.identity(3), np.dot(SS, np.transpose(Q)), np.dot(Q, np.transpose(SS))\n#p = pss, psd, psh, psx, pdd, pdh, pdx, phh, phx, pxx, gd, gh, gs, gp\nC = np.zeros((3,3))\n \nn1 = n-1\nn2 = n - 2\nn22 = n2/2\nsd2 = sd**2\nAh2 = Ah**2\na1 = -ag - tau + taH12*(taH12 + Ah*ta012)\na2 = -ag - tau + n1*taL12*(taL12+Ah*ta012)\na3 = n1*taL12*(taH12+Ah*ta012)\na4 = (taL12+Ah*ta012)*taH12 \n #super technical parameters\nnn1 = n /(n-1)\n\ndata = pandas.read_csv(\"5000h.0000001N100.csv\")\ne = pandas.DataFrame.as_matrix(data)\nJJJFi = 500\nresFi = np.zeros((JJJFi+1, 6))\nprint(e[0,1:15])\npshl = 0\npsxl = 0\nlll = 0\nllll, llll1, llll2, llll3, llll4,llll5,llll6 = 0,0,0,0,0,0,0\nfor JJJ in np.arange(JJJFi+1):\n pss, psd, psh, psx, pdd, pdh, pdx, phh, phx, pxx, gd, gh, gs, gp = e[JJJ,1:15]\n \n h = 0.0000001*(1+JJJ) #- step\n rh = r*h\n At = rh*A / (1 - np.exp(-rh))\n hQ, hSS,hQ2, hAt, ImhQ = h*Q, h*SS, h*Q2, h*At, I - h*Q\n ImhQt = np.transpose(ImhQ)\n #equation for psi_m\n #my paper:\n pm = r - r**2 * h /2\n #KOW\n pmK = r ###let use index K as Kyle-Obizhaeva-Wang \n #\n hpm= h*pm\n pmerh = pm*np.exp(rh)\n mn1pm = pmerh / (n-1) \n ###for psi_0\n QSS = np.dot(Q, SS)\n SSQt = np.dot(SS, Qt)\n AtSS = At*SS\n AQSS2 = -At*(QSS + SSQt) / 2 ###загатовка для матрицы E\n slagpo = 1 - np.log(r) + rh - (rho / r) - (rho * h/ 2) ###?????? rho*h/2 +-\n slagpo2 = (1 -( r*h / 2)) / (2*r) \n #super technical parameters\n mn1 = np.exp(r*h) / (n-1) \n hpss, hgs, psd2, psh2, psx2, psdsh, psdsx, pshsx = \\\n h*pss, h*gs, psd**2, psh**2, psx**2, psd*psh, psd*psx, psx*psh \n pB = np.zeros((3,1))\n ppB = np.zeros((6,1))\n pB[0,0], pB[1,0], pB[2,0] = psd, psh, psx \n ppB[0,0], ppB[1,0], ppB[2,0], ppB[3,0] = psd, psh, psx, pm \n pBt = np.transpose(pB) \n ppBt = np.transpose(ppB)\n C[0][:] = np.array([ pdd, pdh, pdx ]) \n C[1][:] = np.array([ pdh, phh, phx ])\n C[2][:] = np.array([ pdx, phx, pxx ])\n BigM = np.zeros((6,6))\n BigM[0:3,0:3]= SS - h/2*(SSQ+QSS) - hAt*np.dot(SS, np.dot(C, SS))\n BigM[3:6,0:3] = hSS/2\n BigM[0:3,3:6] = hSS/2\n pC1, pC2, pC3 = np.dot(C[0,:], pB), np.dot(C[1,:], pB), np.dot(C[2,:], pB) \n #print(pC1,\"\\n\", pC2,\"\\n\", pC3, \"\\n\")\n SSC, QtC, CQ = np.dot(SS, C), np.dot(Qt,C), np.dot(C,Q)\n SSCSSC, SSCt = np.dot(SSC, SSC), np.transpose(SSC)\n SSC1, SSC2, SSC3, CSSC = \\\n SSC[:,0], SSC[:,1], SSC[:,2], C.dot(SSC)\n #print(SSC1,\"\\n\", SSC2, \"\\n\", SSC3, \"\\n\", CSSC,\"\\n\\n\\n\\n\")\n #print(SSC1,\"\\n\", SSC2,\"\\n\", SSC3,\"\\n\\n\", CSSC, \"\\n\") \n #hAtpBSSpB = hAt* (SS[0][0] *psd2 + SS[1][1] *psh2 + SS[2][2] *psx2 + (SS[0][1] + SS[0][1]) *psdsh + (SS[0][2] + SS[0][2]) *psdsx + (SS[1][2] + SS[1][2]) *pshsx)\n #print( (np.dot(C, np.dot(SS, C))))\n hApBSS = hAt*np.dot(pBt,SS)\n hAtpBSSpB, hAtpBSSC1, hAtpBSSC2, hAtpBSSC3 = \\\n np.dot(hApBSS, pB), np.dot(hApBSS, C[:][0]), np.dot(hApBSS, C[:][1]), np.dot(hApBSS, C[:][2])\n #print(\"hAtpBSSpB\", hAtpBSSpB)\n hpBQ1,hpBQ2,hpBQ3 = np.dot(pBt, hQ[:,0]), np.dot(pBt, hQ[:,1]), np.dot(pBt, hQ[:,2]) \n gx = psx - hpBQ3 - hAtpBSSC3 \n ################## first 4 ############\n \n #supplementory terms\n # mn1 --- exp(rh) / (N-1) \n # mn1pm --- pm*exp(rh) / (N-1) \n # nn1 --- N / (N-1) \n #n1 --- N-1\n sl0 = mn1pm/gp\n sl1, sl2 = sl0 - hpss, nn1 * gx /gh \n sl11 = psd + hpm - hpBQ1 - hAtpBSSC1\n sl22 = psh - hpBQ2 - hAtpBSSC2\n sl44 = pss - hAtpBSSpB\n \n \n ###################### 10 ############\n \n gdgp, ghgp,gsgp = gd/gp, gh/gp, gs/gp\n \n Bp = np.power(2*sl0 - hpss, -1) #Big psi + because of 1-st order approximation\n \n ####запись x совпадает с Kyle A-37 \n BpxdK, Bpxd, Bp2 = psd - pm*gdgp, (sl11 - pmerh*gdgp), Bp**2\n BBpxd = Bp*Bpxd\n \n BBpxh = Bp*sl22 \n BpxhK, Bpxh = psh, sl22\n \n BBpxx = Bp*(gx - pmerh*ghgp)\n BpxxK, Bpxx = psx - pm*gh/gp, (gx - pmerh*ghgp)\n #####Xi\n Xi = np.zeros((3,1))\n Xi[0,0], Xi[1,0], Xi[2,0] = Bpxd, Bpxh, Bpxx\n Xit = np.transpose(Xi)\n ###### (gdgp, 0, ghgp)\n BpXit = Bp*Xit\n BpXi = np.transpose(BpXit)\n \n ################Equations for XX'############################\n EE, edEE = np.zeros((3,3)), np.zeros((1,3))\n edEE[0,0]= 1\n\n \n BBpxs = Bp*(sl44 - mn1pm*gsgp)\n BpxsK, Bpxs = pss - pm*gs/gp/n1, (sl44 - mn1pm*gsgp)\n \n Bpss = mn1pm* (2- hgs) / gp\n BBpss = Bp* Bpss\n \n VARxsmall = np.dot(BpXit, np.dot(VARX, BpXi))\n print(BpXit)\n print(VARxsmall)\n resFi[JJJ,0]= np.sqrt(VARxsmall) \n resFi[JJJ,1:4] = Xit\n resFi[JJJ,4] = BBpxs\n resFi[JJJ,5] = hpBQ2\n print(\"Q2\\n\", Q[:,1])\n print(\"Q\\n\",Q)\n print(\"pB\\n\", pB)\n print(\"psh-pshl\\n\", psh-pshl)\n print(\"hpBQ2\", hpBQ2)\n print(\"hAtpBSSC2\", hAtpBSSC2) \n print(\"hpBQ3\\n\", hpBQ3) \n print(\"hAtpBSSC3\", hAtpBSSC3)\n print(\"psx-psxl\", psx-psxl)\n print(\"pmerh*ghgp- lll\", pmerh*ghgp- lll)\n print(\"Bpxx\", Bpxx)\n print(\"sl2- hpss\", sl2- hpss)\n print(\"sl2\", sl2)\n print(\"sl2 - hpss - llll3\", sl2 - hpss - llll3)\n print(\"gx/llll2 -1\", gx/llll2 -1 )\n print(\"gh/llll4 -1 \", gh/llll4 -1 )\n print(\"(sl2 - hpss)/llll3 - 1\", (sl2 - hpss)/llll3 - 1)\n pshl = psh \n psxl = psx\n lll = pmerh*ghgp\n llll1 = h *pss \n llll2 = gx\n llll4 = gh\n llll3 = sl2 -hpss\n print(\"np.dot(pBt, Q)\", np.dot(pBt, Q))\n print(\"Q\", Q)\n print(\"np.dot(pBt, SSC)\", np.dot(pBt, SSC)) \n \ndata1 = pandas.DataFrame(resFi)\ndata1.to_csv(\"market_volume.csv\")","sub_path":"kow/welfare_nac.py","file_name":"welfare_nac.py","file_ext":"py","file_size_in_byte":10290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"178218122","text":"import cv2\nimport numpy as np\nfrom filters import render_util as render\n\n\ndef tri_color(gray):\n k1 = 80\n k2 = 128\n k3 = 200\n result = gray.copy()\n result[gray < k1] = 0\n result[(gray < k3) * (gray >= k1)] = k2\n result[gray >= k3] = 255\n return result\n\n\ndef get_acne_mask_on_patch(img, in_mask):\n img = img*in_mask\n g = cv2.split(img)[1]\n hard_g = render.hard_light(g, g)\n hard_g2 = render.hard_light(hard_g, hard_g)\n hard_g3 = render.hard_light(hard_g2, hard_g2)\n tri_hg3 = tri_color(hard_g3)\n\n params = cv2.SimpleBlobDetector_Params()\n params.minArea = 20\n params.maxArea = 1000\n params.minConvexity = 0.3\n params.minDistBetweenBlobs = 0\n detector = cv2.SimpleBlobDetector_create(params)\n keypoints = detector.detect(tri_hg3)\n kpLocation = [kp.pt for kp in keypoints]\n kpSize = [kp.size for kp in keypoints]\n\n mask = np.zeros(img.shape[:-1], np.uint8)\n for i, kploc in enumerate(kpLocation):\n cv2.circle(mask, (int(kploc[0]), int(kploc[1])), int(kpSize[i]), 1, -1) # Last -1 means filled, return 0-1 mask\n\n return mask\n","sub_path":"filters/recycle/de_acne/acne_mask.py","file_name":"acne_mask.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"7094547","text":"import os\nimport cv2\nfrom data.base_method.image_option import loaded_label2ndarray, loaded_image2ndarray, np_transform\nfrom data.base_method.image_folder import make_dataset\nfrom PIL import Image\nimport numpy as np\nimport random\n\nclass Dataset_Help(object):\n def __init__(self, opt):\n super(Dataset_Help, self).__init__()\n self.opt = opt\n self.root = opt.dataroot\n\n # label\n if opt.label_nc <1:\n raise ('Need label_nc')\n self.dir_label = os.path.join(opt.dataroot, opt.phase+'_label')\n self.dir_label = sorted(make_dataset(self.dir_label))\n\n # real_image\n if opt.phase == 'train':\n self.dir_real_image = os.path.join(opt.dataroot, opt.phase+'_img')\n self.dir_real_image = sorted(make_dataset(self.dir_real_image))\n\n # instance maps\n if not opt.no_instance:\n self.instant_paths = os.path.join(opt.dataroot, opt.phase+'_inst')\n self.instant_paths = sorted(make_dataset(self.instant_paths))\n if opt.phase == 'train':\n self.shuffle2()\n\n\n def __getitem__(self, item):\n # label\n label_path = self.dir_label[item]\n label = cv2.imread(label_path, 0)\n\n label_2ndarray = loaded_label2ndarray(label, self.opt)\n\n # real image\n if self.opt.phase =='train':\n image_path = self.dir_real_image[item]\n image = cv2.imread(image_path)\n # cv2.imshow('1', image)\n # cv2.waitKey()\n image_2ndarray = loaded_image2ndarray(image, self.opt)\n # cv2.imshow('2', image_2ndarray[0].transpose(1, 2, 0))\n # cv2.waitKey()\n # inst maps\n if not self.opt.no_instance:\n inst_path = self.instant_paths[item]\n inst = Image.open(inst_path)\n inst_nd = np_transform(inst, self.opt, method=Image.NEAREST, normalize=False)\n inst_nd = np.expand_dims(inst_nd, axis=0)\n inst_nd = np.expand_dims(inst_nd, axis=0)\n\n if self.opt.phase == 'train':\n input_dict = {'label': label_2ndarray, 'real_image':image_2ndarray, 'instance':inst_nd}\n else:\n input_dict = {'label': label_2ndarray, 'instance': inst_nd}\n return input_dict\n\n\n def __len__(self):\n return len(self.dir_label)\n\n def lenOfIter_perBatch(self):\n return int(len(self.dir_label)) // int(self.opt.batch_size)\n\n def shuffle2(self):\n # use same random seed to shuffle list\n\n # every time use random seed in case same shuffle in different epoch\n ra = random.random()\n random.seed(ra)\n random.shuffle(self.dir_label)\n random.seed(ra)\n random.shuffle(self.dir_real_image)\n random.seed(ra)\n random.shuffle(self.instant_paths)","sub_path":"SPADE/data/base_method/what_name.py","file_name":"what_name.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"470699257","text":"from django.test import Client, TestCase\nfrom django.urls import reverse\n\n\nclass AboutViewsTests(TestCase):\n def setUp(self):\n self.guest_client = Client()\n\n def test_about_page_author(self):\n adress_url_names = {\n reverse('about:author'),\n reverse('about:tech'),\n }\n # Проверка всех страниц - если пользователь авторизован\n for adress in adress_url_names:\n with self.subTest(adress=adress):\n response = self.guest_client.get(adress)\n self.assertEqual(response.status_code, 200)\n\n def test_about_page_template(self):\n templates_url_names = {\n 'about/author.html': reverse('about:author'),\n 'about/tech.html': reverse('about:tech'),\n }\n for template, adress in templates_url_names.items():\n with self.subTest(adress=adress):\n response = self.guest_client.get(adress)\n self.assertTemplateUsed(response, template)\n","sub_path":"yatube/about/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"545608970","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nA = 101325\nP = 4650\nT = 44.5\n\n# Alpha-Beta\nP_ab = 1\nT_ab = 36\n\nS_1 = 4.59\nV_1 = 0.043 * 10 ** (-6)\n\nB_1 = (P - P_ab) / np.log(T / T_ab)\nC_1 = P_ab - B_1 * np.log(T_ab)\n\nT_1 = np.linspace(36, T)\nP_1 = B_1 * np.log(T_1) + C_1\n\n# Alpha-Gamma\nS_2 = 1.25\nV_2 = 0.165 * 10 ** (-6)\n\nB_2 = S_2 / V_2 / A\nC_2 = P - B_2 * T\n\nT_2 = np.linspace(0, T)\nP_2 = B_2 * T_2 + C_2\n\n# Gamma-Beta\nS_3 = S_1 + S_2\nV_3 = V_2 + V_2\n\nB_3 = S_3 / V_3 / A\nC_3 = P - B_3 * T\n\nT_3 = np.linspace(T, 70)\nP_3 = B_3 * T_3 + C_3\n\n# Plot\nplt.plot(T_1,P_1)\nplt.plot(T_2,P_2)\nplt.plot(T_3,P_3)\n\nplt.title('Nitrogen Phase Diagram')\nplt.xlabel('Temperature (K)')\nplt.ylabel('Pressure (atm)')\n\nplt.text(17, 1000, 'Alpha')\nplt.text(55, 3000, 'Beta')\nplt.text(20, 6000, 'Gamma')","sub_path":"HW_05.py","file_name":"HW_05.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"2347571","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom IPython.display import Image\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef make_coordinates(image,line_parameters):\n slope, intercept = line_parameters\n y1 = image.shape[0]\n y2 = int(y1*(3/5))\n x1 = int((y1-intercept)/slope)\n x2 = int((y2-intercept)/slope)\n return np.array([x1,y1,x2,y2])\ndef average_slope_intercept(image,lines):\n left_fit = []\n right_fit = []\n for line in lines:\n x1,y1,x2,y2 = line.reshape(4)\n parameters = np.polyfit((x1,x2),(y1,y2),1)\n slope = parameters[0]\n intercept = parameters[1]\n #print(image.shape)\n \n if slope <0:\n left_fit.append((slope,intercept))\n else:\n right_fit.append((slope,intercept))\n #print(left_fit)\n #print(right_fit)\n left_fit_average = np.average(left_fit, axis = 0)\n right_fit_average = np.average(right_fit, axis = 0)\n #print(left_fit_average,'leftt')\n #print(right_fit_average,'rightt')\n left_line = make_coordinates(image,left_fit_average)\n right_line = make_coordinates(image,right_fit_average)\n return np.array([left_line,right_line])\n \nimage = cv2.imread('california-highway.jpeg')\nlane_image = np.copy(image)\ndef canny(image):\n gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)\n#cv2.imshow(\"result\",image)\n##finding lane ---gaussian blur\n blur = cv2.GaussianBlur(gray,(5,5),0)\n###finding lane canny---gaussian works internally\n\n canny = cv2.Canny(blur,50,150)\n return canny\ndef display_lines(image,lines):\n line_image = np.zeros_like(image)\n if lines is not None:\n for x1,y1,x2,y2 in lines:\n \n cv2.line(line_image,(x1,y1),(x2,y2),(250,0,0),10)\n return line_image\n \ndef region_of_interest(image):\n height = image.shape[0]\n polygons = np.array([[(200,height),(1100,height),(550,250)]])\n mask = np.zeros_like(image)\n cv2.fillPoly(mask,polygons,255)\n #6 finding lane line --bitwise\n masked_image = cv2.bitwise_and(image,mask)\n return masked_image\n\n\ncap = cv2.VideoCapture(\"test2.mp4\")\nwhile(cap.isOpened()):\n _,frame = cap.read()\n canny_image = canny(frame)\n cropped_image = region_of_interest(canny_image)\n lines = cv2.HoughLinesP(cropped_image,2,np.pi/180,100,np.array([]),minLineLength = 40,maxLineGap = 5)\n averaged_lines = average_slope_intercept(frame,lines)\n#lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold, 0, minLineLength, 20);\n line_image = display_lines(frame,averaged_lines)\n##finding lane line ------region of interest\n combo_image = cv2.addWeighted(frame,0.8,line_image,1,1)\n cv2.imshow('result',combo_image)\n if cv2.waitKey(1) == ord('q'):\n break\ncap.release()\ncv2.destroyallwindows()\n \n","sub_path":"traffic_lane.py","file_name":"traffic_lane.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"16527472","text":"import pathlib\n\n\n# Path for the aliveness swapfile\nALIVENESS_PATH = pathlib.Path(\"/tmp/hulks/aliveness.yml\")\n\n# Path for aliveness lockfile (i.e. \"AlivenessListener running?\")\nALIVENESS_LOCK_PATH = pathlib.Path(\"/tmp/hulks/aliveness.lock\")\n\n# Timespan after which robots will be marked as \"temporarily not alive\"\nALIVENESS_TIMEOUT_ALIVE = 10 # in seconds\n\n# Timespan after which robots will be considered offline\nALIVENESS_TIMEOUT_OFFLINE = 20 # in seconds\n\n# Port for incoming aliveness messages\nALIVENESS_BROADCAST_PORT = 12440\n","sub_path":"tools/libPython/hulks/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"645878315","text":"from . import model\nfrom . import routes\n\nMODELS = [\n model.ZoteroUserSettings,\n model.ZoteroNodeSettings,\n]\n\n\nUSER_SETTINGS_MODEL = model.ZoteroUserSettings\nNODE_SETTINGS_MODEL = model.ZoteroNodeSettings\n\nROUTES = [routes.api_routes]\n\nSHORT_NAME = 'zotero'\nFULL_NAME = 'Zotero'\n\nOWNERS = ['user', 'node']\n\nADDED_DEFAULT = []\nADDED_MANDATORY = []\n\nVIEWS = ['widget']\nCONFIGS = ['user', 'node']\n\nCATEGORIES = ['citations']\n\nINCLUDE_JS = {}\n\nINCLUDE_CSS = {\n 'widget': [],\n 'page': [],\n 'files': []\n}\n\nWIDGET_HELP = 'Zotero'\n\nHAS_HGRID_FILES = False\n\n# HERE = os.path.dirname(os.path.abspath(__file__))\nNODE_SETTINGS_TEMPLATE = None # use default node settings template\nUSER_SETTINGS_TEMPLATE = None # use default user settings template\n","sub_path":"website/addons/zotero/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"79394258","text":"from pwn import *\nimport sys\n\n\nHost = '35.194.194.168'\nPort = 6666\n\nif len(sys.argv) == 1:\n r = process('./writeme', env={'LD_PRELOAD': './libc.so'})\nelse:\n r = remote(Host, Port)\n\none_gadget = 0xf1117 \n\nr.recvuntil('write :')\nr.sendline(str(0x600ba0))\nr.recvuntil('0x600ba0=')\nlibc = int(r.recvuntil('\\n')[0:14], 0) - 0x6f690\nlog.info('libc: ' + hex(libc))\n\nr.recvuntil('write :')\nr.sendline(str(libc+one_gadget))\n\nr.interactive()\n\n\n","sub_path":"ais3-eof-qual-2017/writeme/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"94954043","text":"import os\n\nimport reframe.utility.sanity as sn\nfrom reframe.core.pipeline import RegressionTest\n\n\nclass BoostCrayGnuPythonTest(RegressionTest):\n\n def __init__(self, boost_version, cray_gnu_version, python_version,\n **kwargs):\n\n def normalize(s):\n return s.replace('.', '_')\n\n super().__init__('boost_%s_cray_gnu_%s_python_%s_check' % (\n normalize(boost_version), normalize(cray_gnu_version),\n normalize(python_version)), os.path.dirname(__file__), **kwargs)\n self.descr = ('Test for Boost-%s for CrayGnu-%s with python %s '\n 'support') % (boost_version, cray_gnu_version,\n python_version)\n self.valid_systems = ['daint:mc', 'daint:gpu', 'dom:mc', 'dom:gpu']\n self.valid_prog_environs = ['PrgEnv-cray']\n python_major_version = python_version.split('.')[0]\n self.modules = ['Boost/%s-CrayGNU-%s-python%s' % (\n boost_version, cray_gnu_version, python_major_version)]\n self.executable = 'python%s hello.py' % python_major_version\n self.sanity_patterns = sn.assert_found('hello, world', self.stdout)\n python_include_suffix = 'm' if python_major_version == '3' else ''\n python_lib_suffix = '3' if python_major_version == '3' else ''\n self.variables = {\n 'PYTHON_INCLUDE': (r'${PYTHON_PATH}/include/python%s%s') % (\n python_version, python_include_suffix),\n 'PYTHON_BOOST_LIB': 'boost_python' + python_lib_suffix\n }\n self.maintainers = ['JB', 'AJ']\n self.tags = {'scs', 'production'}\n\n\ndef _get_checks(**kwargs):\n return [BoostCrayGnuPythonTest('1.65.0', '17.08', '2.7', **kwargs),\n BoostCrayGnuPythonTest('1.65.0', '17.08', '3.5', **kwargs)]\n","sub_path":"cscs-checks/libraries/boost/boost_python_check.py","file_name":"boost_python_check.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"369744744","text":"'''\nNote: Your solution should have O(l1.length + l2.length) time complexity, since this is what you will be asked to accomplish in an interview.\n\nGiven two singly linked lists sorted in non-decreasing order, your task is to merge them. In other words, return a singly linked list, also sorted in non-decreasing order, that contains the elements from both original lists.\n\nExample\n\nFor l1 = [1, 2, 3] and l2 = [4, 5, 6], the output should be\nmergeTwoLinkedLists(l1, l2) = [1, 2, 3, 4, 5, 6];\nFor l1 = [1, 1, 2, 4] and l2 = [0, 3, 5], the output should be\nmergeTwoLinkedLists(l1, l2) = [0, 1, 1, 2, 3, 4, 5].\n'''\n\n# Singly-linked lists are already defined with this interface:\n# class ListNode(object):\n# def __init__(self, x):\n# self.value = x\n# self.next = None\n#\ndef mergeTwoLinkedLists(l1, l2):\n li=[]\n while(l1!=None):\n li.append(l1.value)\n l1=l1.next\n while(l2!=None):\n li.append(l2.value)\n l2=l2.next\n if(len(li)==0):\n return l1\n li.sort()\n\n n = ListNode(li[0])\n m=n\n\n for el in range(1,len(li)):\n n.next=ListNode(li[el])\n n=n.next\n return m\n","sub_path":"Interview_Practice/Linked_List/mergeTwoLinkedLists.py","file_name":"mergeTwoLinkedLists.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"442488768","text":"# author:joketeng time:2018/11/25\r\nimport math\r\nnum = input().split()\r\nprime = []\r\n# 判断最后一个素数的大小\r\nx = float(num[1])\r\nif x > 6:\r\n n = x * math.log(x) + x * math.log(math.log(x))\r\n n = int(n)\r\nelse:\r\n n = 15\r\n\r\nflag = [1] * (n + 2)\r\np = 2\r\nwhile p <= n:\r\n prime.append(p)\r\n for i in range(2 * p, n + 1, p):\r\n flag[i] = 0\r\n while 1:\r\n p += 1\r\n if flag[p] == 1:\r\n break\r\n\r\n# 对需要的部分进行切片\r\nrst = prime[int(num[0]) - 1:int(num[1])]\r\nif len(rst) == 1:\r\n print(rst[0])\r\nelse:\r\n for i in range(len(rst) - 1):\r\n if (i+1) % 10 == 0:\r\n print(rst[i])\r\n else:\r\n print(rst[i], end=\" \")\r\n else:\r\n if len(rst) % 10 == 0:\r\n print(rst[-1])\r\n else:\r\n print(rst[-1], end=\"\")\r\n","sub_path":"pat-simple/1013-2.py","file_name":"1013-2.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"144008901","text":"# Implementation of Nelder Mead optimization algorithm\n# https://en.wikipedia.org/wiki/Nelder–Mead_method\n# testing with Rosenbrock function\n# https://en.wikipedia.org/wiki/Rosenbrock_function\n# Author - Prof. Sumith Yesudasan\n# Year 2020\n\nimport numpy as np\nimport math\nimport time\n\ndef cost_estimate(x,n):\n a = 2.0; b = 100;\n cost = (a-x[0])**2 + b*(x[1]-x[0]**2)**2;\n return cost\n\ndef create_initial_simplex(x,n,dh):\n x_mat = np.zeros((n+1,n));\n for i in range(n):\n x_mat[0][i] = x[i];\n for j in range(1,n+1): # row navigation\n for i in range(n): # column nav\n if i == j-1:\n x_mat[j][i] = x[i] + dh;\n else:\n x_mat[j][i] = x[i];\n return x_mat\n\ndef sort_mats(cost_mat,x_mat,n):\n ind = np.argsort(cost_mat, axis=0);\n cost_mat = np.take_along_axis(cost_mat, ind, axis=0);\n x_mat = np.take_along_axis(x_mat, ind, axis=0);\n return cost_mat,x_mat;\n\ndef main():\n start_time = time.time()\n n = 2; dh = 0.001;\n x = [0.01, 0.25];\n alpha = 1.0; gamma = 2.0; rho = 0.5; sigma = 0.5;\n term_tol = 1e-15; MAX_ITER = 200; cur_iter = 0;\n stddev = 1000; # initial val\n\n cost_mat = np.zeros((n+1,1));\n x_0 = np.zeros((n,1));\n \n # step 1: estimate the cost of the current simplex\n x_mat = create_initial_simplex(x,n,dh);\n print(\"Here is the initial simplex\\n\",x_mat);\n for i in range(n+1): # from x_i to x_n+1\n cost_mat[i] = cost_estimate(x_mat[i][:],n);\n \n while stddev > term_tol and cur_iter < MAX_ITER: # termination criteria\n print(\"Current iteration = \", cur_iter);\n # sorting\n (cost_mat,x_mat) = sort_mats(cost_mat,x_mat,n);\n stddev = np.std(cost_mat); \n # step 2: centroid\n x_0 = np.sum(x_mat[0:n][:],axis=0)/n;\n # step 3: reflection\n x_n1 = x_mat[n][:]; # x_(n+1)\n x_r = x_0 + alpha*(x_0-x_n1);\n cost_r = cost_estimate(x_r,n);\n if cost_mat[0] <= cost_r and cost_r < cost_mat[n]:\n x_mat[n][:] = x_r; # Obtaining a new simplex\n cost_mat[n] = cost_r;\n else:\n # step 4: Expansion\n if cost_r < cost_mat[0]:\n x_e = x_0 + gamma*(x_r - x_0);\n cost_e = cost_estimate(x_e,n);\n if cost_e < cost_r:\n x_mat[n][:] = x_e; # Obtaining a new simplex\n cost_mat[n] = cost_e;\n cur_iter += 1;\n continue;\n else:\n x_mat[n][:] = x_r; # Obtaining a new simplex\n cost_mat[n] = cost_r;\n cur_iter += 1;\n continue;\n #step 5 Contraction\n else: \n x_c = x_0 + rho*(x_mat[n][:] - x_0);\n cost_c = cost_estimate(x_c,n);\n if cost_c < cost_mat[n]:\n x_mat[n][:] = x_c; # Obtaining a new simplex\n cost_mat[n] = cost_c;\n cur_iter += 1;\n continue;\n #step 6 Shrink\n else:\n for i in range(1,n+1): # from x_2 to x_n+1\n x_mat[i][:] = x_mat[0][:] + sigma*(x_mat[i][:] - x_mat[0][:]);\n cost_mat[i] = cost_estimate(x_mat[i][:],n);\n cur_iter += 1;\n # while ends here, terminate the whole business\n print(\"\\nTerminating..\\nstddev = \",stddev,\", tolerance = \",term_tol);\n print(\"Total iterations = \",cur_iter);\n print(\"Best x values = \", x_mat[0][:]);\n print(\"Cost = \\n\", cost_mat);\n end_time = time.time();\n print(\"Elapsed time: \",end_time - start_time);\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"Nelder_Mead/Rosen_optimized.py","file_name":"Rosen_optimized.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"457975575","text":"# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals\n\nimport logging\nimport numpy as np\nimport itertools\n\nfrom scipy.spatial import ConvexHull\nfrom pymatgen.analysis.pourbaix.entry import MultiEntry, ion_or_solid_comp_object\nfrom pymatgen.core.periodic_table import Element\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.analysis.reaction_calculator import Reaction, ReactionError\n\n\"\"\"\nModule containing analysis classes which compute a pourbaix diagram given a\ntarget compound/element.\n\"\"\"\n\nfrom six.moves import zip\n\n__author__ = \"Sai Jayaraman\"\n__copyright__ = \"Copyright 2012, The Materials Project\"\n__version__ = \"0.0\"\n__maintainer__ = \"Sai Jayaraman\"\n__credits__ = \"Arunima Singh, Joseph Montoya\"\n__email__ = \"sjayaram@mit.edu\"\n__status__ = \"Development\"\n__date__ = \"Nov 1, 2012\"\n\n\nlogger = logging.getLogger(__name__)\n\nPREFAC = 0.0591\nMU_H2O = -2.4583\n\n# TODO: There's a lot of functionality here that diverges\n# based on whether or not the pbx diagram is multielement\n# or not. Could be a more elegant way to\n# treat the two distinct modes.\n\nclass PourbaixDiagram(object):\n \"\"\"\n Class to create a Pourbaix diagram from entries\n Args:\n entries: Entries list containing both Solids and Ions\n comp_dict: Dictionary of compositions\n \"\"\"\n def __init__(self, entries, comp_dict=None):\n self._solid_entries = list()\n self._ion_entries = list()\n for entry in entries:\n if entry.phase_type == \"Solid\":\n self._solid_entries.append(entry)\n elif entry.phase_type == \"Ion\":\n self._ion_entries.append(entry)\n else:\n raise Exception(\"Incorrect Phase type - needs to be \\\n Pourbaix entry of phase type Ion/Solid\")\n if len(self._ion_entries) == 0:\n raise Exception(\"No ion phase. Equilibrium between ion/solid \"\n \"is required to make a Pourbaix Diagram\")\n self._unprocessed_entries = self._solid_entries + self._ion_entries\n self._elt_comp = comp_dict\n\n if comp_dict and len(comp_dict) > 1:\n self._multielement = True\n pbx_elements = set()\n for comp in comp_dict.keys():\n for el in [el for el in\n ion_or_solid_comp_object(comp).elements\n if el not in [\"H\", \"O\"]]:\n pbx_elements.add(el.symbol)\n self.pourbaix_elements = pbx_elements\n w = [comp_dict[key] for key in comp_dict]\n A = []\n for comp in comp_dict:\n comp_obj = ion_or_solid_comp_object(comp)\n Ai = []\n for elt in self.pourbaix_elements:\n Ai.append(comp_obj[elt])\n A.append(Ai)\n A = np.array(A).T.astype(float)\n w = np.array(w)\n A /= np.dot([a.sum() for a in A], w)\n x = np.linalg.solve(A, w)\n self._elt_comp = dict(zip(self.pourbaix_elements, x))\n\n else:\n self._multielement = False\n self.pourbaix_elements = [el.symbol\n for el in entries[0].composition.elements\n if el.symbol not in [\"H\", \"O\"]]\n # TODO: document the physical meaning\n # of ternary oxide of pbx diagrams in both modes\n self._elt_comp = {self.pourbaix_elements[0]: 1.0}\n self._make_pourbaix_diagram()\n\n def _create_conv_hull_data(self):\n \"\"\"\n Make data conducive to convex hull generator.\n \"\"\"\n if self._multielement:\n self._all_entries = self._process_multielement_entries()\n else:\n self._all_entries = self._unprocessed_entries\n entries_to_process = list()\n for entry in self._all_entries:\n entry.scale(entry.normalization_factor)\n entry.correction += (- MU_H2O * entry.nH2O + entry.conc_term)\n entries_to_process.append(entry)\n self._qhull_entries = entries_to_process\n return self._process_conv_hull_data(entries_to_process)\n\n def _process_conv_hull_data(self, entries_to_process):\n \"\"\"\n From a sequence of ion+solid entries, generate the necessary data\n for generation of the convex hull.\n \"\"\"\n data = []\n for entry in entries_to_process:\n row = [entry.npH, entry.nPhi, entry.g0]\n data.append(row)\n temp = sorted(zip(data, self._qhull_entries),\n key=lambda x: x[0][2])\n [data, self._qhull_entries] = list(zip(*temp))\n return data\n\n def _process_multielement_entries(self):\n \"\"\"\n Create entries for multi-element Pourbaix construction.\n\n This works by finding all possible linear combinations\n of entries that can result in the specified composition\n from the initialized comp_dict.\n \"\"\"\n N = len(self._elt_comp) # No. of elements\n entries = self._unprocessed_entries\n dummy_prod = Composition(self._elt_comp) \n total_comp = Composition(self._elt_comp)\n\n # generate all possible combinations of compounds that have all elts\n entry_combos = [itertools.combinations(entries, j+1) for j in range(N)]\n entry_combos = itertools.chain.from_iterable(entry_combos)\n entry_combos = filter(lambda x: dummy_prod < MultiEntry(x).total_composition, \n entry_combos)\n\n # Generate and filter entries\n processed_entries = []\n for entry_combo in entry_combos:\n processed_entry = self.process_multientry(entry_combo, total_comp)\n if processed_entry is not None:\n processed_entries.append(processed_entry)\n\n return processed_entries\n\n @staticmethod\n def process_multientry(entry_list, prod_comp):\n \"\"\"\n Static method for finding a multientry based on\n a list of entries and a product composition.\n Essentially checks to see if a valid aqueous\n reaction exists between the entries and the \n product composition and returns a MultiEntry\n with weights according to the coefficients if so.\n\n Args:\n entry_list ([Entry]): list of entries from which to\n create a MultiEntry\n comp (Composition): composition constraint for setting\n weights of MultiEntry\n \"\"\"\n dummy_oh = [Composition(\"H\"), Composition(\"O\")]\n try:\n # Get balanced reaction coeffs, ensuring all < 0 or conc thresh\n # Note that we get reduced compositions for solids and non-reduced \n # compositions for ions because ions aren't normalized due to\n # their charge state.\n entry_comps = [e.composition if e.phase_type=='Ion'\n else e.composition.reduced_composition \n for e in entry_list]\n rxn = Reaction(entry_comps + dummy_oh, [prod_comp])\n thresh = np.array([pe.conc if pe.phase_type == \"Ion\"\n else 1e-3 for pe in entry_list])\n coeffs = -np.array([rxn.get_coeff(comp) for comp in entry_comps])\n if (coeffs > thresh).all():\n weights = coeffs / coeffs[0]\n return MultiEntry(entry_list, weights=weights.tolist())\n else:\n return None\n except ReactionError:\n return None\n\n def _make_pourbaix_diagram(self):\n \"\"\"\n Calculates entries on the convex hull in the dual space.\n \"\"\"\n stable_entries = set()\n self._qhull_data = self._create_conv_hull_data()\n dim = len(self._qhull_data[0])\n if len(self._qhull_data) < dim:\n # TODO: might want to lift this restriction and\n # supply a warning instead, should work even if it's slow.\n raise NotImplementedError(\"Can only do elements with at-least \"\n \"3 entries for now\")\n if len(self._qhull_data) == dim:\n self._facets = [list(range(dim))]\n else:\n facets_hull = np.array(ConvexHull(self._qhull_data).simplices)\n self._facets = np.sort(np.array(facets_hull))\n logger.debug(\"Final facets are\\n{}\".format(self._facets))\n\n logger.debug(\"Removing vertical facets...\")\n vert_facets_removed = list()\n for facet in self._facets:\n facetmatrix = np.zeros((len(facet), len(facet)))\n count = 0\n for vertex in facet:\n facetmatrix[count] = np.array(self._qhull_data[vertex])\n facetmatrix[count, dim - 1] = 1\n count += 1\n if abs(np.linalg.det(facetmatrix)) > 1e-8:\n vert_facets_removed.append(facet)\n else:\n logger.debug(\"Removing vertical facet : {}\".format(facet))\n\n logger.debug(\"Removing UCH facets by eliminating normal.z >0 ...\")\n\n # Find center of hull\n vertices = set()\n for facet in vert_facets_removed:\n for vertex in facet:\n vertices.add(vertex)\n c = [0.0, 0.0, 0.0]\n c[0] = np.average([self._qhull_data[vertex][0]\n for vertex in vertices])\n c[1] = np.average([self._qhull_data[vertex][1]\n for vertex in vertices])\n c[2] = np.average([self._qhull_data[vertex][2]\n for vertex in vertices])\n\n # Shift origin to c\n new_qhull_data = np.array(self._qhull_data)\n for vertex in vertices:\n new_qhull_data[vertex] -= c\n\n # For each facet, find normal n, find dot product with P, and\n # check if this is -ve\n final_facets = list()\n for facet in vert_facets_removed:\n a = new_qhull_data[facet[1]] - new_qhull_data[facet[0]]\n b = new_qhull_data[facet[2]] - new_qhull_data[facet[0]]\n n = np.cross(a, b)\n val = np.dot(n, new_qhull_data[facet[0]])\n if val < 0:\n n = -n\n if n[2] <= 0:\n final_facets.append(facet)\n else:\n logger.debug(\"Removing UCH facet : {}\".format(facet))\n final_facets = np.array(final_facets)\n self._facets = final_facets\n\n stable_vertices = set()\n for facet in self._facets:\n for vertex in facet:\n stable_vertices.add(vertex)\n stable_entries.add(self._qhull_entries[vertex])\n self._stable_entries = stable_entries\n self._vertices = stable_vertices\n\n @property\n def facets(self):\n \"\"\"\n Facets of the convex hull in the form of [[1,2,3],[4,5,6]...]\n \"\"\"\n return self._facets\n\n @property\n def qhull_data(self):\n \"\"\"\n Data used in the convex hull operation. This is essentially a matrix of\n composition data and energy per atom values created from qhull_entries.\n \"\"\"\n return self._qhull_data\n\n @property\n def qhull_entries(self):\n \"\"\"\n Return qhull entries\n \"\"\"\n return self._qhull_entries\n\n @property\n def stable_entries(self):\n \"\"\"\n Returns the stable entries in the Pourbaix diagram.\n \"\"\"\n return list(self._stable_entries)\n \n @property\n def unstable_entries(self):\n \"\"\"\n Returns all unstable entries in the Pourbaix diagram\n \"\"\"\n return [e for e in self.qhull_entries if e not in self.stable_entries]\n\n @property\n def all_entries(self):\n \"\"\"\n Return all entries\n \"\"\"\n return self._all_entries\n\n @property\n def vertices(self):\n \"\"\"\n Return vertices of the convex hull\n \"\"\"\n return self._vertices\n\n @property\n def unprocessed_entries(self):\n \"\"\"\n Return unprocessed entries\n \"\"\"\n return self._unprocessed_entries\n","sub_path":"pymatgen/analysis/pourbaix/maker.py","file_name":"maker.py","file_ext":"py","file_size_in_byte":12323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"201922693","text":"from twisted.internet.task import LoopingCall\nfrom twisted.internet import defer\n\nfrom epu.ionproc.provisioner_query import ProvisionerQueryService\nfrom ion.test.iontest import IonTestCase\n\nclass TestProvisionerQueryService(IonTestCase):\n\n @defer.inlineCallbacks\n def setUp(self):\n\n yield self._start_container()\n self.patch(LoopingCall, \"start\", self._fake_start)\n\n self.loop_interval = None\n self.query_called = False\n\n def _fake_start(self, interval, now=True):\n self.loop_interval = interval\n\n def _query_error(self):\n self.query_called = True\n return defer.fail(Exception(\"expected\"))\n\n def _query_ok(self):\n self.query_called = True\n return defer.succeed(None)\n\n @defer.inlineCallbacks\n def test_query(self):\n query = ProvisionerQueryService(spawnargs={\"interval_seconds\": 5.0})\n yield self._spawn_process(query)\n\n self.assertEqual(self.loop_interval, 5.0)\n\n self.patch(query.client, \"query\", self._query_ok)\n query.query()\n\n self.assertTrue(self.query_called)\n\n @defer.inlineCallbacks\n def test_query_error(self):\n query = ProvisionerQueryService(spawnargs={\"interval_seconds\": 5.0})\n yield self._spawn_process(query)\n\n self.assertEqual(self.loop_interval, 5.0)\n\n self.patch(query.client, \"query\", self._query_error)\n # no exception should bubble up\n query.query()\n self.assertTrue(self.query_called)\n\n @defer.inlineCallbacks\n def tearDown(self):\n yield self._shutdown_processes()\n yield self._stop_container()\n","sub_path":"epu/provisioner/test/test_provisioner_query.py","file_name":"test_provisioner_query.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"430964919","text":"import numpy as np\nimport cv2 as cv\nimport glob\nfrom random import randint\n\ndef getData(N, M):\n cnt = 0\n data = []\n names = []\n for file in glob.glob('val2014/*.jpg'):\n if cnt >= N:\n break\n img = cv.imread(file)\n height, width = img.shape[:2]\n if height<400 or width<400:\n continue\n cx = randint(0, height-M)\n cy = randint(0, width-M)\n data.append(img[cx:cx+M,cy:cy+M])\n names.append(file.split('/')[1])\n cnt+=1\n return np.array(data), np.array(names)\n\nN = 20000\ndata, names = getData(N, 256)\nfor i in range(N):\n cv.imwrite('train/'+names[i], data[i])\n","sub_path":"ML/mv.py","file_name":"mv.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"380332161","text":"import pytest\nfrom selenium import webdriver\n\nlink = \"http://selenium1py.pythonanywhere.com/\"\n\n\n@pytest.fixture(scope=\"function\")\ndef browser():\n print(\"\\nstart browser for test..\")\n browser = webdriver.Chrome()\n yield browser\n print(\"\\nquit browser..\")\n browser.quit()\n\n\nclass TestMainPage1():\n\n @pytest.mark.smoke\n def test_guest_should_see_login_link(self, browser):\n browser.get(link)\n browser.find_element_by_css_selector(\"#login_link\")\n\n @pytest.mark.smoke\n @pytest.mark.linuxmint\n def test_guest_should_see_basket_link_on_the_main_page(self, browser):\n browser.get(link)\n browser.find_element_by_css_selector(\".basket-mini .btn-group > a\")\n\n @pytest.mark.skip\n def test_guest_should_see_shop_link_on_the_main_page(self, browser):\n browser.get(link)\n browser.find_element_by_css_selector(\"a.dropdown-toggle\")\n\n @pytest.mark.xfail\n def test_guest_should_see_favorite_button_on_the_main_page(self, browser):\n browser.get(link)\n browser.find_element_by_css_selector(\"button.favorite\")\n\n @pytest.mark.regression\n def test_guest_should_see_search_button_on_the_main_page(self, browser):\n browser.get(link)\n browser.find_element_by_css_selector(\"input.btn.btn-default\")\n\n @pytest.mark.xfail(reason=\"fixing this bug right now\")\n def test_guest_should_see_oscar_link_on_the_main_page(self, browser):\n browser.get(link)\n browser.find_element_by_css_selector(\".col-sm-7>a\")\n\n#Чтобы запустить тест с нужной маркировкой, нужно передать в командной строке параметр -m и нужную метку:\n# pytest -s -v -m smoke test_fixture8_function.py -прогнать один помеченый\n# pytest -s -v -m \"smoke and linuxmint\" test_fixture8_function.py -прогнать несколько помеченных\n# pytest -v test_fixture8_function.py -прогнать все\n# pytest -rX -v test_fixture8_function.py -прогнать все и показать отчет по помеченному reason=\n#регистрировать метки явно перед использованием через файл pytest.ini в корневой директории вашего тестового проекта","sub_path":"test_fixture8_function.py","file_name":"test_fixture8_function.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"581012980","text":"# -*- coding: utf-8 -*-\n'''\nResultData class test\n=====================\n'''\n\nimport unittest\nfrom tests.testutils import print_testtitle, validate_with_fail\nfrom builder.datatypes.builderexception import BuilderError\nfrom builder.datatypes import resultdata as rd\n\n\nclass ResultDataTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print_testtitle(rd.__name__, 'ResultData class')\n\n def test_instance(self):\n data = [\n # (data, is_succeeded, error, expect, exp_is_scd, exp_error)\n (True, [1,2,3], True, None,\n [1,2,3], True, None),\n ]\n def checker(rdata, is_succeeded, error, expect, exp_is_scd, exp_error):\n tmp = rd.ResultData(rdata, is_succeeded, error)\n self.assertIsInstance(tmp, rd.ResultData)\n self.assertEqual(tmp.data, expect)\n self.assertEqual(tmp.is_succeeded, exp_is_scd)\n self.assertEqual(tmp.error, exp_error)\n validate_with_fail(self, 'class instance', checker, data)\n","sub_path":"tests/datatypes/test_resultdata.py","file_name":"test_resultdata.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"587730358","text":"#!/usr/bin/env python2\n#-*- coding: utf-8 -*-\n\n\"\"\"\n.. py:module:: kaartdata\n\nHandles the reading, remembering, changing (colouring) and writing of a map,\nbut not it's visualisation.\n\ncontains the following classes:\n\n`~Kaart`\n\n represents a map containing '~Regio' classes\n and the methods to manipulate them\n\n`~Regio`\n\n represents a regio in a format that can be read and manipulated\n\nand the following constants:\n\n:const KLEUREN:\n dictionary of colours and their RGB values\n\n\n:const: DEFAULT_KAART\n the default CSV file's location; will be read if no paramaters are given\n\n\n:const: DEFAULT_KLEUR\n dictionary of the default colour every `~Regio` will be initialized with\n\n\n\n\"\"\"\n\nimport csv\n\nKLEUREN = {'rood' : (255,0,0),\n 'blauw' : (0,0,255),\n 'groen' : (0,255,0),\n 'geel' : (255,255,0),\n 'oranje': (255,128,0)}\n\nDEFAULT_KAART=r\"data/rajasthan.csv\"\n\nDEFAULT_KLEUR = {'wit':(255, 255, 255), 'zwart': (0,0,0)}\n\nclass Kaart(object):\n \"\"\"\n Class to represent a map containing multiple Regios & information about them\n\n :atr: regio_index:\n contains each Regio Object that is added to the Kaart\n\n :atr: regio_count:\n the amount of regios added to the Kaart\n\n :atr: kleuren_count:\n the amount each colour is used\n\n \"\"\"\n def __init__(self):\n self.regio_index = {}\n self.regio_count = 0\n self.kleuren_count = dict()\n for kleur in KLEUREN:\n self.kleuren_count[kleur] = 0\n\n\n def populate_kaart(self, filename=DEFAULT_KAART):\n \"\"\"\n Reads an CSV file for regions and their neighbours\n then turns them into Regio objects and adds them to the regio_index\n\n :param filename: filename of the CSV file containing the map info\n :type filename: str\n\n .. seealso: :func:`~Kaart.load_kaart`\n\n .. seealso: :func:`~Kaart.add_regio`\n\n .. seealso: `csv`\n\n \"\"\"\n lines = self.load_kaart(filename)\n for line in lines:\n regio = Regio(line[0], line[1].split(','))\n self.add_regio(regio)\n print(\"\\n\")\n\n\n def load_kaart(self, filename=DEFAULT_KAART):\n \"\"\"\n Reads an CSV file and returns each line as an array\n\n :param filename: the location of the CSV file\n :type filename: string\n\n :return: each row in the CSV file\n :rtype: list\n\n .. seealso :func:`~Kaart.populate_kaart`\n\n \"\"\"\n regios = list()\n try:\n with open(filename, 'r') as ftest:\n pass\n except IOError as e:\n print(e.message)\n exit(1)\n\n with open(filename, 'rU') as f:\n csvalues = csv.reader(f)\n\n try:\n csvalues.next()\n except AttributeError:\n csvalues.__next__()\n\n for row in csvalues:\n regios.append(row)\n\n return regios\n\n\n def load_kaartXml(self, filenaam=DEFAULT_KAART):\n raise NotImplementedError\n\n\n def add_regio(self, regio):\n \"\"\"\n adds new regios to a map\n\n :param regio: regio to add to regio_index\n :type regio: Regio\n\n \"\"\"\n if not regio.name in self.regio_index:\n print(\"Added regio {} to map\".format(regio.name))\n self.regio_index[regio.name] = regio\n self.regio_count += 1\n else:\n print(\"regio {} already on map\".format(regio.name));\n\n def check_kleur_buren(self,regio):\n \"\"\"\n Checks for any colours who can't be used to colour a Regio\n\n :param regio: Regio which you need to check\n :type regio: Regio\n\n :return: blacklisted colours\n :rtype: set\n\n .. seealso:: ~Kaart.get_buren\n\n .. seealso:: ~Regio.kleur_in\n\n \"\"\"\n kleuren = set()\n buren = self.get_buren(regio)\n for buur in buren:\n if buur.ingekleurd:\n kleuren.add(buur.kleur)\n return kleuren\n\n def get_buren(self, regio):\n \"\"\"\n Iterates over corresponding Regio objects from the regio_index for every neigbour\n\n :param regio: Regio whose neighbours you're looking for\n :type regio: Regio\n\n :return: buurregios, one at a time\n :rtype: Regio\n\n \"\"\"\n\n for buur in regio.buren:\n if buur in self.regio_index:\n yield self.regio_index[buur]\n\n\n def get_regios(self):\n \"\"\"\n Fetches all regios in the regio_index, one at a time\n\n :return: a regio Object in the regio_index\n :rtype: Regio\n\n \"\"\"\n for regio in self.regio_index.values():\n yield regio\n\n\n def kleur_kaart(self):\n \"\"\"\n Colours in all regios on a map, so that no adjacent Regios have the same colour\n\n .. seealso:: `~Kaart.kleur_regio`\n\n .. seealso:: `~Kaart.check_kleur_buren`\n\n \"\"\"\n for regio in self.get_regios():\n if not regio.ingekleurd:\n kleur = self.kleur_regio(regio)\n self.kleuren_count[kleur] += 1\n\n def kleur_regio(self, regio):\n \"\"\"\n Gives a regio a colour so that it doesn't have the same colour as any of it's neighbours\n\n :return: the colour used to colour the regio\n :rtype: str\n\n \"\"\"\n blacklist = self.check_kleur_buren(regio)\n regio.kleur_in(blacklist);\n return regio.kleur\n\n def get_regio(self, name):\n \"\"\"\n Searches the regio_index for a single regio\n\n :return: the regio object corresponding to the regio you were looking for, or None if it wasn't found\n :rtype: Regio\n\n \"\"\"\n if name in self.regio_index:\n return self.regio_index[name]\n else:\n return None\n\n\n def print_regios(self):\n \"\"\"\n Prints some information of every Regio in the regio_index\n\n \"\"\"\n for regio in self.get_regios():\n print(regio)\n\n\n def check_kleuren(self):\n \"\"\"\n Checks if the map was coloured correctly.\n That is to say, checks if every Regio was coloured and that no adjacent regios got the same colour.\n Prints the results out to the screen.\n\n .. seealso:: `~Kaart.kleur_kaart`\n\n \"\"\"\n netjesIngekleurd = True\n regios = self.get_regios()\n for regio in regios:\n if not regio.ingekleurd:\n print(\"Error region {} isn't coloured\".format(regio.name))\n netjesIngkleurd = False\n return False\n blacklist = self.check_kleur_buren(regio)\n ##print(\"{}:\".format(regio.name))\n ##print(\"blacklist: \" + blacklist.__str__())\n ##print(regio.kleur)\n if regio.kleur in blacklist:\n print(\"Error! Regio {} contains forbidden colour {}\".format(regio.name, regio.kleur))\n print(\"blacklist: {}\".format(blacklist))\n print(\"buren: {}\".format(regio.buren))\n netjesIngekleurd = False\n return False\n\n if netjesIngekleurd:\n print(\"Success!\")\n else:\n pass\n\n def tel_kleuren(self):\n \"\"\"\n Counts the amounts of times each colour was used to colour a regio, and prints the results to the screen\n\n \"\"\"\n for kleur in self.kleuren_count:\n print(\"{}:{}\".format(kleur, self.kleuren_count[kleur]))\n\n def reset_kaart(self):\n print(\"resetting kaart\")\n for regio in self.get_regios():\n regio.ingekleurd = False\n regio.kleur = \"wit\"\n for kleur in self.kleuren_count:\n self.kleuren_count[kleur] = 0\n\n\nclass Regio(object):\n \"\"\"\n Class to represent a Region of a specific map\n\n \"\"\"\n\n def __init__(self, name=str(), buren=list(), richting=list(), kleur=str(\"wit\")):\n self.name = name\n self.ingekleurd = False\n self.kleur = kleur\n self.buren = buren\n self.richting = richting\n\n def kleur_in(self, blacklist):\n ##print(\"blacklist: {}\".format(blacklist.__str__()))\n for kleur in KLEUREN.keys():\n if not kleur in blacklist:\n self.kleur = kleur\n self.ingekleurd = True\n print(\"{} ingekleurd met {}\".format(self.name, self.kleur))\n\n def __str__(self):\n return \"Regio {} heeft de buren {} en de kleur {}\\n\".format(self.name,\n self.buren,\n self.kleur)\n\n\n\nif __name__ == '__main__':\n #init kaart\n kaart = Kaart();\n\n kaart.populate_kaart(DEFAULT_KAART)\n\n #init regios\n regio1 = Regio(\"Zeeland\",[\"Zuid-Holland\",\"Noord-Brabant\"])\n regio2 = Regio(\"Zuid-Holland\",[\"Zeeland\",\"Noord-Brabant\",\"Noord-Holland\",\n \"Utrecht\"])\n regio3 = Regio(\"Noord-Brabant\", [\"Zeeland\",\"Zuid-Holland\",\"Gelderland\"])\n\n regio4 = Regio(\"Zuid-Holland\")\n\n ##kaart.add_regio(regio1)\n ##kaart.add_regio(regio2)\n ##kaart.add_regio(regio3)\n ##kaart.add_regio(regio4)\n\n kaart.kleur_kaart()\n print(\"\\n\")\n kaart.check_kleuren()\n kaart.tel_kleuren()\n\n\n\n\n\n#Laten staan a.u.b.\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","sub_path":"kaartkleuren/kaartdata.py","file_name":"kaartdata.py","file_ext":"py","file_size_in_byte":9333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"464450046","text":"import sys\nsys.stdin = open(\"줄세우기input.txt\")\n\nN=int(input())\n\ndata = list(map(int, input().split()))\nres=[]\ncnt=1\n\nfor i in range(1, N+1):\n if i==1:\n res.append(i)\n else:\n if data[i-1] != 0:\n temp=res[len(res)-data[i-1]:]\n res=res[:len(res)-data[i-1]]\n res.append(i)\n res+=temp\n elif data[i-1] == 0:\n res.append(i)\nprint(' '.join(map(str, res)))","sub_path":"codeXpert/0226/줄세우기.py","file_name":"줄세우기.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"453059370","text":"\nfrom tornado.web import Application, RequestHandler\nfrom tornado.ioloop import IOLoop\nfrom tornado.httpserver import HTTPServer\nimport json\nimport pymysql\n\n\nclass selectHandler(RequestHandler):\n\n def doSelect(self, table, id, name):\n db = sqlStart()\n result, n = db.select(table, id, name)\n if n == 0:\n for rows in result:\n self.write(str(rows) + \"
\")\n else:\n self.write(str(result))\n db.close()\n\n def get(self):\n name = self.get_argument(\"name\", \"\")\n id = self.get_argument(\"id\", \"\")\n table = self.get_argument(\"table\")\n self.doSelect(table, id, name)\n\n def post(self):\n body = self.request.body\n bodyJ = json.loads(body)\n name = bodyJ[\"name\"]\n id = bodyJ[\"id\"]\n table = bodyJ[\"table\"]\n self.doSelect(table, id, name)\n\n\nclass insertHandler(RequestHandler):\n\n def doInsert(self, table, value):\n db = sqlStart()\n result = db.insert(table, value)\n self.write(result)\n db.close()\n\n def get(self):\n table = self.get_argument(\"table\")\n value = self.get_argument(\"value\")\n self.doInsert(table, value)\n\n def post(self):\n body = self.request.body\n bodyJ = json.loads(body)\n table = bodyJ[\"table\"]\n value = bodyJ[\"value\"]\n self.doInsert(table, value)\n\n\nclass updateHandler(RequestHandler):\n\n def doUpdate(self, table, id, column, newValue):\n db = sqlStart()\n result = db.update(table, id, column, newValue)\n self.write(result)\n db.close()\n\n def get(self):\n table = self.get_argument(\"table\")\n id = self.get_argument(\"id\", \"\")\n column = self.get_argument(\"column\")\n newValue = self.get_argument(\"value\")\n self.doUpdate(table, id, column, newValue)\n\n def post(self):\n body = self.request.body\n bodyJ = json.loads(body)\n table = bodyJ[\"table\"]\n newValue = bodyJ[\"value\"]\n id = bodyJ[\"id\"]\n column = bodyJ[\"column\"]\n self.doUpdate(table, id, column, newValue)\n \n\nclass sqlStart:\n\n def __init__(self):\n self.db = pymysql.connect(user=\"root\", passwd=\"yugioh\", database=\"test\")\n self.cursor = self.db.cursor()\n self.selectError = \"No Record\"\n\n def close(self):\n self.db.close();\n\n def select(self, table, id, name):\n table = table.capitalize()\n if id != \"\":\n key = table + \"ID\"\n isID = 0\n elif name != \"\":\n key = table + \"Name\"\n name = \"\\\"\" + name + \"\\\"\"\n isID = 1\n else:\n isID = 2\n list = [id, name]\n sql = \"select * from \" + table\n if isID != 2:\n sql += \" Where \" + key + \" = \" + list[isID]\n try:\n self.cursor.execute(sql)\n result = self.cursor.fetchall()\n if result:\n return result, 0\n else:\n return self.selectError, 1\n except Exception as e:\n return e, 2\n\n def insert(self, table, value):\n table = table.capitalize()\n sql = \"insert into \" + table + \" values \" + value\n try:\n self.cursor.execute(sql)\n self.db.commit()\n return \"Inserted Successfully\"\n except Exception as e:\n self.db.rollback()\n return \"Inserted Failed \" + str(e)\n\n def update(self, table, id, column, newValue):\n table = table.capitalize()\n key = table + \"ID\"\n sql = \"update \" + table + \" set \" + column + \" = \" + newValue\n if id != \"\":\n sql += \" Where \" + key + \" = \" + id\n try:\n self.cursor.execute(sql)\n self.db.commit()\n return \"Updated Successfully\"\n except Exception as e:\n self.db.rollback()\n return \"Updated Failed \" + str(e)\n\n\ndef main():\n app = Application(handlers=[(r\"/select\", selectHandler),\n (r\"/insert\", insertHandler),\n (r\"/update\", updateHandler)])\n httpServer = HTTPServer(app)\n httpServer.listen(8080)\n IOLoop.current().start()\n\n\nif __name__ == '__main__':\n main()","sub_path":"HTTPServer.py","file_name":"HTTPServer.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"292872351","text":"#!/usr/bin/env python\n\nimport roslib; roslib.load_manifest('korus_smach')\nfrom state_machines_imports import *\nfrom korus_smach.pick_and_place_tools import trajectory_control, move_arm, ik, misc_tools\nfrom korus_smach.pick_and_place_tools.msg_imports import *\n\n\nclass TryAgain(smach.State):\n def __init__(self):\n smach.State.__init__(self,\n outcomes=['zero_state',\n 'default_state',\n 'bottom_state',\n 'done',\n 'error'])\n self._state = 0\n\n def execute(self, userdata):\n if self._state is -1:\n rospy.loginfo(\"All available seed states have been tested.\")\n self._state = 0\n return 'done'\n elif self._state is 0:\n self._state = 1\n return 'zero_state'\n elif self._state is 1:\n self._state = 2\n return 'default_state'\n elif self._state is 2:\n self._state = -1\n return 'bottom_state'\n else:\n rospy.logerr(\"Don't know this state (\" + str(self._state) + \")\")\n self._state = 0\n return 'error'\n\ndef createSM():\n sm_move_arm = smach.StateMachine(outcomes=['success', 'preempted', 'error'],\n input_keys=['goal_link_name','goal_pose', 'result'],\n output_keys=['result'])\n with sm_move_arm:\n sm_move_arm.userdata.default_pose = geometry_msgs.PoseStamped()\n sm_move_arm.userdata.default_pose.header.stamp = rospy.Time.now()\n sm_move_arm.userdata.default_pose.header.frame_id = \"base_footprint\"\n sm_move_arm.userdata.default_pose.pose.position.x = 0.40#0.052\n sm_move_arm.userdata.default_pose.pose.position.y = 0.0\n sm_move_arm.userdata.default_pose.pose.position.z = 0.50 #0.412\n sm_move_arm.userdata.default_pose.pose.orientation.x = 0.7071\n sm_move_arm.userdata.default_pose.pose.orientation.y = 0.0032\n sm_move_arm.userdata.default_pose.pose.orientation.z = -0.0032\n sm_move_arm.userdata.default_pose.pose.orientation.w = 0.7071\n sm_move_arm.userdata.wait_0sec = 0.0\n sm_move_arm.userdata.wait_1sec = 1.0\n sm_move_arm.userdata.wait_2sec = 2.0\n sm_move_arm.userdata.wait_5sec = 5.0\n sm_move_arm.userdata.zero_true = True\n sm_move_arm.userdata.zero_false = False \n sm_move_arm.userdata.default_true = True\n sm_move_arm.userdata.default_false = False \n sm_move_arm.userdata.bottom_true = True\n sm_move_arm.userdata.bottom_false = False \n sm_move_arm.userdata.robot_state = moveit_msgs.RobotState()\n\n# smach.StateMachine.add('ResetCollisionMap',\n# ServiceState('/korus/octomap_server/reset',\n# std_srvs.srv.Empty()),\n# transitions={'succeeded':'MoveArm',\n# 'preempted':'preempted',\n# 'aborted':'error'})\n smach.StateMachine.add('GetRobotState',\n misc_tools.GetRobotState(),\n remapping={'robot_state':'robot_state'},\n transitions={'success':'PrepareIKSeedCurrentState'})\n \n smach.StateMachine.add('PrepareIKSeedCurrentState',\n ik.PrepareIKSeed(),\n remapping={'zero':'zero_false',\n 'default':'default_false',\n 'bottom':'bottom_true',\n 'robot_state':'robot_state'},\n transitions={'success':'MoveArm',\n 'error':'error'})\n \n smach.StateMachine.add('PrepareIKSeedZeroState',\n ik.PrepareIKSeed(),\n remapping={'zero':'zero_true',\n 'default':'default_false',\n 'bottom':'bottom_true',\n 'robot_state':'robot_state'},\n transitions={'success':'MoveArm',\n 'error':'error'})\n \n smach.StateMachine.add('PrepareIKSeedDefaultState',\n ik.PrepareIKSeed(),\n remapping={'zero':'zero_false',\n 'default':'default_true',\n 'bottom':'bottom_true',\n 'robot_state':'robot_state'},\n transitions={'success':'MoveArm',\n 'error':'error'})\n \n smach.StateMachine.add('PrepareIKSeedBottomState',\n ik.PrepareIKSeed(),\n remapping={'zero':'zero_false',\n 'default':'default_false',\n 'bottom':'bottom_true',\n 'robot_state':'robot_state'},\n transitions={'success':'MoveArm',\n 'error':'error'})\n \n smach.StateMachine.add('MoveArm',\n SimpleActionState('move_group',\n moveit_msgs.MoveGroupAction,\n goal_cb=move_arm.moveArmGoalCB,\n result_cb=move_arm.moveArmResultCB,\n input_keys=['goal_pose',\n 'goal_link_name',\n 'robot_state'],\n output_keys=['error_code']),\n remapping={'goal_pose':'goal_pose',\n 'goal_link_name':'goal_link_name',\n 'robot_state':'robot_state',\n 'error_code':'error_code'},\n transitions={'succeeded':'ParseMoveArmErrorCode',\n 'aborted':'ParseMoveArmErrorCode',\n 'preempted':'preempted'})\n \n smach.StateMachine.add('ParseMoveArmErrorCode',\n misc_tools.MoveItErrorCodesParser(),\n transitions={'success':'success',\n 'parsed':'error',\n 'planning_failed':'TryAgain',\n 'no_ik_solution':'TryAgain'},\n remapping={'result':'result',\n 'error_code':'error_code'})\n \n smach.StateMachine.add('TryAgain',\n TryAgain(),\n transitions={'zero_state':'PrepareIKSeedZeroState',\n 'default_state':'PrepareIKSeedDefaultState',\n 'bottom_state':'PrepareIKSeedBottomState',\n 'done':'error',\n 'error':'error'})\n return sm_move_arm\n","sub_path":"korus_smach/src/korus_smach/state_machines/move_arm_sm.py","file_name":"move_arm_sm.py","file_ext":"py","file_size_in_byte":7763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"93274584","text":"from flask import Flask, render_template, request, session, redirect\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom werkzeug.utils import secure_filename\r\nfrom werkzeug.datastructures import FileStorage\r\nfrom flask_mail import Mail\r\nimport json\r\nimport time\r\nimport datetime\r\nimport math\r\nimport os\r\n\r\nwith open('config.json', 'r') as c:\r\n params = json.load(c)[\"params\"]\r\n\r\nlocal_server = True\r\napp = Flask(__name__)\r\napp.secret_key = 'rakesh'\r\napp.config['UPLOAD_FOLDER'] = params['upload_location']\r\napp.config.update(\r\n MAIL_SERVER='smtp.gmail.com',\r\n MAIL_PORT='465',\r\n MAIL_USE_SSL=True,\r\n MAIL_USERNAME=params['gmail-user'],\r\n MAIL_PASSWORD=params['gmail-password']\r\n)\r\nmail = Mail(app)\r\nif(local_server):\r\n app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']\r\nelse:\r\n app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']\r\n\r\ndb = SQLAlchemy(app)\r\n\r\n\r\nclass Contacts(db.Model):\r\n srno = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String(80), nullable=False)\r\n phone_no = db.Column(db.String(12), nullable=False)\r\n msg = db.Column(db.String(120), nullable=False)\r\n date = db.Column(db.String(12), nullable=True)\r\n email = db.Column(db.String(20), nullable=False)\r\n\r\n\r\nclass Posts(db.Model):\r\n srno = db.Column(db.Integer, primary_key=True)\r\n title = db.Column(db.String(80), nullable=False)\r\n tagline = db.Column(db.String(80), nullable=False)\r\n slug = db.Column(db.String(21), nullable=False)\r\n content = db.Column(db.String(120), nullable=False)\r\n date = db.Column(db.String(12), nullable=True)\r\n img_file = db.Column(db.String(12), nullable=True)\r\n comments = db.relationship('Comments', backref='title', lazy='dynamic')\r\n\r\n def get_comments(self):\r\n return Comment.query.filter_by(post_srno=post.srno)\r\n\r\n def __repr__(self):\r\n return '' % (self.content)\r\n\r\n\r\nclass Comments(db.Model):\r\n sno = db.Column(db.Integer, primary_key=True)\r\n username = db.Column(db.String(80), nullable=False)\r\n date = db.Column(db.String(12), nullable=True)\r\n content = db.Column(db.String(120), nullable=False)\r\n post_srno = db.Column(db.Integer, db.ForeignKey('posts.srno'))\r\n\r\n def __repr__(self):\r\n return '' % (self.body)\r\n\r\n # pagination logic\r\n # first\r\n # previous = #\r\n # next= page+1\r\n # middele\r\n # previous = page-1\r\n # next = page + 1\r\n # last\r\n # previous = page-1\r\n # next = #\r\n\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n posts = Posts.query.filter_by().all()\r\n posts.reverse()\r\n last = math.ceil(len(posts)/int(params['no_of_post']))\r\n page = request.args.get('page')\r\n if (not str(page).isnumeric()):\r\n page = 1\r\n page = int(page)\r\n posts = posts[(page-1)*int(params['no_of_post']):(page-1) *\r\n int(params['no_of_post'])+int(params['no_of_post'])]\r\n if (page == 1):\r\n prev = \"#\"\r\n next = \"/?page=\" + str(page + 1)\r\n elif (page == last):\r\n prev = \"/?page=\" + str(page - 1)\r\n next = \"#\"\r\n else:\r\n prev = \"/?page=\" + str(page - 1)\r\n next = \"/?page=\" + str(page + 1)\r\n\r\n return render_template('index.html', params=params, posts=posts, prev=prev, next=next)\r\n\r\n\r\n@app.route(\"/post//\", methods=['GET', 'POST'])\r\ndef post_route(post_slug, post_srno):\r\n post = Posts.query.filter_by(slug=post_slug).first()\r\n comments = Comments.query.filter_by(post_srno=post.srno).all()\r\n no_of_comments = len(comments)\r\n\r\n if(request.method == 'POST'):\r\n username = request.form.get('username')\r\n content = request.form.get('content')\r\n no_of_comments = no_of_comments\r\n date = datetime.datetime.now()\r\n post_srno = Posts.srno\r\n comment = Comments(username=username, content=content,\r\n date=date, post_srno=post.srno)\r\n if (username == content or username == '' or content == ''):\r\n return render_template('post.html', params=params, comments=comments, post=post)\r\n else:\r\n db.session.add(comment)\r\n db.session.commit()\r\n return render_template('post.html', params=params, comments=comments, post=post)\r\n\r\n\r\n@app.route(\"/about\")\r\ndef about():\r\n return render_template('about.html', params=params)\r\n\r\n\r\n@app.route(\"/comments\", methods=['GET', 'POST'])\r\ndef comment_control():\r\n posts = Posts.query.filter_by().all()\r\n if 'user' in session and session['user'] == params['admin_username']:\r\n comments = Comments.query.filter_by().all()\r\n return render_template('comment-control.html', params=params, posts=posts, comments=comments)\r\n\r\n if request.method == 'POST':\r\n username = request.form.get('uname')\r\n password = request.form.get('pass')\r\n comments = Comments.query.filter_by().all()\r\n if (username == params['admin_username'] and password == params['admin_password']):\r\n session['user'] = username\r\n return render_template('comment-control.html', params=params, comments=comments, posts=posts)\r\n\r\n return render_template('login.html', params=params)\r\n\r\n\r\n@app.route(\"/dashboard\", methods=['GET', 'POST'])\r\ndef login():\r\n if 'user' in session and session['user'] == params['admin_username']:\r\n posts = Posts.query.filter_by().all()\r\n return render_template('dashboard.html', params=params, posts=posts)\r\n\r\n if request.method == 'POST':\r\n username = request.form.get('uname')\r\n password = request.form.get('pass')\r\n posts = Posts.query.filter_by().all()\r\n if (username == params['admin_username'] and password == params['admin_password']):\r\n session['user'] = username\r\n return render_template('dashboard.html', params=params, posts=posts)\r\n\r\n return render_template('login.html', params=params)\r\n\r\n\r\n@app.route(\"/edit/\", methods=['GET', 'POST'])\r\ndef edit(srno):\r\n if 'user' in session and session['user'] == params['admin_username']:\r\n if request.method == 'POST':\r\n box_title = request.form.get('title')\r\n tagline = request.form.get('tagline')\r\n slug = request.form.get('slug')\r\n img_file = request.form.get('img_file')\r\n content = request.form.get('content')\r\n date = datetime.datetime.now()\r\n\r\n if (srno == '0'):\r\n post = Posts(title=box_title, tagline=tagline, slug=slug,\r\n img_file=img_file, content=content, date=date)\r\n db.session.add(post)\r\n db.session.commit()\r\n return redirect('/post/'+slug)\r\n else:\r\n post = Posts.query.filter_by(srno=srno).first()\r\n post.title = box_title\r\n post.tagline = tagline\r\n post.slug = slug\r\n post.img_file = img_file\r\n post.content = content\r\n post.date = date\r\n db.session.commit()\r\n return redirect('/post/'+slug)\r\n post = Posts.query.filter_by(srno=srno).first()\r\n return render_template('edit.html', params=params, srno=srno, post=post)\r\n\r\n\r\n@app.route(\"/contact\", methods=['GET', 'POST'])\r\ndef contact():\r\n if(request.method == 'POST'):\r\n name = request.form.get('name')\r\n email = request.form.get('email')\r\n phone = request.form.get('phone')\r\n message = request.form.get('message')\r\n entry = Contacts(name=name, phone_no=phone,\r\n msg=message, date=time.asctime(time.localtime(time.time())), email=email)\r\n date = time.asctime(time.localtime(time.time()))\r\n db.session.add(entry)\r\n db.session.commit()\r\n mail.send_message('New message from ' + name,\r\n sender=email,\r\n recipients=[params['gmail-user']],\r\n body=message + \"\\n\" + phone+\"\\n\"+date\r\n )\r\n return render_template('contact.html', params=params)\r\n\r\n\r\n@app.route(\"/delete/\", methods=['GET', 'POST'])\r\ndef delete(srno):\r\n if 'user' in session and session['user'] == params['admin_username']:\r\n post = Posts.query.filter_by(srno=srno).first()\r\n db.session.delete(post)\r\n db.session.commit()\r\n return redirect('/dashboard')\r\n\r\n\r\n@app.route(\"/comment/\", methods=['GET', 'POST'])\r\ndef delete_comment(sno):\r\n if 'user' in session and session['user'] == params['admin_username']:\r\n comment = Comments.query.filter_by(sno=sno).first()\r\n db.session.delete(comment)\r\n db.session.commit()\r\n return redirect('/comments')\r\n\r\n\r\n@app.route(\"/logout\")\r\ndef logout():\r\n session.pop('user')\r\n return redirect('/dashboard')\r\n\r\n\r\n@app.route('/uploader', methods=('GET', 'POST'))\r\ndef uploadimg():\r\n if 'user' in session and session['user'] == params['admin_username']:\r\n if (request.method == 'POST'):\r\n f = request.files['img_file']\r\n f.save(os.path.join(\r\n app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))\r\n return \"Uploaded Successfully\"\r\n\r\n\r\napp.run(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"5730136","text":"#!/usr/local/bin/python\n\n####\n# AUTHOR: Federico G. De Faveri\n# DATE:\tApr 2018\n# PURPOSE: This python script will get campaigns data from propellerads\n####\n\nimport requests\nimport time\nimport pprint\n\n#define pretty print object\npp = pprint.PrettyPrinter(indent=4)\n\n# opening file with credentials\nfilename = 'tokenfile' \nfincreds=open(filename,'r')\n\n# reading API key off file\nkey = fincreds.readline()\n\nkey = key.rstrip()\n\n# creating base url for our request\nbase_api_url = \"http://report.propellerads.com\"\n\n# setting params\naction = 'getCampaigns'\ndate_range = 'last_7_days'\nstat_columns = ['show','click','convers','convrate','cpm','ctr','profit']\ngroup_by = 'campaign_id'\n\n# setting payload\npayload = { 'action': action, 'key': key , 'date_range': date_range , 'stat_columns': stat_columns , 'group_by': group_by}\n\n# building the url\nurl = base_api_url\nprint(\"Sending GET request to \" + url)\nprint(\"\")\n\n# making the api request\nr = requests.get(url, params=payload)\n\n# working with answer\nstatus = r.status_code\n\nprint(\"STATUS: \" + str(status)) \nif status != 200:\n\tprint(\"Error\")\n\n\npp.pprint(r.json())\n\n\n\n\n\n","sub_path":"propellerAds/get-campaigns.py","file_name":"get-campaigns.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"456273658","text":"import re\r\nimport sys\r\nimport hashlib\r\nfrom json import JSONEncoder\r\nimport tempfile\r\nimport os\r\n\r\nfrom libs.dexsim.plugin import Plugin\r\nfrom smaliemu.emulator import Emulator\r\nfrom smaliemu.exception import UnsupportedOpcodeError\r\n\r\n\r\n__all__ = [\"NEW_STRING\"]\r\n\r\n\r\nclass NEW_STRING(Plugin):\r\n\r\n name = \"NEW_STRING\"\r\n version = '0.0.3'\r\n enabled = True\r\n\r\n def __init__(self, driver, methods, smali_files):\r\n self.emu = Emulator()\r\n Plugin.__init__(self, driver, methods, smali_files)\r\n\r\n def run(self):\r\n print('run Plugin: %s' % self.name, end=' -> ')\r\n self.__process_new_str()\r\n self.__process_to_string()\r\n\r\n def __process_new_str(self):\r\n '''\r\n 这里有2种情况:\r\n 1. 只有1个数值常量\r\n 2. 有1个以上的数值常量,会使用fill-array-data\r\n\r\n 这个都无所谓,直接执行代码片段即可\r\n '''\r\n for mtd in self.methods:\r\n if 'Ljava/lang/String;->([B)V' not in mtd.body:\r\n continue\r\n\r\n # TODO 初始化 array-data 所有的数组\r\n fill_array_datas = {}\r\n array_re = r'(array_[\\w\\d]+)\\s*\\.array-data[\\w\\s]+.end array-data$'\r\n ptn1 = re.compile(array_re)\r\n\r\n flag = False\r\n new_body = []\r\n array_key = None\r\n\r\n new_string_re = r'invoke-direct {(v\\d+), v\\d+}, Ljava/lang/String;->\\([\\[BCI]+\\)V'\r\n ptn2 = re.compile(new_string_re)\r\n for line in re.split(r'\\n+', mtd.body):\r\n new_line = None\r\n if 'Ljava/lang/String;->' in line:\r\n result = ptn2.search(line)\r\n if not result:\r\n new_body.append(line)\r\n continue\r\n return_register_name = result.groups()[0]\r\n\r\n tmp = new_body.copy()\r\n tmp.append(line)\r\n try:\r\n tmp.append('return-object %s' % return_register_name)\r\n decoded_string = (self.emu.call(tmp))\r\n if decoded_string:\r\n new_line = 'const-string %s, \"%s\"' % (return_register_name, decoded_string)\r\n except Exception as e:\r\n # TODO log2file\r\n pass\r\n\r\n if new_line:\r\n flag = True\r\n new_body.append(new_line)\r\n else:\r\n new_body.append(line)\r\n\r\n if flag:\r\n mtd.body = '\\n'.join(new_body)\r\n mtd.modified = True\r\n self.make_changes = True\r\n\r\n self.smali_files_update()\r\n\r\n\r\n def __process_to_string(self):\r\n to_string_re = (r'new-instance v\\d+, Ljava/lang/StringBuilder;[\\w\\W\\s]+?{(v\\d+)[.\\sv\\d]*}, Ljava/lang/StringBuilder;->toString\\(\\)Ljava/lang/String;')\r\n ptn2 = re.compile(to_string_re)\r\n for mtd in self.methods:\r\n\r\n if 'const-string' not in mtd.body:\r\n continue\r\n if 'Ljava/lang/StringBuilder;->' not in mtd.body:\r\n continue\r\n if 'Ljava/lang/StringBuilder;->toString()Ljava/lang/String;' not in mtd.body:\r\n continue\r\n\r\n flag = False\r\n new_content = None\r\n\r\n result = ptn2.finditer(mtd.body)\r\n\r\n for item in result:\r\n return_register_name = item.groups()[0]\r\n old_content = item.group()\r\n arr = re.split(r'\\n+', old_content)\r\n arr.append('return-object %s' % return_register_name)\r\n try:\r\n decoded_string = self.emu.call(arr)\r\n\r\n if len(self.emu.vm.exceptions) > 0:\r\n continue\r\n\r\n if decoded_string:\r\n new_content = 'const-string %s, \"%s\"' % (return_register_name, decoded_string)\r\n except Exception as e:\r\n # print(e)\r\n continue\r\n\r\n if new_content:\r\n flag = True\r\n mtd.body = mtd.body.replace(old_content, new_content)\r\n\r\n if flag:\r\n mtd.modified = True\r\n self.make_changes = True\r\n\r\n self.smali_files_update()\r\n","sub_path":"libs/dexsim/plugins/new_string.py","file_name":"new_string.py","file_ext":"py","file_size_in_byte":4401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"595121104","text":"\"\"\"\r\nRESULTS\r\nReads results from file and displays them\r\n\"\"\"\r\n\r\nif __name__ == '__main__':\r\n from numpy import load, hstack\r\n from time import sleep\r\n import cv2\r\n\r\n truths = load('Results/truths.npy')\r\n predictions = load('Results/predictions.npy')\r\n\r\n for truth, prediction in zip(truths, predictions):\r\n cv2.imshow('Results', hstack((truth, prediction)))\r\n ch = 0xFF & cv2.waitKey(1)\r\n if ch == 27: break\r\n\r\n sleep(0.5)\r\n\r\n cv2.destroyAllWindows()\r\n","sub_path":"see_results.py","file_name":"see_results.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"648747629","text":"# -------------\n# Pengfei Yu\n#\n\n\"\"\"Interface class for `RNAstructure `_ executable programs. \"\"\"\n\n\nimport os\nimport re\nimport subprocess\nimport tempfile\nimport sys\n\nclass RNAstructure(object):\n \"\"\"\n Interface class for `RNAstructure `_ executable programs.\n \"\"\"\n def __init__(self, exe_path=None):\n \"\"\"\n Initiation of object\n \n :param exe_path: the folder path of the RNAstructure executables\n \n Example:\n\n >>> from RNAstructure import RNAstructure\n >>> RNA_prog = RNAstructure(exe_path=\"/home/yu68/Software/RNAstructure/exe/\")\n \"\"\"\n if exe_path==None:\n self.exe_path=''\n else:\n self.exe_path = exe_path\n self.datapath=self.exe_path+\"/../data_tables/\"\n os.environ['DATAPATH'] = self.datapath\n \n def DuplexFold(self,seq1=None,seq2=None,dna=False):\n '''\n Use \"DuplexFold\" program to calculate the minimum folding between two input sequences\n\n :param seq1,seq2: two DNA/RNA sequences as string, or existing fasta file name\n :param dna: boolean input. Specify then DNA parameters are to be used\n :returns: minimum binding energy, (unit: kCal/Mol)\n\n Example:\n\n >>> from RNAstructure import RNAstructure\n >>> RNA_prog = RNAstructure(exe_path=\"/home/yu68/Software/RNAstructure/exe/\")\n >>> seq1 = \"TAGACTGATCAGTAAGTCGGTA\"\n >>> seq2 = \"GACTAGCTTAGGTAGGATAGTCAGTA\"\n >>> energy=RNA_prog.DuplexFold(seq1,seq2)\n >>> print energy\n '''\n cmd = [os.path.join(self.exe_path,\"DuplexFold\")]\n #sequences\n seq1_file=None\n if seq1.endswith(\"fasta\"):\n cmd.append(seq1)\n elif seq1 is not None:\n seq1_file = tempfile.NamedTemporaryFile(mode='w')\n seq1_file.write(\">seq1\\n\")\n seq1_file.write(seq1)\n seq1_file.flush()\n cmd.append(seq1_file.name)\n seq2_file=None\n if seq2.endswith(\"fasta\"):\n cmd.append(seq2)\n elif seq2 is not None:\n seq2_file = tempfile.NamedTemporaryFile(mode='w')\n seq2_file.write(\">seq2\\n\")\n seq2_file.write(seq2)\n seq2_file.flush()\n cmd.append(seq2_file.name)\n # output ct file\n ct_file = tempfile.NamedTemporaryFile(mode='w')\n cmd.append(ct_file.name)\n # DNA or RNA\n if dna==True:\n cmd.append('-d')\n # Excuting program\n cmd = \" \".join(cmd)\n os.system(cmd+\"> /dev/null 2>/dev/null\")\n if seq1_file is not None:\n seq1_file.close()\n if seq2_file is not None:\n seq2_file.close()\n #parsing result\n out = open(ct_file.name).read()\n decoded = re.search(r'ENERGY = (?P\\S+)', out)\n ct_file.close()\n try:\n return float(decoded.groupdict()['prob'])\n except:\n return 0.0\n\n def Fold(self,seq=None,ct_name=None,sso_file=None,Num=1):\n '''\n Use \"Fold\" program to predict the secondary structure and output dot format.\n\n :param seq: one DNA/RNA sequence as string, or existing fasta file name\n :param ct_name: specify to output a ct file with this name, otherwise store in temp, default: None\n :param sso_file: give a single strand offset file, format see http://rna.urmc.rochester.edu/Text/File_Formats.html#Offset\n :param Num: choose Num th predicted structure\n :returns: dot format of RNA secondary structure and RNA sequence.\n\n Example:\n\n >>> from RNAstructure import RNAstructure\n >>> RNA_prog = RNAstructure(exe_path=\"/home/yu68/Software/RNAstructure/exe/\")\n >>> seq = \"AUAUAAUUAAAAAAUGCAACUACAAGUUCCGUGUUUCUGACUGUUAGUUAUUGAGUUAUU\"\n >>> sequence,dot=RNA_prog.Fold(seq)\n >>> assert(seq==sequence)\n '''\n cmd = [os.path.join(self.exe_path,\"Fold\")]\n cmd2 = [os.path.join(self.exe_path,\"ct2dot\")]\n #sequences\n seq_file=None\n if seq.endswith(\"fasta\"):\n cmd.append(seq)\n elif seq is not None:\n seq_file = tempfile.NamedTemporaryFile(mode='w')\n seq_file.write(\">seq\\n\")\n seq_file.write(seq)\n seq_file.flush()\n cmd.append(seq_file.name)\n # output ct file\n if ct_name==None:\n ct_file = tempfile.NamedTemporaryFile(mode='w')\n cmd.append(ct_file.name)\n cmd2.append(ct_file.name)\n else:\n cmd.append(ct_name)\n cmd2.append(ct_name)\n # output dot file\n dot_file = tempfile.NamedTemporaryFile(mode='w')\n #cmd.append('-mfe') # only the best one\n # single strand offset\n if sso_file!=None:\n cmd.append(\"-sso\")\n cmd.append(sso_file) \n\n cmd2.append('%d'%(Num)) # Num th structure\n cmd2.append(dot_file.name)\n \n # only the best one\n #cmd.append(\"-m 1\") \n \n # Excuting program\n cmd = \" \".join(cmd)\n cmd2 = \" \".join(cmd2)\n os.environ['DATAPATH'] = self.datapath\n os.system(cmd+\"> /dev/null 2>/dev/null\")\n os.system(cmd2+\"> /dev/null 2>/dev/null\")\n if seq_file is not None:\n seq_file.close()\n #parsing result\n out = open(dot_file.name).read().split('\\n')\n sequence = out[1].strip()\n dot = out[2].strip()\n return sequence,dot\n \n def scorer(self,ct_name1,ct_name2):\n '''\n Use 'scorer' pogram to compare a predicted secondary structure to an accepted structure. It calculates two quality metrics, sensitivity and PPV\n \n :param ct_name1: The name of a CT file containing predicted structure data.\n :param ct_name2: The name of a CT file containing accepted structure data, can only store one structure.\n :return: sensitivity, PPV, number of the best predicted structure.\n \n Example:\n\n >>> ct_name1 = \"temp_prediction.ct\"\n >>> ct_name2 = \"temp_accept.ct\"\n >>> from RNAstructure import RNAstructure\n >>> RNA_prog = RNAstructure(exe_path=\"/home/yu68/Software/RNAstructure/exe/\")\n >>> sensitivity, PPV, Number = RNA_prog.scorer(ct_name1,ct_name2)\n '''\n cmd = [os.path.join(self.exe_path,\"scorer\")]\n cmd.append(ct_name1)\n cmd.append(ct_name2)\n output_file = tempfile.NamedTemporaryFile(mode='w')\n cmd.append(output_file.name)\n cmd=\" \".join(cmd)\n os.system(cmd+\"> /dev/null 2>/dev/null\")\n out=open(output_file.name).read().split(\"\\n\")\n n=0\n maximum=0.0\n sensitivity = 0.0\n PPV = 0.0\n number = 1\n for l in out:\n if l.startswith(\"Score\"):\n n+=1\n continue\n if l.startswith(\"Sensitivity\"):\n o = re.search(r'Sensitivity: (?P.*) = (?P.*)%',l)\n s = float(o.groupdict()['percent'])/100\n if l.startswith(\"PPV\"):\n o = re.search(r'PPV: (?P.*) = (?P.*)%',l)\n p = float(o.groupdict()['percent'])/100\n if s+p > maximum:\n sensitivity = s\n PPV = p\n maximum = s+p\n number=n\n return sensitivity, PPV, number\n\n\n# dot to block\ndef dot2block(dot_string,name=\"Default\"):\n '''\n convert dot format of RNA secondary structure into several linked blocks\n\n :param dot_string: the dot format of RNA secondary structure\n :param name: name of the RNA\n :return: A list of all stems, each stem is a dictionary with 'source' and 'target'\n\n Example:\n \n >>> from RNAstructure import dot2block\n >>> stems = dot2block(\"(((((...)))...(((...)))..))\",\"RNA_X\")\n >>> print stems\n [{'source': {'start': 2, 'chr': 'test', 'end': 4}, 'target': {'start': 8, 'chr': 'test', 'end': 10}}, {'source': {'start': 14, 'chr': 'test', 'end': 16}, 'target': {'start': 20, 'chr': 'test', 'end': 22}}, {'source': {'start': 0, 'chr': 'test', 'end': 1}, 'target': {'start': 25, 'chr': 'test', 'end': 26}}] \n \n '''\n posRegister=[]\n pairRegister=[]\n stems=[]\n def dumpPairRegister(pairRegister,stems,name):\n #print \"source:%d-%d; target:%d-%d\"%(pairRegister[-1][0],pairRegister[0][0],pairRegister[-1][1],pairRegister[0][1])\n stems.append({\"source\":{\"chr\":name,\"start\":pairRegister[-1][0],\"end\":pairRegister[0][0]},\"target\":{\"chr\":name,\"start\":pairRegister[0][1],\"end\":pairRegister[-1][1]}})\n pairRegister=[]\n return pairRegister,stems\n\n for i in range(len(dot_string)):\n char = dot_string[i]\n if char==\".\": continue\n if char==\"(\":\n posRegister.append(i)\n if char==\")\":\n first = posRegister.pop()\n pair=[first,i]\n if (len(pairRegister)>0):\n if (pairRegister[-1][0]-first>1) or (i-pairRegister[-1][1]>1):\n pairRegister,stems=dumpPairRegister(pairRegister,stems,name);\n pairRegister.append(pair)\n \n if (len(pairRegister)>0):\n pairRegister,stems=dumpPairRegister(pairRegister,stems,name);\n\n return stems \n","sub_path":"src/RNAstructure/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"266750395","text":"# Intersection of polylines\n# Maximum distance from centriod to perpendicular line of the road.\n# Genereate new lane marking based on updated coordinates of polyline\nfrom __future__ import division\nimport math\nimport pickle\nfrom beamngpy import BeamNGpy, Scenario, Road, Vehicle, setup_logging\nimport networkx as nx\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfig=plt.figure()\nax=fig.add_subplot(1,1,1)\n\nfilename = 'passau'\npath = \"../resources/osm/\"\nmap_ways_serialize = path + filename + '.ways.serialize'\nmap_nodes_serialize = path + filename + '.nodes.serialize'\nmap_beamng_serialize = path + filename + '.nodes.serialize.beamng'\nmap_degree_serialize = path + filename + '.ways.degree.serialize'\n\nnode_dict = pickle.load(open(map_nodes_serialize, \"rb\"))\nprint(\"Nodes Loaded\")\n\ngraph = pickle.load(open(map_ways_serialize, \"rb\"))\nprint(\"Graph Loaded\")\n\nbeamng_dict = pickle.load(open(map_beamng_serialize, \"rb\"))\nprint(\"BeamNG Nodes Loaded\")\n\ngraph_degree = pickle.load(open(map_degree_serialize, \"rb\"))\nprint(\"Graph Degree\")\n\nV1_SPEED_INDEX_1 = 0\nV1_SPEED_INDEX_2 = 1\nV1_DISTANCE_INDEX_1 = 2\nV1_DISTANCE_INDEX_2 = 3\nV1_WIDTH_INDEX = 4\nV2_SPEED_INDEX_1 = 5\nV2_SPEED_INDEX_2 = 6\nV2_DISTANCE_INDEX_1 = 7\nV2_DISTANCE_INDEX_2 = 8\nV2_WIDTH_INDEX = 9\nPOINT_OF_IMPACT_RADIUS = 10\nPOINT_OF_IMPACT_ANGLE_1 = 11\nPOINT_OF_IMPACT_ANGLE_2 = 12\nPOINT_OF_IMPACT_ANGLE_3 = 13\nIMPACT_POSITION_X = 1\nIMPACT_POSITION_Y = 2\nV1_ROAD_ID = 123456\nV2_ROAD_ID = 654321\nroad_a = ''\nroad_b = ''\nroad_c = ''\nroad_a_distance = 18.545010801854016\nroad_b_distance = 82.41788560240022\nroad_c_distance = 47.37948935299994\n\n\ndef getPolyLineCoordinates(node_a,node_b, distance,width):\n #print(\"get polyline coordinate\")\n # Assumption. width from the center of the road.\n real_distance = getDistance(node_a,node_b)\n t = distance / real_distance\n\n if t == 0.0:\n t = 0.05\n\n point2 = (((1 - t) * node_a[0] + t * node_b[0]), ((1 - t) * node_a[1] + t * node_b[1]))\n\n dx = float(point2[0] - node_a[0])\n dy = float(point2[1] - node_a[1])\n\n L = float(math.sqrt(float(float(dx * dx) + float(dy * dy)))) # handle division by zero\n U = (float(-dy / L), float(dx / L))\n F = float(width)\n\n # Point on one side\n x2p = float(point2[0] + U[0] * F)\n y2p = float(point2[1] + U[1] * F)\n\n return x2p,y2p\n\n\ndef getDistance(node_a,node_b):\n dist = math.sqrt((node_a[1] - node_b[1]) ** 2 + (node_a[0] - node_b[0]) ** 2)\n return dist\n\n\ndef getV1BeamNGCoordinaes(total_distance_v1, width):\n global road_a\n v1_roads = road_a\n v1_roads_distance = road_a_distance\n #print(v1_roads_distance)\n v1_road_max = float(total_distance_v1 * v1_roads_distance)\n #print(v1_road_max)\n beamng_pos = \"\"\n v1_poly_distance = v1_road_max\n for node in v1_roads:\n node_distance = getDistance(beamng_dict[node[0]],beamng_dict[node[1]])\n v1_poly_distance = v1_poly_distance - node_distance\n if v1_poly_distance < 0:\n v1_poly_distance = v1_poly_distance + node_distance\n #print(\"road found\")\n beamng_pos = getPolyLineCoordinates(beamng_dict[node[0]],beamng_dict[node[1]],v1_poly_distance,width)\n break\n\n #print(beamng_pos)\n return beamng_pos\n\n\n\n\ndef getV2BeamNGCoordinaes(total_distance_v2, width):\n global road_b\n #print(\"beamng v2 coordinates\")\n #print(total_distance_v2)\n v2_roads = road_b\n v2_roads_distance = road_b_distance\n v2_road_max = float(total_distance_v2 * v2_roads_distance)\n #print(v2_road_max)\n beamng_pos = \"\"\n v2_poly_distance = v2_road_max\n for node in v2_roads:\n node_distance = getDistance(beamng_dict[node[0]],beamng_dict[node[1]])\n v2_poly_distance = v2_poly_distance - node_distance\n\n if v2_poly_distance < 0:\n v2_poly_distance = v2_poly_distance + node_distance\n #print(\"road found\")\n beamng_pos = getPolyLineCoordinates(beamng_dict[node[0]],beamng_dict[node[1]], v2_poly_distance, width)\n break\n\n return beamng_pos\n\n\n\ndef decoding_of_parameter(chromosome):\n #print(\"decoding of parameters\")\n # Speed\n v1_speed = int(str(chromosome[V1_SPEED_INDEX_1]) + str(chromosome[V1_SPEED_INDEX_2]))\n v2_speed = int(str(chromosome[V2_SPEED_INDEX_1]) + str(chromosome[V2_SPEED_INDEX_2]))\n\n #print (v1_speed)\n #print(v2_speed)\n # point of impact\n radius = chromosome[POINT_OF_IMPACT_RADIUS] % 3\n angle_str = str(chromosome[POINT_OF_IMPACT_ANGLE_1]) + str(chromosome[POINT_OF_IMPACT_ANGLE_2]) + str(chromosome[POINT_OF_IMPACT_ANGLE_3])\n angle = int(angle_str) % 360\n\n #print(radius)\n #print(angle)\n # point of impact (collision point provided by user)\n # https://stackoverflow.com/questions/2912779/how-to-calculate-a-point-with-an-given-center-angle-and-radius\n\n point_of_impact_x = IMPACT_POSITION_X + radius * math.cos(math.radians(angle)) # radians\n point_of_impact_y = IMPACT_POSITION_Y + radius * math.sin(math.radians(angle)) # radians\n impact_point = (point_of_impact_x,point_of_impact_y)\n #print(impact_point)\n\n # position length\n total_distance_v1 = float(int(str(chromosome[V1_DISTANCE_INDEX_1]) + str(chromosome[V1_DISTANCE_INDEX_2])) / 100)\n v1_pos_bg = getV1BeamNGCoordinaes(total_distance_v1, chromosome[V1_WIDTH_INDEX]) # get beamng coordinates (polyline coordinate). it will be always calculated from center - joint\n #print(v1_pos_bg)\n\n total_distance_v2 = float(int(str(chromosome[V2_DISTANCE_INDEX_1]) + str(chromosome[V2_DISTANCE_INDEX_2])) / 100)\n v2_pos_bg = getV2BeamNGCoordinaes(total_distance_v2, chromosome[V2_WIDTH_INDEX]) # get beamng coordinates (polyline coordinate). it will be always calculated from center - joint\n #print(v2_pos_bg)\n\n return v1_speed, v1_pos_bg, v2_speed, v2_pos_bg, impact_point\n\n\ndef generateRandomPopulation(N=10,Gene=14):\n #print(\"random population\")\n #print([[np.random.randint(0,9) for i in range(Gene)] for j in range(N)])\n initial_population = [[np.random.randint(0,9) for i in range(Gene)] for j in range(N)]\n return initial_population\n\n\ndef calculateDistance(x1, y1, x2, y2):\n dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n return dist\n\n\ndef getImpactPoint(road):\n point = road[0]\n point = beamng_dict[point[0]]\n return point\n\ndef getRoadDistance(road):\n #print(\"get road distance\")\n distance = 0\n for edge in road:\n point1 = beamng_dict[edge[0]]\n point2 = beamng_dict[edge[1]]\n distance = distance + calculateDistance(point1[0],point1[1], point2[0], point2[1])\n\n return distance\n\ndef geneticAlgorithmSimulation():\n\n global IMPACT_POSITION_X\n global IMPACT_POSITION_Y\n global road_a\n global road_b\n global road_c\n global road_a_distance\n global road_b_distance\n global road_c_distance\n\n print(\"Genetic Algorithm Simulation\")\n for tup in graph_degree:\n if tup[1] == 3:\n n = 3\n #print(list(nx.dfs_edges(graph, source=tup[0], depth_limit=n)))\n way_3 = list(nx.dfs_edges(graph, source=tup[0], depth_limit=n))\n\n l = way_3\n way_3 =[l[i:i + n] for i in range(0, len(l), n)]\n road_a = way_3[0]\n road_b = way_3[1]\n road_c = way_3[2]\n\n\n\n\n road_a_distance = getRoadDistance(road_a)\n road_b_distance = getRoadDistance(road_b)\n road_c_distance = getRoadDistance(road_c)\n\n impact_point = getImpactPoint(road_a)\n IMPACT_POSITION_X = impact_point[0]\n IMPACT_POSITION_Y = impact_point[1]\n\n initial_population = generateRandomPopulation(10)\n\n collision_points = []\n striker_points = []\n victim_points = []\n\n for chromosome in initial_population:\n print(chromosome)\n beamng_parameters = decoding_of_parameter(chromosome)\n print(beamng_parameters)\n striker_points.append(beamng_parameters[1])\n victim_points.append(beamng_parameters[3])\n collision_points.append(beamng_parameters[4])\n\n\n\n slist1, slist2 = zip(*striker_points)\n clist1, clist2 = zip(*collision_points)\n vlist1, vlist2 = zip(*victim_points)\n\n plt.scatter(slist1, slist2, c='blue', alpha=0.5, label='striker')\n plt.scatter(clist1, clist2, c='red', alpha=0.5, label='collision')\n plt.scatter(vlist1, vlist2, c='green', alpha=0.5, label='victim')\n\n road_a_plt = []\n out = [item for t in road_a for item in t]\n for node in out:\n road_a_plt.append(beamng_dict[node])\n\n\n plta1, plta2 = zip(*road_a_plt)\n plt.plot(plta1,plta2,'k--')\n\n\n road_b_plt = []\n out = [item for t in road_b for item in t]\n for node in out:\n road_b_plt.append(beamng_dict[node])\n\n pltb1, pltb2 = zip(*road_b_plt)\n plt.plot(pltb1, pltb2, 'k--')\n\n\n road_c_plt = []\n out = [item for t in road_c for item in t]\n for node in out:\n road_c_plt.append(beamng_dict[node])\n\n pltc1, pltc2 = zip(*road_c_plt)\n plt.plot(pltc1, pltc2, 'k--')\n\n\n\n plt.legend(loc='best')\n plt.show()\n\n\n\ngeneticAlgorithmSimulation()\n\n","sub_path":"genetic_algorithm_driving/genetic_algorithm_simulation.py","file_name":"genetic_algorithm_simulation.py","file_ext":"py","file_size_in_byte":9018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"127698743","text":"from mock import Mock\nfrom pyquery import PyQuery\n\nfrom olympia import amo\nfrom olympia.amo.tests import TestCase\nfrom olympia.addons.templatetags.jinja_helpers import (\n statusflags, flag, contribution)\nfrom olympia.addons.models import Addon\n\n\nclass TestHelpers(TestCase):\n fixtures = ['base/addon_3615', 'base/users',\n 'addons/featured', 'base/collections',\n 'base/featured', 'bandwagon/featured_collections']\n\n def test_statusflags(self):\n ctx = {'APP': amo.FIREFOX, 'LANG': 'en-US'}\n\n # unreviewed\n a = Addon(status=amo.STATUS_NOMINATED)\n assert statusflags(ctx, a) == 'unreviewed'\n\n # featured\n featured = Addon.objects.get(pk=1003)\n assert statusflags(ctx, featured) == 'featuredaddon'\n\n # category featured\n featured = Addon.objects.get(pk=1001)\n assert statusflags(ctx, featured) == 'featuredaddon'\n\n def test_flags(self):\n ctx = {'APP': amo.FIREFOX, 'LANG': 'en-US'}\n\n # unreviewed\n a = Addon(status=amo.STATUS_NOMINATED)\n assert flag(ctx, a) == '
Not Reviewed
'\n\n # featured\n featured = Addon.objects.get(pk=1003)\n assert flag(ctx, featured) == '
Featured
'\n\n # category featured\n featured = Addon.objects.get(pk=1001)\n assert flag(ctx, featured) == '
Featured
'\n\n def test_contribution_box(self):\n a = Addon.objects.get(pk=7661)\n a.suggested_amount = '12'\n\n settings = Mock()\n settings.MAX_CONTRIBUTION = 5\n\n request = Mock()\n request.GET = {'src': 'direct'}\n\n c = {'LANG': 'en-us', 'APP': amo.FIREFOX, 'settings': settings,\n 'request': request}\n\n s = contribution(c, a)\n doc = PyQuery(s)\n # make sure input boxes are rendered correctly (bug 555867)\n assert doc('input[name=onetime-amount]').length == 1\n\n def test_src_retained(self):\n a = Addon.objects.get(pk=7661)\n a.suggested_amount = '12'\n\n settings = Mock()\n settings.MAX_CONTRIBUTION = 5\n\n request = Mock()\n\n c = {'LANG': 'en-us', 'APP': amo.FIREFOX, 'settings': settings,\n 'request': request}\n\n s = contribution(c, a, contribution_src='browse')\n doc = PyQuery(s)\n assert doc('input[name=source]').attr('value') == 'browse'\n","sub_path":"src/olympia/addons/tests/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"62815181","text":"import os\n\nroot_path = os.path.dirname(__file__)\nclass_list = os.listdir(os.path.join(root_path,\"samples\"))\nprint(class_list)\n\nos.chdir(os.path.join(root_path,\"training_set\"))\n\n# 循环将txt转换成vec\nfor item in class_list:\n cmd = \"opencv_createsamples.exe -vec \" + item + \".vec -info \" + item + \".txt -num 11 -w 60 -h 60\"\n os.system(cmd)","sub_path":"host_computer_training/get_vec.py","file_name":"get_vec.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"359998418","text":"import os\nfrom tqdm import tqdm\nimport json\nimport argparse\nimport pickle\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport pprint\nimport re\nimport shutil\nfrom datetime import datetime\n\n\nfrom src.models import shallow_conv, resnet_12, wide_resnet, dense_net\nfrom src.algorithm_trainer.algorithm_trainer import Meta_algorithm_trainer, Init_algorithm_trainer, TL_algorithm_trainer\nfrom src.algorithms.algorithm import SVM, ProtoNet, Ridge, InitBasedAlgorithm\nfrom src.optimizers import modified_sgd\nfrom src.data.dataset_managers import MetaDataLoader\nfrom src.data.datasets import MetaDataset, ClassImagesSet, SimpleDataset\n\n\ndef ensure_path(path):\n if not os.path.exists(path):\n os.makedirs(path)\n return path\n\n\ndef str2bool(arg):\n return arg.lower() == 'true'\n\n\ndef create_model_and_load_chkpt(args, dataset_name, checkpoint_path):\n\n print(\"\\n\", \"--\"*20, \"MODEL\", \"--\"*20)\n\n if args.model_type == 'resnet_12':\n if 'miniImagenet' in dataset_name or 'CUB' in dataset_name:\n model = resnet_12.resnet12(avg_pool=str2bool(args.avg_pool), drop_rate=0.1, dropblock_size=5,\n num_classes=args.num_classes_train, classifier_type=args.classifier_type,\n projection=str2bool(args.projection))\n else:\n model = resnet_12.resnet12(avg_pool=str2bool(args.avg_pool), drop_rate=0.1, dropblock_size=2,\n num_classes=args.num_classes_train, classifier_type=args.classifier_type,\n projection=str2bool(args.projection))\n elif args.model_type in ['conv64', 'conv48', 'conv32']:\n dim = int(args.model_type[-2:])\n model = shallow_conv.ShallowConv(z_dim=dim, h_dim=dim, num_classes=args.num_classes_train, x_width=image_size,\n classifier_type=args.classifier_type, projection=str2bool(args.projection))\n elif args.model_type == 'wide_resnet28_10':\n model = wide_resnet.wrn28_10(\n projection=str2bool(args.projection), classifier_type=args.classifier_type)\n elif args.model_type == 'wide_resnet16_10':\n model = wide_resnet.wrn16_10(\n projection=str2bool(args.projection), classifier_type=args.classifier_type)\n else:\n raise ValueError(\n 'Unrecognized model type {}'.format(args.model_type))\n print(\"Model\\n\" + \"==\"*27) \n print(model) \n\n print(f\"loading model from {checkpoint_path}\")\n model_dict = model.state_dict()\n chkpt = torch.load(checkpoint_path, map_location=torch.device('cpu'))\n chkpt_state_dict = chkpt['model']\n chkpt_state_dict_cpy = chkpt_state_dict.copy()\n # remove \"module.\" from key, possibly present as it was dumped by data-parallel\n for key in chkpt_state_dict_cpy.keys():\n if 'module.' in key:\n new_key = re.sub('module\\.', '', key)\n chkpt_state_dict[new_key] = chkpt_state_dict.pop(key)\n chkpt_state_dict = {k: v for k, v in chkpt_state_dict.items() if k in model_dict}\n model_dict.update(chkpt_state_dict)\n updated_keys = set(model_dict).intersection(set(chkpt_state_dict))\n print(f\"Updated {len(updated_keys)} keys using chkpt\")\n print(\"Following keys updated :\", \"\\n\".join(sorted(updated_keys)))\n missed_keys = set(model_dict).difference(set(chkpt_state_dict))\n print(f\"Missed {len(missed_keys)} keys\")\n print(\"Following keys missed :\", \"\\n\".join(sorted(missed_keys)))\n model.load_state_dict(model_dict)\n \n # Multi-gpu support and device setup\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.device_number\n print('Using GPUs: ', os.environ[\"CUDA_VISIBLE_DEVICES\"])\n model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))\n model.cuda()\n\n return model\n\n\n\ndef create_alg_and_trainer(args, algorithm_type, model):\n\n # algorithm\n if algorithm_type == 'InitBasedAlgorithm':\n algorithm = InitBasedAlgorithm(\n model=model,\n loss_func=torch.nn.CrossEntropyLoss(),\n method=args.init_meta_algorithm,\n alpha=args.alpha,\n inner_loop_grad_clip=args.grad_clip_inner,\n inner_update_method=args.inner_update_method,\n device='cuda')\n elif algorithm_type == 'ProtoNet':\n algorithm = ProtoNet(\n model=model,\n inner_loss_func=torch.nn.CrossEntropyLoss(),\n device='cuda',\n scale=args.scale_factor,\n metric=args.classifier_metric)\n elif algorithm_type == 'SVM':\n algorithm = SVM(\n model=model,\n inner_loss_func=torch.nn.CrossEntropyLoss(),\n scale=args.scale_factor,\n device='cuda')\n elif algorithm_type == 'Ridge':\n algorithm = Ridge(\n model=model,\n inner_loss_func=torch.nn.CrossEntropyLoss(),\n scale=args.scale_factor,\n device='cuda')\n elif algorithm_type == 'TransferLearning':\n \"\"\"\n We use the ProtoNet algorithm at test time.\n \"\"\"\n algorithm = ProtoNet(\n model=model,\n inner_loss_func=torch.nn.CrossEntropyLoss(),\n device='cuda',\n scale=args.scale_factor,\n metric=args.classifier_metric)\n else:\n raise ValueError(\n 'Unrecognized algorithm {}'.format(args.algorithm))\n\n\n if algorithm_type == 'InitBasedAlgorithm':\n trainer = Init_algorithm_trainer(\n algorithm=algorithm,\n optimizer=None,\n writer=None,\n log_interval=args.log_interval, \n save_folder='', \n grad_clip=None,\n num_updates_inner_train=args.num_updates_inner_train,\n num_updates_inner_val=args.num_updates_inner_val,\n init_global_iteration=None)\n elif algorithm_type == 'TransferLearning':\n trainer = TL_algorithm_trainer(\n algorithm=algorithm,\n optimizer=None,\n writer=None,\n log_interval=args.log_interval, \n save_folder='', \n grad_clip=None,\n init_global_iteration=None\n )\n else:\n trainer = Meta_algorithm_trainer(\n algorithm=algorithm,\n optimizer=None,\n writer=None,\n log_interval=args.log_interval, \n save_folder='', \n grad_clip=None,\n init_global_iteration=None)\n\n return trainer\n\n\ndef main(args):\n\n ####################################################\n # LOGGING AND SAVING #\n ####################################################\n args.output_folder = ensure_path('./runs/{0}'.format(args.output_folder))\n eval_results = f'{args.output_folder}/base_acc_results.txt'\n with open(eval_results, 'w') as f:\n f.write(\"--\"*20 + \"EVALUATION RESULTS\" + \"--\"*20 + '\\n')\n\n\n ####################################################\n # DATASET AND DATALOADER CREATION #\n ####################################################\n\n # json paths\n dataset_name = args.dataset_path.split('/')[-1]\n image_size = args.img_side_len\n basetest_file = os.path.join(args.dataset_path, 'base_test.json')\n print(\"Dataset name\", dataset_name, \"image_size\", image_size)\n \n \"\"\"\n 1. Create ClassImagesSet object, which handles preloading of images\n 2. Pass ClassImagesSet to MetaDataset which handles nshot, nquery and fixSupport\n 3. Create Dataloader object from MetaDataset\n \"\"\"\n\n print(\"\\n\", \"--\"*20, \"BASE\", \"--\"*20)\n \n \n base_classes = ClassImagesSet(basetest_file, preload=str2bool(args.preload_train))\n\n ####################################################\n # MODEL/BACKBONE CREATION #\n ####################################################\n \n model = create_model_and_load_chkpt(\n args, \n dataset_name=dataset_name, \n checkpoint_path=args.checkpoint)\n\n ####################################################\n # ALGORITHM AND ALGORITHM TRAINER #\n ####################################################\n\n trainer = create_alg_and_trainer(\n args, \n algorithm_type=args.algorithm,\n model=model)\n\n ####################################################\n # EVALUATION #\n ####################################################\n\n for run in range(args.n_runs):\n\n # randomly select args.n_examples_per_class for each base class\n if args.n_examples_per_class > 0:\n for _, class_imgs in base_classes.items():\n class_imgs.resample_images(n_chosen=args.n_examples_per_class)\n\n base_datasets = MetaDataset(\n dataset_name=dataset_name,\n support_class_images_set=base_classes,\n query_class_images_set=base_classes,\n image_size=image_size,\n support_aug=False,\n query_aug=False,\n fix_support=0,\n save_folder='')\n \n base_loaders = MetaDataLoader(\n dataset=base_datasets,\n n_batches=args.n_iterations_val,\n batch_size=args.batch_size_val,\n n_way=args.n_way_val,\n n_shot=args.n_shot_val,\n n_query=args.n_query_val, \n randomize_query=False,\n )\n\n results = trainer.run(\n mt_loader=base_loaders, is_training=False)\n \n with open(eval_results, 'a') as f:\n f.write(f\"Run {run+1} {args.n_way_val}w{args.n_shot_val}s: \")\n f.write(f\"Loss {round(results['test_loss_after']['loss'], 3)} Acc {round(results['test_loss_after']['accu'], 3)} \\n\")\n \n\nif __name__ == '__main__':\n\n \n parser = argparse.ArgumentParser(\n description='Training the feature backbone on all classes from all tasks.')\n \n parser.add_argument('--random-seed', type=int, default=0,\n help='')\n\n # Algorithm\n parser.add_argument('--algorithm', type=str, help='type of algorithm')\n \n # Model\n parser.add_argument('--model-type', type=str, default='gatedconv',\n help='type of the model')\n parser.add_argument('--classifier-type', type=str, default='no-classifier',\n help='classifier type [distance based, linear, GDA]')\n parser.add_argument('--scale-factor', type=float, default=1.,\n help='scalar factor multiplied with logits')\n\n\n # Initialization-based methods\n parser.add_argument('--alpha', type=float, default=0.0,\n help='inner learning rate for init based methods')\n parser.add_argument('--init-meta-algorithm', type=str, default='MAML',\n help='MAML/Reptile/FOMAML')\n parser.add_argument('--grad-clip-inner', type=float, default=0.0,\n help='gradient clip value in inner loop')\n parser.add_argument('--num-updates-inner-train', type=int, default=1,\n help='number of updates in inner loop')\n parser.add_argument('--num-updates-inner-val', type=int, default=1,\n help='number of updates in inner loop val')\n parser.add_argument('--inner-update-method', type=str, default='sgd',\n help='inner update method can be sgd or adam')\n\n\n # Dataset\n parser.add_argument('--dataset-path', type=str,\n help='which dataset to use')\n parser.add_argument('--img-side-len', type=int, default=84,\n help='width and height of the input images')\n parser.add_argument('--batch-size-val', type=int, default=10,\n help='batch size for validation')\n parser.add_argument('--n-query-val', type=int, default=15,\n help='how many samples per class for validation (meta val)')\n parser.add_argument('--n-shot-val', type=int, default=5,\n help='how many samples per class for train (meta val)')\n parser.add_argument('--n-way-val', type=int, default=5,\n help='how classes per task for train (meta val)')\n parser.add_argument('--label-offset', type=int, default=0,\n help='offset for label values during fine tuning stage')\n parser.add_argument('--eps', type=float, default=0.0,\n help='epsilon of label smoothing')\n parser.add_argument('--n-iterations-val', type=int, default=100,\n help='no. of iterations validation.') \n parser.add_argument('--preload-train', type=str, default=\"True\")\n parser.add_argument('--num-classes-train', type=int, default=0,\n help='no of train classes')\n parser.add_argument('--num-classes-val', type=int, default=0,\n help='no of novel (val) classes')\n \n\n # Miscellaneous\n parser.add_argument('--output-folder', type=str, default='maml',\n help='name of the output folder')\n parser.add_argument('--device-number', type=str, default='0',\n help='gpu device number')\n parser.add_argument('--log-interval', type=int, default=100,\n help='number of batches between tensorboard writes')\n parser.add_argument('--checkpoint', type=str, default='',\n help='path to saved parameters for alg.')\n parser.add_argument('--classifier-metric', type=str, default='',\n help='')\n parser.add_argument('--projection', type=str, default='',\n help='')\n parser.add_argument('--avg-pool', type=str, default='True',\n help='')\n parser.add_argument('--n-examples-per-class', type=int, default=5,\n help='number of examples chosen in the test set of a class')\n parser.add_argument('--n-runs', type=int, default=20,\n help='number of runs')\n \n \n args = parser.parse_args()\n\n # set random seed. only set for numpy, uncomment the below lines for torch and CuDNN.\n if args.random_seed != 0:\n np.random.seed(args.random_seed)\n \n # main function call\n main(args)\n","sub_path":"analysis/compute_base_acc_variance.py","file_name":"compute_base_acc_variance.py","file_ext":"py","file_size_in_byte":13708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"337370678","text":"from datetime import datetime\nimport mimetypes\nimport os\nimport re\nimport threading\nimport time\n\nfrom musik import log\nfrom musik.db import DatabaseWrapper, ImportTask, Track, Album, Artist, Disc\nfrom musik.importer.mediafile import MediaFile, UnreadableFileError\n\n\nclass ImportThread(threading.Thread):\n\n running = True # whether or not the thread should continue to run\n sa_session = None # database session\n log = None # logging instance\n\n def __init__(self):\n \"\"\"Creates a new instance of ImportThread and connects to the database.\n This design pattern is important: since the constructor runs synchonously,\n it ensures that two threads don't attempt to initialize the database at\n the same time.\n \"\"\"\n super(ImportThread, self).__init__(name=__name__)\n db = DatabaseWrapper()\n self.sa_session = db.get_session()\n\n # create a log object that uses the same session that we do so that we can write error messages\n # during transactions\n self.log = log.Log(__name__, self.sa_session)\n\n def run(self):\n \"\"\"Checks for new import tasks once per second and passes them off to\n the appropriate handler functions for completion.\n \"\"\"\n try:\n # process 'till you drop\n while self.running:\n\n # find the first uncompleted import task. This limits the\n # importer to being single-threaded, but ensures that jobs\n # that are stopped while in progress will complete on next\n # startup.\n task = self.sa_session.query(ImportTask).filter(ImportTask.completed == None).order_by(ImportTask.created).first()\n\n if task != None:\n # start processing it\n task.started = datetime.utcnow()\n self.sa_session.commit()\n self.log.info(u'Processing task %s' % task.uri)\n\n # process the task\n if os.path.isdir(task.uri):\n self.log.info(u'Importing directory %s' % task.uri)\n self.import_directory(task.uri)\n elif os.path.isfile(task.uri):\n self.log.info(u'Importing file %s' % task.uri)\n self.import_file(task.uri)\n else:\n self.log.warning(u'Unrecognized URI %s' % task.uri)\n\n task.completed = datetime.utcnow()\n self.sa_session.commit()\n self.log.info(u'finished processing task %s' % task.uri)\n\n time.sleep(1)\n finally:\n # always clean up - your mom doesn't work here\n if self.sa_session != None:\n self.sa_session.close()\n self.sa_session = None\n\n def import_directory(self, uri):\n \"\"\"Adds the specified directory to the library.\n In practice, this implements a recursive breadth-first search over the\n subtree rooted at uri. All files with a mimetype that starts with the\n string 'audio' will be put back into the import queue for additional\n processing. Returns True.\"\"\"\n search_queue = [uri]\n while len(search_queue) > 0:\n # this is the current working directory\n baseuri = search_queue.pop(0)\n if os.path.isdir(baseuri) == False:\n continue\n\n # TODO: directory permissions. Make sure that we can read before we try to\n # iterate over the subdirectories and files in the current working directory\n entries = os.listdir(baseuri)\n for subdir in entries:\n\n # if we found a directory, put it back on the queue. otherwise, process it\n newuri = os.path.join(baseuri, subdir)\n if os.path.isdir(newuri):\n search_queue.append(newuri)\n elif os.path.isfile(newuri):\n if self.is_mime_type_supported(newuri):\n # create a new import task for useful files\n newtask = ImportTask(newuri)\n self.sa_session.add(newtask)\n self.sa_session.commit()\n else:\n self.log.info(u'Ignoring file %s' % newuri)\n return True\n\n\n def is_mime_type_supported(self, uri):\n \"\"\"Takes a guess at the mimetype of the file at the specified uri.\n Returns True if the mimetype could be inferred and file contains audio\n data, false otherwise. Note that this function does not care whether or\n not the file actually exists.\"\"\"\n (mimetype, encoding) = mimetypes.guess_type(uri)\n return mimetype is not None and mimetype.startswith('audio')\n\n\n def guess_mime_type(self, uri):\n \"\"\"Returns the mimetype string of the file at the specified uri or None\"\"\"\n (mimetype, encoding) = mimetypes.guess_type(uri)\n return mimetype\n\n\n def import_file(self, uri):\n \"\"\"Adds the specified file to the library.\n Returns True if the file was successfully added to the database, or\n False if metadata could not be read or the file could not be added.\"\"\"\n\n # ensure that the uri isn't already in our library - we don't want duplicates\n track = self.sa_session.query(Track).filter(Track.uri == uri).first()\n if track == None:\n track = Track(uri)\n self.sa_session.add(track)\n else:\n self.log.info(u'The file %s is already in the library. Updating metadata...' % uri)\n\n try:\n metadata = MediaFile(uri)\n except UnreadableFileError:\n self.log.error(u'Could not extract metadata from %s' % uri)\n return False\n\n # artist\n artist = self.find_artist(metadata.artist, metadata.artist_sort, metadata.mb_artistid)\n if artist != None:\n if track.artist == None:\n track.artist = artist\n self.sa_session.add(artist)\n elif track.artist.id != artist.id:\n # TODO: conflict!\n self.log.warning(u'Artist conflict for track %s: %s != %s' % (track.uri, track.artist.name, artist.name))\n\n # album artist - use the artist if metadata isn't set\n album_artist = self.find_artist(metadata.albumartist, metadata.albumartist_sort)\n if album_artist != None:\n if track.album_artist == None:\n track.album_artist = album_artist\n self.sa_session.add(album_artist)\n elif track.album_artist.id != album_artist.id:\n # TODO: conflict!\n self.log.warning(u'Album artist conflict for track %s: %s != %s' % (track.uri, track.album_artist.name, album_artist.name))\n elif artist != None:\n if track.album_artist == None:\n track.album_artist = artist\n self.sa_session.add(artist)\n elif track.album_artist.id != artist.id:\n # TODO: conflict!\n self.log.warning(u'Album artist conflict for track %s: %s != %s' % (track.uri, track.album_artist.name, artist.name))\n\n # composer\n composer = self.find_artist(metadata.composer, '')\n if composer != None:\n if track.composer == None:\n track.composer = composer\n self.sa_session.add(composer)\n elif track.composer.id != composer.id:\n # TODO: conflict!\n self.log.warning(u'Composer conflict for track %s: %s != %s' % (track.uri, track.composer.name, composer.name))\n\n # album\n album = self.find_album(metadata.album, metadata.mb_albumid, track.artist, metadata)\n if album != None:\n if track.album == None:\n track.album = album\n self.sa_session.add(album)\n elif track.album.id != album.id:\n # TODO: conflict!\n self.log.warning(u'Album conflict for track %s: %s != %s' % (track.uri, track.album.title, album.title))\n\n # bitdepth\n if metadata.bitdepth != 0:\n if track.bitdepth == None:\n track.bitdepth = metadata.bitdepth\n elif track.bitdepth != metadata.bitdepth:\n #TODO: conflict!\n self.log.warning(u'Track bitdepth conflict for track %s: %d != %d' % (track.uri, track.bitdepth, metadata.bitdepth))\n\n # bitrate\n if metadata.bitrate != 0:\n if track.bitrate == None:\n track.bitrate = metadata.bitrate\n elif track.bitrate != metadata.bitrate:\n #TODO: conflict!\n self.log.warning(u'Track bitrate conflict for track %s: %d != %d' % (track.uri, track.bitrate, metadata.bitrate))\n\n #bpm\n if metadata.bpm != 0:\n if track.bpm == None:\n track.bpm = metadata.bpm\n elif track.bpm != metadata.bpm:\n # TODO: conflict!\n self.log.warning(u'Track bpm conflict for track %s: %d != %d' % (track.uri, track.bpm, metadata.bpm))\n\n #channels\n if metadata.channels != 0:\n if track.channels == None:\n track.channels = metadata.channels\n elif track.channels != metadata.channels:\n # TODO: conflict!\n self.log.warning(u'Track channels conflict for track %s: %d != %d' % (track.uri, track.channels, metadata.channels))\n\n # comments\n if metadata.comments != '':\n if track.comments == None:\n track.comments = metadata.comments\n elif track.comments != metadata.comments:\n #TODO: conflict!\n self.log.warning(u'Track comments conflict for track %s: %s != %s' % (track.uri, track.comments, metadata.comments))\n\n #date\n if metadata.date != None:\n if track.date == None:\n track.date = metadata.date\n elif track.date != metadata.date:\n # TODO: conflict!\n self.log.warning(u'Track date conflict for track %s: %s != %s' % (track.uri, unicode(track.date), unicode(metadata.date)))\n\n # disc\n if track.album != None:\n disc = self.find_disc(track.album, metadata.disc, metadata.disctitle, metadata.disctotal)\n for d in track.album.discs:\n if d.id == disc.id:\n # found disc is already linked - don't add it again\n disc = None\n if disc != None:\n track.album.discs.append(disc)\n\n #encoder\n if metadata.encoder != '':\n if track.encoder == None:\n track.encoder = metadata.encoder\n elif track.encoder != metadata.encoder:\n # TODO: conflict!\n self.log.warning(u'Track encoder conflict for track %s: %s != %s' % (track.uri, track.encoder, metadata.encoder))\n\n # format\n if metadata.format != '':\n if track.format == None:\n track.format = metadata.format\n elif track.format != metadata.format:\n #TODO: conflict!\n self.log.warning(u'Track format conflict for track %s: %s != %s' % (track.uri, track.format, metadata.format))\n\n #genre\n if metadata.genre != '':\n if track.genre == None:\n track.genre = metadata.genre\n elif track.genre != metadata.genre:\n # TODO: conflict!\n self.log.warning(u'Track genre conflict for track %s: %s != %s' % (track.uri, track.genre, metadata.genre))\n\n # language\n if metadata.language != '':\n if track.language == None:\n track.language = metadata.language\n elif track.language != metadata.language:\n #TODO: conflict!\n self.log.warning(u'Track language conflict for track %s: %s != %s' % (track.uri, track.language, metadata.language))\n\n #length\n if metadata.length != 0:\n if track.length == None:\n track.length = metadata.length\n elif track.length != metadata.length:\n # TODO: conflict!\n self.log.warning(u'Track length conflict for track %s: %d != %d' % (track.uri, track.length, metadata.length))\n\n # lyrics\n if metadata.lyrics != '':\n if track.lyrics == None:\n track.lyrics = metadata.lyrics\n elif track.lyrics != metadata.lyrics:\n #TODO: conflict!\n self.log.warning(u'Track lyrics conflict for track %s: %s != %s' % (track.uri, track.lyrics, metadata.lyrics))\n\n #mb_trackid\n if metadata.mb_trackid != '':\n if track.mb_trackid == None:\n track.mb_trackid = metadata.mb_trackid\n elif track.mb_trackid != metadata.mb_trackid:\n # TODO: conflict!\n self.log.warning(u'Track mb_trackid conflict for track %s: %s != %s' % (track.uri, track.mb_trackid, metadata.mb_trackid))\n\n #samplerate\n if metadata.samplerate != 0:\n if track.samplerate == None:\n track.samplerate = metadata.samplerate\n elif track.samplerate != metadata.samplerate:\n # TODO: conflict!\n self.log.warning(u'Track samplerate conflict for track %s: %d != %d' % (track.uri, track.samplerate, metadata.samplerate))\n\n # title\n if metadata.title != '':\n if track.title == None:\n track.title = metadata.title\n elif track.title != metadata.title:\n # TODO: conflict!\n self.log.warning(u'Track title conflict for track %s: %s != %s' % (track.uri, track.title, metadata.title))\n\n # tracknumber\n if metadata.track != 0:\n if track.tracknumber == None:\n track.tracknumber = metadata.track\n elif track.tracknumber != metadata.track:\n # TODO: conflict!\n self.log.warning(u'Track tracknumber conflict for track %s: %d != %d' % (track.uri, track.tracknumber, metadata.track))\n\n # mime type\n track.mimetype = self.guess_mime_type(uri)\n\n # if we couldn't determine track, album, artist from metadata, try to snag it from the path\n # track name = file name\n # album title = last directory in path,\n # artist name = second last directory in path.\n (dirName, fileName) = os.path.split(uri)\n (fileBaseName, fileExtension) = os.path.splitext(fileName)\n if track.title == None:\n track.title = fileBaseName\n track.title_sort = fileBaseName\n\n dirs = re.split(os.sep, dirName)\n if len(dirs) > 0:\n album = self.find_album(dirs[-1])\n if album != None:\n if track.album == None:\n track.album = album\n self.sa_session.add(album)\n\n if len(dirs) > 1:\n artist = self.find_artist(dirs[-2])\n if artist != None:\n if track.artist == None:\n track.artist = artist\n track.album_artist = artist\n self.sa_session.add(artist)\n\n self.log.info(u'Added %s by %s to the current session.' % (track.title, track.artist.name))\n\n #commit the transaction\n self.sa_session.commit()\n\n def find_artist(self, name='', name_sort='', musicbrainz_id=''):\n \"\"\"Searches the database for an existing artist that matches the specified criteria.\n If no existing artist can be found, a new artist is created with the criteria.\n When a new artist is created, it is not added to the database. This is the responsibility\n of the calling function.\n \"\"\"\n artist = None\n if musicbrainz_id != '':\n # we trust musicbrainz_artistid the most because it infers that\n # some other tagger has already verified the metadata.\n artist = self.sa_session.query(Artist).filter(Artist.musicbrainz_artistid == musicbrainz_id).first()\n if artist != None:\n # found an existing artist in our db - compare its metadata\n # to the new info. Always prefer existing metadata over new.\n self.log.info(u'Artist name musicbrainz_artistid search found existing artist %s in database' % artist.name)\n if name != '':\n if artist.name == None:\n artist.name = name\n elif artist.name != name:\n # TODO: conflict -> schedule musicbrainz task!\n self.log.warning(u'Artist name conflict for musicbrainz_artistid %s: %s != %s' % (artist.musicbrainz_artistid, artist.name, name))\n if name_sort != '':\n if artist.name_sort == None:\n artist.name_sort = name_sort\n elif artist.name_sort != name_sort:\n # TODO: conflict -> schedule musicbrainz task!\n self.log.warning(u'Artist sort name conflict for musicbrainz_artistid %s: %s != %s' % (artist.musicbrainz_artistid, artist.name_sort, name_sort))\n\n if artist == None and name != '':\n # if we don't have musicbrainz_artistid or there is no matching\n # artist in our db, try to find an existing artist by name\n artist = self.sa_session.query(Artist).filter(Artist.name == name).first()\n if artist != None:\n self.log.info(u'Artist name search found existing artist %s in database' % artist.name)\n # found an existing artist in our db - compare its metadata\n # to the new info. Always prefer existing metadata over new.\n if name_sort != '':\n if artist.name_sort == None:\n artist.name_sort = name_sort\n elif artist.name_sort != name_sort:\n self.log.warning(u'Artist sort name conflict for artist %s: %s != %s' % (artist.name, artist.name_sort, name_sort))\n else:\n # an existing artist could not be found in our db. Make a new one\n artist = Artist(name)\n if name_sort != '':\n artist.name_sort = name_sort\n if musicbrainz_id != '':\n artist.musicbrainz_artistid = musicbrainz_id\n # add the artist object to the DB\n self.log.info(u'Artist not found in database. Created new artist %s' % artist.name)\n\n # return the artist that we found and/or created\n return artist\n\n def find_album(self, title='', musicbrainz_id='', artist=None, metadata=None):\n \"\"\"Searches the database for an existing album that matches the specified criteria.\n If no existing album can be found, a new album is created with the criteria.\n When a new album is created, it is not added to the database. This is the responsibility of\n the calling function.\n \"\"\"\n album = None\n\n # we trust mb_albumid the most because it infers that\n # some other tagger has already verified the metadata.\n if musicbrainz_id != '':\n album = self.sa_session.query(Album).filter(Album.mb_albumid == musicbrainz_id).first()\n\n # if we don't have mb_albumid or there is no matching\n # album in our db, try to find an existing album by title and artist\n if album == None and title != '' and artist != None:\n album = self.sa_session.query(Album).filter(Album.title == title, Album.artist_id == artist.id).first()\n\n # an existing album could not be found in our db. Make a new one\n if album == None:\n album = Album(title)\n self.log.info(u'Album not found in database. Created new album %s' % album.title)\n\n # we either found or created the album. now verify its metadata\n if album != None and metadata != None:\n # albumstatus\n if metadata.albumstatus != '':\n if album.albumstatus == None:\n album.albumstatus = metadata.albumstatus\n elif album.albumstatus != metadata.albumstatus:\n #TODO: conflict!\n self.log.warning(u'Album albumstatus conflict for album %s: %s != %s' % (album.title, album.albumstatus, metadata.albumstatus))\n\n # albumtype\n if metadata.albumtype != '':\n if album.albumtype == None:\n album.albumtype = metadata.albumtype\n elif album.albumtype != metadata.albumtype:\n #TODO: conflict!\n self.log.warning(u'album albumtype conflict for album %s: %s != %s' % (album.title, album.albumtype, metadata.albumtype))\n\n # artist\n if artist != None:\n if album.artist == None:\n album.artist = artist\n elif album.artist_id != artist.id:\n # TODO: conflict -> schedule musicbrainz task!\n self.log.warning(u'Album artist conflict for mb_albumid %s: %s != %s' % (album.mb_albumid, album.artist.name, artist.name))\n\n # asin\n if metadata.asin != '':\n if album.asin == None:\n album.asin = metadata.asin\n elif album.asin != metadata.asin:\n #TODO: conflict!\n self.log.warning(u'Album asin conflict for album %s: %s != %s' % (album.title, album.asin, metadata.asin))\n\n # catalognum\n if metadata.catalognum != '':\n if album.catalognum == None:\n album.catalognum = metadata.catalognum\n elif album.catalognum != metadata.catalognum:\n #TODO: conflict!\n self.log.warning(u'album catalognum conflict for album %s: %s != %s' % (album.title, album.catalognum, metadata.catalognum))\n\n # compilation\n if album.compilation == None:\n album.compilation = metadata.comp\n elif album.compilation != metadata.comp:\n # TODO: conflict!\n self.log.warning(u'album comp conflict for album %s: %s != %s' % (album.title, album.compilation, metadata.comp))\n\n # country\n if metadata.country != '':\n if album.country == None:\n album.country = metadata.country\n elif album.country != metadata.country:\n #TODO: conflict!\n self.log.warning(u'album country conflict for album %s: %s != %s' % (album.title, album.country, metadata.country))\n\n # label/organization\n if metadata.label != '':\n if album.label == None:\n album.label = metadata.label\n elif album.label != metadata.label:\n #TODO: conflict!\n self.log.warning(u'Album label conflict for album %s: %s != %s' % (album.title, album.label, metadata.label))\n\n #mb_releasegroupid\n if metadata.mb_releasegroupid != '':\n if album.mb_releasegroupid == None:\n album.mb_releasegroupid = metadata.mb_releasegroupid\n elif album.mb_releasegroupid != metadata.mb_releasegroupid:\n # TODO: conflict!\n self.log.warning(u'album mb_releasegroupid conflict for album %s: %s != %s' % (album.title, album.mb_releasegroupid, metadata.mb_releasegroupid))\n\n #media type\n if metadata.media != '':\n if album.media_type == None:\n album.media_type = metadata.media\n elif album.media_type != metadata.media:\n # TODO: conflict!\n self.log.warning(u'album media_type conflict for album %s: %s != %s' % (album.title, album.media_type, metadata.media))\n\n if title != '':\n if album.title == None:\n album.title = title\n album.title_sort = title\n elif album.title != title:\n # TODO: conflict -> schedule musicbrainz task!\n self.log.warning(u'Album title conflict for mb_albumid %s: %s != %s' % (album.mb_albumid, album.title, title))\n\n # year\n if metadata.track != 0:\n if album.year == None:\n album.year = metadata.track\n elif album.year != metadata.track:\n # TODO: conflict!\n self.log.warning(u'album.year conflict for track %s: %d != %d' % (metadata.title, album.year, metadata.year))\n\n return album\n\n def find_disc(self, album=None, discnumber=0, discsubtitle='', num_tracks=0):\n \"\"\"Tries to find an existing disc that matches the specified criteria.\n If an existing disc cannot be found, creates a new disc with the specified criteria.\n \"\"\"\n # first see if there's a disc that's already linked to the album that\n # has either the specified musicbrainz_discid or discnumber.\n disc = None\n if album != None:\n for d in album.discs:\n if discnumber != 0:\n if d.discnumber == discnumber:\n disc = d\n\n # if we found a disc in the existing album's collection that matches\n # the specified criteria, update any missing metadata\n if disc != None:\n self.log.info(u'Disc musicbrainz_discid/discnumber search found existing disc %s in database' % disc)\n if discnumber != 0:\n if d.discnumber == None:\n d.discnumber = discnumber\n elif d.discnumber != discnumber:\n # TODO: conflict!\n self.log.warning(u'Disc number conflict for disc %s: %s != %s' % (disc, disc.discnumber, discnumber))\n if discsubtitle != '':\n if d.subtitle == None:\n d.subtitle = discsubtitle\n elif d.subtitle != discsubtitle:\n # TODO: Conflict!\n self.log.warning(u'Disc subtitle conflict for disc %s: %s != %s' % (disc, disc.subtitle, discsubtitle))\n if num_tracks != 0:\n if d.num_tracks == None:\n d.num_tracks = num_tracks\n elif d.num_tracks != num_tracks:\n # TODO: conflict!\n self.log.warning(u'Disc number of tracks conflict for disc %s: %s != %s' % (disc, disc.num_tracks, num_tracks))\n\n if disc == None and album != None and discnumber != 0:\n # musicbrainz_discid wasn't supplied or didn't yield an existing album.\n # try to search with album id and disc number instead.\n disc = self.sa_session.query(Disc).filter(Disc.album_id == album.id, Disc.discnumber == discnumber).first()\n if disc != None:\n self.log.info(u'Disc album/number search found existing disc %s in database' % disc)\n if discsubtitle != '':\n if disc.disc_subtitle == None:\n disc.disc_subtitle = discsubtitle\n elif disc.disc_subtitle != discsubtitle:\n # TODO: conflict -> schedule musicbrainz task!\n self.log.warning(u'Disc subtitle conflict for disc %s: %s != %s' % (disc, disc.disc_subtitle, discsubtitle))\n if num_tracks != 0:\n if disc.num_tracks == None:\n disc.num_tracks = num_tracks\n elif disc.num_tracks != num_tracks:\n # TODO: conflict!\n self.log.warning(u'Disc number of tracks conflict for disc %s: %s != %s' % (disc, disc.num_tracks, num_tracks))\n else:\n # could not find the disc in question. Create a new one instead\n disc = Disc(discnumber)\n if album != None:\n disc.album = album\n if discsubtitle != '':\n disc.disc_subtitle = discsubtitle\n if num_tracks != 0:\n disc.num_tracks = num_tracks\n self.log.info(u'Could not find disc in database. Created new disc %s' % disc)\n self.sa_session.add(disc)\n\n return disc\n\n def stop(self):\n \"\"\"Cleans up the thread\"\"\"\n self.log.info(u'Stop has been called')\n self.running = False\n","sub_path":"musik/importer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":28721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260162666","text":"import numpy as np \r\nimport scipy as sp \r\nimport matplotlib.pyplot as plt\r\nimport profile\r\nimport h5py\r\nimport tables #this is PyTables to use HDF5 for Python \r\nimport sys\r\nimport itertools\r\n\r\nfrom scipy.integrate import odeint \r\nfrom numpy.random import random_sample, uniform\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nfrom pyConstants import *\r\nfrom SrConstants import * \r\n\r\n\"\"\"\r\nGeneral equations for the MOT force in 3D. This assumes the approximation of perfect polarization of\r\nthe beams\r\n\"\"\"\r\n\r\nviewport_rad = 19e-3 #radius of the windows in meters (19mm, 38mm diam). \r\n\t\t\t\t\t#This explicitly takes into account the fact that the beam can be clipped by the viewport\r\n\r\ndef MOT_force(k_laser,linewidth,sat_param,velocity,B_gradient,position,detunings_list):\r\n delta_min = [detuning - k_laser*velocity - (muBohr*B_gradient*position/hbar) for detuning in detunings_list]\r\n delta_plus = [detuning + k_laser*velocity + (muBohr*B_gradient*position/hbar) for detuning in detunings_list]\r\n force_list = [(hbar*k_laser*linewidth*sat_param/2)*(1/(1+sat_param*(2*delta_min[q]/linewidth)**2) - \\\r\n 1/(1+sat_param*(2*delta_plus[q]/linewidth)**2)) for q in range(len(delta_min))]\r\n return np.sum(force_list)\r\n\r\n\r\n\r\ndef diffeqs_blue(variables,t,params): #We disregard gravity\r\n (x,vx,y,vy,z,vz) = variables\r\n (laserPowerX,laserPowerY,laserPowerZ,beamWaistRadX,beamWaistRadY,beamWaistRadZ,B_gradient,detunings_list) = params\r\n\r\n\r\n # This assumes circular beams!\r\n gaussian_Xbeam = (2*laserPowerX/(np.pi*beamWaistRadX**2))*np.exp(-2*(y**2)/beamWaistRadX**2)*np.exp(-2*(z**2)/beamWaistRadX**2) if (y**2+z**2<=viewport_rad**2) else 0\r\n gaussian_Ybeam = (2*laserPowerY/(np.pi*beamWaistRadY**2))*np.exp(-2*(x**2)/beamWaistRadY**2)*np.exp(-2*(z**2)/beamWaistRadY**2) if (x**2+z**2<=viewport_rad**2) else 0\r\n gaussian_Zbeam = (2*laserPowerZ/(np.pi*beamWaistRadZ**2))*np.exp(-2*(x**2)/beamWaistRadZ**2)*np.exp(-2*(y**2)/beamWaistRadZ**2) if (x**2+y**2<=viewport_rad**2) else 0\r\n\r\n\r\n derivs = [vx,(1/mSr88)*MOT_force(kVecBlue,blueGamma,gaussian_Xbeam/blueIsat,vx,B_gradient,x,detunings_list),\\\r\n vy,(1/mSr88)*MOT_force(kVecBlue,blueGamma,gaussian_Ybeam/blueIsat,vy,B_gradient,y,detunings_list),\\\r\n vz,0] \r\n\r\n # we set the force in z-dir to 0 to make it 2D and see how it behaves in that direction \r\n \r\n\r\n # Quadrupole field from: \r\n # https://www2.physics.ox.ac.uk/sites/default/files/2013-01-19/minsung_pdf_16672.pdf eq. 2.40\r\n return derivs\r\n\r\n\r\n\r\n# Simulation parameters\r\n\r\ndetunings_blue = [-blueGamma]\r\n\r\n\r\n#Put only integer number of milliwatts, not fractions\r\nbluePowerX = bluePowerY = 15*10**-3 \r\nbluePowerZ = 2*10**-3\r\n#Put only integer number of millimeters, not fractions\r\n# blueRadX = blueRadY = 10*10**-3\r\n# blueRadZ = 10*10**-3\r\nblueGradientGcm = 20 #put an integer number here\r\nblueGradient = 0.01*blueGradientGcm # T/m \r\n\r\n\r\n# parameters_blue = [bluePowerX,bluePowerY,bluePowerZ,blueRadX,blueRadY,blueRadZ,blueGradient,detunings_blue]\r\n\r\n\r\n\r\ntStop = 0.5\r\nt = np.linspace(0., tStop, 10**5)\r\n\r\ninitz = np.linspace(-12e-3,12e-3,7)\r\ninit_rad = 0.1\r\ninit_angle = 30*(np.pi/180) #not to change\r\nx_shifts = np.linspace(0,13.86e-3,5)\r\ny_shifts = np.linspace(0,24e-3,5)\r\ninitx = -init_rad*np.sin(init_angle)+x_shifts\r\ninity = -init_rad*np.cos(init_angle)+y_shifts\r\ninits_pos_1 = np.array(list(itertools.product(initx,[inity[0]],initz)))\r\ninits_pos_2 = np.array(list(itertools.product([initx[0]],inity[1:],initz)))\r\ninits_pos = np.concatenate((inits_pos_1,inits_pos_2))\r\n\r\n\r\ninit_speed_xy = 40 #m/s\r\nvel_angle = np.linspace(25,35,5) #deg\r\ninitvx = init_speed_xy*np.sin(vel_angle*np.pi/180)\r\ninitvy = init_speed_xy*np.cos(vel_angle*np.pi/180)\r\ninitvz = np.linspace(0,2,4) \r\ninits_vel = np.array([[init_speed_xy*np.sin(angle*np.pi/180),init_speed_xy*np.cos(angle*np.pi/180),vz] for angle in vel_angle for vz in initvz])\r\n\r\n\r\ninits = np.array([[p[0],v[0],p[1],v[1],p[2],v[2]] for p in inits_pos for v in inits_vel])\r\n\r\n\r\nclass Results(tables.IsDescription):\r\n x_init = tables.Float64Col() \r\n vx_init = tables.Float64Col()\r\n y_init = tables.Float64Col()\r\n vy_init = tables.Float64Col()\r\n z_init = tables.Float64Col()\r\n vz_init = tables.Float64Col()\r\n x_final = tables.Float64Col() \r\n vx_final = tables.Float64Col()\r\n y_final = tables.Float64Col()\r\n vy_final = tables.Float64Col()\r\n z_final = tables.Float64Col()\r\n vz_final = tables.Float64Col()\r\n \r\n\r\nclass Descriptions(tables.IsDescription):\r\n detuning = tables.Float64Col()\r\n gradient = tables.Float64Col()\r\n init_position_away = tables.Float64Col()\r\n PowerX = tables.Float64Col()\r\n PowerY = tables.Float64Col()\r\n PowerZ = tables.Float64Col() \r\n WaistRadX = tables.Float64Col()\r\n WaistRadY = tables.Float64Col()\r\n WaistRadZ = tables.Float64Col()\r\n\r\n\r\n\r\n# grp_descriptions = file_save.create_group(grp_simulation,\"Descriptions\",\\\r\n# title=\"The input parameters of the simulation are given here, units are SI\")\r\n\r\nradiiXY = np.array([5,8,11,14,17])*1e-3\r\nfor radX in radiiXY:\r\n\tradY = radZ = radX\r\n\tparameters_blue = [bluePowerX,bluePowerY,bluePowerZ,radX,radY,radZ,blueGradient,detunings_blue]\r\n\r\n\tfile_save = tables.open_file(\"resultsBlueMOT/pX%.ipY%.ipZ%.igrad%.i.hdf5\"%(int(bluePowerX*1e3),int(bluePowerY*1e3),int(bluePowerZ*1e3),\\\r\n\t\tblueGradientGcm),mode=\"a\",title= \"Blue MOT simulation, detuning -1*gamma\")\r\n\tgrp_simulation = file_save.create_group(\"/\",\"radX%.iradY%.iradZ%.i\"%(int(radX*1e3),int(radY*1e3),int(radZ*1e3)),\\\r\n\t\ttitle=\"Different beam radii [mm]\")\r\n\ttbl_data = file_save.create_table(grp_simulation,\"Data\",Results)\r\n\ttbl_descriptions = file_save.create_table(grp_simulation,\"Descriptions\",Descriptions)\r\n\tdata_save = tbl_data.row\r\n\tdescr_save = tbl_descriptions.row\r\n\t\r\n\tfor num,ic in enumerate(inits):\r\n\t\tprint(\"Solving \",num,\" for rad \",radX)\r\n\t\tsolution_blue = odeint(diffeqs_blue, ic, t, args=(parameters_blue,),mxstep=10**8)\r\n\t\t\r\n\t\tdata_save[\"x_init\"] = solution_blue[0,0]\r\n\t\tdata_save[\"vx_init\"] = solution_blue[0,1]\r\n\t\tdata_save[\"y_init\"] = solution_blue[0,2]\r\n\t\tdata_save[\"vy_init\"] = solution_blue[0,3]\r\n\t\tdata_save[\"z_init\"] = solution_blue[0,4]\r\n\t\tdata_save[\"vz_init\"] = solution_blue[0,5]\r\n\t\tdata_save[\"x_final\"] = solution_blue[-1,0]\r\n\t\tdata_save[\"vx_final\"] = solution_blue[-1,1]\r\n\t\tdata_save[\"y_final\"] = solution_blue[-1,2]\r\n\t\tdata_save[\"vy_final\"] = solution_blue[-1,3]\r\n\t\tdata_save[\"z_final\"] = solution_blue[-1,4]\r\n\t\tdata_save[\"vz_final\"] = solution_blue[-1,5]\r\n\t\tdata_save.append()\r\n\r\n\tdescr_save[\"detuning\"] = detunings_blue[0]\r\n\tdescr_save[\"gradient\"] = blueGradient\r\n\tdescr_save[\"init_position_away\"] = init_rad\r\n\tdescr_save[\"PowerX\"] = bluePowerX\r\n\tdescr_save[\"PowerY\"] = bluePowerY\r\n\tdescr_save[\"PowerZ\"] = bluePowerZ\r\n\tdescr_save[\"WaistRadX\"] = radX\r\n\tdescr_save[\"WaistRadY\"] = radY\r\n\tdescr_save[\"WaistRadZ\"] = radZ\r\n\tdescr_save.append()\r\n\r\n\ttbl_data.flush()\r\n\ttbl_descriptions.flush()\r\n\r\n\tfile_save.close()\r\n\r\n\r\nsys.exit(0)\r\n\r\n\r\n\r\n","sub_path":"blueMOT2D.py","file_name":"blueMOT2D.py","file_ext":"py","file_size_in_byte":6979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"560158373","text":"import numpy as np\nimport scipy.stats\nfrom matplotlib import pyplot as plt\nfrom bax_insertion.util import fitting\nimport bax_insertion.plots.titration_fits as tf\n\ndef calc_err_var(data, last_n_pts=50, fit_type='cubic', plot=False,\n plot_title=None):\n # Prune the data\n t = np.arange(len(data))\n data_subset = data[-last_n_pts:]\n t_subset = t[-last_n_pts:]\n # Get the appropriate fit object\n if fit_type == 'linear':\n fit = tf.LinearIntercept(log_transform=False)\n elif fit_type == 'quadratic':\n fit = tf.Quadratic(log_transform=False)\n elif fit_type == 'cubic':\n fit = tf.Cubic(log_transform=False)\n elif fit_type == 'two_exp_sum':\n fit = tf.TwoExpSum()\n else:\n raise ValueError(\"Unknown fit type! Must be 'linear', 'quadratic', \"\n \"'cubic', or 'two_exp_sum'.\")\n # Run the fit\n params = fit.fit_timecourse(t_subset, data_subset)\n # Get the best-fit curve\n ypred = fit.fit_func(t_subset, params)\n # Calculate residuals\n residuals = data_subset - ypred\n # Remove NaNs\n residuals = residuals[~np.isnan(residuals)]\n # Plot results\n fig = None\n if plot:\n # Plot of fit and distribution of residuals\n fig = plt.figure(figsize=(12, 5))\n plt.subplot(1, 3, 1)\n plt.plot(t, data)\n plt.plot(t_subset, ypred)\n plt.title('Fit of %s to last %s pts' % (fit_type, last_n_pts))\n plt.subplot(1, 3, 2)\n plt.hist(residuals)\n plt.title('Histogram of residuals')\n plt.subplot(1, 3, 3)\n scipy.stats.probplot(residuals, dist='norm', plot=plt)\n plt.title('Quantile-quantile plot vs. normal')\n plt.tight_layout()\n if plot_title:\n fig.subplots_adjust(top=0.86)\n fig.text(0.5, 0.95, plot_title, verticalalignment='top',\n horizontalalignment='center')\n return (residuals, fig)\n\n","sub_path":"bax_insertion/util/calculate_error_variance.py","file_name":"calculate_error_variance.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"499162783","text":"from selenium import webdriver\nfrom selenium.common.exceptions import StaleElementReferenceException\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\n\nfrom pom.base_page import BasePage\nfrom pom.home_page import HomePage\nfrom pom.login_page import LoginPage\n\n\nclass CreateTopicPage(BasePage):\n def create_topic_contents(self, tab, title, content):\n tab_select = self.driver.find_element(By.ID, \"tab-value\")\n tab_select.click()\n eles = self.driver.find_elements(By.XPATH, '//*[@id=\"tab-value\"]/option')\n for ele in eles:\n if ele.text == tab:\n ele.click()\n break\n else:\n raise Exception(f'找不到{tab}')\n\n title_input = self.driver.find_element(By.XPATH, '//*[@id=\"title\"]')\n title_input.clear()\n title_input.send_keys(title)\n\n content_input = self.driver.find_element(By.XPATH, '//*[@class=\"CodeMirror-scroll\"]')\n content_input.click()\n\n ac = ActionChains(self.driver) # 模拟鼠标的方式输入(不是input标签的输入框使用这个方式)\n ac.move_to_element(content_input).send_keys(content).perform()\n\n self.driver.find_element_by_xpath('//*[@value=\"提交\"]').click()\n\n def reply_topic(self, content):\n rep_content_input = self.driver.find_element(By.XPATH, '//div[@class=\"CodeMirror-code\"]/pre')\n rep_content_input.click()\n\n ac = ActionChains(self.driver) # 模拟鼠标的方式输入(不是input标签的输入框使用这个方式)\n ac.move_to_element(rep_content_input).send_keys(content).perform()\n\n self.driver.find_element_by_xpath('//*[@class=\"span-primary submit_btn\"]').click()\n\n\nif __name__ == '__main__':\n hp = HomePage()\n hp.click_link_new_page_by_text('登录')\n lp = LoginPage()\n lp.user_login_with_username_password('fanmao1', '123456')\n hp.click_create_topic_btn()\n cp = CreateTopicPage()\n cp.create_topic_contents('分享', 'web自动化测试', '从0到1搭建自动化测试框架')\n","sub_path":"pom/create_topic_page.py","file_name":"create_topic_page.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"394522019","text":"class Banquet():\n\n\tdef __init__(self, numberOfTables=40, peoplePerTable=10):\n\t\tself.tables = []\n\t\tself.numberOfTables = numberOfTables\n\t\tself.searchText = \"\"\n\n\t\tfor i in range(numberOfTables):\n\t\t\tself.tables.append(Table(i + 1, peoplePerTable))\n\n\t\tfile = open(\"example.txt\", \"r\")\n\t\tfor line in file:\n\t\t\tline = line.rstrip()\n\t\t\tline = line.split(\":\")\n\t\t\tname = line[0]\n\t\t\tnumber = int(line[1]) - 1\n\t\t\tself.tables[number].addPerson(name)\n\n\tdef movePerson(self, startTable, endTable):\n\t\tself.tables[endTable].addPerson(self.tables[startTable].takePerson())\n\n\n\n\tdef applySearch(self, text):\n\t\tself.searchText = text\n\n\tdef getPeople(self):\n\t\tpeople = []\n\t\tfor i in range(len(self.tables)):\n\t\t\tfor j in self.tables[i].people:\n\t\t\t\tpeople.append((j, i))\n\t\treturn people\n\n\n\n\tdef getTables(self):\n\t\ttables = []\n\n\t\tsmallestLen = 0\n\n\t\tfor i in self.tables:\n\t\t\tif len(self.tables[i].people) > smallestLen:\n\t\t\t\tsmallestLen = len(self.tables[i].people)\n\n\n\t\tfor i in range(len(self.tables)):\n\t\t\tsmallest = 0\n\t\t\tsmallestIndex = 0\n\t\t\tfor j in range(i, len(self.tables)):\n\t\t\t\tpass\n\t\t\t\t\n\n\n\n\n\nclass Table():\n\tdef __init__(self, number, pplPerTable):\n\t\tself.people = []\n\t\tself.number = number\n\t\tself.pplPerTable = pplPerTable\n\n\tdef addPerson(self, person):\n\t\tif len(self.people) < self.pplPerTable:\n\t\t\tself.people.append(person)\n\t\telse:\n\t\t\tassert False, \"There are more than 25 people per table\"\n\n\tdef takePerson(self, personNumber):\n\t\tperson = self.people[personNumber]\n\t\tdel self.people[personNumber]\n\t\treturn person\n\nif __name__ == '__main__':\n\tban = Banquet()\n\n\tprint(ban.getPeople())","sub_path":"oldFiles/oldBanquet.py","file_name":"oldBanquet.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"546875992","text":"#!/usr/bin/env python\r\n#python2\r\n\r\nimport os\r\nimport sys\r\nimport binascii\r\n\r\n\r\nRISCV_TOOLCHAIN_PATH = '.\\\\riscv32-gnu-toolchain-windows\\\\'\r\n\r\n#INPUT = sys.argv[1]\r\nOUTPUT = sys.argv[2]\r\n\r\n#res = os.system( '%sriscv32-elf-as %s -o compile_tmp.o -march=rv32i' % (RISCV_TOOLCHAIN_PATH, INPUT) )\r\n#if res != 0:\r\n # print('\\n Assembling Error!')\r\n # sys.exit()\r\nos.system( '%sriscv32-elf-ld lb.o -o compile_tmp.om' % (RISCV_TOOLCHAIN_PATH ) )\r\n#os.system( 'del compile_tmp.o' )\r\nos.system( '%sriscv32-elf-objcopy -O binary compile_tmp.om compile_tmp.bin' % (RISCV_TOOLCHAIN_PATH, ) )\r\nos.system( 'del compile_tmp.om' )\r\ns = binascii.b2a_hex( open('compile_tmp.bin', 'rb').read() )\r\n\r\n\r\ndef byte_wise_reverse(b):\r\n return b[6:8] + b[4:6] + b[2:4] + b[0:2]\r\n\r\nwith open(OUTPUT, 'wb') as f:\r\n for i in range(0, len(s), 8):\r\n f.write(byte_wise_reverse(s[i:i+8])+'\\n')\r\n ","sub_path":"new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"389359181","text":"import praw_reddit_data\nimport pandas as pd\nimport tqdm\n\n\n# # Criteria for subreddit selection:\n# - Looking for subreddits that primarily consist of self text - i.e. aren't just links to something else.\n\ndef get_self_fraction(subreddit: str, threshold: float = 0.5) -> bool:\n top_submissions = list(praw_reddit_data.get_top_submissions(subreddit, limit=None))\n if len(top_submissions) == 0:\n return False\n self_submissions = [submission for submission in top_submissions if submission.is_self]\n return len(self_submissions)/len(top_submissions) > threshold\n\n\nif __name__ == '__main__':\n reddit = praw_reddit_data.get_reddit()\n subreddits = list(set(list(reddit.subreddits.popular(limit=None)) + list(reddit.subreddits.default(limit=None))))\n\n self_subreddits = []\n for sub in tqdm.tqdm(subreddits):\n print(f'checking: {sub.display_name}')\n if get_self_fraction(sub.display_name):\n print(f'{sub.display_name} is in')\n self_subreddits.append(sub.display_name)\n\n self_subreddits_df = pd.DataFrame()\n self_subreddits_df['subreddits'] = self_subreddits\n self_subreddits_df.to_csv('self_subreddits.csv')\n","sub_path":"openai/pick_subreddits.py","file_name":"pick_subreddits.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"448345665","text":"from stellar_sdk import Keypair, Network, Server, TransactionBuilder\n\nclass account_merge:\n\n def __init__(self, source_secr_seed, destination, fee = 100):\n self.fee = fee\n self.destination = destination\n self.server = Server(\"https://horizon.stellar.org/\")\n self.source = Keypair.from_secret(source_secr_seed)\n self.source_account = self.server.load_account(account_id=self.source.public_key)\n self.__create_transaction()\n\n def __create_transaction(self):\n self.transaction = (\n TransactionBuilder(\n source_account = self.source_account,\n network_passphrase = Network.PUBLIC_NETWORK_PASSPHRASE,\n base_fee = self.fee\n )\n .append_account_merge_op(\n destination=self.destination\n )\n .build()\n )\n self.__execute_transaction()\n\n def __execute_transaction(self):\n self.transaction.sign(self.source)\n self.response = self.server.submit_transaction(self.transaction)\n","sub_path":"account_merge/account_merge.py","file_name":"account_merge.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"460563030","text":"\"\"\"\nhttps://leetcode.com/problems/minimum-sideway-jumps/\n\nDP. \nTime Complexity: O(n)\n\"\"\"\nclass Solution:\n def minSideJumps(self, obstacles: List[int]) -> int:\n n = len(obstacles) - 1\n dp = [[float('inf')] * 3 for _ in range(n)]\n dp[0] = [1, 0, 1]\n for i in range(1, n):\n for r in range(3):\n if obstacles[i] == r + 1 or obstacles[i+1] == r + 1:\n dp[i][r] = float('inf')\n else:\n dp[i][r] = min([\n dp[i-1][r],\n dp[i-1][(r+1)%3] + 1,\n dp[i-1][(r+2)%3] + 1,\n ])\n return min(dp[-1])","sub_path":"1824_MinimumSidewayJumps.py","file_name":"1824_MinimumSidewayJumps.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"394609197","text":"from django.contrib.auth.views import LoginView, LogoutView\nfrom django.urls import path\n\nfrom users.forms import LoginForm\n\n\nurlpatterns = [\n path(\n 'login/',\n LoginView.as_view(authentication_form=LoginForm), name='login',\n ),\n path('logout/', LogoutView.as_view(), name='logout'),\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"440754007","text":"\n\nfrom xai.brain.wordbase.nouns._microwave import _MICROWAVE\n\n#calss header\nclass _MICROWAVED(_MICROWAVE, ):\n\tdef __init__(self,): \n\t\t_MICROWAVE.__init__(self)\n\t\tself.name = \"MICROWAVED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"microwave\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_microwaved.py","file_name":"_microwaved.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336980414","text":"import re\r\nimport itertools\r\n\r\nCASE = 1000\r\n\r\nwith open('input.txt', 'r') as file:\r\n lines = file.read().split('\\n')\r\n\r\ngridX, gridY = CASE, CASE;\r\nlights = [[0 for x in range(gridX)] for y in range(gridY)]\r\nlights_lit = 0\r\npattern = re.compile('(turn on|turn off|toggle)\\s(\\d+),(\\d+)\\sthrough\\s(\\d+),(\\d+)')\r\n\r\nfor line in lines:\r\n\tmatches = pattern.findall(line)\r\n\tmatch = list(itertools.chain.from_iterable(matches))\r\n\tline1 = int(match[1])\r\n\tline2 = int(match[3])\r\n\tcol1 = int(match[2])\r\n\tcol2 = int(match[4])\r\n\t\r\n\tif match[0] == 'turn on':\r\n\t\twhile line1 <= line2:\r\n\t\t\twhile col1 <= col2:\r\n\t\t\t\tlights[line1][col1] = 1\r\n\t\t\t\tcol1 += 1\t\r\n\t\t\tcol1 = int(match[2])\r\n\t\t\tline1 += 1\r\n\t\t\t\r\n\tif match[0] == 'turn off':\r\n\t\twhile line1 <= line2:\r\n\t\t\twhile col1 <= col2:\r\n\t\t\t\tlights[line1][col1] = 0\r\n\t\t\t\tcol1 += 1\t\r\n\t\t\tcol1 = int(match[2])\r\n\t\t\tline1 += 1\r\n\t\t\t\r\n\tif match[0] == 'toggle':\r\n\t\twhile line1 <= line2:\r\n\t\t\twhile col1 <= col2:\r\n\t\t\t\tif(lights[line1][col1] == 0):\r\n\t\t\t\t\tlights[line1][col1] = 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tlights[line1][col1] = 0\r\n\t\t\t\tcol1 += 1\t\r\n\t\t\tcol1 = int(match[2])\r\n\t\t\tline1 += 1\r\n\r\nfor lightX in range(CASE):\r\n\tfor lightY in range(CASE):\r\n\t\tif lights[lightX][lightY] == 1:\r\n\t\t\tlights_lit += 1\r\n\r\nprint(lights_lit)","sub_path":"day6/day6-1.py","file_name":"day6-1.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"584570921","text":"import sys\nimport json\nimport logging\nimport cfnresponse\nimport boto3\nfrom botocore.exceptions import ClientError\n\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\npolicyDocument = {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\"Effect\": \"Allow\", \"Action\": \"iot:*\", \"Resource\": \"*\"},\n {\"Effect\": \"Allow\", \"Action\": \"greengrass:*\", \"Resource\": \"*\"},\n ],\n}\nconfigDocument = {\n \"coreThing\": {\n \"thingArn\": \"\",\n \"iotHost\": \"\",\n \"ggHost\": \"\",\n \"iotMqttPort\": 443,\n \"iotHttpPort\": 443,\n \"ggHttpPort\": 443,\n \"keepAlive\": 600,\n },\n \"runtime\": {\"cgroup\": {\"useSystemd\": \"yes\"}},\n \"managedRespawn\": False,\n \"crypto\": {\n \"principals\": {\n \"IoTCertificate\": {\n \"certificatePath\": \"file:///greengrass/certs/CERTIFICATE_NAME_HERE\",\n \"privateKeyPath\": \"file:///greengrass/certs/PRIVATE_KEY_FILENAME_HERE\",\n }\n },\n \"caPath\": \"file:///greengrass/certs/AmazonRootCA1.pem\",\n },\n}\n\n\ndef handler(event, context):\n responseData = {}\n try:\n logger.info(\"Received event: {}\".format(json.dumps(event)))\n result = cfnresponse.FAILED\n client = boto3.client(\"iot\")\n thingName = event[\"ResourceProperties\"][\"ThingName\"]\n certArn = event[\"ResourceProperties\"][\"CertificateArn\"]\n if event[\"RequestType\"] == \"Create\":\n # Verify certificate is valid and correct region\n client.describe_certificate(certificateId=certArn.split(\"/\")[-1])\n thing = client.create_thing(thingName=thingName)\n client.create_policy(\n policyName=\"{}-full-access\".format(thingName),\n policyDocument=json.dumps(policyDocument),\n )\n response = client.attach_policy(\n policyName=\"{}-full-access\".format(thingName), target=certArn\n )\n response = client.attach_thing_principal(\n thingName=thingName, principal=certArn\n )\n logger.info(\n \"Created thing: %s and policy: %s\"\n % (thingName, \"{}-full-access\".format(thingName))\n )\n result = cfnresponse.SUCCESS\n\n # Build config.json content and serialize\n configJSON = configDocument\n configJSON[\"coreThing\"][\"thingArn\"] = thing[\"thingArn\"]\n configJSON[\"coreThing\"][\"iotHost\"] = client.describe_endpoint(\n endpointType=\"iot:Data-ATS\"\n )[\"endpointAddress\"]\n configJSON[\"coreThing\"][\"ggHost\"] = (\n \"greengrass-ats.iot.\"\n + configJSON[\"coreThing\"][\"iotHost\"].split(\".\")[2]\n + \".amazonaws.com\"\n )\n responseData[\"configJSON\"] = json.dumps(configJSON)\n elif event[\"RequestType\"] == \"Update\":\n logger.info(\"Updating thing: %s\" % thingName)\n result = cfnresponse.SUCCESS\n elif event[\"RequestType\"] == \"Delete\":\n logger.info(\"Deleting thing: %s and policy\" % thingName)\n response = client.list_thing_principals(thingName=thingName)\n for i in response[\"principals\"]:\n response = client.detach_thing_principal(\n thingName=thingName, principal=i\n )\n response = client.detach_policy(\n policyName=\"{}-full-access\".format(thingName), target=i\n )\n response = client.delete_policy(\n policyName=\"{}-full-access\".format(thingName)\n )\n response = client.delete_thing(thingName=thingName)\n result = cfnresponse.SUCCESS\n except ClientError as e:\n logger.error(\"Error: {}\".format(e))\n result = cfnresponse.FAILED\n logger.info(\n \"Returning response of: {}, with result of: {}\".format(result, responseData)\n )\n sys.stdout.flush()\n cfnresponse.send(event, context, result, responseData)\n","sub_path":"v1/machine_learning_inference/cfn/lambda_functions/cfn_custom_resources/create_thing.py","file_name":"create_thing.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"575498117","text":"\"\"\"\n删除 bison 系统中的指定 ID 的试卷及其内部试题\npaper_ids 参数给定试卷ID 列表,用','隔开,例如['1','2']\n\"\"\"\nimport requests\nimport json\npaper_ids=['5def1d306dcbae00076f427e','5def1d326dcbae0008433a0d','5def1d386dcbae00076f42c3','5def20ee6dcbae00076f42e5','5def20f06dcbae00076f42f7','5def20f66dcbae0008433a73'] # 试卷的 ID,方便获取试卷内的题目 ID\nbison_headers={\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\",\n \"Connection\": \"keep-alive\",\n \"Content-Type\": \"application/json; charset=UTF-8\",\n \"Cookie\": 'session=.eJwNzDEKgDAQRNG7TG2xQpZNcpkQ2FFSKGJiJd7dtJ_Hf1GaI0PjRpolUdtERSQ6k5lgQbl4H_XkOZDH_XDBVXsv3nb2mRBSVQ_OSUc7iLyqaQo6V98POJMb3g.ENC0pg.Gv3hVC1wpheDGXZ7incEL3d8XLo',\n \"Host\": \"bison.lanqi.org\",\n \"Origin\": \"http://bison.lanqi.org\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n }\ndata={\"boost\":0,\"force\":True} # 传递的参数\n\ndef bison_delete_ques(paper_ids):\n# 删除试卷 ID 下的试题,并最后删除试卷本身\n for paper_id in paper_ids:\n paper_url=f'http://bison.lanqi.org/api/omega_paper/{paper_id}'\n ques_ids=requests.get(paper_url,headers=bison_headers).json()['item_ids']\n for ques_id in ques_ids:\n url=f'http://bison.lanqi.org/api/item/{ques_id}'\n requests.post(url,headers=bison_headers,data=json.dumps(data))\n requests.delete(paper_url,headers=bison_headers)\n\nif __name__ == '__main__':\n\tbison_delete_ques(paper_ids)\n","sub_path":"obsolete/2019/tal_to_bison/bison_delete_paper.py","file_name":"bison_delete_paper.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"265560499","text":"from edit_distance.models.cnn.model import CNN\nfrom closest_string.triplet.train import execute_train, general_arg_parser\nfrom util.data_handling.data_loader import BOOL_CHOICE\n\nparser = general_arg_parser()\nparser.add_argument('--readout_layers', type=int, default=1, help='Number of readout layers')\nparser.add_argument('--channels', type=int, default=2, help='Number of channels at each convolutional layer')\nparser.add_argument('--layers', type=int, default=5, help='Number of convolutional layers')\nparser.add_argument('--stride', type=int, default=1, help='Stride in convolutions')\nparser.add_argument('--kernel_size', type=int, default=3, help='Kernel size in convolutions')\nparser.add_argument('--pooling', type=str, default='avg', help='Pooling type (avg, max or none')\nparser.add_argument('--non_linearity', type=str, default='True', help='Whether to apply non-linearity to convolutions')\nparser.add_argument('--batch_norm', type=str, default='True', help='Batch normalization')\nargs = parser.parse_args()\n\nassert args.non_linearity in BOOL_CHOICE and args.batch_norm in BOOL_CHOICE, \\\n \"Boolean values have to be either 'True' or 'False' \"\n\nexecute_train(model_class=CNN,\n model_args=dict(readout_layers=args.readout_layers,\n channels=args.channels,\n layers=args.layers,\n kernel_size=args.kernel_size,\n pooling=args.pooling,\n non_linearity=True if args.non_linearity == 'True' else False,\n batch_norm=True if args.batch_norm == 'True' else False,\n stride=args.stride),\n args=args)","sub_path":"xiongjeffrey__Neural-Embedding-in-Hyperbolic-Space/closest_string/triplet/models/cnn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"339248519","text":"import os\nimport re\n\nimport subprocess\nfrom Queue import Queue, Empty\nfrom threading import Thread\nimport uuid\nimport os\nimport shutil\nimport sys\nfrom celery import Celery\nfrom celery.contrib import rdb\n\nfrom ovirt_imageio_common import directio\nfrom kombu import Queue as kqueue\nimport json\nimport random\nimport logging\nimport logging.config\n\nlog = logging.getLogger(\"server\")\n\n\napp = Celery('celery_tasks', backend='redis', broker='redis://localhost:6379/0')\n'''app.conf.task_queues = (\n kqueue('backup_tasks'),\n kqueue('restore_tasks'),\n)'''\n#rdb.set_trace()\n\ndef is_blk_device(dev):\n try:\n if stat.S_ISBLK(os.stat(dev).st_mode):\n return True\n return False\n except Exception:\n print ('Path %s not found in is_blk_device check', dev)\n return False\n\n\ndef check_for_odirect_support(src, dest, flag='oflag=direct'):\n\n # Check whether O_DIRECT is supported\n try:\n nova_utils.execute('dd', 'count=0', 'if=%s' % src, 'of=%s' % dest,\n flag, run_as_root=True)\n return True\n except processutils.ProcessExecutionError:\n return False\n\n\ndef enqueue_output(out, queue):\n line = out.read(17)\n while line:\n line = out.read(17)\n queue.put(line)\n out.close()\n\n@app.task(bind=True, name=\"ovirt_imageio_daemon.celery_tasks.backup\")\ndef backup(self, ticket_id, path, dest, size, type, buffer_size, recent_snap_id):\n\n if type == \"full\":\n cmdspec = [\n 'qemu-img',\n 'convert',\n '-p',\n ]\n cmdspec += ['-O', 'qcow2', path, dest]\n cmd = \" \".join(cmdspec)\n print('Take a full snapshot with qemu-img convert cmd: %s ' % cmd)\n process = subprocess.Popen(cmdspec,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n bufsize=-1,\n close_fds=True,\n shell=False)\n\n queue = Queue()\n read_thread = Thread(target=enqueue_output,\n args=(process.stdout, queue))\n\n read_thread.daemon = True # thread dies with the program\n read_thread.start()\n\n percentage = 0.0\n while process.poll() is None:\n try:\n try:\n output = queue.get(timeout=300)\n except Empty:\n continue\n except Exception as ex:\n print(ex)\n\n percentage = re.search(r'\\d+\\.\\d+', output).group(0)\n\n print((\"copying from %(path)s to \"\n \"%(dest)s %(percentage)s %% completed\\n\") %\n {'path': path,\n 'dest': dest,\n 'percentage': str(percentage)})\n\n percentage = float(percentage)\n\n self.update_state(state='PENDING',\n meta={'percentage': percentage})\n\n except Exception as ex:\n pass\n\n '''qemu_cmd = [\"qemu-img\", \"info\", \"--output\", \"json\", dest]\n temp_process = subprocess.Popen(qemu_cmd, stdout=subprocess.PIPE)\n data, err = temp_process.communicate()\n data = json.loads(data)\n size = data[\"actual-size\"]\n process.stdin.close()\n self.update_state(state='PENDING',\n meta={'actual-size': size})'''\n\n _returncode = process.returncode # pylint: disable=E1101\n if _returncode:\n print(('Result was %s' % _returncode))\n raise Exception(\"Execution error %(exit_code)d (%(stderr)s). \"\n \"cmd %(cmd)s\" %\n {'exit_code': _returncode,\n 'stderr': process.stderr.read(),\n 'cmd': cmd})\n else:\n process = subprocess.Popen('qemu-img info --backing-chain --output json ' + path, stdout=subprocess.PIPE, shell=True)\n stdout, stderr = process.communicate()\n if stderr:\n print(('Result was %s' % stderr))\n raise Exception(\"Execution error %(exit_code)d (%(stderr)s). \"\n \"cmd %(cmd)s\" %\n {'exit_code': 1,\n 'stderr': stderr,\n 'cmd': 'qemu-img info --backing-chain --output json ' + path})\n\n result = json.loads(stdout)\n\n first_record = result[0]\n first_record_backing_file = first_record.get('backing-filename', None)\n recent_snap_path = recent_snap_id.get(str(first_record_backing_file), None)\n if first_record_backing_file and recent_snap_path:\n op = directio.Send(path,\n None,\n size,\n buffersize=buffer_size)\n total = 0\n print('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(\n self.request))\n gigs = 0\n with open(dest, \"w+\") as f:\n for data in op:\n total += len(data)\n f.write(data)\n if total/1024/1024/1024 > gigs:\n gigs = total/1024/1024/1024\n percentage = (total/size) * 100\n self.update_state(state='PENDING',\n meta={'percentage': percentage})\n process = subprocess.Popen('qemu-img rebase -u -b ' + recent_snap_path + ' ' + dest, stdout=subprocess.PIPE, shell=True)\n stdout, stderr = process.communicate()\n if stderr:\n log.error(\"Unable to change the backing file\", dest, stderr)\n else:\n\n temp_random_id = generate_random_string(5)\n tempdir = '/var/triliovault-mounts/staging/' + temp_random_id\n os.makedirs(tempdir)\n commands = []\n for record in result:\n filename = os.path.basename(str(record.get('filename', None)))\n recent_snap_path = recent_snap_id.get(str(record.get('backing-filename')), None)\n if record.get('backing-filename', None) and str(record.get('backing-filename', None)) and not recent_snap_path:\n try:\n shutil.copy(path, tempdir)\n backing_file = os.path.basename(str(record.get('backing-filename', None)))\n\n command = 'qemu-img rebase -u -b ' + backing_file + ' ' + filename\n commands.append(command)\n except IOError as e:\n print(\"Unable to copy file. %s\" % e)\n except:\n print(\"Unexpected error:\", sys.exc_info())\n else:\n try:\n shutil.copy(path, tempdir)\n command = 'qemu-img rebase -u ' + filename\n commands.append(command)\n except IOError as e:\n print(\"Unable to copy file. %s\" % e)\n except:\n print(\"Unexpected error:\", sys.exc_info())\n break\n path = str(record.get('full-backing-filename'))\n string_commands = \";\".join(str(x) for x in commands)\n process = subprocess.Popen(string_commands, stdin=subprocess.PIPE, stdout=subprocess.PIPE\n , cwd=tempdir, shell=True)\n stdout, stderr = process.communicate()\n if stderr:\n raise Exception(stdout)\n cmdspec = [\n 'qemu-img',\n 'convert',\n '-p',\n ]\n filename = os.path.basename(str(first_record.get('filename', None)))\n path = os.path.join(tempdir, filename)\n cmdspec += ['-O', 'qcow2', path, dest]\n process = subprocess.Popen(cmdspec,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n bufsize=-1,\n close_fds=True,\n shell=False)\n\n queue = Queue()\n read_thread = Thread(target=enqueue_output,\n args=(process.stdout, queue))\n\n read_thread.daemon = True # thread dies with the program\n read_thread.start()\n\n percentage = 0.0\n while process.poll() is None:\n try:\n try:\n output = queue.get(timeout=300)\n except Empty:\n continue\n except Exception as ex:\n print(ex)\n\n percentage = re.search(r'\\d+\\.\\d+', output).group(0)\n\n print((\"copying from %(path)s to \"\n \"%(dest)s %(percentage)s %% completed\\n\") %\n {'path': path,\n 'dest': dest,\n 'percentage': str(percentage)})\n\n percentage = float(percentage)\n\n self.update_state(state='PENDING',\n meta={'percentage': percentage})\n\n except Exception as ex:\n pass\n if recent_snap_path:\n process = subprocess.Popen('qemu-img rebase -u -b ' + recent_snap_path + ' ' + dest, stdout=subprocess.PIPE, shell=True)\n stdout, stderr = process.communicate()\n if stderr:\n log.error(\"Unable to change the backing file\", dest, stderr)\n del_command = 'rm -rf ' + tempdir\n delete_process = subprocess.Popen(del_command, shell=True, stdout=subprocess.PIPE)\n delete_process.communicate()\n\n\n@app.task(bind=True, name=\"ovirt_imageio_daemon.celery_tasks.restore\")\ndef restore(self, ticket_id, volume_path, backup_image_file_path, size, buffer_size):\n\n def transfer_qemu_image_to_volume(\n volume_path,\n backup_image_file_path):\n\n cmdspec = [\n 'qemu-img',\n 'convert',\n '-p',\n ]\n\n if is_blk_device(volume_path) and \\\n check_for_odirect_support(backup_image_file_path,\n volume_path, flag='oflag=direct'):\n cmdspec += ['-t', 'none']\n\n cmdspec += ['-O', 'qcow2', backup_image_file_path, volume_path]\n\n default_cache = True\n if default_cache is True:\n if '-t' in cmdspec:\n cmdspec.remove('-t')\n if 'none' in cmdspec:\n cmdspec.remove('none')\n cmd = \" \".join(cmdspec)\n print('transfer_qemu_image_to_volume cmd %s ' % cmd)\n process = subprocess.Popen(cmdspec,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n bufsize=-1,\n close_fds=True,\n shell=False)\n\n queue = Queue()\n read_thread = Thread(target=enqueue_output,\n args=(process.stdout, queue))\n\n read_thread.daemon = True # thread dies with the program\n read_thread.start()\n\n percentage = 0.0\n while process.poll() is None:\n try:\n try:\n output = queue.get(timeout=300)\n except Empty:\n continue\n except Exception as ex:\n print(ex)\n\n percentage = re.search(r'\\d+\\.\\d+', output).group(0)\n\n print((\"copying from %(backup_path)s to \"\n \"%(volume_path)s %(percentage)s %% completed\\n\") %\n {'backup_path': backup_image_file_path,\n 'volume_path': volume_path,\n 'percentage': str(percentage)})\n\n percentage = float(percentage)\n\n self.update_state(state='PENDING',\n meta={'percentage': percentage})\n\n except Exception as ex:\n pass\n\n process.stdin.close()\n\n _returncode = process.returncode # pylint: disable=E1101\n if _returncode:\n print(('Result was %s' % _returncode))\n raise Exception(\"Execution error %(exit_code)d (%(stderr)s). \"\n \"cmd %(cmd)s\" %\n {'exit_code': _returncode,\n 'stderr': process.stderr.read(),\n 'cmd': cmd})\n\n transfer_qemu_image_to_volume(volume_path, backup_image_file_path)\n\ndef generate_random_string(string_length=5):\n \"\"\"Returns a random string of length string_length.\"\"\"\n\n random = str(uuid.uuid4())\n random = random.upper()\n random = random.replace(\"-\",\"\")\n return random[0:string_length]\n","sub_path":"daemon/celery_tasks.py","file_name":"celery_tasks.py","file_ext":"py","file_size_in_byte":13310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"250886494","text":"import tkinter as tk\n\n\ndef builder(page, cid):\n cache = page.components[cid]\n master = cache[\"master\"]\n padding = cache[\"padding\"]\n config = cache[\"config\"]\n frame = tk.Frame(master)\n frame.pack(side=config[\"side\"], anchor=config[\"anchor\"],\n padx=padding[0], pady=padding[1])\n label = tk.Label(frame, text=config[\"title\"])\n label.pack(anchor=\"w\")\n show = None\n if config[\"secretive\"]:\n show = \"*\"\n str_var = tk.StringVar()\n entry = tk.Entry(frame, show=show,\n textvariable=str_var,\n width=config[\"width\"])\n entry.pack(anchor=\"w\")\n on_submit = config[\"on_submit\"]\n if config[\"text\"]:\n str_var.set(config[\"text\"])\n if on_submit:\n cache = (lambda e, page=page,\n cid=cid,\n on_submit=on_submit:\n on_submit(page, cid))\n entry.bind(\"\", cache)\n parts = {\"entry\": entry, \"str_var\": str_var,\n \"label\": label, \"frame\": frame}\n return parts, data_getter\n\n\ndef data_getter(page, cid):\n cache = page.components[cid]\n parts = cache[\"parts\"]\n config = cache[\"config\"]\n return parts[\"str_var\"].get()\n","sub_path":"dresscode/component/entry.py","file_name":"entry.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"635073257","text":"from threading import Thread, RLock\nfrom enum import Enum\n\n# You must define notification names like this:\n# class DeviceNotification(Enum):\n# willMove = \"willMove\"\n# didMove = \"didMove\"\n# didGetPosition = \"didGetPosition\"\n\nclass Notification:\n def __init__(self, name, object=None, userInfo=None):\n if not isinstance(name, Enum):\n raise ValueError(\"You must use an enum-subclass of Enum, not a string for the notification name\")\n\n self.name = name\n self.object = object\n self.userInfo = userInfo\n\nclass ObserverInfo:\n def __init__(self, observer, method=None, notificationName=None, observedObject=None):\n self.observer = observer\n self.method = method\n self.observedObject = observedObject\n self.notificationName = notificationName\n\n def matches(self, otherObserver) -> bool:\n if self.notificationName is not None and otherObserver.notificationName is not None and self.notificationName != otherObserver.notificationName:\n return False\n elif self.observedObject is not None and otherObserver.observedObject is not None and self.observedObject != otherObserver.observedObject:\n return False\n elif self.observer != otherObserver.observer:\n return False\n return True\n\n def __eq__(self, rhs):\n return self.matches(rhs)\n\nclass NotificationCenter:\n _instance = None\n\n def destroy(self):\n nc = NotificationCenter()\n NotificationCenter._instance = None\n del(nc)\n\n def __init__(self):\n if not hasattr(self, 'observers'):\n self.observers = {}\n if not hasattr(self, 'lock'):\n self.lock = RLock()\n\n def __new__(cls, *args, **kwargs):\n if cls._instance is None:\n cls._instance = object.__new__(cls, *args, **kwargs)\n return cls._instance\n\n def addObserver(self, observer, method, notificationName=None, observedObject=None):\n if notificationName is not None and not isinstance(notificationName, Enum):\n raise ValueError(\"You must use an enum-subclass of Enum, not a string for the notificationName\")\n\n observerInfo = ObserverInfo(observer=observer, method=method, notificationName=notificationName, observedObject=observedObject)\n\n with self.lock:\n if notificationName not in self.observers.keys():\n self.observers[notificationName] = [observerInfo]\n else:\n if observerInfo not in self.observers[notificationName]:\n self.observers[notificationName].append(observerInfo)\n\n def removeObserver(self, observer, notificationName=None, observedObject=None):\n if notificationName is not None and not isinstance(notificationName, Enum):\n raise ValueError(\"You must use an enum-subclass of Enum, not a string for the notificationName\")\n\n observerToRemove = ObserverInfo(observer=observer, notificationName=notificationName, observedObject=observedObject)\n\n with self.lock:\n if notificationName is not None:\n self.observers[notificationName] = [currentObserver for currentObserver in self.observers[notificationName] if not currentObserver.matches(observerToRemove) ]\n else:\n for name in self.observers.keys():\n self.observers[name] = [observer for observer in self.observers[name] if not observer.matches(observerToRemove) ] \n\n def postNotification(self, notificationName, notifyingObject, userInfo=None):\n if not isinstance(notificationName, Enum):\n raise ValueError(\"You must use an enum-subclass of Enum, not a string for the notificationName\")\n\n with self.lock:\n if notificationName in self.observers.keys():\n notification = Notification(notificationName, notifyingObject, userInfo)\n for observerInfo in self.observers[notificationName]:\n if observerInfo.observedObject is None or observerInfo.observedObject == notifyingObject:\n observerInfo.method(notification)\n\n def observersCount(self):\n with self.lock:\n count = 0\n for name in self.observers.keys():\n count += len(self.observers[name])\n return count\n\n def clear(self):\n with self.lock:\n self.observers = {}\n","sub_path":"hardwarelibrary/notificationcenter.py","file_name":"notificationcenter.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"576656201","text":"import sys\r\nfrom string import ascii_lowercase\r\n\r\n\r\ndef scrabbleCheat(argv):\r\n\r\n # Error checking\r\n for el in list(argv.lower()):\r\n if el not in ascii_lowercase and el not in ['*', '?']:\r\n raise Exception(\"The Scrabble rack can only contain letters, or '*' or '?' for wildcards.\")\r\n\r\n if len(sys.argv) > 2:\r\n raise Exception(\"Only one rack of letters allowed.\")\r\n\r\n # Scrabble scores for each letter\r\n scoresList = {\"a\": 1, \"c\": 3, \"b\": 3, \"e\": 1, \"d\": 2, \"g\": 2,\r\n \"f\": 4, \"i\": 1, \"h\": 4, \"k\": 5, \"j\": 8, \"m\": 3,\r\n \"l\": 1, \"o\": 1, \"n\": 1, \"q\": 10, \"p\": 3, \"s\": 1,\r\n \"r\": 1, \"u\": 1, \"t\": 1, \"w\": 4, \"v\": 4, \"y\": 4,\r\n \"x\": 8, \"z\": 10, \"*\": 0, \"?\": 0}\r\n\r\n # Create the Scrabble rack from user input\r\n letters = sorted(list(argv.upper()), reverse=True)\r\n\r\n # Constructing the word list from outside file\r\n wordList = list()\r\n file = open(\"sowpods.txt\", 'r')\r\n for line in file:\r\n wordList.append(line.strip('\\n'))\r\n\r\n # Find matches\r\n validWords = list()\r\n for word in wordList:\r\n wordTemp = list(word)\r\n\r\n if len(wordTemp) > len(letters):\r\n continue\r\n\r\n for letter in letters:\r\n if letter in wordTemp:\r\n wordTemp.remove(letter)\r\n else:\r\n if len(wordTemp) == 0 or len(wordTemp) <= (letters.count('*') + letters.count('?')):\r\n validWords.append(word)\r\n\r\n # Init the answer list and calculate the score value for each entry\r\n answerList = list()\r\n for ans in validWords:\r\n score = 0\r\n for el in ans:\r\n score += scoresList[el.lower()]\r\n answerList.append((score, ans))\r\n\r\n # Sort answer list and print\r\n answerList.sort(reverse = True)\r\n for el in answerList:\r\n print(el[0], el[1])\r\n\r\n\r\nif __name__ == '__main__':\r\n try:\r\n scrabbleCheat(sys.argv[1])\r\n # scrabbleCheat('?AAB')\r\n except IndexError:\r\n print(\"Scrabble rack required as a command line argument. Please enter a valid Scrabble rack of 1 to 7 \"\r\n \"letters in the format 'scrabCheat.py '.\")\r\n sys.exit(1)","sub_path":"week7/scrabbleCheat.py","file_name":"scrabbleCheat.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"344652825","text":"#!/usr/bin/python\n\nimport time\nimport RPi.GPIO as GPIO\n\nclass hc_sr04:\n def __init__(self,trig,echo):\n self.trig = trig\n self.echo = echo\n GPIO.setup(trig, GPIO.OUT)\n GPIO.setup(echo, GPIO.IN)\n GPIO.output(trig, GPIO.LOW)\n time.sleep(1)\n \n def measure(self):\n GPIO.output(self.trig, GPIO.HIGH)\n time.sleep(0.00001)\n GPIO.output(self.trig, GPIO.LOW)\n while GPIO.input(self.echo) == 0:\n sigoff = time.time()\n \n while GPIO.input(self.echo) == 1:\n sigon = time.time()\n \n return (sigon - sigoff) * 17000","sub_path":"pi_root/home/pi/shell/Python/hc_sr04.py","file_name":"hc_sr04.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"358049589","text":"import os\nimport re\nfrom collections import Counter\n\nsymbols = [',','.',';',':','\"','<','>','?','/','\\\\','!','$','%','^','^','&','*','-','\\'','(',')','=']\n\ndef cleanText(word):\n global symbols\n a = word.split()\n newWord = ''\n for i in a:\n if not '@' in i and not '#' in i and not 'http:' in i and not 'https:' in i:\n for j in symbols:\n i = i.replace(j,'') \n newWord = newWord + i + ' '\n return newWord.rstrip()\n\ndef write(tweets,text,f,name):\n tweets[text] = name\n a = cleanText(text)\n if len(a) > 0:\n f.write(a)\n f.write('\\n')\n return tweets\n\npath=\"H:\\\\masters\\\\sem5\\\\special_topics_in_advanced_db\\\\\"\n\nf1 = open(path+'movie tweets\\\\the_longest_ride.txt','w')\nf2 = open(path+'movie tweets\\\\ex_machina.txt','w')\nf3 = open(path+'movie tweets\\\\desert_dancer.txt','w')\nf4 = open(path+'movie tweets\\\\clouds_of_sils_maria.txt','w')\nf5 = open(path+'movie tweets\\\\kill_me_three_times.txt','w')\nf6 = open(path+'movie tweets\\\\lost_river.txt','w')\nf7 = open(path+'movie tweets\\\\while_we_are_young.txt','w')\nf8 = open(path+'movie tweets\\\\selma.txt','w')\nf9 = open(path+'movie tweets\\\\danny_collins.txt','w')\nf10 = open(path+'movie tweets\\\\the_second_best_exotic_marigold_hotel.txt','w')\nf11 = open(path+'movie tweets\\\\fifty_shades_of_grey.txt','w')\nf12 = open(path+'movie tweets\\\\into_the_woods.txt','w')\nf13 = open(path+'movie tweets\\\\the_imitation_game.txt','w')\nf14 = open(path+'movie tweets\\\\seventh_son.txt','w')\nf15 = open(path+'movie tweets\\\\the_spongebob_movie_sponge_out_of_water.txt','w')\nf16 = open(path+'movie tweets\\\\paddington.txt','w')\nf17 = open(path+'movie tweets\\\\american_sniper.txt','w')\nf18 = open(path+'movie tweets\\\\night_at_the_musuem_secret_of_the_tomb.txt','w')\nf19 = open(path+'movie tweets\\\\cinderella.txt','w')\nf20 = open(path+'movie tweets\\\\furious7.txt','w')\nf21 = open(path+'movie tweets\\\\the_gunman.txt','w')\nf22 = open(path+'movie tweets\\\\do_you_believe.txt','w')\nf23 = open(path+'movie tweets\\\\run_all_night.txt','w')\nf24 = open(path+'movie tweets\\\\kingsman.txt','w')\nf25 = open(path+'movie tweets\\\\insurgent.txt','w')\nf26 = open(path+'movie tweets\\\\chappie.txt','w')\nf27 = open(path+'movie tweets\\\\focus.txt','w')\nf28 = open(path+'movie tweets\\\\get_hard.txt','w')\nf29 = open(path+'movie tweets\\\\home.txt','w')\nf30 = open(path+'movie tweets\\\\woman_in_gold.txt','w')\nf31 = open(path+'movie tweets\\\\it_follows.txt','w')\n\nfilenames = next(os.walk(path+'tweets'))[2]\ncount = 0\ntweets = {}\nfor name in filenames:\n content = open(path+'tweets\\\\'+name,'r')\n count1 = 0\n for line in content:\n a = str(line)\n if ',\"text\"' and ',\"source\"' in a:\n \n count1 = count1 + 1\n firstIndex = a.index(',\"text\"')\n firstIndex = firstIndex + 9\n secondIndex = a.index(',\"source\"')\n secondIndex = secondIndex - 1\n text = a[firstIndex:secondIndex]\n\n if not text in tweets:\n text = text.lower()\n if text.find('The Longest Ride'.lower()) != -1 or text.find('thelongestride') != -1 or text.find('longestride') != -1 or text.find('longest ride') != -1 :\n tweets = write(tweets,text,f1,'the_longest_ride')\n elif text.find('Ex Machina'.lower()) != -1 or text.find('ExMachina'.lower()) != -1 :\n tweets = write(tweets,text,f2,'ex_machina')\n elif text.find('Desert Dancer'.lower()) != -1 or text.find('DesertDancer'.lower()) != -1 :\n tweets = write(tweets,text,f3,'desert_dancer')\n elif text.find('Clouds of Sils Maria'.lower()) != -1 or text.find('CloudsOfSilsMaria'.lower()) != -1 or text.find('Sils Maria'.lower()) != -1 or text.find('SilsMaria'.lower()) != -1:\n tweets = write(tweets,text,f4,'clouds_of_sils_maria')\n elif text.find('Kill Me Three Times'.lower()) != -1 or text.find('KillMeThreeTimes'.lower()) != -1 :\n tweets = write(tweets,text,f5,'kill_me_thee_times')\n elif text.find('Lost River'.lower()) != -1 or text.find('LostRiver'.lower()) != -1 :\n tweets = write(tweets,text,f6,'lost_river')\n elif text.find('While We\\'re Young'.lower()) != -1 or text.find('While We are Young'.lower()) != -1 or text.find('WhileWeAreYoung'.lower()) != -1:\n tweets = write(tweets,text,f7,'while_we_are_young')\n elif text.find('selma'.lower()) != -1 :\n tweets = write(tweets,text,f8,'selma')\n elif text.find('Danny Collins'.lower()) != -1 or text.find('DannyCollins'.lower()) != -1 :\n tweets = write(tweets,text,f9,'danny_collins')\n elif text.find('The Second Best Exotic Marigold Hotel'.lower()) != -1 :\n tweets = write(tweets,text,f10,'the_second_best_exotic_marigold_hotel')\n elif text.find('Fifty Shades of Grey'.lower()) != -1 or text.find('FiftyShades'.lower()) != -1 :\n tweets = write(tweets,text,f11,'fifty_shades_of_grey')\n elif text.find('Into the Woods'.lower()) != -1 or text.find('IntotheWoods'.lower()) != -1 :\n tweets = write(tweets,text,f12,'into_the_woods')\n elif text.find('The Imitation Game'.lower()) != -1 or text.find('TheImitationGame'.lower()) != -1 or text.find('Imitation Game'.lower()) != -1 or text.find('ImitationGame'.lower()) != -1:\n tweets = write(tweets,text,f13,'the_imitation_game')\n elif text.find('Seventh Son'.lower()) != -1 or text.find('SeventhSon'.lower()) != -1 :\n tweets = write(tweets,text,f14,'seventh_son')\n elif text.find('The SpongeBob Movie: Sponge Out of Water'.lower()) != -1 or text.find('SpongeBobMovie'.lower()) != -1 or text.find('SpongeBob'.lower()) != -1:\n tweets = write(tweets,text,f15,'the_spongebob_movie_out_of_water')\n elif text.find('Paddington'.lower()) != -1 :\n tweets = write(tweets,text,f16,'paddington')\n elif text.find('American Sniper'.lower()) != -1 or text.find('AmericanSniper'.lower()) != -1 :\n tweets = write(tweets,text,f17,'american_sniper')\n elif text.find('Night at the Museum: Secret of the Tomb'.lower()) != -1 or text.find('Night at the Museum'.lower()) != -1 :\n tweets = write(tweets,text,f18,'night_at_the_museum_secret_of_the_tomb')\n elif text.find('cinderella'.lower()) != -1 :\n tweets = write(tweets,text,f19,'cinderella')\n elif text.find('furious7'.lower()) != -1 or text.find('furious 7'.lower()) != -1 :\n tweets = write(tweets,text,f20,'furious7')\n elif text.find('the gunman'.lower()) != -1 or text.find('thegunman'.lower()) != -1 :\n tweets = write(tweets,text,f21,'the_gunman')\n elif text.find('do you believe'.lower()) != -1 :\n tweets = write(tweets,text,f22,'do_you_believe')\n elif text.find('run all night'.lower()) != -1 :\n tweets = write(tweets,text,f23,'run_all_night')\n elif text.find('kingsman'.lower()) != -1 :\n tweets = write(tweets,text,f24,'kingsman')\n elif text.find('insurgent'.lower()) != -1 or text.find('insurgentmovie'.lower()) != -1 :\n tweets = write(tweets,text,f25,'insurgent')\n elif text.find('chappie'.lower()) != -1 or text.find('chappiemovie'.lower()) != -1 or text.find('chappiethemovie'.lower()) != -1 :\n tweets = write(tweets,text,f26,'chappie')\n elif text.find('focus movie'.lower()) != -1 :\n tweets = write(tweets,text,f27,'focus')\n elif text.find('gethard'.lower()) != -1 or text.find('get hard'.lower()) != -1 :\n tweets = write(tweets,text,f28,'get_hard')\n elif text.find('home movie'.lower()) != -1 or text.find('homemovie'.lower()) != -1 or text.find('DreamWorksHOME'.lower()) != -1 :\n tweets = write(tweets,text,f29,'home')\n elif text.find('woman in gold'.lower()) != -1 or text.find('womaningold'.lower()) != -1 :\n tweets = write(tweets,text,f30,'woman_in_gold')\n elif text.find('itfollows'.lower()) != -1 or text.find('itfollowsfilm'.lower()) != -1 :\n tweets = write(tweets,text,f31,'it_follows')\n## if count1 == 100:\n## break\n print(count)\n count = count + 1\n## print(tweets)\n## if count == 1:\n## break\nprint(Counter(tweets.values()))\n","sub_path":"clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":8746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"308421566","text":"\"\"\"\nCreated 7/25/19\n\nHopefully this turns out to be a half decent minecraft clone\n\"\"\"\n\nimport pygame\nimport pygame.locals as lcl\n\nimport OpenGL.GL as GL\nimport OpenGL.GLU as GLU\nfrom Block import Block\n\nmyBlocks=[]\nedges = (\n (0,1),\n (0,3),\n (0,4),\n (2,1),\n (2,3),\n (2,7),\n (6,3),\n (6,4),\n (6,7),\n (5,1),\n (5,4),\n (5,7)\n )\n\n\nmove_map = {pygame.K_w: ( 0, 0, .1),\n pygame.K_s: ( 0, 0,-.1),\n pygame.K_a: ( .1, 0, 0),\n pygame.K_d: (-.1, 0, 0),\n pygame.K_q: (1000, 0, 0)}\n\ndef checkKeys():\n move=[]\n pressed = pygame.key.get_pressed()\n for key in move_map:\n if pressed[key]:\n move.append(move_map[key])\n for direction in move:\n if direction[0]==1000:\n GL.glRotatef(1, 3, 1, 1)\n else:\n GL.glTranslatef(direction[0], direction[1], direction[2])\n \n\ndef draw():\n GL.glBegin(GL.GL_LINES)\n for b in myBlocks:\n vertices=b.getVertices()\n for edge in edges:\n for vertex in edge:\n GL.glVertex3fv(vertices[vertex])\n GL.glEnd()\n\ndef main():\n global count,myBlocks\n pygame.init()\n display = (1000,750)\n pygame.display.set_mode(display, lcl.DOUBLEBUF|lcl.OPENGL)\n\n GLU.gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)\n \n GL.glTranslatef(0.0,0.0, -5)\n myBlocks.append(Block(0,0,0))\n myBlocks.append(Block(1,0,0))\n myBlocks.append(Block(0,0,3))\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n checkKeys()\n GL.glClear(GL.GL_COLOR_BUFFER_BIT|GL.GL_DEPTH_BUFFER_BIT)\n draw()\n pygame.display.flip()\n pygame.time.wait(10)\n\nmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"154689785","text":"import sqlite3\n\nconn = sqlite3.connect('db.db')\nc = conn.cursor()\naskid =6\nwhile(1):\n\tprint('1) Costumer room number and id \\n2) Info of hotel owner \\n3) Bookings \\n4) The dates of payments and amount \\n5) The info of costumers hotel \\n6) Update the price of rooms \\n7) Add new costumer \\n0) End \\n')\n\tchoice = input(\"Your choice: \")\n\tif choice == '1':\n\t\tcostumer = input(\"Name of costumer \")\n\t\ttuple = (costumer,)\n\t\tc.execute('SELECT firstname, lastname, room.roomID, roomtype.price, roomtype.amount FROM (costumer INNER JOIN booking ON costumer.costumerID = booking.costumerID) INNER JOIN room ON booking.roomID = room.roomID INNER JOIN roomtype ON room.roomtypeID = roomtype.roomtypeID WHERE firstname =?;', tuple)\n\t\trow = c.fetchone()\n\t\theaders = ['Costumer first name', 'Costumer last name', 'Room number', 'Room price', 'Room type']\n\t\twhile row is not None:\n \t\t\ta = 0\n \t\t\twhile a <= 4:\n \t\t\t\tprint(headers[a], '=', row[a])\n \t\t\t\ta = a + 1\n \t\t\tprint('\\n')\n \t\t\trow = c.fetchone()\n\t\tconn.commit()\n\telif choice == '2':\n\t\tc.execute('SELECT * FROM \"ownerInfo\";')\n\t\trow = c.fetchone()\n\t\theaders = ['Owner first name', 'Owner last name', 'Owner email', 'Owner phonenumber', 'Hotel name', 'Hotel address']\n\t\twhile row is not None:\n\t\t\ta = 0\n\t\t\twhile a <= 5:\n\t\t\t\tprint(headers[a], '=', row[a])\n\t\t\t\ta = a + 1\n\t\t\tprint('\\n')\n\t\t\trow = c.fetchone()\n\t\tconn.commit()\n\telif choice == '3':\n\t\tc.execute('SELECT * FROM \"bookingTimes\";')\n\t\trow = c.fetchone()\n\t\theaders = ['Costumer first name', 'Costumer last name', 'Booking start date', 'Booking end date', 'Payment complete']\n\t\twhile row is not None:\n\t\t\ta = 0\n\t\t\twhile a <= 4:\n\t\t\t\tprint(headers[a], '=', row[a])\n\t\t\t\ta = a + 1\n\t\t\tprint('\\n')\n\t\t\trow = c.fetchone()\n\t\tconn.commit()\n\telif choice == '4':\n\t\tc.execute('SELECT * FROM \"payments\";')\n\t\trow = c.fetchone()\n\t\theaders = ['Costumer first name', 'Costumer last name', 'Room price','Payment complete']\n\t\twhile row is not None:\n\t\t\ta = 0\n\t\t\twhile a <= 3:\n\t\t\t\tprint(headers[a], '=', row[a])\n\t\t\t\ta = a + 1\n\t\t\tprint('\\n')\n\t\t\trow = c.fetchone()\n\t\tconn.commit()\n\telif choice == '5':\n\t\tc.execute('SELECT * FROM \"hotels\";')\n\t\trow = c.fetchone()\n\t\theaders = ['Costumer first name', 'Costumer last name', 'Hotel name', 'Hotel address', 'Hotel country']\n\t\twhile row is not None:\n\t\t\ta = 0\n\t\t\twhile a <= 4:\n\t\t\t\tprint(headers[a], '=', row[a])\n\t\t\t\ta = a + 1\n\t\t\tprint('\\n')\n\t\t\trow = c.fetchone()\n\t\tconn.commit()\n\telif choice == '6':\n\t\tprice = input(\"Give new price for family room: \")\n\t\ttuple = (price,)\n\t\tc.execute('UPDATE roomtype SET price =? WHERE roomtype.roomtypeID = 2;', tuple) \n\t\tc.execute('SELECT amount, price FROM roomtype WHERE roomtype.roomtypeID = 2')\n\t\trow = c.fetchone()\n\t\theaders = ['Room type', 'New price']\n\t\twhile row is not None:\n\t\t\ta = 0\n\t\t\twhile a <= 1:\n\t\t\t\tprint(headers[a], '=', row[a])\n\t\t\t\ta = a + 1\n\t\t\tprint('\\n')\n\t\t\trow = c.fetchone()\n\t\tconn.commit()\n\telif choice == '7':\n\t\tfirst =input(\"Costumer first name: \")\n\t\tlast = input(\"Costumer last name: \")\n\t\tbd = input (\"Costumer birthdate ('yyyy-mm-dd'): \")\n\t\tpnum = input(\"Costumer phonenumber: \")\n\t\temail = input(\"Costumer email: \")\n\t\tc.execute(\"INSERT INTO costumer (costumerID, email, phonenum, birthdate, firstname, lastname) VALUES(?,?,?,?,?,?);\", (askid, email, pnum, bd,first, last))\n\t\tprint(\"\\n\")\n\t\tc.execute('SELECT * FROM costumer')\n\t\trow = c.fetchone()\n\t\theaders = ['Costumer ID', 'Costumer email', 'Costumer phonenumber', 'Costumer birthdate', 'Costumer first name', 'Costumer last name']\n\t\twhile row is not None:\n\t\t\ta = 0\n\t\t\twhile a <= 5:\n\t\t\t\tprint(headers[a], '=', row[a])\n\t\t\t\ta = a + 1\n\t\t\tprint('\\n')\n\t\t\trow = c.fetchone()\n\t\tconn.commit()\n\t\taskid = askid + 1\t\n\telif choice == '0':\n\t\tconn.close()\n\t\tbreak;\n\telse:\n\t\tprint(\"Unknown command.\")\n","sub_path":"Hotel/Ohjelmisto/hotelli.py","file_name":"hotelli.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"468387074","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0059_auto_20170404_0635'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='trip',\n name='destinations',\n ),\n migrations.AddField(\n model_name='trip',\n name='destinations',\n field=models.CharField(default=True, max_length=256, verbose_name='Where', blank=True),\n ),\n ]\n","sub_path":"apps/trips/migrations/0060_auto_20170404_0710.py","file_name":"0060_auto_20170404_0710.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"347385496","text":"import numpy as np\nimport keras\nfrom keras.models import Model\nfrom models import rec_model\nfrom coder import decoder\nfrom data_input import data_input\nfrom matplotlib import pyplot as plt\n\n\ndef model_train_plot(hidden = 100, dropout = 0.0, optimizer = 'rmsprop'):\n '''\n Train the recurrent model with batch of fixed-length sequences.\n Save the weights with filename indicating the configuration of the model,\n and plot accuracy and loss of training and validation set throughout the\n training.\n '''\n\n filename = 'data/input.txt'\n train_data, val_data, vocab_list, vocab_dict = data_input(filename)\n\n timestep = 30\n dim = len(vocab_list)\n model = rec_model(dim,hidden,temp = 1, dropout = dropout)\n\n model.compile(optimizer= optimizer,\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n hist = []\n for epoch in range(50):\n training, train_label = generate_slices(train_data, timestep, 100000, vocab_dict)\n val, val_label = generate_slices(val_data, timestep, 20000, vocab_dict)\n h = model.fit(training, train_label, batch_size=100, nb_epoch=2 * epoch + 2, validation_data= (val, val_label),initial_epoch= epoch * 2)\n hist.append(h)\n\n # model.save_weights('model/model_'+str(hidden)+'_' + str(dropout)+'_'+ optimizer+'.h5')\n\n history = {}\n for h in hist:\n for k in h.history:\n if k in history:\n history[k] += h.history[k]\n else:\n history[k] = h.history[k]\n\n plt.figure()\n acc, = plt.plot(np.array(history['acc']),label = 'Training Accuracy')\n valacc, = plt.plot(np.array(history['val_acc']), label = 'Validation Accuracy')\n plt.legend(handles = [acc, valacc])\n plt.savefig('image/accu_' + str(hidden)+'_' + str(dropout)+'_'+ optimizer+'.eps', format='eps', dpi=400)\n plt.show()\n\n plt.figure()\n loss, = plt.plot(np.array(history['loss']),label = 'Training Loss')\n valloss, = plt.plot(np.array(history['val_loss']), label = 'Validation Loss')\n plt.legend(handles = [loss, valloss])\n plt.savefig('image/loss_' + str(hidden)+'_' + str(dropout)+'_'+ optimizer+'.eps', format='eps', dpi=400)\n plt.show()\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"577402979","text":"import argparse\nimport logging\nimport logging.handlers\nfrom common import config\nfrom service import ClientWorker\n\ndef _configure_logging(conf):\n log_filename = conf.get('log', 'file')\n root_logger = logging.RootLogger\n\n handler = logging.handlers.RotatingFileHandler(\n log_filename, maxBytes=1024 * 1024 * 5, backupCount=5)\n formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M')\n handler.setFormatter(formatter)\n\n logging.root.addHandler(handler)\n logging.root.setLevel(logging.DEBUG)\n\n logging.getLogger(\"VirtualEnv\").setLevel(logging.INFO)\n logging.getLogger(\"GitRepoHandler\").setLevel(logging.INFO)\n logging.getLogger(\"Pika\").setLevel(logging.WARNING)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='CMPE 273 Raspberry Pi Client service')\n parser.add_argument('--config-file', dest='config_file', default='/etc/deployer-client/deployer.conf')\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n parser = parse_args()\n conf = config.get_config(parser.config_file)\n _configure_logging(conf)\n ClientWorker.start_service(conf)\n","sub_path":"deployer/PiClient/client/client_service.py","file_name":"client_service.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"200220601","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Assist',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='Hold',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('navn', models.CharField(max_length=35)),\n ],\n ),\n migrations.CreateModel(\n name='Kamp',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('kampnr', models.IntegerField()),\n ('modstander', models.CharField(max_length=35)),\n ('hjemmebane', models.BooleanField(default=False)),\n ('vores_maal', models.IntegerField()),\n ('deres_maal', models.IntegerField()),\n ('tilskuere', models.IntegerField()),\n ('dommer', models.CharField(max_length=50)),\n ('stadion', models.CharField(max_length=35)),\n ('adresse', models.CharField(max_length=150)),\n ('tidspunkt', models.DateTimeField()),\n ('afsluttet', models.BooleanField(default=False)),\n ],\n ),\n migrations.CreateModel(\n name='Klub',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('navn', models.CharField(max_length=35)),\n ('stiftet', models.DateField()),\n ('adresse', models.CharField(max_length=150)),\n ],\n ),\n migrations.CreateModel(\n name='Kort',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('roedt', models.BooleanField()),\n ('gult', models.BooleanField()),\n ('kamp', models.ForeignKey(to='main.Kamp')),\n ],\n ),\n migrations.CreateModel(\n name='Maal',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('kamp', models.ForeignKey(to='main.Kamp')),\n ],\n ),\n migrations.CreateModel(\n name='Saeson',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('raekke', models.CharField(max_length=25)),\n ('pulje', models.CharField(max_length=25)),\n ],\n ),\n migrations.CreateModel(\n name='Spiller',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('alder', models.IntegerField()),\n ('position', models.CharField(max_length=35)),\n ('ben', models.CharField(max_length=15)),\n ('tilstand', models.CharField(max_length=255)),\n ('bruger', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ('hold', models.ForeignKey(to='main.Hold')),\n ],\n ),\n migrations.CreateModel(\n name='Tilmelding',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('kamp', models.ForeignKey(to='main.Kamp')),\n ('spillere', models.ManyToManyField(to='main.Spiller')),\n ],\n ),\n migrations.AddField(\n model_name='maal',\n name='spiller',\n field=models.ForeignKey(to='main.Spiller'),\n ),\n migrations.AddField(\n model_name='kort',\n name='spiller',\n field=models.ForeignKey(to='main.Spiller'),\n ),\n migrations.AddField(\n model_name='kamp',\n name='kampens_spiller',\n field=models.ForeignKey(to='main.Spiller'),\n ),\n migrations.AddField(\n model_name='kamp',\n name='saeson',\n field=models.ForeignKey(to='main.Saeson'),\n ),\n migrations.AddField(\n model_name='hold',\n name='klub',\n field=models.ForeignKey(to='main.Klub'),\n ),\n migrations.AddField(\n model_name='assist',\n name='kamp',\n field=models.ForeignKey(to='main.Kamp'),\n ),\n migrations.AddField(\n model_name='assist',\n name='spiller',\n field=models.ForeignKey(to='main.Spiller'),\n ),\n ]\n","sub_path":"sisu/main/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"447572946","text":"# coding: SHIFT-JIS\r\n# opencvの学習済みHOG分類器を使用\r\nimport os\r\nimport cv2\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\n\r\n#c_dir = os.path.dirname(__file__)\r\n\r\nimage_name = sys.argv[1]\r\nprint(image_name)\r\nimage = cv2.imread(image_name)\r\n\r\nhog = cv2.HOGDescriptor()\r\nhog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\r\nhogParams = {'winStride': (8, 8), 'padding': (32,32), 'scale':1.05}\r\ndetect, r = hog.detectMultiScale(image, **hogParams)\r\nfor(x, y, w, h) in detect:\r\n cv2.rectangle(image, (x,y), (x+w, y+h), (0, 50, 255), 3)\r\ncv2.imshow('Result', image)\r\n\r\nwhile(1):\r\n# 文字列をASCIIコード変換\r\n wait = cv2.waitKey(1)&0xff\r\n if wait == ord('q'):\r\n cv2.destroyAllWindows()\r\n exit()","sub_path":"extract_HOG.py","file_name":"extract_HOG.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"169466360","text":"import tkinter\nfrom tkinter import *\n\nwindow = Tk()\n\nm1 = PanedWindow(window)\nm1.pack(fill=BOTH, expand=1)\n\nleft = Entry(m1, bd=3)\nm1.add(left)\n\nm2 = PanedWindow(m1, orient=VERTICAL)\nm1.add(m2)\n\ntop = Scale(m2, orient=HORIZONTAL)\nm2.add(top)\n\nbtn = Button(m2, text=\"M2 btn\")\nm2.add(btn)\n\nwindow.mainloop()\n","sub_path":"src/gui/tkinter/paned_window.py","file_name":"paned_window.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"150346347","text":"import os\n\nroot_dir = '.'\n\ndouble_byte = ['é', 'ö', 'Á', 'à', 'ü', 'ç', 'ã', 'ô', 'Ü', 'ō', 'ñ', 'ý', 'á', 'ĕ', 'Ç', 'è', 'É', 'â', 'ú', 'ó', 'í', 'ê', 'ï', 'Ö', 'ä', 'À', 'ž', 'û']\nsingle_byte = ['é', 'ö', 'Á', 'à', 'ü', 'ç', 'ã', 'ô', 'Ü', 'ō', 'ñ', 'ý', 'á', 'ĕ', 'Ç', 'è', 'É', 'â', 'ú', 'ó', 'í', 'ê', 'ï', 'Ö', 'ä', 'À', 'ž', 'û']\n\nfor file in os.listdir(root_dir):\n\tif file.endswith(\".m3u8\"):\n\t\twith open(file) as main:\n\t\t\tif not os.path.exists('cleaned'):\n\t\t\t\tos.makedirs('cleaned')\n\t\t\twrite_file = os.path.join(root_dir, \"cleaned\", file)\n\t\t\twith open(write_file, 'w') as new_main:\n\t\t\t\tinput_data = main.read()\n\t\t\t\tfor i in range(0, len(double_byte)):\n\t\t\t\t\tinput_data = input_data.replace(double_byte[i], single_byte[i])\n\t\t\t\tnew_main.write(input_data)","sub_path":"fix_char_windows.py","file_name":"fix_char_windows.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"339971641","text":"# 544. Output Contest Matches\nclass Solution:\n def findContestMatch(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n def build(n, teams):\n if n == 1: return teams[0]\n teamsNextRound = []\n for i in range(n//2):\n newTeam = '({},{})'.format(teams[i], teams[~i])\n teamsNextRound.append(newTeam)\n return build(n//2, teamsNextRound)\n return build(n, list(range(1,n+1)))\n","sub_path":"544/lc544.py","file_name":"lc544.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"25793247","text":"'''\r\nCreated on Mar 12, 2019\r\n\r\n@author: Dr.aarij\r\n'''\r\nfrom tkinter import Tk\r\nfrom com.ai.csp.gui.menuBoard import MenuBoard\r\nfrom com.ai.csp.gui.bottomRowBoard import BottomRowBoard\r\nimport threading\r\nimport time\r\nfrom com.ai.csp.inference.simpleInference import SimpleInference\r\nfrom com.ai.csp.inference.forwardCheckingInference import ForwardCheckingInference\r\nfrom com.ai.csp.strategy.backtrackingSearch import BactrackingSearch\r\nfrom com.ai.csp.gui.nQueenGameBoard import NQueenGameBoard\r\nfrom com.ai.csp.inference.arcConsistencyInference import ArcConsistencyInference\r\nfrom com.ai.csp.gui.cspGameBoard import CSPGameBoard\r\n\r\nclass GuiHandler(object):\r\n '''\r\n classdocs\r\n '''\r\n\r\n\r\n def __init__(self):\r\n self.root = Tk()\r\n\r\n \r\n def initializeCSPGUI(self,board):\r\n self.board = board\r\n self.board.grid(row=0,column=0)\r\n # player1 = PhotoImage(data=imagedata)\r\n # self.board.addpiece(\"player1\", player1, 0,0)\r\n \r\n self.frm = MenuBoard(self.root)\r\n self.frm.grid(row=0,column=1)\r\n \r\n self.frm2 = BottomRowBoard(self.root)\r\n self.frm2.grid(row=1,column=0,columnspan=2,sticky=\"w\",padx=15,pady=10)\r\n \r\n self.frm2.nextButton.bind('',self.nextHandler)\r\n self.frm2.playButton.bind('',self.playHandler)\r\n self.frm2.pauseButton.bind('',self.pauseHandler)\r\n \r\n \r\n self.nextFlag = False\r\n self.play = False\r\n self.pause = False\r\n \r\n self.condition = threading.Condition()\r\n \r\n self.started = False\r\n \r\n def on_closing(): \r\n # self.c1.shutdown_flag.set()\r\n self.root.destroy()\r\n \r\n self.root.protocol(\"WM_DELETE_WINDOW\", on_closing)\r\n self.root.mainloop()\r\n \r\n def fireChange(self,csp,assignment):\r\n with self.condition:\r\n if self.nextFlag or self.pause:\r\n self.condition.wait()\r\n elif self.play:\r\n time.sleep(float(self.frm.speedEntry.get()))\r\n print(assignment)\r\n self.board.handleFireChange(csp,assignment)\r\n \r\n def startIt(self):\r\n self.started = True\r\n variableOrdering = False\r\n valueOrdering = False\r\n \r\n \r\n if self.frm.ordering.get() == 2:\r\n variableOrdering = True\r\n elif self.frm.ordering.get() == 3:\r\n variableOrdering = True\r\n valueOrdering = True\r\n \r\n if self.frm.filtering.get() == 1:\r\n self.inPro = SimpleInference()\r\n elif self.frm.filtering.get() == 2:\r\n self.inPro = ForwardCheckingInference()\r\n elif self.frm.filtering.get() == 3:\r\n self.inPro = ArcConsistencyInference()\r\n \r\n self.csp = self.board.createCSP()\r\n self.bts = BactrackingSearch(self.inPro,[self],variableOrdering,valueOrdering)\r\n \r\n self.c1 = threading.Thread(name='c1', target=self.bts.solve, args=(self.csp,))\r\n self.c1.start()\r\n \r\n def nextHandler(self,_):\r\n self.nextFlag = True\r\n if not self.started: \r\n self.startIt()\r\n if self.pause:\r\n self.pause = False \r\n with self.condition:\r\n self.condition.notifyAll()\r\n \r\n def playHandler(self,_):\r\n with self.condition:\r\n self.play = True\r\n \r\n if not self.started: \r\n self.startIt()\r\n if self.pause:\r\n self.pause = False\r\n self.condition.notifyAll() \r\n if self.nextFlag:\r\n self.nextFlag = False\r\n self.condition.notifyAll() \r\n\r\n def pauseHandler(self,_):\r\n self.pause = True\r\n self.play = False\r\n self.nextFlag = False\r\n \r\nif __name__ == \"__main__\":\r\n bd = GuiHandler()\r\n# csp = NQueenGameBoard(bd.root)\r\n csp = CSPGameBoard(bd.root)\r\n bd.initializeCSPGUI(csp)\r\n ","sub_path":"NewCSP/com/ai/csp/gui/guiHandler.py","file_name":"guiHandler.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"546240085","text":"\n#1 -)SAY \"HELLO, WORLD!\" WITH PYTHON\n\na = \"Hello, World!\"\nprint(a)\n\n#2 -)PYTHON IF - ELSE\n\n# !/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# For all condition writing if or elif\n\nif __name__ == '__main__':\n n = int(input().strip())\n if n % 2 == 1:\n print(\"Weird\")\n elif n % 2 == 0 and 2 <= n <= 5:\n print(\"Not Weird\")\n elif n % 2 == 0 and 6 <= n <= 20:\n print(\"Weird\")\n elif n % 2 == 0 and n > 20:\n print(\"Not Weird\")\n\n#3 -)ARITHMETIC OPERATORS\n\n# Take input and implement arithmetic operators\nif __name__ == '__main__':\n a = int(input())\n b = int(input())\n line1 = a + b\n line2 = a - b\n line3 = a * b\n print(line1, line2, line3, sep=\"\\n\")\n\n#4 -)PYTHON: DIVISION\n# take the inputs and divide with floatdivision (/) and integerdivision (//)\n\nif __name__ == '__main__':\n a = int(input())\n b = int(input())\n intdivision = a // b\n floatdivision = a / b\n\n print(intdivision, floatdivision, sep='\\n')\n\n#5 -)LOOPS\n# Take the input and up to input,print the each number square\nif __name__ == '__main__':\n n = int(input())\n for i in range(n):\n print(i ** 2)\n\n#6 -)WRITE A FUNCTION\n\n# this function first checks whether input number is divisible by 4 if not Return false\n# If it is then try to divide it with 100\n# if it is both divisible to 400 and 100 and it returns True, if only divisibleto 100 return false\n\n\ndef is_leap(year):\n if year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n return True\n else:\n return False\n\n else:\n return True\n\n else:\n return False\n\n\nyear = int(input())\nprint(is_leap(year))\n\n#7 -)PRINT FUNCTION\n\n# take a number as a input.Then create list by list compherension add 1 to each number.\n# Then print them by using end method = \"\"\nif __name__ == '__main__':\n n = int(input())\n n = [n + 1 for n in range(n)]\n for i in n:\n print(i, end=\"\")\n\n","sub_path":"hw1scripts/Introduction.py","file_name":"Introduction.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"641739470","text":"from __future__ import print_function\nimport numpy as np\n\nimport astropy.time\n\nfrom legacypipe.image import LegacySurveyImage, CP_DQ_BITS\n\n'''\nCode specific to images from the Dark Energy Camera (DECam).\n'''\n\nclass DecamImage(LegacySurveyImage):\n '''\n A LegacySurveyImage subclass to handle images from the Dark Energy\n Camera, DECam, on the Blanco telescope.\n '''\n def __init__(self, survey, t):\n super(DecamImage, self).__init__(survey, t)\n # Adjust zeropoint for exposure time\n self.ccdzpt += 2.5 * np.log10(self.exptime)\n\n def read_invvar(self, **kwargs):\n return self.read_invvar_clipped(**kwargs)\n\n glowmjd = astropy.time.Time('2014-08-01').utc.mjd\n\n def get_good_image_subregion(self):\n x0,x1,y0,y1 = None,None,None,None\n\n # Handle 'glowing' edges in DES r-band images\n # aww yeah\n if self.band == 'r' and (\n ('DES' in self.imgfn) or ('COSMOS' in self.imgfn) or\n (self.mjdobs < DecamImage.glowmjd)):\n # Northern chips: drop 100 pix off the bottom\n if 'N' in self.ccdname:\n print('Clipping bottom part of northern DES r-band chip')\n y0 = 100\n else:\n # Southern chips: drop 100 pix off the top\n print('Clipping top part of southern DES r-band chip')\n y1 = self.height - 100\n\n # Clip the bad half of chip S7.\n # The left half is OK.\n if self.ccdname == 'S7':\n print('Clipping the right half of chip S7')\n x1 = 1023\n\n return x0,x1,y0,y1\n\n def remap_dq(self, dq, hdr):\n '''\n Called by get_tractor_image() to map the results from read_dq\n into a bitmask.\n '''\n from distutils.version import StrictVersion\n # The format of the DQ maps changed as of version 3.5.0 of the\n # Community Pipeline. Handle that here...\n primhdr = self.read_primary_header(self.dqfn)\n plver = primhdr['PLVER'].strip()\n plver = plver.replace('V','')\n plver = plver.replace('DES ', '')\n plver = plver.replace('+1', 'a1')\n if StrictVersion(plver) >= StrictVersion('3.5.0'):\n dq = self.remap_dq_cp_codes(dq, hdr)\n else:\n from legacypipe.image import CP_DQ_BITS\n dq = dq.astype(np.int16)\n # Un-set the SATUR flag for pixels that also have BADPIX set.\n bothbits = CP_DQ_BITS['badpix'] | CP_DQ_BITS['satur']\n I = np.flatnonzero((dq & bothbits) == bothbits)\n if len(I):\n print('Warning: un-setting SATUR for', len(I),\n 'pixels with SATUR and BADPIX set.')\n dq.flat[I] &= ~CP_DQ_BITS['satur']\n assert(np.all((dq & bothbits) != bothbits))\n return dq\n","sub_path":"py/legacypipe/decam.py","file_name":"decam.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124969193","text":"from djblets.webapi.errors import WebAPIError\n\n\n#\n# Standard error messages\n#\nUNSPECIFIED_DIFF_REVISION = WebAPIError(\n 200,\n 'Diff revision not specified.',\n http_status=400) # 400 Bad Request\n\nINVALID_DIFF_REVISION = WebAPIError(\n 201,\n 'Invalid diff revision.',\n http_status=404) # 404 Not Found\n\nINVALID_ACTION = WebAPIError(\n 202,\n 'Invalid action specified.',\n http_status=400) # 400 Bad Request\n\nINVALID_CHANGE_NUMBER = WebAPIError(\n 203,\n 'The commit ID specified could not be found.',\n http_status=404) # 404 Not Found\n\nCHANGE_NUMBER_IN_USE = WebAPIError(\n 204,\n 'The commit ID specified has already been used.',\n http_status=409) # 409 Conflict\n\nMISSING_REPOSITORY = WebAPIError(\n 205,\n 'There was no repository found at the specified path.',\n http_status=400) # 400 Bad Request\n\nINVALID_REPOSITORY = WebAPIError(\n 206,\n 'The repository path specified is not in the list of known repositories.',\n http_status=400) # 400 Bad Request\n\nREPO_FILE_NOT_FOUND = WebAPIError(\n 207,\n 'The file was not found in the repository.',\n http_status=400) # 400 Bad Request\n\nINVALID_USER = WebAPIError(\n 208,\n 'User does not exist.',\n http_status=400) # 400 Bad Request\n\nREPO_NOT_IMPLEMENTED = WebAPIError(\n 209,\n 'The specified repository is not able to perform this action.',\n http_status=501) # 501 Not Implemented\n\nREPO_INFO_ERROR = WebAPIError(\n 210,\n 'There was an error fetching extended information for this repository.',\n http_status=500) # 500 Internal Server Error\n\nNOTHING_TO_PUBLISH = WebAPIError(\n 211,\n 'You attempted to publish a review request without any modifications.',\n http_status=400) # 400 Bad Request\n\nEMPTY_CHANGESET = WebAPIError(\n 212,\n 'The commit ID specified represents an empty changeset.',\n http_status=400) # 400 Bad Request\n\nSERVER_CONFIG_ERROR = WebAPIError(\n 213,\n 'There was an error storing configuration on the server.',\n http_status=500) # 500 Internal Server Error\n\nBAD_HOST_KEY = WebAPIError(\n 214,\n 'The SSH key on the host does not match the stored key.',\n http_status=403) # 403 Forbidden\n\nUNVERIFIED_HOST_KEY = WebAPIError(\n 215,\n 'The SSH key on the host is unverified.',\n http_status=403) # 403 Forbidden\n\nUNVERIFIED_HOST_CERT = WebAPIError(\n 216,\n 'The HTTPS certificate on the host is unverified.',\n http_status=403) # 403 Forbidden\n\nMISSING_USER_KEY = WebAPIError(\n 217,\n 'A public SSH key was requested, but no SSH key was available to send.',\n http_status=403) # 403 Forbidden\n\nREPO_AUTHENTICATION_ERROR = WebAPIError(\n 218,\n 'Unable to authenticate with the repository using the provided '\n 'credentials.',\n http_status=403) # 403 Forbidden\n\nDIFF_EMPTY = WebAPIError(\n 219,\n 'The specified diff file is empty.',\n http_status=400) # 400 Bad Request\n\nDIFF_TOO_BIG = WebAPIError(\n 220,\n 'The specified diff file is too large.',\n http_status=400) # 400 Bad Request\n\nFILE_RETRIEVAL_ERROR = WebAPIError(\n 221,\n 'There was an error fetching a source file.',\n http_status=500) # 500 Internal Server Error\n\nHOSTINGSVC_AUTH_ERROR = WebAPIError(\n 222,\n 'There was an error authorizing with a service.',\n http_status=403) # 403 Forbidden\n\nGROUP_ALREADY_EXISTS = WebAPIError(\n 223,\n 'A group with this name already exists.',\n http_status=409) # 409 Conflict\n\nDIFF_PARSE_ERROR = WebAPIError(\n 224,\n 'The specified diff file could not be parsed.',\n http_status=400) # 400 Bad Request\n\nPUBLISH_ERROR = WebAPIError(\n 225,\n 'An error occurred during publishing.',\n http_status=500) # 500 Internal Server Error\n\nUSER_QUERY_ERROR = WebAPIError(\n 226,\n 'An error occurred querying the user list.',\n http_status=500) # 500 Internal Server Error\n\nCOMMIT_ID_ALREADY_EXISTS = WebAPIError(\n 227,\n 'Review request with this commit ID already exists in the repository.',\n http_status=409) # 409 Conflict\n\nTOKEN_GENERATION_FAILED = WebAPIError(\n 228,\n 'There was an error generating the API token. Please try again.',\n http_status=500) # 500 Internal Server Error.\n\nREPOSITORY_ALREADY_EXISTS = WebAPIError(\n 229,\n 'A repository with this name already exists.',\n http_status=409) # 409 Conflict\n\nCLOSE_ERROR = WebAPIError(\n 230,\n 'An error occurred while closing the review request.',\n http_status=500) # 500 Internal Server Error\n\nREOPEN_ERROR = WebAPIError(\n 231,\n 'An error occurred while reopening the review request.',\n http_status=500) # 500 Internal Server Error\n\nREVOKE_SHIP_IT_ERROR = WebAPIError(\n 232,\n 'An error occurred while revoking the Ship It for a review.',\n http_status=500) # 500 Internal Server Error\n\nREAD_ONLY_ERROR = WebAPIError(\n 233,\n 'The site is currently in read-only mode.',\n http_status=503) # 503 Service Unavailable Error\n\nINVALID_GROUP = WebAPIError(\n 234,\n 'Group does not exist.',\n http_status=400) # 400 Bad Request\n","sub_path":"reviewboard/webapi/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":5023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"355861288","text":"#!/usr/bin/python3\n# script to export fontbakery checks for review\n# adapted from https://github.com/googlefonts/fontbakery/issues/2039\n\nimport pkgutil\n\nfrom fontbakery import profiles\nfrom fontbakery.callable import FontBakeryCheck\n\nchecks = []\n\nfor importer, modname, ispkg in pkgutil.iter_modules(profiles.__path__):\n exec('from fontbakery.profiles import ' + modname)\n exec('module = ' + modname)\n for attr_name in dir(module):\n attr = getattr(module, attr_name)\n if isinstance(attr, FontBakeryCheck):\n try:\n rationale = f\"\\n## rationale:\\n\\t{attr.rationale}\\n\"\n except:\n rationale = \"\"\n checks.append((attr.id, attr.__doc__, rationale))\n\nchecks.sort()\n\nfor check_id, doc, rationale in checks:\n print(f'# {check_id}\\n{doc.strip()}{rationale}\\n')\n\n\n","sub_path":"checklist.py","file_name":"checklist.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474348477","text":"import time\n# define the price dictionary for each different day\n# [first hour,Amount,Subsequent Minute,Subsequent Amount,Exit mins free,Tolerate 5 min,Max charge Amount]\nprice_dict = {\n 1:[180,3,60,1,15,5,20],\n 2:[180,3,60,1,15,5,20],\n 3:[180,0,30,1,15,5,20], # requirement change as first 3 hour cost 0 RM \n 4:[180,3,60,1,15,5,20],\n 5:[180,3,60,1,15,5,20],\n 6:[120,5,60,2,15,5,40],\n 7:[120,5,60,2,15,5,40],\n}\nenter_count = 1\n\ndef day_input_eva():\n \"this function is mainly for validating user's input on day chosen \"\n global enter_count\n day_list = list(range(1,8))\n while True: \n try:\n day = int(input(str(enter_count)+\".Enter the day number between 1-7:\")) # string\n if day != int and day not in day_list: # condition on type \n print(\"input is out of scope,pls enter again\")\n time.sleep(1.5)\n enter_count += 1 \n continue\n else:\n enter_count += 1\n break\n except Exception:\n print(\"pls enter correct integer format number,enter again\")\n time.sleep(1.5)\n enter_count += 1 \n continue\n return day\n\ndef time_input_eva():\n \"this function is mainly for validating user's input on duration chosen\"\n while True:\n try:\n duration = input(\"Enter the Duration:\")\n hour = int(duration.split(\":\")[0]) # slice out the hour part\n minute = int(duration.split(\":\")[1]) # slice out the minute part\n if type(hour) != int or type(minute) != int : # condition on type \n print(\"pls enter correct (Hours:Minutes HH:MM format) format.....\")\n time.sleep(1.5)\n continue\n else:\n # in case if user enter minute value > 60 \n if (minute//60) != 0: \n hour += (minute//60) # add to hour \n minute %= 60 # reduce the minute\n total_minutes = hour * 60 + minute # conver the HH:MM format to minutes\n break\n except (IndexError,ValueError):\n print(\"pls enter correct (Hours:Minutes HH:MM format) format......\")\n time.sleep(1.5)\n continue\n return hour,minute,total_minutes\n\ndef week(day,hour,minute,total_minutes): # enter the how many day are considered as weekday,return as tuple\n \"outer function that return the amount value\"\n fir_time_free,fir_charge,sub_min,sub_charge,min_free,tol_min,max_charge = price_dict[day] #one line multiple assignment\n amount = 0 # initialize the local variable\n # 3 layers nested if else statement\n if 0 <= total_minutes <= min_free:#first 15 min free\n pass\n elif min_free < total_minutes <= fir_time_free: # first 3 hours free 3:05 = 180 minutes\n amount = fir_charge\n else:# time is 3 hours above and amount charge based on minute unit\n minute = total_minutes - fir_time_free\n amount = fir_charge # add from fir_charge\n print(minute,amount,total_minutes)\n while minute > tol_min:\n amount += sub_charge # increase the subsequent charge each iteration\n minute -= sub_min # substract the subsequent minute each iteration\n if amount > max_charge:\n amount = max_charge # reassignment if exceed the maximum charge\n return amount\n \n#below is the main function \nif __name__ == \"__main__\":\n while True:\n day = day_input_eva()\n hour,minute,total_minutes = time_input_eva()\n amount = week(day,hour,minute,total_minutes)\n print(f\"Total Minutes:{total_minutes}\\nDuration: {hour} Hours {minute} Minutes\\nNet Amount Needed To Paid: {amount} RM\\n\")\n time.sleep(0.5)","sub_path":"Python Script Quzzies/04.py","file_name":"04.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"146568021","text":"\"\"\"\npython操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。\n可从这里下载https://pypi.python.org/pypi。下面分别记录python读和写excel.\n\"\"\"\nimport xlrd, xlwt, hashlib\nimport re\nimport os\nfrom datetime import date, datetime\nimport json\nfrom flask_server.common import Spider_table,qcc_new,com_reserve\nfrom flask import current_app\n\ndef read_excel(user_id,trade):\n \"\"\"\n\n :param user_id: 工号\n :param trade: 液态\n :return:\n \"\"\"\n\n from company.manage import app\n # 打开文件\n files = r'D:\\bmd\\bmd_server\\src\\company\\flask_server\\files\\{}'.format(user_id)\n file_lt = os.listdir(files)\n\n # sheet的名称,行数,列数\n # print\n # sheet.name, sheet.nrows, sheet.ncols\n # 获取整行和整列的值(数组)\n m = 0\n n = 0\n s = 0\n lt = []\n for file in file_lt:\n if file == \"TEL\":\n pass\n else:\n file_path = files + r'\\{}'.format(file)\n workbook = xlrd.open_workbook(file_path)\n mark = str(trade)\n # 获取所有sheet\n sheet_name = workbook.sheet_names()[0]\n # 根据sheet索引或者名称获取sheet内容\n sheet = workbook.sheet_by_index(0) # sheet索引从0开始\n\n a = 1\n while True:\n try:\n rows = sheet.row_values(a)\n # print(rows)\n except Exception as e:\n print(e)\n break\n else:\n if len(rows) == 0:\n break\n else:\n companyName = rows[0]\n businessState = rows[1]\n legalMan = rows[2]\n registerMoney = rows[3]\n reg_time = rows[4]\n if type(rows[4]) == str:\n registerTime = rows[4]\n else:\n registerTime == str(datetime.datetime(*xlrd.xldate_as_tuple(rows[4], 0))).replace(' 00:00:00', '')\n companyProvince = rows[5]\n companyCity = rows[6]\n companyTel = str(rows[7]).replace(\".0\",\"\")\n imTel = rows[8]\n email = rows[9]\n tynum = str(rows[10]).replace(\".0\",\"\")\n nsnum = str(rows[11]).replace(\".0\", \"\")\n zch = str(rows[12]).replace(\".0\", \"\")\n zznum = str(rows[13]).replace(\".0\", \"\")\n cbrs = rows[14]\n companyType = rows[15]\n industry = rows[16]\n web = rows[17]\n registerAddress = rows[18]\n businessScope = rows[19]\n\n id = hashlib.md5(companyName.encode(encoding='utf-8')).hexdigest()\n\n data = {\n '_id': id,\n 'companyName': companyName,\n 'businessState': businessState,\n 'legalMan': legalMan,\n 'registerMoney': registerMoney,\n 'registerTime': registerTime,\n 'companyProvince': companyProvince,\n 'companyCity': companyCity,\n 'companyTel': companyTel,\n 'imTel': imTel,\n 'email': email,\n 'tynum': tynum,\n 'nsnum': nsnum,\n 'zch': zch,\n 'zznum': zznum,\n 'cbrs': cbrs,\n 'companyType': companyType,\n 'industry': industry,\n 'web': web,\n 'registerAddress': registerAddress,\n 'businessScope': businessScope,\n 'mark': mark\n }\n try:\n # 存入成功的数据 data\n Spider_table.insert(data)\n m += 1\n s += 1\n a += 1\n lt.append(data)\n except :\n # 失败的数据 data\n s += 1\n n += 1\n a += 1\n\n for file in file_lt:\n if file != \"TEL\":\n file_path = files + r'\\{}'.format(file)\n os.remove(file_path)\n\n # a: 总数, m:插入成功 n:失败\n current_app.logger.info(f'合计:上传数据总数{s}, 新上传数据m:{m}, 已有数据n:{n}')\n\n return s,m,n,lt\n\n\ndef tel_handler(data):\n \"\"\"\n 对公司的手机号去重存入数据库\n :return:\n \"\"\"\n sucuess_count = 0\n # result = Spider_table.find({'flag':{\"$exists\":False}})\n result = data\n for i in result:\n old_id = i['_id']\n tel = []\n companyTel = i['companyTel']\n if companyTel.isdigit() and len(companyTel) == 11 and companyTel[0] == '1':\n tel.append(companyTel)\n imTel = i['imTel']\n if len(imTel):\n for j in imTel.split(';'):\n if j.isdigit() and len(j) == 11 and j[0] == '1':\n tel.append(j)\n for k in tel:\n _id = hashlib.md5(k.encode(encoding='utf-8')).hexdigest()\n companyName = i['companyName']\n businessState = i['businessState']\n legalMan = i['legalMan']\n registerMoney = i['registerMoney']\n registerTime = i['registerTime']\n companyProvince = i['companyProvince']\n companyCity = i['companyCity']\n registerAddress = i['registerAddress']\n businessScope = i['businessScope']\n mark = i['mark']\n industry = i['industry']\n companyType = i['companyType']\n web = i['web']\n\n data = {\n \"_id\": _id,\n \"companyName\": companyName,\n \"companyTel\": k,\n \"businessState\": businessState,\n \"legalMan\": legalMan,\n \"registerMoney\": registerMoney,\n \"registerTime\": registerTime,\n \"companyProvince\": companyProvince,\n \"registerAddress\": registerAddress,\n \"businessScope\": businessScope,\n \"companyCity\": companyCity,\n \"industry\": industry,\n \"companyType\": companyType,\n \"web\": web,\n \"mark\": mark,\n }\n\n try:\n com_reserve.insert(data)\n sucuess_count += 1\n print(data)\n except Exception as e:\n\n print(e)\n\n\n Spider_table.find_one_and_update({\"_id\": old_id}, {\"$set\": {\"flag\": 1}})\n\n return sucuess_count\n\nif __name__ == '__main__':\n read_excel(user_id=\"102888\",trade=\"a\")\n","sub_path":"src/company/flask_server/process_/excel_push.py","file_name":"excel_push.py","file_ext":"py","file_size_in_byte":7218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"41786914","text":"from socket import *\nserverPort = 12000\nserverSocket = socket(AF_INET, SOCK_STREAM)\nserverSocket.bind(('', serverPort))\nserverSocket.listen(5)\nprint('The TCP server is ready to receive.')\n\nwhile True:\n connectionSocket, addr = serverSocket.accept()\n msg = connectionSocket.recv(1024).decode()\n newMsg = msg.upper()\n connectionSocket.send(newMsg.encode())\n connectionSocket.close()","sub_path":"Assignment0/basicSocketProgramming(server).py","file_name":"basicSocketProgramming(server).py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"158847129","text":"import torch\nimport numpy as np\n\ndef get_stats(dataset):\n\n \"\"\"\n Args\n ----\n dataset: torch Dataset\n \"\"\"\n\n if type(dataset.data) == np.ndarray:\n dset = torch.tensor(dataset.data, dtype=torch.float)\n else:\n dset = dataset.data\n\n n_channels = dset.shape[-1]\n\n if dset.max().item() == 255:\n dset.div_(255.0)\n\n d_mean = [round(dset[..., channel].mean().item(), 4) for channel in list(range(n_channels))]\n d_std = [round(dset[..., channel].std().item(), 4) for channel in list(range(n_channels))]\n\n return tuple(d_mean), tuple(d_std)\n\n","sub_path":"week9/utils/img_reg.py","file_name":"img_reg.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"87912743","text":"# Copyright 2015 Google 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 bookshelf import get_model, storage\nfrom flask import Blueprint, current_app, redirect, render_template, request, \\\n url_for\nimport cloud_vision, json\n\ncrud = Blueprint('crud', __name__)\n\n\n# [START upload_image_file]\ndef upload_image_file(file):\n \"\"\"\n Upload the user-uploaded file to Google Cloud Storage and retrieve its\n publicly-accessible URL.\n \"\"\"\n if not file:\n return None\n\n public_url = storage.upload_file(\n file.read(),\n file.filename,\n file.content_type\n )\n\n current_app.logger.info(\n \"Uploaded file %s as %s content type %s.\", file.filename, public_url, file.content_type)\n\n return public_url\n# [END upload_image_file]\n\n\n@crud.route(\"/\")\ndef list():\n current_app.logger.info(\"enter crud.list\")\n token = request.args.get('page_token', None)\n books, next_page_token = get_model().list(cursor=token)\n\n return render_template(\n \"list.html\",\n books=books,\n next_page_token=next_page_token)\n\n\n@crud.route('/')\ndef view(id):\n book = get_model().read(id)\n \n if book['cv_response']:\n cv_response = json.loads(book['cv_response'])\n attrib_info = cloud_vision.get_attributes_info(cv_response, \"BIRD\", True)\n book['birdInfo'] = attrib_info\n\n _book = dict(book)\n \n return render_template(\"view.html\", book=_book)\n\n\n@crud.route('/add', methods=['GET', 'POST'])\ndef add():\n if request.method == 'POST':\n data = request.form.to_dict(flat=True)\n\n # If an image was uploaded, update the data to point to the new image.\n # [START image_url]\n image_url = upload_image_file(request.files.get('image'))\n # [END image_url]\n \n current_app.logger.info(\"Image uploaded. URI: %s\" %image_url)\n _url = image_url.split( \"/\")\n gcfile = _url[len(_url) - 1]\n gcbucket = _url[len(_url) - 2]\n \n current_app.logger.info(\"Starting Cloud Vision gcfile : {} : gcbucket : {}\".format(gcfile, gcbucket))\n cv_response = cloud_vision.identify_image_attributes_gcs(gcfile, gcbucket)\n #TODO: check and remove json.dumps\n cv_response_pretty = json.dumps(cv_response, indent=4, sort_keys=True)\n # [START image_url2]\n if image_url:\n data['imageUrl'] = image_url\n # [END image_url2]\n if cv_response:\n data['cv_response'] = cv_response_pretty\n\n book = get_model().create(data)\n\n return redirect(url_for('.view', id=book['id']))\n \n\n return render_template(\"form.html\", action=\"Add\", book={})\n\n\n@crud.route('//edit', methods=['GET', 'POST'])\ndef edit(id):\n book = get_model().read(id)\n\n if request.method == 'POST':\n data = request.form.to_dict(flat=True)\n\n image_url = upload_image_file(request.files.get('image'))\n\n if image_url:\n data['imageUrl'] = image_url\n\n book = get_model().update(data, id)\n\n return redirect(url_for('.view', id=book['id']))\n\n return render_template(\"form.html\", action=\"Edit\", book=book)\n\n\n@crud.route('//delete')\ndef delete(id):\n get_model().delete(id)\n return redirect(url_for('.list'))\n\n\n","sub_path":"bookshelf/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"27948900","text":"import click\nimport json\nfrom pathlib import Path\nfrom tqdm import tqdm\n\nfrom SFD_pytorch import FaceDetector\nfrom utils import VideoFile\nfrom utils import iter_by_step\n\nconfigs = {\n 'detector_model': \"models/S3FD/s3fd_convert.pth\",\n 'detector_resize': 480,\n}\n\n\n@click.command()\n@click.argument(\n 'input_file',\n type=click.Path(exists=True, dir_okay=False, file_okay=True),\n)\n@click.argument('output_file', type=click.Path(), nargs=-1)\n@click.option('-n', '--every-n-frame', type=int, default=1)\ndef main(input_file, output_file, every_n_frame):\n input_file = Path(input_file)\n assert input_file.is_file()\n\n if output_file:\n output_file = Path(output_file[0])\n else:\n output_file = input_file.parent / \"detections.json\"\n\n if output_file.exists():\n raise FileExistsError(f\"Output file {output_file} already exists.\")\n\n detector = FaceDetector(configs['detector_model'])\n\n video = VideoFile(input_file)\n iter_frames = iter_by_step(enumerate(video), every_n_frame)\n progress_bar = tqdm(\n iter_frames, total=len(video) // every_n_frame, ascii=True)\n\n detections = dict()\n\n for index, frame in progress_bar:\n boxes = detector.detect(frame, resize_width=configs['detector_resize'])\n boxes = {x: boxes[x].tolist() for x in boxes.dtype.names}\n detections[index] = boxes\n\n with output_file.open('w') as f:\n json.dump(detections, f)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"detect_faces_in_video.py","file_name":"detect_faces_in_video.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"466228962","text":"#!/usr/bin/env python\n\nimport pythonpath; pythonpath\nfrom isrealdir import isrealdir\nfrom x19290 import find_walking\n\nfrom sys import path as pythonpath\nfrom os.path import dirname, join, realpath\nfrom argparse import ArgumentParser\nfrom os.path import curdir, join\nfrom os import chdir, listdir, remove\nfrom sys import argv\n\ndef main(args):\n p = ArgumentParser()\n p.add_argument('-m', '--module')\n p.add_argument('-r', '--remove', action='store_true')\n p.add_argument('-C', '--directory')\n p.add_argument('dirs', nargs='*')\n args = p.parse_args(args)\n wd = args.directory\n if wd:\n chdir(wd)\n action = remove if args.remove else _print\n m = args.module\n cond = __import__(m).cond if m else lambda name, path: name.endswith('~')\n for y in garbage(cond, args.dirs):\n action(y)\n\ndef _print(scalar):\n print(scalar)\n\ndef garbage(cond, dirs):\n if not dirs:\n prefix_len = len(join(curdir, ''))\n for y in find_walking(cond, curdir):\n yield y[prefix_len:]\n else:\n for dir in dirs:\n for y in find_walking(cond, dir):\n yield y\n\nif __name__ == '__main__':\n main(argv[1:])\n","sub_path":"garbage.py","file_name":"garbage.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"326110624","text":"from distutils.core import setup\nimport os, glob\n\n# list all documentation files that need to be included\ndocFiles = []\nfor (dirp, dirns, n) in os.walk('doc'):\n nr = [n1.replace('\\\\', '/') for n1 in n]\n dirn = dirp.replace('\\\\', '/')[4:]\n if len(dirn):\n dirn = dirn + '/'\n docFiles.extend( [dirn + n1r for n1r in nr if '.svn' not in dirp + '/' + n1r] )\n\ndestDir=\"orange/add-ons/Bioinformatics\"\n\nif __name__ == \"__main__\":\n setup(name = \"Orange-Bioinformatics\",\n version = \"1.0.0b\",\n description = \"Bioinformatics Add-On for Orange\",\n author = \"Bioinformatics Laboratory, FRI UL\",\n author_email = \"orange@fri.uni-lj.si\",\n maintainer = \"Ales Erjavec\",\n maintainer_email = \"ales.erjavec@fri.uni-lj.si\",\n url = \"http://www.ailab.si/obi\",\n download_url = \"http://orange.biolab.si/svn/orange/trunk/add-ons/Bioinformatics/\",\n packages = [ 'widgets', 'widgets.prototypes', 'doc', '.' ],\n package_data = {'widgets': ['icons/*.png'], 'doc': docFiles, '.':[\"addon.xml\"] },\n extra_path=(\"orange-bioinformatics\", destDir),\n license = \"GNU General Public License (GPL)\",\n keywords = [\"data mining\", \"machine learning\", \"artificial intelligence\",\n \"bioinformatics\", \"gene ontology\", \"KEGG\", \"expression profiles\"],\n classifiers = [\"Development Status :: 4 - Beta\",\n \"Programming Language :: Python\",\n \"License :: OSI Approved :: GNU General Public License (GPL)\",\n \"Operating System :: POSIX\",\n \"Operating System :: Microsoft :: Windows\",\n \"Topic :: Scientific/Engineering :: Visualization\",\n \"Topic :: Scientific/Engineering :: Bio-Informatics\",\n \"Intended Audience :: Education\",\n \"Intended Audience :: Science/Research\"\n ],\n long_description=\"\"\"\\\nOrange Bioinformatics\n=====================\n\nOrange Bioinformatics is an add-on for Orange data mining \nsoftware package. It extends Orange by providing common functionality\nfor basic tasks in bioinformatics.\n\n\"\"\")\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"309467037","text":"'''\n2D PSO.\nDraft 1 - psoDraft1.py\n\nCreated 6 Feb - 9 Feb 2016 (#772 - 775)\nUpdated 3 June 2016 \n\n'''\nimport time;\nimport random;\nimport math;\ntry:\n import tkinter as tk;\nexcept:\n import Tkinter as tk;\n\n'''\n1. Defining the function in question.\n'''\n\n#for particle chase mouse function\ndef motion(e):\n global mouseX, mouseY\n mouseX, mouseY = (((e.x-100)*(2*LIMX)/1200)-LIMX), (((e.y-50)*(2*LIMY)/600)-LIMY)\n\ndef function(a, b, n):\n #return -(1 + math.cos(12*((a**2+b**2)**0.5)))/((0.5*(a**2+b**2)) + 2) + 1\n #return ((a**2)+(b**2))**0.5\n return ((a-mouseX)**2 + (b-mouseY)**2)**0.5\n'''\n2. The main particle object.\n'''\n \nclass particles():\n\n #2A(1): Draws particles on canvas. Called each time particles are updated.\n\n def drawParticles(self, canvas):\n \n for i in range(self.n):\n stepX = 1200/(self.limX*2)\n stepY = 600/(self.limY*2)\n x = int((self.px[i]+self.limX)*stepX+100)\n y = int((self.py[i]+self.limY)*stepY+50)\n \n canvas.delete(self.markers[i])\n self.markers[i] = canvas.create_oval(x-4, y-4, x+5, y+5, fill=\"\", outline=\"black\")\n \n canvas.focus_set()\n\n #2A(2): Creates the particle id on canvas. Called once the tkinter GUI is opened.\n \n def drawParticlesINIT(self):\n \n for i in range(self.n):\n stepX = 1200/(self.limX*2)\n stepY = 600/(self.limY*2)\n x = int((self.px[i]+self.limX)*stepX+100)\n y = int((self.py[i]+self.limY)*stepY+50)\n \n self.markers.append(self.canvas.create_oval(x-4, y-4, x+5, y+5, fill = \"\", outline=\"black\"))\n \n canvas.focus_set() \n\n #2B: Initialisation function.\n def __init__(self, n, limX, limY, weight, cSoc, cCog, canvas):\n\n #object parameters\n self.n = n;\n self.isMoving = 0;\n self.canvas = canvas\n self.cSoc = []\n self.cCog = []\n self.w = []\n\n self.limX = limX \n self.limY = limY\n \n self.functionN = 1;\n self.iteration = 0;\n\n #object dynamic values\n \n self.vx = []#velocity\n self.vy = []\n self.px = []#position\n self.py = []\n\n self.markers = [] \n \n self.gbest = 10000000\n self.gbestXPos = 5\n self.gbestYPos = 5\n self.pbestXPos = []\n self.pbestYPos = []\n self.pbest = []\n\n #other object attributes / statistics\n\n self.constancy = 0;\n self.prevBest = 0;\n\n self.distance = []\n self.distanceMarker = []\n \n for i in range(n):\n #initialise the velocities - consider using other methods - play around!\n self.vx.append(random.random()*10-5);\n self.vy.append(random.random()*10-5);\n \n self.pbest.append(10000000);\n self.pbestXPos.append(5);\n self.pbestYPos.append(5);\n self.w.append(weight);\n self.cSoc.append(cSoc);\n self.cCog.append(cCog);\n self.distance.append(0);\n self.distanceMarker.append(0);\n\n for i in range(n):\n self.px.append(random.random()*2*limX - limX)\n self.py.append(random.random()*2*limY - limY)\n\n self.drawParticlesINIT()\n \n \n \n def update(self):\n vx = self.vx\n vy = self.vy\n cSoc = self.cSoc\n cCog = self.cCog\n px = self.px\n py = self.py\n w = self.w\n gbest = self.gbest\n pbest = self.pbest\n gbestXPos = self.gbestXPos\n gbestYPos = self.gbestYPos\n pbestXPos = self.pbestXPos\n pbestYPos = self.pbestYPos\n distance = self.distance\n\n self.gbest = function(self.gbestXPos, self.gbestYPos, 0) #dynamic function\n \n maxDistance = 0\n self.iteration += 1\n \n for i in range(self.n):\n r1 = random.random()\n r2 = random.random() \n \n position = function(px[i], py[i], self.functionN)\n\n #use self. when updating, variable name alone when retrieving values.\n #update the best positions.\n if(position < gbest):\n self.gbestXPos = px[i]\n self.gbestYPos = py[i]\n self.gbest = position\n if(position < pbest[i]):\n self.pbest[i] = position\n self.pbestXPos[i] = px[i]\n self.pbestYPos[i] = py[i]\n \n vx[i] = w[i]*vx[i] + cSoc[i]*r1*(gbestXPos - px[i]) + cCog[i]*r2*(pbestXPos[i] - px[i])\n vy[i] = w[i]*vy[i] + cSoc[i]*r1*(gbestYPos - py[i]) + cCog[i]*r2*(pbestYPos[i] - py[i])\n \n tx = (px[i] + vx[i])\n ty = (py[i] + vy[i])\n distance[i] += (vx[i]**2+vy[i]**2)**(0.5)\n if(distance[i] > maxDistance):\n maxDistance = distance[i]\n graphY = int(GRAPH_HEIGHT - (distance[i]/maxDistance) * GRAPH_HEIGHT)\n graphX = int((i/self.n)*GRAPH_WIDTH)+6\n graphCanvas.delete(self.distanceMarker[i])\n self.distanceMarker[i] = graphCanvas.create_rectangle(graphX, graphY, graphX+1, GRAPH_HEIGHT-2, outline=\"red\")\n \n \n if(tx > 0): \n px[i] = min(tx, self.limX)\n else:\n px[i] = max(tx, -self.limX)\n \n if(ty > 0): \n py[i] = min(ty, self.limY)\n else:\n py[i] = max(ty, -self.limY)\n #print(gbest)\n #print(px[i], py[i])\n \n self.drawParticles(self.canvas)\n\n def printResults(self):\n #find the modal position\n #or just output gbest!\n global PARAMETERS\n\n foo = str(round(self.gbest, ROUNDING))\n bar = str(round(self.gbestXPos, ROUNDING))\n baz = str(round(self.gbestYPos, ROUNDING))\n if bar == \"-0.0\":\n bar = \"0.0\"\n if baz == \"-0.0\":\n baz = \"0.0\"\n \n print(foo, \" is found at \", bar, \",\", baz)\n\n self.canvas.itemconfig(LABELS[4], text = str(self.iteration))\n self.canvas.itemconfig(LABELS[5], text = str(foo))\n self.canvas.itemconfig(LABELS[6], text = str(bar))\n self.canvas.itemconfig(LABELS[7], text = str(baz))\n self.canvas.itemconfig(LABELS[8], text = str(mouseX))\n self.canvas.itemconfig(LABELS[9], text = str(mouseY))\n self.canvas.itemconfig(LABELS[10], text = \"Swarming...\")\n\n #self.canvas.itemconfig(LABELS[0], text=\"asdf\")\n return round(self.gbest, ROUNDING)\n\n def finalResults(self, mode):\n #after auto-stop\n self.canvas.itemconfig(LABELS[10], text = \"Stopped\")\n if(mode == -1):\n print(\"Function has stopped automatically!\")\n if(mode == 0):\n print(\"Function stopped by user!\")\n print(\"===================================\")\n print(\"Gloabl Best: \", round(self.gbest, ROUNDING))\n print(\"XPOS of Best:\", round(self.gbestXPos, ROUNDING))\n print(\"YPOS of Best:\", round(self.gbestYPos, ROUNDING))\n print(\"===================================\")\n print(\"\")\n print(\"\")\n print(\"\")\n \n def iterate(self):\n if self.isMoving == 1:\n x = self.printResults()\n if(self.prevBest == x):\n self.constancy += 1\n self.prevBest = x\n if(self.constancy > LIMIT):\n self.isMoving = -1\n self.update()\n root.after(DELAY, self.iterate)\n else:\n if self.isMoving == -1:\n self.finalResults(-1)\n else:\n self.finalResults(0)\n\n def start(self, e):\n self.isMoving = 1\n self.iterate()\n \n def stop(self, e):\n self.isMoving = 0\n self.printResults()\n \n'''\n3. GUI Elements, Initialisation\n'''\n\n#3.1 Distance graph\n#done first, so focus will not interfere with main window.\ngraph = tk.Tk()\ngraph.title(\"Distance\")\ngraph.geometry('+2000+100')\ngraph.resizable(False, False)\ngraphCanvas = tk.Canvas(graph, width=200, height = 200)\ngraphCanvas.create_rectangle(3, 0, 5, 200, fill=\"black\")\ngraphCanvas.create_rectangle(3, 198, 200, 200, fill=\"black\")\ngraphCanvas.pack()\n\n#3.2 Root Window\nroot = tk.Tk()\nroot.title(\"PSO\")\nroot.geometry('+10+10')\n\nroot.resizable(False,False)\n\n#3.3 Canvas object with grid\ncanvas = tk.Canvas(root, width = 1500, height = 700)\ncanvas.create_rectangle(100, 348, 1300, 352, fill = \"black\")\ncanvas.create_rectangle(698, 50, 702, 650, fill = \"black\")\n\ncanvas.create_rectangle(99, 50, 100, 650, fill = \"green\")\ncanvas.create_rectangle(1299, 50, 1300, 650, fill = \"green\")\n\ncanvas.create_rectangle(100, 49, 1300, 50, fill = \"green\")\ncanvas.create_rectangle(100, 649, 1300, 650, fill = \"green\")\n\nINF = 9223372036854775000\n\n#3.4 functional constants\nDELAY = 100;\nROUNDING = 4;\nLIMIT = 50;\nGRAPH_HEIGHT = 200\nGRAPH_WIDTH = 200\n\n#3.5 particle spread parameters\nN = 50\nLIMX = 5\nLIMY = 5\nWEIGHT = 0.05\nCSOC = 4.0\nCCOG = 1.5\n\n#3.6 other globals\nmouseX = 0\nmouseY = 0\nparaLabel_one = [\"N = \", \"Weight = \", \"csoc = \", \"ccog = \"]\nparaLabel_two = [\"iter # = \", \"gbest = \", \"gbestX = \", \"gbestY = \", \"mouseX = \", \"mouseY = \"]\nPARAMETERS = [str(N), str(WEIGHT), str(CSOC), str(CCOG), str(0), str(INF), str(5), str(5), mouseX, mouseY, \"\"]\n\n#3.7 Print label on GUI\ncanvas.create_rectangle(1310, 90, 1490, 610, fill=\"#0F0F0F\")\n\ncanvas.create_rectangle(1310, 50, 1490, 90, fill=\"#1A1A1A\")\ncanvas.create_rectangle(1310, 50, 1490, 52, fill=\"#01A05A\", outline = \"#01A05A\")\ncanvas.create_text(1320, 60, text=\"Swarm Parameters:\", anchor = \"nw\", fill=\"#BEBEBE\", font=(\"Source Sans Pro\", 14))\n\ncanvas.create_rectangle(1310, 240, 1490, 280, fill=\"#1A1A1A\")\ncanvas.create_rectangle(1310, 240, 1490, 242, fill=\"#3E90BD\", outline = \"#3E90BD\")\ncanvas.create_text(1320, 250, text=\"Swarm Results:\", anchor = \"nw\", fill=\"#BEBEBE\", font=(\"Source Sans Pro\", 14))\n\nLABELS = []\nfor i in range(4):\n canvas.create_text(1320, i*35+100, text=paraLabel_one[i], anchor = \"nw\", fill = \"#FFFFFF\", font=(\"Consolas\",14))\n canvas.create_text(1320, (i+4)*35+150, text=paraLabel_two[i], anchor = \"nw\", fill = \"#FFFFFF\", font=(\"Consolas\",14))\n LABELS.append(canvas.create_text(1420, i*35+100, text=PARAMETERS[i], anchor = \"nw\", fill = \"#FFFFFF\", font=(\"Consolas\",14)))\ncanvas.create_text(1320, (4+4)*35+150, text=paraLabel_two[4], anchor = \"nw\", fill = \"#FFFFFF\", font=(\"Consolas\",14))\ncanvas.create_text(1320, (5+4)*35+150, text=paraLabel_two[5], anchor = \"nw\", fill = \"#FFFFFF\", font=(\"Consolas\",14))\n\nfor i in range(6):\n LABELS.append(canvas.create_text(1420, (i+4)*35+150, text=PARAMETERS[i+4], anchor = \"nw\", fill = \"#FFFFFF\", font=(\"Consolas\",14)))\nLABELS.append(canvas.create_text(1320, (10)*35+150, text=PARAMETERS[8], anchor = \"nw\", fill = \"#FF6607\", font=(\"Consolas\",14))) \n\ncanvas.pack()\n\n#3.8 Create Particle Object, key bindings\nmyParticles = particles(N, LIMX, LIMY, WEIGHT, CSOC, CCOG, canvas)\nroot.bind('', myParticles.start)\nroot.bind('', myParticles.stop)\nroot.bind('', motion)\n\nroot.focus_set()\nroot.mainloop();\n\n\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"71957524","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val = 0, neighbors = None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n\"\"\"\n\nclass Solution:\n def cloneGraph(self, node: 'Node') -> 'Node':\n \n if not node: return\n \n ht = {node: Node(node.val)}\n queue = deque([node])\n \n while queue:\n currNode = queue.popleft()\n for neighbor in currNode.neighbors:\n if neighbor not in ht:\n ht[neighbor] = Node(neighbor.val)\n queue.append(neighbor)\n \n ht[currNode].neighbors.append(ht[neighbor])\n \n return ht[node]\n","sub_path":"graphs/clone-graph.py","file_name":"clone-graph.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"327230705","text":"# Copyright The OpenTelemetry 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\nfrom .protobuf.test_server_pb2 import Request\n\nCLIENT_ID = 1\n\n\ndef simple_method(stub, error=False):\n request = Request(\n client_id=CLIENT_ID, request_data=\"error\" if error else \"data\"\n )\n stub.SimpleMethod(request)\n\n\ndef simple_method_future(stub, error=False):\n request = Request(\n client_id=CLIENT_ID, request_data=\"error\" if error else \"data\"\n )\n return stub.SimpleMethod.future(request)\n\n\ndef client_streaming_method(stub, error=False):\n # create a generator\n def request_messages():\n for _ in range(5):\n request = Request(\n client_id=CLIENT_ID, request_data=\"error\" if error else \"data\"\n )\n yield request\n\n stub.ClientStreamingMethod(request_messages())\n\n\ndef server_streaming_method(stub, error=False):\n request = Request(\n client_id=CLIENT_ID, request_data=\"error\" if error else \"data\"\n )\n response_iterator = stub.ServerStreamingMethod(request)\n list(response_iterator)\n\n\ndef bidirectional_streaming_method(stub, error=False):\n def request_messages():\n for _ in range(5):\n request = Request(\n client_id=CLIENT_ID, request_data=\"error\" if error else \"data\"\n )\n yield request\n\n response_iterator = stub.BidirectionalStreamingMethod(request_messages())\n\n list(response_iterator)\n","sub_path":"instrumentation/opentelemetry-instrumentation-grpc/tests/_client.py","file_name":"_client.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"258230742","text":"salario = float(input('Qual o valor so salario : '))\nif salario <= 1250:\n novo=salario * 15 /100 + salario\nelse:\n novo=salario * 10 /100 + salario\n\nprint('Quem ganhava {:.2f} \\nComeça a ganhar {:.2f} '.format(salario, novo))\n\n\n\n\n","sub_path":"ex034.py","file_name":"ex034.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"478454425","text":"from ml import *\n\nINSTRUCTION_END_BLOCK = 1 << 0\nINSTRUCTION_START_BLOCK = 1 << 1\nINSTRUCTION_FORMAT_ARG_NEW_LINE = 1 << 2\nINSTRUCTION_FORMAT_EMPTY_LINE = 1 << 3\n\nclass InstructionFlags:\n def __init__(self, flags):\n self.Flags = flags\n self.EndBlock = bool(flags & INSTRUCTION_END_BLOCK)\n self.StartBlock = bool(flags & INSTRUCTION_START_BLOCK)\n self.ArgNewLine = bool(flags & INSTRUCTION_FORMAT_ARG_NEW_LINE)\n\nclass InstructionOperand:\n def __init__(self, operand, size):\n self.Operand = operand\n self.Size = size\n\nclass LabelEntry:\n def __init__(self, label, offset):\n self.Label = label # label name\n self.Offset = offset # label offset in instruction\n\nclass Instruction:\n def __init__(self, op = None, operand = None, flags = 0):\n self.OpCode = op\n self.Operand = operand if operand != None else []\n self.OperandFormat = None\n self.BranchTargets = []\n self.Flags = InstructionFlags(flags)\n self.Labels = []\n self.RefCount = 0\n self.Offset = -1\n self.Text = ''\n\nclass CodeBlock:\n def __init__(self, Offset = -1):\n self.Offset = Offset\n self.Instructions = []\n self.Parent = None\n self.CodeBlocks = []\n self.Name = None\n\n def AddBlock(self, block):\n self.CodeBlocks.append(block)\n\n def AddInstruction(self, instruction):\n self.Instructions.append(instruction)\n","sub_path":"Source/Hooks/EDAO/Decompiler/BaseType.py","file_name":"BaseType.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"490367960","text":"#!/usr/bin/env python3\nimport praw\nfrom bg3po_oauth import login\nimport re\nfrom datetime import datetime\nfrom html import unescape\n\nSUBREDDIT = \"boardgames\"\nPOST_BODY = \"/home/bg3po/bg3po-scripts/etc/bazaar_post_body.red\"\n\n\ndef get_month():\n month = datetime.now().strftime(\"%B\")\n return(month)\n\n\ndef get_body():\n f = open(POST_BODY)\n body = f.read()\n f.close()\n return body\n\n\ndef post_bazaar(reddit, month):\n title = month + \" Board Game Bazaar\"\n post_text = get_body()\n post = reddit.subreddit(SUBREDDIT).submit(title=title, selftext=post_text)\n return (post.id)\n\n\ndef change_sidebar(reddit, post_id, month):\n sr = reddit.subreddit(SUBREDDIT)\n sidebar = unescape(reddit.subreddit(SUBREDDIT).description)\n new_bazaar = r'['+month+' Bazaar](/'+post_id+')'\n new_sb = re.sub(r'\\[[a-zA-Z]+ Bazaar\\]\\(\\/[a-z0-9]+\\)', new_bazaar, sidebar, 1)\n reddit.subreddit(SUBREDDIT).mod.update(description=new_sb)\n\n\ndef main():\n month = get_month()\n reddit = login()\n post_id = post_bazaar(reddit, month)\n change_sidebar(reddit, post_id, month)\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/bazaar-autopost.py","file_name":"bazaar-autopost.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"639640720","text":"'''\nButton related implementations.\n'''\nimport logging\nimport os\nimport random\nimport re\n\nfrom posix_ipc import MessageQueue, O_CREAT\n\n\n_RE_HELMHOLTZ = re.compile('^([a-gA-G]#?)(`*)$')\n_note_map = {\n 'C': 0, 'C#': 1,\n 'D': 2, 'D#': 3,\n 'E': 4,\n 'F': 5, 'F#': 6,\n 'G': 7, 'G#': 8,\n 'A': 9, 'A#': 10,\n 'B': 11\n}\n\n_VIRTUAL = 'virtual'\n_IC2 = 'ic2'\n_KEY_MODE = os.getenv('BANDONEON_BUTTONS', _VIRTUAL)\n\n_SOUND_DIR = os.getenv('SOUND_DIRECTORY', 'sounds/transposed')\n\n_buttons = {}\n_socket = None\n\n\n# Prescan the sound dir to make a map of ISO note values to sound files\n# only take Pre1 sounds\n_file_list = os.listdir(_SOUND_DIR)\n_file_map = {\n note: [f for f in _file_list if note in f and 'Pre2' in f and f.startswith('K')]\n for note in [f'{n}{o}' for n in _note_map.keys() for o in range(7)]\n}\n\n\nclass InvalidNoteError(Exception):\n pass\n\n\nclass Note():\n '''\n A Note is a representation of a frequency, initiated with a\n helmholtz_value (eg. c#` indicates the MIDI note 61, or C3# or C4#\n '''\n\n def __init__(self, helmholtz_value):\n self.helmholtz_value = helmholtz_value\n\n m = _RE_HELMHOLTZ.search(helmholtz_value)\n if not m:\n raise InvalidNoteError(f'{helmholtz_value} failed to parse')\n note = m.group(1)\n octave_shift = m.group(2)\n if note[0].isupper():\n octave = 2\n else:\n octave = 3 + len(octave_shift)\n\n self.octave_value_yamaha = f'{note.upper()}{octave - 1}'\n self.octave_value = f'{note.upper()}{octave}'\n self.midi = 24 + _note_map[note.upper()] + 12 * octave\n\n def fname(self):\n file_ = random.choice(_file_map[self.octave_value])\n return os.path.join(_SOUND_DIR, file_)\n\n def __repr__(self):\n return f'[{self.midi}] {self.octave_value}'\n\n def __str__(self):\n return self.__repr__()\n\n\nclass Button():\n '''\n A button is one of the 72 keys on the bandoneon. Each button may have\n a different tone depending on whether the bandoneon is being opened or\n closed.\n\n note values are represented in Helmholtz Pitch notation:\n http://www.theoreticallycorrect.com/Helmholtz-Pitch-Numbering/\n\n We parse and store them out to Octave Numbering and MIDI notes.\n '''\n\n def __init__(self, key_number, draw_value, push_value):\n self.key_number = key_number\n self.draw_note = Note(draw_value)\n self.push_note = Note(push_value)\n\n def get_file(self, bellows_value):\n note = self.push_note if bellows_value >= 0 else self.draw_note\n logging.debug((\n f'button {self.key_number} on '\n f'{bellows_value}: {note.octave_value}'\n ))\n return note.fname()\n\n def __repr__(self):\n return (\n f'[{self.key_number}] {self.draw_note.octave_value}'\n f'/{self.push_note.octave_value}')\n\n def __str__(self):\n return self.__repr__()\n\n\ndef get_current_buttons_pushed(button_message):\n '''\n Given a , return the of currently pushed\n