diff --git "a/4317.jsonl" "b/4317.jsonl" new file mode 100644--- /dev/null +++ "b/4317.jsonl" @@ -0,0 +1,632 @@ +{"seq_id":"188839331","text":"from kivy.app import App\nfrom kivy.uix.relativelayout import RelativeLayout\nfrom kivy.config import Config\nfrom RiotAPI import RiotAPI as API\nimport RiotConsts as Consts\n\n\nclass StartScreen(RelativeLayout):\n\tdef get_current_game_data(self):\n\t\tname = self.ids[\"text_name\"]\n\t\tregion = self.ids[\"text_region\"]\n\t\tif region.text.lower() in Consts.REGIONS:\n\t\t\t#api key goes below in the quotes\n\t\t\tapi = API('', Consts.REGIONS[region.text.lower()])\n\t\t\tinfo = api.get_summoner_by_name(name.text.lower())\n\t\t\tif 'status' not in info:\n\t\t\t\tsummonerID = info['id']\n\t\t\t\t#self.ids[\"account_id\"].text = str(info['accountId'])\n\t\t\t\tmasteryInfo = api.get_champion_mastery_by_ID(summonerID)\n\t\t\t\thighestID = masteryInfo[0]['championId']\n\t\t\t\tself.ids[\"champion_name\"].text = api.get_champion_by_ID(highestID)['name']\n\t\t\t\tcurrentGameData = api.get_spectator_info(summonerID)\n\t\t\t\tif 'status' not in currentGameData:\n\t\t\t\t\tprint(currentGameData)\n\t\t\t\t\tfor x in range(0, len(currentGameData['participants'])):\n\n\t\t\t\t\t\t# get champion and playtime data\n\t\t\t\t\t\tplayerData = currentGameData['participants'][x]\n\t\t\t\t\t\tself.ids[\"player_\" + str(x + 1) + \"_champion\"].source = \"assets/loading/\" + api.get_champion_by_ID(playerData['championId'])['name'] + \".jpg\"\n\t\t\t\t\t\tself.ids[\"player_\" + str(x + 1) + \"_champion\"].size_hint = 1, 1\n\n\t\t\t\t\t\t# get summoner name\n\t\t\t\t\t\tself.ids[\"summoner_name_\" + str(x + 1)].text = playerData['summonerName']\n\n\t\t\t\t\t\t# get summoner spell data\n\t\t\t\t\t\tspell2 = api.get_spell_by_ID(playerData['spell2Id'])['name']\n\t\t\t\t\t\tspell1 = api.get_spell_by_ID(playerData['spell1Id'])['name']\n\t\t\t\telse:\n\t\t\t\t\t1 == 1\n\t\t\t\t\t#self.ids[\"no_game\"].text = \"You are not in game.\"\n\t\t\t\t\t#self.ids[\"my_champion\"].text = \"\"\n\t\t\t\t\t#self.ids[\"my_spells\"].text = \"\"\n\t\t\t\t\t#self.ids[\"my_keystone\"].text = \"\"\n\n\nclass StatCarryApp(App):\n\tdef on_start(self):\n\t\tself.title = 'StatCarry'\n\t\tself.icon = 'assets/app_logo.png'\n\n\tdef build(self):\n\t\tConfig.set('graphics', 'width', '770')\n\t\tConfig.set('graphics', 'height', '560')\n\t\treturn StartScreen()\n\nif __name__ == \"__main__\":\n\tStatCarryApp().run()\n","sub_path":"StatCarry.py","file_name":"StatCarry.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"513647960","text":"from unittest import TestCase\nimport sys\nimport os.path\nimport tempfile\n\nimport pexpect\n\n\nDATADIR = os.path.join(os.path.dirname(__file__), 'data')\nSIMPLE_PNG = os.path.join(DATADIR, 'simple.png')\nEXAMPLE_PNG = os.path.join(DATADIR, 'example.png')\nEXAMPLE_NOCURSOR_PNG = os.path.join(DATADIR, 'example_nocursor.png')\n\n\nclass TestVNCCapture(TestCase):\n server = None\n\n def setUp(self):\n self.tempfiles = []\n\n def tearDown(self):\n if self.server:\n self.server.terminate(force=True)\n\n for f in self.tempfiles:\n os.remove(f.name)\n\n def mktemp(self):\n f = tempfile.NamedTemporaryFile(suffix='.png')\n self.tempfiles.append(f)\n f.close()\n return f.name\n\n def run_server(self, server):\n cmd = '%s -rfbport 5910 -rfbwait 1000' % server\n self.server = pexpect.spawn(cmd, timeout=2)\n self.server.logfile_read = sys.stdout\n\n def run_vncdo(self, commands, exitcode=0):\n cmd = 'vncdo -s :10 ' + commands\n vnc = pexpect.spawn(cmd, logfile=sys.stdout, timeout=5)\n vnc.logfile_read = sys.stdout\n vnc.expect(pexpect.EOF)\n if vnc.isalive():\n vnc.wait()\n\n assert vnc.exitstatus == exitcode, vnc.exitstatus\n\n def assertFilesEqual(self, filename, othername):\n content = open(filename, 'rb').read()\n othercontent = open(othername, 'rb').read()\n\n assert content == othercontent\n\n def testCaptureExample(self):\n fname = self.mktemp()\n self.run_server('example')\n self.run_vncdo('move 150 100 capture %s' % fname)\n self.assertFilesEqual(fname, EXAMPLE_PNG)\n\n def testCaptureCapture(self):\n f1 = self.mktemp()\n f2 = self.mktemp()\n\n self.run_server('example')\n self.run_vncdo('move 150 100 capture %s capture %s' % (f1, f2))\n self.assertFilesEqual(f1, EXAMPLE_PNG)\n self.assertFilesEqual(f2, f1)\n\n def testCaptureNoCursor(self):\n fname = self.mktemp()\n self.run_server('example')\n self.run_vncdo('--nocursor move 150 100 pause 0.1 capture %s' % fname)\n self.assertFilesEqual(fname, EXAMPLE_NOCURSOR_PNG)\n\n def testCaptureLocalCursor(self):\n fname = self.mktemp()\n self.run_server('example')\n self.run_vncdo('--localcursor move 150 100 pause 0.1 capture %s' % fname)\n self.assertFilesEqual(fname, EXAMPLE_PNG)\n\n def testExpectExampleExactly(self):\n self.run_server('example')\n self.run_vncdo('move 150 100 pause 0.1 expect %s 0' % EXAMPLE_PNG)\n\n def testExpectExampleSloppy(self):\n self.run_server('example')\n self.run_vncdo('move 200 100 expect %s 25' % EXAMPLE_PNG)\n\n def testExpectFailsExample(self):\n self.run_server('example')\n try:\n self.run_vncdo('expect %s 0' % SIMPLE_PNG, exitcode=10)\n except pexpect.TIMEOUT:\n pass\n else:\n raise AssertionError('should timeout')\n","sub_path":"tests/functional/test_screen.py","file_name":"test_screen.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"397792318","text":"import logging\nimport html as html_parser\nimport re\n\n# Used to enable launch as a main\nimport os.path\nimport sys\n\nsys.path.insert(0, os.path.abspath('.'))\nfrom webmining.html5wrapper import HTML5Wrapper\nimport webmining.relevant_text_extractor as relevant_text_extractor\n\n\n__author__ = \"https://github.com/MinistereSupRecherche\"\n__email__ = \"github@recherche.gouv.fr\"\n__status__ = \"dev\"\n\n\nclass Website:\n def __init__(self):\n \"\"\"\n Initializes a website extractor.\n \"\"\"\n self.htmlwrapper = HTML5Wrapper()\n self.logger = logging.getLogger(\"webmining.Website\")\n\n def magnify(self, html):\n \"\"\"\n param: html: raw html\n returns: tuple(clean html, relevant text)\n \"\"\"\n # Try to get dom from html string\n try:\n dom = self.htmlwrapper.pq(html)\n except Exception as e:\n self.logger.warning(\"Impossible to magnify HTML\\n %s\" % str(e))\n return None, None\n\n # Converting html into \"clean\" and interesting text\n relevant_txt = self.extract_meaningful_text(dom)\n return dom, relevant_txt\n\n def extract_text(self, html):\n \"\"\"\n Transforms HTML into nice text.\n\n param: html: raw html\n :returns: text as a string\n \"\"\"\n try:\n dom = self.htmlwrapper.pq(html)\n return self.htmlwrapper.text(dom(\"body\"))\n except Exception as e:\n self.logger.warning(\"Impossible to extract text with parser, \"\n \"using dumb method.\\n %s\" % str(e))\n cleantxt = html_parser.unescape(html)\n cleantxt = re.sub(\"<.+?>\", \" \", cleantxt, flags=re.S)\n\n return cleantxt\n\n def extract_title(self, dom):\n \"\"\"\n Extract title from a webpage, if not found or error it will always return \"\"\n \"\"\"\n try:\n return self.htmlwrapper.text(dom(\"title\"))\n except Exception:\n return \"\"\n\n def extract_meaningful_text(self, dom):\n \"\"\"\n Extract meaningful content from an html page. Returns raw text.\n param: dom: the pq element\n \"\"\"\n try:\n return relevant_text_extractor.extract(dom)\n except Exception as e:\n # Extraction can fail when dom is too deep\n # We then try a dumb méthod with a regexp\n self.logger.warning(\"Impossible to extract meaningful text, using \"\n \"dumb method.\\n %s\" % str(e))\n return self.htmlwrapper.text(dom(\"body\"))\n","sub_path":"python/webmining-1.75/webmining/website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"491470856","text":"from Diffusion import *\n\n\ndef selectDegreeSeed(d_dict):\n # -- get the node with highest degree --\n mep = (-1, '-1')\n max_degree = -1\n while mep[1] == '-1':\n while max_degree == -1:\n for deg in list(d_dict.keys()):\n if int(deg) > max_degree:\n max_degree = int(deg)\n\n if max_degree == -1:\n return mep\n\n if d_dict[str(max_degree)] == set():\n del d_dict[str(max_degree)]\n max_degree = -1\n\n if d_dict[str(max_degree)] == set():\n del d_dict[str(max_degree)]\n max_degree = -1\n continue\n\n mep = choice(list(d_dict[str(max_degree)]))\n d_dict[str(max_degree)].remove(mep)\n\n return mep\n\n\nclass SeedSelectionHD:\n def __init__(self, g_dict, s_c_dict, prod_list):\n ### g_dict: (dict) the graph\n ### s_c_dict: (dict) the set of cost for seeds\n ### prod_list: (list) the set to record products [kk's profit, kk's cost, kk's price]\n ### num_node: (int) the number of nodes\n ### num_product: (int) the kinds of products\n self.graph_dict = g_dict\n self.seed_cost_dict = s_c_dict\n self.product_list = prod_list\n self.num_node = len(s_c_dict)\n self.num_product = len(prod_list)\n\n def constructDegreeDict(self, data_name):\n # -- display the degree and the nodes with the degree --\n ### d_dict: (dict) the degree and the nodes with the degree\n ### d_dict[deg]: (set) the set for deg-degree nodes\n d_dict = {}\n with open(IniGraph(data_name).data_degree_path) as f:\n for line in f:\n (i, deg) = line.split()\n if deg == '0':\n continue\n for k in range(self.num_product):\n if deg in d_dict:\n d_dict[deg].add((k, i))\n else:\n d_dict[deg] = {(k, i)}\n f.close()\n\n return d_dict\n\n def constructExpendDegreeDict(self):\n # -- display the degree and the nodes with the degree --\n ### d_dict: (dict) the degree and the nodes with the degree\n ### d_dict[deg]: (set) the set for deg-degree nodes\n d_dict = {}\n for i in self.graph_dict:\n i_set = {i}\n for ii in self.graph_dict[i]:\n if ii not in i_set:\n i_set.add(ii)\n for ii in self.graph_dict[i]:\n if ii in self.graph_dict:\n for iii in self.graph_dict[ii]:\n if iii not in i_set:\n i_set.add(iii)\n\n deg = str(len(i_set))\n for k in range(self.num_product):\n if deg in d_dict:\n d_dict[deg].add((k, i))\n else:\n d_dict[deg] = {(k, i)}\n\n return d_dict\n\n\nclass SeedSelectionHDPW:\n def __init__(self, g_dict, s_c_dict, prod_list, pw_list):\n ### g_dict: (dict) the graph\n ### s_c_dict: (dict) the set of cost for seeds\n ### prod_list: (list) the set to record products [kk's profit, kk's cost, kk's price]\n ### num_node: (int) the number of nodes\n ### num_product: (int) the kinds of products\n ### pw_list: (list) the product weight list\n self.graph_dict = g_dict\n self.seed_cost_dict = s_c_dict\n self.product_list = prod_list\n self.num_node = len(s_c_dict)\n self.num_product = len(prod_list)\n self.pw_list = pw_list\n\n def constructDegreeDict(self, data_name):\n # -- display the degree and the nodes with the degree --\n ### d_dict: (dict) the degree and the nodes with the degree\n ### d_dict[deg]: (set) the set for deg-degree nodes\n d_dict = {}\n with open(IniGraph(data_name).data_degree_path) as f:\n for line in f:\n (i, deg) = line.split()\n if deg == '0':\n continue\n for k in range(self.num_product):\n deg = str(round(float(deg) * self.pw_list[k]))\n if deg in d_dict:\n d_dict[deg].add((k, i))\n else:\n d_dict[deg] = {(k, i)}\n f.close()\n\n return d_dict\n\n def constructExpendDegreeDict(self):\n # -- display the degree and the nodes with the degree --\n ### d_dict: (dict) the degree and the nodes with the degree\n ### d_dict[deg]: (set) the set for deg-degree nodes\n d_dict = {}\n for i in self.graph_dict:\n i_set = {i}\n for ii in self.graph_dict[i]:\n if ii not in i_set:\n i_set.add(ii)\n for ii in self.graph_dict[i]:\n if ii in self.graph_dict:\n for iii in self.graph_dict[ii]:\n if iii not in i_set:\n i_set.add(iii)\n\n for k in range(self.num_product):\n deg = str(round(len(i_set) * self.pw_list[k]))\n if deg in d_dict:\n d_dict[deg].add((k, i))\n else:\n d_dict[deg] = {(k, i)}\n\n return d_dict\n\n\nif __name__ == '__main__':\n dataset_name = 'email_undirected'\n cascade_model = 'ic'\n product_name = 'item_lphc'\n wallet_distribution_type = 'm50e25'\n total_budget = 10\n whether_passing_information_with_purchasing = bool(1)\n personal_purchasing_prob = 'random'\n eva_monte_carlo = 100\n\n iniG = IniGraph(dataset_name)\n iniP = IniProduct(product_name)\n\n seed_cost_dict = iniG.constructSeedCostDict()\n graph_dict = iniG.constructGraphDict(cascade_model)\n product_list = iniP.getProductList()\n num_node = len(seed_cost_dict)\n num_product = len(product_list)\n\n # -- initialization for each budget --\n start_time = time.time()\n sshd = SeedSelectionHD(graph_dict, seed_cost_dict, product_list)\n\n # -- initialization for each sample_number --\n now_budget = 0.0\n seed_set = [set() for _ in range(num_product)]\n\n degree_dict = sshd.constructDegreeDict(dataset_name)\n mep_g = selectDegreeSeed(degree_dict)\n mep_k_prod, mep_i_node = mep_g[0], mep_g[1]\n\n # -- main --\n while now_budget < total_budget and mep_i_node != '-1':\n if now_budget + seed_cost_dict[mep_i_node] > total_budget:\n mep_g = selectDegreeSeed(degree_dict)\n mep_k_prod, mep_i_node = mep_g[0], mep_g[1]\n if mep_i_node == '-1':\n break\n continue\n\n seed_set[mep_k_prod].add(mep_i_node)\n now_budget += seed_cost_dict[mep_i_node]\n\n mep_g = selectDegreeSeed(degree_dict)\n mep_k_prod, mep_i_node = mep_g[0], mep_g[1]\n\n print('seed selection time: ' + str(round(time.time() - start_time, 2)) + 'sec')\n eva = Evaluation(graph_dict, seed_cost_dict, product_list, personal_purchasing_prob, whether_passing_information_with_purchasing)\n iniW = IniWallet(dataset_name, product_name, wallet_distribution_type)\n wallet_list = iniW.getWalletList()\n personal_prob_list = eva.setPersonalPurchasingProbList(wallet_list)\n\n sample_pro_acc, sample_bud_acc = 0.0, 0.0\n sample_sn_k_acc, sample_pnn_k_acc = [0.0 for _ in range(num_product)], [0 for _ in range(num_product)]\n sample_pro_k_acc, sample_bud_k_acc = [0.0 for _ in range(num_product)], [0.0 for _ in range(num_product)]\n\n for _ in range(eva_monte_carlo):\n pro, pro_k_list, pnn_k_list = eva.getSeedSetProfit(seed_set, copy.deepcopy(wallet_list), copy.deepcopy(personal_prob_list))\n sample_pro_acc += pro\n for kk in range(num_product):\n sample_pro_k_acc[kk] += pro_k_list[kk]\n sample_pnn_k_acc[kk] += pnn_k_list[kk]\n sample_pro_acc = round(sample_pro_acc / eva_monte_carlo, 4)\n for kk in range(num_product):\n sample_pro_k_acc[kk] = round(sample_pro_k_acc[kk] / eva_monte_carlo, 4)\n sample_pnn_k_acc[kk] = round(sample_pnn_k_acc[kk] / eva_monte_carlo, 2)\n sample_sn_k_acc[kk] = len(seed_set[kk])\n for sample_seed in seed_set[kk]:\n sample_bud_acc += seed_cost_dict[sample_seed]\n sample_bud_k_acc[kk] += seed_cost_dict[sample_seed]\n sample_bud_acc = round(sample_bud_acc, 2)\n sample_bud_k_acc[kk] = round(sample_bud_k_acc[kk], 2)\n\n print('seed set: ' + str(seed_set))\n print('profit: ' + str(sample_pro_acc))\n print('budget: ' + str(sample_bud_acc))\n print('seed number: ' + str(sample_sn_k_acc))\n print('purchasing node number: ' + str(sample_pnn_k_acc))\n print('ratio profit: ' + str(sample_pro_k_acc))\n print('ratio budget: ' + str(sample_bud_k_acc))\n print('total time: ' + str(round(time.time() - start_time, 2)) + 'sec')\n","sub_path":"SeedSelection_HighDegree.py","file_name":"SeedSelection_HighDegree.py","file_ext":"py","file_size_in_byte":8808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"595548035","text":"#!/usr/bin/env python\n\nimport os, sys, re\nfrom logging import *\n\nfrom Action import Action\n\nclass VxAction(Action):\n def __init__(self, continueFailedCmd = False):\n debug('entering class VxAction::__init__')\n super(VxAction, self).__init__(continueFailedCmd)\n self.windBaseDir = ''\n\n\n def BeforeRun(self):\n debug('entering class VxAction::Before')\n\n self.windBaseDir = os.getenv(\"WIND_BASE\")\n debug('WIND_BASE=%s' % self.windBaseDir)\n if self.windBaseDir is None:\n error('environment WIND_BASE not found')\n exit(1)\n else:\n if not re.search('vxworks-7', self.windBaseDir):\n error('environment WIND_BASE is not correct')\n exit(1)\n return self.windBaseDir\n ","sub_path":"practical_script_study/VxAction.py","file_name":"VxAction.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"101190033","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nhttps://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/description/\n\n\nGiven a binary tree,\nyou need to find the length of Longest Consecutive Path in Binary Tree.\n\nEspecially, this path can be either increasing or decreasing.\n\nFor example, [1,2,3,4] and [4,3,2,1] are both considered valid,\nbut the path [1,2,4,3] is not valid.\n\nOn the other hand,\nthe path can be in the child-Parent-child order,\nwhere not necessarily be parent-child order.\n\n\nExample 1:\nInput:\n 1\n / \\\n 2 3\n\nOutput: 2\nExplanation: The longest consecutive path is [1, 2] or [2, 1].\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def longestConsecutive(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n dfs\n 兩種解法??\n 1. convert成 linked list 解? 不可能~~ 有多重路徑.\n 2. 直接上.\n \"\"\"\n\n def dfs(node, prev):\n \"\"\"\n input\n output left: increase, right: decrease\n \"\"\"\n\n if not node:\n return\n\n linc = ldec = rinc = rdec = 0\n\n if node.left:\n linc, ldec = dfs(node.left, node)\n\n if node.right:\n rinc, rdec = dfs(node.right, node)\n\n gmx[0] = max(gmx[0], linc + rdec + 1, ldec + rinc + 1)\n\n if node is not prev:\n if node.val == prev.val - 1:\n # increase inorder.\n mx_inc = max(linc + 1, rinc + 1)\n\n return mx_inc, 0\n\n elif node.val == prev.val + 1:\n mx_dec = max(ldec + 1, rdec + 1)\n\n return 0, mx_dec\n else:\n return 0, 0\n\n gmx = [0]\n dfs(root, root)\n\n return gmx[0]\n\n def lc_answer(self, root):\n def dfs(node, parent):\n if not node:\n return 0, 0\n\n li, ld = dfs(node.left, node)\n ri, rd = dfs(node.right, node)\n l[0] = max(l[0], li + rd + 1, ld + ri + 1)\n\n if node.val == parent.val + 1:\n return max(li, ri) + 1, 0\n\n if node.val == parent.val - 1:\n return 0, max(ld, rd) + 1\n return 0, 0\n\n l = [0]\n dfs(root, root)\n\n return l[0]\n\n\ndef build():\n \"\"\"\n 3\n / \\\n 2 4\n / \\\n 5 7\n \"\"\"\n root = TreeNode(3)\n root.left = TreeNode(2)\n root.right = TreeNode(4)\n root.right.right = TreeNode(7)\n root.right.left = TreeNode(5)\n return root\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.longestConsecutive(build()))\n","sub_path":"co_google/549_Binary_Tree_Longest_Consecutive_Sequence_II.py","file_name":"549_Binary_Tree_Longest_Consecutive_Sequence_II.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"52383401","text":"\"\"\"\ngreat performing, greatly written module\n\n\"\"\"\n\nimport datetime\nimport random\nfrom faker import Faker\nimport csv\nimport os\nfrom string import ascii_lowercase, digits\n\ndef gen_data(filename, entries, regenerate = False):\n ''' Generates a ton of random entries and dumps them into filename '''\n if os.path.isfile(filename) and regenerate == False:\n # dont regenerate data if the file exists\n return\n print(\"Generating data in %s\" % filename)\n f = open(filename, 'w+')\n f.write(\"seq,guid,seq,seq,ccnumber,date,sequence\\n\")\n fakerer = Faker()\n word_list = [\"karaoke\", \"test\", \"words\", \"stuff\", \"apple\", \"orange\",\n \"fedora\", \"list\", \"canary\", \"slugs\", \"snails\", \"flipper\",\n \"sandals\", \"shoes\", \"nails\", \"hammers\", \"to\", \"the\", \"and\",\n \"asdfsadjf\", \"asdf\", \"noise\", \"random\", \"letters\"]\n for row in range(entries):\n data = \"%s,%s,%s,%s,%s,%s,%s\\n\" % (row, fakerer.uuid4(), row, row,\n fakerer.credit_card_number(),\n fakerer.date(pattern=\"%m/%d/%Y\"),\n fakerer.text(ext_word_list=word_list).replace('\\n', ' ').replace(',', ' '))\n f.write(data)\n f.close()\n print(\"Generated data.\")\n\n\ndef analyze(filename):\n ''' checks filename for specific years and 'ao' in column 6 '''\n start = datetime.datetime.now()\n with open(filename) as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n\n year_count = {\n \"2013\": 0,\n \"2014\": 0,\n \"2015\": 0,\n \"2016\": 0,\n \"2017\": 0,\n \"2018\": 0\n }\n found = 0\n\n for row in reader:\n lrow = list(row)\n\n try:\n year = int(lrow[5][6:])\n except ValueError:\n continue\n if 2012 < year <= 2018:\n year_count[str(year)] += 1\n if \"ao\" in lrow[6]:\n found += 1\n\n print(year_count)\n print(f\"'ao' was found {found} times\")\n end = datetime.datetime.now()\n return (start, end, year_count, found)\n\ndef main():\n ''' the main function automatically loads data/generated_data.csv '''\n ''' if the file doesn't exist already '''\n filename = \"data/generated_data.csv\"\n analyze(filename)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"students/aaron/lesson06/assignment/src/good_perf.py","file_name":"good_perf.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"462835115","text":"import time\nfrom botnet.config import Config\nfrom botnet.modules.builtin.irc import IRC, InactivityMonitor\n\n\ndef make_config():\n config = {\n 'module_config': {\n 'botnet': {\n 'irc': {}\n }\n }\n }\n return Config(config)\n\n\ndef test_process_data():\n data = [b'data1\\n', b'da', b'ta2\\nda', b'ta3', b'\\n', b'']\n config = make_config()\n irc = IRC(config)\n lines = []\n for d in data:\n lines.extend(irc.process_data(d))\n assert len(lines) == 3\n\n\ndef test_inactivity_monitor():\n\n class TestMonitor(InactivityMonitor):\n\n ping_timeout = 0.5\n abort_timeout = 1\n\n def __init__(self, irc_module):\n super(TestMonitor, self).__init__(irc_module)\n self.pinged = False\n self.aborted = False\n\n def on_timer_ping(self):\n self.pinged = True\n\n def on_timer_abort(self):\n self.aborted = True\n\n\n config = make_config()\n irc = IRC(config)\n\n with TestMonitor(irc) as t:\n time.sleep(1.5)\n assert t.pinged\n assert t.aborted\n\n with TestMonitor(irc) as t:\n time.sleep(.75)\n assert t.pinged\n assert not t.aborted\n\n with TestMonitor(irc) as t:\n assert not t.pinged\n assert not t.aborted\n\n\ndef test_inactivity_monitor_repeated():\n class TestMonitor(InactivityMonitor):\n\n ping_timeout = 0.5\n ping_repeat = 0.1\n abort_timeout = 1\n\n def __init__(self, irc_module):\n super(TestMonitor, self).__init__(irc_module)\n self.pinged = 0\n self.aborted = 0\n\n def on_timer_ping(self):\n super(TestMonitor, self).on_timer_ping()\n self.pinged += 1\n\n def on_timer_abort(self):\n super(TestMonitor, self).on_timer_abort()\n self.aborted += 1\n\n\n config = make_config()\n irc = IRC(config)\n\n with TestMonitor(irc) as t:\n time.sleep(1.5)\n assert t.pinged > 3\n assert t.aborted > 0\n","sub_path":"tests/modules/builtin/test_irc.py","file_name":"test_irc.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"192709721","text":"import cPickle as pickle\nimport os,csv\nimport numpy as np\n\n\"\"\"class author:\n def __init__(self,name=''):\n self.name = name\n self.data = {}\n\n def add(self,date,batch):\n self.data[date] = batch\n\nwith open('data/authors/aillaud.pkl','rb') as input:\n data = pickle.load(input)\n\ncwd = os.getcwd()\n\nd=data.data\nd=d[d.keys()[0]]\nd = d.split('\\n')\"\"\"\n\ndef format(data,destination,filename):\n if not os.path.exists(destination):\n os.makedirs(destination)\n with open(destination+filename,'w') as f:\n d = data.split('\\n')\n filewriter = csv.writer(f)\n for row in d:\n #For each row, split in between |\n out = row.split(\"|\")\n out_ = []\n for i in range(len(out)):\n #For each item in each row\n item = out[i]\n if len(item) != 0:\n #Provided item isn't 0\n indices=[]\n flag = 0\n for x in range(len(item)):\n if item[x] == ' ': #Mark whitespace for removal\n indices.append(x)\n if item[x] == '?': #Mark empty data\n flag = 1\n if len(indices) > 1: #If length is more than 1, reverse\n indices.reverse()\n for index in indices:\n #Remove all items marked for removal\n item = item[:index]+item[(index+1):]\n if flag == 1:\n #If data is empty, enter as NaN\n out_.append(np.nan)\n elif len(item) != 0:\n #If not of 0 length, add to csv\n out_.append(item)\n if len(out_) > 1:\n filewriter.writerow(out_) #Write to csv\n print(out_)\n else:\n print('Error, output length <= 1. ',out_)\n","sub_path":"format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"127691999","text":"'''The signals for the scores app, update the total score when individual scores are updated'''\n\n#import the post_save signal\nfrom django.db.models.signals import post_save\n#import involved models\nfrom scores.models import IndividualScore, TotalScore\n\n#the function to be called when the individual score is updated\ndef update_total_score(sender, **kwargs):\n #the updated instance\n this_individual_score = kwargs['instance']\n #the total score obj tied to the instance\n this_total_score = this_individual_score.total_score\n #get all associated individual scores objects\n in_list = list(this_total_score.individual_scores.all())\n #group individual scores that have the same category\n in_list = group_list(in_list)\n #iterate over pairs and add to the score. If encounter a list (same category) will need to add scores before applying wieghting\n updated_score = 0\n for obj in in_list:\n #check if obj is list, if so account for multiple goals of same category\n if isinstance(obj, list):\n #sum the scores and the goal measures\n s = 0\n g = 0\n for score_ in obj:\n #add to score\n s = s + int(score_.individual_score)\n #add to goal value\n g = g + int(score_.goal.measure)\n #all weights are the same, so just get from the first one\n w = int(obj[0].goal.weight)\n w = float(w/100)\n #otherwise, handle individual item\n else:\n #get the score\n s = int(obj.individual_score)\n #get the goal value\n g = int(obj.goal.measure)\n #get the weight\n w = int(obj.goal.weight)\n w = float(w/100)\n #Now use score, goal, and wieght values to calculate\n #normalized score\n s = int(100*(s/g))\n #the product\n prod = s * w\n prod = int(prod)\n #the updated score\n updated_score = updated_score + prod\n #set the updated score to the score of the total score object\n this_total_score.total_score = updated_score\n this_total_score.save()\n\n#a function that takes a list of individual scores and returns a list where all scores of goals in the same\n#category are put into lists of length 2\ndef group_list(in_list):\n #make a list of all the categories of the scores\n cat_list = []\n for score in in_list:\n #get the category\n cat = score.goal.category\n #append to cat list\n cat_list.append(cat)\n #the list of score values to return\n grouped = []\n #identified indices to prevent dups\n visited = []\n #iterate over cat list, make duplicate sets\n for i in range(0, len(cat_list)):\n #if visited, continue\n if(i in visited):\n continue\n else:\n visited.append(i)\n #the set right now is just this score\n the_set = [in_list[i]]\n #the value at that index\n the_cat = cat_list[i]\n #iterate over from one spot ahead\n for j in range(i+1, len(cat_list)):\n if the_cat == cat_list[j]:\n #visited\n visited.append(j)\n #append to list defining the set of this category\n the_set.append(in_list[j])\n #check if length 1, if so just use the value. otherwwise, append the set\n if len(the_set) == 1:\n grouped.append(in_list[i])\n else:\n grouped.append(the_set)\n \n #after iteration, return the list\n return grouped\n \n#call on update of an individual score object\npost_save.connect(update_total_score, sender = IndividualScore)\n\n\n\n","sub_path":"backend/scores/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"555246109","text":"\nfrom xml.dom import minidom\nfrom xml.etree import ElementTree\nimport csv\nimport matplotlib.pyplot as plt\nimport xml.etree.ElementTree as ET\nimport os\nimport numpy as np\nfrom tqdm import tqdm\nfrom PIL import Image\nfrom numpy import asarray\nimport pandas as pd\n\n# Labels = []\n\ndef get_traces_data(inkml_file_abs_path,classresult):\n traces_data = []\n\n tree = ET.parse(inkml_file_abs_path)\n root = tree.getroot()\n doc_namespace = \"{http://www.w3.org/2003/InkML}\"\n\n # get label\n ui = root.find(doc_namespace + \"annotation[@type='UI']\")\n ui = ui.text.replace('\"','')\n label = classresult[ui]\n label=label.replace('\\\\','slash_')\n # if label not in Labels:\n # print(label)\n # Labels.append(label)\n # process only 10 files for each class to reduce execution time for now\n # if os.path.exists(outputdir +'/'+ label) and len(os.listdir(outputdir +'/'+ label)) > 1:\n # return None\n\n 'Stores traces_all with their corresponding id'\n traces_all = [{'id': trace_tag.get('id'),\n 'coords': [\n [round(float(axis_coord)) if float(axis_coord).is_integer() else round(float(axis_coord) * 10000) \\\n for axis_coord in coord[1:].split(' ')] if coord.startswith(' ') \\\n else [round(float(axis_coord)) if float(axis_coord).is_integer() else round(\n float(axis_coord) * 10000) \\\n for axis_coord in coord.split(' ')] \\\n for coord in (trace_tag.text).replace('\\n', '').split(',')]} \\\n for trace_tag in root.findall(doc_namespace + 'trace')]\n\n 'Sort traces_all list by id to make searching for references faster'\n traces_all.sort(key=lambda trace_dict: int(trace_dict['id']))\n\n 'Always 1st traceGroup is a redundant wrapper'\n traceGroupWrapper = root.find(doc_namespace + 'traceGroup')\n\n if traceGroupWrapper is not None:\n for traceGroup in traceGroupWrapper.findall(doc_namespace + 'traceGroup'):\n 'traces of the current traceGroup'\n traces_curr = []\n for traceView in traceGroup.findall(doc_namespace + 'traceView'):\n 'Id reference to specific trace tag corresponding to currently considered label'\n traceDataRef = int(traceView.get('traceDataRef'))\n\n index = next((index for (index, d) in enumerate(traces_all) if int(d[\"id\"]) == traceDataRef), None)\n # print(index)\n 'Each trace is represented by a list of coordinates to connect'\n single_trace = traces_all[index]['coords']\n traces_curr.append(single_trace)\n\n traces_data.append({'label': label, 'trace_group': traces_curr})\n\n return traces_data\n\n\ndef inkml2img(input_path, output_path,classresult):\n # get coords and label\n traces = get_traces_data(input_path,classresult)\n\n path = input_path.split('/')\n path = path[len(path) - 1].split('.')\n path = path[0]\n\n if traces is not None:\n for elem in traces:\n\n # print(elem)\n # print('-------------------------')\n # print(elem['label'])\n\n plt.gca().invert_yaxis()\n plt.gca().set_aspect('equal', adjustable='box')\n plt.axis('off')\n trace = elem['trace_group']\n output_path = output_path\n\n # plot coords\n for subls in trace:\n # print(subls)\n data = np.array(subls)\n if len(data[0]) == 2:\n x, y = zip(*data)\n else:\n # x,y and time\n x, y, z = zip(*data)\n plt.plot(x, y, linewidth=2, c='black')\n\n label = elem['label']\n # print(label)\n ind_output_path = output_path +'/'+ label\n try:\n os.mkdir(ind_output_path)\n except OSError:\n # print (\"Folder %s Already Exists\" % ind_output_path)\n # print(OSError.strerror)\n pass\n else:\n # print (\"Successfully created the directory %s \" % ind_output_path)\n pass\n\n plt.savefig(ind_output_path + '/' + path + '.png', bbox_inches='tight', dpi=100)\n plt.gcf().clear()\n image = Image.open(ind_output_path + '/' + path + '.png').convert('L')\n image_arr = asarray(image)\n return image_arr,trace,label\n\n\n\noutputdir = 'images'\n\n\nif __name__ == \"__main__\":\n # create directory for output images\n try:\n os.mkdir(outputdir)\n except OSError:\n # print(\"Folder %s Already Exists\" % outputdir)\n # print(OSError.strerror)\n pass\n else:\n # print(\"Successfully created the directory %s \" % outputdir)\n pass\n\n path = 'trainingSymbols'\n # get labels for each input\n classresult = dict()\n with open(path + '/iso_GT.txt', mode='r') as infile:\n reader = csv.reader(infile)\n for row in reader:\n classresult[row[0]] = row[1]\n filenames = []\n labels = []\n traces = []\n images = []\n # convert all inkml from training data to png\n files = os.listdir(path)\n for file in tqdm(files):\n if str(file).__contains__('.inkml'):\n # print(file)\n result = inkml2img(path + '/' + file, outputdir,classresult)\n if result is not None:\n image,trace,label = result\n filenames.append(file)\n images.append(image)\n traces.append(trace)\n labels.append(label)\n\n df = pd.DataFrame({'filenames':filenames,'images':images,'traces':traces,'labels':labels})\n df.to_csv('trainingdata.csv', index=False, header=True)\n\n\n\n\n","sub_path":"LoadData.py","file_name":"LoadData.py","file_ext":"py","file_size_in_byte":5863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"28666997","text":"from disjoint_set import DisjointSetLinkedList, DisjointSetForestNode\nimport heapq\nfrom heap import MinHeapPriorityQueue\nimport math\n\n#iterator to return each edge and weight in format\n#(vertex1, vertex2, weight)\ndef kruskal_mst(length, it, disjoint_set):\n nodes = [None for i in range(length)]\n for i in range(length):\n nodes[i] = disjoint_set.init_set(i)\n\n edges = sorted(it, key=lambda x:x[2])\n\n tree_edges = []\n for e in edges:\n node1, node2 = nodes[e[0]], nodes[e[1]]\n print(e)\n print(\"{} | {}\".format(node1.d_set, node2.d_set))\n if node1.union_set(node2):\n print(\"{} | {}\".format(node1.d_set, node2.d_set))\n tree_edges.append(e)\n\n return tree_edges\n\n#each edge contains (v1, v2, weight)\ndef al_it(al):\n for i, v in enumerate(al):\n for e in v:\n yield i, e[0], e[1]\n\ndef am_it(am):\n for i, v in enumerate(am):\n for j, e in enumerate(v):\n if e > 0:\n yield i, j, e\n\n#??? default to 0 might not be the best choice since these works with negative\n#edges ???\ndef al_to_am(al):\n length = len(al)\n res = [[0] * length for i in range(length)]\n\n for i, n in enumerate(al):\n for j, e in enumerate(n):\n res[i][e[0]] = e[1]\n\n return res\n\nclass DataObj(object):\n def __init__(self, **kwargs):\n if kwargs:\n self.__dict__.update(kwargs)\n\n def __str__(self):\n return str(self.__dict__)\n\n#INF = math.inf\nINF = float(\"inf\")\n\ndef prim_mst(nodes, edge_it):\n tree_edges = []\n min_priority_q = MinHeapPriorityQueue((INF, i) for i in range(len(nodes)))\n #this is assuming order hasn't changed when keys are the same\n #comment out build_heap in constructor and call it explicitly\n node_data = [DataObj(pq_entry=min_priority_q[i],\n parent_index=None,\n edges=nodes[i])\n for i in range(len(nodes))]\n min_priority_q.build_heap()\n\n while min_priority_q:\n cur_pq_node = min_priority_q.extract_min()\n cur_node = node_data[cur_pq_node.data]\n cur_node.pq_entry = None\n print(cur_pq_node)\n print(cur_node)\n #print([str(x) for x in node_data])\n\n if cur_node.parent_index is not None:\n tree_edges.append((cur_node.parent_index, cur_pq_node.data,\n cur_pq_node.key))\n\n for other_node_index, e_weight in edge_it(cur_node.edges):\n print(other_node_index, e_weight)\n other_node_data = node_data[other_node_index]\n other_pq_entry = other_node_data.pq_entry\n\n if other_pq_entry is not None:\n if e_weight < other_pq_entry.key:\n min_priority_q.decrease_key(other_pq_entry, e_weight)\n other_node_data.parent_index = cur_pq_node.data\n\n return tree_edges\n\ndef al_edge_it(edges):\n for e in edges:\n yield e\n\ndef am_edge_it(edges):\n for i, e in enumerate(edges):\n if e > 0:\n yield (i, e)\n\nif __name__ == '__main__':\n al = (\n ((1, 4), (7, 8)),\n ((0, 4), (2, 8), (7, 11)),\n ((1, 8), (3, 7), (5, 4), (8, 2)),\n ((2, 7), (4, 9), (5, 14)),\n ((3, 9), (5, 10)),\n ((2, 4), (3, 14), (4, 10), (6, 2)),\n ((5, 2), (7, 1), (8, 6)),\n ((0, 8), (1, 11), (6, 1), (8, 7)),\n ((2, 2), (6, 6), (7, 7)),\n )\n\n print('al')\n print(al)\n\n print('am')\n am = al_to_am(al)\n print(am)\n assert list(am_it(am)) == list(al_it(al))\n\n print('k_mst al')\n k_al_ll = kruskal_mst(len(al), al_it(al), DisjointSetLinkedList)\n k_al_f = kruskal_mst(len(al), al_it(al), DisjointSetForestNode)\n\n print('k_mst am')\n k_am_ll = kruskal_mst(len(am), am_it(am), DisjointSetLinkedList)\n k_am_f = kruskal_mst(len(am), am_it(am), DisjointSetForestNode)\n\n assert k_al_ll == k_am_ll\n assert k_al_f == k_am_f\n\n print('prim al')\n p_al = prim_mst(al, al_edge_it)\n print('prim am')\n p_am = prim_mst(am, am_edge_it)\n assert p_al == p_am\n print(p_al)\n\n","sub_path":"lab/algo/CLRS/mst.py","file_name":"mst.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"359378408","text":"\"\"\"\ndata to test list\n\"\"\"\nfrom rest_framework import status\nfrom .data_create import Records_create as recc\n\n\nclass Records_list():\n \"\"\"\n class to define the records to test and assert\n \"\"\"\n\n list_ok = {\n \"create\": [\n recc.ok1,\n recc.ok2\n ],\n \"out\": recc.ok2['out'],\n \"status_code\": status.HTTP_200_OK\n }\n\n list_empty = {\n \"create\": [],\n \"out\": {},\n \"status_code\": status.HTTP_200_OK\n }\n","sub_path":"call_records/app/tests/config_price/data_list.py","file_name":"data_list.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"583837560","text":"import gtk\n\nclass MailDialog(gtk.Dialog):\n LAST_RECIPIENT = ''\n \n def __init__(self, header):\n # Construct superclass.\n gtk.Dialog.__init__(self, header)\n \n # Add widgets.\n self.add_button(gtk.STOCK_CANCEL, 0)\n self.add_button(gtk.STOCK_OK, 1)\n\n hbox = gtk.HBox()\n left_vbox = gtk.VBox(True)\n right_vbox = gtk.VBox(True)\n hbox.pack_start(left_vbox)\n hbox.pack_start(right_vbox)\n left_vbox.pack_start(gtk.Label('Recipient:'))\n left_vbox.pack_start(gtk.Label('Subject:'))\n self.recipient = gtk.Entry()\n self.recipient.set_text(MailDialog.LAST_RECIPIENT)\n self.subject = gtk.Entry()\n right_vbox.pack_start(self.recipient)\n right_vbox.pack_start(self.subject)\n self.vbox.pack_start(hbox)\n \n def do_it(self):\n self.show_all()\n rc = self.run()\n self.hide_all()\n if rc == 1:\n # Ok button was clicked. Return the value given by the scale.\n MailDialog.LAST_RECIPIENT = self.recipient.get_text()\n return (self.recipient.get_text(), self.subject.get_text())\n else:\n # Cancel was clicked. Return an error indicator.\n return None\n","sub_path":"demo_apps/augim/maemo4/src/mail_dialog.py","file_name":"mail_dialog.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"18054906","text":"# coding:utf-8\n\"\"\"\nwide and deep\n\"\"\"\nfrom framework.data_input import IDataInput\nfrom framework.inference import IInference\nfrom framework.train import ITrain\nfrom framework.eval import IEval\nimport pandas as pd\nimport tensorflow as tf\nimport common\nfrom hook import LoggerHook\nclass DataInput(IDataInput):\n def __init__(self,\n csv_column_names,\n label_column_name,\n input_file_paths,\n shuffle,\n batch_size,\n example_per_epoch_num,\n parallel_thread_num=16):\n super(DataInput, self).__init__(input_file_paths,\n batch_size,\n example_per_epoch_num,\n parallel_thread_num=parallel_thread_num)\n self._csv_column_names = csv_column_names\n self._label_column_name = label_column_name\n self._shuffle = shuffle\n\n def read_data(self):\n input_file_path = self._input_file_paths[0]\n df = pd.read_csv(tf.gfile.Open(input_file_path),names=self._csv_column_names,skipinitialspace=True,skiprows=1)\n df.dropna(axis=0, how='any')\n #label = df[self._label_column_name].apply(lambda x: \">50K\" in x).astype(int)\n label = df[self._label_column_name].astype(int)\n print(df.head())\n print(label.head())\n return tf.estimator.inputs.pandas_input_fn(\n x=df,\n y=label,\n batch_size=self._batch_size,\n shuffle=self._shuffle,\n num_threads=self._parallel_thread_num,\n num_epochs=self._example_per_echo_num)\n def _preprocess_data(self, record):\n pass\n def _generate_train_batch(self, train_data, label, shuffle=True):\n pass\n def _read_data_from_queue(self, file_path_queue):\n pass\nclass Inference(IInference):\n def __init__(self, model_dir, model_type, linear_feature_columns, dnn_feature_columns):\n super(Inference, self).__init__()\n self._model_dir = model_dir\n self._model_type = model_type\n self._linear_feature_columns = linear_feature_columns\n self._dnn_featrue_columns = dnn_feature_columns\n\n def inference(self, data):\n if self._model_type == 'wide':\n return tf.estimator.LinearClassifier(feature_columns=self._linear_feature_columns,model_dir=self._model_dir)\n elif self._model_type == 'deep':\n return tf.estimator.DNNClassifier(feature_columns=self._dnn_featrue_columns,model_dir=self._model_dir,hidden_units=[200, 80,2])\n elif self._model_type == 'wide_n_deep':\n return tf.estimator.DNNLinearCombinedClassifier(model_dir=self._model_dir,linear_feature_columns=self._linear_feature_columns,\n dnn_feature_columns=self._dnn_featrue_columns,dnn_hidden_units=[200, 80,2])\n else:\n raise RuntimeError('no %s model type' % self._model_type)\n\nclass Train(ITrain):\n def __init__(self, model_type, model_dir):\n super(Train, self).__init__()\n self._model_type = model_type\n self._model_dir = model_dir\n @property\n def model_dir(self):\n return self._model_dir\n @property\n def model_type(self):\n return self._model_type\n\n def train(self):\n data_input = DataInput(common.CSV_COLUMNS,\n common.LABEL_COLUMN_NAME,\n ['C:\\\\liuyf\\\\作業\\\\07_A-8データ\\\\IM_ALL_addworker.csv'],\n shuffle=True,\n batch_size=128,\n example_per_epoch_num=None)\n input_fn = data_input.read_data()\n if self._model_type == 'wide':\n inference = Inference(self._model_dir,\n self._model_type,\n common.base_columns + common.crossed_columns, None)\n elif self._model_type == 'deep':\n inference = Inference(self._model_dir,\n self._model_type,\n None,\n common.deep_columns)\n elif self._model_type == 'wide_n_deep':\n inference = Inference(self._model_dir,\n self._model_type,\n common.crossed_columns,\n common.deep_columns)\n else:\n raise RuntimeError('model type error: ' + self._model_type)\n model = inference.inference(None)\n logger_hook = LoggerHook()\n model.train(input_fn=input_fn, hooks=[logger_hook], steps=2000)\n return model\n\nclass Eval(IEval):\n def __init__(self, model):\n super(Eval, self).__init__(None, None, None, 128)\n self._model = model\n def accuracy(self, predict_results, labels):\n pass\n def read_test_data_set(self):\n pass\n def predict(self, test_data_batch):\n predictions = list(self._model.predict(input_fn=test_data_batch))\n return predictions\n def eval(self):\n data_input = DataInput(common.CSV_COLUMNS,\n common.LABEL_COLUMN_NAME,\n ['C:\\\\liuyf\\\\作業\\\\07_A-8データ\\\\IM_ALL_addworker.csv'],\n shuffle=False,\n batch_size=128,\n example_per_epoch_num=1)\n test_data_input_fn = data_input.read_data()\n results = self._model.evaluate(input_fn=test_data_input_fn,steps=None)\n for key in sorted(results):\n print(\"%s: %s\" % (key, results[key]))","sub_path":"010.wide_deep/wide_and_deep.py","file_name":"wide_and_deep.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"446812024","text":"import sys\nsys.path.append(\"..\")\nimport cv2\nimport numpy as np\nfrom Question_01_10.q2 import Gray\n\ndef zero_padding(_img, K_size = 3):\n img = _img.copy()\n pad = K_size//2\n out = np.pad(img, [(pad,pad), (pad,pad)], \"constant\")\n return out\n\ndef differentialfilter(_img, K_size = 3):\n img = _img.copy()\n pad = K_size//2\n if len(img.shape) == 3:\n H,W,C = img.shape\n else:\n img = np.expand_dims(img ,axis = -1)\n H, W, C = img.shape\n\n img_zero = zero_padding(_img)\n out = np.zeros_like(img_zero).astype(np.float)\n tmp = img_zero.copy().astype(np.float)\n\n out_v = out.copy()\n out_h = out.copy()\n\n #prepare Kernel\n Kernel_v = [[0., -1., 0.], [0., 1., 0.], [0., 0., 0.]]\n Kernel_h = [[0., 0., 0.],[-1., 1., 0.], [0., 0., 0.]]\n\n\n for y in range(H):\n for x in range(W):\n out_v[pad+y,pad+x] = np.sum(Kernel_v* (tmp[y: y + K_size, x: x + K_size]))\n out_h[pad+y,pad+x] = np.sum(Kernel_h*(tmp[y: y + K_size, x: x + K_size]))\n\n\n out_v = np.clip(out_v, 0, 255)\n out_h = np.clip(out_h, 0, 255)\n out_v = out_v[pad:pad+H,pad:pad+W].astype(np.uint8)\n out_h = out_h[pad:pad+H,pad:pad+W].astype(np.uint8)\n\n print(out_v)\n print(out_h)\n return out_v, out_h\n\n\n\nimg = cv2.imread(\"./image_11_20/imori.jpg\").astype(np.float)\nimg_gray = Gray(img)\nimg_ans_v, img_ans_h = differentialfilter(img_gray)\n\ncv2.imwrite(\"./image_11_20/answer14_v.jpg\", img_ans_v)\ncv2.imshow(\"result_v\", img_ans_v)\nwhile cv2.waitKey(100) != 27:# loop if not get ESC\n if cv2.getWindowProperty('result_v',cv2.WND_PROP_VISIBLE) <= 0:\n break\ncv2.destroyWindow('result_v')\n\n\ncv2.imwrite(\"./image_11_20/answer14_h.jpg\", img_ans_h)\ncv2.imshow(\"result_h\", img_ans_h)\nwhile cv2.waitKey(100) != 27:\n if cv2.getWindowProperty('result_h',cv2.WND_PROP_VISIBLE) <= 0:\n break\ncv2.destroyWindow('result_h')\ncv2.destroyAllWindows()\n","sub_path":"Question_11_20/q14.py","file_name":"q14.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"449634459","text":"\"\"\"\nTarefa de programação: Lista de exercícios - 2\n\nExercício 1: Letras maiúsculas\nEscreva a função maiusculas(frase) que recebe uma frase (uma string) como parâmetro e\ndevolve uma string com as letras maiúsculas que existem nesta frase, na ordem em que elas aparecem.\n\nPara resolver este exercício, pode ser útil verificar uma tabela ASCII, que contém os valores de cada caractere.\nVer https://pt.wikipedia.org/wiki/ASCII\n\nNote que para simplificar a solução do exercício, as frases passadas para a sua função não possuirão caracteres que\nnão estejam presentes na tabela ASCII apresentada, como ç, á, É, ã, etc.\n\nDica: Os valores apresentados na tabela são os mesmos devolvidos pela função ord apresentada nas aulas.\n\nExemplos:\n\nmaiusculas('Programamos em python 2?')\n# deve devolver 'P'\n\nmaiusculas('Programamos em Python 3.')\n# deve devolver 'PP'\n\nmaiusculas('PrOgRaMaMoS em python!')\n# deve devolver 'PORMMS'\n\"\"\"\n\n\n# Mudar nome da função no envio da terefa para o mesma do exemplo, maiusculas().\ndef print_uppercase(phrase: str) -> str:\n capital_letters = []\n\n for index in range(len(phrase)):\n character = phrase[index]\n ascii_code = ord(character)\n\n if 64 < ascii_code < 91:\n capital_letters.append(character)\n\n return \"\".join(capital_letters)\n","sub_path":"SecondPart/Week2/PrintUppercase.py","file_name":"PrintUppercase.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"537206040","text":"# 한쪽 눈만 동공찾기\r\nimport cv2 as cv\r\nimport numpy as np\r\n\r\nfullvideo = 'IMG_0192.mov'\r\n\r\ncap = cv.VideoCapture(fullvideo) # 파일명 넣기'originalleft.avi'\r\ncap.set(3, 640) # Set Size ( Width )\r\ncap.set(4, 480) # Set SizE ( Height )\r\nwl = 0\r\nhl = 0\r\nxl = 0\r\nyl = 0\r\ncv.namedWindow('roi')\r\nf = open(\"pupil_coordinates.txt\", mode='wt')\r\n\r\n# 트랙바\r\ndef nothing(x):\r\n pass\r\ncv.createTrackbar('Pupil', 'roi', 0, 255, nothing)\r\ncv.setTrackbarPos('Pupil', 'roi', 35)\r\n\r\nkernel = np.ones((11, 11), np.uint8)\r\n\r\nwhile True:\r\n ret, frame = cap.read(0)\r\n\r\n if not ret:\r\n break\r\n\r\n roi = frame\r\n roi = frame[250:600, 350:850] # [start-y:y, start-x,x]\r\n\r\n rows, cols, _ = roi.shape\r\n\r\n gray_roi = cv.cvtColor(roi, cv.COLOR_BGR2GRAY)\r\n gray_roi = cv.medianBlur(gray_roi, 5)\r\n\r\n gray_roi = cv.erode(gray_roi, kernel, iterations=3) # 침식\r\n gray_roi = cv.dilate(gray_roi, kernel, iterations=3) # 팽창 연산\r\n gray_roi = cv.morphologyEx(gray_roi, cv.MORPH_CLOSE, kernel)\r\n\r\n pupil_th_val = cv.getTrackbarPos('Pupil', 'roi') # 트랙바에서 값 가져오기\r\n\r\n _, pupil_threshold = cv.threshold(gray_roi, pupil_th_val, 255, cv.THRESH_BINARY_INV)\r\n _, pupil_contours, _ = cv.findContours(pupil_threshold, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\r\n pupil_contours = sorted(pupil_contours, key=lambda x: cv.contourArea(x), reverse=True)\r\n\r\n hough = frame\r\n hough = cv.resize(hough, dsize=(640, 480), interpolation=cv.INTER_AREA)\r\n rows, cols, _ = hough.shape\r\n cv.imshow(\"gray\", gray_roi)\r\n\r\n circles = cv.HoughCircles(gray_roi, cv.HOUGH_GRADIENT, 1, 100, param1=120, param2=40, minRadius=0, maxRadius=0)\r\n\r\n if circles is not None:\r\n circles = np.uint16(np.around(circles))\r\n x, y, radius = circles[0][0]\r\n center = (x, y)\r\n cv.circle(hough, center, radius, (255, 0, 0), 2)\r\n cv.circle(hough, center, 3, (0, 255, 0), -1)\r\n f.write(str(x) + \"\\t\" + str(y) + \"\\n\")\r\n\r\n cv.imshow('Hough circle', hough)\r\n\r\n for cnt2 in pupil_contours: # 동공\r\n (x2, y2, w2, h2) = cv.boundingRect(cnt2)\r\n rad = (int)(w2 / 2)\r\n x_val = x2 + int(w2 / 2)\r\n y_val = y2 + int(h2 / 2)\r\n cv.drawContours(roi, [cnt2], -1, (0, 0, 255), 2)\r\n cv.circle(roi, (x_val, y_val), 3, (0, 255, 0), -1)\r\n cv.circle(roi, (x_val, y_val), rad, (255, 0, 0), 2)\r\n break\r\n\r\n cv.imshow(\"roi\", roi)\r\n cv.imshow(\"Pupil_Threshold\", pupil_threshold)\r\n key = cv.waitKey(60) # 45\r\n\r\n if key == ord('q'):\r\n break\r\n\r\ncv.destroyAllWindows()\r\nf.close()\r\n#\r\n","sub_path":"one_pupil_detect.py","file_name":"one_pupil_detect.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"618918808","text":"# -*- coding: utf-8 -*- \n# @Time : 2021/1/12 9:46 \n# @Author : xu \n# @File : dingbot.py\n\n\nimport sys, os\nimport requests\nimport json\nimport apscheduler\nfrom datetime import datetime\n\n\ndef dingmessage():\n # 请求的URL,WebHook地址\n webhook = \"https://oapi.dingtalk.com/robot/send?access_token=f671e2a37e76a095201def8f687595d89c15b66c816a55d5b9e4470768fec255\"\n\n # 构建请求头部\n header = {\n \"Content-Type\": \"application/json\",\n \"Charset\": \"UTF-8\"\n }\n # 构建请求数据\n tex = f\"its a test for {datetime.now()}\"\n message = {\n\n \"msgtype\": \"text\",\n \"text\": {\n \"content\": \"look:\" + tex\n },\n \"at\": {\n \"isAtAll\": True\n }\n\n }\n # 对请求的数据进行json封装\n message_json = json.dumps(message)\n # 发送请求\n info = requests.post(url=webhook, data=message_json, headers=header)\n print(info.text)\n\n\ndef restart_program():\n python = sys.executable\n os.execl(python, python, * sys.argv)\n\n\nif __name__ == \"__main__\":\n dingmessage()\n","sub_path":"note-taking/dingbot.py","file_name":"dingbot.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"382495320","text":"\n\nfrom xai.brain.wordbase.nouns._ornithologist import _ORNITHOLOGIST\n\n#calss header\nclass _ORNITHOLOGISTS(_ORNITHOLOGIST, ):\n\tdef __init__(self,): \n\t\t_ORNITHOLOGIST.__init__(self)\n\t\tself.name = \"ORNITHOLOGISTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"ornithologist\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_ornithologists.py","file_name":"_ornithologists.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"540908527","text":"#!/usr/bin/env python\n''' distances.py -- for working with distances in pdb files\n\n'''\n\nfrom itertools import product\n\nfrom numpy.linalg import norm\n\n__author__ = 'Aram Avila-Herrera'\n\ndef get_CB_coord(residue):\n ''' Get beta carbon coordinates from residue\n\n residue: a Bio.PDB.Residue\n \n If residue is a glycine, returns alpha carbon coordinates\n Returns a list containing one coordinate as a numpy.ndarray of float32\n\n '''\n\n if residue.get_resname() == 'GLY':\n return [residue['CA'].coord]\n else:\n return [residue['CB'].coord]\n\ndef get_nonH_coords(residue):\n ''' Get coordinates from non-hydrogen atoms in residue\n residue: a Bio.PDB.Residue\n\n Returns a list of coordinates, each a numpy.ndarray\n\n '''\n\n return [atom.coord\n for atom\n in residue.get_list()\n if not atom.get_id().startswith('H')\n ]\n\ndef get_allatom_coords(residue):\n ''' Get coordinates from all atoms in residue\n \n residue: a Bio.PDB.Residue\n\n Returns a list of coordinates, each a numpy.ndarray\n\n '''\n\n return [atom.coord\n for atom\n in residue.get_list()\n ]\n\ndef has_structure_carbon(residue):\n ''' Returns True if residue has a CB (CA if residue is a glycine)\n \n '''\n\n if 'CB' in residue:\n return True\n if residue.get_resname() == 'GLY' and 'CA' in residue:\n return True\n\n return False\n\ndef get_nonhet_residues(chain):\n ''' Get residues in a Bio.PDB.Chain entity with blank HET flag\n\n Returns a generator over those residues\n\n '''\n\n residues = chain.get_residues()\n nonhet_res = (res for res in residues if res.id[0] == ' ')\n\n return nonhet_res\n\ndef calc_residue_distance(res_a, res_b, get_coords):\n ''' Get euclidean distance between residues\n\n res_a, res_b: Bio.PDB.Residue entities\n get_coords: a function that returns atom coordinates for a residue\n get_coords() should return a list of numpy.ndarrays\n\n Returns a numpy.float32\n \n '''\n \n coords_a = get_coords(res_a)\n coords_b = get_coords(res_b)\n\n atom_distances = (\n norm(X1 - X2)\n for (X1, X2)\n in product(coords_a, coords_b)\n )\n \n # We want the smallest atom-atom distance between residues\n return min(atom_distances)\n\ndef choose_get_coords(dist_atoms):\n ''' Choose get_coords function from dist_atoms\n\n dist_atoms: a string 'Cb', 'NoH', or 'Any'\n\n Returns a get_coords function. Defaults to get_CB_coord()\n \n TODO: make these part of a class or something...\n\n '''\n \n if dist_atoms == 'NoH':\n return get_nonH_coords\n if dist_atoms == 'Any':\n return get_allatom_coords\n return get_CB_coord\n\n","sub_path":"coevo/pdb_aux/distances.py","file_name":"distances.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"637987449","text":"from app import app\nfrom flask import request, jsonify, make_response\nimport os\nimport json\n\n\n@app.route('/')\ndef index():\n return \"Hello From Note\"\n\n\n@app.route('/notes')\ndef notes():\n keyword = request.args.get('keyword')\n if not os.path.isfile('notes_stored/' + keyword):\n return make_response(jsonify(code=0, text=\"No Notes\"), 200)\n\n with open(\"notes_stored/\" + keyword, \"r+\") as file:\n notes = file.read()\n notes = notes.split(\"\\n,=>\\n\")[:-1]\n return make_response(jsonify(code=1, notes=notes), 200)\n\n\n@app.route('/add_note', methods=[\"POST\"])\ndef add_notes():\n data = request.get_json()\n keyword = data[\"keyword\"]\n note = data[\"note\"]\n if not os.path.isdir('notes_stored'):\n os.makedirs('notes_stored')\n with open(\"notes_stored/\" + keyword, \"a+\") as file:\n file.write(note)\n file.write(\"\\n,=>\\n\")\n return make_response(jsonify(code=1,text=\"OK\"), 200)","sub_path":"notes/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"272706577","text":"#\n# License: BSD\n# https://raw.github.com/robotics-in-concert/rocon_tools/license/LICENSE\n#\n\n##############################################################################\n# Imports\n##############################################################################\n\nimport rospy\nimport time\n\n##############################################################################\n# Wall Rate (Uses system time, independent of ros /clock)\n##############################################################################\n\nclass WallRate():\n\n def __init__(self, rate):\n '''\n @param rate : rate in hertz. If rate = 0, then won't sleep\n @type float\n '''\n self.rate = rate\n self.period = 1.0 / rate if rate > 0.0 else 0.0\n self.recorded_time = time.time() \n\n def sleep(self):\n current_time = time.time()\n elapsed = current_time - self.recorded_time\n if self.period - elapsed > 0:\n rospy.rostime.wallsleep(self.period - elapsed)\n self.recorded_time = time.time()\n","sub_path":"rocon_python_comms/src/rocon_python_comms/wall_rate.py","file_name":"wall_rate.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"408759602","text":"import sys\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler\nfrom sklearn.metrics import mean_absolute_error\nimport pandas as pd\nimport numpy as np\nimport xarray as xr\nimport argparse\nimport random\nimport yaml\nimport os\nfrom os.path import join, exists\nfrom datetime import datetime\nimport tensorflow as tf\n\nsys.path.append('../../')\n \nfrom holodecml.data import load_scaled_datasets\nfrom holodecml.models import Conv2DNeuralNetwork\nimport holodecml.ml_utils as ml\n\n\nscalers = {\"MinMaxScaler\": MinMaxScaler,\n \"MaxAbsScaler\": MaxAbsScaler,\n \"StandardScaler\": StandardScaler,\n \"RobustScaler\": RobustScaler}\n\nmetrics = {\"mae\": mean_absolute_error}\n\n\ndef main():\n \n # parse arguments from config/yaml file\n parser = argparse.ArgumentParser(description='Describe a Conv2D nn')\n parser.add_argument(\"config\", help=\"Path to config file\")\n args = parser.parse_args()\n with open(args.config) as config_file:\n config = yaml.load(config_file, Loader=yaml.FullLoader)\n\n path_data = config[\"path_data\"]\n path_save = config[\"path_save\"]\n if not os.path.exists(path_save):\n os.makedirs(path_save) \n seed = config[\"random_seed\"]\n np.random.seed(seed)\n random.seed(seed)\n tf.random.set_seed(seed)\n input_variable = config[\"input_variable\"]\n label_variable = config[\"label_variable\"]\n batch_size = config[\"conv2d_network\"][\"batch_size\"]\n \n # load data\n load_start = datetime.now()\n fns = [x for x in os.walk(path_data)][0][2]\n fn_train = [x for x in fns if 'training' in x][0]\n fn_valid = [x for x in fns if 'validation' in x][0]\n fn_test = [x for x in fns if 'test' in x][0]\n \n with xr.open_dataset(path_data+fn_train, chunks={'hologram_number': batch_size}) as ds:\n print(\"Loading TRAINING dataset\")\n\n if len(ds[input_variable].dims) == 4:\n train_inputs = ds[input_variable].transpose('hologram_number','xsize','ysize','input_channels')\n elif len(ds[input_variable].dims) == 3:\n train_inputs = ds[input_variable].transpose('hologram_number','rsize','input_channels')\n input_scaler = ml.MinMaxScalerX(train_inputs)\n train_inputs = input_scaler.fit_transform(train_inputs)\n print(f\"\\n\\ttrain_inputs.shape:{train_inputs.shape}\")\n \n train_outputs = ds[label_variable]\n output_scaler = ml.MinMaxScalerX(train_outputs)\n train_outputs = output_scaler.fit_transform(train_outputs)\n print(f\"\\n\\ttrain_outputs.shape:{train_outputs.shape}\")\n\n with xr.open_dataset(path_data+fn_valid, chunks={'hologram_number': batch_size}) as ds:\n print(\"Loading VALIDATION dataset\")\n\n if len(ds[input_variable].dims) == 4:\n valid_inputs = ds[input_variable].transpose('hologram_number','xsize','ysize','input_channels')\n elif len(ds[input_variable].dims) == 3:\n valid_inputs = ds[input_variable].transpose('hologram_number','rsize','input_channels')\n input_scaler = ml.MinMaxScalerX(valid_inputs)\n valid_inputs = input_scaler.fit_transform(valid_inputs)\n print(f\"\\n\\tvalid_inputs.shape:{valid_inputs.shape}\")\n \n valid_outputs = ds[label_variable]\n output_scaler = ml.MinMaxScalerX(valid_outputs)\n valid_outputs = output_scaler.fit_transform(valid_outputs)\n print(f\"\\n\\tvalid_outputs.shape:{valid_outputs.shape}\")\n print(f\"Loading datasets took {datetime.now() - load_start} time\")\n \n # train and save the model\n model_start = datetime.now()\n mod = Conv2DNeuralNetwork(**config[\"conv2d_network\"])\n hist = mod.fit(train_inputs, train_outputs,\n xv=valid_inputs, yv=valid_outputs)\n print(f\"Running model took {datetime.now() - model_start} time\")\n \n # predict outputs\n train_outputs_pred = mod.predict(train_inputs)\n valid_outputs_pred = mod.predict(valid_inputs) \n \n # save results\n print(\"Saving results and config file..\")\n mod.model.save(join(path_save, config[\"model_name\"]+\".h5\"))\n np.savetxt(join(path_save, \"train_outputs_pred.csv\"), train_outputs_pred)\n np.savetxt(join(path_save, \"valid_outputs_pred.csv\"), valid_outputs_pred) \n for k in hist.keys():\n np.savetxt(join(path_save, k+\".csv\"), hist[k])\n with open(join(path_save, 'config.yml'), 'w') as f:\n yaml.dump(config, f)\n \n return\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/ggantos/train_zdist_FT_radavg.py","file_name":"train_zdist_FT_radavg.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"248773701","text":"class Player(object):\n \"\"\"Gracz w grze strzelance\"\"\"\n def blast(self, enemy):\n print(\"Gracz razi wroga.\\n\")\n enemy.die()\n\n\nclass Alien(object):\n \"\"\"Obcy w grze strzelance\"\"\"\n def die(self):\n print(\"Obcy z trudem łapie oddech, 'To już koniec. Ale wielki koniec...\\n\"\n \"Tak, już robi się ciemno. Powiedz moim dwóm milionom larw, że je kochałem.\\n\"\n \"Żegnaj, okrutny Wszechświecie.\")\n\n\nprint(\"\\t\\tŚmierć obcego\\n\")\n\nhero = Player()\ninvader = Alien()\nhero.blast(invader)\n","sub_path":"pogromca_obcych.py","file_name":"pogromca_obcych.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"446296181","text":"'''\nCreated on Feb 3, 2015\n\n@author: lyx\n'''\n\nimport numpy as np;\nimport matplotlib.pyplot as plt\n\nn = 31;\nx0 = n // 2;\n'''\ntime = 1000000;\n\nber = np.random.random(time);\nchemin = ber > 0.5;\n\nans = [i for i in range(time + 1)];\n\nans[0] = x0;\nfor i in range(time):\n if (chemin[i]):\n ans[i + 1] = (ans[i] + 1) % n;\n else:\n ans[i + 1] = (ans[i] - 1) % n;\n \nprint(sum(ans) / (time + 1));\n\nplt.hist(ans, bins = 31);\nplt.title(\"Chemin aléatoire\");\nplt.xlabel(\"Distance\");\nplt.ylabel(\"Fréquence\");\nplt.show();\n'''\n\nseed = 2000;\n#time = n;\n#time = n * n // 5;\ntime = n * n;\n\nres = [i for i in range(seed)];\n\nfor j in range(seed):\n ber = np.random.random(time);\n chemin = ber > 0.5;\n \n ans = x0;\n for i in range(time):\n if (chemin[i]):\n ans = (ans + 1) % n;\n else:\n ans = (ans - 1) % n;\n \n res[j] = ans;\n \nplt.hist(res, bins = 31);\nplt.title(\"Chemin aléatoire à distance donnée\");\nplt.xlabel(\"Distance\");\nplt.ylabel(\"Fréquence\");\nplt.show();","sub_path":"PC1.py","file_name":"PC1.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"654532710","text":"from oodb_wrapper import OODBWrapper\nfrom oodb_wrapper import UnableToCreateExchangeException\nfrom oodb_wrapper import UnableToFindExchangeExeption\nfrom expa_wrapper import UnableToFindPersonException\nfrom expa_wrapper import UnableToFindApplicationException\nfrom expa_wrapper import EXPAWrapper\nfrom credentials_store import credentials\nfrom ep_csv_wrapper import EPCSVWrapper\nfrom op_csv_wrapper import OPCSVWrapper\nfrom whs_csv_wrapper import WHSCSVWrapper\nimport logging\nimport datetime\nimport sys\n\n\nclass StreamToLogger(object):\n \"\"\"\n Fake file-like stream object that redirects writes to a logger instance.\n \"\"\"\n\n def __init__(self, logger, log_level=logging.INFO):\n self.logger = logger\n self.log_level = log_level\n self.linebuf = ''\n\n def write(self, buf):\n for line in buf.rstrip().splitlines():\n self.logger.log(self.log_level, line.rstrip())\n\n\nclass Migrator:\n def __init__(self):\n self.oodb = OODBWrapper(credentials['oodb']['access_token'])\n self.expa = EXPAWrapper(credentials['expa']['user'], credentials['expa']['password'])\n self.ep_csv = EPCSVWrapper('EP_c.csv')\n self.op_csv = OPCSVWrapper('ICC_c.csv')\n self.whs_csv = WHSCSVWrapper('WHS_c.csv')\n self.invalid_ep_ids = []\n self.foreign_ep_ids = []\n\n @staticmethod\n def parse_opp_id(opp_url):\n if opp_url is not None and opp_url != '':\n opp_id = opp_url.rsplit('/', 1)[-1]\n if opp_id == '':\n opp_id = opp_url.rsplit('/')[-2]\n if opp_id == '':\n return None\n else:\n opp_id = None\n if opp_id is not None:\n try:\n int(opp_id)\n except ValueError:\n return None\n return opp_id\n\n def process_invalid_expa_id(self, expa_id):\n if expa_id in self.invalid_ep_ids:\n logging.info('Skipping person {0} because he/she does not exist!'.format(expa_id))\n elif expa_id in self.foreign_ep_ids:\n logging.info('Skipping person {0} because he/she is from another MC!'.format(expa_id))\n elif not self.expa.does_person_exist(expa_id):\n self.invalid_ep_ids.append(expa_id)\n logging.info(\n 'Skipping person {0} because he/she does not exist! Adding him/her to the blacklist...'.format(\n expa_id))\n elif not self.expa.is_person_from_mc(expa_id, 1596):\n self.foreign_ep_ids.append(expa_id)\n logging.info(\n 'Skipping person {0} because he/she is from another MC! Adding him/her to the blacklist...'.format(\n expa_id))\n else:\n logging.error('Skipping person {0} for unknown reasons...'.format(expa_id))\n\n def migrate(self, start_index=None, create_person=True, start_persons_with_sf_id=None, create_exchange=True,\n start_exchanges_with_sf_id=None, create_agb=True, create_op=True, create_whs=True):\n if create_op:\n ops = self.op_csv.get_ops()\n counter = 1\n for op in ops:\n logging.info('Processing OP {0}/{1}'.format(counter, len(ops)))\n self.oodb.create_op(op)\n counter += 1\n if create_whs:\n whs_list = self.whs_csv.get_whs()\n counter = 1\n for whs in whs_list:\n logging.info('Processing WHS {0}/{1}'.format(counter, len(whs_list)))\n self.oodb.create_whs(whs)\n counter += 1\n if create_person:\n existing_ids = self.oodb.get_existing_people()\n accounts = self.ep_csv.get_accounts()\n counter = 1\n total_accounts = len(accounts)\n try_all_accounts = start_persons_with_sf_id is None\n if not try_all_accounts:\n reached_start_id = False\n for sf_id, account in accounts.iteritems():\n logging.info('Processing account {0}/{1}'.format(counter, total_accounts))\n expa_id = account['expa_id']\n if not try_all_accounts and sf_id == start_persons_with_sf_id:\n reached_start_id = True\n if expa_id > 1 and expa_id not in existing_ids and (try_all_accounts or reached_start_id):\n try:\n email = self.expa.get_email(expa_id)\n self.oodb.create_person(expa_id, email, account)\n except UnableToFindPersonException:\n self.process_invalid_expa_id(expa_id)\n counter += 1\n if create_exchange or create_agb:\n existing_exchanges_sf_ids = self.oodb.get_sf_ids_for_existing_exchanges()\n existing_person_ids = self.oodb.get_existing_people()\n exchanges = self.ep_csv.get_exchanges()\n counter = 1\n try_all_exchanges = start_exchanges_with_sf_id is None\n if not try_all_exchanges:\n reached_start_id = False\n if start_index is not None:\n exchanges = exchanges[start_index:]\n counter = start_index\n for expa_id, exchange in exchanges.iteritems():\n logging.info('Processing exchange {0}/{1}'.format(counter, len(exchanges)))\n if expa_id in existing_person_ids:\n if create_exchange and exchange['sf_exchange_id'] not in existing_exchanges_sf_ids and (\n try_all_exchanges or reached_start_id):\n if not try_all_exchanges and exchange['sf_exchange_id'] == start_exchanges_with_sf_id:\n reached_start_id = True\n opp_url = exchange['opp_url']\n opp_id = Migrator.parse_opp_id(opp_url)\n if opp_id is not None:\n try:\n application_id = self.expa.get_application_id(expa_id, opp_id)\n except UnableToFindApplicationException:\n application_id = None\n else:\n application_id = None\n self.oodb.create_exchange(exchange, application_id)\n if create_agb:\n try:\n exchange_id = self.oodb.get_exchange_id(expa_id, exchange['sf_exchange_id'])\n self.create_agb(exchange, exchange_id)\n except UnableToFindExchangeExeption:\n logging.info('Skipping exchange {0}'.format(expa_id))\n else:\n logging.info('Person {0} does not exist, skipping this exchange...'.format(expa_id))\n counter += 1\n\n def create_agb(self, exchange, exchange_id):\n if exchange['agb']['signed']:\n sign_date = exchange['agb']['date']\n if sign_date is None or sign_date == '':\n sign_date = exchange['agb']['version']\n if sign_date is None or sign_date == '':\n logging.error('AGB has been marked as Confirmed but neither version nor sign date were found!')\n return\n self.oodb.sign_agb(exchange_id, sign_date)\n\n @staticmethod\n def is_ep_id_on_blacklist(expa_id):\n filenames = {'invalid_ep_ids.txt', 'foreign_ep_ids.txt'}\n for filename in filenames:\n current_file = open(filename, 'r')\n for line in current_file.readlines():\n if expa_id == line:\n return True\n return False\n\n\ndef main():\n logging.basicConfig(filename='migrator.log'.format(str(datetime.datetime.today().date())), level=logging.DEBUG,\n format='%(asctime)s %(levelname)-8s %(message)s')\n stdout_logger = logging.getLogger('')\n sl = StreamToLogger(stdout_logger, logging.INFO)\n sys.stdout = sl\n stderr_logger = logging.getLogger('')\n sl = StreamToLogger(stderr_logger, logging.ERROR)\n sys.stderr = sl\n migrator = Migrator()\n migrator.migrate(create_person=False, start_persons_with_sf_id=None, create_exchange=True,\n start_exchanges_with_sf_id=None, create_agb=True, create_op=False, create_whs=False)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"migrator.py","file_name":"migrator.py","file_ext":"py","file_size_in_byte":8386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"393151740","text":"__author__ = 'ephrom'\nimport tornado.web\nfrom db.database import open_session, Donation\nimport json\n\n\nclass DonationsHandler(tornado.web.RequestHandler):\n\n def initialize(self):\n self.session = open_session()\n\n def get(self):\n limit = 50\n offset = int(self.get_query_argument('p', default=0)) * limit\n donations = [dict(id=donation.id, name=donation.name, value=donation)\n for donation in self.session.query(Donation).limit(limit).offset(offset)]\n\n self.write(json.dumps(donations))\n\n\nclass DonationHandler(tornado.web.RequestHandler):\n\n def initialize(self):\n self.session = open_session()\n\n\n def get(self, id):\n donation = self.session.query(Donation).get(id)\n\n if donation is None:\n raise tornado.web.HTTPError(404)\n else:\n self.write(json.dumps(dict(id=donation.id, name=donation.name, value=donation.value,\n entity_id=donation.entity_id, person_id=donation.person_id)))\n\n\n def post(self):\n donation = Donation(id=self.get_body_argument('id'), name=self.get_body_argument('name'),\n value=self.get_body_argument('value'), entity_id=self.get_body_argument('entity_id'),\n person_id=self.get_body_argument('person_id'))\n self.session.add(donation)\n self.session.commit()\n\n def put(self, id):\n donation = self.session.query(Donation).get(id)\n\n if donation is None:\n raise tornado.web.HTTPError(404)\n else:\n donation.name = self.get_body_argument('name')\n self.session.add(donation)\n self.session.commit()\n\n def delete(self, id):\n donation = self.session.query(Donation).get(id)\n\n if donation is None:\n raise tornado.web.HTTPError(404)\n else:\n self.session.delete(donation)\n self.session.commit()\n\n","sub_path":"app/donation/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"447817503","text":"from flask import Flask,request,Response\nfrom botbuilder.core import BotFrameworkAdapter,BotFrameworkAdapterSettings,TurnContext,ConversationState,MemoryStorage\nfrom botbuilder.schema import Activity\nimport asyncio\nfrom herocard import SampleAnimationCard\n\n\napp = Flask(__name__)\nloop = asyncio.get_event_loop()\n\nbotsettings = BotFrameworkAdapterSettings(\"\",\"\")\nbotadapter = BotFrameworkAdapter(botsettings)\n\nCONMEMORY = ConversationState(MemoryStorage())\nbotdialog = SampleAnimationCard()\n\n\n@app.route(\"/api/messages\",methods=[\"POST\"])\ndef messages():\n if \"application/json\" in request.headers[\"content-type\"]:\n body = request.json\n else:\n return Response(status = 415)\n\n activity = Activity().deserialize(body)\n\n auth_header = (request.headers[\"Authorization\"] if \"Authorization\" in request.headers else \"\")\n\n async def call_fun(turncontext):\n await botdialog.on_turn(turncontext)\n\n task = loop.create_task(\n botadapter.process_activity(activity,auth_header,call_fun)\n )\n loop.run_until_complete(task)\n\n\nif __name__ == '__main__':\n app.run('localhost',3978)\n","sub_path":"Python_tutorial/13-HeroCard/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"479580500","text":"import numpy as np\nimport tensorflow as tf\nfrom skimage.transform import resize as imresize\n\nfrom cadl import vaegan\n\n\ndef load_vaegan(ckpt_name, sess):\n n_epochs=100\n filter_sizes=[3, 3, 3, 3]\n n_filters=[100, 100, 100, 100]\n crop_shape=[100, 100, 3]\n model = vaegan.VAEGAN(\n input_shape=[None] + crop_shape,\n convolutional=True,\n variational=True,\n n_filters=n_filters,\n n_hidden=None,\n n_code=64,\n filter_sizes=filter_sizes,\n activation=tf.nn.elu)\n saver = tf.train.Saver()\n ckpt_path = tf.train.latest_checkpoint(ckpt_name)\n if ckpt_path:\n saver.restore(sess, ckpt_path)\n print(\"VAE model restored.\")\n return model\n\n\ndef preprocess(img, crop_factor=0.8):\n crop = np.min(img.shape[:2])\n r = (img.shape[0] - crop) // 2\n c = (img.shape[1] - crop) // 2\n cropped = img[r:r + crop, c:c + crop]\n r, c, *d = cropped.shape\n if crop_factor < 1.0:\n amt = (1 - crop_factor) / 2\n h, w = int(c * amt), int(r * amt)\n cropped = cropped[h:-h, w:-w]\n rsz = imresize(cropped, (100, 100))\n return rsz\n","sub_path":"2_mdn_char_rnn/chars_vaegan.py","file_name":"chars_vaegan.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"557519785","text":"#!/bin/python3\n\nimport sys\n\n\ngrid = []\nfor grid_i in range(20):\n\tgrid_t = [int(grid_temp) for grid_temp in input().strip().split(' ')]\n\tgrid.append(grid_t)\n \ndy = [1, 1, 1, 0]\ndx = [-1, 0, 1, 1]\n\nm = len(grid)\nn = len(grid[0])\nres = 0\nfor i in range(0, m):\n for j in range(0, n):\n for k in range(0, 4):\n t = 1\n flag = True\n for l in range(0, 4):\n if (i + dx[k] * l >= 0) and (i + dx[k] * l < m) and (j + dy[k] * l >= 0) and (j + dy[k] * l < n):\n t *= grid[i + dx[k] * l][j + dy[k] * l]\n else:\n flag = False\n break\n res = max(res, t)\n\nprint(res)\n","sub_path":"11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"165944635","text":"import os.path\r\nimport re\r\n\r\ndef listitemclubbed(listName):\r\n sentence = listName\r\n sent_str = \"\"\r\n for i in sentence:\r\n sent_str += str(i) + '\\\\'\r\n sent_str = sent_str[:-1]\r\n return sent_str+'\\\\'\r\n\r\ndef file_Name_Path(pln_path,request_for):\r\n planfile_directory_split_list=[]\r\n\r\n if request_for==\"file_name\":\r\n planfile_directory_split_list= str(pln_path).split(\"\\\\\")\r\n planfile_Name=planfile_directory_split_list[-1]\r\n #print(\"{}\"+\"name is\".format(testORplan),planfile_Name)\r\n return planfile_Name\r\n if request_for==\"file_path\":\r\n planfile_directory_split_list = str(pln_path).split(\"\\\\\")\r\n path_name_list=planfile_directory_split_list[0:-1]\r\n planfile_path=listitemclubbed(path_name_list)\r\n #print(\"{}\"+\"path is\".format(testORplan),planfile_path)\r\n return planfile_path\r\ndef planfile_open_read(pln_file_name):\r\n #pln_file_cleaned=pln_file_name.replace(r\"\\\",'//')\r\n with open(pln_file_name,'r') as tfile_digger:\r\n for pln in tfile_digger.readlines():\r\n pln_TC=pln\r\n pln=pln.lower()\r\n if 'machine' in pln:\r\n print(pln)\r\n if len(pln) == 5 or len(pln) == 6 or len(pln) == 7:\r\n print(pln)\r\n if '.pln' in pln:\r\n try:\r\n plan_to_input=\"{}\".format(pln)\r\n plan_to_input_remove_n = plan_to_input.rstrip('\\n')\r\n print(\"[+] \",plan_to_input, end=\"\")\r\n #return plan_to_input\r\n with open(plan_to_input_remove_n, 'r') as pln_file:\r\n for tname in pln_file.readlines():\r\n if '.t' in tname:\r\n try:\r\n #print(tname)\r\n script_tname_split_list = tname.split(\":\")\r\n if len(script_tname_split_list)>=2:\r\n TC_Name = (script_tname_split_list[1]).rstrip()\r\n #print(\"\\t TC_Name is {}\".format(TC_Name))\r\n tfile_name = file_Name_Path(plan_to_input, 'file_path')\r\n complete_tC_path = tfile_name + TC_Name\r\n complete_tC_path = complete_tC_path.replace(\" \", \"\")\r\n if os.path.isfile(complete_tC_path):\r\n #print(\"\\t\\t TC_Path=\",complete_tC_path, end=\"\\n\")\r\n print(\"\\t[ ] \",complete_tC_path)\r\n if len(script_tname_split_list) <= 1:\r\n TC_Name = (script_tname_split_list[0]).rstrip()\r\n print(\"\\t TC_Name is {}\".format(TC_Name))\r\n tfile_name = file_Name_Path(plan_to_input, 'file_path')\r\n complete_tC_path = tfile_name + TC_Name\r\n complete_tC_path = complete_tC_path.replace(\" \", \"\")\r\n #print(\"\\t\",complete_tC_path)\r\n if os.path.isfile(complete_tC_path):\r\n #print(\"\\t\\t TC_Path=\", complete_tC_path,end=\"\\n\")\r\n print(\"\\t[ ] \", complete_tC_path)\r\n\r\n except:\r\n print('\\t Could not open the test file from the location {}'.format(complete_tC_path))\r\n except:\r\n print('Could not open the pln file from the location {}'.format(pln))\r\n if '.t' in pln:\r\n try:\r\n plan_to_input = \"{}\".format(pln)\r\n plan_to_input_remove_n = plan_to_input.rstrip('\\n')\r\n if os.path.isfile(plan_to_input_remove_n):\r\n # print(\"\\t\\t TC_Path=\", complete_tC_path,end=\"\\n\")\r\n print(plan_to_input_remove_n)\r\n except:\r\n print(\"Could not find the TC assigned under Pid in SCTM\")\r\n\r\n if ' TC' in pln_TC:\r\n try:\r\n plan_to_input = \"{}\".format(pln_TC)\r\n plan_to_input_remove_n = plan_to_input.rstrip('\\n')\r\n print(plan_to_input_remove_n)\r\n\r\n #if os.path.isfile(plan_to_input_remove_n)==False:\r\n # print(\"\\t\\t TC_Path=\", complete_tC_path,end=\"\\n\")\r\n\r\n #pass\r\n\r\n except:\r\n print(\"TC_Could not find the TC assigned under Pid in SCTM\")\r\n\r\n\r\nplanfile_open_read(\"Master_plan_feeder.txt\")\r\n#Master_plan_feeder.txt\r\n#BHC_Feeder_Masterplan.txt\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Master_Plan_creator.py","file_name":"Master_Plan_creator.py","file_ext":"py","file_size_in_byte":4916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"457523835","text":"import numpy as np\nimport aiaccix as aix\nimport time\nimport os\n# %%init session\nsess = aix.InferenceSession(\"./resnet50-v1-7.onnx\")\ninput_name = sess.get_inputs()[0].name\ninput_shape = sess.get_inputs()[0].shape\nprint(\"input_name is %s, input_shape is %s\"%(input_name,str(input_shape)))\n# %%test image, image size == [1,3,224,224]\ninput_image = np.random.random((1,3,224,224)).astype(np.float32)\n\n#warmup\nfor _ in range(10):\n pred_onnx = sess.run(None, {input_name: input_image})\n\n#test the inference time of input_image\nstart = time.time()\nfor _ in range(1000):\n pred_onnx = sess.run(None, {input_name: input_image})\nend = time.time()\nprint('shape is ',input_image.shape,', delta time: ',end-start,' ms')\n","sub_path":"aiacc_inference_onnx/resnet50v1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"365522405","text":"# Bubble Sort\n# Implement the bubble sort algorithm\n\n\ndef bubblesort(nums):\n if len(nums) < 2:\n return nums\n\n done = False\n\n while not done:\n done = True\n for i in range(0, len(nums)-1):\n if nums[i] > nums[i+1]:\n temp = nums[i+1]\n nums[i+1] = nums[i]\n nums[i] = temp\n done = False\n\n return nums\n\n\nprint(bubblesort([10, -2, 4, 1, 3, 5, -34, -19, 29]))\n","sub_path":"solutions/python/bubblesort.py","file_name":"bubblesort.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"312976977","text":"#导包\nimport unittest\nimport requests\n\n#设置测试类\nclass TestDepQueryByName(unittest.TestCase):\n def test_depQuery_byName(self):\n url = r'http://127.0.0.1:8000/api/departments/'\n params={\"dep_name\":\"Test学院\"}\n res = requests.get(url,params)\n self.assertEqual(200,res.status_code)\n\n def test_depQuery_byName_notExistsName(self):\n url = r'http://127.0.0.1:8000/api/departments/'\n params = {\"dep_name\": \"dadfadf\"}\n res = requests.get(url, params)\n self.assertEqual(200, res.status_code)\n\n if __name__ =='__main__':\n unittest.main()\n\n\n","sub_path":"test_cases/test_departments/test_depQyery_byName.py","file_name":"test_depQyery_byName.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"640917354","text":"import sys\nimport os\nimport json\n\ndef throw_err():\n\tprint\n\tsys.stdout.flush()\n\tsys.exit(0)\n\nif len(sys.argv) < 2:\n\tthrow_err()\nquery = sys.argv[1].lower()\nif not query:\n\tthrow_err()\n\ninfile=open(\"infile.txt\",\"w\")\ninfile.write(query)\ninfile.write('\\n')\ninfile.close()\n\nos.system('moses -f phrase-model/moses.ini < infile.txt > outfile.txt')\n\noutfile=open(\"outfile.txt\",\"r\")\nout=outfile.readline()[0:-1]\n\nsys.stdout.write(out)\nsys.stdout.flush()\nsys.exit(0)\n","sub_path":"server/pebble-translator.py","file_name":"pebble-translator.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"26887397","text":"\"\"\"\r\nThis is an automated way to upload multiple FPT test templates to CxAlloy.\r\n\r\nThere are several default options assumed. Ask JAD.\r\n\"\"\"\r\n\r\nfrom selenium import webdriver\r\nimport time\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport ctypes # used for user input pause to select project\r\nimport sys\r\n\r\ndriver = webdriver.Chrome(\r\n \"ADD PATH TO DRIVER HERE\")\r\n\r\n\r\nUN = sys.argv[1]\r\nPW = sys.argv[2]\r\n\r\n\r\ndef site_login():\r\n \"\"\"Navigate to login page, send login details.\"\"\"\r\n driver.get(\"https://tq.cxalloy.com/auth/login\")\r\n driver.find_element_by_xpath(\"//*[@id='username']\").send_keys(UN)\r\n driver.find_element_by_xpath(\"//*[@id='password']\").send_keys(PW)\r\n driver.find_element_by_id('login-button').click()\r\n\r\n\r\ndef select_project():\r\n \"\"\"Selecting project and navigate to test templates.\"\"\"\r\n ctypes.windll.user32.MessageBoxW(0, \"Click CxAlloy project in the browser then click OK to continue.\", \"Navigate to CxAlloy Project Dashboard\", 0x1000)\r\n driver.find_element_by_xpath(\"//*[@id='test']/a\").click() # tests\r\n time.sleep(1)\r\n driver.find_element_by_xpath(\r\n \"//*[@id='test-menu']/ul[1]/li[2]/a\").click() # test templates\r\n\r\n\r\ndef select_files():\r\n \"\"\"Get filepath of folder with excel docs from user.\"\"\"\r\n import tkinter as tk\r\n from tkinter import filedialog\r\n\r\n root = tk.Tk()\r\n root.withdraw()\r\n file_paths = list(filedialog.askopenfilenames(\r\n title=\"Select Functional Test Templates for Upload\"))\r\n return(file_paths)\r\n\r\n\r\ndef path_to_name(file_paths):\r\n \"\"\"Take the file paths and return the file names.\"\"\"\r\n import os\r\n file_names = []\r\n for path in file_paths:\r\n file_names.append(os.path.splitext(os.path.basename(path))[0])\r\n return(file_names)\r\n\r\n\r\ndef add_templates(file_name, file_path):\r\n \"\"\"Adding a new test template.\"\"\"\r\n driver.find_element_by_xpath(\r\n \"//*[@id='button-add-template']\").click() # add new\r\n time.sleep(1)\r\n # send title of test template\r\n driver.find_element_by_xpath(\r\n \"//*[@id='template-name']\").send_keys(file_name)\r\n # time.sleep(1) # unneeded?\r\n driver.find_element_by_xpath(\r\n \"//*[@id='button-submit-add-template']\").click() # add\r\n time.sleep(1)\r\n\r\n webelement = driver.find_element_by_xpath(\"//*[@id='project']/a\")\r\n # sends 14 tabs and one return\r\n webelement.send_keys(Keys.TAB * 14 + Keys.RETURN)\r\n\r\n time.sleep(1)\r\n driver.find_element_by_class_name('import-button').click() # import\r\n\r\n fancyboxFrame = driver.find_element_by_class_name(\r\n \"fancybox-iframe\") # finding the fancybox popup\r\n # switching the focus of selenium to the fancybox\r\n driver.switch_to.frame(fancyboxFrame)\r\n # clicking checkbox for \"background color to indicate headers\"\r\n driver.find_element_by_class_name(\"checkbox-label\").click()\r\n\r\n # this file path for upload and will need to be generated and changed in a loop\r\n driver.find_element_by_name(\"file\").send_keys(file_path)\r\n\r\n driver.find_element_by_class_name(\"submit\").click() # continue\r\n driver.find_element_by_class_name(\"submit\").click() # continue\r\n driver.find_element_by_class_name(\r\n \"import-select\").send_keys(\"D\") # Import as description\r\n driver.find_element_by_class_name(\"submit\").click() # continue\r\n driver.find_element_by_class_name(\"submit\").click() # continue\r\n driver.find_element_by_class_name(\"submit\").click() # continue\r\n\r\n\r\nsite_login()\r\nselect_project()\r\n\r\nfile_paths = select_files() # list of all selected file paths\r\nfile_names = path_to_name(file_paths) # list of all selected file names\r\n\r\nfor name, path in zip(file_names, file_paths): # add template for all files\r\n add_templates(name, path)\r\n","sub_path":"upload_fpts_public.py","file_name":"upload_fpts_public.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"185738351","text":"import time\nimport urlparse\nimport re\nfrom scrapy.http import Request\nfrom scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom topeka.items import TopekaItem\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\n\nclass SyncpSpider(BaseSpider):\n\tname = \"syncpress\"\n\tstart_urls = [\"http://www.syncplicity.com/about-us/press/\"]\n\n\tdef parse(self, response):\n\t\thxs = HtmlXPathSelector(response)\n\t\ttitles = hxs.xpath(\"//div[@class='record']\")\n\t\titems = []\n\t\tcount = 0\n\t\tfor titles in titles:\n\t\t\titem = TopekaItem()\n\t\t\titem[\"initial_url\"] = self.start_urls\n\t\t\titem[\"headline_name\"] = titles.xpath(\"a/text()\").extract()\n\t\t\titem[\"publish_date\"] = (re.search(r'(Jan\\ \\d+, \\d+|Feb\\ \\d+, \\d+|Mar\\ \\d+, \\d+|Apr\\ \\d+, \\d+|May\\ \\d+, \\d+|Jun\\ \\d+, \\d+|Jul\\ \\d+, \\d+|Aug\\ \\d+, \\d+|Sep\\ \\d+, \\d+|Oct\\ \\d+, \\d+|Nov\\ \\d+, \\d+|Dec\\ \\d+, \\d+)', str(titles.xpath(\"b/text()\").extract()))).group(1)\n\t\t\tif item[\"publish_date\"]:\n\t\t\t\titem[\"date_found\"] = \"Yes\"\n\t\t\telse:\n\t\t\t\titem[\"date_found\"] = \"No\"\n\t\t\titem[\"scanned_date\"] = time.strftime(\"%d/%m/%Y\")\t\t\t\n\t\t\titem[\"url\"] = titles.xpath(\"a/@href\").extract() or \"url\"\n\t\t\tcount = count + 1\n\t\t\tfor i in item[\"url\"]:\n\t\t\t\tyield Request(urlparse.urljoin(\"http:/\", i), meta={'item': item, 'count': count}, callback=self.parse_body)\n\n\tdef parse_body(self, response):\n\t\thxss = HtmlXPathSelector(response)\n\t\titem = response.request.meta['item']\n\t\tcount = response.request.meta['count']\n\t\titems = []\n\t\ttemp = hxss.xpath(\"//div[@class='span8 records_container article pull-right']/p/text()\").extract() or hxss.xpath(\"//div[@class='entry-content']/p/text()\").extract()\n\t\tif temp:\n\t\t\tf = open('body_%s_%d.txt' % (self.name, count), 'w+b')\n\t\t\titem[\"body\"] = f.name\n\t\telse:\n\t\t\treturn\n\t\tfor i in temp:\n\t\t\tf.write(i.encode('utf-8'))\n\t\titems.append(item)\n\t\treturn items\n","sub_path":"News_Scraping/Demo/Demo/spiders/topeka/spiders/syncpress.py","file_name":"syncpress.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"542491980","text":"#\n# The Multiverse Platform is made available under the MIT License.\n#\n# Copyright (c) 2012 The Multiverse Foundation\n#\n# Permission is hereby granted, free of charge, to any person \n# obtaining a copy of this software and associated documentation \n# files (the \"Software\"), to deal in the Software without restriction, \n# including without limitation the rights to use, copy, modify, \n# merge, publish, distribute, sublicense, and/or sell copies \n# of the Software, and to permit persons to whom the Software \n# is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be \n# included in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES \n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE \n# OR OTHER DEALINGS IN THE SOFTWARE.\n#\n#\n\nfrom multiverse.mars import *\nfrom multiverse.mars.objects import *\nfrom multiverse.mars.core import *\nfrom multiverse.mars.events import *\nfrom multiverse.mars.util import *\nfrom multiverse.mars.plugins import *\nfrom multiverse.server.plugins import *\nfrom multiverse.server.math import *\nfrom multiverse.server.events import *\nfrom multiverse.server.objects import *\nfrom multiverse.server.engine import *\nfrom java.lang import *\n\nmeshInfo = { \"casual07_f_mediumpoly.mesh\" : [[ \"casual07_f_mediumpoly-mesh.0\", \"casual07_f_mediumpoly.body\" ],\n [ \"casual07_f_mediumpoly-mesh.1\", \"casual07_f_mediumpoly.hair_transparent\" ]],\n \"casual06_f_mediumpoly.mesh\" : [[ \"casual06_f_mediumpoly-mesh.0\", \"casual06_f_mediumpoly.body\" ],\n [ \"casual06_f_mediumpoly-mesh.1\", \"casual06_f_mediumpoly.hair_transparent\" ]],\n \"casual15_f_mediumpoly.mesh\" : [[ \"casual15_f_mediumpoly-mesh.0\", \"casual15_f_mediumpoly.body\" ],\n [ \"casual15_f_mediumpoly-mesh.1\", \"casual15_f_mediumpoly.hair_transparent\" ]],\n \"casual19_f_mediumpoly.mesh\" : [[ \"casual19_f_mediumpoly-mesh.0\", \"casual19_f_mediumpoly.body\" ],\n [ \"casual19_f_mediumpoly-mesh.1\", \"casual19_f_mediumpoly.hair_transparent\" ]],\n \"casual21_f_mediumpoly.mesh\" : [[ \"casual21_f_mediumpoly-mesh.0\", \"casual21_f_mediumpoly.body\" ],\n [ \"casual21_f_mediumpoly-mesh.1\", \"casual21_f_mediumpoly.hair_transparent\" ]],\n \"business04_f_mediumpoly.mesh\" : [[ \"business04_mediumpoly-mesh.0\", \"business04_f_mediumpoly.body\" ],\n [ \"business04_mediumpoly-mesh.1\", \"business04_f_mediumpoly.hair_transparent\" ]],\n \"sportive01_f_mediumpoly.mesh\" : [[ \"sportive01_f_mediumpoly-mesh.0\", \"sportive01_f_mediumpoly.body\" ],\n [ \"sportive01_f_mediumpoly-mesh.1\", \"sportive01_f_mediumpoly.hair_transparent\" ]],\n \"sportive02_f_mediumpoly.mesh\" : [[ \"sportive02_f_mediumpoly-mesh.0\", \"sportive02_f_mediumpoly.body\" ],\n [ \"sportive02_f_mediumpoly-mesh.1\", \"sportive02_f_mediumpoly.hair_transparent\" ]],\n \"sportive05_f_mediumpoly.mesh\" : [[ \"sportive05_f_mediumpoly-mesh.0\", \"sportive05_f_mediumpoly.body\" ],\n [ \"sportive05_f_mediumpoly-mesh.1\", \"sportive05_f_mediumpoly.hair_transparent\" ]],\n \"sportive07_f_mediumpoly.mesh\" : [[ \"sportive07_f_mediumpoly-mesh.0\", \"sportive07_f_mediumpoly.body\" ]],\n \"casual03_m_mediumpoly.mesh\" : [[ \"casual03_m_medium-mesh.0\", \"casual03_m_mediumpoly.body\" ]],\n \"casual04_m_mediumpoly.mesh\" : [[ \"casual04_m_mediumpoly-mesh.0\", \"casual04_m_mediumpoly.body\" ]],\n \"casual07_m_mediumpoly.mesh\" : [[ \"casual07_m_mediumpoly-mesh.0\", \"casual07_m_mediumpoly.body\" ]],\n \"casual10_m_mediumpoly.mesh\" : [[ \"casual10_m_mediumpoly-mesh.0\", \"casual10_m_mediumpoly.body\" ]],\n \"casual16_m_mediumpoly.mesh\" : [[ \"casual16_m_mediumpoly-mesh.0\", \"casual16_m_mediumpoly.body\" ]],\n \"casual21_m_mediumpoly.mesh\" : [[ \"casual21_m_mediumpoly-mesh.0\", \"casual21_m_mediumpoly.body\" ]],\n \"business03_m_mediumpoly.mesh\" : [[ \"business03_m_medium-mesh.0\", \"business03_m_mediumpoly.body\" ]],\n \"business05_m_mediumpoly.mesh\" : [[ \"business05_m_mediumpoly-mesh.0\", \"business05_m_mediumpoly.body\" ]],\n \"sportive01_m_mediumpoly.mesh\" : [[ \"sportive01_m_mediumpoly-mesh.0\", \"sportive01_m_mediumpoly.body\" ]],\n \"sportive09_m_mediumpoly.mesh\" : [[ \"sportive09_m_mediumpoly-mesh.0\", \"sportive09_m_mediumpoly.body\" ]] }\n\ndisplayContext = DisplayContext(\"casual07_f_mediumpoly.mesh\", True)\n\n# default player template\nplayer = Template(\"MVSocialPlayer\")\n\nplayer.put(WorldManagerClient.NAMESPACE,\n WorldManagerClient.TEMPL_DISPLAY_CONTEXT,\n displayContext)\n\nplayer.put(WorldManagerClient.NAMESPACE,\n WorldManagerClient.TEMPL_OBJECT_TYPE,\n ObjectTypes.player)\n\nObjectManagerClient.registerTemplate(player)\n\n# character factory\nclass MVSocialFactory (CharacterFactory):\n def createCharacter(self, worldName, uid, properties):\n ot = Template()\n\n name = properties.get(\"characterName\");\n\n # get the account name for this player\n if not name:\n db = Engine.getDatabase()\n name = db.getUserName(uid)\n if not name:\n name = \"default\"\n\n # set the spawn location\n loc = Point(368917, 71000, 294579)\n\n meshName = properties.get(\"model\")\n gender = properties.get(\"sex\")\n\n if meshName:\n displayContext = DisplayContext(meshName, True)\n submeshInfo = meshInfo[meshName]\n for entry in submeshInfo:\n displayContext.addSubmesh(DisplayContext.Submesh(entry[0],\n entry[1]))\n ot.put(WorldManagerClient.NAMESPACE,\n WorldManagerClient.TEMPL_DISPLAY_CONTEXT, displayContext)\n\n # get default instance oid\n instanceOid = InstanceClient.getInstanceOid(\"default\")\n if not instanceOid:\n Log.error(\"MVSocialFactory: no 'default' instance\")\n properties.put(\"errorMessage\", \"No default instance\")\n return 0\n\n # override template\n ot.put(WorldManagerClient.NAMESPACE,\n WorldManagerClient.TEMPL_NAME, name)\n ot.put(WorldManagerClient.NAMESPACE,\n WorldManagerClient.TEMPL_INSTANCE, Long(instanceOid))\n ot.put(WorldManagerClient.NAMESPACE,\n WorldManagerClient.TEMPL_LOC, loc)\n ot.put(Namespace.OBJECT_MANAGER,\n ObjectManagerClient.TEMPL_PERSISTENT, Boolean(True));\n\n restorePoint = InstanceRestorePoint(\"default\", loc);\n restorePoint.setFallbackFlag(True);\n restoreStack = LinkedList();\n restoreStack.add(restorePoint);\n ot.put(Namespace.OBJECT_MANAGER,\n ObjectManagerClient.TEMPL_INSTANCE_RESTORE_STACK, restoreStack)\n ot.put(Namespace.OBJECT_MANAGER,\n ObjectManagerClient.TEMPL_CURRENT_INSTANCE_NAME, \"default\")\n\n # generate the object\n objOid = ObjectManagerClient.generateObject(\"MVSocialPlayer\", ot)\n Log.debug(\"MVSocialFactory: generated obj oid=\" + str(objOid))\n return objOid\n\nmvSocialFactory = MVSocialFactory()\nLoginPlugin.getCharacterGenerator().setCharacterFactory(mvSocialFactory)\n","sub_path":"server/config/mv_social/character_factory.py","file_name":"character_factory.py","file_ext":"py","file_size_in_byte":7935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"456253495","text":"# label encoding\r\n# scalling \r\n\r\nimport os\r\nfrom re import split\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport argparse\r\nimport yaml\r\nimport logging\r\n\r\n# configuring logging operations\r\nlogging.basicConfig(filename='Logs/loggs.log', level=logging.INFO,\r\n format='%(levelname)s:%(asctime)s:%(message)s')\r\n\r\ndef read_params(config_path):\r\n\twith open(config_path) as yaml_file:\r\n\t\tconfig = yaml.safe_load(yaml_file)\r\n\treturn config\r\n\r\ndef label_encoding(config_path):\r\n\tconfig =read_params (config_path)\r\n\ttrain_data_path=config[\"encoder\"][\"train_path\"]\r\n\ttest_data_path=config[\"encoder\"][\"test_path\"]\r\n\tsource_train_data_path=config[\"split_data\"][\"train_path\"]\r\n\tsource_test_data_path=config[\"split_data\"][\"test_path\"]\r\n\t\r\n\ttrain=pd.read_csv(source_train_data_path)\r\n\ttest=pd.read_csv(source_test_data_path)\r\n\tencoder =LabelEncoder()\r\n\tfor column in range(len(train.columns)):\r\n\t\ttrain[train.columns[column]]= encoder.fit_transform(train[train.columns[column]])\r\n\t\ttrain.to_csv(train_data_path,index=False)\r\n\tlogging.info('Encoding was done for train data ')\r\n\t\t\r\n\tencoder = LabelEncoder()\r\n\tfor column in range(len(test.columns)):\r\n\t\ttest[test.columns[column]]= encoder.fit_transform(test[test.columns[column]])\r\n\t\ttest.to_csv(test_data_path,index=False)\r\n\tlogging.info('Encoding was done for test data ')\r\n\r\nif __name__ ==\"__main__\":\r\n args = argparse.ArgumentParser()\r\n args.add_argument(\"--config\", default=\"params.yaml\")\r\n parsed_args = args.parse_args()\r\n label_encoding(config_path=parsed_args.config)","sub_path":"src/data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"581697780","text":"import numpy as np\nfrom PymoNNto.NetworkCore.Base import *\nfrom numpy.random import *\n\nclass Behaviour(NetworkObjectBase):\n #modificaton_reset_vars = []\n run_on_init = False\n\n def __init__(self, **kwargs):\n self.init_kwargs = kwargs\n self.used_attr_keys = []\n self.behaviour_enabled = self.get_init_attr('behaviour_enabled', True, None)\n super().__init__(tag=self.get_init_attr('tag', None, None))\n\n def run_on_neuron_init(self):\n self.run_on_neuron_init_var = True\n return self\n\n def diversity_string_to_vec(self, ds, neurons):\n\n if 'same(' in ds and ds[-1] == ')':\n params=ds[5:-1].replace(' ', '').split(',')\n if len(params) == 2:\n #print('same', params)\n return getattr(neurons[params[0], 0], params[1])\n\n command = ds.split(';')\n if (not '(' in ds and not ')' in ds) and not command[0].replace('.', '').replace('+', '').replace('-', '').isdigit():\n return ds\n\n\n if len(command) == 1:\n if command[0].replace('.', '').replace('+', '').replace('-', '').isdigit():\n result = float(command[0])\n\n #else:\n # result = self.get_random_nparray((neurons.size), rnd_code=command[0])\n #print(result, type(result))\n return result\n\n dist_cmd='uniform(low, high)'\n if len(command) > 2 and not 'plot' in command[2]:# problem: , also in command\n dist_cmd=command[2]\n\n if 'smooth' in command[2]:\n smoothing = float(command[2].replace('smooth', ''))\n dist_cmd = 'np.sum([uniform(low, high, size=dim) for _ in range(smoothing)], axis=0)/smoothing'.replace('smoothing', str(smoothing))\n\n\n if command[0].replace('.', '').replace('+', '').replace('-', '').isdigit():\n min_v = float(command[0])\n if '%' in command[1]:\n max_v = min_v\n if '-' in command[1]:\n min_v -= min_v / 100 * float(command[1].replace('+', '').replace('-', '').replace('%', ''))\n if '+' in command[1]:\n max_v += max_v / 100 * float(command[1].replace('+', '').replace('-', '').replace('%', ''))\n else:\n max_v = float(command[1])\n\n dist_cmd=dist_cmd.replace('low',str(min_v)).replace('high',str(max_v)).replace('min_v',str(min_v)).replace('max_v',str(max_v)).replace('min',str(min_v)).replace('max',str(max_v))\n else:\n dist_cmd=command[0]\n\n if 'lognormal_real_mean' in command[0]:\n parts = command[0].replace(')', '').replace(' ', '').split('(')\n arguments = parts[1].split(',')\n mean = float(arguments[0])\n sigma = float(arguments[1])\n mu = -np.power(sigma, 2) + np.log(mean)\n dist_cmd = 'lognormal({}, {})'.format(mu, sigma)\n\n result=self.get_random_nparray((neurons.size), rnd_code=dist_cmd)\n\n\n if 'plot' in command[-1]:\n import matplotlib.pyplot as plt\n #print(result)\n plt.hist(result, bins=30)\n plt.show()\n\n\n return result\n\n def set_init_attrs_as_variables(self, object):\n for key in self.init_kwargs:\n setattr(object, key, self.get_init_attr(key, None, neurons=object))\n print('init', key)\n #get_init_attr\n\n def check_unused_attrs(self):\n for key in self.init_kwargs:\n if not key in self.used_attr_keys:\n print('Warning: \"'+key+'\" not used in set_variables of '+str(self)+' behaviour! Make sure that \"'+key+'\" is spelled correctly and get_init_attr('+key+',...) is called in set_variables. Valid attributes are:'+str(self.used_attr_keys))\n\n def get_init_attr(self, key, default, neurons=None, do_not_diversify=False, search_other_behaviours=False):\n self.used_attr_keys.append(key)\n\n result = self.init_kwargs.get(key, default)\n\n if key not in self.init_kwargs and neurons is not None and search_other_behaviours:\n for b in neurons.behaviours:\n if key in b.init_kwargs:\n result = b.init_kwargs.get(key, result)\n\n if not do_not_diversify and type(result) is str and neurons is not None:\n result = self.diversity_string_to_vec(result, neurons)\n\n return result\n\n def set_variables(self, neurons):\n return\n\n def reset(self):\n return\n\n def new_iteration(self, neurons):\n return\n\n #def get_shared_variable(self, name):\n # return None\n\n\n\n def initialize_synapse_attr(self, target_attr, density, equal_range, random_range, neurons, synapse_type, all_neurons_same=False):\n for s in neurons.afferent_synapses[synapse_type]:\n s.enabled *= s.get_random_synapse_mat(density, all_neurons_same) > 0.0\n setattr(s, target_attr, s.enabled*(s.get_synapse_mat()+equal_range+s.get_random_synapse_mat(1.0, all_neurons_same)*random_range))#s.shape_mat*#neurons.GABA_strength+neurons.min_GABA_strength\n\n\n\n\n\n","sub_path":"NetworkCore/Behaviour.py","file_name":"Behaviour.py","file_ext":"py","file_size_in_byte":5083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"196410081","text":"import numpy as np\nimport copy\ndef separate_into_classes(valid_y, args):\n unique, counts = np.unique(valid_y, return_counts=True)\n print(unique)\n print(counts)\n sorted_y = copy.deepcopy(valid_y)\n sorted_index_y = np.argsort(np.squeeze(sorted_y))\n\n valid_dist=[]\n\n for i in range(args.num_classes):\n print(i)\n valid_dist.append(sorted_index_y[sum(counts[:i]):sum(counts[:i+1])])\n\n \n return valid_dist","sub_path":"utils/separate_into_classes.py","file_name":"separate_into_classes.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"273082269","text":"import re\nfrom datetime import datetime\n\nfrom django.contrib.auth import authenticate, login\nfrom django.shortcuts import render\nfrom django.contrib.auth.models import User\nfrom django.http import Http404\nfrom django.shortcuts import render_to_response\n\nfrom .models import *\n\nimport pinyin\n\nfrom .forms import *\nfrom django.shortcuts import render, redirect\nfrom django.core.context_processors import csrf\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n new_user = form.save()\n new_user.first_name = cd['first_name']\n new_user.last_name = cd['last_name']\n new_user.email = cd['username']\n new_user.save()\n aDomain = pinyin.get('-'.join(cd['first_name'] + cd['last_name']))\n regex = '^' + aDomain + '(-\\d+)?'\n same_name = AccountModel.objects.filter(\n aDomain__regex=regex).order_by('-aUser__id')\n if not same_name:\n p = AccountModel(aUser=new_user, aDomain=aDomain)\n else:\n the_last = same_name[0].aDomain\n regex1 = re.compile('^' + aDomain + '$')\n regex2 = re.compile('^' + aDomain + '-(\\d+)')\n match1 = re.match(regex1, the_last)\n match2 = re.match(regex2, the_last)\n if match1:\n p = AccountModel(aUser=new_user, aDomain=aDomain + '-1')\n else:\n match2.group(1)\n p = AccountModel(\n aUser=new_user, aDomain=aDomain + '-' + str(int(match2.group(1)) + 1))\n p.save()\n return redirect(\"/register\")\n else:\n form = UserCreationForm()\n ctx = {'form': form}\n ctx.update(csrf(request))\n return render(request, \"register.html\", ctx)\n\n\ndef user_login(request):\n if request.method == 'POST':\n username = request.POST.get('email')\n password = request.POST.get('password')\n user = authenticate(username=username, password=password)\n if user is not None and user.is_active:\n login(request, user)\n return redirect(\"/\")\n else:\n return redirect(\"/admin\")\n else:\n form = LoginForm()\n ctx = {'form': form}\n ctx.update(csrf(request))\n return render(request, \"register.html\", ctx)\n\n\ndef display_topic(request, tId):\n\n topic = TopicModel.objects.get(id=tId)\n if not topic:\n raise Http404\n return render_to_response('display_topic.html', {'user': request.user, 'topic': topic})\n\n\ndef display_account(request, aDomain):\n account = AccountModel.objects.get(aDomain=aDomain)\n if not account:\n raise Http404\n return render_to_response('display_account.html', {'account': account})\n\n\ndef display_question(request, qId):\n question = QuestionModel.objects.get(qId=qId)\n try:\n asked = len(question.answers.all().filter(aOwner=request.user))\n except KeyError:\n asked = 0\n if not question:\n raise Http404\n if request.method == 'POST':\n form = request.POST\n aTime = datetime.now()\n aOwner = request.user\n aContent = form.get('answer')\n aQuestion = QuestionModel.objects.get(qId=qId)\n new_answer = AnswerModel(aTime=aTime, aOwner=aOwner.account, aContent=aContent, aQuestion=aQuestion)\n new_answer.save()\n return render_to_response('display_question.html', {'user': request.user, 'question': question, 'asked': asked})\n else:\n ctx = {'user': request.user, 'question': question, 'asked': asked}\n ctx.update(csrf(request))\n return render(request, \"display_question.html\", ctx)\n\n\ndef followed_topics(request):\n pass\n\n\ndef show_topics(request):\n pass\n\n\ndef ask_question(request):\n if request.method == 'POST':\n form = request.POST\n qTitle = form.get('title')\n qContent = form.get('content')\n qTime = datetime.now()\n qOwner = request.user\n new_question = QuestionModel(qId = 0, qTitle=qTitle, qContent=qContent, qTime=qTime, qOwner=qOwner.account)\n new_question.save()\n new_question.qId += new_question.id + 19550224\n topics = form.get('hidden-topics').split(',')\n for i in topics:\n new_question.qTopic.add(TopicModel.objects.get(tName=i))\n new_question.qFollower.add(request.user.account)\n new_question.save()\n return redirect('/display_question/{}'.format(new_question.qId))\n else:\n c = {}\n c.update(csrf(request))\n return render(request, \"ask_question.html\", c)\n","sub_path":"quora/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"51383555","text":"import pytest\nfrom typing import Dict, Union, Any\n\nfrom skjold.sources.github import GithubSecurityAdvisory, Github\n\n\n@pytest.fixture\ndef github_advisory() -> Dict[str, Union[str, Dict]]:\n return {\n \"cursor\": \"...\",\n \"node\": {\n \"advisory\": {\n \"ghsaId\": \"GHSA-p5wr-vp8g-q5p4\",\n \"publishedAt\": \"2018-07-12T14:45:15Z\",\n \"summary\": \"Moderate severity vulnerability that affects Plone\",\n },\n \"firstPatchedVersion\": {\"identifier\": \"4.3.12\"},\n \"package\": {\"ecosystem\": \"PIP\", \"name\": \"Plone\"},\n \"severity\": \"MODERATE\",\n \"updatedAt\": \"2018-07-11T19:41:00Z\",\n \"vulnerableVersionRange\": \">= 4.0, < 4.3.12\",\n },\n }\n\n\ndef test_ensure_using_build_obj(github_advisory: Dict) -> None:\n obj = GithubSecurityAdvisory.using(github_advisory)\n\n assert obj.package_name == \"Plone\"\n assert obj.identifier == \"GHSA-p5wr-vp8g-q5p4\"\n assert obj.source == \"github\"\n assert \"Moderate\" in obj.summary\n assert obj.severity == \"MODERATE\"\n assert obj.first_patched_version == \"4.3.12\"\n assert obj.vulnerable_versions == \">=4.0,<4.3.12\"\n assert obj.ecosystem == \"PIP\"\n\n\ndef test_ensure_is_affected_example(github_advisory: Dict) -> None:\n obj = GithubSecurityAdvisory.using(github_advisory)\n assert obj.package_name == \"Plone\"\n\n assert obj.is_affected(\"4.3.12\") is False\n assert obj.is_affected(\"4.1\") is True\n assert obj.is_affected(\"4.0\") is True\n assert obj.is_affected(\"3.0\") is False\n\n\ndef test_ensure_accessing_advisories_triggers_update(\n cache_dir: str, mocker: Any\n) -> None:\n source = Github(cache_dir, 3600)\n assert len(source._advisories) == 0\n\n spy = mocker.spy(source, \"update\")\n assert len(source.get_security_advisories()) > 100\n assert spy.assert_called\n assert source.total_count > 100\n","sub_path":"tests/test_github.py","file_name":"test_github.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"316110803","text":"#-*- coding:utf-8 -*-\nfrom flask import Flask, request, jsonify, json, g\n\nimport sqlite3\nimport logging\nimport datetime\n\n\n\n\nfrom backend10s.manager import message\nfrom backend10s.manager import s3 as s3_manager\nfrom backend10s.manager import database\nfrom backend10s.backend10s_blueprint import backend10s as app\n\nmessage_manager = message.MessageManager()\ndb_manager = database.DatabseManager(\"10s.db\")\n\ndef json_message(message):\n return jsonify({\"message\": message})\n\n@app.route(\"/api/auth\", methods=[\"GET\", \"POST\"])\ndef auth():\n # join: addUser\n if request.method == 'POST':\n body = request.json\n email = body[\"email\"]\n nickname = body['nickname']\n profile_image = body['profile_image']\n\n token = hash(email)\n db_manager.add_user(email, nickname, profile_image, token)\n\n auth_token = {'auth_token': token}\n return jsonify(auth_token), 200\n\n # login: getUser\n else: #request.method == 'GET':\n user_email = request.headers['email']\n auth_token = db_manager.check_user(user_email)\n if auth_token == None:\n return jsonify(message=\"Not Exist User\"), 400\n\n result_json = {'auth_token': auth_token[0]}\n return jsonify(result_json), 200\n \n\n@app.route(\"/api/chatRoom\", methods=[\"GET\", \"POST\", \"PUT\", \"DELETE\"])\ndef chat_room():\n #try:\n # create a chat_room\n if request.method == 'POST':\n auth_token = request.headers[\"Authorization\"].split()[1]\n user_id = db_manager.get_user_id(auth_token)\n\n body = request.json\n room_name = body['room_name']\n time_created = datetime.datetime.now()\n\n db_manager.create_chatroom(room_name, time_created, user_id)\n\n return json_message(\"chat_room created\"), 200\n\n ## get chat_room that user is in\n elif request.method == 'GET':\n auth_token = request.headers[\"Authorization\"].split()[1]\n user_id = db_manager.get_user_id(auth_token)\n \n room_infos = db_manager.get_room_infos(user_id)\n\n room_infos_json = list()\n \n for room_info in room_infos:\n room_infos_json.append({\"room_id\":room_info[0], \"room_name\":room_info[1]})\n \n return jsonify(room_infos_json), 200\n\n # delete chat_room\n elif request.method == 'DELETE':\n body = request.json\n room_id = body['room_id']\n auth_token = request.headers[\"Authorization\"].split()[1]\n user_id = db_manager.get_user_id(auth_token)\n \n db_manager.out_chatroom(room_id, user_id)\n\n db_manager.check_delete_room(room_id)\n\n return json_message(\"exit successfully\"), 200\n\n\n # invite friend to chat_room\n elif request.method == 'PUT':\n body = request.json\n room_id = body['room_id']\n invited_id = body['invited_id']\n db_manager.update_chatuser(room_id, invited_id)\n\n return json_message(\"friend invited\"), 200\n\n\n@app.route(\"/api/friend\", methods=[\"GET\", \"POST\"])\ndef friend():\n auth_token = request.headers[\"Authorization\"].split()[1]\n user_id = db_manager.get_user_id(auth_token)\n\n # search friend\n if request.method == 'GET':\n friend_infos = db_manager.get_friend_info(user_id)\n friends = []\n for friend_info in friend_infos:\n friend = {'id': friend_info[0], 'nickname': friend_info[1], 'profile_image': friend_info[2], 'status_message': friend_info[3]}\n friends.append(friend)\n\n dic = { 'friends' : friends }\n return json.dumps(dic, ensure_ascii=False), 200\n\n\n@app.route(\"/api/profile/\", methods=[\"GET\"])\ndef get_profile(user_id):\n user_profile = db_manager.get_user_profile(user_id)\n return json.dumps(user_profile, ensure_ascii=False)\n\n\n@app.route(\"/api/profile\", methods=[\"GET\", \"PUT\"])\ndef profile():\n auth_token = request.headers[\"Authorization\"].split()[1]\n user_id = db_manager.get_user_id(auth_token)\n \n # get profile\n if request.method == 'GET':\n # 내 프로필 정보\n return get_profile(user_id)\n\n # update profile\n elif request.method == 'PUT':\n new_nickname = request.form['nickname']\n new_status = request.form['status_message']\n image_file = request.files['profile_image']\n new_image_path = s3_manager.upload_file(image_file, user_id, \"10s-profile\", image_file.filename)\n db_manager.update_user_profile(new_nickname, new_status, new_image_path, user_id)\n \n return json_message(\"user updated\"), 200\n\n\n#when message is received from client\n@app.route(\"/api/chatRoom//message\", methods = ['POST', 'GET'])\ndef receive(id):\n if request.method == 'POST':\n auth_token = request.headers[\"Authorization\"].split()[1]\n user_id = db_manager.get_user_id(auth_token)\n\n #upload file onto S3\n f = request.files['file']\n path = s3_manager.upload_file(f, id, '10s-voice', f.filename)\n\n order = message_manager.countMessage(id) + 1\n message = {\"index\" : order, \n \"sender\" : user_id,\n \"receiver\" : id, \n \"content\" : path,\n \"date\" : datetime.datetime.now()}\n message_manager.pushMessage(id, message)\n return json_message(\"success\"), 200\n\n else:\n result = message_manager.getMessage(id)\n return jsonify({\"messages\": result}), 200\n\n\n#bring messages with index\n@app.route(\"/api/chatRoom//message/\", methods = ['GET'])\ndef bring(id, start):\n result = message_manager.getMessage(id, start)\n return jsonify({\"messages\": result}), 200\n\n","sub_path":"Python_10s/backend10s/controller/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"113570233","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@name: multichoice.py\n@editor: PyCharm\n@Date: 2019/2/27 13:13\n@Author: ly\n@Description: 多项选择导入\n\"\"\"\nimport re\nimport uuid\nimport sqlite3\nimport xlrd\n\ncon = sqlite3.connect('../data.db')\n\nwb = xlrd.open_workbook('F:/aa/multi_and_short2019.xls')\njudge_sheet = wb.sheet_by_index(0)\ntotal_rows = judge_sheet.nrows\nscu_num = 0\n\nfor n in range(1, total_rows):\n row = judge_sheet.row(n)\n content = row[1].value.strip()\n c1 = str(row[2].value).strip()\n c2 = str(row[3].value).strip()\n c3 = str(row[4].value).strip()\n c4 = str(row[5].value).strip()\n ans = str(row[6].value).strip()\n ans_p = re.compile('\\d')\n ans = ''.join(re.findall(ans_p, ans))\n if ans.endswith('0'):\n ans = ans[:-1]\n _id = uuid.uuid4().hex\n try:\n con.execute('''insert into multi_choice (id, content, c1, c2, c3, c4, ans) values (?, ?, ?, ?, ?, ?, ?)''',\n (_id, content, c1, c2, c3, c4, ans))\n scu_num += 1\n except Exception as e:\n print(e.args[0])\ncon.commit()\nprint('成功导入{}道试题'.format(scu_num))\n","sub_path":"tools/multichoice.py","file_name":"multichoice.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"180692007","text":"def postprocess(face_detector, scene, markers_json=None, *args, **kwargs):\n\n from app import SessionReader\n from app.utils import create_learning_dataset\n\n sess_reader = SessionReader()\n sess_reader.fit('1531844043', r'D:\\param_train_sess\\17_07_18\\1531844043', cams=scene.cams, by='basler')\n\n markers = []\n for i in range(3):\n for j in range(8):\n marker = markers_json.get(f'wall_{i}_dot_{j+1}')\n if marker:\n markers.extend([marker] * 100)\n\n create_learning_dataset('../brs/',\n sess_reader,\n face_detector,\n scene,\n indices=range(len(sess_reader.snapshots)),\n markers=markers)\n","sub_path":"app/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"203093778","text":"import os\n\nfrom api import db\nfrom api import sentry\nfrom api.users.models.user import User\n\nADDRESSES = {\n \"1\": 13,\n \"2\": 12\n}\n\nINVESTMENT_PROFILES = {\n \"agressivo\": 1,\n \"conservador\": 2,\n \"arrojado\": 3,\n \"moderado\": 4\n}\n\n\ndef create_user(data):\n name = data.get('name')\n user = User(name)\n db.session.add(user)\n db.session.commit()\n\n\ndef update_user(user_id, data):\n user = User.query.filter(User.id == user_id).first()\n user.name = data.get('name')\n db.session.add(user)\n db.session.commit()\n\n\ndef delete_user(user_id):\n user = User.query.filter(User.id == user_id).first()\n db.session.delete(user)\n db.session.commit()\n\n\ndef get_user(user_id):\n return User.query.filter(User.id == user_id).first()\n\n\ndef get_addresses(type_address):\n return ADDRESSES[type_address]\n\n\ndef get_investment_profile(investment_profile):\n investment_profile = investment_profile.lower()\n if investment_profile in INVESTMENT_PROFILES:\n return INVESTMENT_PROFILES[investment_profile]\n return None\n\n\ndef exec_proc_insert_account_bank(cursor, id_person, id_bank, num_agency, num_current_account, name_person, cpf_person,\n type_account):\n try:\n # conn = session_oracle.bind.raw_connection()\n # cursor = conn.cursor()\n\n id_doc_person_out = 0\n cursor.callproc(os.environ.get('ORACLE_DB_NAME', '') + \".sbcapimanipuladocpessoa\",\n parameters=['I', id_doc_person_out, id_person, id_bank, num_agency,\n None, num_current_account, name_person, cpf_person, None, type_account, 6, None,\n 'STR', 'F', 'S'])\n # conn.commit()\n # print(result.get_value())\n return True\n except Exception as e:\n # session_oracle.rollback()\n sentry.captureException()\n return False\n\n\ndef exec_proc_insert_user_custom(cursor, args):\n try:\n # conn = session_oracle.bind.raw_connection()\n # cursor = conn.cursor()\n\n cursor.callproc(\n os.environ.get('ORACLE_DB_NAME', '') + \".sBcApiIncluiCampoCustomPessoa\", parameters=args)\n # conn.commit()\n return True\n\n except Exception as e:\n # session_oracle.rollback()\n sentry.captureException()\n return False\n\n\ndef select_reference_date_relationship(cursor):\n # return session_oracle.query(SubSistemaMatera).filter(SubSistemaMatera.id == 'SDBANCO').first()\n query = \"\"\"SELECT DATA_REFERENCIA FROM BC_SUB_SISTEMA WHERE ID_SUB_SISTEMA = :ID_SUB_SISTEMA\"\"\"\n cursor.execute(query, {\n \"ID_SUB_SISTEMA\": os.environ.get('ORACLE_DB_NAME', '')\n })\n result = cursor.fetchone()\n if result:\n return result[0]\n return None\n","sub_path":"Allgoo/andbank-service/api/users/business/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"592013081","text":"import os\nlives = 3\nword = \"\"\nresult = \"\"\ndiff = 0\nchars = 0\nalready = []\ndef print_line(list):\n s = \"\"\n for i in list:\n s+=i\n print(s)\ndef get_char():\n s = \"\"\n s = input(\"Enter symbol: \")\n if len(s) == 1:\n return s\n while len(s) > 1:\n s = input(\"Enter only 1 symbol: \")\n return s\ndef init_game():\n global chars\n global word\n global result\n global diff\n word = input(\"Enter word:\")\n os.system('clear')\n l = len(word)\n chars = l\n while l > 0:\n result+=\"|_|\"\n l-=1\n result = list(result)\n while diff == 0:\n diff = int(input(\"Enter game level:(1,2,3)\"))\n if diff < 0 or diff > 3:\n diff = 0\n print(\"Too hard..))\")\ndef start_game():\n global word\n global result\n global chars\n global lives\n global already\n while chars >= 0:\n if chars == 0:\n print(\"You win and save your life<3\")\n return 0\n print_line(result)\n if lives == 0:\n print(\"YOU LOOOSER!!!\")\n return 0\n j = 1\n c = get_char()\n if c not in already:\n already.append(c)\n else:\n print(\"You already sad:\")\n print_line(already)\n return start_game()\n if c in word:\n print(\"Thats right dude!\")\n for i in word:\n if i == c:\n chars-=1\n result[j-1] = \"\"\n result[j] = c\n result[j+1] = \"\"\n j+=3\n else:\n lives-=diff\n print(\"There is no such letter:P\")\n\n\n\ninit_game()\nstart_game()\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"85513076","text":"import collections\nimport itertools\nfrom typing import List\n\nfrom cached_property import cached_property\nfrom public import public\n\nfrom ... import util\nfrom ...common import exceptions as com\nfrom .. import rules as rlz\nfrom .. import schema as sch\nfrom .. import types as ir\nfrom .core import Node, all_equal, distinct_roots\nfrom .sortkeys import _maybe_convert_sort_keys\n\n_table_names = (f'unbound_table_{i:d}' for i in itertools.count())\n\n\n@public\ndef genname():\n return next(_table_names)\n\n\n@public\nclass TableNode(Node):\n def get_type(self, name):\n return self.schema[name]\n\n def output_type(self):\n return ir.TableExpr\n\n def aggregate(self, this, metrics, by=None, having=None):\n return Aggregation(this, metrics, by=by, having=having)\n\n def sort_by(self, expr, sort_exprs):\n return Selection(\n expr,\n [],\n sort_keys=_maybe_convert_sort_keys(\n [self.to_expr(), expr],\n sort_exprs,\n ),\n )\n\n def is_ancestor(self, other):\n import ibis.expr.lineage as lin\n\n if isinstance(other, ir.Expr):\n other = other.op()\n\n if self.equals(other):\n return True\n\n fn = lambda e: (lin.proceed, e.op()) # noqa: E731\n expr = self.to_expr()\n for child in lin.traverse(fn, expr):\n if child.equals(other):\n return True\n return False\n\n\n@public\nclass PhysicalTable(TableNode, sch.HasSchema):\n def blocks(self):\n return True\n\n\n@public\nclass UnboundTable(PhysicalTable):\n schema = rlz.instance_of(sch.Schema)\n name = rlz.optional(rlz.instance_of(str), default=genname)\n\n\n@public\nclass DatabaseTable(PhysicalTable):\n name = rlz.instance_of(str)\n schema = rlz.instance_of(sch.Schema)\n source = rlz.client\n\n def change_name(self, new_name):\n return type(self)(new_name, self.args[1], self.source)\n\n\n@public\nclass SQLQueryResult(TableNode, sch.HasSchema):\n \"\"\"A table sourced from the result set of a select query\"\"\"\n\n query = rlz.instance_of(str)\n schema = rlz.instance_of(sch.Schema)\n source = rlz.client\n\n def blocks(self):\n return True\n\n\ndef _make_distinct_join_predicates(left, right, predicates):\n # see GH #667\n\n # If left and right table have a common parent expression (e.g. they\n # have different filters), must add a self-reference and make the\n # appropriate substitution in the join predicates\n\n if left.equals(right):\n right = right.view()\n\n predicates = _clean_join_predicates(left, right, predicates)\n return left, right, predicates\n\n\ndef _clean_join_predicates(left, right, predicates):\n import ibis.expr.analysis as L\n\n result = []\n\n if not isinstance(predicates, (list, tuple)):\n predicates = [predicates]\n\n for pred in predicates:\n if isinstance(pred, tuple):\n if len(pred) != 2:\n raise com.ExpressionError('Join key tuple must be ' 'length 2')\n lk, rk = pred\n lk = left._ensure_expr(lk)\n rk = right._ensure_expr(rk)\n pred = lk == rk\n elif isinstance(pred, str):\n pred = left[pred] == right[pred]\n elif not isinstance(pred, ir.Expr):\n raise NotImplementedError\n\n if not isinstance(pred, ir.BooleanColumn):\n raise com.ExpressionError('Join predicate must be comparison')\n\n preds = L.flatten_predicate(pred)\n result.extend(preds)\n\n _validate_join_predicates(left, right, result)\n return result\n\n\ndef _validate_join_predicates(left, right, predicates):\n from ibis.expr.analysis import fully_originate_from\n\n # Validate join predicates. Each predicate must be valid jointly when\n # considering the roots of each input table\n for predicate in predicates:\n if not fully_originate_from(predicate, [left, right]):\n raise com.RelationError(\n 'The expression {!r} does not fully '\n 'originate from dependencies of the table '\n 'expression.'.format(predicate)\n )\n\n\n@public\nclass Join(TableNode):\n left = rlz.table\n right = rlz.table\n predicates = rlz.optional(rlz.list_of(rlz.boolean), default=[])\n\n def __init__(self, left, right, predicates):\n left, right, predicates = _make_distinct_join_predicates(\n left, right, predicates\n )\n super().__init__(left, right, predicates)\n\n def _get_schema(self):\n # For joins retaining both table schemas, merge them together here\n left = self.left\n right = self.right\n\n if not left._is_materialized():\n left = left.materialize()\n\n if not right._is_materialized():\n right = right.materialize()\n\n sleft = left.schema()\n sright = right.schema()\n\n overlap = set(sleft.names) & set(sright.names)\n if overlap:\n raise com.RelationError(\n 'Joined tables have overlapping names: %s' % str(list(overlap))\n )\n\n return sleft.append(sright)\n\n def has_schema(self):\n return False\n\n def root_tables(self):\n if util.all_of([self.left.op(), self.right.op()], (Join, Selection)):\n # Unraveling is not possible\n return [self.left.op(), self.right.op()]\n else:\n return distinct_roots(self.left, self.right)\n\n\n@public\nclass InnerJoin(Join):\n pass\n\n\n@public\nclass LeftJoin(Join):\n pass\n\n\n@public\nclass RightJoin(Join):\n pass\n\n\n@public\nclass OuterJoin(Join):\n pass\n\n\n@public\nclass AnyInnerJoin(Join):\n pass\n\n\n@public\nclass AnyLeftJoin(Join):\n pass\n\n\n@public\nclass LeftSemiJoin(Join):\n def _get_schema(self):\n return self.left.schema()\n\n\n@public\nclass LeftAntiJoin(Join):\n def _get_schema(self):\n return self.left.schema()\n\n\n@public\nclass CrossJoin(Join):\n pass\n\n\n@public\nclass MaterializedJoin(TableNode, sch.HasSchema):\n join = rlz.table\n\n def _validate(self):\n assert isinstance(self.join.op(), Join)\n # check whether the underlying schema has overlapping columns or not\n assert self.schema\n\n @cached_property\n def schema(self):\n return self.join.op()._get_schema()\n\n def root_tables(self):\n return self.join.op().root_tables()\n\n def blocks(self):\n return True\n\n\n@public\nclass AsOfJoin(Join):\n left = rlz.table\n right = rlz.table\n predicates = rlz.list_of(rlz.boolean)\n by = rlz.optional(\n rlz.list_of(\n rlz.one_of(\n (\n rlz.function_of(\"table\"),\n rlz.column_from(\"table\"),\n rlz.any,\n )\n )\n ),\n default=[],\n )\n tolerance = rlz.optional(rlz.interval)\n\n def __init__(self, left, right, predicates, by, tolerance):\n super().__init__(left, right, predicates)\n self.by = _clean_join_predicates(self.left, self.right, by)\n self.tolerance = tolerance\n\n self._validate_args(['by', 'tolerance'])\n\n def _validate_args(self, args: List[str]):\n # this should be removed altogether\n for arg in args:\n argument = self.__signature__.parameters[arg]\n value = argument.validate(self, getattr(self, arg))\n setattr(self, arg, value)\n\n\n@public\nclass SetOp(TableNode, sch.HasSchema):\n left = rlz.table\n right = rlz.table\n\n def _validate(self):\n if not self.left.schema().equals(self.right.schema()):\n raise com.RelationError(\n 'Table schemas must be equal for set operations'\n )\n\n @cached_property\n def schema(self):\n return self.left.schema()\n\n def blocks(self):\n return True\n\n\n@public\nclass Union(SetOp):\n distinct = rlz.optional(rlz.instance_of(bool), default=False)\n\n\n@public\nclass Intersection(SetOp):\n pass\n\n\n@public\nclass Difference(SetOp):\n pass\n\n\n@public\nclass Limit(TableNode):\n table = rlz.table\n n = rlz.instance_of(int)\n offset = rlz.instance_of(int)\n\n def blocks(self):\n return True\n\n @property\n def schema(self):\n return self.table.schema()\n\n def has_schema(self):\n return self.table.op().has_schema()\n\n def root_tables(self):\n return [self]\n\n\n@public\nclass SelfReference(TableNode, sch.HasSchema):\n table = rlz.table\n\n @cached_property\n def schema(self):\n return self.table.schema()\n\n def root_tables(self):\n # The dependencies of this operation are not walked, which makes the\n # table expression holding this relationally distinct from other\n # expressions, so things like self-joins are possible\n return [self]\n\n def blocks(self):\n return True\n\n\n@public\nclass Selection(TableNode, sch.HasSchema):\n table = rlz.table\n selections = rlz.optional(\n rlz.list_of(\n rlz.one_of(\n (\n rlz.table,\n rlz.column_from(\"table\"),\n rlz.function_of(\"table\"),\n rlz.any,\n rlz.named_literal,\n )\n )\n ),\n default=[],\n )\n predicates = rlz.optional(rlz.list_of(rlz.boolean), default=[])\n sort_keys = rlz.optional(\n rlz.list_of(\n rlz.one_of(\n (\n rlz.column_from(\"table\"),\n rlz.function_of(\"table\"),\n rlz.sort_key(from_=\"table\"),\n rlz.pair(\n rlz.one_of(\n (\n rlz.column_from(\"table\"),\n rlz.function_of(\"table\"),\n rlz.any,\n )\n ),\n rlz.map_to(\n {\n True: True,\n False: False,\n \"desc\": False,\n \"descending\": False,\n \"asc\": True,\n \"ascending\": True,\n 1: True,\n 0: False,\n }\n ),\n ),\n )\n )\n ),\n default=[],\n )\n\n def _validate(self):\n from ibis.expr.analysis import FilterValidator\n\n # Need to validate that the column expressions are compatible with the\n # input table; this means they must either be scalar expressions or\n # array expressions originating from the same root table expression\n dependent_exprs = self.selections + self.sort_keys\n self.table._assert_valid(dependent_exprs)\n\n # Validate predicates\n validator = FilterValidator([self.table])\n validator.validate_all(self.predicates)\n\n # Validate no overlapping columns in schema\n assert self.schema\n\n @cached_property\n def schema(self):\n # Resolve schema and initialize\n if not self.selections:\n return self.table.schema()\n\n types = []\n names = []\n\n for projection in self.selections:\n if isinstance(projection, ir.DestructColumn):\n # If this is a destruct, then we destructure\n # the result and assign to multiple columns\n struct_type = projection.type()\n for name in struct_type.names:\n names.append(name)\n types.append(struct_type[name])\n elif isinstance(projection, ir.ValueExpr):\n names.append(projection.get_name())\n types.append(projection.type())\n elif isinstance(projection, ir.TableExpr):\n schema = projection.schema()\n names.extend(schema.names)\n types.extend(schema.types)\n\n return sch.Schema(names, types)\n\n def blocks(self):\n return bool(self.selections)\n\n def substitute_table(self, table_expr):\n return Selection(table_expr, self.selections)\n\n def root_tables(self):\n return [self]\n\n def can_add_filters(self, wrapped_expr, predicates):\n pass\n\n @staticmethod\n def empty_or_equal(lefts, rights):\n return not lefts or not rights or all_equal(lefts, rights)\n\n def compatible_with(self, other):\n # self and other are equivalent except for predicates, selections, or\n # sort keys any of which is allowed to be empty. If both are not empty\n # then they must be equal\n if self.equals(other):\n return True\n\n if not isinstance(other, type(self)):\n return False\n\n return self.table.equals(other.table) and (\n self.empty_or_equal(self.predicates, other.predicates)\n and self.empty_or_equal(self.selections, other.selections)\n and self.empty_or_equal(self.sort_keys, other.sort_keys)\n )\n\n # Operator combination / fusion logic\n\n def aggregate(self, this, metrics, by=None, having=None):\n if len(self.selections) > 0:\n return Aggregation(this, metrics, by=by, having=having)\n else:\n helper = AggregateSelection(this, metrics, by, having)\n return helper.get_result()\n\n def sort_by(self, expr, sort_exprs):\n resolved_keys = _maybe_convert_sort_keys(\n [self.table, expr], sort_exprs\n )\n if not self.blocks():\n if self.table._is_valid(resolved_keys):\n return Selection(\n self.table,\n self.selections,\n predicates=self.predicates,\n sort_keys=self.sort_keys + resolved_keys,\n )\n\n return Selection(expr, [], sort_keys=resolved_keys)\n\n\n@public\nclass AggregateSelection:\n # sort keys cannot be discarded because of order-dependent\n # aggregate functions like GROUP_CONCAT\n\n def __init__(self, parent, metrics, by, having):\n self.parent = parent\n self.op = parent.op()\n self.metrics = metrics\n self.by = by\n self.having = having\n\n def get_result(self):\n if self.op.blocks():\n return self._plain_subquery()\n else:\n return self._attempt_pushdown()\n\n def _plain_subquery(self):\n return Aggregation(\n self.parent, self.metrics, by=self.by, having=self.having\n )\n\n def _attempt_pushdown(self):\n metrics_valid, lowered_metrics = self._pushdown_exprs(self.metrics)\n by_valid, lowered_by = self._pushdown_exprs(self.by)\n having_valid, lowered_having = self._pushdown_exprs(self.having)\n\n if metrics_valid and by_valid and having_valid:\n return Aggregation(\n self.op.table,\n lowered_metrics,\n by=lowered_by,\n having=lowered_having,\n predicates=self.op.predicates,\n sort_keys=self.op.sort_keys,\n )\n else:\n return self._plain_subquery()\n\n def _pushdown_exprs(self, exprs):\n import ibis.expr.analysis as L\n\n # exit early if there's nothing to push down\n if not exprs:\n return True, []\n\n resolved = self.op.table._resolve(exprs)\n subbed_exprs = []\n\n valid = False\n if resolved:\n for x in util.promote_list(resolved):\n subbed = L.sub_for(x, [(self.parent, self.op.table)])\n subbed_exprs.append(subbed)\n valid = self.op.table._is_valid(subbed_exprs)\n else:\n valid = False\n\n return valid, subbed_exprs\n\n\n@public\nclass Aggregation(TableNode, sch.HasSchema):\n\n \"\"\"\n metrics : per-group scalar aggregates\n by : group expressions\n having : post-aggregation predicate\n\n TODO: not putting this in the aggregate operation yet\n where : pre-aggregation predicate\n \"\"\"\n\n table = rlz.table\n metrics = rlz.optional(\n rlz.list_of(\n rlz.one_of(\n (\n rlz.function_of(\n \"table\",\n output_rule=rlz.one_of(\n (rlz.reduction, rlz.scalar(rlz.any))\n ),\n ),\n rlz.reduction,\n rlz.scalar(rlz.any),\n rlz.list_of(rlz.scalar(rlz.any)),\n rlz.named_literal,\n )\n ),\n flatten=True,\n ),\n default=[],\n )\n by = rlz.optional(\n rlz.list_of(\n rlz.one_of(\n (\n rlz.function_of(\"table\"),\n rlz.column_from(\"table\"),\n rlz.column(rlz.any),\n )\n )\n ),\n default=[],\n )\n having = rlz.optional(\n rlz.list_of(\n rlz.one_of(\n (\n rlz.function_of(\n \"table\", output_rule=rlz.scalar(rlz.boolean)\n ),\n rlz.scalar(rlz.boolean),\n )\n ),\n ),\n default=[],\n )\n predicates = rlz.optional(rlz.list_of(rlz.boolean), default=[])\n sort_keys = rlz.optional(\n rlz.list_of(\n rlz.one_of(\n (\n rlz.column_from(\"table\"),\n rlz.function_of(\"table\"),\n rlz.sort_key(from_=\"table\"),\n rlz.pair(\n rlz.one_of(\n (\n rlz.column_from(\"table\"),\n rlz.function_of(\"table\"),\n rlz.any,\n )\n ),\n rlz.map_to(\n {\n True: True,\n False: False,\n \"desc\": False,\n \"descending\": False,\n \"asc\": True,\n \"ascending\": True,\n 1: True,\n 0: False,\n }\n ),\n ),\n )\n )\n ),\n default=[],\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n if not self.by:\n self.sort_keys.clear()\n\n def _validate(self):\n from ibis.expr.analysis import FilterValidator\n\n # All non-scalar refs originate from the input table\n all_exprs = self.metrics + self.by + self.having + self.sort_keys\n self.table._assert_valid(all_exprs)\n\n # Validate predicates\n validator = FilterValidator([self.table])\n validator.validate_all(self.predicates)\n\n # Validate schema has no overlapping columns\n assert self.schema\n\n def blocks(self):\n return True\n\n def substitute_table(self, table_expr):\n return Aggregation(\n table_expr, self.metrics, by=self.by, having=self.having\n )\n\n @cached_property\n def schema(self):\n names = []\n types = []\n\n for e in self.by + self.metrics:\n if isinstance(e, ir.DestructValue):\n # If this is a destruct, then we destructure\n # the result and assign to multiple columns\n struct_type = e.type()\n for name in struct_type.names:\n names.append(name)\n types.append(struct_type[name])\n else:\n names.append(e.get_name())\n types.append(e.type())\n\n return sch.Schema(names, types)\n\n def sort_by(self, expr, sort_exprs):\n resolved_keys = _maybe_convert_sort_keys(\n [self.table, expr], sort_exprs\n )\n if self.table._is_valid(resolved_keys):\n return Aggregation(\n self.table,\n self.metrics,\n by=self.by,\n having=self.having,\n predicates=self.predicates,\n sort_keys=self.sort_keys + resolved_keys,\n )\n\n return Selection(expr, [], sort_keys=resolved_keys)\n\n\n@public\nclass Distinct(TableNode, sch.HasSchema):\n \"\"\"\n Distinct is a table-level unique-ing operation.\n\n In SQL, you might have:\n\n SELECT DISTINCT foo\n FROM table\n\n SELECT DISTINCT foo, bar\n FROM table\n \"\"\"\n\n table = rlz.table\n\n def _validate(self):\n # check whether schema has overlapping columns or not\n assert self.schema\n\n @cached_property\n def schema(self):\n return self.table.schema()\n\n def blocks(self):\n return True\n\n\n@public\nclass ExistsSubquery(Node):\n foreign_table = rlz.table\n predicates = rlz.list_of(rlz.boolean)\n\n def output_type(self):\n return ir.ExistsExpr\n\n\n@public\nclass NotExistsSubquery(Node):\n foreign_table = rlz.table\n predicates = rlz.list_of(rlz.boolean)\n\n def output_type(self):\n return ir.ExistsExpr\n\n\n@public\nclass FillNa(TableNode, sch.HasSchema):\n \"\"\"Fill null values in the table.\"\"\"\n\n table = rlz.table\n replacements = rlz.one_of(\n (\n rlz.numeric,\n rlz.string,\n rlz.instance_of(collections.abc.Mapping),\n )\n )\n\n @cached_property\n def schema(self):\n return self.table.schema()\n\n\n@public\nclass DropNa(TableNode, sch.HasSchema):\n \"\"\"Drop null values in the table.\"\"\"\n\n table = rlz.table\n how = rlz.isin({'any', 'all'})\n subset = rlz.optional(rlz.list_of(rlz.column_from(\"table\")), default=[])\n\n @cached_property\n def schema(self):\n return self.table.schema()\n","sub_path":"ibis/expr/operations/relations.py","file_name":"relations.py","file_ext":"py","file_size_in_byte":21895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"585886297","text":"\"\"\"upgrade module for the cli.\"\"\"\nimport click\n\nimport iocage.lib.ioc_common as ioc_common\nimport iocage.lib.ioc_json as ioc_json\nimport iocage.lib.ioc_list as ioc_list\nimport iocage.lib.ioc_start as ioc_start\nimport iocage.lib.ioc_stop as ioc_stop\nimport iocage.lib.ioc_upgrade as ioc_upgrade\n\n__rootcmd__ = True\n\n\n@click.command(name=\"upgrade\", help=\"Run freebsd-update to upgrade a specified\"\n \" jail to the RELEASE given.\")\n@click.argument(\"jail\", required=True)\n@click.option(\"--release\", \"-r\", required=True, help=\"RELEASE to upgrade to\")\ndef cli(jail, release):\n \"\"\"Runs upgrade with the command given inside the specified jail.\"\"\"\n jails, paths = ioc_list.IOCList(\"uuid\").list_datasets()\n _jail = {tag: uuid for (tag, uuid) in jails.items() if\n uuid.startswith(jail) or tag == jail}\n\n if len(_jail) == 1:\n tag, uuid = next(iter(_jail.items()))\n path = paths[tag]\n root_path = \"{}/root\".format(path)\n elif len(_jail) > 1:\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\"Multiple jails found for {jail}:\"\n })\n for t, u in sorted(_jail.items()):\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\" {u} ({t})\"\n })\n exit(1)\n else:\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\"{jail} not found!\"\n })\n exit(1)\n\n status, jid = ioc_list.IOCList.list_get_jid(uuid)\n conf = ioc_json.IOCJson(path).json_load()\n jail_release = conf[\"release\"]\n started = False\n\n if conf[\"release\"] == \"EMPTY\":\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": \"Upgrading is not supported for empty jails.\"\n })\n exit(1)\n if conf[\"type\"] == \"jail\":\n if not status:\n ioc_start.IOCStart(uuid, tag, path, conf, silent=True)\n started = True\n\n new_release = ioc_upgrade.IOCUpgrade(conf, release,\n root_path).upgrade_jail()\n elif conf[\"type\"] == \"basejail\":\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": \"Please run \\\"iocage migrate\\\" before trying\"\n f\" to upgrade {uuid} ({tag})\"\n })\n exit(1)\n elif conf[\"type\"] == \"template\":\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": \"Please convert back to a jail before trying\"\n f\" to upgrade {uuid} ({tag})\"\n })\n exit(1)\n else:\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\"{conf['type']} is not a supported jail type.\"\n })\n exit(1)\n\n if started:\n ioc_stop.IOCStop(uuid, tag, path, conf, silent=True)\n\n ioc_common.logit({\n \"level\" : \"INFO\",\n \"message\": f\"\\n{uuid} ({tag}) successfully upgraded from\"\n f\" {jail_release} to {new_release}!\"\n })\n","sub_path":"iocage/cli/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"438517180","text":"\"\"\"textutils URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('admin/', admin.site.urls), # code for video : 4\n path('',views.index_func,name='index'), # code for video : 4\n path('about/',views.about_func,name='about'), # code for video : 4\n path('html/',views.html_func,name='html'), # code for video : 5\n path('text/',views.read_file_func,name='txt'), # code for video : 5\n path('navigator/',views.navigator_func,name='navigator'), # code for video : 6\n\n\n path('removepunc', views.removepunc, name='rempun'), # code for video : 7\n path('capitalizefirst', views.capfirst, name='capfirst'), # code for video : 7\n path('newlineremove', views.newlineremove, name='newlineremove'), # code for video : 7\n path('spaceremove', views.spaceremove, name='spaceremove'), # code for video : 7\n path('charcount', views.charcount, name='charcount'), # code for video : 7\n\n path('templates', views.tem_fun, name='templates'), # code for video : 8\n\n\n path('html9', views.html9_func, name='html9'), # code for video : 9\n path('removepunc', views.removepunc, name='rempun'), # code for video : 9\n\n\n path('html10', views.html10_func, name='html10'), # code for video : 10\n path('analyze', views.analyze, name='analyze') # code for video : 10\n]\n","sub_path":"Serial wise files/textutils (1 -10)/textutils/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"456269942","text":"def reward_function(params):\n ###############################################################################\n '''\n Example of using waypoints and heading to make the car in the right direction\n '''\n import math\n # Read input variables\n waypoints = params['waypoints']\n closest_waypoints = params['closest_waypoints']\n heading = params['heading']\n #update to also read wheels on track and speed\n all_wheels_on_track = params['all_wheels_on_track']\n speed = params['speed']\n SPEED_THRESHOLD = 1.0 \n HIGH_SPEED_THRESHOLD = 4.0\n\n # Initialize the reward\n reward = 1.0\n\n # Calculate the direction of the center line based on the closest waypoints\n next_point = waypoints[closest_waypoints[1]]\n prev_point = waypoints[closest_waypoints[0]]\n\n # Calculate the direction in radius, arctan2(dy, dx), the result is (-pi, pi) in radians\n track_direction = math.atan2(next_point[1] - prev_point[1], next_point[0] - prev_point[0]) \n # Convert to degree\n track_direction = math.degrees(track_direction)\n\n # Calculate the difference between the track direction and the heading direction of the car\n direction_diff = abs(track_direction - heading)\n if direction_diff > 180:\n direction_diff = 360 - direction_diff\n \n DIRECTION_THRESHOLD = 15.0\n CLOSE_DIRECTION_THRESHOLD = 5.0\n \n # Reward if close to waypoints\n if direction_diff < CLOSE_DIRECTION_THRESHOLD: #Reward more if closer to the center\n reward *= 4.0\n elif direction_diff < DIRECTION_THRESHOLD: #Still reward if close to waypoints\n reward *= 2.0 \n \n # Higher reward if the car goes faster\n elif speed > HIGH_SPEED_THRESHOLD: \n reward *= 4.0\n elif speed > SPEED_THRESHOLD: # Still reward if car goes fast\n reward *= 2.0\n \n # Penalize if going away from waypoints, going off track or going slow \n elif direction_diff > DIRECTION_THRESHOLD or speed < SPEED_THRESHOLD or all_wheels_on_track == False: \n reward *= 0.01\n \n return reward","sub_path":"src/slow3CNN.py","file_name":"slow3CNN.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"473763964","text":"from django.shortcuts import render\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom .forms import EmailSignupForm\nfrom .models import Signup\nimport json\nimport requests\nfrom django.contrib import messages\n# Create your views here.\nMAILCHIMP_API_KEY=settings.MAILCHIMP_API_KEY\nMAILCHIMP_DATA_CENTER=settings.MAILCHIMP_DATA_CENTER\nMAILCHIMP_EMAIL_LIST_ID=settings.MAILCHIMP_API_KEY\n\napi_url=f'https://{MAILCHIMP_DATA_CENTER}.api.mailchimp.com/3.0'\nmembers_endpoint=f'{api_url}/lists/{MAILCHIMP_EMAIL_LIST_ID}/members'\n\n\ndef suscribe(email):\n data={\n \"email_address\":email,\n \"status\":\"suscribed\"\n }\n r=requests.post(\n members_endpoint,\n auth=(\"\",MAILCHIMP_API_KEY),\n data=json.dumps(data)\n )\n return r.status_code, r.json()\n\ndef email_list_signup(request):\n form=EmailSignupForm(request.POST or None)\n if request.method==\"POST\":\n if form.is_valid():\n email_signup_qs=Signup.objects.filter(email=form.instance.email)\n if email_signup_qs.exists():\n messages.info(request,\"you are already suscribed\")\n else :\n suscribe(form.instance.email)\n form.save()\n return HttpResponseRedirect(request.META.get(\"HTTP_REFERER\"))\n","sub_path":"marketing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"27243469","text":"#from django.http import HttpRequest, HttpResponse\nfrom django.shortcuts import render_to_response\nfrom models import Location\n\ndef home(request):\n # create a location for no particular reason\n if Location.objects.count() == 0:\n loc = Location(name=\"Microsoft NERD Center\",\n street=\"1 Memorial Drive\",\n city=\"Cambridge\",\n state=\"MA\",\n country=\"US\")\n loc.save()\n return render_to_response('home.html')\n\ndef whois(request):\n name = request.GET.get(\"name\", \"\") or \"World\"\n if Location.objects.count() > 0:\n loc = Location.objects.all()[0]\n address = \"%s, %s %s\" % (loc.street, loc.city, loc.state)\n else:\n address = \"unknown\"\n return render_to_response('whois.html',\n {\"name\": name,\n \"address\": address})\n","sub_path":"webfun/stacks/django-sqlite3/trivialproject/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"59151740","text":"import re\n\nfrom load_movie_data import df\n\ndf.loc[0, 'review'][-50:]\n# 2019.09.22 add\nif __name__ == '__main__':\n print(df.loc[0, 'review'][-50:])\n\n\ndef preprocessor(text):\n text = re.sub('<[^>]*>', '', text)\n emoticons = re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)',\n text)\n text = (re.sub('[\\W]+', ' ', text.lower()) +\n ' '.join(emoticons).replace('-', ''))\n return text\n\n\n\n\npreprocessor(df.loc[0, 'review'][-50:])\n# 2019.09.22 add\nif __name__ == '__main__':\n print(preprocessor(df.loc[0, 'review'][-50:]))\n\n\npreprocessor(\"This :) is :( a test :-)!\")\n# 2019.09.22 add\nif __name__ == '__main__':\n print(preprocessor(\"This :) is :( a test :-)!\"))\n\ndf['review'] = df['review'].apply(preprocessor)\n# 2019.09.22 add\nif __name__ == '__main__':\n print(preprocessor(df.loc[0, 'review']))\n","sub_path":"ch08/imdb_cleansing.py","file_name":"imdb_cleansing.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"535889331","text":"#!C:/Users/Saurabh/AppData/Local/Programs/Python/Python36/python.exe\nimport os\nimport sys\nfrom subprocess import *\nfrom datetime import datetime, timedelta\nimport time\nimport search_processing as sp\nimport database_insert as db_insert\n\nprint(\"Content-Type: text/html\")\nprint()\nimport cgi, cgitb\n\ncgitb.enable() # for debugging\nform = cgi.FieldStorage()\n# search_loc = 'panathur'\n# days_ago = 7\nsearch_loc = form.getvalue('location')\ndays_ago = form.getvalue('posted_since')\n# now = (datetime.datetime.now()).strftime(\"%d%m%Y%H%M%S\")+str(round(time.time() * 1000) )#current time +millisecond\nnow = time.strftime('%Y-%m-%d %H:%M:%S')\nid = time.strftime('%Y%m%d%H%M%S')\n\n\n\ndef main_program():\n # option 1\n loc = db_insert.get_m_location(search_loc)\n if loc is None or loc == \"\":\n print(search_loc+\" location in not present in MagicBrick....\")\n pass\n else:\n # run child script 1\n p = Popen([r'm_magic_brick.py ', search_loc, str(days_ago), now, \"rentalsearch\"], shell=True, stdin=PIPE, stdout=PIPE)\n output = p.communicate()\n print(output[0])\n\n # run child script 2\n p = Popen([r'99_acres.py ', search_loc, str(days_ago), now, \"rentalsearch\"], shell=True, stdin=PIPE, stdout=PIPE)\n output = p.communicate()\n print(output[0])\n\nstart = time.time()\nold_stdout = sys.stdout\nlog_file = open(\"logs\\message.log\", \"a\")\nsys.stdout = log_file\nprint(id+\" \"+search_loc+\" \"+str(days_ago))\nlatest_timestamp = sp.is_recent(search_loc, str(days_ago))\nsp.insert_search_info(id, search_loc, now, str(days_ago))\nif latest_timestamp[0] is None:\n\tmain_program()\n\tcreated_date_time1 = now\nelse:\n\tif latest_timestamp[0] >= datetime.now() - timedelta(hours=4):\n\t\tcreated_date_time1 = latest_timestamp[0]\n\t\tprint(search_loc+\" location searched in past 4 hour.Latest known timestamp: \"+str(created_date_time1))\n\telse:\n\t\tmain_program()\n\t\tcreated_date_time1 = now\nelapsed = (time.time() - start)\nprint(elapsed, \" seconds\")\nsys.stdout = old_stdout\n\nlog_file.close()\nprint('')\nprint('')\nprint(\n '')\n# print(\n# \t'')\nprint('')\nprint('')\n","sub_path":"python/main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"272999001","text":"import os\nfrom skimage.transform import resize\nimport nibabel as nib\nimport numpy as np\nimport sys\nfrom matplotlib import pyplot as plt\n\n##############################################\n# Code for preprocessing all of the scans and storing them in numpy arrays. Done so that the preprocessing and image resizing steps\n# wouldn't be repeated during training, thereby speeding up the training process. Assumes the data stored in raw_data_path are in two folders: HGG and LGG.\n\n# INPUT:\nraw_data_path = r'C:\\Users\\artur\\Desktop\\UCL\\Brats2019\\Data\\MICCAI_BraTS_2019_Data_Validation\\data'\n# raw_data_path = r\"/home/artur-cmic/Desktop/UCL/Brats2019/Data/MICCAI_BraTS_2019_Data_Training/data\"\nsave_preprocessed_data_path = r'C:/Users/artur/Desktop/UCL/Brats2019/Data/Preprocessed_Validation'\n# save_preprocessed_data_path = r\"/home/artur-cmic/Desktop/UCL/Brats2019/Data/Preprocessed\"\ntrain_data = False # Specify whether to preprocess Brats training or valid data\n# OUTPUT: Preprocessed data stored in numpy arrays in the save_preprocessed_path\n##############################################\n\n# Create folder to store preprocessed data in, exit if folder already exists.\nif not os.path.isdir(save_preprocessed_data_path):\n os.mkdir(save_preprocessed_data_path)\n\n# Get folder paths and ids of where the raw scans are stored\nfolder_paths = []\nfolder_IDS = []\nif train_data:\n for grade in os.listdir(raw_data_path):\n for subdir in os.listdir(os.path.join(raw_data_path, grade)):\n folder_paths.append(os.path.join(raw_data_path, grade, subdir))\n folder_IDS.append(subdir)\nelse:\n for subdir in os.listdir(raw_data_path):\n folder_paths.append(os.path.join(raw_data_path, subdir))\n folder_IDS.append(subdir)\n\ni = 1\nfor patient in range(len(folder_paths)):\n data_folder = folder_paths[patient]\n data_id = folder_IDS[patient]\n os.mkdir(os.path.join(save_preprocessed_data_path, data_id))\n\n output_size = (128,128,128) # Size to change images to\n\n # Load in and resize the mri images\n img_t1 = resize(nib.load(os.path.join(data_folder, data_id) + \"_t1.nii.gz\").get_fdata(), output_size)\n img_t1ce = resize(nib.load(os.path.join(data_folder, data_id) + \"_t1ce.nii.gz\").get_fdata(), output_size)\n img_t2 = resize(nib.load(os.path.join(data_folder, data_id) + \"_t2.nii.gz\").get_fdata(), output_size)\n img_flair = resize(nib.load(os.path.join(data_folder, data_id) + \"_flair.nii.gz\").get_fdata(), output_size)\n\n if train_data:\n # Load in labels\n img_segm = nib.load(os.path.join(data_folder, data_id) + \"_seg.nii.gz\").get_fdata().astype('long')\n # Segmentation Mask has labels 0,1,2,4. Will change these to 0,1,2,3 and perform resizing on the labels separately\n # Combine them afterwards. Multiplication of labels by 10 so difference between label and background pixel would be\n # greater, otherwise resize wont work properly.\n img_segm[img_segm == 4] = 3\n lbl1 = resize((img_segm == 1)*10, output_size, preserve_range=True, anti_aliasing=True)\n lbl2 = resize((img_segm == 2)*10, output_size, preserve_range=True, anti_aliasing=True)\n lbl3 = resize((img_segm == 3)*10, output_size, preserve_range=True, anti_aliasing=True)\n\n # Remove uncertain pixels at the edges of a label area before merging labels. Essentially remove pixels with class belonging confidence of < 30%.\n # Made equal to -1 instead of 0, just to make sure that the background pixels are always assigned label 0 with argmax.\n lbl1[lbl1 < 3] = -1\n lbl2[lbl2 < 3] = -1\n lbl3[lbl3 < 3] = -1\n\n # Merge labels by taking argmax of label values - for a pixel that belongs to two classes after resize, assign to the class\n # that its value is highest for. Adding np.zeros to the first dimension so np.argmax would give 1 for label 1 and not 0.\n img_segm = np.argmax(np.asarray([np.zeros(output_size),lbl1, lbl2, lbl3]),axis=0).astype('long')\n\n # Preprocess mri volumes\n X = []\n for modality in [img_t1, img_t1ce, img_t2, img_flair]:\n brain_region = modality > 0 # Get region of brain to only manipulate those voxels\n mean = np.mean(modality[brain_region])\n stdev = np.std(modality[brain_region])\n new_img = np.zeros(output_size)\n new_img[brain_region] = (modality[brain_region] - mean) / stdev # Standardize by mean and stdev\n new_img[new_img > 5] = 5 # Clip outliers\n new_img[new_img < -5] = -5\n Maximum = np.max(new_img)\n Minimum = np.min(new_img[brain_region])\n Range = Maximum - Minimum\n new_img[brain_region] = ((((new_img[brain_region] - Minimum) / Range - 0.5) * 2) + 1) / 2 # Scale to be between 0 and 1\n X.append(new_img.astype('float32'))\n\n np.save(\"{}/{}/{}_scans.npy\".format(save_preprocessed_data_path, data_id, data_id), X)\n if train_data:\n np.save(\"{}/{}/{}_mask.npy\".format(save_preprocessed_data_path, data_id, data_id), img_segm)\n print(\"Preprocessed patient {}/{} scans\".format(i, len(folder_paths)))\n i = i + 1\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"376212940","text":"import sqlite3\nbaglanti=sqlite3.connect(\"example.db\")\nif(baglanti):\n print(\"Bağlantı Başarılı\")\nelse:\n print(\"Bağlantı Başarısız\")\nveritabani=baglanti.cursor()\nveritabani.execute('''Insert into Kitaplar(kitap_id,kitap_adi,yazar) values('001','VisualC#.Net','Jon Jagger')''')\nbaglanti.commit()\nbaglanti.close()\n","sub_path":"InsertData.py","file_name":"InsertData.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"95288847","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport re\nWORD_SPLITTER = re.compile(r'[\\s]+')\n\ndef split_words(s):\n return [i for i in WORD_SPLITTER.split(s) if i]\n\ndef pair_split(items, split='as'):\n result = []\n queue, parts = [], []\n for item in items:\n if item.lower() == split:\n if queue or not parts:\n raise Exception('Couldn\\'t correctly understand %s\" in %s' %\n (split, items))\n queue, parts = parts, []\n elif queue:\n result.append((queue.pop(0), item))\n else:\n parts.append(item)\n result.extend((s, None) for s in queue + parts)\n return result\n\ndef split_scores(scores):\n if not scores:\n return []\n\n if isinstance(scores, (tuple, list)):\n scores = ' '.join(scores)\n return pair_split(split_words(scores))\n\n","sub_path":"code/python/echomesh/util/Split.py","file_name":"Split.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"634490085","text":"from collections import defaultdict, Counter\nimport codecs, warnings, os\nwarnings.filterwarnings('ignore')\n\ndef parse_pages():\n '''\n Return a mapping from single character representation of transcriptor to\n array of line strings.\n @kwarg str path: the path to the voynich full text\n @returns\n [str] page_order: a list of the page keys in order\n dict d: # d[annotator][page] = ['line_one', 'line_two']\n '''\n page_order = []\n d = defaultdict(lambda: defaultdict(list))\n path = os.path.join(__file__.replace('helpers.py', 'text16e6.evt'))\n if path[-1] == 'c':\n path = ''.join(path[:-1])\n with codecs.open(path, 'r', 'latin1') as f:\n f = f.read()\n for line_idx, line in enumerate(f.split('\\n')):\n if not line.strip(): continue\n if line[0] != '<': continue # skip paratextual lines\n meta = line.split('<')[1].split('>')[0]\n if '.' not in meta: # indicates the start of a new page (e.g. )\n page_order.append(meta)\n continue\n page, sheet, line_num_and_annotator = meta.split('.')\n line_num, annotator = line_num_and_annotator.split(';')\n if '>' not in line: continue\n if not page: continue # skip the page id 0\n line_text = line.split('>')[1].strip()\n d[annotator][page].append(line_text)\n return page_order, d\n\npage_order, line_map = parse_pages()\n\n# select the annotator to use (Takahashi)\nannotator = 'H'\n\n# set page array\npages = line_map[annotator]","sub_path":"utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"549701087","text":"# MIT License\n#\n# Copyright (c) 2020 Kate Aubrey Cellan\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nimport os\nimport time\nimport datetime\n\nfrom discord.ext import commands\n\n# LOG START\nimport logging\n\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.DEBUG)\nhandler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\n\n# LOG END\n\nstart_time = time.time()\n\n# Open token file\nwith open(\"token.txt\", \"r\") as file:\n token = file.read()\n\nclient = commands.Bot(command_prefix=\".\")\n\n\n# Change ctx.author.id to your own discord ID if you plan to self host\nasync def is_owner(ctx):\n return ctx.author.id == 451974524053749780 # DaijobuDes#0870\n\n\n@client.command()\n@commands.check(is_owner)\nasync def load(ctx, extension):\n client.load_extension(f'plugins.{extension}')\n print(f'{extension} loaded')\n\n\n# Unload plugins\n@client.command()\n@commands.check(is_owner)\nasync def unload(ctx, extension):\n client.unload_extension(f'plugins.{extension}')\n print(f'{extension} unloaded')\n\n\n# Reload plugins\n# Useful for realtime plugin testing\n@client.command()\n@commands.check(is_owner)\nasync def reload(ctx, extension):\n client.unload_extension(f'plugins.{extension}')\n client.load_extension(f'plugins.{extension}')\n print(f'{extension} reloaded')\n\n\nfor filename in os.listdir('./plugins'):\n if filename.endswith('.py'):\n client.load_extension(f'plugins.{filename[:-3]}')\n print(f'{filename} loaded')\n\n\n@client.command()\nasync def uptime(ctx):\n current_time = time.time()\n difference = int(round(current_time-start_time))\n text_time = str(datetime.timedelta(seconds=difference))\n await ctx.send(f'`Uptime: {text_time}`')\n\n\nclient.run(token)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"581701913","text":"'''\nCreated on Dec 14, 2018\n\n@author: coditum\n'''\ndef shapemain():\n x=int(input('1 for square, 2 for triangle, 3 for \\\n circle, 4 for rectangle: '))\n if x == 1:\n answer=square()\n elif x==2:\n answer=triangle()\n elif x==3:\n answer=circle()\n elif x==4:\n answer=rectangle()\n else:\n print(\"sorry\")\n return\n \n print(\"The area is:\", answer)\ndef square():\n side=int(input(\"What is the length of the sides?\"))\n area=(side*side)\n return area\n\ndef triangle():\n base=int(input(\"What is the length of the base?: \"))\n height=int(input(\"What is the height?: \"))\n area=.5*(base*height)\n return area\n\ndef circle():\n radius=int(input(\"What is the radius?: \"))\n area=(3.14*radius*radius)\n return area\n\ndef rectangle():\n length=int(input(\"What is the length?: \"))\n width=int(input(\"What is the width?: \"))\n area=(length*width) \n return area \n\nshapemain()","sub_path":"wickmclean-coditum-3aada66b1a92/wickmclean-coditum-3aada66b1a92/areashapes.py","file_name":"areashapes.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"464921111","text":"import os\nimport sikuli\nimport time\n\n# Local imports\nfrom utils import pyUtils, sikuliUtils\nfrom utils.pyUtils import log\nimport checkUtils\n\n\nclass ExportCheck:\n def __init__(self, export):\n self.export = export\n\n def exportPanelsCheck(self, settings):\n log('## exportPanelsCheck')\n\n # Using 2 sec per panel should be enough?\n timeout = len(settings['panels'])*2\n if not checkUtils.popupCheck(self.export.testInfo, timeout, 'exportPanelsCheck'):\n self.export.testInfo.failed('exportPanelsCheck: Plugin failed, '\n 'check log for errors. Exiting current checks...')\n return\n\n outputPath = '%s/%ss/' % (self.export.testInfo.outDir, settings['format'])\n\n # check panels have been exported to output directory\n if settings['format'] == 'jpeg':\n ext = 'jpg'\n elif settings['format'] == 'psd':\n ext = 'psd'\n exported = pyUtils.countFiles(outputPath, '%s_%s_*.%s' %\n (self.export.testInfo.show, self.export.testInfo.sequence, ext))\n if not exported == len(settings['panels']):\n self.export.testInfo.failed(\n 'exportPanelsCheck: Not the right number of %ss '\n 'have been exported. Expected %s, found %s instead.' % (ext, len(settings['panels']), exported))\n else:\n log('- Found all expected %ss.' % ext)\n\n log('All checks performed for exportPanels.')\n\n def exportQuickTimeCheck(self, timeout):\n log('## exportQuickTimeCheck')\n\n if not checkUtils.popupCheck(self.export.testInfo, timeout, 'exportQuickTimeCheck'):\n self.export.testInfo.failed('exportQuickTimeCheck: Plugin failed, '\n 'check log for errors. Exiting current checks...')\n return\n\n # movieFile = pyUtils.waitForFile(self.export.fleMovDir, '*.mov', 5)\n movieFile = \"%s/%s_%s_v%s.mov\" % (self.export.fleMovDir,\n self.export.testInfo.sequence,\n self.export.testInfo.currentBranch,\n self.export.testInfo.getEditVersion())\n\n if not os.path.exists(movieFile):\n self.export.testInfo.failed('exportQuickTimeCheck: Movie was not generated in %s.' % self.export.fleMovDir)\n else:\n log('- Found generated movie.')\n\n movieSize = os.path.getsize(movieFile)\n if movieSize < 100:\n self.export.testInfo.failed('exportQuickTimeCheck: Movie created is less than 100 bytes, '\n 'probably failed to be created.\\nFilesize: %s' % movieSize)\n else:\n log('- Generated movie is not 0 bytes.')\n\n log('All checks performed for exportQuickTime.')\n\n def exportPdfCheck(self, panelsPerPage):\n log('## exportPdfCheck')\n\n # Assuming 5sec + 1sec/panel is enough to generate the PDF\n timeout = 5 + self.export.testInfo.getNumberPanelsFromShotEdit()\n\n pdfFile = \"%s/%s_%s_%s_%s_%s.pdf\" % (self.export.pdfDir,\n self.export.testInfo.show,\n self.export.testInfo.sequence,\n self.export.testInfo.getEditVersion(),\n self.export.testInfo.currentBranch,\n panelsPerPage)\n\n sikuli.wait(timeout)\n if not os.path.exists(pdfFile):\n self.export.testInfo.failed('exportPdfCheck: PDF was not generated in %s.' % self.export.pdfDir)\n else:\n log('- Found generated PDF.')\n sikuliUtils.closeChromeTab()\n\n if not checkUtils.popupCheck(self.export.testInfo, 5, \"exportPdfCheck\"):\n self.export.testInfo.failed('exportPdfCheck: Plugin failed, '\n 'check log for errors. Exiting current checks...')\n\n log('All checks performed for exportPdf.')\n","sub_path":"Lib/checks/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"191657848","text":"from musicscore.dtd.dtd import Sequence, Element, Choice\nfrom musicscore.musicxml.types.complextypes.complextype import ComplexType\nfrom musicscore.musicxml.types.complextypes.partgroup import ComplexTypePartGroup\nfrom musicscore.musicxml.types.complextypes.scorepart import ComplexTypeScorePart\n\n\nclass ScorePart(ComplexTypeScorePart):\n \"\"\"\n The score-part element is defined within a group due to its multiple uses within the part-list element.\n Each MusicXML part corresponds to a track in a Standard MIDI Format 1 file. The score-instrument elements are used\n when there are multiple instruments per track. The midi-device element is used to make a MIDI device or port\n assignment for the given track. Initial midi-instrument assignments may be made here as well.\n \"\"\"\n _TAG = 'score-part'\n\n def __init__(self, id, *args, **kwargs):\n super().__init__(tag=self._TAG, id=id, *args, **kwargs)\n\n\nclass PartGroup(ComplexTypePartGroup):\n _TAG = 'part-group'\n\n def __init__(self, *args, **kwargs):\n super().__init__(tag=self._TAG, *args, **kwargs)\n\n\nclass ComplexTypePartList(ComplexType):\n \"\"\"\n The part-list identifies the different musical parts in this movement. Each part has an ID that is used later within\n the musical data. Since parts may be encoded separately and combined later, identification elements are present at\n both the score and score-part levels. There must be at least one score-part, combined as desired with part-group\n elements that indicate braces and brackets. Parts are ordered from top to bottom in a score based on the order in\n which they appear in the part-list.\n \"\"\"\n # _DTD = Sequence(\n # Element(PartGroup, min_occurrence=0, max_occurrence=None),\n # Element(ScorePart),\n # Choice(\n # Element(PartGroup),\n # Element(ScorePart),\n # min_occurrence=0, max_occurrence=None\n # )\n # )\n _DTD = Sequence(\n Choice(Element(PartGroup, min_occurrence=0, max_occurrence=None),\n Element(ScorePart)\n ),\n Choice(\n Element(PartGroup),\n Element(ScorePart),\n min_occurrence=0, max_occurrence=None\n )\n )\n\n def __init__(self, tag, *args, **kwargs):\n super().__init__(tag=tag, *args, **kwargs)\n","sub_path":"musicscore/musicxml/types/complextypes/partlist.py","file_name":"partlist.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"627796169","text":"from datetime import datetime\nfrom transactions.cql import utils\n\nclass DeliveryHandler:\n def __init__(self, cql_session, query, w_id, carrier_id):\n self.session = cql_session\n self.query = query\n self.w_id = int(w_id)\n self.carrier_id = int(carrier_id)\n\n def find_smallest_order(self, w_id, d_id):\n args = [w_id, d_id, -1]\n counter = 0\n while counter < 3:\n try:\n order = utils.select_one(self.session, self.query.select_order_with_carrier, args)\n return order\n except Exception as e:\n print(e)\n counter += 1\n return None\n\n def update_order_carrier_id(self, w_id, d_id, o_id, carrier_id):\n args = [carrier_id, w_id, d_id, o_id]\n utils.update(self.session, self.query.update_order_carrier_id, args)\n\n def select_order_line(self, w_id, d_id, o_id):\n args = [w_id, d_id, o_id]\n return utils.select(self.session, self.query.select_ol, args)\n\n def update_delivery_d(self, w_id, d_id, o_id, ol_number, t):\n args = [t, w_id, d_id, o_id, ol_number]\n utils.update(self.session, self.query.update_ol_deliver_d, args)\n\n def sum_order_amount(self, w_id, d_id, o_id):\n args = [w_id, d_id, o_id]\n rows = utils.select(self.session, self.query.select_ol, args)\n amount = 0\n for row in rows:\n amount += row.ol_amount\n return amount\n\n def update_customer(self, w_id, d_id, c_id, o_id):\n total_order_amount = self.sum_order_amount(self.w_id, d_id, o_id)\n args = [int(100*(round(total_order_amount, 2))), w_id, d_id, c_id]\n utils.update(self.session, self.query.update_customer_delivery_change, args)\n\n def run(self):\n for d_id in range(1, 11):\n smallest_order = self.find_smallest_order(self.w_id, d_id)\n if smallest_order is None:\n continue\n o_id = smallest_order.o_id\n print(\"w_id = {}, d_id={}, o_id={}\".format(self.w_id, d_id, o_id))\n self.update_order_carrier_id(self.w_id, d_id, o_id, self.carrier_id)\n\n order_lines = self.select_order_line(self.w_id, d_id, o_id)\n for ol in order_lines:\n self.update_delivery_d(self.w_id, d_id, o_id, ol.ol_number, datetime.now())\n\n # select and update customer\n return self.update_customer(self.w_id, d_id, smallest_order.o_c_id, o_id)\n","sub_path":"src/transactions/Delivery.py","file_name":"Delivery.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"212413085","text":"from django.shortcuts import render,redirect\nfrom django.views import View\nfrom django import template\nfrom service import path,session\nfrom django.http import HttpResponse\n#from .data import mockContest\nfrom datetime import datetime\nfrom ContestAdmin import models\nfrom django.contrib.auth.models import User\nimport django_rq\nimport os\nimport rq\nimport re\n\ndef run_tester(s,path):\n import importlib\n import sys\n spec = importlib.util.spec_from_file_location('tester', path+'tester.py')\n module = importlib.util.module_from_spec(spec)\n sys.modules['tester'] = module\n spec.loader.exec_module(module)\n obj = models.Status.objects.get(id=s)\n try:\n obj.Status=module.check_python(str(s))\n except rq.timeouts.JobTimeoutException:\n obj.Status=\"TLE\"\n except:\n obj.Status=\"Compile Error\"\n obj.save()\n\ndef run_tester_cpp(s,path):\n import importlib\n import sys\n spec = importlib.util.spec_from_file_location('tester', path+'tester.py')\n module = importlib.util.module_from_spec(spec)\n sys.modules['tester'] = module\n spec.loader.exec_module(module)\n obj = models.Status.objects.get(id=s)\n try:\n obj.Status=module.check_cpp(str(s))\n except rq.timeouts.JobTimeoutException:\n obj.Status=\"TLE\"\n except:\n obj.Status=\"Compile Error\"\n obj.save()\n\ndef run_tester_java(s,path):\n import importlib\n import sys\n spec = importlib.util.spec_from_file_location('tester', path+'tester.py')\n module = importlib.util.module_from_spec(spec)\n sys.modules['tester'] = module\n spec.loader.exec_module(module)\n obj = models.Status.objects.get(id=s)\n try:\n obj.Status=module.check_java('java'+str(s),'model')\n except rq.timeouts.JobTimeoutException:\n obj.Status=\"TLE\"\n except:\n obj.Status=\"Compile Error\"\n obj.save()\n\nclass ParticipantView(View):\n def get(self, request):\n if request.user.is_active:\n try:\n userName = request.user.username\n userId = request.user.id\n except:\n userName = ''\n userId = 0\n try:\n\n id = userId\n allContest = models.Contest.objects.all().order_by('-id')\n # print(allContest)\n\n idContestRegis = models.RegisterContest.objects.filter(IDUser=request.user.id).values_list('IDContest',flat=True).order_by('-id') # contest that user regis before\n # print(list(idContestRegis))\n contestRegisted = []\n for id in list(idContestRegis):\n contestRegisted.append(allContest.filter(id=id)[0])\n # print('contestRegisted',contestRegisted)\n \n allStatus = models.Status.objects.filter(IDUser=request.user.id).order_by('-id')\n idContestSubmitted = allStatus.values_list('IDcontest',flat=True)\n statusContestSubmitted = allStatus.values_list('Status',flat=True)\n contestSubmitted = []\n index = 0\n for id in list(idContestSubmitted):\n selected = allContest.filter(id=id)[0]\n selected.Result = statusContestSubmitted[index]\n repeated = list(filter(lambda x: int(x.id) == int(id), contestSubmitted))\n if not repeated:\n contestSubmitted.append(selected)\n else:\n if not re.findall('[a-zA-Z]', selected.Result) and selected.Result > repeated[0].Result:\n jndex = contestSubmitted.index(repeated[0])\n contestSubmitted[jndex] = selected\n index += 1\n # print('contestSubmitted',contestSubmitted)\n \n contestUnRegisted = []\n for contest in allContest:\n if contest not in contestRegisted and contest not in contestSubmitted:\n contestUnRegisted.append(contest)\n # print('contestUnRegisted', contestUnRegisted)\n\n except Exception as e:\n print(e)\n\n context = {\n 'name': userName,\n 'unRegisContests':list(contestUnRegisted),\n 'regisContests':list(contestRegisted),\n 'historyContests': list(contestSubmitted),\n }\n\n \n return render(request, path.templateParticipant , context)\n else:\n #request.session['messAuth'] = 'Please Log In'\n return redirect('login')\n def post(self, request):\n #do sth\n return redirect('./')\n\n\nclass Register(View):\n def get(self, request, id):\n if request.user.is_active:\n try:\n userName = request.user.username\n userId = request.user.id\n except:\n userName = ''\n userId = ''\n try:\n\n\n selectedContest = models.Contest.objects.get(id=id)\n time_reg_string = selectedContest.TimeRegister.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_start_string = selectedContest.TimeStart.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_now = datetime.now()\n \n\n time_reg = datetime.strptime(time_reg_string,\"%Y-%m-%d %H:%M:%S\")\n time_start = datetime.strptime(time_start_string,\"%Y-%m-%d %H:%M:%S\")\n\n status = ''\n if time_now > time_reg and time_now < time_start:\n try:\n regisTemplate = models.RegisterContest(IDContest=id,IDUser=userId)\n regisTemplate.save()\n status = 'OK'\n except Exception as e:\n print(e)\n status = 'FAIL'\n else:\n status = 'PENDING'\n \n # print(status)\n\n except Exception as e:\n print(e)\n\n context = {\n 'name': userName,\n 'registerStatus': status,\n 'contest': selectedContest\n }\n\n\n return render(request, path.templateRegister , context)\n else:\n request.session['messAuth'] = 'Please Log In'\n return redirect('login')\n\n\nclass Starting(View):\n def get(self, request, id):\n # print(id)\n if request.user.is_active:\n try:\n userName = request.user.username\n userId = request.user.id\n except:\n userName = ''\n userId = ''\n\n try:\n\n \n selectedContest = models.Contest.objects.get(id=id)\n time_start_string = selectedContest.TimeStart.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_end_string = selectedContest.TimeEnd.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_now = datetime.now()\n print(time_now)\n\n time_start = datetime.strptime(time_start_string,\"%Y-%m-%d %H:%M:%S\")\n time_end = datetime.strptime(time_end_string,\"%Y-%m-%d %H:%M:%S\")\n\n\n if time_now < time_start:\n status = 'PENDING'\n else:\n if time_now > time_end:\n status = 'EXPIRED' \n else:\n status = 'OK'\n \n except Exception as e:\n print(e)\n context = {\n 'name': userName,\n 'startStatus': status,\n 'contest': selectedContest, # selected by id\n 'timeEnd': selectedContest.TimeEnd.strftime(\"%m/%d/%Y %H:%M:%S\"),\n 'timeStart': selectedContest.TimeStart.strftime(\"%m/%d/%Y %H:%M:%S\"),\n 'language': models.Language.objects.all()\n }\n # print(context)\n return render(request, path.templateStart , context)\n else:\n request.session['messAuth'] = 'Please Log In'\n return redirect('login')\n def post(self, request,id):\n # Check time Submit\n selectedContest = models.Contest.objects.get(id=id)\n time_end_string = selectedContest.TimeEnd.strftime(\"%Y-%m-%d %H:%M:%S\")\n time_now = datetime.now()\n time_end = datetime.strptime(time_end_string,\"%Y-%m-%d %H:%M:%S\")\n if time_now > time_end:\n return redirect('/start/'+id)\n\n # Submit\n f = request.FILES[\"file\"]\n name = str(f)\n # print(name)\n path = './static/contest/contest'+str(id)+'/'\n if \".py\" in name:\n obj = models.Status()\n obj.IDcontest = id\n obj.IDUser = request.user.id\n obj.Status = 'Pending'\n obj.TimeSubmit = datetime.now()\n obj.save()\n obj.LinkSubmit = path+str(obj.id)+'.py'\n obj.save()\n with open(obj.LinkSubmit, 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n # run_tester(obj.id,path)\n t = models.Contest.objects.get(id=id).TimeOut * 8\n # print(t)\n queue = django_rq.get_queue('default',default_timeout=t)\n queue.enqueue(run_tester,obj.id,path,result_ttl=0) \n if \".cpp\" in name:\n obj = models.Status()\n obj.IDcontest = id\n obj.IDUser = request.user.id\n obj.Status = 'Pending'\n obj.TimeSubmit = datetime.now()\n obj.save()\n obj.LinkSubmit = path+str(obj.id)+'.cpp'\n obj.save()\n with open(obj.LinkSubmit, 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n # run_tester_cpp(obj.id,path)\n t = models.Contest.objects.get(id=id).TimeOut * 8\n # print(t)\n queue = django_rq.get_queue('default',default_timeout=t)\n queue.enqueue(run_tester_cpp,obj.id,path,result_ttl=0) \n if \".java\" in name:\n obj = models.Status()\n obj.IDcontest = id\n obj.IDUser = request.user.id\n obj.Status = 'Pending'\n obj.TimeSubmit = datetime.now()\n obj.save()\n path_java = path+'java'+str(obj.id)\n if not os.path.exists(path_java):\n os.makedirs(path_java)\n obj.LinkSubmit = path_java+'/model.java'\n obj.save()\n with open(obj.LinkSubmit, 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n # run_tester_java(obj.id,path)\n t = models.Contest.objects.get(id=id).TimeOut * 8\n # print(t)\n queue = django_rq.get_queue('default',default_timeout=t)\n queue.enqueue(run_tester_java,obj.id,path,result_ttl=0) \n return redirect('/contest/status/'+id)\n\nclass Standing(View):\n def get(self, request, id):\n userName = str()\n try:\n userName = request.user.username\n except:\n userName = ''\n # Scoreboard\n status = models.Status.objects.filter(IDcontest = id).order_by('-Status','TimeSubmit')\n timestart = models.Contest.objects.get(id=id).TimeStart\n data = []\n error = []\n for x in status:\n time = x.TimeSubmit-timestart\n tg = {\n 'iduser' : x.id,\n 'name' : User.objects.get(id = x.IDUser).username,\n 'time' : x.TimeSubmit,\n 'pen' : round(time.seconds/60),\n 'status' : x.Status\n }\n if x.Status=='TLE' or x.Status=='Compile Error' or x.Status=='Pending':\n error.append(tg)\n else :\n data.append(tg)\n data = data + error\n kt = []\n final = []\n for x in data:\n if x.get('name') in kt:\n continue\n else:\n kt.append(x.get('name'))\n final.append(x)\n context = {\n 'name': userName,\n 'dataContests': final,\n }\n return render(request,path.templateContestStanding,context)","sub_path":"ContestAi/ContestParticipant/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"206069716","text":"import sys\nimport decimal\n\ndef sisort(filename):\n file=open(filename)\n for line in file:\n list1=[]\n list2=[]\n for word in line.split():\n if word.startswith('-'):\n list1.append(float(word))\n else:\n list2.append(float(word))\n list1.sort()\n list2.sort()\n for word in list1:\n print('{0:.3f}'.format(word), end=' ')\n for word in list2:\n print('{0:.3f}'.format(word), end=' ')\n print('')\n file.close()\nsisort(sys.argv[1])\n","sub_path":"Python/complete/simplesorting.py3","file_name":"simplesorting.py3","file_ext":"py3","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"538008344","text":"\"\"\"\nDescription\nGiven a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.\n\nNow, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.\n\nAfter merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.\n\nThe length of accounts will be in the range [1, 1000].\nThe length of accounts[i] will be in the range [1, 10].\nThe length of accounts[i][j] will be in the range [1, 30].\n\n \nExample\nGiven\n\n[\n [\"John\", \"johnsmith@mail.com\", \"john00@mail.com\"],\n [\"John\", \"johnnybravo@mail.com\"],\n [\"John\", \"johnsmith@mail.com\", \"john_newyork@mail.com\"],\n [\"Mary\", \"mary@mail.com\"]\n]\nReturn\n\n[\n [\"John\", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],\n [\"John\", \"johnnybravo@mail.com\"],\n [\"Mary\", \"mary@mail.com\"]\n]\nExplanation:\nThe first and third John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe second John and Mary are different people as none of their email addresses are used by other accounts.\n\nYou could return these lists in any order, for example the answer\n\n[\n ['Mary', 'mary@mail.com'],\n ['John', 'johnnybravo@mail.com'],\n ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']\n]\nis also acceptable.\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param accounts: List[List[str]]\n @return: return a List[List[str]]\n \"\"\"\n \n \"\"\"\n 这道题需要一个很重要的小方法:enumerate()\n 这个方法可以让一个List中的元素附加一个它的index,如\n >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']\n >>> list(enumerate(seasons))\n [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]\n \n 然后很重要的两个实现就是emails_to_ids 和 id_to_emails\n 1. emails_to_ids的实现思维就是:\n 原本的数据中可能是\n [\n [\"John\", \"j200@mail.com\",\"j2@mail.com\"], <- id = 1, emails = XXXXX\n [\"John\", \"j1@mail.com\"], <- id = 2, emails = XXXXX\n [\"John\", \"j1@mail.com\",\"j2@mail.com\"] <- id = 3, emails = XXXXX\n ]\n \n 在enumerate加上每个id以后,\n emails_to_ids[email] = emails_to_ids.get(email, []) (有就拿,没有就[])\n emails_to_ids.append(i)\n 这两步的意义就是,对于每一条id对应下的emails们里面的每一个email,\n 我把它所对应的用户id都一次次加进一个set里。\n 如, emails_to_ids[j1@mail.com]一开始没东西,是[],然后把id = 2放进去了。\n 接着又放了2。结果就是emails_to_ids[j1@mail.com]这个set里面会有\n => [2,3]\n \n 在主方法里面,对于这么些(email, ids), 如emails_to_ids[j1@mail.com] -> [2,3]\n 把2和3的id合并一下,就变成了 emails_to_ids[j1@mail.com] -> 一个老大哥id = 2\n \n 2. id_to_emails的实现思维就是:\n 对于id = 1, 2, 3这三个john来说,我们先把id = 1的john的老大哥找出来。\n 在1.中,j2@mail.com -> id = 1, id = 3 j200@mail.com -> id = 1\n j1@gmail.com -> id = 2, id = 3\n 然后1, 3合并了, 2,3也合并了,那么1,2,3都合并了\n \n 现在,重新来一遍,在enumerate之后每一个id对应的它的一堆emails之间,\n 我就找到这每一个id的老大哥,然后把这个id有的email全部给老大哥。\n 那id = 1 的老大哥是3, 2的也是3 ,那么老大哥被给予的email_set\n 就是上面这些全部email了\n 基本上就是 1 有 j200, j2 2 有 j1 3 有 j1 j2\n 那么老大哥先加了j2--, j2 然后又加了j1, 因为j1,j2都有了,到了id=3时就不弄了\n john id = 3 -> set()\n john id = 3 -> \"j200@mail.com\",\"j2@mail.com\"\n john id = 3 -> \"j200@mail.com\",\"j2@mail.com\",\"j1@mail.com\"\n \n 上面这步完成后就想办法加到结果里就好了\n \n \"\"\"\n def accountsMerge(self, accounts):\n self.initialize(len(accounts))\n emails_to_ids = self.get_email_to_ids(accounts)\n \n for email, ids in emails_to_ids.items():\n root_id = ids[0]\n for id in ids[1:]:\n self.union(id, root_id)\n \n id_to_emails_set = self.get_id_to_emails(accounts)\n \n merged_accounts = []\n for user_id, email_set in id_to_emails_set.items():\n merged_accounts.append([\n accounts[user_id][0],\n *sorted(email_set),])\n \n return merged_accounts\n \n \n def initialize(self, n):\n self.father = {}\n for i in range(n):\n self.father[i] = i\n \n #注意 emails_to_ids的初始默认是[], 相当Java里的List 这两个方法在Java版本中比较好体现\n def get_email_to_ids(self, accounts):\n emails_to_ids = {}\n for i, account in enumerate(accounts):\n for email in account[1:]:\n emails_to_ids[email] = emails_to_ids.get(email, [])\n emails_to_ids[email].append(i)\n return emails_to_ids\n \n #注意 id_to_emails_set的初始默认是 set(), 相当java的HashSet,去重用\n def get_id_to_emails(self, accounts):\n id_to_emails_set = {}\n for user_id, account in enumerate(accounts):\n root_user_id = self.find(user_id)\n email_set = id_to_emails_set.get(root_user_id, set())\n for email in account[1:]:\n email_set.add(email)\n id_to_emails_set[root_user_id] = email_set\n return id_to_emails_set\n \n def union(self, id_1, id_2):\n root_1 = self.find(id_1)\n root_2 = self.find(id_2)\n if (root_1 != root_2):\n self.father[root_1] = root_2\n \n def find(self, user_id):\n path = []\n while user_id != self.father[user_id]:\n path.append(user_id)\n user_id = self.father[user_id]\n \n for u_id in path:\n self.father[u_id] = user_id\n \n return user_id\n \n","sub_path":"Data Structure 1/Accounts Merge.py","file_name":"Accounts Merge.py","file_ext":"py","file_size_in_byte":6653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"119954784","text":"import os\nimport sys\nimport logging\nimport shutil\n\nfrom pkg_resources import resource_exists, resource_filename\n\nfrom chapbucket import module\nfrom chapbucket.util import ChapbucketException\n\nlog = logging.getLogger(__name__)\n\nSKELETON_DIR = 'data/skel'\n\n\nclass EnvironmentException(ChapbucketException):\n pass\n\n\nclass Environment(object):\n \"\"\"\n Represents a chapbucket environment.\n\n Can be used to easily get paths to certain\n locations within an environment.\n\n \"\"\"\n def __init__(self, path):\n self.path = _PathBuilder(path)\n self.modules = _Modules(self.path.code)\n\n\n\ndef get_environment(path, environments = {}):\n \"\"\"Returns Env instance or creates if not yet exists for path.\"\"\"\n # Clean the path\n path = os.path.normpath(path)\n if path not in environments:\n environments[path] = Environment(path)\n return environments[path]\n\n\nclass _PathBuilder(object):\n \"\"\"Generate paths for directories inside a module.\"\"\"\n def __init__(self, path):\n self._path = path\n\n def __str__(self):\n return self._path\n\n def __getattr__(self, name):\n return os.path.join(self._path, name)\n\n\nclass _Modules(object):\n \"\"\"CB's module management.\"\"\"\n def __init__(self, code_dir):\n self._code_dir = code_dir\n self._loaded = {}\n\n def resolve(self, name):\n \"\"\"Return path to actual module.\"\"\"\n path = os.path.join(self._code_dir, name)\n if not os.path.isdir(path):\n raise EnvironmentException(\n \"No directory found for name: %s\" % name)\n return path\n\n def load(self, name):\n \"\"\"Load a plugin.\"\"\"\n if name in self._loaded:\n return self._loaded[name]\n path = self.resolve(name)\n self._loaded[name] = module.load(path)\n\n\ndef discover(paths=None):\n \"\"\"Find the path of the current chapbucket environment.\"\"\"\n if not paths:\n paths = [os.getcwd()]\n main = sys.modules['__main__']\n if hasattr(main, '__file__'):\n # TODO: is that a good idea? What if we have a wrapper script?\n main_file = main.__file__\n if os.path.isfile(main_file):\n paths.append(os.path.dirname(main_file))\n\n for path in paths:\n env = _discover_walker(path)\n if env:\n return env\n raise EnvironmentException(\"No environment was found.\")\n\n\ndef _discover_walker(path):\n \"\"\"Walk directory tree upwards to find cp environment.\"\"\"\n last = None\n found = None\n while last != path:\n cp_dotfile = os.path.join(path, '.chapbucket')\n hidden_dotfile = os.path.join(cp_dotfile, '.chapbucket')\n if os.path.isfile(cp_dotfile):\n found = cp_dotfile\n break\n if os.path.isfile(hidden_dotfile):\n found = hidden_dotfile\n break\n last, path = path, os.path.dirname(path)\n return Environment(found) if found else None\n\n\ndef create(path, mkdir=False, overwrite=False):\n \"\"\"Set up chapbucket directory structure inside path.\"\"\"\n try:\n discover([path])\n except EnvironmentException:\n pass\n else:\n raise EnvironmentException(\"Do not nest chapbucket installations.\")\n\n if not os.path.isdir(path):\n if not mkdir:\n raise EnvironmentException(\"Destination does not exist\")\n else:\n os.makedirs(path)\n elif os.path.isdir(path) and not overwrite:\n if os.listdir(path):\n raise EnvironmentException(\"Destination is not empty\")\n\n if not resource_exists('chapbucket', SKELETON_DIR):\n raise EnvironmentException(\"Resource folder is inacessible\")\n skel_dir = resource_filename('chapbucket', SKELETON_DIR)\n for node in os.listdir(skel_dir):\n shutil.copy(os.path.join(skel_dir, node), path)\n","sub_path":"src/chapbucket/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"598088021","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom requests_html import HTMLSession\nimport requests\n'''\nsession = HTMLSession()\nr = session.get('https://python.org/')\nall_links = r.html.links\nprint(all_links)\n\nall_absolute_links = r.html.absolute_links\nprint(all_absolute_links) '''\n\ndef save_img(url, title):\n img_res = requests.get(url)\n with open('./bg'+title+'.jpg' , 'wb') as fb:\n fb.write(img_res.content)\n\nurl = \"http://www.win4000.com/wallpaper_2358_0_10_1.html\"\nsession = HTMLSession()\nr = session.get(url)\n\nitem_img = r.html.find('ul.clearfix > li > a')\nfor img in item_img:\n img_url = img.attrs['href']\n if \"/wallpaper_detail\" in img_url:\n r = session.get(img_url)\n item_img = r.html.find('img.pic-large', first=True)\n url = item_img.attrs['src']\n title = item_img.attrs['title']\n print(url+title)\n save_img(url, title)\n\n\n","sub_path":"autotest/testreq_html.py","file_name":"testreq_html.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"292296521","text":"import smtplib\nimport time\nimport socket\nimport imapclient\nimport pyzmail\nimport os\nimport webbrowser\nimport shelve\nimport pprint\n# at&t: number@mms.att.net\n# t-mobile: number@tmomail.net\n# verizon: number@vtext.com\n# sprint: number@page.nextel.com\nuser=0\nmessages=list()\npart1=list()\nhey=list()\nconvos=list()\nimapObj=imapclient.IMAPClient('imap.gmail.com',ssl=True)\nserver=smtplib.SMTP(socket.gethostbyname('smtp.gmail.com'),587)\nserver.starttls()\nemail=input('What is your gmail? ')\nemail=email+'@gmail.com'\npassword=input('What is your password? ')\nserver.login(email,password)\nimapObj.login(email,password)\nprint('Succesful Login')\nprint('----------------------------------')\nwhile(True):\n number=input('Who are you trying to contact? (type /q to quit) ')\n addressbook=shelve.open('address')\n if number in addressbook.keys():\n name=number\n number=addressbook.get(number)\n convo=open(number+'.txt','a+')\n addressbook.close()\n elif number=='/q':\n break\n else:\n new=input('There is no record of them in your addressbook, is this a new number? (y/n) ')\n if new =='y':\n while(True): \n carrier=input('What is their carrier? ')\n if carrier =='att':\n number=number+'@mms.att.net'\n break\n elif carrier == 'tmobile':\n number=number+'tmomail.net'\n break\n elif carrier =='verizon':\n number=nummber+'vtext.com'\n break\n elif carrier =='sprint':\n number=number+'page.nextel.com'\n break\n else:\n print('Please choose (att,tmobile,verizon,sprint)')\n continue\n while (True):\n add=input('Would you like to add them to your address book? (y/n) ')\n if add=='y':\n name=input(\"What is their name? \")\n addressbook[name]= number\n convo=open(number+'.txt','a+')\n addressbook.close()\n break\n elif add=='n':\n convo=open(number+'.txt','a+')\n name=number\n addressbook.close()\n break\n else:\n continue\n else:\n continue\n print(' ')\n webbrowser.open(number+'.txt')\n print('Type Your Message Below (type /q to quit), (type /c to check messages)')\n while(True):\n message=input()\n if message== '/q':\n convo.close\n break\n if message=='/c':\n imapObj.select_folder('INBOX',readonly=False)\n replies=imapObj.search(['UNSEEN','FROM',number])\n raw=imapObj.fetch(replies,['BODY[]'])\n for i in range (0,len(replies)):\n messages=messages+[pyzmail.PyzMessage.factory(raw[replies[i]][b'BODY[]'])]\n for i in range (0,len(raw)):\n convos=convos+[messages[i].html_part.get_payload().decode(messages[i].html_part.charset)]\n hey=convos[i][353:len(convos[i])]\n hello=convos[i][352]\n for c in hey:\n if c=='\\n':\n break\n hello=hello+c\n part1=part1+[hello]\n part2=open('temp.txt','w+')\n if len(replies) != 0:\n part2.write('\\n')\n for i in range (1,len(part1)+1):\n part2.write(name+': '+ part1[-i])\n part3=open(number+'.txt','r')\n content=part3.read()\n part2.write(content)\n part3.close()\n part2.close()\n part2=open('temp.txt','r')\n content=part2.read()\n convo.close()\n convo=open(number+'.txt','w+')\n convo.write(content)\n part2.close()\n part1=list()\n convos=list()\n messages=list()\n convo.close()\n os.startfile(number+'.txt')\n input('Hit Enter to return to texting')\n os.system('TASKKILL /F /IM notepad.exe')\n convo=open(number+'.txt','a+')\n continue\n server.sendmail('hello',number,message)\n print('Sending...',end=' ')\n for i in range (0,3):\n print('...', end=' ')\n time.sleep(1)\n print('Sent!')\n part2=open('temp.txt','w+')\n part3=open(number+'.txt','r')\n content=part3.read()\n part2.write('Me: '+message+'\\n')\n part2.write(content)\n part2.close()\n part3.close()\n part3=open('temp.txt','r')\n content=part3.read()\n part2=open(number+'.txt','w+')\n part2.write(content)\n part2.close()\n part3.close()\n \n \n\n\n","sub_path":"Python/TextingDownWards.py","file_name":"TextingDownWards.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"456722425","text":"from random import randint\n\n__author__ = \"Matthew Andersen\"\n\n\ndef main():\n pick_num = int(input(\"How many quick picks? \"))\n pick_gen(pick_num)\n\n\ndef pick_gen(pick_num):\n for i in range(pick_num):\n num_list = []\n while len(num_list) != 6:\n random_num = randint(1, 45)\n if random_num not in num_list:\n num_list.append(random_num)\n print(*sorted(num_list), sep=' \\t') # Format method for each item in list\n\nmain()\n","sub_path":"Prac04/DoFromScratch/quick_pick.py","file_name":"quick_pick.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"302104238","text":"# Librerias\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport time\nimport random\n\n\ndef init_workres_array(workers):\n pet_in = []\n for i in range(workers):\n pet_in.append([])\n return pet_in\n\ndef RaoundRobin(cargas, list_to, workers):\n for x in range(len(list_to)):\n select_bin = x % workers\n cargas[select_bin].append(list_to[x])\n return cargas\n\ndef PseudoRandom(cargas, list_to, workers):\n for x in range(len(list_to)):\n select_bin = random.randint(0, workers-1)\n cargas[select_bin].append(list_to[x])\n return cargas\n\ndef TwoChoices(cargas, list_to, workers):\n select_bin = 0\n select_bin2 = 0\n aux = True\n if(workers==1):\n for x in range(len(list_to)):\n cargas[0].append(list_to[x])\n else:\n for x in range(len(list_to)):\n select_bin = random.randint(0, workers-1)\n while(aux):\n select_bin2 = random.randint(0, workers-1)\n if(select_bin != select_bin2):\n aux = False\n if( len(cargas[select_bin]) < len(cargas[select_bin2]) ):\n cargas[select_bin].append(list_to[x])\n else:\n cargas[select_bin2].append(list_to[x])\n aux = True\n return cargas\n\ndef type_blane_cond(tipo):\n if (tipo=='Y'):\n return 'Ano'\n elif (tipo=='M'):\n return 'Mes'\n elif (tipo=='D'):\n return 'Dia'\n else:\n return 'Mes'\n\ndef read_CSV(name):\n return pd.read_csv(\"./data/\"+name+\".csv\")\n","sub_path":"preparation/utils_balance.py","file_name":"utils_balance.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"387402679","text":"from flask import Flask, redirect, request, render_template, session, url_for\nfrom flask import jsonify\nimport json\nimport mysql.connector\nfrom mysql.connector import Error\n\nfrom flask import Blueprint\norders_api = Blueprint(\"orders_api\", __name__, static_folder=\"static\", template_folder=\"template\")\n\n\n\n# MySQL connect setting \nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"1qaz@WSX#EDC\",\n database=\"user\"\n)\n\nmycursor = mydb.cursor()\n\n\n# Write orders info in\n@orders_api.route(\"/api/orders\", methods=['POST'])\ndef get_order():\n try:\n request_data = request.get_json()\n\n userId = session['id']\n userName = session['name']\n userEmail = session['email']\n bookingAttractionId = session['attractionId']\n bookingDate = session['date']\n bookingPrice = session['price']\n contactName = request_data['contactName']\n contactEmail = request_data['contactEmail']\n contactNumber = request_data['contactNumber']\n\n\n if not (contactName and contactEmail and contactNumber):\n return jsonify({ \"error\": True, \"message\": \"聯絡資料不得為空\" })\n\n else:\n sql = \"INSERT INTO booking_info (userId, userName, userEmail, bookingAttractionId, bookingDate, bookingPrice, contactName, contactEmail, contactNumber) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);\"\n new_data = (userId, userName, userEmail, bookingAttractionId, bookingDate, bookingPrice, contactName, contactEmail, contactNumber)\n mycursor.execute(sql, new_data)\n\n # 確認資料有存入資料庫\n mydb.commit()\n mycursor.close()\n\n # Delete ordered info session\n session.pop('attractionId', None)\n session.pop('date', None)\n session.pop('time', None)\n session.pop('price', None)\n\n\n return jsonify({\"ok\":True})\n\n except:\n errormessage = {\n \"error\" : True,\n \"message\" : \"伺服器錯誤\"\n }\n return jsonify(errormessage)\n\n\n\n","sub_path":"routes/orders_api.py","file_name":"orders_api.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"534259542","text":"import urllib.parse\r\nimport requests\r\n\r\nmain_api = \"https://www.mapquestapi.com/directions/v2/route?\"\r\norig = \"Washington\"\r\ndest = \"Baltimaore\"\r\nkey = \"CcA2LVlpehrBKhAyaiAaF0ffmNEibVyT\"\r\n\r\nurl = main_api + urllib.parse.urlencode({\"key\": key, \"from\":orig, \"to\":dest})\r\n\r\n#json_data = requests.get(url).json()\r\n#print(json_data)\r\n\r\n#Parte 2 del ejercicio\r\n\r\nprint(\"URL: \" + (url)) #Imprimir URL\r\njson_data = requests.get(url).json()#Verificar los datos devueltos \r\njson_status = json_data[\"info\"][\"statuscode\"]\r\nif json_status == 0: #Para verificar si hay una llamada exitosa\r\n print(\"API Status: \" + str(json_status) + \" = A successful route call.\\n\") #Mostrar el valor del código de estado y su significado\r\n\"\"\"Fin de la parte 2\"\"\"\r\n#Gerardo Trujillo Azpeitia\r\n","sub_path":"unidad_2/actividad-2/08_parse-json2_Gerardo.py","file_name":"08_parse-json2_Gerardo.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"393111456","text":"'''\nApplication : ReplSim\nFile name : config.py\nAuthors : Jacob Summerville, Martin Lopez, Henry Lee\nCreation : 04/17/21\nDescription : This file contains the cache configuration\n'''\n\n# Copyright (c) April 26, 2021 Jacob Summerville, Martin Lopez, Henry Lee\n# All rights reserved.\n#\n# The license below extends only to copyright in the software and shall\n# not be construed as granting a license to any other intellectual\n# property including but not limited to intellectual property relating\n# to a hardware implementation of the functionality of the software\n# licensed hereunder. You may use the software subject to the license\n# terms below provided that you ensure that this notice is replicated\n# unmodified and in its entirety in all distributions of the software,\n# modified or unmodified, in source code or in binary form.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met: 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 copyright holders nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport sys, argparse\n\nb = 1\nB = 1\nKB = 1024\nMB = 1048576\nGB = 1073741824\n\nclass CacheConfig(dict):\n \"\"\" This class sets the cache configuration \"\"\"\n def __init__(self):\n self.cache_config = { 'memory' : None,\n 'mem_src' : '',\n 'mem_size' : None,\n 'mem_range' : None,\n 'mem_pattern' : 'normal',\n 'address_size' : 32 * b,\n 'cache_size' : 8 * KB,\n 'line_size' : 32 * B,\n 'mult_sims' : 1,\n }\n\n def __getitem__(self, key):\n return self.cache_config[key]\n\n def __setitem__(self, key, value):\n if key not in self.cache_config.keys():\n print(\"\\nKeyError: '{}' does not exist in settings\".format(key))\n print('The following keys exist:')\n print('\\tmemory')\n print('\\tmem_type')\n print('\\tmem_range')\n print('\\tmem_size')\n print('\\tmem_range')\n print('\\taddress_size')\n print('\\tcache_size')\n print('\\tline_size')\n print('\\tmult_sims')\n \n sys.exit()\n\n self.cache_config[key] = value\n\ncache_config = CacheConfig()\n","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"309463656","text":"import re\nimport numpy, wave,matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport librosa\nimport librosa.display\nfrom PIL import Image\nimport re\nimport shutil\nfrom create_base import *\nfrom create_labels_files import *\nfrom myDtw import *\n\ndef load_and_trim(path):\n audio, sr = librosa.load(path)\n energy = librosa.feature.rmse(audio)\n frames = np.nonzero(energy >= np.max(energy) / 5)\n indices = librosa.core.frames_to_samples(frames)[1]\n audio = audio[indices[0]:indices[-1]] if indices.size else audio[0:0]\n\n return audio, sr\n\n\ndef load_and_trim_v2(path,offset,duration):\n audio, sr = librosa.load(path, offset=offset, duration=duration)\n energy = librosa.feature.rmse(audio)\n frames = np.nonzero(energy >= np.max(energy) / 5)\n indices = librosa.core.frames_to_samples(frames)[1]\n audio = audio[indices[0]:indices[-1]] if indices.size else audio[0:0]\n\n return audio, sr\n\nsavepath = 'e:/test_image/'\nfilename = 'F:/项目/花城音乐项目/样式数据/2.27MP3/旋律/视唱1-02(90).wav'\n\n#y, sr = librosa.load(filename)\ny, sr = load_and_trim(filename)\nchromagram = librosa.feature.chroma_cqt(y, sr=sr)\nlibrosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', cmap='coolwarm')\n\nonset_frames = librosa.onset.onset_detect(y=y, sr=sr)\nonset_times = librosa.frames_to_time(onset_frames, sr=sr)\nplt.vlines(onset_times, 0, y.max(), color='r', linestyle='--')\nonset_samples = librosa.time_to_samples(onset_times)\nprint(onset_samples)\n#plt.subplot(len(onset_times),1,1)\nplt.show()\n\nplt.figure(figsize=(5,80))\nfor i in range(0, len(onset_times)):\n start = onset_samples[i] - sr/2\n if start < 0:\n start =0\n end = onset_samples[i] + sr/2\n #y2 = [x if i> start and i start and i start and irunningMax):\n\n\t\trunningMax=abs(getCosSim(pastState[0], currentState))\n\t\trunningPrediction = pastState[1]\n\t#\tprint(runningPrediction)\t\n#\tprint(abs(np.corrcoef(pastState[0], currentState)[0][1]))\n\n\ndef getPrediction(corpus, currentState):\n\trunningMax = 0\n\trunningPrediction = 0\n\tfor corpusState in corpus:\n\t\tif(abs(getCosSim(corpusState[0], currentState))>runningMax and corpusState[1]<100):\n\t\t\trunningMax = abs(getCosSim(corpusState[0], currentState))\n\t\t\trunningPrediction = corpusState[1]\n\treturn runningPrediction\n\nprint(getPrediction(weekVectors, currentState))\ncurrentState.append(runningPrediction)\n\n\n\nfor x in range(1,1000):\n\tcurrentState.append(getPrediction(weekVectors, currentState[x:]))\n\nfor i in range(0, len(currentState)):\n\tcurrentState[i] = (currentState[i]/100)*mostRecentPrice + mostRecentPrice\n\tmostRecentPrice = currentState[i]\nprint(currentState)\nplt.plot(currentState)\nplt.show()\n#keeps going for number of desired predictions\n# for i in range(0,6):\n# print(runningPrediction)\n# currentState.append(runningPrediction)\n# plt.plot(currentState)\n# plt.show()\n#attempt #1, each \"word\" is 7 days (arbitrary period, assume some level of periodicity because of week, maybe will do fft later). \n#Similarity (correlation coeff) between 2 vectors is a weight, set boundary similarity for considered \"equality\" current goal is just to be able to guess direction accurately\n\n","sub_path":"btcBuySell.py","file_name":"btcBuySell.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"95989304","text":"from collections import deque\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\nclass _LogsManager():\n __pending = deque()\n\n def __init__(self, filename):\n self.__logger = logging.getLogger('plugin_logger')\n self.__logger.setLevel(logging.DEBUG)\n self.__handler = RotatingFileHandler(filename, maxBytes=1048576, backupCount=3, delay=False)\n self.__logger.addHandler(self.__handler)\n\n def _update(self):\n for _ in range(0, len(_LogsManager.__pending)):\n entry = _LogsManager.__pending.popleft()\n self.__logger.info(entry)\n\n @classmethod\n def _received_request(cls, request):\n cls.__pending.append(request)","sub_path":"nanome/_internal/_process/_logs_manager.py","file_name":"_logs_manager.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345881925","text":"from model import EnvironmentModel, RunEnvironmentModel\n# from swarms.utils.jsonhandler import JsonData\nfrom swarms.utils.graph import Graph, GraphACC\nfrom joblib import Parallel, delayed\nfrom swarms.utils.results import SimulationResults\n\n# Global variables for width and height\nwidth = 100\nheight = 100\n\nUI = False\n\n\ndef simulate(agent, iteration):\n # Testing the performane of evolved behavior\n phenotype = agent.individual[0].phenotype\n # iteration = 10000\n threshold = 75.0\n sim = RunEnvironmentModel(\n 100, 100, 100, 10, iter=iteration, xmlstring=phenotype)\n sim.build_environment_from_json()\n\n # for all agents store the information about hub\n for agent in sim.agents:\n agent.shared_content['Hub'] = {sim.hub}\n\n simresults = SimulationResults(\n sim.pname, sim.connect, sim.sn, sim.stepcnt, sim.food_in_hub(),\n phenotype\n )\n simresults.save_phenotype()\n simresults.save_to_file()\n\n # Iterate and execute each step in the environment\n for i in range(iteration):\n # For every iteration we need to store the results\n # Save them into db or a file\n sim.step()\n simresults = SimulationResults(\n sim.pname, sim.connect, sim.sn, sim.stepcnt, sim.food_in_hub(),\n phenotype\n )\n simresults.save_to_file()\n\n # print(\"Total food in the hub\", len(food_objects))\n value = sim.food_in_hub()\n\n foraging_percent = (\n value * 100.0) / (sim.num_agents * 2.0)\n\n sucess = False\n if foraging_percent >= threshold:\n print('Foraging success')\n sucess = True\n\n # sim.experiment.update_experiment_simulation(value, sucess)\n sim.experiment.update_experiment_simulation(value, sucess)\n\n # Plot the fitness in the graph\n graph = GraphACC(sim.pname, 'simulation.csv')\n graph.gen_plot()\n\n\ndef evolve(iteration):\n # iteration = 10000\n\n env = EnvironmentModel(100, 100, 100, 10, iter=iteration)\n env.build_environment_from_json()\n\n # for all agents store the information about hub\n for agent in env.agents:\n agent.shared_content['Hub'] = {env.hub}\n\n # Hub and site object\n # print(env.hub, env.site)\n\n # Iterate and execute each step in the environment\n for i in range(iteration):\n env.step()\n\n env.experiment.update_experiment()\n\n best_agent = env.top\n\n # Find if food has been deposited in the hub\n grid = env.grid\n food_loc = (0, 0)\n neighbours = grid.get_neighborhood(food_loc, 5)\n food_objects = grid.get_objects_from_list_of_grid('Food', neighbours)\n for food in food_objects:\n if food.agent_name == best_agent:\n print('Foraging success', food.id, food.location)\n\n # Plot the fitness in the graph\n graph = Graph(env.pname, 'best.csv', ['explore', 'foraging'])\n graph.gen_best_plots()\n\n # Test the evolved behavior\n return env.agents[best_agent]\n\n\ndef main(iter):\n agent = evolve(iter)\n simulate(agent, iter)\n\n\nif __name__ == '__main__':\n # Running 50 experiments in parallel\n\n Parallel(n_jobs=4)(delayed(main)(i) for i in range(1000, 900000, 2000))\n # Parallel(n_jobs=4)(delayed(main)(i) for i in range(1000, 8000, 2000))\n # main(100)\n","sub_path":"examples/comm_foraging_evolution/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"2201756","text":"\n# Copyright 2017-present Open Networking Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport os\nimport sys\n\nimport datetime\nimport time\n\nfrom xossynchronizer.steps.syncstep import SyncStep\nfrom xossynchronizer.modelaccessor import MCordSubscriberInstance\n\nfrom xosconfig import Config\nfrom multistructlog import create_logger\nimport json\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\n\n\nlog = create_logger(Config().get('logging'))\n\nparentdir = os.path.join(os.path.dirname(__file__), \"..\")\nsys.path.insert(0, parentdir)\nsys.path.insert(0, os.path.dirname(__file__))\nfrom helpers import ProgranHelpers\n\nclass SyncImsiBack(SyncStep):\n provides = [MCordSubscriberInstance]\n\n observes = MCordSubscriberInstance\n\n\n def call(self, failed=[], deletion=False):\n \"\"\"\n Read profile from progran and save them in xos\n \"\"\"\n\n if deletion == False:\n # NOTE we won't it to run only after the delete has completed\n return\n\n log.debug(\"Reading IMSI from progran\")\n onos = ProgranHelpers.get_progran_onos_info(self.model_accessor)\n imsi_url = \"http://%s:%s/onos/progran/imsi/\" % (onos['url'], onos['port'])\n r = requests.get(imsi_url, auth=HTTPBasicAuth(onos['username'], onos['password']))\n res = r.json()['ImsiArray']\n\n log.debug(\"Received IMSIs: \", imsis=res)\n\n field_mapping = {\n 'IMSI': 'imsi_number',\n 'UeStatus': 'ue_status'\n }\n\n field_transformations = {\n 'UeStatus': ProgranHelpers.int_to_string,\n }\n\n updated_imsi = []\n\n for i in res:\n try:\n si = MCordSubscriberInstance.objects.get(imsi_number=i['IMSI'])\n log.debug(\"IMSI %s already exists, updating it\" % i['IMSI'])\n except IndexError:\n si = MCordSubscriberInstance()\n\n si.no_sync = True\n si.backend_code = 1\n si.backend_status = \"OK\"\n si.created_by = \"Progran\"\n\n log.debug(\"IMSI %s is new, creating it\" % i['IMSI'])\n\n si = ProgranHelpers.update_fields(si, i, field_mapping, field_transformations)\n\n si.save()\n\n updated_imsi.append(si.imsi_number)\n\n existing_imsi = [p.imsi_number for p in MCordSubscriberInstance.objects.all() if not p.is_new]\n deleted_imsi = ProgranHelpers.list_diff(existing_imsi, updated_imsi)\n\n if len(deleted_imsi) > 0:\n log.debug(\"Profiles %s have been removed in progran, removing them from XOS\" % str(deleted_imsi))\n for p in deleted_imsi:\n si = MCordSubscriberInstance.objects.get(imsi_number=p)\n # if si.created_by == 'XOS' and si.previously_sync == False:\n # don't delete if the imsi has been created by XOS and it hasn't been sync'ed yet\n # continue\n si.delete()\n","sub_path":"xos/synchronizer/steps/sync_imsi_back.py","file_name":"sync_imsi_back.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"482738574","text":"\"\"\"\nMerges multiple history sqlite databases into one\n\"\"\"\n\nimport warnings\nfrom datetime import datetime\nfrom typing import Iterator, Iterable, Sequence, Set, Tuple, List\n\nfrom .log import logger\nfrom .model import Visit\nfrom .common import PathIsh, expand_path\nfrom .parse import read_visits\n\n# not sure on the typing/Sequence's with splat here\n# works fine though, each of these accept variadic arguments\n# with either PathIsh-things or Iterator/List things w/ Visits\n\n\ndef read_and_merge(paths: Sequence[PathIsh]) -> Iterator[Visit]:\n \"\"\"\n Receives any amount of Path-like databases as input,\n reads Visits from each of those databases,\n and merges them together (removing duplicates)\n \"\"\"\n pths = [expand_path(p) for p in paths]\n hst: List[Iterator[Visit]] = list(map(read_visits, pths))\n yield from merge_visits(hst)\n\n\ndef merge_visits(sources: Sequence[Iterable[Visit]]) -> Iterator[Visit]:\n \"\"\"\n Removes duplicate Visit items from multiple sources\n \"\"\"\n if len(sources) == 0:\n warnings.warn(\"merge_visits received no sources!\")\n else:\n logger.debug(f\"merging information from {len(sources)} sources...\")\n # use combination of URL, visit date and visit type to uniquely identify visits\n emitted: Set[Tuple[str, datetime]] = set()\n duplicates = 0\n for src in sources:\n for vs in src:\n key = (vs.url, vs.dt)\n if key in emitted:\n # logger.debug(f\"skipping {key} => {vs}\")\n duplicates += 1\n continue\n yield vs\n emitted.add(key)\n logger.debug(\"Summary: removed {} duplicates...\".format(duplicates))\n logger.info(\"Summary: returning {} visit entries...\".format(len(emitted)))\n","sub_path":"browserexport/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"621030304","text":"\"\"\"Contains the unit tests and helper functions to test\n the meetup feature of the BeLL app\"\"\"\nimport datetime\nimport unittest\nfrom selenium.common.exceptions import (NoSuchElementException,\n StaleElementReferenceException,\n TimeoutException)\nfrom selenium.webdriver.common.alert import Alert\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import Select, WebDriverWait\nfrom time import sleep\n\nimport bell\nfrom base_case import BaseCase, browsers, on_platforms\n\n\n@on_platforms(browsers)\nclass MeetupTest(BaseCase):\n \"\"\"Contains the unit tests and helper functions to test the meetup feature\n of the BeLL app\"\"\"\n\n def create_meetup(self, num_days=1, cancel=False, recurring=False):\n \"\"\"Creates a meetup that lasts num_days, and if recurring is set to true,\n then it will select the recurring option. If cancel is set to true\n then it will hit cancel after filling the form.\"\"\"\n driver = self.driver\n wait = WebDriverWait(driver, 30)\n bell.login(driver, \"admin\", \"password\")\n self.assertTrue(self.go_to_meetups())\n\n # Make sure the'Add Meetup' button is there and press it.\n # Keep clicking the button till its gone.\n add_id = 'linkOfMeetUpHeading'\n wait.until(EC.element_to_be_clickable((By.ID, add_id)))\n add_meetup_btn = driver.find_element_by_id(add_id)\n\n keepclicking = True\n while keepclicking:\n try:\n add_meetup_btn.click()\n sleep(1)\n except StaleElementReferenceException:\n keepclicking = False\n\n self.fill_meetup_form(recurring=recurring, num_of_days=num_days)\n if cancel is False:\n # Bring up the invite page, since this is a new meetup.\n submit = driver.find_element_by_id(\"MeetUpformButton\")\n submit.click()\n wait.until(EC.presence_of_element_located((By.ID, 'formButton')))\n return True\n\n def fill_meetup_form(self, recurring, num_of_days):\n \"\"\"Fills out the meetup form with filler information.\"\"\"\n driver = self.driver\n wait = WebDriverWait(driver, 30)\n\n # Wait for the form to appear and fill it out.\n wait.until(EC.presence_of_element_located((By.ID, 'meetUpForm')))\n wait.until(EC.element_to_be_clickable((By.NAME, 'title')))\n\n elem = driver.find_element_by_name(\"title\")\n elem.send_keys(\"test_meetup.py - Test Meetup\")\n elem = driver.find_element_by_name(\"description\")\n desc = \"This is a test meeting automatically created by test_meetup.py\"\n elem.send_keys(desc)\n elem = driver.find_element_by_name(\"startDate\")\n elem.send_keys(datetime.datetime.now().strftime('%m/%d/%Y'))\n elem = driver.find_element_by_name(\"endDate\")\n end_date = datetime.datetime.now() \\\n + datetime.timedelta(days=num_of_days)\n elem.send_keys(end_date.strftime('%m/%d/%Y'))\n\n elem = driver.find_element_by_name(\"startTime\")\n elem.send_keys(\"8:00am\")\n elem = driver.find_element_by_name(\"endTime\")\n elem.send_keys(\"11:00pm\")\n\n elem = driver.find_element_by_name(\"category\")\n wait.until(EC.element_to_be_clickable((By.NAME, 'category')))\n select = Select(elem)\n select.select_by_value('E Learning')\n\n elem = driver.find_element_by_name(\"meetupLocation\")\n elem.send_keys(\"Test catagory\")\n if recurring:\n css_sel = 'input[type=\"radio\"]'\n recurring_radio = driver.find_element_by_css_selector(css_sel)\n recurring_radio.click()\n rec_id = recurring_radio.get_attribute(\"id\")\n wait.until(EC.element_located_to_be_selected((By.ID, rec_id)))\n\n def go_to_meetups(self):\n \"\"\"\"Navigates to the meetups tab.\"\"\"\n driver = self.driver\n wait = WebDriverWait(driver, 15)\n # Go to the meetups tab\n wait.until(EC.element_to_be_clickable((By.ID, 'itemsinnavbar')))\n old_page = driver.find_element_by_id('dashboard')\n css_sel = 'a[href=\"#meetups\"]'\n wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sel)))\n meetups_tab = driver.find_element_by_css_selector(css_sel)\n meetups_tab.click()\n\n # Clicking on the meetups link doesn't always work,\n # so keep trying until we are at the meetups page.\n # This might only be needed due to a bug in the site see:\n # https://github.com/open-learning-exchange/BeLL-Apps/issues/585\n keeptrying = True\n numoftries = 0\n while keeptrying:\n try:\n # If the old page is stale then we are on the meetups tab.\n wait.until(EC.staleness_of(old_page))\n keeptrying = False\n except TimeoutException:\n wait.until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, css_sel)))\n meetups_tab = driver.find_element_by_css_selector(css_sel)\n meetups_tab.click()\n numoftries = numoftries + 1\n if numoftries == 4:\n # If we still haven't got there something else went wrong.\n keeptrying = False\n return False\n\n heading_id = 'linkOfMeetUpHeading'\n wait.until(EC.presence_of_element_located((By.ID, heading_id)))\n return True\n\n def save_meetup(self):\n \"\"\"Saves the currently open meetup.\"\"\"\n driver = self.driver\n try:\n submit = driver.find_element_by_id(\"formButton\")\n submit.click()\n except (TimeoutException, NoSuchElementException):\n print(\"Could not submit invatations. \\\n Check that you navigated to \\\n the invation screen and that formButton exists.\")\n return False\n\n WebDriverWait(driver, 25).until(EC.alert_is_present())\n actual = Alert(driver).text\n expected = \"Invitation sent successfully.\"\n Alert(driver).accept()\n return actual == expected\n\n def test_add_new_meetup_singleday(self):\n \"\"\"Creates a meetup for a single day.\"\"\"\n self.create_meetup(1)\n result = self.save_meetup()\n self.assertEqual(True, result)\n\n def test_delete_meetup(self):\n \"\"\"Deletes all meetups containing 'test_meetup.py'\"\"\"\n driver = self.driver\n wait = WebDriverWait(driver, 25)\n bell.login(driver, \"admin\", \"password\")\n result = self.go_to_meetups()\n self.assertEqual(True, result)\n\n # Check if there is at least one row of meetups.\n is_meetups_present = False\n try:\n x_path = \"//*[@id='parentLibrary']/table/tbody/tr[2]/td[4]/a\"\n driver.find_element_by_xpath(x_path)\n is_meetups_present = True\n except NoSuchElementException:\n self.assertEqual(True, is_meetups_present)\n\n # Delete any meetups made by test_meetup.py\n meetups_xpath = \\\n \"//*[@id='parentLibrary']/table/tbody/tr[contains(.,'test_meetup.py')]\\\n /td/a[@class='destroy btn btn-danger']\"\n meetups = driver.find_elements_by_xpath(meetups_xpath)\n meetups_deleted = False\n attempts = 0\n while len(meetups) > 0:\n try:\n meetups[0].click()\n wait.until(EC.alert_is_present())\n Alert(driver).accept()\n wait.until(EC.staleness_of(meetups[0]))\n # Reload list -- the list is stale now that we deleted one.\n meetups = driver.find_elements_by_xpath(\n \"//*[@id='parentLibrary']/table/tbody/tr[contains(.,'Test')]\\\n /td/a[@class='destroy btn btn-danger']\")\n meetups_deleted = True\n except (StaleElementReferenceException,\n NoSuchElementException, TimeoutException):\n\n attempts = attempts + 1\n if attempts > 5:\n meetups_deleted = False\n break\n\n self.assertEqual(True, meetups_deleted)\n\n def test_invite_member(self):\n \"\"\"Selects all members and invites them\"\"\"\n driver = self.driver\n wait = WebDriverWait(driver, 15)\n self.create_meetup(1)\n elem = driver.find_element_by_name(\"invitationType\")\n wait.until(EC.element_to_be_clickable((By.NAME, 'invitationType')))\n\n invitation_type = Select(elem)\n index = 0\n for opt in invitation_type.options:\n if index == 1:\n opt.click()\n index = index + 1\n\n wait.until(EC.presence_of_element_located((By.NAME, 'members')))\n members_list = driver.find_element_by_name('members')\n chkboxes = members_list.find_elements_by_tag_name(\"input\")\n\n for val in chkboxes:\n val.click()\n\n sleep(1)\n result = self.save_meetup()\n self.assertEqual(True, result)\n\n def test_multiday_meetup(self):\n \"\"\"Tests a multiday meetup\"\"\"\n self.create_meetup(3)\n result = self.save_meetup()\n self.assertEqual(True, result)\n\n def test_recurring_meetup(self):\n \"\"\"Tests a recurring meetup\"\"\"\n self.assertTrue(self.create_meetup(1, recurring=True))\n result = self.save_meetup()\n self.assertEqual(True, result)\n\n def test_cancel_meetup(self):\n \"\"\"Creates a meetup and cancels on the form screen\"\"\"\n driver = self.driver\n self.create_meetup(1, cancel=True)\n wait = WebDriverWait(driver, 25)\n cancel_id = 'MeetUpcancel'\n wait.until(EC.element_to_be_clickable((By.ID, cancel_id)))\n cancel = driver.find_element_by_id(cancel_id)\n cancel.click()\n heading_id = 'linkOfMeetUpHeading'\n wait.until(EC.presence_of_element_located((By.ID, heading_id)))\n expected = \\\n 'http://127.0.0.1:5981/apps/_design/bell/MyApp/index.html#meetups'\n actual = driver.current_url\n self.assertEqual(expected, actual)\n\n if __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_meetup.py","file_name":"test_meetup.py","file_ext":"py","file_size_in_byte":10255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"600674517","text":"import torch\n\n\ndef create_mask(qlen, mlen, same_length=False):\n \"\"\"create causal attention mask.\"\"\"\n attn_mask = torch.ones([qlen, qlen], dtype=torch.float)\n mask_u = torch.triu(attn_mask, 0)\n mask_dia = torch.tril(attn_mask, 0) - torch.tril(attn_mask, -1)\n attn_mask_pad = torch.zeros([qlen, mlen], dtype=torch.float)\n\n ret = torch.cat([attn_mask_pad, mask_u - mask_dia], 1)\n\n if same_length:\n mask_l = torch.tril(attn_mask, -1)\n ret = torch.cat([ret[:, :qlen] + mask_l - mask_dia, ret[:, qlen:]], 1)\n\n return ret\n","sub_path":"xlnet/model/utils/mask.py","file_name":"mask.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"191907629","text":"import os\nimport json\nimport warnings\nimport functools\nimport operator\n\nimport torch\nimport pandas as pd\nimport numpy as np\n\nclass IndividualParameters:\n r\"\"\"\n IndividualParameters object class.\n The object holds a collection of individual parameters, that are outputs of the api personalization.\n There are used as io of the simulation algorithm, to provide an initial distribution of individual parameters.\n\n Attributes\n ----------\n _indices: list\n List of the patient indices\n _individual_parameters: dict\n Individual indices (key) with their corresponding individual parameters {parameter name: parameter value}\n _parameters_shape: dict\n Shape of each individual parameter\n _default_saving_type: str\n Default extension for saving when none is provided\n\n Methods\n ----------\n add_individual_parameters(index, individual_parameters)\n Adds the individual parameters of a new patient\n __getitem__[index]\n Returns the individual parameters of patient idx\n subset(indices)\n Returns a IndividualParameters object containing only the patients in indices\n get_mean(parameter_name)\n Returns the mean value of the parameter_name across all patients\n get_std(parameter_name)\n Return the standard deviation value of the parameter_name across all patients\n to_dataframe()\n Returns the dataframe of individual parameters\n from_dataframe(df)\n Static method that returns an IndividualParameters object from the dataframe\n to_pytorch()\n Returns the indices, pytorch_dict corresponding to the individual parameters\n from_pytorch(indices, pytorch_dict)\n Static method that returns an IndividualParameters object from the indices and pytorch dictionary\n save(path):\n Saves the individual parameters (json or csv) at the path location\n load(path):\n Static method that loads the individual parameters (json or csv) existing at the path locatio\n \"\"\"\n\n def __init__(self):\n self._indices = []\n self._individual_parameters = {}\n self._parameters_shape = None # {p_name: p_shape as tuple}\n self._default_saving_type = 'csv'\n\n @property\n def _parameters_size(self):\n # convert parameter shape to parameter size\n # e.g. () -> 1, (1,) -> 1, (2,3) -> 6\n shape_to_size = lambda shape: functools.reduce(operator.mul, shape, 1)\n\n return {p: shape_to_size(s)\n for p,s in self._parameters_shape.items()}\n\n def add_individual_parameters(self, index, individual_parameters):\n r\"\"\"\n Add the individual parameter of an individual to the IndividualParameters object\n\n Parameters\n ----------\n index: str\n Index of the individual\n individual_parameters: dict\n Individual parameters of the individual {name: value}\n\n Raises\n ------\n ValueError\n If the index is not a string or has already been added\n\n Examples\n --------\n Add two individual with tau, xi and sources parameters\n\n >>> ip = IndividualParameters()\n >>> ip.add_individual_parameters('index-1', {\"xi\": 0.1, \"tau\": 70, \"sources\": [0.1, -0.3]})\n >>> ip.add_individual_parameters('index-2', {\"xi\": 0.2, \"tau\": 73, \"sources\": [-0.4, -0.1]})\n \"\"\"\n # Check indices\n if type(index) != str:\n raise ValueError(f'The index should be a string ({type(index)} provided instead)')\n\n if index in self._indices:\n raise ValueError(f'The index {index} has already been added before')\n\n # Check the dictionary format\n if type(individual_parameters) != dict:\n raise ValueError('The `individual_parameters` argument should be a dictionary')\n\n # Conversion of numpy arrays to lists\n individual_parameters = {k: v.tolist() if isinstance(v, np.ndarray) else v\n for k, v in individual_parameters.items()}\n\n # Check types of params\n for k, v in individual_parameters.items():\n\n valid_scalar_types = [int, np.int32, np.int64, float, np.float32, np.float64]\n\n scalar_type = type(v)\n if isinstance(v, list):\n scalar_type = None if len(v) == 0 else type(v[0])\n #elif isinstance(v, np.ndarray):\n # scalar_type = v.dtype\n\n if scalar_type not in valid_scalar_types:\n raise ValueError(f'Incorrect dictionary value. Error for key: {k} -> scalar type {scalar_type}')\n\n # Fix/check parameters nomenclature and shapes\n # (scalar or 1D arrays only...)\n pshapes = {p: (len(v),) if isinstance(v, list) else ()\n for p,v in individual_parameters.items()}\n\n if self._parameters_shape is None:\n # Keep track of the parameter shape\n self._parameters_shape = pshapes\n elif self._parameters_shape != pshapes:\n raise ValueError(f'Invalid parameter shapes provided: {pshapes}. Expected: {self._parameters_shape}. Some parameters may be missing/unknown or have a wrong shape.')\n\n # Finally: add to internal dict object + indices array\n self._indices.append(index)\n self._individual_parameters[index] = individual_parameters\n\n\n def __getitem__(self, item):\n if type(item) != str:\n raise ValueError(f'The index should be a string ({type(item)} provided instead)')\n return self._individual_parameters[item]\n\n def subset(self, indices):\n r\"\"\"\n Returns IndividualParameters object with a subset of the initial individuals\n\n Parameters\n ----------\n indices: list\n List of strings that corresponds to the indices of the individuals to return\n\n Returns\n -------\n IndividualParameters\n An instance of the IndividualParameters object with the selected list of individuals\n\n Raises\n ------\n ValueError\n Raise an error if one of the index is not in the IndividualParameters\n\n Examples\n --------\n\n >>> ip = IndividualParameters()\n >>> ip.add_individual_parameters('index-1', {\"xi\": 0.1, \"tau\": 70, \"sources\": [0.1, -0.3]})\n >>> ip.add_individual_parameters('index-2', {\"xi\": 0.2, \"tau\": 73, \"sources\": [-0.4, -0.1]})\n >>> ip.add_individual_parameters('index-3', {\"xi\": 0.3, \"tau\": 58, \"sources\": [-0.6, 0.2]})\n >>> ip_sub = ip.subset(['index-1', 'index-3'])\n \"\"\"\n ip = IndividualParameters()\n\n for idx in indices:\n if idx not in self._indices:\n raise ValueError(f'The index {0} is not in the indices'.format(idx))\n p = self[idx].copy()\n ip.add_individual_parameters(idx, p)\n\n return ip\n\n def get_mean(self, parameter):\n r\"\"\"\n Returns the mean value of the parameter_name across all patients\n\n Parameters\n ----------\n parameter: str\n Name of the parameter\n\n Returns\n -------\n list or float\n Mean value of the parameter\n\n Raises\n ------\n ValueError\n If the parameter is not in the IndividualParameters\n\n Examples\n --------\n\n >>> ip = IndividualParameters.load(\"path/to/individual_parameters\")\n >>> tau_mean = ip.get_mean(\"tau\")\n \"\"\"\n if parameter not in self._parameters_shape.keys():\n ValueError(f\"Parameter {parameter} does not exist in the individual parameters\")\n\n p = [v[parameter] for v in self._individual_parameters.values()]\n p_mean = np.mean(p, axis=0).tolist()\n\n return p_mean\n\n def get_std(self, parameter):\n r\"\"\"\n Returns the stardard deviation of the parameter_name across all patients\n\n Parameters\n ----------\n parameter: str\n Name of the parameter\n\n Returns\n -------\n list or float\n Standard value of the parameter\n\n Raises\n ------\n ValueError\n If the parameter is not in the IndividualParameters\n\n Examples\n --------\n\n >>> ip = IndividualParameters.load(\"path/to/individual_parameters\")\n >>> tau_std = ip.get_std(\"tau\")\n \"\"\"\n if parameter not in self._parameters_shape.keys():\n ValueError(f\"Parameter {parameter} does not exist in the individual parameters\")\n\n p = [v[parameter] for v in self._individual_parameters.values()]\n p_std = np.std(p, axis=0).tolist()\n\n return p_std\n\n def to_dataframe(self):\n r\"\"\"\n Returns the dataframe of individual parameters\n\n Returns\n -------\n dataframe: pandas.DataFrame\n Each row corresponds to one individual. The index corresponds to the individual index. The columns are\n the names of the parameters.\n\n\n Examples\n --------\n Convert the individual parameters object into a dataframe\n\n >>> ip = IndividualParameters.load(\"path/to/individual_parameters\")\n >>> ip_df = ip.to_dataframe()\n \"\"\"\n # Get the data, idx per idx\n arr = []\n for idx in self._indices:\n indiv_arr = [idx]\n indiv_p = self._individual_parameters[idx]\n\n for p_name, p_shape in self._parameters_shape.items():\n if p_shape == ():\n indiv_arr.append(indiv_p[p_name])\n else:\n indiv_arr += indiv_p[p_name] # 1D array only...\n arr.append(indiv_arr)\n\n # Get the column names\n final_names = ['ID']\n for p_name, p_shape in self._parameters_shape.items():\n if p_shape == ():\n final_names.append(p_name)\n else:\n final_names += [p_name+'_'+str(i) for i in range(p_shape[0])] # 1D array only...\n\n df = pd.DataFrame(arr, columns=final_names)\n return df.set_index('ID')\n\n\n @staticmethod\n def from_dataframe(df):\n r\"\"\"\n Static method that returns an IndividualParameters object from the dataframe\n\n Parameters\n ----------\n df: pandas.DataFrame\n Dataframe of the invidual parameters. Each row must correspond to one individual. The index corresponds\n to the individual index. The columns are the names of the parameters.\n\n\n Returns\n -------\n IndividualParameters\n\n \"\"\"\n # Check the names to keep\n df_names = list(df.columns.values)\n\n final_names = {}\n for name in df_names:\n split = name.split('_')[0]\n if split == name: # e.g tau, xi, ...\n final_names[name] = name\n else: # e.g sources_0 --> sources\n if split not in final_names:\n final_names[split] = []\n final_names[split].append(name)\n\n # Create the individual parameters\n ip = IndividualParameters()\n\n for idx, row in df.iterrows():\n i_d = {param: row[col].tolist() if isinstance(col, list) else row[col]\n for param, col in final_names.items()}\n ip.add_individual_parameters(idx, i_d)\n\n return ip\n\n @staticmethod\n def from_pytorch(indices, dict_pytorch):\n r\"\"\"\n Static method that returns an IndividualParameters object from the indices and pytorch dictionary\n\n Parameters\n ----------\n indices: list\n List of the patients indices\n dict_pytorch: dict\n Dictionary of the individual parameters\n\n Returns\n -------\n IndividualParameters\n\n\n Examples\n --------\n\n >>> indices = ['index-1', 'index-2', 'index-3']\n >>> ip_pytorch = {\n >>> \"xi\": torch.tensor([[0.1], [0.2], [0.3]], dtype=torch.float32),\n >>> \"tau\": torch.tensor([[70], [73], [58.]], dtype=torch.float32),\n >>> \"sources\": torch.tensor([[0.1, -0.3], [-0.4, 0.1], [-0.6, 0.2]], dtype=torch.float32)\n >>> }\n >>> ip_pytorch = IndividualParameters.from_pytorch(indices, ip_pytorch)\n\n \"\"\"\n\n len_p = {k: len(v) for k, v in dict_pytorch.items()}\n for k, v in len_p.items():\n if v != len(indices):\n raise ValueError(f'The parameter {k} should be of same length as the indices')\n\n ip = IndividualParameters()\n\n keys = list(dict_pytorch.keys())\n\n for i, idx in enumerate(indices):\n p = {k: dict_pytorch[k][i].tolist() for k in keys}\n p = {k: v[0] if len(v) == 1 and k != 'sources' else v for k, v in p.items()}\n\n ip.add_individual_parameters(idx, p)\n\n return ip\n\n def to_pytorch(self):\n r\"\"\"\n Returns the indices and pytorch dictionary of individual parameters\n\n Returns\n -------\n indices: list\n List of patient indices\n pytorch_dict: dict\n Dictionary of the individual parameters {parameter name: pytorch tensor of values across individuals}\n\n\n Examples\n --------\n Convert the individual parameters object into a dataframe\n\n >>> ip = IndividualParameters.load(\"path/to/individual_parameters\")\n >>> indices, ip_pytorch = ip.to_pytorch()\n \"\"\"\n ips_pytorch = {}\n\n for p_name, p_size in self._parameters_size.items():\n\n p_val = [self._individual_parameters[idx][p_name] for idx in self._indices]\n p_val = torch.tensor(p_val, dtype=torch.float32)\n p_val = p_val.reshape(shape=(len(self._indices), p_size)) # always 2D\n\n ips_pytorch[p_name] = p_val\n\n return self._indices, ips_pytorch\n\n def save(self, path):\n r\"\"\"\n Saves the individual parameters (json or csv) at the path location\n\n Parameters\n ----------\n path: str\n Path and file name of the individual parameters. The extension can be json or csv.\n If no extension, default extension (csv) is used\n\n \"\"\"\n extension = IndividualParameters._check_and_get_extension(path)\n if not extension:\n warnings.warn(f'You did not provide a valid extension (csv or json) for the file. '\n f'Default to {self._default_saving_type}')\n extension = self._default_saving_type\n path = path+'.'+extension\n\n if extension == 'csv':\n self._save_csv(path)\n elif extension == 'json':\n self._save_json(path)\n else:\n raise ValueError(f\"Something bad happened: extension is {extension}\")\n\n @staticmethod\n def load(path):\n r\"\"\"\n Static method that loads the individual parameters (json or csv) existing at the path locatio\n\n Parameters\n ----------\n path: str\n Path and file name of the individual parameters.\n\n Returns\n -------\n IndividualParameters:\n Individual parameters object load from the file\n\n Raises\n ------\n ValueError:\n If the provided extension is not csv not json\n\n Examples\n --------\n\n >>> ip = IndividualParameters.load('/path/to/individual_parameters_1.json')\n >>> ip2 = IndividualParameters.load('/path/to/individual_parameters_2.csv')\n \"\"\"\n extension = IndividualParameters._check_and_get_extension(path)\n if not extension or extension not in ['csv', 'json']:\n raise ValueError('The file you provide should have a `.csv` or `.json` name')\n\n if extension == 'csv':\n ip = IndividualParameters._load_csv(path)\n elif extension == 'json':\n ip = IndividualParameters._load_json(path)\n else:\n raise ValueError(f\"Something bad happened: extension is {extension}\")\n\n return ip\n\n @staticmethod\n def _check_and_get_extension(path):\n _, ext = os.path.splitext(path)\n if len(ext) == 0:\n return False\n else:\n return ext[1:]\n\n def _save_csv(self, path):\n df = self.to_dataframe()\n df.to_csv(path)\n\n def _save_json(self, path):\n json_data = {\n 'indices': self._indices,\n 'individual_parameters': self._individual_parameters,\n 'parameters_shape': self._parameters_shape\n }\n\n with open(path, 'w') as f:\n json.dump(json_data, f)\n\n @staticmethod\n def _load_csv(path):\n\n df = pd.read_csv(path, dtype={'ID':str}).set_index('ID')\n ip = IndividualParameters.from_dataframe(df)\n\n return ip\n\n @staticmethod\n def _load_json(path):\n with open(path, 'r') as f:\n json_data = json.load(f)\n\n ip = IndividualParameters()\n ip._indices = json_data['indices']\n ip._individual_parameters = json_data['individual_parameters']\n ip._parameters_shape = json_data['parameters_shape']\n\n # convert json lists to tuple for shapes\n ip._parameters_shape = {p: tuple(s) for p,s in ip._parameters_shape.items()}\n\n return ip\n","sub_path":"leaspy/io/outputs/individual_parameters.py","file_name":"individual_parameters.py","file_ext":"py","file_size_in_byte":17162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"371585708","text":"import os\nimport tensorflow as tf\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.framework import graph_util\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\ndef save():\n x = tf.placeholder(tf.float32, shape=[1, 3], name='x')\n\n w = tf.get_variable('weight', shape=[3, 2], initializer=tf.ones_initializer())\n b = tf.get_variable('bias', shape=[2], initializer=tf.ones_initializer())\n\n # y = x*w + b\n y = tf.add(tf.matmul(x, w), b, name='y')\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n predict = sess.run(y, feed_dict={x: [[1.0, 2.0, 3.0]]})\n print(\"y: %s\" % predict)\n\n # save\n constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['y'])\n with tf.gfile.FastGFile('./model/graph_util/model.pb', mode='wb') as f:\n f.write(constant_graph.SerializeToString())\n print(\"Model saved.\")\n\n\ndef restore():\n with tf.Session() as sess:\n # restore\n with gfile.FastGFile('./model/graph_util/model.pb', 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n sess.graph.as_default()\n tf.import_graph_def(graph_def, name='')\n sess.run(tf.global_variables_initializer())\n print('Model restored.')\n\n x = sess.graph.get_tensor_by_name('x:0')\n y = sess.graph.get_tensor_by_name('y:0')\n\n predict = sess.run(y, feed_dict={x: [[1.0, 2.0, 3.0]]})\n print(\"y: %s\" % predict)\n\n\ndef main():\n save()\n restore()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"save_restore/save_restore_saver_graph_util.py","file_name":"save_restore_saver_graph_util.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"133654987","text":"# This file summarizes some helper functions to analyse the track time extraction. They are used by the\n# study script extracted_time_mc_compare.py\nimport basf2\nimport numpy as np\n\nfrom ROOT import Belle2\nimport ROOT\n\nfrom tracking.harvest.harvesting import harvest\nfrom tracking.harvest.refiners import save_tree, save_pull_analysis\n\nDriftTimeUtil = Belle2.TrackFindingCDC.DriftTimeUtil\n\n\nclass RandomizeTrackTimeModule(basf2.Module):\n \"\"\"\n Main module for the analysis: take the CDCSimHits as well as the MCParticles\n and add the mc_drift value to their internal event time.\n If the mc_drift is -999, set the drift for each event to a random value between\n -50 and 50.\n\n Please note that this module needs to run between the FullSim and the CDCDigitizer module.\n Also, setting the MCParticles time has no influence on the event at all, nut is just for later\n reference and to compare the reconstructed/extracted time with something.\n \"\"\"\n\n def __init__(self, mc_drift):\n \"\"\"\n Create a new RandomizeTrackTimeModule instance.\n :param mc_drift: The drift in ns to which the CDCSimHits and MCParticles should be shifted.\n \"\"\"\n self.mc_drift = mc_drift\n\n basf2.Module.__init__(self)\n\n def event(self):\n \"\"\"\n Shift the MCParticles (just for reference) and the CDCSimHits.\n :return:\n \"\"\"\n cdc_sim_hits = Belle2.PyStoreArray(\"CDCSimHits\")\n mc_particles = Belle2.PyStoreArray(\"MCParticles\")\n\n if self.mc_drift == -999:\n mc_drift = np.random.randint(-50, 50)\n else:\n mc_drift = self.mc_drift\n\n for cdc_sim_hit in cdc_sim_hits:\n cdc_sim_hit.setFlightTime(cdc_sim_hit.getFlightTime() + float(mc_drift))\n\n # JUST FOR LATER REFERENCE!\n for mc_particle in mc_particles:\n mc_particle.setProductionTime(float(mc_drift))\n\n\nclass MCRecoTracksResetModule(basf2.Module):\n \"\"\"\n If we use the TrackFinderMCTruth for testing, it will use the track time stored in the MCParticles,\n which makes the time extraction too simple. Instead, we have to reset the track time to 0 and set the\n track start position to the first hit, which will allow us to use the IPTrackTimeEstimator later.\n \"\"\"\n\n def event(self):\n \"\"\"\n Reset the track position of all reco tracks to start at their first hit and set the time seed to 0.\n \"\"\"\n reco_tracks = Belle2.PyStoreArray(\"RecoTracks\")\n\n for reco_track in reco_tracks:\n # Set the time seed to 0\n reco_track.setTimeSeed(0)\n\n # Define the position and momentum at the first CDC hit:\n first_cdc_hit = reco_track.getSortedCDCHitList()[0]\n first_cdc_wire = Belle2.TrackFindingCDC.CDCWire.getInstance(first_cdc_hit)\n first_hit_position = first_cdc_wire.getRefPos2D()\n\n helix = Belle2.Helix(reco_track.getPositionSeed(), reco_track.getMomentumSeed(),\n reco_track.getChargeSeed(), 1.5)\n\n arc_length_at_first_hit = helix.getArcLength2DAtXY(first_hit_position.x(), first_hit_position.y())\n momentum_at_first_hit = helix.getMomentumAtArcLength2D(arc_length_at_first_hit, 1.5)\n\n position_t_vector = helix.getPositionAtArcLength2D(arc_length_at_first_hit)\n momentum_t_vector = ROOT.TVector3(momentum_at_first_hit.x(), momentum_at_first_hit.y(),\n momentum_at_first_hit.z())\n reco_track.setPositionAndMomentum(position_t_vector, momentum_t_vector)\n\n\ndef add_harvester(path, mc_drift, generator_module, track_finder, turns):\n \"\"\"\n Add four harvester to the path. The harvester are better described in their corresponding functions.\n Use the parameters to control the name of the root output files.\n :param path: To which path to add the modules.\n :param mc_drift: Which drift was applied to the mc particles.\n :param generator_module: Which generator was used.\n :param track_finder: Which track finding algorithm was used.\n :param turns: How many turns the track extraction had.\n \"\"\"\n @save_pull_analysis(truth_name=\"mc_production_time\",\n estimate_name=\"reco_track_time\",\n part_name=\"track_time\")\n @save_tree(name=\"tree\")\n @harvest(foreach=\"EventT0\", show_results=False,\n output_file_name=\"harvest_track_time_{mc_drift}_{generator}_{track_finder}_{turns}.root\".format(\n mc_drift=mc_drift, generator=generator_module, track_finder=track_finder, turns=turns))\n def harvest_track_time(event_t0):\n \"\"\"\n Write out the extracted time from the EventT0 and compare it to the MCParticle time.\n \"\"\"\n mc_particles = Belle2.PyStoreArray(\"MCParticles\")\n\n if event_t0 is not None:\n time_seed = event_t0.getEventT0()\n else:\n time_seed = -999\n\n if mc_particles[0] is not None:\n mc_time = mc_particles[0].getProductionTime()\n else:\n mc_time = -999\n\n yield dict(mc_production_time=mc_time,\n reco_track_time=time_seed)\n\n @save_tree(name=\"tree\")\n @harvest(\n foreach=\"EventMetaData\",\n show_results=False,\n output_file_name=\"harvest_extracted_times_{mc_drift}_{generator}_{track_finder}_{turns}.root\".format(\n mc_drift=mc_drift, generator=generator_module, track_finder=track_finder, turns=turns))\n def harvest_extracted_times(event_meta_data):\n \"\"\"\n Do one time extraction step and write out the extracted derivatives and some information on the track.\n \"\"\"\n for reco_track in Belle2.PyStoreArray(\"__SelectedRecoTracks\"):\n pair_of_results = Belle2.TimeExtractionUtils.getChi2Derivatives(reco_track)\n\n yield {\n \"dchi2da\": pair_of_results.first,\n \"d2chi2da2\": pair_of_results.second,\n \"pt\": reco_track.getMomentumSeed().Pt(),\n \"charge\": reco_track.getChargeSeed(),\n \"number_of_hits\": reco_track.getNumberOfCDCHits(),\n \"event_number\": event_meta_data.getEvent()\n }\n\n @save_tree(name=\"tree\")\n @harvest(foreach=\"__SelectedRecoTracks\",\n show_results=False,\n output_file_name=\"harvest_full_chi2_grid_{mc_drift}_{generator}_{track_finder}_{turns}.root\".format(\n mc_drift=mc_drift, generator=generator_module, track_finder=track_finder, turns=turns))\n def harvest_full_chi2_grid(reco_track):\n \"\"\"\n Do a grid search on the range -30 to 30 and extract the time.\n\n This means go to 30 points between -30 and 30, set the global event time, do a fit, extract the time\n and calculate the chi2. All this information together with an event number will be stored in the ROOT file.\n \"\"\"\n track_fitter = Belle2.TrackFitter()\n\n initial_value = reco_track.getTimeSeed()\n\n reco_track.setTimeSeed(reco_track.getTimeSeed() - 30)\n reco_track.deleteFittedInformation()\n\n delta_t0 = 2\n\n for i in range(30):\n reco_track.setTimeSeed(reco_track.getTimeSeed() + delta_t0)\n reco_track.deleteFittedInformation()\n\n track_fitter.fit(reco_track)\n\n extractedDerivatePair = Belle2.TimeExtractionUtils.getChi2Derivatives(reco_track)\n extractedTime = extractedDerivatePair.first / extractedDerivatePair.second\n try:\n chi2 = reco_track.getTrackFitStatus().getChi2() / reco_track.getTrackFitStatus().getNdf()\n except ZeroDivisionError:\n chi2 = 999\n\n yield dict(t0_estimate=reco_track.getTimeSeed(),\n chi2=chi2,\n extracted_time=extractedTime,\n )\n\n reco_track.setTimeSeed(initial_value)\n\n @save_tree(name=\"tree\")\n @harvest(foreach=\"EventMetaData\",\n show_results=False,\n output_file_name=\"harvest_chi2_path_{mc_drift}_{generator}_{track_finder}_{turns}.root\".format(\n mc_drift=mc_drift, generator=generator_module, track_finder=track_finder, turns=turns))\n def harvest_chi2_path(event_meta_data):\n \"\"\"\n Harvesting module build after the FullGridTrackTimeExtractionModule. Does the same as this module,\n but writes out information in every iteration step together with an event number.\n \"\"\"\n track_fitter = Belle2.TrackFitter()\n\n t0_min = -30\n t0_max = 30\n\n def extract_until_finished(reco_track, start_value, event_number, number_of_tries, try_list):\n current_try = 0\n\n initial_value = reco_track.getTimeSeed()\n\n reco_track.setTimeSeed(initial_value + start_value)\n reco_track.deleteFittedInformation()\n\n track_fitter.fit(reco_track)\n\n if not reco_track.wasFitSuccessful():\n return\n\n chi2 = Belle2.TimeExtractionUtils.extractReducedChi2(reco_track)\n derivatives_pair = Belle2.TimeExtractionUtils.getChi2Derivatives(reco_track)\n\n reco_track_time = reco_track.getTimeSeed()\n try_list.append(dict(chi2=chi2, extracted_time=reco_track_time, event_number=event_number, finished=False,\n first_deriv=derivatives_pair.first,\n second_deriv=derivatives_pair.second, delta_t0=np.NaN, delta_chi2=np.NaN))\n current_try += 1\n\n for i in range(number_of_tries):\n extracted_time = Belle2.TimeExtractionUtils.extractTime(reco_track)\n derivatives_pair = Belle2.TimeExtractionUtils.getChi2Derivatives(reco_track)\n reco_track.setTimeSeed(reco_track.getTimeSeed() + extracted_time)\n reco_track.deleteFittedInformation()\n\n track_fitter.fit(reco_track)\n\n if not reco_track.wasFitSuccessful():\n break\n\n chi2 = Belle2.TimeExtractionUtils.extractReducedChi2(reco_track)\n\n reco_track_time = reco_track.getTimeSeed()\n\n if abs(reco_track_time) > 30 or chi2 > 10:\n break\n\n finished = derivatives_pair.second > 2.7122 and chi2 < 1.739\n\n try_list.append(dict(chi2=chi2, extracted_time=reco_track_time,\n event_number=event_number,\n first_deriv=derivatives_pair.first,\n second_deriv=derivatives_pair.second,\n finished=finished, delta_t0=np.NaN, delta_chi2=np.NaN))\n current_try += 1\n\n reco_track.setTimeSeed(initial_value)\n reco_track.deleteFittedInformation()\n\n if current_try > 2 and abs(try_list[-1][\"extracted_time\"] - try_list[-2][\"extracted_time\"]) < 2:\n try_list[-1][\"delta_t0\"] = try_list[-1][\"extracted_time\"] - try_list[-2][\"extracted_time\"]\n try_list[-1][\"delta_chi2\"] = try_list[-1][\"chi2\"] - try_list[-2][\"chi2\"]\n\n event_number = event_meta_data.getEvent()\n\n for reco_track in Belle2.PyStoreArray(\"__SelectedRecoTracks\"):\n try_list = []\n\n extract_until_finished(reco_track, t0_min + 0.2 * (t0_max - t0_min), event_number, 2, try_list)\n extract_until_finished(reco_track, t0_min + 0.4 * (t0_max - t0_min), event_number, 2, try_list)\n extract_until_finished(reco_track, t0_min + 0.6 * (t0_max - t0_min), event_number, 2, try_list)\n extract_until_finished(reco_track, t0_min + 0.8 * (t0_max - t0_min), event_number, 2, try_list)\n\n for try_out in try_list:\n yield try_out\n\n finished_ones = list(filter(lambda x: x[\"finished\"], try_list))\n if finished_ones:\n yield min(finished_ones, key=lambda i: i[\"chi2\"])\n else:\n best_guesses = sorted(try_list, key=lambda i: i[\"chi2\"])\n for best_guess in best_guesses:\n extract_until_finished(reco_track, best_guess[\"extracted_time\"], event_number, 2, try_list)\n if try_list[-1][\"finished\"]:\n yield try_list[-1]\n return\n\n path.add_module(harvest_track_time)\n # path.add_module(harvest_extracted_times)\n # path.add_module(harvest_full_chi2_grid)\n # path.add_module(harvest_chi2_path)\n","sub_path":"release/cdc/test/time_extraction_helper_modules.py","file_name":"time_extraction_helper_modules.py","file_ext":"py","file_size_in_byte":12535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"510053111","text":"#!/usr/bin/env python\n# encoding:utf-8\n__author__ = 'Chocolee'\n\nimport socket\n\ndef main():\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.bind(('localhost',8088))\n sock.listen(5)\n\n while True:\n connection, address = sock.accept()\n buf = connection.recv(1024)\n data = open('img.html', 'rb').read()\n connection.sendall(bytes(\"HTTP/1.1 201 OK\\r\\n\\r\\n\",\"utf8\"))\n connection.sendall(bytes(data))\n connection.close()\n\nif __name__ == '__main__':\n\n main()","sub_path":"study/前端/html/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"3643443","text":"def build_confirmation_menu(question, defaultResponse=None):\n\n response = None\n default_prompt = \"(y/n)\"\n if defaultResponse:\n default_prompt = \"(Y/n)\"\n elif defaultResponse != None:\n default_prompt = \"(y/N)\"\n\n print(question, default_prompt, \":\", end=\" \")\n while response == None:\n raw_response = input()\n if not raw_response and defaultResponse != None:\n response = defaultResponse\n # elif not raw_response:\n # print('Invalid selection! Please try again.')\n elif raw_response in ['Y','y']:\n response = True\n elif raw_response in ['N','n']:\n response = False\n else:\n print('Invalid selection! Please try again.')\n\n return response","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"587611613","text":"from typing import List\n\nfrom google.protobuf.descriptor import FieldDescriptor\nfrom sqlalchemy import literal, func\n\nfrom backend.database.objects import PlayerGame\nfrom backend.database.utils.dynamic_field_manager import ProtoFieldResult\nfrom backend.database.wrapper.field_wrapper import QueryFieldWrapper\nfrom backend.database.wrapper.stats.stat_math import safe_divide\n\n\nclass SharedStatCreation:\n\n def __init__(self):\n self.dynamic_field_list = None\n self.stat_explanation_list = None\n self.stat_explanation_map = None\n self.stat_list = None\n self.stats_query = None\n self.std_query = None\n self.individual_query = None\n\n @staticmethod\n def create_stats_field_list(field_list, explanation_map, database_object, math_list=None, custom=None) \\\n -> List[QueryFieldWrapper]:\n stat_list = []\n for dynamic_field in field_list:\n query_field = getattr(database_object, dynamic_field.field_name)\n stat_list.append(QueryFieldWrapper(query_field, dynamic_field=dynamic_field))\n\n if math_list is not None:\n stat_list += math_list\n\n if custom is not None:\n stat_list += custom\n\n SharedStatCreation.assign_values(stat_list, explanation_map)\n return stat_list\n\n @staticmethod\n def assign_values(stat_list: List[QueryFieldWrapper], explanation_map):\n for stat in stat_list:\n if isinstance(stat.dynamic_field, ProtoFieldResult):\n if stat.dynamic_field.field_descriptor.type == FieldDescriptor.TYPE_BOOL:\n stat.is_boolean = True\n if 'average' in stat.get_query_key():\n stat.is_averaged = True\n if stat.get_query_key() in explanation_map:\n stat.explanation = explanation_map[stat.get_query_key()]\n\n @staticmethod\n def get_stats_query(stat_list: List[QueryFieldWrapper]):\n avg_list = []\n std_list = []\n individual_list = []\n for stat in stat_list:\n if stat.is_cumulative:\n std_list.append(literal(1))\n avg_list.append(stat.query)\n individual_list.append(stat.query)\n elif stat.is_averaged or stat.is_percent:\n std_list.append(func.stddev_samp(stat.query))\n avg_list.append(func.avg(stat.query))\n individual_list.append(func.sum(stat.query))\n elif stat.is_boolean:\n std_list.append(literal(1))\n avg_list.append(func.count())\n individual_list.append(func.bool_and(stat.query))\n else:\n std_list.append(func.stddev_samp(stat.query))\n avg_list.append(\n 300 * func.sum(stat.query) / safe_divide(func.sum(PlayerGame.time_in_game), default=300))\n individual_list.append(func.sum(stat.query))\n return avg_list, std_list, individual_list\n\n @staticmethod\n def get_wrapped_stats(stats, stat_list):\n zipped_stats = dict()\n\n for i in range(len(stat_list)):\n zipped_stats[stat_list[i].get_query_key()] = stats[i]\n\n return zipped_stats\n\n def get_stat_list(self):\n return self.stat_list\n","sub_path":"backend/database/wrapper/stats/creation/shared_stat_creation.py","file_name":"shared_stat_creation.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"637087968","text":"import numpy as np, cv2\r\n\r\ndef scaling_nearset(img, size):\r\n dst = np.zeros(size[::-1], img.dtype)\r\n ratioY, ratioX = np.divide(size[::-1], img.shape[:2])\r\n i = np.arange(0, size[1], 1) #이놈은 size루다가\r\n j = np.arange(0, size[0], 1)\r\n i, j = np.meshgrid(i, j)\r\n y, x = np.int32(i / ratioY), np.int32(j / ratioX)\r\n dst[i, j] = img[y, x]\r\n\r\n return dst\r\n\r\ndef preprocessing():\r\n image = cv2.imread(\"per1.jpg\", cv2.IMREAD_COLOR)\r\n if image is None: return None, None\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n gray = cv2.equalizeHist(gray)\r\n return image, gray\r\n\r\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_alt2.xml\")\r\nimage, gray = preprocessing()\r\nif image is None: raise Exception(\"영상파일 읽기 에러\")\r\n\r\nfaces = face_cascade.detectMultiScale(gray, 1.1, 2, 0, (100, 100))\r\nif faces.any():\r\n for(x, y, w, h) in faces:\r\n # 얼굴 영역 구하기\r\n face_image = image[y:y + h, x:x + w]\r\n cv2.rectangle(image, faces[0], (0, 0, 0))\r\n\r\n # 구한 얼굴영역 R, G, B로 나누기\r\n # R, G, B 각각 따로 사이즈 작게 했다가 크게하기 << 모자이크 방법\r\n list_bgr = cv2.split(face_image)\r\n dst1 = scaling_nearset(list_bgr[0], (10, 10))\r\n dst1 = scaling_nearset(dst1, (w, h)) # B\r\n\r\n dst2 = scaling_nearset(list_bgr[1], (10, 10))\r\n dst2 = scaling_nearset(dst2, (w, h)) # G\r\n\r\n dst3 = scaling_nearset(list_bgr[2], (10, 10))\r\n dst3 = scaling_nearset(dst3, (w, h)) # R\r\n\r\n # 나눈 R, G, B 합치기\r\n dst_list = [dst1, dst2, dst3]\r\n dst = cv2.merge(dst_list)\r\n\r\n # 합친 얼굴영역 다시 이미지에다가 삽입\r\n image[y:y + h, x:x + w] = dst\r\n\r\n cv2.imshow(\"mosaic\", image)\r\n\r\nelse:\r\n print(\"얼굴 미검출\")\r\n\r\ncv2.waitKey(0)","sub_path":"FIN/fin_pro.py","file_name":"fin_pro.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"506533962","text":"import socket\nimport ipaddress\nfrom concurrent.futures import ThreadPoolExecutor\nimport os\nimport json\nimport sys\n#message:$$name,VNFid,type_id,group_id,iftype$$\n#name=forwarder1, vnf_id=555, type_id=1, group_id=1, iftype=2, bidirectional=False, \n\nportLis=50000\nogeo_location='server1.rack2.row3.room4'\nconf_ip='10.0.0.254'\nconf_port=60000\n\nclass BgRec:\n def __init__(self, host, port):\n \n super(BgRec, self).__init__()\n \n self.pool = ThreadPoolExecutor(128)\n \n self.s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n \n self.buffer = ''\n \n self.s.bind((host,port))\n self.hostName = socket.gethostname()\n #print(\"Port \"+str(portLis)+\" on host \"+self.hostName+\" is listening\")\n\n \n def close(self):\n global connected\n self.s.close()\n connected=False\n return\n \n def handle_read(self):\n #此处有拥塞可能\n self.pool.submit(self.recv)\n \n def recv(self):\n #print('Listening...')\n while True:\n try:\n data,addr=self.s.recvfrom(2048)\n except:\n break\n if not data:\n break\n recvdata=''\n recvdata=str(data,'utf8')\n #print(addr)\n #print(recvdata) \n command=recvdata.split('$$')[1]\n self.dealWithMsg(command,addr)\n \n \n \n def valid_ip(self,address):\n try: \n ipaddress.ip_address(address)\n return True\n except:\n return False\n\n#message:$$name,VNFid,type_id,group_id,iftype$$\n def dealWithMsg(self,command,addr): \n oname=command.split(',')[0]\n oVNFid=command.split(',')[1]\n otype_id=command.split(',')[2]\n ogroup_id=command.split(',')[3]\n oiftype=command.split(',')[4]\n if(int(oiftype)==1 or int(oiftype)==2):\n obidirectional='False'\n elif(int(oiftype)==3):\n obidirectional='True'\n \n register_dict = dict(\n vnf_id = oVNFid,\n name=oname,\n type_id=otype_id,\n group_id=ogroup_id,\n geo_location=ogeo_location,\n iftype=oiftype,\n bidirectional=obidirectional)\n json_message = json.dumps(register_dict)\n\n try:\n s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n except socket.error:\n #print ('Failed to create socket')\n sys.exit()\n s2.sendto(json_message.encode(encoding='utf_8'), (conf_ip, conf_port ))\n\n\nif __name__ == '__main__':\n bgrunner = BgRec('', portLis)\n bgrunner.recv()","sub_path":"listen.py","file_name":"listen.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"618469061","text":"#C:\\Users\\guosen\\AppData\\Local\\Programs\\Python\\Python36-32\n# -*- coding: UTF-8 -*-\nimport DBManager as dbm\nimport ToolConf as conf\nimport traceback\nimport time\nimport re\nimport ResourceApply \nimport xml.sax as xmlSax\nimport queue\n\nclass KbssPDMHandler(xmlSax.ContentHandler):\n def __init__(self,pTableNameList):\n xmlSax.ContentHandler.__init__(self)\n self.lstTableName = pTableNameList\n self.content = ''\n self.blBegDefTable = False\n self.blBegDefCols = False\n self.blBegDefCol = False\n self.blBegDefIndexs = False\n self.blBegDefIndex = False\n self.blBegDefKeys = False\n self.blBegDefKey = False\n self.strTableName = ''\n self.strTableDesc = ''\n self.strFieldName = ''\n self.strFieldDesc = ''\n self.strFieldType = ''\n self.strFieldSize = ''\n self.strFieldPrecision = ''\n self.strFieldRemark = ''\n self.strIndexName = ''\n self.strIndexFields = ''\n self.strUniqueFlag = ''\n self.dictFields = {}\n self.strFieldId = ''\n self.queueNodeTree = queue.LifoQueue()\n self.clApplyResource = ResourceApply.ResourceApply()\n \n def startElement(self,name,attrs):\n try:\n if name == 'o:Table':\n self.blBegDefTable = True\n self.queueNodeTree.put(name)\n else:\n if self.blBegDefTable:\n self.queueNodeTree.put(name)\n if self.blBegDefCols:\n #定义列开始\n if name == 'o:Column':\n self.blBegDefCol = True\n self.strFieldId = attrs['Id']\n elif self.blBegDefIndexs:\n #定义索引开始\n if name == 'o:Index':\n self.blBegDefIndex = True \n else:\n if self.blBegDefIndex:\n if name == 'o:Column':\n if self.strIndexFields == '':\n self.strIndexFields = self.dictFields[attrs['Ref']]\n else:\n self.strIndexFields = self.strIndexFields + ',' + self.dictFields[attrs['Ref']] \n elif self.blBegDefKeys:\n #定义索引开始\n if name == 'o:Key':\n self.blBegDefKey = True \n else:\n if self.blBegDefKey:\n if name == 'o:Column':\n if self.strIndexFields == '':\n self.strIndexFields = self.dictFields[attrs['Ref']]\n else:\n self.strIndexFields = self.strIndexFields + ',' + self.dictFields[attrs['Ref']] \n else:\n #定义表开始\n if self.blBegDefTable:\n if name == 'c:Columns':\n self.blBegDefCols = True\n elif name == 'c:Indexes':\n self.blBegDefIndexs = True\n elif name == 'c:Keys':\n self.blBegDefKeys = True \n except:\n traceback.print_exc(file=open(time.strftime('%Y%m%d',time.localtime()) + 'log.txt','a+'))\n return False \n \n def endElement(self,name):\n try:\n if self.blBegDefCol and (name == 'o:Column'):\n self.blBegDefCol = False\n if self.strFieldSize == '':\n self.strFieldSize = '0'\n if self.strFieldPrecision == '':\n self.strFieldPrecision = '0'\n self.clApplyResource.addTableFieldFromPdm(self.strTableName,self.strFieldName,self.strFieldDesc,self.strFieldType,self.strFieldSize,self.strFieldRemark,self.strFieldPrecision)\n self.strFieldName = ''\n self.strFieldDesc = ''\n self.strFieldType = ''\n self.strFieldSize = ''\n self.strFieldPrecision = ''\n self.strFieldRemark = ''\n elif self.blBegDefIndex and (name == 'o:Index'):\n self.blBegDefIndex = False\n if self.strUniqueFlag == '':\n self.strUniqueFlag = '0'\n if (self.strIndexName != '') and (self.strIndexFields != ''):\n self.clApplyResource.addTableIndexFromPdm(self.strTableName,self.strIndexName,self.strUniqueFlag,self.strIndexFields)\n self.strIndexName = ''\n self.strIndexFields = ''\n self.strUniqueFlag = ''\n elif self.blBegDefKey and (name == 'o:Key'):\n self.blBegDefIndex = False\n if self.strUniqueFlag == '':\n self.strUniqueFlag = '0'\n if (self.strIndexName != '') and (self.strIndexFields != ''):\n self.clApplyResource.addTableIndexFromPdm(self.strTableName,self.strIndexName,self.strUniqueFlag,self.strIndexFields)\n self.strIndexName = ''\n self.strIndexFields = ''\n self.strUniqueFlag = ''\n elif self.blBegDefIndexs and (name == 'c:Indexes'):\n self.blBegDefIndexs = False\n elif self.blBegDefKeys and (name == 'c:Keys'):\n self.blBegDefKeys = False\n elif self.blBegDefCols and (name == 'c:Columns'): \n self.blBegDefCols = False\n elif self.blBegDefTable and (name == 'o:Table'):\n self.queueNodeTree.get()\n self.blBegDefTable = False\n if self.strTableName != '':\n self.clApplyResource.addTableFromPdm(self.strTableName,self.strTableDesc)\n self.strTableName = ''\n self.strTableDesc = ''\n self.dictFields.clear()\n \n if self.blBegDefTable:\n self.queueNodeTree.get()\n if self.blBegDefCols:\n #定义列开始\n if self.blBegDefCol:\n #定义单个列开始\n if name == 'a:Name':\n self.strFieldDesc = self.content\n elif name == 'a:Code':\n self.strFieldName = self.content\n self.dictFields[self.strFieldId] = self.strFieldName\n elif name == 'a:DataType':\n self.strFieldType = re.sub(r'[(].*[)]','',self.content).lower()\n elif name == 'a:Length':\n self.strFieldSize = self.content\n elif name == 'a:Precision':\n self.strFieldPrecision = self.content\n elif name == 'a:Comment':\n self.strFieldRemark = self.content\n elif self.blBegDefIndexs:\n #定义索引开始\n if self.blBegDefIndex:\n if name == 'a:Code':\n self.strIndexName = self.content\n elif name == 'a:Unique':\n self.strUniqueFlag = self.content \n else:\n #定义表开始\n if self.blBegDefTable and (self.queueNodeTree.qsize() == 1):\n if name == 'a:Name':\n self.strTableDesc = self.content\n elif name == 'a:Code':\n self.strTableName = self.content\n if self.lstTableName:\n if self.strTableName not in self.lstTableName:\n self.blBegDefTable = False\n self.queueNodeTree.get() \n except:\n traceback.print_exc(file=open(time.strftime('%Y%m%d',time.localtime()) + 'log.txt','a+'))\n return False \n \n def characters(self,content):\n self.content = content\n","sub_path":"DefTableFromPDM.py","file_name":"DefTableFromPDM.py","file_ext":"py","file_size_in_byte":8395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"574979045","text":"# Copyright 2016 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file or at\n# https://developers.google.com/open-source/licenses/bsd\n\n\"\"\"Persistence class for user groups.\n\nUser groups are represented in the database by:\n- A row in the Users table giving an email address and user ID.\n (A \"group ID\" is the user_id of the group in the User table.)\n- A row in the UserGroupSettings table giving user group settings.\n\nMembership of a user X in user group Y is represented as:\n- A row in the UserGroup table with user_id=X and group_id=Y.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport collections\nimport logging\nimport re\n\nfrom framework import exceptions\nfrom framework import permissions\nfrom framework import sql\nfrom proto import usergroup_pb2\nfrom services import caches\n\n\nUSERGROUP_TABLE_NAME = 'UserGroup'\nUSERGROUPSETTINGS_TABLE_NAME = 'UserGroupSettings'\nUSERGROUPPROJECTS_TABLE_NAME = 'Group2Project'\n\nUSERGROUP_COLS = ['user_id', 'group_id', 'role']\nUSERGROUPSETTINGS_COLS = ['group_id', 'who_can_view_members',\n 'external_group_type', 'last_sync_time',\n 'notify_members', 'notify_group']\nUSERGROUPPROJECTS_COLS = ['group_id', 'project_id']\n\nGROUP_TYPE_ENUM = (\n 'chrome_infra_auth', 'mdb', 'baggins', 'computed')\n\n\nclass MembershipTwoLevelCache(caches.AbstractTwoLevelCache):\n \"\"\"Class to manage RAM and memcache for each user's memberships.\"\"\"\n\n def __init__(self, cache_manager, usergroup_service, group_dag):\n super(MembershipTwoLevelCache, self).__init__(\n cache_manager, 'user', 'memberships:', None)\n self.usergroup_service = usergroup_service\n self.group_dag = group_dag\n\n def _DeserializeMemberships(self, memberships_rows):\n \"\"\"Reserialize the DB results into a {user_id: {group_id}}.\"\"\"\n result_dict = collections.defaultdict(set)\n for user_id, group_id in memberships_rows:\n result_dict[user_id].add(group_id)\n\n return result_dict\n\n def FetchItems(self, cnxn, keys):\n \"\"\"On RAM and memcache miss, hit the database to get memberships.\"\"\"\n direct_memberships_rows = self.usergroup_service.usergroup_tbl.Select(\n cnxn, cols=['user_id', 'group_id'], distinct=True,\n user_id=keys)\n memberships_set = set()\n self.group_dag.MarkObsolete()\n logging.info('Rebuild group dag on RAM and memcache miss')\n for c_id, p_id in direct_memberships_rows:\n all_parents = self.group_dag.GetAllAncestors(cnxn, p_id, True)\n all_parents.append(p_id)\n memberships_set.update([(c_id, g_id) for g_id in all_parents])\n retrieved_dict = self._DeserializeMemberships(list(memberships_set))\n\n # Make sure that every requested user is in the result, and gets cached.\n retrieved_dict.update(\n (user_id, set()) for user_id in keys\n if user_id not in retrieved_dict)\n return retrieved_dict\n\n\nclass UserGroupService(object):\n \"\"\"The persistence layer for user group data.\"\"\"\n\n def __init__(self, cache_manager):\n \"\"\"Initialize this service so that it is ready to use.\n\n Args:\n cache_manager: local cache with distributed invalidation.\n \"\"\"\n self.usergroup_tbl = sql.SQLTableManager(USERGROUP_TABLE_NAME)\n self.usergroupsettings_tbl = sql.SQLTableManager(\n USERGROUPSETTINGS_TABLE_NAME)\n self.usergroupprojects_tbl = sql.SQLTableManager(\n USERGROUPPROJECTS_TABLE_NAME)\n\n self.group_dag = UserGroupDAG(self)\n\n # Like a dictionary {user_id: {group_id}}\n self.memberships_2lc = MembershipTwoLevelCache(\n cache_manager, self, self.group_dag)\n # Like a dictionary {group_email: [group_id]}\n self.group_id_cache = caches.ValueCentricRamCache(\n cache_manager, 'usergroup')\n\n ### Group creation\n\n def CreateGroup(self, cnxn, services, group_name, who_can_view_members,\n ext_group_type=None, friend_projects=None):\n \"\"\"Create a new user group.\n\n Args:\n cnxn: connection to SQL database.\n services: connections to backend services.\n group_name: string email address of the group to create.\n who_can_view_members: 'owners', 'members', or 'anyone'.\n ext_group_type: The type of external group to import.\n friend_projects: The project ids declared as group friends to view its\n members.\n\n Returns:\n int group_id of the new group.\n \"\"\"\n friend_projects = friend_projects or []\n assert who_can_view_members in ('owners', 'members', 'anyone')\n if ext_group_type:\n ext_group_type = str(ext_group_type).lower()\n assert ext_group_type in GROUP_TYPE_ENUM, ext_group_type\n assert who_can_view_members == 'owners'\n group_id = services.user.LookupUserID(\n cnxn, group_name.lower(), autocreate=True, allowgroups=True)\n group_settings = usergroup_pb2.MakeSettings(\n who_can_view_members, ext_group_type, 0, friend_projects)\n self.UpdateSettings(cnxn, group_id, group_settings)\n self.group_id_cache.InvalidateAll(cnxn)\n return group_id\n\n def DeleteGroups(self, cnxn, group_ids):\n \"\"\"Delete groups' members and settings. It will NOT delete user entries.\n\n Args:\n cnxn: connection to SQL database.\n group_ids: list of group ids to delete.\n \"\"\"\n member_ids_dict, owner_ids_dict = self.LookupMembers(cnxn, group_ids)\n citizens_id_dict = collections.defaultdict(list)\n for g_id, user_ids in member_ids_dict.items():\n citizens_id_dict[g_id].extend(user_ids)\n for g_id, user_ids in owner_ids_dict.items():\n citizens_id_dict[g_id].extend(user_ids)\n for g_id, citizen_ids in citizens_id_dict.items():\n logging.info('Deleting group %d', g_id)\n # Remove group members, friend projects and settings\n self.RemoveMembers(cnxn, g_id, citizen_ids)\n self.usergroupprojects_tbl.Delete(cnxn, group_id=g_id)\n self.usergroupsettings_tbl.Delete(cnxn, group_id=g_id)\n self.group_id_cache.InvalidateAll(cnxn)\n\n def DetermineWhichUserIDsAreGroups(self, cnxn, user_ids):\n \"\"\"From a list of user IDs, identify potential user groups.\n\n Args:\n cnxn: connection to SQL database.\n user_ids: list of user IDs to examine.\n\n Returns:\n A list with a subset of the given user IDs that are user groups\n rather than individual users.\n \"\"\"\n # It is a group if there is any entry in the UserGroupSettings table.\n group_id_rows = self.usergroupsettings_tbl.Select(\n cnxn, cols=['group_id'], group_id=user_ids)\n group_ids = [row[0] for row in group_id_rows]\n return group_ids\n\n ### User memberships in groups\n\n def LookupComputedMemberships(self, cnxn, domain, use_cache=True):\n \"\"\"Look up the computed group memberships of a list of users.\n\n Args:\n cnxn: connection to SQL database.\n domain: string with domain part of user's email address.\n use_cache: set to False to ignore cached values.\n\n Returns:\n A list [group_id] of computed user groups that match the user.\n For now, the length of this list will always be zero or one.\n \"\"\"\n group_email = 'everyone@%s' % domain\n group_id = self.LookupUserGroupID(cnxn, group_email, use_cache=use_cache)\n if group_id:\n return [group_id]\n\n return []\n\n def LookupUserGroupID(self, cnxn, group_email, use_cache=True):\n \"\"\"Lookup the group ID for the given user group email address.\n\n Args:\n cnxn: connection to SQL database.\n group_email: string that identies the user group.\n use_cache: set to False to ignore cached values.\n\n Returns:\n Int group_id if found, otherwise None.\n \"\"\"\n if use_cache and self.group_id_cache.HasItem(group_email):\n return self.group_id_cache.GetItem(group_email)\n\n rows = self.usergroupsettings_tbl.Select(\n cnxn, cols=['email', 'group_id'],\n left_joins=[('User ON UserGroupSettings.group_id = User.user_id', [])],\n email=group_email,\n where=[('group_id IS NOT NULL', [])])\n retrieved_dict = dict(rows)\n # Cache a \"not found\" value for emails that are not user groups.\n if group_email not in retrieved_dict:\n retrieved_dict[group_email] = None\n self.group_id_cache.CacheAll(retrieved_dict)\n\n return retrieved_dict.get(group_email)\n\n def LookupAllMemberships(self, cnxn, user_ids, use_cache=True):\n \"\"\"Lookup all the group memberships of a list of users.\n\n Args:\n cnxn: connection to SQL database.\n user_ids: list of int user IDs to get memberships for.\n use_cache: set to False to ignore cached values.\n\n Returns:\n A dict {user_id: {group_id}} for the given user_ids.\n \"\"\"\n result_dict, missed_ids = self.memberships_2lc.GetAll(\n cnxn, user_ids, use_cache=use_cache)\n assert not missed_ids\n return result_dict\n\n def LookupMemberships(self, cnxn, user_id):\n \"\"\"Return a set of group_ids that this user is a member of.\"\"\"\n membership_dict = self.LookupAllMemberships(cnxn, [user_id])\n return membership_dict[user_id]\n\n ### Group member addition, removal, and retrieval\n\n def RemoveMembers(self, cnxn, group_id, old_member_ids):\n \"\"\"Remove the given members/owners from the user group.\"\"\"\n self.usergroup_tbl.Delete(\n cnxn, group_id=group_id, user_id=old_member_ids)\n\n all_affected = self._GetAllMembersInList(cnxn, old_member_ids)\n\n self.group_dag.MarkObsolete()\n self.memberships_2lc.InvalidateAllKeys(cnxn, all_affected)\n\n def UpdateMembers(self, cnxn, group_id, member_ids, new_role):\n \"\"\"Update role for given members/owners to the user group.\"\"\"\n # Circle detection\n for mid in member_ids:\n if self.group_dag.IsChild(cnxn, group_id, mid):\n raise exceptions.CircularGroupException(\n '%s is already an ancestor of group %s.' % (mid, group_id))\n\n self.usergroup_tbl.Delete(\n cnxn, group_id=group_id, user_id=member_ids)\n rows = [(member_id, group_id, new_role) for member_id in member_ids]\n self.usergroup_tbl.InsertRows(\n cnxn, ['user_id', 'group_id', 'role'], rows)\n\n all_affected = self._GetAllMembersInList(cnxn, member_ids)\n\n self.group_dag.MarkObsolete()\n self.memberships_2lc.InvalidateAllKeys(cnxn, all_affected)\n\n def _GetAllMembersInList(self, cnxn, group_ids):\n \"\"\"Get all direct/indirect members/owners in a list.\"\"\"\n children_member_ids, children_owner_ids = self.LookupAllMembers(\n cnxn, group_ids)\n all_members_owners = set()\n all_members_owners.update(group_ids)\n for users in children_member_ids.values():\n all_members_owners.update(users)\n for users in children_owner_ids.values():\n all_members_owners.update(users)\n return list(all_members_owners)\n\n def LookupAllMembers(self, cnxn, group_ids):\n \"\"\"Retrieve user IDs of members/owners of any of the given groups\n transitively.\"\"\"\n direct_member_rows = self.usergroup_tbl.Select(\n cnxn, cols=['user_id', 'group_id', 'role'], distinct=True,\n group_id=group_ids)\n member_ids_dict = {}\n owner_ids_dict = {}\n for gid in group_ids:\n all_descendants = self.group_dag.GetAllDescendants(cnxn, gid, True)\n indirect_member_rows = []\n if all_descendants:\n indirect_member_rows = self.usergroup_tbl.Select(\n cnxn, cols=['user_id'], distinct=True,\n group_id=all_descendants)\n\n # Owners must have direct membership. All indirect users are members.\n owner_ids_dict[gid] = [m[0] for m in direct_member_rows\n if m[1] == gid and m[2] == 'owner']\n member_ids_list = [r[0] for r in indirect_member_rows]\n member_ids_list.extend([m[0] for m in direct_member_rows\n if m[1] == gid and m[2] == 'member'])\n member_ids_dict[gid] = list(set(member_ids_list))\n return member_ids_dict, owner_ids_dict\n\n def LookupMembers(self, cnxn, group_ids):\n \"\"\"\"Retrieve user IDs of direct members/owners of any of the given groups.\n\n Args:\n cnxn: connection to SQL database.\n group_ids: list of int user IDs for all user groups to be examined.\n\n Returns:\n A dict of member IDs, and a dict of owner IDs keyed by group id.\n \"\"\"\n member_rows = self.usergroup_tbl.Select(\n cnxn, cols=['user_id', 'group_id', 'role'], distinct=True,\n group_id=group_ids)\n member_ids_dict = {}\n owner_ids_dict = {}\n for gid in group_ids:\n member_ids_dict[gid] = [row[0] for row in member_rows\n if row[1] == gid and row[2] == 'member']\n owner_ids_dict[gid] = [row[0] for row in member_rows\n if row[1] == gid and row[2] == 'owner']\n return member_ids_dict, owner_ids_dict\n\n # TODO(jojwang): monorail:4642, where appropriate, replace calls to\n # ExpandAnyUserGroups with calls to ExpandAnyGroupEmailRecipients.\n def ExpandAnyUserGroups(self, cnxn, user_ids):\n \"\"\"Transitively expand any user groups and return member user IDs.\n\n Args:\n cnxn: connection to SQL database.\n user_ids: list of user IDs to check.\n\n Returns:\n A pair (individual_user_ids, transitive_ids). individual_user_ids\n is a list of user IDs that were in the given user_ids list and\n that identify individual members. transitive_ids is a list of\n user IDs of the members of any user group in the given list of\n user_ids and the individual members of any nested groups.\n \"\"\"\n group_ids = self.DetermineWhichUserIDsAreGroups(cnxn, user_ids)\n direct_ids = [uid for uid in user_ids if uid not in group_ids]\n member_ids_dict, owner_ids_dict = self.LookupAllMembers(cnxn, group_ids)\n indirect_ids = set()\n for gid in group_ids:\n indirect_ids.update(member_ids_dict[gid])\n indirect_ids.update(owner_ids_dict[gid])\n\n # Note: we return direct and indirect member IDs separately so that\n # the email notification footer can give more a specific reason for\n # why the user got an email. E.g., \"You were Cc'd\" vs. \"You are a\n # member of a user group that was Cc'd\".\n return direct_ids, list(indirect_ids)\n\n def ExpandAnyGroupEmailRecipients(self, cnxn, user_ids):\n \"\"\"Expand the list with members that are part of a group configured\n to have notifications sent directly to members. Remove any groups\n not configured to have notifications sent directly to the group.\n\n Args:\n cnxn: connection to SQL database.\n user_ids: list of user IDs to check.\n\n Returns:\n A paire (individual user_ids, transitive_ids). individual_user_ids\n is a list of user IDs that were in the given user_ids list and\n that identify individual members or a group that has\n settings.notify_group set to True. transitive_ids is a list of\n user IDs of members of any user group in user_ids with\n settings.notify_members set to True.\n \"\"\"\n group_ids = self.DetermineWhichUserIDsAreGroups(cnxn, user_ids)\n group_settings_dict = self.GetAllGroupSettings(cnxn, group_ids)\n member_ids_dict, owner_ids_dict = self.LookupAllMembers(cnxn, group_ids)\n indirect_ids = set()\n direct_ids = {uid for uid in user_ids if uid not in group_ids}\n for gid, settings in group_settings_dict.items():\n if settings.notify_members:\n indirect_ids.update(member_ids_dict.get(gid, set()))\n indirect_ids.update(owner_ids_dict.get(gid, set()))\n if settings.notify_group:\n direct_ids.add(gid)\n\n return list(direct_ids), list(indirect_ids)\n\n def LookupVisibleMembers(\n self, cnxn, group_id_list, perms, effective_ids, services):\n \"\"\"\"Retrieve the list of user group direct member/owner IDs that the user\n may see.\n\n Args:\n cnxn: connection to SQL database.\n group_id_list: list of int user IDs for all user groups to be examined.\n perms: optional PermissionSet for the user viewing this page.\n effective_ids: set of int user IDs for that user and all\n his/her group memberships.\n services: backend services.\n\n Returns:\n A list of all the member IDs from any group that the user is allowed\n to view.\n \"\"\"\n settings_dict = self.GetAllGroupSettings(cnxn, group_id_list)\n group_ids = list(settings_dict.keys())\n (owned_project_ids, membered_project_ids,\n contrib_project_ids) = services.project.GetUserRolesInAllProjects(\n cnxn, effective_ids)\n project_ids = owned_project_ids.union(\n membered_project_ids).union(contrib_project_ids)\n # We need to fetch all members/owners to determine whether the requester\n # has permission to view.\n direct_member_ids_dict, direct_owner_ids_dict = self.LookupMembers(\n cnxn, group_ids)\n all_member_ids_dict, all_owner_ids_dict = self.LookupAllMembers(\n cnxn, group_ids)\n visible_member_ids = {}\n visible_owner_ids = {}\n for gid in group_ids:\n member_ids = all_member_ids_dict[gid]\n owner_ids = all_owner_ids_dict[gid]\n\n if permissions.CanViewGroupMembers(\n perms, effective_ids, settings_dict[gid], member_ids, owner_ids,\n project_ids):\n visible_member_ids[gid] = direct_member_ids_dict[gid]\n visible_owner_ids[gid] = direct_owner_ids_dict[gid]\n\n return visible_member_ids, visible_owner_ids\n\n ### Group settings\n\n def GetAllUserGroupsInfo(self, cnxn):\n \"\"\"Fetch (addr, member_count, usergroup_settings) for all user groups.\"\"\"\n group_rows = self.usergroupsettings_tbl.Select(\n cnxn, cols=['email'] + USERGROUPSETTINGS_COLS,\n left_joins=[('User ON UserGroupSettings.group_id = User.user_id', [])])\n count_rows = self.usergroup_tbl.Select(\n cnxn, cols=['group_id', 'COUNT(*)'],\n group_by=['group_id'])\n count_dict = dict(count_rows)\n\n group_ids = [g[1] for g in group_rows]\n friends_dict = self.GetAllGroupFriendProjects(cnxn, group_ids)\n\n user_group_info_tuples = [\n (email, count_dict.get(group_id, 0),\n usergroup_pb2.MakeSettings(visiblity, group_type, last_sync_time,\n friends_dict.get(group_id, []),\n bool(notify_members), bool(notify_group)),\n group_id)\n for (email, group_id, visiblity, group_type, last_sync_time,\n notify_members, notify_group) in group_rows]\n return user_group_info_tuples\n\n def GetAllGroupSettings(self, cnxn, group_ids):\n \"\"\"Fetch {group_id: group_settings} for the specified groups.\"\"\"\n # TODO(jrobbins): add settings to control who can join, etc.\n rows = self.usergroupsettings_tbl.Select(\n cnxn, cols=USERGROUPSETTINGS_COLS, group_id=group_ids)\n friends_dict = self.GetAllGroupFriendProjects(cnxn, group_ids)\n settings_dict = {\n group_id: usergroup_pb2.MakeSettings(\n vis, group_type, last_sync_time, friends_dict.get(group_id, []),\n notify_members=bool(notify_members),\n notify_group=bool(notify_group))\n for (group_id, vis, group_type, last_sync_time,\n notify_members, notify_group) in rows}\n return settings_dict\n\n def GetGroupSettings(self, cnxn, group_id):\n \"\"\"Retrieve group settings for the specified user group.\n\n Args:\n cnxn: connection to SQL database.\n group_id: int user ID of the user group.\n\n Returns:\n A UserGroupSettings object, or None if no such group exists.\n \"\"\"\n return self.GetAllGroupSettings(cnxn, [group_id]).get(group_id)\n\n def UpdateSettings(self, cnxn, group_id, group_settings):\n \"\"\"Update the visiblity settings of the specified group.\"\"\"\n who_can_view_members = str(group_settings.who_can_view_members).lower()\n ext_group_type = group_settings.ext_group_type\n assert who_can_view_members in ('owners', 'members', 'anyone')\n if ext_group_type:\n ext_group_type = str(group_settings.ext_group_type).lower()\n assert ext_group_type in GROUP_TYPE_ENUM, ext_group_type\n assert who_can_view_members == 'owners'\n self.usergroupsettings_tbl.InsertRow(\n cnxn, group_id=group_id, who_can_view_members=who_can_view_members,\n external_group_type=ext_group_type,\n last_sync_time=group_settings.last_sync_time,\n notify_members=group_settings.notify_members,\n notify_group=group_settings.notify_group,\n replace=True)\n self.usergroupprojects_tbl.Delete(\n cnxn, group_id=group_id)\n if group_settings.friend_projects:\n rows = [(group_id, p_id) for p_id in group_settings.friend_projects]\n self.usergroupprojects_tbl.InsertRows(\n cnxn, ['group_id', 'project_id'], rows)\n\n def GetAllGroupFriendProjects(self, cnxn, group_ids):\n \"\"\"Get {group_id: [project_ids]} for the specified user groups.\"\"\"\n rows = self.usergroupprojects_tbl.Select(\n cnxn, cols=USERGROUPPROJECTS_COLS, group_id=group_ids)\n friends_dict = {}\n for group_id, project_id in rows:\n friends_dict.setdefault(group_id, []).append(project_id)\n return friends_dict\n\n def GetGroupFriendProjects(self, cnxn, group_id):\n \"\"\"Get a list of friend projects for the specified user group.\"\"\"\n return self.GetAllGroupFriendProjects(cnxn, [group_id]).get(group_id)\n\n def ValidateFriendProjects(self, cnxn, services, friend_projects):\n \"\"\"Validate friend projects.\n\n Returns:\n A list of project ids if no errors, or an error message.\n \"\"\"\n project_names = list(filter(None, re.split('; |, | |;|,', friend_projects)))\n id_dict = services.project.LookupProjectIDs(cnxn, project_names)\n missed_projects = []\n result = []\n for p_name in project_names:\n if p_name in id_dict:\n result.append(id_dict[p_name])\n else:\n missed_projects.append(p_name)\n error_msg = ''\n if missed_projects:\n error_msg = 'Project(s) %s do not exist' % ', '.join(missed_projects)\n return None, error_msg\n else:\n return result, None\n\n # TODO(jrobbins): re-implement FindUntrustedGroups()\n\n def ExpungeUsersInGroups(self, cnxn, ids):\n \"\"\"Wipes the given user from the groups system.\n The given user_ids may to members or groups, or groups themselves.\n The groups and all their members will be deleted. The users will be\n wiped from the groups they belong to.\n\n It will NOT delete user entries. This method will not commit the\n operations. This method will not make any changes to in-memory data.\n \"\"\"\n # Delete any groups\n self.usergroupprojects_tbl.Delete(cnxn, group_id=ids, commit=False)\n self.usergroupsettings_tbl.Delete(cnxn, group_id=ids, commit=False)\n self.usergroup_tbl.Delete(cnxn, group_id=ids, commit=False)\n\n # Delete any group members\n self.usergroup_tbl.Delete(cnxn, user_id=ids, commit=False)\n\n\nclass UserGroupDAG(object):\n \"\"\"A directed-acyclic graph of potentially nested user groups.\"\"\"\n\n def __init__(self, usergroup_service):\n self.usergroup_service = usergroup_service\n self.user_group_parents = collections.defaultdict(list)\n self.user_group_children = collections.defaultdict(list)\n self.initialized = False\n\n def Build(self, cnxn, circle_detection=False):\n if not self.initialized:\n self.user_group_parents.clear()\n self.user_group_children.clear()\n group_ids = self.usergroup_service.usergroupsettings_tbl.Select(\n cnxn, cols=['group_id'])\n usergroup_rows = self.usergroup_service.usergroup_tbl.Select(\n cnxn, cols=['user_id', 'group_id'], distinct=True,\n user_id=[r[0] for r in group_ids])\n for user_id, group_id in usergroup_rows:\n self.user_group_parents[user_id].append(group_id)\n self.user_group_children[group_id].append(user_id)\n self.initialized = True\n\n if circle_detection:\n for child_id, parent_ids in self.user_group_parents.items():\n for parent_id in parent_ids:\n if self.IsChild(cnxn, parent_id, child_id):\n logging.error(\n 'Circle exists between group %d and %d.', child_id, parent_id)\n\n def GetAllAncestors(self, cnxn, group_id, circle_detection=False):\n \"\"\"Return a list of distinct ancestor group IDs for the given group.\"\"\"\n self.Build(cnxn, circle_detection)\n result = set()\n child_ids = [group_id]\n while child_ids:\n parent_ids = set()\n for c_id in child_ids:\n group_ids = self.user_group_parents[c_id]\n parent_ids.update(g_id for g_id in group_ids if g_id not in result)\n result.update(parent_ids)\n child_ids = list(parent_ids)\n return list(result)\n\n def GetAllDescendants(self, cnxn, group_id, circle_detection=False):\n \"\"\"Return a list of distinct descendant group IDs for the given group.\"\"\"\n self.Build(cnxn, circle_detection)\n result = set()\n parent_ids = [group_id]\n while parent_ids:\n child_ids = set()\n for p_id in parent_ids:\n group_ids = self.user_group_children[p_id]\n child_ids.update(g_id for g_id in group_ids if g_id not in result)\n result.update(child_ids)\n parent_ids = list(child_ids)\n return list(result)\n\n def IsChild(self, cnxn, child_id, parent_id):\n \"\"\"Returns True if child_id is a direct/indirect child of parent_id.\"\"\"\n all_descendants = self.GetAllDescendants(cnxn, parent_id)\n return child_id in all_descendants\n\n def MarkObsolete(self):\n \"\"\"Mark the DAG as uninitialized so it'll be re-built.\"\"\"\n self.initialized = False\n\n def __repr__(self):\n result = {}\n result['parents'] = self.user_group_parents\n result['children'] = self.user_group_children\n return str(result)\n","sub_path":"appengine/monorail/services/usergroup_svc.py","file_name":"usergroup_svc.py","file_ext":"py","file_size_in_byte":25531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"103785283","text":"return \" \".join(\"{:.6f}\".format(i) for i in res)\nprint(\"{:.7f}\".format(r))\n\n\ndef lcm(ip):\n l = len(ip)\n a, b = ip[:2]\n res = (a * b) // math.gcd(a, b)\n i = 2\n while i < l:\n a = ip[i]\n res = (res * a) // math.gcd(res, a)\n i += 1\n\n return res\n\n\ndef inverse(A):\n return [chr(ord('0') + ord('1') - ord(c)) for c in A]\n\n\ndef qhull(sample):\n link = lambda a, b: numpy.concatenate((a, b[1:]))\n edge = lambda a, b: numpy.concatenate(([a], [b]))\n\n def dome(sample, base):\n h, t = base\n dists = numpy.dot(sample - h, numpy.dot(((0, -1), (1, 0)), (t - h)))\n outer = numpy.repeat(sample, dists > 0, axis=0)\n\n if len(outer):\n pivot = sample[numpy.argmax(dists)]\n return link(dome(outer, edge(h, pivot)),\n dome(outer, edge(pivot, t)))\n else:\n return base\n\n if len(sample) > 2:\n axis = sample[:, 0]\n base = numpy.take(\n sample, [numpy.argmin(axis), numpy.argmax(axis)], axis=0)\n return link(dome(sample, base),\n dome(sample, base[::-1]))\n else:\n return sample\n","sub_path":"solutions/helpers/python-helpers.py","file_name":"python-helpers.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"573542569","text":"from sklearn import datasets\nimport numpy as np \n\niris = datasets.load_iris()\niris_x = iris.data \nmasking_array = np.random.binomial(1, .25, iris_x.shape).astype(bool)\niris_x[masking_array] = np.nan \nprint(masking_array[:5])\nprint(iris_x[:5])\n\n# handling missing values \nfrom sklearn.impute import SimpleImputer\n\nimpute = SimpleImputer(missing_values=np.nan, strategy='mean')\niris_x_prime = impute.fit_transform(iris_x)\n\nprint(iris_x_prime[:5])\n\n\n# fill missing with -1 as a test \niris_x[np.isnan(iris_x)] = -1 \nprint(iris_x[:5])\n\nnew_imputer = SimpleImputer(missing_values=-1)\niris_x_prime = new_imputer.fit_transform(iris_x)\nprint(iris_x_prime[:5])\n\n\n# using pandas to impute missing values \nimport pandas as pd \niris_x_prime = np.where(pd.DataFrame(iris_x).isna(), -1, iris_x)\niris_x_prime[:5]","sub_path":"scikit-learn/ch2/missing_values.py","file_name":"missing_values.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"605442505","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport re\nimport argparse\n\n\nimport pandas as pd\n\n\n# naming convention\n# key: config name\n# value: ([version, num_gpus], rename)\n# version: 0 for pytorch:20.01-py3, and 1 for pytorch:20.10-py3\n# num_gpus: sometimes num_gpus can't be inferred from config name (for example p3.16xlarge) or missing from the result log. So we ask for user to specify it here.\n# rename: renaming the system so it is easier to read\n# watt per gpu\n# price per gpu\n\nlist_system_single = {\n 'V100': ([0, 1], 'V100 32GB', 250, 11357),\n 'QuadroRTX8000': ([0, 1], 'RTX 8000', 260, 6900),\n 'QuadroRTX6000': ([0, 1], 'RTX 6000', 260, 4964),\n 'QuadroRTX5000': ([0, 1], 'RTX 5000', 230, 2392),\n 'TitanRTX': ([0, 1], 'Titan RTX', 280, 3500),\n '2080Ti': ([0, 1], 'RTX 2080Ti', 250, 1928),\n '1080Ti': ([0, 1], 'GTX 1080Ti', 250, 892),\n '2080SuperMaxQ': ([0, 1], 'RTX 2080 SUPER MAX-Q', 80, 1377),\n '2080MaxQ': ([0, 1], 'RTX 2080 MAX-Q', 90, 1032), \n '2070MaxQ': ([0, 1], 'RTX 2070 MAX-Q', 90, 975),\n '3070': ([1, 1], 'RTX 3070', 220, 1035),\n '3080': ([1, 1], 'RTX 3080', 320, 1642),\n '3090': ([1, 1], 'RTX 3090', 350, 3142),\n 'A100_PCIe': ([1, 1], 'A100 40GB PCIe', 250, 12785),\n 'A100_SXM4': ([1, 1], 'A100 40GB SXM4', 400, 14571),\n 'A6000': ([1, 1], 'RTX A6000', 300, 5785),\n 'A5000': ([1, 1], 'RTX A5000', 230, 2857),\n 'LambdaCloud_A6000': ([1, 1], 'Lambda Cloud — RTX A6000', 300, 5785),\n '3080Max-Q': ([1, 1], 'RTX 3080 Max-Q', 80, 1600),\n 'A40': ([1, 1], 'RTX A40', 300, 6464),\n 'A4000': ([1, 1], 'RTX A4000', 140, 1321),\n }\n\nlist_system_multiple = {\n '2x2080TiNVlink_trt': ([0, 2], '2x RTX 2080Ti NVLink', 250, 1928),\n '2x2080Ti_trt': ([0, 2], '2x RTX 2080Ti', 250, 1928),\n '4x2080TiNVlink_trt': ([0, 4], '4x RTX 2080Ti NVLink', 250, 1928),\n '4x2080Ti_trt': ([0, 4], '4x RTX 2080Ti', 250, 1928),\n '8x2080TiNVlink_trt': ([0, 8], '8x RTX 2080Ti NVLink', 250, 1928),\n '8x2080Ti_trt': ([0, 8], '8x RTX 2080Ti', 250, 1928),\n '2xQuadroRTX8000NVlink_trt2': ([0, 2], '2x RTX 8000 NVLink', 260, 6900),\n '2xQuadroRTX8000_trt2': ([0, 2], '2x RTX 8000', 260, 6900),\n '4xQuadroRTX8000NVlink_trt2': ([0, 4], '4x RTX 8000 NVLink', 260, 6900),\n '4xQuadroRTX8000_trt2': ([0, 4], '4x RTX 8000', 260, 6900),\n '8xQuadroRTX8000NVlink_trt2': ([0, 8], '8x RTX 8000 NVLink', 260, 6900),\n '8xQuadroRTX8000_trt2': ([0, 8], '8x RTX 8000', 260, 6900),\n '2xV100': ([0, 2], '2x V100 32GB', 250, 11357),\n '4xV100': ([0, 4], '4x V100 32GB', 250, 11357),\n '8xV100': ([0, 8], '8x V100 32GB', 250, 11357),\n 'p3.16xlarge': ([0, 8], 'p3.16xlarge', 300, 10664),\n 'p3.8xlarge': ([0, 4], 'p3.8xlarge', 300, 10664),\n 'LambdaCloud_8xV10016G': ([0, 8], 'Lambda Cloud — 8x V100 16GB', 300, 10664),\n 'LambdaCloud_4x1080Ti': ([0, 4], 'Lambda Cloud — 4x GTX 1080Ti', 250, 892),\n 'LambdaCloud_2xQuadroRTX6000': ([0, 2], 'Lambda Cloud — 2x RTX 6000', 260, 4964),\n 'LambdaCloud_4xQuadroRTX6000': ([0, 4], 'Lambda Cloud — 4x RTX 6000', 260, 4964),\n 'Linode_2xQuadroRTX6000': ([0, 2], 'Linode Cloud — 2x RTX 6000', 260, 4964),\n '2x3070': ([1, 2], '2x RTX 3070', 220, 1035),\n '4x3070': ([1, 4], '4x RTX 3070', 220, 1035),\n '8x3070': ([1, 8], '8x RTX 3070', 220, 1035),\n '2x3080': ([1, 2], '2x RTX 3080', 320, 1642),\n '2x3090': ([1, 2], '2x RTX 3090', 350, 3142),\n '3x3090': ([1, 3], '3x RTX 3090', 350, 3142),\n '4x3090': ([1, 4], '4x RTX 3090', 350, 3142),\n '8x3090': ([1, 8], '8x RTX 3090', 350, 3142),\n '2xA100_PCIe': ([1, 2], '2x A100 40GB PCIe', 250, 12785),\n '4xA100_PCIe': ([1, 4], '4x A100 40GB PCIe', 250, 12785),\n '8xA100_PCIe': ([1, 8], '8x A100 40GB PCIe', 250, 12785),\n '2xA100_SXM4': ([1, 2], '2x A100 40GB SXM4', 400, 14571),\n '4xA100_SXM4': ([1, 4], '4x A100 40GB SXM4', 400, 14571),\n '8xA100_SXM4': ([1, 8], '8x A100 40GB SXM4', 400, 14571),\n '8xA100_p4': ([1, 8], 'p4d.24xlarge', 400, 14571),\n '2xA6000': ([1, 2], '2x RTX A6000', 300, 5785),\n '4xA6000': ([1, 4], '4x RTX A6000', 300, 5785),\n '8xA6000': ([1, 8], '8x RTX A6000', 300, 5785),\n 'LambdaCloud_2xA6000': ([1, 2], 'Lambda Cloud — 2x RTX A6000', 300, 5785),\n 'LambdaCloud_4xA6000': ([1, 4], 'Lambda Cloud — 4x RTX A6000', 300, 5785),\n '4xA5000': ([1, 4], '4x RTX A5000', 230, 2857),\n '2xA5000': ([1, 2], '2x RTX A5000', 230, 2857),\n '2xA40': ([1, 2], '2x RTX A40', 300, 6464),\n '4xA40': ([1, 4], '4x RTX A40', 300, 6464),\n '8xA40': ([1, 8], '8x RTX A40', 300, 6464),\n '2xA4000': ([1, 2], '2x RTX A4000', 140, 1321),\n '4xA4000': ([1, 4], '4x RTX A4000', 140, 1321),\n '8xA4000': ([1, 8], '8x RTX A4000', 140, 1321),\n}\n\nlist_test_fp32 = [\n # nvcr.io/nvidia/pytorch:20.01-py3\n {\n 'PyTorch_SSD_FP32': ('ssd', \"^.*Training performance =.*$\", -2),\n 'PyTorch_resnet50_FP32': ('resnet50', \"^.*Summary: train.loss.*$\", -2),\n 'PyTorch_maskrcnn_FP32': ('maskrcnn', \"^.*Training perf is:.*$\", -2),\n 'PyTorch_gnmt_FP32': ('gnmt', \"^.*Training:.*$\", -4),\n 'PyTorch_ncf_FP32': ('ncf', \"^.*best_train_throughput:.*$\", -1),\n 'PyTorch_transformerxlbase_FP32': ('transformerxlbase', \"^.*Training throughput:.*$\", -2),\n 'PyTorch_transformerxllarge_FP32': ('transformerxllarge', \"^.*Training throughput:.*$\", -2),\n 'PyTorch_tacotron2_FP32': ('tacotron2', \"^.*train_epoch_avg_items/sec:.*$\", -1),\n 'PyTorch_waveglow_FP32': ('waveglow', \"^.*train_epoch_avg_items/sec:.*$\", -1),\n 'PyTorch_bert_large_squad_FP32': ('bert_large_squad', \"^.*training throughput:.*$\", -1),\n 'PyTorch_bert_base_squad_FP32': ('bert_base_squad', \"^.*training throughput:.*$\", -1),\n },\n # nvcr.io/nvidia/pytorch:20.10-py3\n {\n 'PyTorch_SSD_FP32': ('ssd', \"^.*Training performance =.*$\", -2),\n 'PyTorch_resnet50_FP32': ('resnet50', \"^.*Summary: train.loss.*$\", -2),\n 'PyTorch_maskrcnn_FP32': ('maskrcnn', \"^.*Training perf is:.*$\", -2),\n 'PyTorch_gnmt_FP32': ('gnmt', \"^.*Training:.*$\", -4),\n 'PyTorch_ncf_FP32': ('ncf', \"^.*best_train_throughput:.*$\", -1),\n 'PyTorch_transformerxlbase_FP32': ('transformerxlbase', \"^.*Training throughput:.*$\", -2),\n 'PyTorch_transformerxllarge_FP32': ('transformerxllarge', \"^.*Training throughput:.*$\", -2),\n 'PyTorch_tacotron2_FP32': ('tacotron2', \"^.*train_items_per_sec :.*$\", -2),\n 'PyTorch_waveglow_FP32': ('waveglow', \"^.*train_items_per_sec :.*$\", -2),\n 'PyTorch_bert_large_squad_FP32': ('bert_large_squad', \"^.*training_sequences_per_second :.*$\", -6),\n 'PyTorch_bert_base_squad_FP32': ('bert_base_squad', \"^.*training_sequences_per_second :.*$\", -6),\n } \n]\n\nlist_test_fp16 = [\n # version 0: nvcr.io/nvidia/pytorch:20.01-py3\n {\n 'PyTorch_SSD_AMP': ('ssd', \"^.*Training performance =.*$\", -2),\n 'PyTorch_resnet50_FP16': ('resnet50', \"^.*Summary: train.loss.*$\", -2),\n 'PyTorch_maskrcnn_FP16': ('maskrcnn', \"^.*Training perf is:.*$\", -2),\n 'PyTorch_gnmt_FP16': ('gnmt', \"^.*Training:.*$\", -4),\n 'PyTorch_ncf_FP16': ('ncf', \"^.*best_train_throughput:.*$\", -1),\n 'PyTorch_transformerxlbase_FP16': ('transformerxlbase', \"^.*Training throughput:.*$\", -2),\n 'PyTorch_transformerxllarge_FP16': ('transformerxllarge', \"^.*Training throughput:.*$\", -2),\n 'PyTorch_tacotron2_FP16': ('tacotron2', \"^.*train_epoch_avg_items/sec:.*$\", -1),\n 'PyTorch_waveglow_FP16': ('waveglow', \"^.*train_epoch_avg_items/sec:.*$\", -1),\n 'PyTorch_bert_large_squad_FP16': ('bert_large_squad', \"^.*training throughput:.*$\", -1),\n 'PyTorch_bert_base_squad_FP16': ('bert_base_squad', \"^.*training throughput:.*$\", -1),\n },\n # version 1: nvcr.io/nvidia/pytorch:20.10-py3\n {\n 'PyTorch_SSD_AMP': ('ssd', \"^.*Training performance =.*$\", 3),\n 'PyTorch_resnet50_FP16': ('resnet50', \"^.*Summary: train.loss.*$\", -2),\n 'PyTorch_maskrcnn_FP16': ('maskrcnn', \"^.*Training perf is:.*$\", -2),\n 'PyTorch_gnmt_FP16': ('gnmt', \"^.*Training:.*$\", -4),\n 'PyTorch_ncf_FP16': ('ncf', \"^.*best_train_throughput:.*$\", -1),\n 'PyTorch_transformerxlbase_FP16': ('transformerxlbase', \"^.*Training throughput:.*$\", -2),\n 'PyTorch_transformerxllarge_FP16': ('transformerxllarge', \"^.*Training throughput:.*$\", -2),\n 'PyTorch_tacotron2_FP16': ('tacotron2', \"^.*train_items_per_sec :.*$\", -2),\n 'PyTorch_waveglow_FP16': ('waveglow', \"^.*train_items_per_sec :.*$\", -2),\n 'PyTorch_bert_large_squad_FP16': ('bert_large_squad', \"^.*training_sequences_per_second :.*$\", -6),\n 'PyTorch_bert_base_squad_FP16': ('bert_base_squad', \"^.*training_sequences_per_second :.*$\", -6),\n }\n]\n\ndef gather_last(list_test, list_system, name, system, config_name, df, version, path_result):\n column_name, key, pos = list_test[version][name]\n pattern = re.compile(key)\n\n path = path_result + '/' + system + '/' + name\n count = 0.000001\n total_throughput = 0.0\n\n if os.path.exists(path):\n for filename in os.listdir(path):\n if filename.endswith(\".txt\"):\n flag = False\n throughput = 0\n # Sift through all lines and only keep the last occurrence\n for i, line in enumerate(open(os.path.join(path, filename))):\n\n for match in re.finditer(pattern, line):\n try:\n throughput = float(match.group().split(' ')[pos])\n except:\n pass\n\n if throughput > 0:\n count += 1\n total_throughput += throughput\n flag = True\n\n if not flag:\n print(system + \"/\" + name + \" \" + filename + \": something wrong\")\n df.at[config_name, column_name] = int(round(total_throughput / count, 2))\n else:\n df.at[config_name, column_name] = 0\n\n df.at[config_name, 'num_gpu'] = list_system[system][0][1]\n df.at[config_name, 'watt'] = list_system[system][2] * int(list_system[system][0][1])\n df.at[config_name, 'price'] = list_system[system][3] * int(list_system[system][0][1])\n\ndef main():\n parser = argparse.ArgumentParser(description='Gather benchmark results.')\n\n parser.add_argument('--path', type=str, default='results',\n help='path that has the results') \n\n parser.add_argument('--precision', type=str, default='fp32',\n choices=['fp32', 'fp16'],\n help='Choose becnhmark precision')\n\n parser.add_argument('--system', type=str, default='all',\n choices=['single', 'multiple', 'all'],\n help='Choose system type (single or multiple GPUs)')\n\n args = parser.parse_args()\n\n if args.precision == 'fp32':\n list_test = list_test_fp32\n elif args.precision == 'fp16':\n list_test = list_test_fp16\n else:\n sys.exit(\"Wrong precision: \" + precision + ', choose between fp32 and fp16')\n\n\n if args.system == 'single':\n list_system = list_system_single\n elif args.system == 'multiple':\n list_system = list_system_multiple\n else:\n list_system = {} \n list_system.update(list_system_single)\n list_system.update(list_system_multiple)\n\n columns = []\n columns.append('num_gpu')\n columns.append('watt')\n columns.append('price')\n\n for test_name, value in sorted(list_test[0].items()):\n columns.append(list_test[0][test_name][0])\n list_configs = [list_system[key][1] for key in list_system]\n\n print(columns)\n print(list_configs)\n \n df = pd.DataFrame(index=list_configs, columns=columns)\n df = df.fillna(-1.0)\n\n for key in list_system:\n for test_name, value in sorted(list_test[0].items()):\n version = list_system[key][0][0]\n config_name = list_system[key][1]\n gather_last(list_test, list_system, test_name, key, config_name, df, version, args.path)\n\n df.index.name = 'name_gpu'\n\n df.to_csv('pytorch-train-throughput-' + args.precision + '.csv')\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"pytorch/scripts/compile_results_pytorch_throughput.py","file_name":"compile_results_pytorch_throughput.py","file_ext":"py","file_size_in_byte":12530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"314422889","text":"\"\"\"\nThis File should run on the raspberry pi that is driving the strip.\nit will listed on\n\"\"\"\nimport time\nimport comm\nfrom datetime import datetime\n\nSTRIP_TYPE = 'APA102' #APA102 or NEOPIXEL\nstrip = None\n\nTARGET_FPS = 25\n\nif STRIP_TYPE == 'NEOPIXEL':\n import neopixel\n import board\n class NeoPixelStrip:\n def __init__(self, num_pixels=144, pixel_pin = board.D18, ORDER = neopixel.GRB):\n self.pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False,pixel_order=ORDER, bpp=3)\n\n def render_pixels(self, data, brightness):\n # print(len(data))\n for i in range(0, len(data)):\n self.pixels[i] = data[i]\n self.pixels.show()\n\n def clear(self):\n self.pixels.fill((0, 0, 0))\n self.pixels.show()\n strip = NeoPixelStrip(144)\n\nelif STRIP_TYPE == 'APA102':\n import apa102\n class APA102Strip:\n def __init__(self, num_pixels=144):\n self.strip = apa102.APA102(num_pixels)\n\n def render_pixels(self, data, brightness):\n # print(len(data))\n for i in range(0, len(data)):\n self.strip.set_pixel(i, data[i][0], data[i][1], data[i][2], brightness)\n self.strip.show()\n\n def clear(self):\n self.strip.clear_strip()\n strip = APA102Strip(144)\n\n\npkt_count = 0\nframe_count = 0\nstart = 0\nlast_td = 0\nlast_frame_count = 0\nlast_pkt_count = 0\n\npixel_channel = comm.PixelsChannel()\npixel_channel.listen()\n\nall_data = []\n\n\nstart_time = int(time.time()*1000.0)\nprev_ts = 0\nwhile True:\n pm = pixel_channel.recv()\n ts = int(time.time()*1000.0) - start_time\n # print(from_start - prev_from_start)\n\n if len(pm.pixels) == 0:\n strip.clear()\n continue\n\n # s1 = int(time.time()*1000.0)\n strip.render_pixels(pm.pixels, pm.brightness)\n # print(int(time.time()*1000.0 - s1))\n\n # # print(len(data))\n # for i in range(0, len(data)):\n # pixels[i] = data[i]\n # pixels.show()\n\n frame_count += 1\n td = (int(time.time()*1000.0) - start)\n if td - last_td > 2000:\n fps = 1000*(frame_count - last_frame_count)/(td-last_td)\n print('fps-%s, pkt-%s, frm-%s, time=%s' % (fps, (pkt_count-last_pkt_count), (frame_count-last_frame_count), td))\n last_td = td\n last_frame_count = frame_count\n last_pkt_count = pkt_count\n\n\n\n # print('ready')\n prev_ts = ts\n\n","sub_path":"python/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"77042145","text":"from JumpScale import j\nActionsBase = j.atyourservice.getActionsBaseClass()\n\n\nclass Actions(ActionsBase):\n \"\"\"\n process for install\n -------------------\n step1: prepare actions\n step2: check_requirements action\n step3: download files & copy on right location (hrd info is used)\n step4: configure action\n step5: check_uptime_local to see if process stops (uses timeout $process.stop.timeout)\n step5b: if check uptime was true will do stop action and retry the check_uptime_local check\n step5c: if check uptime was true even after stop will do halt action and retry the check_uptime_local check\n step6: use the info in the hrd to start the application\n step7: do check_uptime_local to see if process starts\n step7b: do monitor_local to see if package healthy installed & running\n step7c: do monitor_remote to see if package healthy installed & running, but this time test is done from central location\n \"\"\"\n\n def prepare(self, serviceObj):\n \"\"\"\n this gets executed before the files are downloaded & installed on approprate spots\n \"\"\"\n def createLogDir():\n path = j.system.fs.joinPaths(j.dirs.logDir, \"openvpn\")\n if j.system.fs.exists(path):\n j.system.fs.removeDirTree(path)\n j.system.fs.createDir(path)\n j.actions.start(description='create Logging Directory', action=createLogDir, name='createLogDir', serviceObj=serviceObj)\n\n return True\n\n def configure(self, serviceObj):\n def createConf():\n serviceObj.hrd.applyOnFile(\"/opt/openvpn/etc/server.conf\")\n j.application.config.applyOnFile(\"/opt/openvpn/etc/server.conf\")\n\n serviceObj.hrd.applyOnFile(\"/opt/openvpn/etc/client.conf\")\n j.application.config.applyOnFile(\"/opt/openvpn/etc/client.conf\")\n j.actions.start(description='create config files', name='createConf', action=createConf, serviceObj=serviceObj)\n\n def writeVarsFile():\n serviceObj.hrd.applyOnFile(\"/opt/openvpn/easy-rsa/vars\")\n j.actions.start(description='writeVarsFile', action=writeVarsFile, name='writeVarsFile', serviceObj=serviceObj)\n\n def generateCerts():\n script = \"/bin/bash -c 'cd /opt/openvpn/easy-rsa; source vars; ./clean-all'\"\n j.do.executeInteractive(script)\n\n script = \"/bin/bash -c 'cd /opt/openvpn/easy-rsa; source vars; ./build-ca'\"\n j.do.executeInteractive(script)\n\n script = \"/bin/bash -c 'cd /opt/openvpn/easy-rsa; source vars; ./build-key-server server'\"\n j.do.executeInteractive(script)\n\n script = \"/bin/bash -c 'cd /opt/openvpn/easy-rsa; source vars; ./build-key client'\"\n j.do.executeInteractive(script)\n\n script = \"/bin/bash -c 'cd /opt/openvpn/easy-rsa; source vars; ./build-dh'\"\n j.do.executeInteractive(script)\n\n files = ['ca.crt', 'server.key', 'server.crt','client.key', 'client.crt', 'dh2048.pem']\n for f in files:\n source = j.system.fs.joinPaths('/opt/openvpn/easy-rsa/keys', f)\n dest = j.system.fs.joinPaths('/opt/openvpn/etc/', f)\n j.system.fs.copyFile(source, dest)\n j.actions.start(description='Create the CA (Root certificate)', action=generateCerts, name='generateCerts', serviceObj=serviceObj)\n\n def removedata(self, serviceObj):\n script = \"/bin/bash -c 'source vars; ./clean-all'\"\n j.do.execute(script, cwd='/opt/openvpn/easy-rsa')\n","sub_path":"_servers/openvpn/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"615184618","text":"from PIL import Image\nfrom io import BytesIO\n\n\ndef save_captcha_image(driver, filename):\n SIPAC = ('https://www.receita.fazenda.gov.br/Aplicacoes/SSL/'\n 'ATFLA/Sipac.App/')\n if driver.current_url == SIPAC is False:\n raise ValueError('Sipac não está carregado no browser.]')\n captcha = crop_captcha(driver)\n captcha.save(filename)\n\n\ndef take_screenshot(driver):\n im = BytesIO(driver.get_screenshot_as_png())\n return Image.open(im)\n\n\ndef get_captcha_location(driver):\n CAPTCHA_ID = 'imgcaptcha'\n captcha = driver.find_element_by_id(CAPTCHA_ID)\n location = captcha.location_once_scrolled_into_view\n return location\n\n\ndef crop_captcha(driver):\n location = get_captcha_location(driver)\n screenshot = take_screenshot(driver)\n\n CAPTCHA_WIDTH, CAPTCHA_HEIGHT = 180, 50\n CAPTCHA_IMAGE = (location['x'],\n location['y'],\n location['x'] + CAPTCHA_WIDTH,\n location['y'] + CAPTCHA_HEIGHT)\n\n captcha = screenshot.crop(CAPTCHA_IMAGE)\n return captcha\n","sub_path":"docker/app/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"156961456","text":"from __future__ import print_function\nimport dbt.schema\nimport dbt.templates\nimport jinja2\n\nfrom dbt.adapters.factory import get_adapter\n\n\nclass Archival(object):\n\n def __init__(self, project, archive_model):\n self.archive_model = archive_model\n self.project = project\n\n def compile(self):\n source_schema = self.archive_model.source_schema\n target_schema = self.archive_model.target_schema\n source_table = self.archive_model.source_table\n target_table = self.archive_model.target_table\n unique_key = self.archive_model.unique_key\n updated_at = self.archive_model.updated_at\n\n profile = self.project.run_environment()\n adapter = get_adapter(profile)\n\n adapter.create_schema(profile, target_schema)\n\n source_columns = adapter.get_columns_in_table(\n profile, source_schema, source_table)\n\n if len(source_columns) == 0:\n raise RuntimeError(\n 'Source table \"{}\".\"{}\" does not '\n 'exist'.format(source_schema, source_table))\n\n extra_cols = [\n dbt.schema.Column(\"valid_from\", \"timestamp\", None),\n dbt.schema.Column(\"valid_to\", \"timestamp\", None),\n dbt.schema.Column(\"scd_id\", \"text\", None),\n dbt.schema.Column(\"dbt_updated_at\", \"timestamp\", None)\n ]\n\n dest_columns = source_columns + extra_cols\n\n adapter.create_table(\n profile,\n target_schema,\n target_table,\n dest_columns,\n sort=updated_at,\n dist=unique_key\n )\n\n env = jinja2.Environment()\n\n ctx = {\n \"columns\": source_columns,\n \"updated_at\": updated_at,\n \"unique_key\": unique_key,\n \"source_schema\": source_schema,\n \"source_table\": source_table,\n \"target_schema\": target_schema,\n \"target_table\": target_table\n }\n\n base_query = dbt.templates.SCDArchiveTemplate\n template = env.from_string(base_query, globals=ctx)\n rendered = template.render(ctx)\n\n return rendered\n","sub_path":"dbt/archival.py","file_name":"archival.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"305246312","text":"# coding: utf-8\n\n\"\"\"\n Cloudera Manager API\n\n

Cloudera Manager API v33

Introduced in Cloudera Manager 6.3.0

Cloudera Product Documentation

\n\n OpenAPI spec version: 6.3.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom pprint import pformat\nfrom six import iteritems\nimport re\n\n\nclass ApiClusterTemplate(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'cdh_version': 'str',\n 'products': 'list[ApiProductVersion]',\n 'services': 'list[ApiClusterTemplateService]',\n 'host_templates': 'list[ApiClusterTemplateHostTemplate]',\n 'display_name': 'str',\n 'cm_version': 'str',\n 'instantiator': 'ApiClusterTemplateInstantiator',\n 'repositories': 'list[str]',\n 'cluster_spec': 'ApiClusterTemplateClusterSpec'\n }\n\n attribute_map = {\n 'cdh_version': 'cdhVersion',\n 'products': 'products',\n 'services': 'services',\n 'host_templates': 'hostTemplates',\n 'display_name': 'displayName',\n 'cm_version': 'cmVersion',\n 'instantiator': 'instantiator',\n 'repositories': 'repositories',\n 'cluster_spec': 'clusterSpec'\n }\n\n def __init__(self, cdh_version=None, products=None, services=None, host_templates=None, display_name=None, cm_version=None, instantiator=None, repositories=None, cluster_spec=None):\n \"\"\"\n ApiClusterTemplate - a model defined in Swagger\n \"\"\"\n\n self._cdh_version = None\n self._products = None\n self._services = None\n self._host_templates = None\n self._display_name = None\n self._cm_version = None\n self._instantiator = None\n self._repositories = None\n self._cluster_spec = None\n\n if cdh_version is not None:\n self.cdh_version = cdh_version\n if products is not None:\n self.products = products\n if services is not None:\n self.services = services\n if host_templates is not None:\n self.host_templates = host_templates\n if display_name is not None:\n self.display_name = display_name\n if cm_version is not None:\n self.cm_version = cm_version\n if instantiator is not None:\n self.instantiator = instantiator\n if repositories is not None:\n self.repositories = repositories\n if cluster_spec is not None:\n self.cluster_spec = cluster_spec\n\n @property\n def cdh_version(self):\n \"\"\"\n Gets the cdh_version of this ApiClusterTemplate.\n CDH version\n\n :return: The cdh_version of this ApiClusterTemplate.\n :rtype: str\n \"\"\"\n return self._cdh_version\n\n @cdh_version.setter\n def cdh_version(self, cdh_version):\n \"\"\"\n Sets the cdh_version of this ApiClusterTemplate.\n CDH version\n\n :param cdh_version: The cdh_version of this ApiClusterTemplate.\n :type: str\n \"\"\"\n\n self._cdh_version = cdh_version\n\n @property\n def products(self):\n \"\"\"\n Gets the products of this ApiClusterTemplate.\n All the parcels that needs to be deployed and activated\n\n :return: The products of this ApiClusterTemplate.\n :rtype: list[ApiProductVersion]\n \"\"\"\n return self._products\n\n @products.setter\n def products(self, products):\n \"\"\"\n Sets the products of this ApiClusterTemplate.\n All the parcels that needs to be deployed and activated\n\n :param products: The products of this ApiClusterTemplate.\n :type: list[ApiProductVersion]\n \"\"\"\n\n self._products = products\n\n @property\n def services(self):\n \"\"\"\n Gets the services of this ApiClusterTemplate.\n All the services that needs to be deployed\n\n :return: The services of this ApiClusterTemplate.\n :rtype: list[ApiClusterTemplateService]\n \"\"\"\n return self._services\n\n @services.setter\n def services(self, services):\n \"\"\"\n Sets the services of this ApiClusterTemplate.\n All the services that needs to be deployed\n\n :param services: The services of this ApiClusterTemplate.\n :type: list[ApiClusterTemplateService]\n \"\"\"\n\n self._services = services\n\n @property\n def host_templates(self):\n \"\"\"\n Gets the host_templates of this ApiClusterTemplate.\n All host templates\n\n :return: The host_templates of this ApiClusterTemplate.\n :rtype: list[ApiClusterTemplateHostTemplate]\n \"\"\"\n return self._host_templates\n\n @host_templates.setter\n def host_templates(self, host_templates):\n \"\"\"\n Sets the host_templates of this ApiClusterTemplate.\n All host templates\n\n :param host_templates: The host_templates of this ApiClusterTemplate.\n :type: list[ApiClusterTemplateHostTemplate]\n \"\"\"\n\n self._host_templates = host_templates\n\n @property\n def display_name(self):\n \"\"\"\n Gets the display_name of this ApiClusterTemplate.\n Cluster display name\n\n :return: The display_name of this ApiClusterTemplate.\n :rtype: str\n \"\"\"\n return self._display_name\n\n @display_name.setter\n def display_name(self, display_name):\n \"\"\"\n Sets the display_name of this ApiClusterTemplate.\n Cluster display name\n\n :param display_name: The display_name of this ApiClusterTemplate.\n :type: str\n \"\"\"\n\n self._display_name = display_name\n\n @property\n def cm_version(self):\n \"\"\"\n Gets the cm_version of this ApiClusterTemplate.\n CM version for which the template\n\n :return: The cm_version of this ApiClusterTemplate.\n :rtype: str\n \"\"\"\n return self._cm_version\n\n @cm_version.setter\n def cm_version(self, cm_version):\n \"\"\"\n Sets the cm_version of this ApiClusterTemplate.\n CM version for which the template\n\n :param cm_version: The cm_version of this ApiClusterTemplate.\n :type: str\n \"\"\"\n\n self._cm_version = cm_version\n\n @property\n def instantiator(self):\n \"\"\"\n Gets the instantiator of this ApiClusterTemplate.\n A constructor listing all the variables and references that needs to be resolved for this template\n\n :return: The instantiator of this ApiClusterTemplate.\n :rtype: ApiClusterTemplateInstantiator\n \"\"\"\n return self._instantiator\n\n @instantiator.setter\n def instantiator(self, instantiator):\n \"\"\"\n Sets the instantiator of this ApiClusterTemplate.\n A constructor listing all the variables and references that needs to be resolved for this template\n\n :param instantiator: The instantiator of this ApiClusterTemplate.\n :type: ApiClusterTemplateInstantiator\n \"\"\"\n\n self._instantiator = instantiator\n\n @property\n def repositories(self):\n \"\"\"\n Gets the repositories of this ApiClusterTemplate.\n List of all repositories registered with CM\n\n :return: The repositories of this ApiClusterTemplate.\n :rtype: list[str]\n \"\"\"\n return self._repositories\n\n @repositories.setter\n def repositories(self, repositories):\n \"\"\"\n Sets the repositories of this ApiClusterTemplate.\n List of all repositories registered with CM\n\n :param repositories: The repositories of this ApiClusterTemplate.\n :type: list[str]\n \"\"\"\n\n self._repositories = repositories\n\n @property\n def cluster_spec(self):\n \"\"\"\n Gets the cluster_spec of this ApiClusterTemplate.\n Cluster specification.\n\n :return: The cluster_spec of this ApiClusterTemplate.\n :rtype: ApiClusterTemplateClusterSpec\n \"\"\"\n return self._cluster_spec\n\n @cluster_spec.setter\n def cluster_spec(self, cluster_spec):\n \"\"\"\n Sets the cluster_spec of this ApiClusterTemplate.\n Cluster specification.\n\n :param cluster_spec: The cluster_spec of this ApiClusterTemplate.\n :type: ApiClusterTemplateClusterSpec\n \"\"\"\n\n self._cluster_spec = cluster_spec\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if not isinstance(other, ApiClusterTemplate):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n","sub_path":"venv/lib/python3.7/site-packages/cm_client/models/api_cluster_template.py","file_name":"api_cluster_template.py","file_ext":"py","file_size_in_byte":10150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"287576030","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'polls'\nurlpatterns = [\n path('index/', views.index, name='index'),\n path('index_demo/', views.index_demo, name='index_demo'),\n path('/', views.detail, name='detail'),\n path('/results/', views.results, name='results'),\n path('/vote/', views.vote, name='vote'),\n path('test_demo//', views.test_demo, name='test_demo'),\n path('press_list/', views.press_list, name='press_list'),\n\n]\n","sub_path":"mySiteOne/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"463980545","text":"\"\"\"\nHTML Widget classes\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom django.forms.utils import flatatt, to_current_timezone\nfrom django.utils.html import conditional_escape, format_html, html_safe\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy\nfrom django.forms import Media, MediaDefiningClass, Widget, CheckboxInput\nfrom django.utils.safestring import SafeText\n\n__all__ = (\n 'ClearableMultipleFileInput', 'FileInput',\n)\n\nMEDIA_TYPES = ('css', 'js')\n\nclass InputMultiFile(Widget):\n \"\"\"\n Base class for all widgets (except type='checkbox' and\n type='radio', which are special).\n \"\"\"\n input_type = None # Subclasses must define this.\n\n def format_value(self, value):\n if self.is_localized:\n return formats.localize_input(value)\n return value\n\n def render(self, name, value, attrs=None):\n if value is None:\n value = ''\n final_attrs = self.build_attrs(attrs, type=self.input_type, name=name, )\n if value != '':\n # Only add the 'value' attribute if a value is non-empty.\n final_attrs['value'] = force_text(self.format_value(value))\n return format_html('', flatatt(final_attrs))\n\nclass FileInput(InputMultiFile):\n input_type = 'file'\n needs_multipart_form = True\n\n def render(self, name, value, attrs=None):\n return super(FileInput, self).render(name, None, attrs=attrs)\n\n def value_from_datadict(self, data, files, name):\n \"File widgets take data from FILES, not POST\"\n return files.get(name)\n\n def value_omitted_from_data(self, data, files, name):\n return name not in files\n\nclass ClearableMultipleFileInput(FileInput):\n initial_text = ugettext_lazy('Currently testing')\n input_text = ugettext_lazy('Change')\n clear_checkbox_label = ugettext_lazy('Clear')\n\n template_with_initial = (\n '%(initial_text)s: %(initial)s '\n '%(clear_template)s
%(input_text)s: %(input)s'\n )\n\n template_with_clear = '%(clear)s '\n\n def clear_checkbox_name(self, name):\n \"\"\"\n Given the name of the file input, return the name of the clear checkbox\n input.\n \"\"\"\n return name + '-clear'\n\n def clear_checkbox_id(self, name):\n \"\"\"\n Given the name of the clear checkbox input, return the HTML id for it.\n \"\"\"\n return name + '_id'\n\n def is_initial(self, value):\n \"\"\"\n Return whether value is considered to be initial value.\n \"\"\"\n return bool(value and getattr(value, 'url', False))\n\n def get_template_substitution_values(self, value):\n \"\"\"\n Return value-related substitutions.\n \"\"\"\n #return {\n # 'initial': conditional_escape(value),\n # 'initial_url': conditional_escape(value.url),\n #}\n\n def render(self, name, value, attrs=None):\n substitutions = {\n 'initial_text': self.initial_text,\n 'input_text': self.input_text,\n 'clear_template': '',\n 'clear_checkbox_label': self.clear_checkbox_label,\n }\n\n template = '%(input)s %(clearfiles)s'\n substitutions['input'] = super(ClearableMultipleFileInput, self).render(name, value, attrs)\n substitutions['clearfiles'] = ''\n if type(value) is list:\n substitutions['clearfiles'] = \"
\"\n if value:\n for fi in value:\n if fi:\n substitutions['clearfiles'] += \"\"\n substitutions['clearfiles'] += \"
Clear
\"\n\n if self.is_initial(value):\n template = self.template_with_initial\n substitutions.update(self.get_template_substitution_values(value))\n if not self.is_required:\n checkbox_name = self.clear_checkbox_name(name)\n checkbox_id = self.clear_checkbox_id(checkbox_name)\n substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)\n substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)\n substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})\n substitutions['clear_template'] = self.template_with_clear % substitutions\n\n return mark_safe(template % substitutions)\n\n def value_from_datadict(self, data, files, name):\n upload = super(ClearableMultipleFileInput, self).value_from_datadict(data, files, name)\n if not self.is_required and CheckboxInput().value_from_datadict(\n data, files, self.clear_checkbox_name(name)):\n\n if upload:\n # If the user contradicts themselves (uploads a new file AND\n # checks the \"clear\" checkbox), we return a unique marker\n # object that FileField will turn into a ValidationError.\n return FILE_INPUT_CONTRADICTION\n # False signals to clear any existing value, as opposed to just None\n return False\n return upload\n\n def use_required_attribute(self, initial):\n return super(ClearableMultipleFileInput, self).use_required_attribute(initial) and not initial\n\n def value_omitted_from_data(self, data, files, name):\n return (\n super(ClearableMultipleFileInput, self).value_omitted_from_data(data, files, name) and\n self.clear_checkbox_name(name) not in data\n )\n\n","sub_path":"applications/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":6047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"181157139","text":"# The functions in this file are adapted from the\n# following repository:\n# https://github.com/utkuozbulak/pytorch-cnn-visualizations\n# We sincerely thank them in making this code publicly available\n\nimport os\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.autograd import Variable\n\n\ndef convert_to_grayscale(im_as_arr):\n \"\"\"\n Converts 3d image to grayscale\n Args:\n im_as_arr (numpy arr): RGB image with shape (D,W,H)\n returns:\n grayscale_im (numpy_arr): Grayscale image with shape (1,W,D)\n \"\"\"\n grayscale_im = np.sum(np.abs(im_as_arr), axis=0)\n im_max = np.percentile(grayscale_im, 99)\n im_min = np.min(grayscale_im)\n grayscale_im = (np.clip((grayscale_im - im_min) / (im_max - im_min), 0, 1))\n grayscale_im = np.expand_dims(grayscale_im, axis=0)\n return grayscale_im\n\n\ndef save_class_activation_images(org_img, activation_map, file_name):\n \"\"\"\n Saves cam activation map and activation map on the original image\n Args:\n org_img (PIL img): Original image\n activation_map (numpy arr): Activation map (grayscale) 0-255\n file_name (str): File name of the exported image\n \"\"\"\n if not os.path.exists('../results'):\n os.makedirs('../results')\n # Grayscale activation map\n heatmap, heatmap_on_image = apply_colormap_on_image(org_img, activation_map, 'hsv')\n # Save colored heatmap\n path_to_file = os.path.join('../results', file_name + '_Cam_Heatmap.png')\n save_image(heatmap, path_to_file)\n # Save heatmap on iamge\n path_to_file = os.path.join('../results', file_name + '_Cam_On_Image.png')\n save_image(heatmap_on_image, path_to_file)\n # SAve grayscale heatmap\n path_to_file = os.path.join('../results', file_name + '_Cam_Grayscale.png')\n save_image(activation_map, path_to_file)\n\n\ndef format_np_output(np_arr):\n \"\"\"\n This is a (kind of) bandaid fix to streamline saving procedure.\n It converts all the outputs to the same format which is 3xWxH\n with using sucecssive if clauses.\n Args:\n im_as_arr (Numpy array): Matrix of shape 1xWxH or WxH or 3xWxH\n \"\"\"\n # Phase/Case 1: The np arr only has 2 dimensions\n # Result: Add a dimension at the beginning\n if len(np_arr.shape) == 2:\n np_arr = np.expand_dims(np_arr, axis=0)\n # Phase/Case 2: Np arr has only 1 channel (assuming first dim is channel)\n # Result: Repeat first channel and convert 1xWxH to 3xWxH\n if np_arr.shape[0] == 1:\n np_arr = np.repeat(np_arr, 3, axis=0)\n # Phase/Case 3: Np arr is of shape 3xWxH\n # Result: Convert it to WxHx3 in order to make it saveable by PIL\n if np_arr.shape[0] == 3:\n np_arr = np_arr.transpose(1, 2, 0)\n # Phase/Case 4: NP arr is normalized between 0-1\n # Result: Multiply with 255 and change type to make it saveable by PIL\n if np.max(np_arr) <= 1:\n np_arr = (np_arr * 255).astype(np.uint8)\n return np_arr\n\n\ndef save_gradient_images(gradient, file_name):\n \"\"\"\n Exports the original gradient image\n Args:\n gradient (np arr): Numpy array of the gradient with shape (3, 224, 224)\n file_name (str): File name to be exported\n \"\"\"\n # Normalize\n gradient = gradient - gradient.min()\n gradient /= gradient.max()\n # Save image\n\n if file_name is not None:\n path_to_file = os.path.join(file_name)\n\n # Pass through the PIL Image to return\n return save_image(gradient, path_to_file)\n else:\n return save_image(gradient, None)\n\n\ndef save_image(im, path):\n \"\"\"\n Saves a numpy matrix or PIL image as an image\n Args:\n im_as_arr (Numpy array): Matrix of shape DxWxH\n path (str): Path to the image\n \"\"\"\n if isinstance(im, (np.ndarray, np.generic)):\n im = format_np_output(im)\n im = Image.fromarray(im)\n\n if path is not None:\n im.save(path)\n\n return im\n\n\ndef preprocess_image(pil_im, resize_im=True):\n \"\"\"\n Processes image for CNNs\n Args:\n PIL_img (PIL_img): Image to process\n resize_im (bool): Resize to 224 or not\n returns:\n im_as_var (torch variable): Variable that contains processed float tensor\n \"\"\"\n # mean and std list for channels (Imagenet)\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n # Resize image\n if resize_im:\n pil_im = pil_im.resize((224, 224))\n im_as_arr = np.float32(pil_im)\n im_as_arr = im_as_arr.transpose(2, 0, 1) # Convert array to D,W,H\n # Normalize the channels\n for channel, _ in enumerate(im_as_arr):\n im_as_arr[channel] /= 255\n im_as_arr[channel] -= mean[channel]\n im_as_arr[channel] /= std[channel]\n # Convert to float tensor\n im_as_ten = torch.from_numpy(im_as_arr).float()\n # Add one more channel to the beginning. Tensor shape = 1,3,224,224\n im_as_ten.unsqueeze_(0)\n # Convert to Pytorch variable\n im_as_var = Variable(im_as_ten, requires_grad=True)\n return im_as_var\n\n\ndef get_positive_negative_saliency(gradient):\n \"\"\"\n Generates positive and negative saliency maps based on the gradient\n Args:\n gradient (numpy arr): Gradient of the operation to visualize\n returns:\n pos_saliency ( )\n \"\"\"\n pos_saliency = (np.maximum(0, gradient) / gradient.max())\n neg_saliency = (np.maximum(0, -gradient) / -gradient.min())\n return pos_saliency, neg_saliency\n\n\ndef get_positive_negative_saliency_IMPROVED(gradient):\n \"\"\"\n Generates positive and negative saliency maps based on the gradient\n This has been improved by instead dividing by the MEAN instead of the min and max\n Args:\n gradient (numpy arr): Gradient of the operation to visualize\n returns:\n pos_saliency ( )\n \"\"\"\n pos_saliency = (np.maximum(0, gradient) / gradient.mean())\n neg_saliency = (np.maximum(0, -gradient) / -gradient.mean())\n return pos_saliency, neg_saliency\n","sub_path":"util/map_util.py","file_name":"map_util.py","file_ext":"py","file_size_in_byte":5927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"160898837","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('store', '0010_auto_20180226_0857'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='customer',\n name='mobile_number',\n field=models.CharField(max_length=10),\n ),\n ]\n","sub_path":"store/migrations/0011_auto_20180226_0903.py","file_name":"0011_auto_20180226_0903.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"522289622","text":"import pygame\nfrom player import Player\nfrom fonction_du_jeu import Function\n\n\npygame.init()\n\n\nclass Game:\n def __init__(self):\n # variable qui va nous dire si l'user lance le jeu\n self.on_joue = False\n self.function = Function()\n self.player1 = Player(\"N\", \"assets/coca.png\")\n self.player2 = Player(\"S\", \"assets/Fanta.jpg\")\n self.liste_rect = []\n\n\n def start(self):\n # en change cette variable le jeu demande\n self.on_joue = True\n\n def c_partie(self, screen):\n # on affiche le premier groupe de joueur\n # for i in self.function.planjoeur(side=\"N\"):\n screen.blit(self.player1.image, self.function.dicofinal()[\"c2\"])\n # on affiche le deuxieme groupe de joueur\n # for ii in self.function.planjoeur(side=\"S\"):\n screen.blit(self.player2.image, self.function.dicofinal()[\"d9\"])\n\n\n def tab(self):\n # liste de tout le rectangle\n for iii in self.function.planjoeur(side=\"I\"):\n self.liste_rect.append(pygame.Rect(self.function.dicofinal()[iii], (70, 70)))\n return self.liste_rect\n\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"601250168","text":"#!/usr/bin/python3\n# coding=utf-8\n\nimport argparse\nimport influxdb.exceptions\nimport logging\nimport requests\nimport socket\nimport time\n\nfrom datetime import datetime\nfrom influxdb import InfluxDBClient\nfrom read_sensor_data import read_temp\n\n\nclass InfluxDBLogger:\n\n def __init__(self, device, sensor_type, node, measurement, database, host='localhost', port=8086, user=None, password=None):\n if user and password is not None:\n self.influx_client = InfluxDBClient(\n host, port, user, password, database)\n else:\n self.influx_client = InfluxDBClient(host, port, database=database)\n\n self.measurement = measurement\n self.device = device\n self.sensor_type = sensor_type\n self.node = node\n\n def construct_db_string(self, temperature):\n jason_string = [\n {\n \"measurement\": self.measurement,\n \"tags\": {\n \"device\": self.device,\n \"node\": self.node,\n \"sensor\": self.sensor_type\n },\n \"time\": datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),\n \"fields\": {\n \"temperature\": temperature\n }\n }\n ]\n\n return jason_string\n\n def log_temperature(self, sensor_id):\n temperature = read_temp(sensor_id)\n if temperature is not None:\n data = self.construct_db_string(temperature)\n try:\n self.influx_client.write_points(data)\n except (influxdb.exceptions.InfluxDBServerError, requests.exceptions.ConnectionError) as err:\n logging.error(err)\n else:\n logging.error(\"Error while reading temperature\")\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='InfluxDB logger')\n parser.add_argument('--host', type=str, required=False,\n default='localhost',\n help='hostname of InfluxDB http API')\n parser.add_argument('--port', type=int, required=False, default=8086,\n help='port of InfluxDB http API')\n parser.add_argument('--device-name', type=str, required=False,\n default=socket.gethostname(), help='the devices name, defaults to hostname')\n parser.add_argument('--sensor-type', type=str, required=True,\n help='sensor type e.g. a DHT22 or DS18B20')\n parser.add_argument('--node', type=str, required=True,\n help='a description of the devices purpose e.g. the location')\n parser.add_argument('--measurement', type=str, required=True, help='')\n parser.add_argument('--database', type=str, required=True,\n help='a InfluxDB database name')\n parser.add_argument('--sensor-id', type=str, required=True)\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n sensor_id = args.sensor_id\n sensor_name = \"/sys/bus/w1/devices/%s/w1_slave\" % sensor_id\n client = InfluxDBLogger(args.device_name, args.sensor_type, args.node,\n args.measurement, args.database, host=args.host, port=args.port)\n\n logging.basicConfig(format='%(levelname)s %(asctime)s: %(message)s', level=logging.INFO)\n while True:\n start = time.time()\n client.log_temperature(sensor_name)\n end = time.time()\n logging.debug(end - start)\n time.sleep(30)\n","sub_path":"measure/influxdb_logger.py","file_name":"influxdb_logger.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"61348105","text":"import sys\n\npositions = list(map(int, sys.stdin.readline().strip().split(\",\")))\nmaxPosition = max(positions)\nminPosition = min(positions)\ntotal = 999999999\n\nfor x in range(minPosition, maxPosition + 1):\n fuel = 0\n for position in positions:\n fuel += (float(abs(x - position)) / 2) * (1 + abs(x - position))\n\n if fuel < total:\n total = fuel\n\nprint(total)\n","sub_path":"2021/7/second_solution.py","file_name":"second_solution.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"549030724","text":"from __future__ import print_function\nfrom constants import *\nimport pygame\nfrom levels import GravityBlock, SpeedBlock, DoorBlock, mainlist #This will hopefully be changed so that it doesn't need to do this\nfrom time import time\n\n#######################################\n# #\n# Player #\n# #\n#######################################\nclass Player(pygame.sprite.Sprite):\n\n #initialize these variables\n change_x = 0\n change_y = 0\n level = None\n\n def __init__(self, pos):\n pygame.sprite.Sprite.__init__(self)\n\n\n #player image\n self.image = pygame.image.load('../images/trent.png')\n #self.image = pygame.Surface(PLAYERSIZE)\n #self.image.fill(RED)\n\n self.rect = self.image.get_rect()\n self.rect.x = pos[0]\n self.rect.y = pos[1]\n\n self.facing = 'right'\n self.effects = []\n\n #At 1, this is essentially inactive. to slow, lower than 1, to speed up, higher than 1\n self.speedmodifier = 1\n\n #default gravity amount\n self.grav_amount = .35\n\n def update(self):\n ###move player###\n #gravity\n self.calc_grav(self.grav_amount)\n #left/right\n self.rect.x += self.change_x\n\n ######################################\n # Power Up/Event Block Collision #\n ######################################\n block_hit_list = pygame.sprite.spritecollide(self, self.level.special_blocks, False)\n for block in block_hit_list:\n\n ###GRAVITY###\n if isinstance(block, GravityBlock):\n self.grav_start = time() #Start timer for effect\n self.grav_amount = .15 #Status effected\n self.effects.append('low_gravity') #Append to effects list\n self.level.special_blocks.remove(block) #Remove the block you got\n\n ###SPEED UP###\n if isinstance(block, SpeedBlock):\n self.speed_start = time() #Start timer for effect\n self.speedmodifier = 2 #Status affected\n self.effects.append('speed') #Append to effects list\n self.level.special_blocks.remove(block) #Remove the block you got\n\n ###DOOR###\n if isinstance(block, DoorBlock):\n if block.cooldown == \"off\":\n if pygame.key.get_pressed()[pygame.K_w] or block.auto:\n self.rect.bottomleft = mainlist[block.room].doorlist[block.linkeddoor].rect.bottomleft\n mainlist[block.room].doorlist[block.linkeddoor].cooldown = \"on\"\n self.level = mainlist[block.room]\n\n\n ###############################\n # Platform Collision #\n ###############################\n block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n for block in block_hit_list:\n if self.change_x > 0: #if moving right\n self.rect.right = block.rect.left #set the right edge of the player to the left edge fo the block you collided with\n elif self.change_x < 0: #if moving left\n self.rect.left = block.rect.right #do the inverse\n\n #up/down, player's y position changes based on value of self.change_y\n self.rect.y += self.change_y\n\n ###check for collisions with platforms again... why?###\n block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n for block in block_hit_list:\n if self.change_y > 0:#if moving down\n self.rect.bottom = block.rect.top #set the bottom of the player rect to the top of the block you collided with\n elif self.change_y < 0:#if moving up\n self.rect.top = block.rect.bottom#do the inverse\n\n self.change_y = 0 #reset self.change_y value so that you aren't moving up anymore if jumping and gravity can take its course\n\n\n ###check for status effects###\n if self.effects:\n for effect in self.effects:\n if effect == 'speed':\n if time() - self.speed_start > 5: #checks for five seconds since the effect started, if it has been longer than 5 seconds...\n self.speedmodifier = 1 #reset speed\n self.effects.remove(effect) #remove effect\n\n if effect == 'low_gravity': #same model as above..\n if time() - self.grav_start > 5:\n self.grav_amount = .35\n self.effects.remove(effect)\n\n def calc_grav(self, amount):\n if self.change_y == 0:#if change_y is nothing...\n self.change_y = 1 #keep pushing player down one...?\n else:\n self.change_y += amount #otherwise, if change_y is anything, add .35 to it (positive numbers represent downward motion)\n\n #if bottom of player is outside of screen and still moving down...\n if self.rect.y >= GAMESURFH - self.rect.height and self.change_y >= 0:\n self.change_y = 0 #stop y motion\n self.rect.y = GAMESURFH - self.rect.height #set player's bottom edge on bottom of screen\n\n def jump(self):\n\n #moves down two px to check for platform collision below\n self.rect.y += 2\n #should collide if platform is below\n platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n self.rect.y -= 2 #moves back up\n\n #if collided with a platform or if you're at the bottom of the screen, then you are allowed to jump\n if len(platform_hit_list) > 0 or self.rect.bottom >= GAMESURFH:\n self.change_y = -10 #jump.. negative\n\n ################################\n # KEY - CONTROLLED MOVEMENT #\n ################################\n def go_left(self):\n self.change_x = -PLAYERSPEED * self.speedmodifier\n if self.facing == 'right':\n self.image = pygame.transform.flip(self.image, 1, 0) #flips image based on direction\n self.facing = 'left'\n\n def go_right(self):\n self.change_x = PLAYERSPEED * self.speedmodifier\n if self.facing == 'left':\n self.image = pygame.transform.flip(self.image, 1, 0) #same thing as above\n self.facing = 'right'\n\n def stop(self):\n self.change_x = 0\n\n def stopjump(self):\n self.change_y = self.change_y / 2 #contols the way the jump handles when you release space bar\n\n#######################################\n# #\n# Projectiles #\n# #\n#######################################\nclass Bullet(pygame.sprite.Sprite):\n \"\"\"A class for Bullet objects\"\"\"\n def __init__(self, owner):\n pygame.sprite.Sprite.__init__(self)\n\n self.owner = owner\n #To get the constant direction of the bullet, get the direction that the person who shot it was facing when they did\n self.direction = self.owner.facing\n self.image = pygame.Surface(BULLETSIZE) #4,10 is the size\n self.image.fill(BULLETCOLOR) #a blackish color\n self.rect = self.image.get_rect()\n\n def update(self): #moves bullet in direction\n if self.direction == 'right':\n self.rect.x += BULLETSPEED\n else:\n self.rect.x -= BULLETSPEED\n\n","sub_path":"sub-squares/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":7447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"527163427","text":"# -*- coding:utf-8 -*-\nimport hashlib\nfrom unittest import skipIf\n\nimport django\nfrom django.db.models import F\nfrom django.test import TestCase\n\nfrom django_mysql.models.functions import (\n CRC32, ELT, MD5, SHA1, SHA2, Abs, Ceiling, ConcatWS, Field, Floor,\n Greatest, LastInsertId, Least, Round, Sign\n)\nfrom django_mysql_tests.models import Alphabet\n\nrequiresDatabaseFunctions = skipIf(\n django.VERSION <= (1, 8),\n \"Requires Database Functions from Django 1.8+\"\n)\n\n\n@requiresDatabaseFunctions\nclass ComparisonFunctionTests(TestCase):\n\n def test_greatest(self):\n Alphabet.objects.create(d='A', e='B')\n ab = Alphabet.objects.annotate(best=Greatest('d', 'e')).first()\n self.assertEqual(ab.best, 'B')\n\n def test_greatest_takes_no_kwargs(self):\n with self.assertRaises(TypeError):\n Greatest('a', something='wrong')\n\n def test_least(self):\n Alphabet.objects.create(a=1, b=2, c=-1)\n ab = Alphabet.objects.annotate(worst=Least('a', 'b', 'c')).first()\n self.assertEqual(ab.worst, -1)\n\n\n@requiresDatabaseFunctions\nclass NumericFunctionTests(TestCase):\n\n def test_abs(self):\n Alphabet.objects.create(a=-2)\n ab = Alphabet.objects.annotate(aaa=Abs('a')).first()\n self.assertEqual(ab.aaa, 2)\n\n def test_ceiling(self):\n Alphabet.objects.create(g=0.5)\n ab = Alphabet.objects.annotate(gceil=Ceiling('g')).first()\n self.assertEqual(ab.gceil, 1)\n\n def test_crc32(self):\n Alphabet.objects.create(d='AAAAAA')\n ab = Alphabet.objects.annotate(crc=CRC32('d')).first()\n # Precalculated this in MySQL prompt. Python's binascii.crc32 doesn't\n # match - maybe sign issues?\n self.assertEqual(ab.crc, 2854018686)\n\n def test_crc32_only_takes_one_arg_no_kwargs(self):\n with self.assertRaises(TypeError):\n CRC32('d', 'c')\n\n with self.assertRaises(TypeError):\n CRC32('d', something='wrong')\n\n def test_floor(self):\n Alphabet.objects.create(g=1.5)\n ab = Alphabet.objects.annotate(gfloor=Floor('g')).first()\n self.assertEqual(ab.gfloor, 1)\n\n def test_round(self):\n Alphabet.objects.create(g=24.459)\n ab = Alphabet.objects.annotate(ground=Round('g')).get()\n self.assertEqual(ab.ground, 24)\n\n def test_round_up(self):\n Alphabet.objects.create(g=27.859)\n ab = Alphabet.objects.annotate(ground=Round('g')).get()\n self.assertEqual(ab.ground, 28)\n\n def test_round_places(self):\n Alphabet.objects.create(a=81731)\n ab = Alphabet.objects.annotate(around=Round('a', -2)).get()\n self.assertEqual(ab.around, 81700)\n\n def test_sign(self):\n Alphabet.objects.create(a=123, b=0, c=-999)\n ab = Alphabet.objects.annotate(\n asign=Sign('a'),\n bsign=Sign('b'),\n csign=Sign('c'),\n ).first()\n self.assertEqual(ab.asign, 1)\n self.assertEqual(ab.bsign, 0)\n self.assertEqual(ab.csign, -1)\n\n\n@requiresDatabaseFunctions\nclass StringFunctionTests(TestCase):\n\n def test_concat_ws(self):\n Alphabet.objects.create(d='AAA', e='BBB')\n ab = Alphabet.objects.annotate(de=ConcatWS('d', 'e')).first()\n self.assertEqual(ab.de, 'AAA,BBB')\n\n def test_concat_ws_integers(self):\n Alphabet.objects.create(a=1, b=2)\n ab = Alphabet.objects.annotate(ab=ConcatWS('a', 'b')).first()\n self.assertEqual(ab.ab, '1,2')\n\n def test_concat_ws_skips_nulls(self):\n Alphabet.objects.create(d='AAA', e=None, f=2)\n ab = Alphabet.objects.annotate(de=ConcatWS('d', 'e', 'f')).first()\n self.assertEqual(ab.de, 'AAA,2')\n\n def test_concat_ws_separator(self):\n Alphabet.objects.create(d='AAA', e='BBB')\n ab = (\n Alphabet.objects.annotate(de=ConcatWS('d', 'e', separator=':'))\n .first()\n )\n self.assertEqual(ab.de, 'AAA:BBB')\n\n def test_concat_ws_separator_null_returns_none(self):\n Alphabet.objects.create(a=1, b=2)\n concat = ConcatWS('a', 'b', separator=None)\n ab = Alphabet.objects.annotate(ab=concat).first()\n self.assertEqual(ab.ab, None)\n\n def test_concat_ws_separator_field(self):\n Alphabet.objects.create(a=1, d='AAA', e='BBB')\n concat = ConcatWS('d', 'e', separator=F('a'))\n ab = Alphabet.objects.annotate(de=concat).first()\n self.assertEqual(ab.de, 'AAA1BBB')\n\n def test_concat_ws_bad_arg(self):\n with self.assertRaises(ValueError) as cm:\n ConcatWS('a', 'b', separataaa=',')\n self.assertIn('Invalid keyword arguments for ConcatWS: separataaa',\n str(cm.exception))\n\n def test_concat_ws_too_few_fields(self):\n with self.assertRaises(ValueError) as cm:\n ConcatWS('a')\n self.assertIn('ConcatWS must take at least two expressions',\n str(cm.exception))\n\n def test_concat_ws_then_lookups_from_textfield(self):\n Alphabet.objects.create(d='AAA', e='BBB')\n Alphabet.objects.create(d='AAA', e='CCC')\n ab = (\n Alphabet.objects.annotate(de=ConcatWS('d', 'e', separator=':'))\n .filter(de__endswith=':BBB')\n .first()\n )\n self.assertEqual(ab.de, 'AAA:BBB')\n\n def test_elt_simple(self):\n Alphabet.objects.create(a=2)\n ab = Alphabet.objects.annotate(elt=ELT('a', ['apple', 'orange'])).get()\n self.assertEqual(ab.elt, 'orange')\n ab = Alphabet.objects.annotate(elt=ELT('a', ['apple'])).get()\n self.assertEqual(ab.elt, None)\n\n def test_field_simple(self):\n Alphabet.objects.create(d='a')\n ab = Alphabet.objects.annotate(dp=Field('d', ['a', 'b'])).first()\n self.assertEqual(ab.dp, 1)\n ab = Alphabet.objects.annotate(dp=Field('d', ['b', 'a'])).first()\n self.assertEqual(ab.dp, 2)\n ab = Alphabet.objects.annotate(dp=Field('d', ['c', 'd'])).first()\n self.assertEqual(ab.dp, 0)\n\n def test_order_by(self):\n Alphabet.objects.create(a=1, d='AAA')\n Alphabet.objects.create(a=2, d='CCC')\n Alphabet.objects.create(a=4, d='BBB')\n Alphabet.objects.create(a=3, d='BBB')\n avalues = list(\n Alphabet.objects.order_by(Field('d', ['AAA', 'BBB']), 'a')\n .values_list('a', flat=True)\n )\n self.assertEqual(avalues, [2, 1, 3, 4])\n\n\n@requiresDatabaseFunctions\nclass EncryptionFunctionTests(TestCase):\n\n def test_md5_string(self):\n string = 'A string'\n Alphabet.objects.create(d=string)\n pymd5 = hashlib.md5(string.encode('ascii')).hexdigest()\n ab = Alphabet.objects.annotate(md5=MD5('d')).first()\n self.assertEqual(ab.md5, pymd5)\n\n def test_sha1_string(self):\n string = 'A string'\n Alphabet.objects.create(d=string)\n pysha1 = hashlib.sha1(string.encode('ascii')).hexdigest()\n ab = Alphabet.objects.annotate(sha=SHA1('d')).first()\n self.assertEqual(ab.sha, pysha1)\n\n def test_sha2_string(self):\n string = 'A string'\n Alphabet.objects.create(d=string)\n\n for hash_len in (224, 256, 384, 512):\n sha_func = getattr(hashlib, 'sha{}'.format(hash_len))\n pysha = sha_func(string.encode('ascii')).hexdigest()\n ab = Alphabet.objects.annotate(sha=SHA2('d', hash_len)).first()\n self.assertEqual(ab.sha, pysha)\n\n def test_sha2_string_hash_len_default(self):\n string = 'A string'\n Alphabet.objects.create(d=string)\n pysha512 = hashlib.sha512(string.encode('ascii')).hexdigest()\n ab = Alphabet.objects.annotate(sha=SHA2('d')).first()\n self.assertEqual(ab.sha, pysha512)\n\n def test_sha2_bad_hash_len(self):\n with self.assertRaises(ValueError):\n SHA2('a', 123)\n\n\n@requiresDatabaseFunctions\nclass InformationFunctionTests(TestCase):\n\n def test_last_insert_id(self):\n Alphabet.objects.create(a=7891)\n Alphabet.objects.update(a=LastInsertId('a') + 1)\n lid = LastInsertId.get()\n self.assertEqual(lid, 7891)\n\n def test_last_insert_id_other_db_connection(self):\n Alphabet.objects.using('other').create(a=9191)\n Alphabet.objects.using('other').update(a=LastInsertId('a') + 9)\n lid = LastInsertId.get(using='other')\n self.assertEqual(lid, 9191)\n\n def test_last_insert_id_in_query(self):\n ab1 = Alphabet.objects.create(a=3719, b=717612)\n ab2 = Alphabet.objects.create(a=1838, b=12636)\n\n # Delete but store value of b and re-assign it to first second Alphabet\n Alphabet.objects.filter(id=ab1.id, b=LastInsertId('b')).delete()\n Alphabet.objects.filter(id=ab2.id).update(b=LastInsertId())\n\n ab = Alphabet.objects.get()\n self.assertEqual(ab.b, 717612)\n\n\n@skipIf(django.VERSION >= (1, 8),\n \"Requires old Django version without Database Functions\")\nclass OldDjangoFunctionTests(TestCase):\n\n def test_single_arg_doesnt_work(self):\n with self.assertRaises(ValueError):\n CRC32('name')\n\n def test_multi_arg_doesnt_work(self):\n with self.assertRaises(ValueError):\n Greatest('a', 'b')\n\n def test_concat_ws_doesnt_work(self):\n with self.assertRaises(ValueError):\n ConcatWS('a', 'b', separator='::')\n","sub_path":"tests/django_mysql_tests/test_functions.py","file_name":"test_functions.py","file_ext":"py","file_size_in_byte":9372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"237865310","text":"import helper.monitor as monitor\nfrom helper.ops import linear\nfrom functools import reduce\nimport tensorflow as tf\nkDense = tf.contrib.keras.layers.Dense\nrnn = tf.contrib.rnn\nvariable_scope = tf.variable_scope\nname_scope = tf.name_scope\nnn = tf.nn\n\ndef model(X, out_seq_length, out_dim=1, MLP_size=[64], activation = tf.nn.elu):\n \"\"\"\n `X` - batch_size x encoder length x dim(observation) placeholder\n `out_seq_length` - length of output sequence\n \"\"\"\n in_seq_len = X.shape[1]\n layer_coeff = in_seq_len*out_seq_length\n X = tf.reshape(X, shape=[-1,(X.shape[1]*X.shape[2]).value])\n for l_size in MLP_size:\n X = kDense(l_size*layer_coeff.value, activation=activation)(X)\n return tf.reshape(kDense(out_seq_length)(X), [-1,out_seq_length,out_dim])\n\ndef l1_loss(Yhat,Y):\n return tf.reduce_mean(tf.reduce_mean(tf.abs(Yhat-Y),axis=1))\n\ndef get_reg_loss(l2_weight):\n def l2regl1loss_op(Yhat, Y):\n t_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\n r2 = l2_weight*tf.sqrt(tf.reduce_sum([tf.reduce_sum(tf.square(t)) for t in t_vars]))\n return l1_loss(Yhat, Y)+ r2\n return l2regl1loss_op\n","sub_path":"RNN/models/MLP1.py","file_name":"MLP1.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"324909358","text":"# Copyright 2021 Nokia\n# Licensed under the BSD 3-Clause License.\n# SPDX-License-Identifier: BSD-3-Clause\n\nfrom flask import Blueprint, request, jsonify\nimport json\nimport datetime\nfrom claims import claimstructure\n\npifake_endpoint = Blueprint('pifake_endpoint', __name__)\n\n@pifake_endpoint.route('/log', methods=['GET','POST'])\ndef returnfakemeasuredbootlog():\n\n\n c = claimstructure.Claim()\n c.addHeaderItem(\"ta_received\",str(datetime.datetime.now(datetime.timezone.utc)))\n \n log_content=\"-empty-\"\n \n with open('/var/log/measuredBootLog', 'r') as f:\n \tlog_content = f.read()\n \t\n c.addPayloadItem(\"measuredbootlog\",log_content)\n c.addHeaderItem(\"ta_complete\",str(datetime.datetime.now(datetime.timezone.utc)))\n c.addHeaderItem(\"ak_name\",\"whatever the AK name is here\") \n c.sign()\n rc = c.getClaim()\n\n return jsonify(rc), 200\n\n\n","sub_path":"t10/A10httprest/endpoints/pifake/pifake_endpoint.py","file_name":"pifake_endpoint.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"44881341","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 1 12:11:57 2019\r\n\r\n@author: sren\r\n\"\"\"\r\nimport numpy as np\r\n\r\n\r\n# in this environment, 1 is used to present own moves, -1 the opposites\r\n\r\nclass GameEnv:\r\n def __init__(self):\r\n # initialize the class\r\n self.board = np.zeros(shape=(7,6))\r\n self.toplay = 0\r\n self.done = False\r\n \r\n def reset(self):\r\n # set the game initial\r\n self.board = np.zeros(shape=(7,6))\r\n self.toplay = 0\r\n self.done = False\r\n \r\n def move(self, column):\r\n # take a move and update the board\r\n # the avaluable moves range from 0 to 6\r\n valid_moves = self.get_valid_moves()\r\n if column in valid_moves:\r\n self.update_borad(column, player = 1)\r\n \r\n # check the situation\r\n win_lose = self.check()\r\n if win_lose == 1: #win\r\n reward = 1\r\n elif win_lose == -1: #lose\r\n reward = -1\r\n else:\r\n reward = 0 \r\n \r\n else:\r\n print(\"invalid move!\")\r\n self.show_board()\r\n return self.board, reward \r\n \r\n def check(self):\r\n # check the winning, losing or tie situation\r\n # check column\r\n for m in range(7):\r\n win_lose = self.check_raw(m, self.board)\r\n if win_lose == 1 or win_lose == -1:\r\n return win_lose\r\n \r\n # check raw\r\n board_mirror = self.board.transpose()\r\n for n in range(6):\r\n win_lose = self.check_raw(n, board_mirror)\r\n if win_lose == 1 or win_lose == -1:\r\n return win_lose\r\n \r\n # check diagnose\r\n \r\n return 0 \r\n def check_raw(self, raw, board): \r\n if np.count_nonzero(board[raw]) < 4: #nobody could win\r\n return 0\r\n else:\r\n length = self.max_length(board[raw])\r\n if (length >= 4): #someone wins\r\n winner_num = self.more_element(board[raw])\r\n if winner_num == 1:\r\n return 1 #win\r\n self.done = True\r\n else:\r\n return -1 #lose\r\n self.done = True\r\n else: # nobody wins\r\n return 0\r\n \r\n \r\n def max_length(self, num_list): \r\n if len(num_list) == 1:\r\n return 0\r\n else:\r\n if num_list[0] == num_list[1]:\r\n return (1+ self.max_length(num_list[1:]))\r\n else:\r\n return self.max_length(num_list[1:])\r\n \r\n def more_element(self, num_list):\r\n list0 = num_list-1\r\n num_plus_one = len(num_list) - np.count_nonzero(list0) \r\n list1 = num_list+1\r\n num_minus_one = len(num_list) - np.count_nonzero(list1) \r\n if num_plus_one > num_minus_one:\r\n return 1\r\n else:\r\n return -1\r\n \r\n \r\n def opposite_move_random(self):\r\n # the opposite moves randomly\r\n valid_move = self.get_valid_moves()\r\n opposite_move = int(np.random.choice(valid_move))\r\n self.update_borad(opposite_move, player = -1)\r\n win_lose = self.check()\r\n if win_lose == 1: #win\r\n reward = 1\r\n self.done = True\r\n elif win_lose == -1: #lose\r\n reward = -1\r\n self.done = True\r\n else:\r\n reward = 0 \r\n print(self.board)\r\n return self.board, reward\r\n \r\n def update_borad(self, column, player):\r\n for n in range(6):\r\n if self.board[column][n] == 0:\r\n raw = n\r\n break\r\n self.board[column][raw] = player\r\n \r\n def get_valid_moves(self): \r\n valid = []\r\n for i in range(7):\r\n if 0 in self.board[i]:\r\n valid.append(i)\r\n return valid\r\n \r\n def first_player(self): \r\n random_num = np.random.rand()\r\n if random_num > 0.5:\r\n return 1\r\n else:\r\n return -1\r\n \r\n def show_board(self):\r\n print(self.board)\r\n \r\n","sub_path":"GameEnv.py","file_name":"GameEnv.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"205819626","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass ClphonescraperSpider(scrapy.Spider):\n name = 'CLphonescraper'\n allowed_domains = ['losangeles.craigslist.org/d/cell-phones/search/moa']\n start_urls = ['https://losangeles.craigslist.org/d/cell-phones/search/moa/']\n\n def parse(self, response):\n #Extracting the content using css selectors\n titles = response.xpath('//a[@class=\"result-title hdrlnk\"]/text()').extract()\n prices = response.css('.result-price::text').extract()\n locations = response.css('.result-hood::text').extract()\n dates = response.css('time::attr(title)').extract()\n links = response.css(\"a::attr(href)\").extract()\n \n #Give the extracted content row wise\n for item in zip(titles, prices, locations, dates, links):\n #create a dictionary to store the scraped info\n scraped_info = {\n 'title' : item[0],\n 'prices' : item[1],\n 'locations' : item[2],\n 'dates' : item[3],\n 'links' : item[4]\n }\n\n #yield or give the scraped info to scrapy\n yield scraped_info\n","sub_path":"spiders/CLphonescraper.py","file_name":"CLphonescraper.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"171453946","text":"\nimport inspect\nimport os\n\nimport shutil\nimport tempfile\n\nfrom os.path import abspath, basename, dirname, exists, join, splitext\n\nfrom ..robotpy import installer\n\n\ndef relpath(path):\n '''Path helper, gives you a path relative to this file'''\n return os.path.normpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), path))\n \nclass PyFrcDeploy:\n \"\"\"\n Uploads your robot code to the robot and executes it immediately\n \"\"\"\n \n def __init__(self, parser):\n ''' :type parser: argparse.ArgumentParser '''\n parser.add_argument('--skip-tests', action='store_true', default=False,\n help=\"If specified, don't run tests before uploading code to robot (DANGEROUS)\")\n \n parser.add_argument('--debug', action='store_true', default=False,\n help=\"If specified, runs the code in debug mode (which only currently enables verbose logging)\")\n \n parser.add_argument('--nonstandard', action='store_true', default=False,\n help=\"When specified, allows you to deploy code in a file that isn't called robot.py\")\n \n def run(self, options, robot_class, **static_options):\n \n from .. import config\n config.mode = 'upload'\n \n # run the test suite before uploading\n if not options.skip_tests:\n from .cli_test import PyFrcTest\n \n tester = PyFrcTest()\n \n retval = tester.run_test([], robot_class, ignore_missing_test=True)\n if retval != 0:\n print(\"Your robot tests failed, aborting upload. Use --skip-tests if you want to upload anyways\")\n return retval\n \n # upload all files in the robot.py source directory\n robot_file = abspath(inspect.getfile(robot_class))\n robot_path = dirname(robot_file)\n robot_filename = basename(robot_file)\n cfg_filename = join(robot_path, '.deploy_cfg')\n \n if not options.nonstandard and robot_filename != 'robot.py':\n print(\"ERROR: Your robot code must be in a file called robot.py (launched from %s)!\" % robot_filename)\n print()\n print(\"If you really want to do this, then specify the --nonstandard argument\")\n return 1\n \n # This probably should be configurable... oh well\n \n deploy_dir = '/home/lvuser'\n py_deploy_dir = '%s/py' % deploy_dir\n \n if options.debug:\n deployed_cmd = '/usr/local/frc/bin/netconsole-host /usr/local/bin/python3 %s/%s -v run' % (py_deploy_dir, robot_filename) \n deployed_cmd_fname = 'robotDebugCommand'\n extra_cmd = 'touch /tmp/frcdebug; chown lvuser:ni /tmp/frcdebug'\n else:\n deployed_cmd = '/usr/local/frc/bin/netconsole-host /usr/local/bin/python3 -O %s/%s run' % (py_deploy_dir, robot_filename)\n deployed_cmd_fname = 'robotCommand'\n extra_cmd = ''\n \n sshcmd = \"/bin/bash -ce '\" + \\\n '[ -d %(py_deploy_dir)s ] && rm -rf %(py_deploy_dir)s; ' + \\\n 'echo \"%(cmd)s\" > %(deploy_dir)s/%(cmd_fname)s; ' + \\\n '%(extra_cmd)s' + \\\n \"'\"\n \n sshcmd %= {\n 'deploy_dir': deploy_dir,\n 'py_deploy_dir': py_deploy_dir,\n 'cmd': deployed_cmd,\n 'cmd_fname': deployed_cmd_fname,\n 'extra_cmd': extra_cmd\n }\n \n try:\n controller = installer.SshController(cfg_filename)\n \n # Housekeeping first\n controller.ssh(sshcmd) \n \n # Copy the files over, copy to a temporary directory first\n # -> this is inefficient, but it's easier in sftp\n tmp_dir = tempfile.mkdtemp()\n py_tmp_dir = join(tmp_dir, 'py')\n \n try:\n self._copy_to_tmpdir(py_tmp_dir, robot_path)\n controller.sftp(py_tmp_dir, deploy_dir)\n finally:\n shutil.rmtree(tmp_dir)\n \n # Restart the robot code and we're done!\n sshcmd = \"/bin/bash -ce '\" + \\\n '. /etc/profile.d/natinst-path.sh; ' + \\\n 'chown -R lvuser:ni %s; ' + \\\n '/usr/local/frc/bin/frcKillRobot.sh -t -r' + \\\n \"'\"\n \n sshcmd %= (py_deploy_dir)\n \n controller.ssh(sshcmd)\n controller.close()\n \n except installer.Error as e:\n print(\"ERROR: %s\" % e)\n return 1\n \n return 0\n\n def _copy_to_tmpdir(self, tmp_dir, robot_path):\n \n upload_files = []\n \n for root, dirs, files in os.walk(robot_path):\n \n prefix = root[len(robot_path)+1:]\n os.mkdir(join(tmp_dir, prefix))\n \n # skip .svn, .git, .hg, etc directories\n for d in dirs[:]:\n if d.startswith('.') or d == '__pycache__':\n dirs.remove(d)\n \n # skip .pyc files\n for filename in files:\n \n r, ext = splitext(filename)\n if ext == 'pyc' or r.startswith('.'):\n continue\n \n shutil.copy(join(root, filename), join(tmp_dir, prefix, filename))\n \n return upload_files\n","sub_path":"lib/pyfrc/mains/cli_deploy.py","file_name":"cli_deploy.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"199776661","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom PIL import Image\r\nfrom pylab import *\r\nimport cv2 as cv\r\n# 添加中文字体支持\r\nfrom matplotlib.font_manager import FontProperties\r\nfont = FontProperties(fname=r\"c:\\windows\\fonts\\SimSun.ttc\", size=14)\r\nfigure()\r\n# 显示原图\r\nMy_img = Image.open(\"DDD.jpg\")\r\n#print(My_img.mode,My_img.size.My_img.format)\r\nsubplot(231)\r\ntitle(u'原图', fontproperties=font)\r\naxis('off')\r\nimshow(My_img)\r\n#imshow(My_img)\r\n#My_img.convert('L')\r\n#imshow(My_img.convert('L'))\r\n#My_img.thumbnail((128,128))\r\n#imshow(smallimg)\r\n#subplot(231)\r\n'''box = (50,50,300,300)\r\nregion = My_img.crop(box)\r\nimshow(region)\r\n'''\r\n#显示灰度图\r\ngray()\r\nLimg=My_img.convert('L')\r\nsubplot(232)\r\ntitle(u'灰度图', fontproperties=font)\r\naxis('off')\r\nimshow(Limg)\r\n\r\n#复制并粘贴区域\r\nsubplot(233)\r\ndox = (50,50,150,150)\r\nregion = My_img.crop(dox)\r\nNewregion = region.transpose(Image.ROTATE_180)\r\nMy_img.paste(Newregion,dox)\r\ntitle(u'复制贴图',fontproperties=font)\r\naxis('off')\r\nimshow(My_img)\r\n\r\n#略缩图\r\nsubplot(234)\r\nMy_img = Image.open(\"DDD.jpg\")\r\nsize = 128,128\r\nMy_img.thumbnail(size)\r\ntitle(u'缩略图', fontproperties=font)\r\naxis('off')\r\nimshow(My_img)\r\n\r\n#调整图像尺寸\r\nsubplot(235)\r\nMy_img = Image.open(\"DDD.jpg\")\r\nsize = 64,128\r\nMy_img = My_img.resize(size)\r\ntitle(u'缩放图',fontproperties = font)\r\naxis('off')\r\nimshow(My_img)\r\n\r\n#旋转图像45度\r\nMy_img = Image.open(\"DDD.jpg\")\r\nsubplot(236)\r\nMy_img = My_img.rotate(45)\r\ntitle(u'旋转45度',fontproperties=font)\r\naxis('off')\r\nimshow(My_img)\r\n\r\nshow()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"june10th_imgprocessing.py","file_name":"june10th_imgprocessing.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"295369517","text":"import math\nfrom typing import List, Optional, Tuple\n\nimport parameters\nfrom world.simulated_world import SimulatedWorld\n\n\nclass Ledge(SimulatedWorld):\n opposite_player = {\n 1: 2,\n 2: 1\n }\n\n def __init__(self, state: Optional[Tuple[int, ...]] = None):\n self.__size = parameters.SIZE\n self.__action_space = parameters.NUMBER_OF_ACTIONS\n self.reset(state)\n\n def reset(self, state: Optional[Tuple[int, ...]] = None) -> Tuple[int, ...]:\n if state is None:\n self.__player_id = 1\n self.__board = list(parameters.LEDGE_BOARD)\n else:\n self.__player_id, *self.__board = list(state)\n return self.__get_state()\n\n def is_final_state(self) -> bool:\n return 2 not in self.__board\n\n def get_winner_id(self) -> int:\n if self.is_final_state():\n return Ledge.opposite_player[self.__player_id]\n else:\n return 0\n\n def step(self, action: int) -> Tuple[Tuple[int, ...], int]:\n coin_position, landing_position = self.index_to_tuple(action)\n if landing_position >= 0:\n self.__board[landing_position], self.__board[coin_position] = self.__board[coin_position], 0\n else:\n self.__board[coin_position] = 0\n self.__player_id = Ledge.opposite_player[self.__player_id]\n return self.__get_state(), self.get_winner_id()\n\n def get_legal_actions(self) -> Tuple[int, ...]:\n legal_actions = []\n for action in range(self.__action_space):\n legal_actions.append(int(self.__is_legal_action(self.__board, self.index_to_tuple(action))))\n return tuple(legal_actions)\n\n def __get_state(self) -> Tuple[int, ...]:\n return (self.__player_id, *self.__board)\n\n def generate_state(self, action: int) -> Tuple[int, ...]:\n coin_position, landing_position = self.index_to_tuple(action)\n board = list(self.__board)\n if landing_position >= 0:\n board[landing_position], board[coin_position] = board[coin_position], 0\n else:\n board[coin_position] = 0\n return (self.__player_id, *board)\n\n def __is_legal_action(self, board: List[int], action: Tuple[int, int]) -> bool:\n coin_position, landing_position = action\n if board[coin_position] == 0:\n return False\n if coin_position < landing_position:\n return False\n if coin_position == 0:\n return True\n if sum(board[landing_position:coin_position]) > 0:\n return False\n return True\n\n def index_to_tuple(self, index: int) -> Tuple[int, int]:\n coin_position = math.ceil((math.sqrt(8 * index + 1) - 1) / 2)\n landing_position = index - int(coin_position * (coin_position - 1) / 2) - 1 # index % coin_position (also works, might be cheaper)\n return (coin_position, landing_position)\n","sub_path":"src/world/ledge.py","file_name":"ledge.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"484139805","text":"#!/usr/bin/python3\nfrom sys import stdin, stdout\n\ndef findWinner (a, b, d):\n for m in d:\n a -= m\n b -= m\n if a < 0:\n if b < 0: return \"Tie\\n\"\n return \"Sayan Won\\n\"\n if b < 0: return \"Raghu Won\\n\"\n return \"Tie\\n\"\n\ndef main ():\n read = stdin.readline\n write = stdout.write\n t = int (read ())\n for t_ in range (t):\n a, b, n = map (int, read ().split ())\n d = sorted (map (int, read ().split ()))\n write (findWinner (a, b, d))\n\nif __name__ == \"__main__\": main ()","sub_path":"_raghu_vs_sayan.py","file_name":"_raghu_vs_sayan.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"8683056","text":"\"\"\" Internal utilities. \"\"\"\n\n\ndef reverse_path(start, end, prev):\n \"\"\" Returns the path from start to end, given a previous table. \"\"\"\n path = []\n while end != start:\n path.append(end)\n end = prev[end]\n path.append(start)\n path.reverse()\n return path\n","sub_path":"generic_paths/_common.py","file_name":"_common.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"581819961","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of hepcrawl.\n# Copyright (C) 2016, 2017 CERN.\n#\n# hepcrawl is a free software; you can redistribute it and/or modify it\n# under the terms of the Revised BSD License; see LICENSE file for\n# more details.\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pytest\n\nfrom hepcrawl.spiders import mit_spider\n\nfrom hepcrawl.testlib.fixtures import (\n fake_response_from_file,\n fake_response_from_string,\n get_node,\n)\n\n\n@pytest.fixture\ndef record():\n \"\"\"Return scraping results from the MIT spider.\"\"\"\n spider = mit_spider.MITSpider()\n response = fake_response_from_file('mit/test_splash.html')\n\n parsed_item = spider.build_item(response)\n assert parsed_item\n assert parsed_item.record\n\n return parsed_item.record\n\n\n@pytest.fixture\ndef parsed_node():\n \"\"\"Call parse_node and return its request call.\"\"\"\n spider = mit_spider.MITSpider()\n response = fake_response_from_file('mit/test_list.html')\n tag = spider.itertag\n node = get_node(spider, tag, response, rtype=\"html\")\n\n parsed_item = spider.parse_node(response, node).next()\n assert parsed_item\n\n return parsed_item\n\n\ndef test_url(parsed_node):\n \"\"\"Test url is correct.\"\"\"\n url = 'http://dspace.mit.edu/handle/1721.1/99280?show=full'\n assert parsed_node.url == url\n\n\ndef test_title(record):\n \"\"\"Test title.\"\"\"\n assert record[\n \"title\"] == u'Theoretical investigation of energy alignment at metal/semiconductor interfaces for solar photovoltaic applications'\n\n\ndef test_abstract(record):\n \"\"\"Test abstract.\"\"\"\n assert record[\"abstract\"] == (\n \"Our work was inspired by the need to improve the efficiency of new \"\n \"types of solar cells. We mainly focus on metal-semiconductor \"\n \"interfaces. In the CdSe study, we find that not all surface states \"\n \"serve to pin the Fermi energy. In our organic-metal work, we explore \"\n \"the complexity and challenges of modeling these systems. For example, \"\n \"we confirm that aromatic compounds indeed have stronger interactions \"\n \"with metal surfaces, but this may lead to the geometry changing as a \"\n \"result of the interaction. We also find that molecules that are not \"\n \"rigid are strongly affected by their neighboring molecules. Surface \"\n \"roughness will have an effect on molecules that more strongly bind to \"\n \"metal surfaces. This study of interfaces relates to one part of the \"\n \"picture of efficiency, but we also look at trying to go beyond the \"\n \"Shockley-Quiesser limit. We explore the idea of combining a direct and \"\n \"indirect bandgap in a single material but find that, in quasi-\"\n \"equilibrium, this does no better than just the direct gap material. \"\n \"This thesis hopes to extend our understanding of metal-semiconductor \"\n \"interface behavior and lead to improvements in photovoltaic efficiency \"\n \"in the future.\"\n )\n\n\ndef test_authors(record):\n \"\"\"Test authors.\"\"\"\n authors = [\"Tomasik, Michelle Ruth\"]\n affiliation = \"Massachusetts Institute of Technology. Department of Physics.\"\n\n assert 'authors' in record\n assert len(record['authors']) == len(authors)\n\n # here we are making sure order is kept\n for index, name in enumerate(authors):\n assert record['authors'][index]['full_name'] == name\n assert affiliation in [\n aff['value'] for aff in record['authors'][index]['affiliations']\n ]\n\n\ndef test_date_published(record):\n \"\"\"Test date published.\"\"\"\n assert record[\"date_published\"] == \"2015\"\n\n\ndef test_files(record):\n \"\"\"Test pdf files.\"\"\"\n assert record[\"additional_files\"][0][\"url\"] == \"http://dspace.mit.edu/bitstream/handle/1721.1/99287/922886248-MIT.pdf?sequence=1\"\n\n\ndef test_thesis(record):\n \"\"\"Test thesis information.\"\"\"\n assert record[\"thesis\"][\"date\"] == '2015'\n assert record[\"thesis\"][\"institutions\"][0][\"name\"] == 'Massachusetts Institute of Technology'\n\n\ndef test_thesis_supervisor(record):\n \"\"\"Test thesis supervisor.\"\"\"\n assert record[\"thesis_supervisor\"][0][\"full_name\"] == u'Grossman, Jeffrey C.'\n\n\ndef test_page_nr(record):\n \"\"\"Test page numbers.\"\"\"\n assert record[\"page_nr\"] == [\"124\"]\n\n\n@pytest.fixture\ndef non_thesis():\n \"\"\"Return a heprecord for a Master's thesis (should be None as we don't\n want them).\"\"\"\n spider = mit_spider.MITSpider()\n body = \"\"\"\n \n \n \n dc.description.degree\n M.Sc.\n en_US\n \n \n \n \"\"\"\n response = fake_response_from_string(body)\n return spider.build_item(response)\n\n\ndef test_non_thesis(non_thesis):\n \"\"\"Test MSc thesis skipping.\"\"\"\n assert non_thesis is None\n\n\n@pytest.fixture\ndef supervisors():\n \"\"\"Response from a record with multiple supervisors.\"\"\"\n spider = mit_spider.MITSpider()\n body = \"\"\"\n \n \n \n dc.contributor.advisor\n Seth Lloyd and J.D. Joannopoulos\n en_US\n \n \n \n \"\"\"\n response = fake_response_from_string(body)\n\n parsed_item = spider.build_item(response)\n assert parsed_item\n assert parsed_item.record\n\n return parsed_item.record\n\n\ndef test_two_supervisors(supervisors):\n \"\"\"Test what happens when there are two supervisors.\"\"\"\n assert supervisors\n assert supervisors[\"thesis_supervisor\"][0][\"full_name\"] == u'Lloyd, Seth'\n assert supervisors[\"thesis_supervisor\"][1][\"full_name\"] == u'Joannopoulos, J.D.'\n","sub_path":"tests/unit/test_mit.py","file_name":"test_mit.py","file_ext":"py","file_size_in_byte":5816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"453428928","text":"#coding=utf-8\nimport sys\nsys.path.append(\"../lib/\")\nfrom head_lib import *\nfrom process_feature import process_feature\n\n\ndef main():\n pf=process_feature()\n train_df=pf.process_train(\"train.csv\")\n all_feature = train_df.filter(regex='Age_.*|SibSp|Parch|Fare_.*|Cabin_.*|Embarked_.*|Sex_.*|Pclass_.*')\n X = all_feature.as_matrix()\n all_label=train_df['Survived']\n y = all_label.as_matrix()\n\n\n \"\"\"\n grid search\n \"\"\"\n\n param_test1={\n\n \"learning_rate\":np.arange(0.01,1,0.02),\n\n\n\n }\n\n\n estimator=XGBClassifier(learning_rate =0.1,n_estimators=140,max_depth=7,min_child_weight=1,\n gamma=0,subsample=0.8,colsample_bytree=0.8,objective= 'binary:logistic', nthread=4, \n scale_pos_weight=1,seed=27)\n\n \"\"\"\n param_test1={\n \"n_estimators\":np.arange(1,8,1),\n\n }\n estimator=RandomForestClassifier()\n \"\"\"\n \"\"\"\n param_test1={\n \"max_iter\":np.arange(1,20,1)\n\n }\n estimator = linear_model.LogisticRegression(C=1.0, penalty='l1')\n \"\"\"\n clf= my_grid_search(estimator,X,y, param_grid = param_test1,scoring='roc_auc',n_jobs=4,iid=True,cv=10)\n\n \nif __name__==\"__main__\":\n main()","sub_path":"taitannike/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"217668994","text":"\"\"\"This script creates Stampifier which pipelines all internal modules\"\"\"\n\nimport logging\n\nfrom classification.classifier_main import Classifier\nfrom data_models.stampifier_output import StampifierOutput\nfrom data_models.website import Website\nfrom error import InvalidUrlError, WebsiteNotStampifiableError\nfrom extraction.extractor import Extractor\nfrom stamp_generation.stamp_generator import StampGenerator\nfrom summarization.extractor_output_preprocessor import \\\n ExtractorOutputPreprocessor\nfrom summarization.summarizer_main import Summarizer\n\nLOGGER = logging.getLogger()\nLOG_FILENAME = 'website.log'\nlogging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)\n\n\nclass Stampifier:\n \"\"\"Creates class for stampification\"\"\"\n\n def __init__(self, url, max_pages):\n self.url = url\n self.max_pages = max_pages\n self._website = Website(self.url)\n self.is_stampifiable = False\n self.stampified_pages = None\n\n def stampify(self):\n \"\"\"Starts the stampification process\"\"\"\n\n if not self._website.is_valid:\n raise InvalidUrlError(self._website.url)\n\n return self.__convert_website_to_stamp()\n\n def __convert_website_to_stamp(self):\n \"\"\"This method is the pipeline between all the modules\"\"\"\n\n _extractor = Extractor(self._website.url)\n self._website.set_contents(_extractor.extract_html())\n\n LOGGER.debug(self._website.convert_to_dict())\n\n _classifier_and_summarizer_response = self.get_stampified_content()\n\n if not _classifier_and_summarizer_response[\"is_stampifiable\"]:\n raise WebsiteNotStampifiableError(\n message=\"Website cannot be stampified!\",\n failure_source=\"Summarizer\")\n\n generated_stamp \\\n = StampGenerator(self._website,\n _classifier_and_summarizer_response[\"stamp_pages\"]\n ).stamp_html\n\n LOGGER.debug(generated_stamp)\n\n return StampifierOutput(generated_stamp,\n self._website.get_title())\n\n def _preprocess_contents(self):\n '''\n This method will use ExtractorOutputPreprocessor\n to split the contents into different types\n '''\n output_preprocessor \\\n = ExtractorOutputPreprocessor(self._website.contents)\n self.preprocessed_contents_dict \\\n = output_preprocessor.get_preprocessed_content_lists()\n self.title_text_contents \\\n = self.preprocessed_contents_dict[\"titles\"]\n self.normal_text_contents \\\n = self.preprocessed_contents_dict[\"sentences\"]\n self.media_contents = self.preprocessed_contents_dict[\"media\"]\n self.embedded_contents \\\n = self.preprocessed_contents_dict[\"embedded_content\"]\n\n def get_stampified_content(self):\n ''' returns the list of stamp pages'''\n # pre-process the contents first\n self._preprocess_contents()\n\n # classify the page as stampifiable or not\n self._classify()\n\n # early return when the pages are not\n # stampifiable\n if not self.is_stampifiable:\n return {\n \"is_stampifiable\": self.is_stampifiable,\n \"stamp_pages\": None\n }\n\n # summarize\n self._summarize()\n # order the stamp pages\n self._order_stamp_pages()\n\n return {\n \"is_stampifiable\": self.is_stampifiable,\n \"stamp_pages\": self.stampified_pages\n }\n\n def _classify(self):\n classifier = Classifier(\n normal_text_contents=self.normal_text_contents,\n title_text_contents=self.title_text_contents,\n media_contents=self.media_contents,\n embedded_contents=self.embedded_contents,\n max_pages=self.max_pages\n )\n self.is_stampifiable = classifier.is_page_stampifiable()\n\n def _summarize(self):\n summarizer = Summarizer(\n self.title_text_contents,\n self.normal_text_contents,\n self.media_contents,\n self.embedded_contents,\n self.max_pages\n )\n\n self.stampified_pages = summarizer.get_summarized_content()\n\n def _get_min_index_for_stamp_page(self, stamp_page):\n if stamp_page.para_index != -1:\n return stamp_page.get_weighted_text_index()\n\n if stamp_page.media_index != -1:\n return stamp_page.media_index\n\n def _order_stamp_pages(self):\n # separate this as function so\n # logic can be amended to include\n # more information if necessary\n self.stampified_pages.stamp_pages.sort(\n key=self._get_min_index_for_stamp_page)\n","sub_path":"stampifier.py","file_name":"stampifier.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"495933584","text":"import cv2\nimport numpy as np\n\nfrom prototype.vision.feature2d.fast import FAST\nfrom prototype.vision.feature2d.keypoint import KeyPoint\nfrom prototype.vision.feature2d.feature_track import FeatureTrack\n\n\nclass LKFeatureTracker:\n \"\"\"Lucas-Kanade Feature Tracker\"\"\"\n\n def __init__(self, **kwargs):\n \"\"\" Constructor\n\n Args:\n\n detector : FAST\n Feature detector\n\n \"\"\"\n self.frame_id = 0\n self.detector = kwargs.get(\"detector\", FAST(threshold=2))\n\n self.track_id = 0\n self.tracks = {}\n self.tracks_tracking = []\n\n self.frame_prev = None\n self.kp_cur = None\n self.kp_ref = None\n self.min_nb_features = 100\n\n def detect(self, frame):\n \"\"\"Detect features\n\n Detects and initializes feature tracks\n\n Parameters\n ----------\n frame_id : int\n Frame id\n frame : np.array\n Frame\n\n \"\"\"\n for kp in self.detector.detect_keypoints(frame):\n track = FeatureTrack(self.track_id, self.frame_id, kp)\n self.tracks[self.track_id] = track\n self.tracks_tracking.append(self.track_id)\n self.track_id += 1\n\n def last_keypoints(self):\n \"\"\"Returns previously tracked features\n\n Returns\n -------\n\n KeyPoints as a numpy array of shape (N, 2), where N is the number\n of keypoints\n\n \"\"\"\n keypoints = []\n for track_id in self.tracks_tracking:\n keypoints.append(self.tracks[track_id].last().pt)\n\n return np.array(keypoints, dtype=np.float32)\n\n def track_features(self, image_ref, image_cur):\n \"\"\"Track Features\n\n Parameters\n ----------\n image_ref : np.array\n Reference image\n image_cur : np.array\n Current image\n\n \"\"\"\n # Re-detect new feature points if too few\n if len(self.tracks_tracking) < self.min_nb_features:\n self.tracks_tracking = [] # reset alive feature tracks\n self.detect(image_ref)\n\n # LK parameters\n win_size = (21, 21)\n max_level = 2\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.03)\n\n # Convert reference keypoints to numpy array\n self.kp_ref = self.last_keypoints()\n\n # Perform LK tracking\n lk_params = {\"winSize\": win_size,\n \"maxLevel\": max_level,\n \"criteria\": criteria}\n self.kp_cur, statuses, err = cv2.calcOpticalFlowPyrLK(image_ref,\n image_cur,\n self.kp_ref,\n None,\n **lk_params)\n\n # Filter out bad matches (choose only good keypoints)\n status = statuses.reshape(statuses.shape[0])\n still_alive = []\n for i in range(len(status)):\n if status[i] == 1:\n track_id = self.tracks_tracking[i]\n still_alive.append(track_id)\n kp = KeyPoint(self.kp_cur[i], 0)\n self.tracks[track_id].update(self.frame_id, kp)\n\n self.tracks_tracking = still_alive\n\n def draw_tracks(self, frame, debug=False):\n \"\"\"Draw tracks\n\n Parameters\n ----------\n frame : np.array\n Image frame\n debug : bool\n Debug mode (Default value = False)\n\n \"\"\"\n if debug is False:\n return\n\n # Create a mask image and color for drawing purposes\n mask = np.zeros_like(frame)\n color = [0, 0, 255]\n\n # Draw tracks\n for i, (new, old) in enumerate(zip(self.kp_cur, self.kp_ref)):\n a, b = new.ravel()\n c, d = old.ravel()\n mask = cv2.line(mask, (a, b), (c, d), color, 1)\n img = cv2.add(frame, mask)\n cv2.imshow(\"Feature Tracks\", img)\n\n def update(self, frame, debug=False):\n \"\"\"Update\n\n Parameters\n ----------\n frame : np.array\n Image frame\n debug : bool\n Debug mode (Default value = False)\n\n Returns\n -------\n\n \"\"\"\n if self.frame_id > 0: # Update\n self.track_features(self.frame_prev, frame)\n self.draw_tracks(frame, debug)\n\n elif self.frame_id == 0: # Initialize\n self.detect(frame)\n\n # Keep track of current frame\n self.frame_prev = frame\n self.frame_id += 1\n","sub_path":"prototype/vision/feature2d/lk_tracker.py","file_name":"lk_tracker.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"287111131","text":"#Harry Derouich\r\n#19/09/14\r\n#Circumference calculation exercise\r\n\r\nimport math\r\n\r\nprint(\"Hello user\")\r\nradius = int(input(\"Please enter the radius of the circle in centimetres: \"))\r\n\r\ncircum = 2 * math.pi * radius\r\narea = math.pi * radius**2\r\n\r\ncircum_round = round(circum, 2)\r\narea_round = round(area, 2)\r\n\r\nprint(\"The circumference is {0}cm, and the area is {1}cm squared\".format(circum_round, area_round))\r\n","sub_path":"Circle calcs.py","file_name":"Circle calcs.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"372882751","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport math\n\ndef ncr(n,c):\n last = math.factorial(n) / (math.factorial(c) * math.factorial(n-c))\n return last\n\ndef ncr2(n,c,p):\n last = math.factorial(n) / (math.factorial(c) * math.factorial(n - c))\n second = math.pow(p, c) * math.pow((1 - p), (n - c))\n final = last * second\n return final\n\np = 0.89\ntotal = 0\nfor i in range(15,20):\n sum = ncr2(20,i,p)\n total += sum\n\nprint(total)\nprint(ncr2(20,20,0.89))\n\naa = (ncr(4,2)*ncr(3,2)) / ncr(11,4)\nprint(aa)\n\nprint(ncr(4,0)+ncr(5,1)+ncr(6,2)+ncr(7,3)+ncr(8,4)+ncr(9,5))\n\nprint(ncr(7,4)*math.pow((4/7),4)*math.pow((3/7),3)*0.5)","sub_path":"untitled/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"274214498","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'chan_gami'\nSITENAME = 'chan_memo'\nSITEURL = 'http://changami.github.io'\n\nPATH = 'content'\nARTICLE_PATHS = ['blog']\nARTICLE_SAVE_AS = '{date:%Y}/{date:%m}/{slug}.html'\nARTICLE_URL = '{date:%Y}/{date:%m}/{slug}.html'\n\nSTATIC_PATHS = ['images', 'extra/CNAME']\nEXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}\n\nDEFAULT_LANG = 'ja'\nTIMEZONE = 'America/Vancouver'\nDATE_FORMATS = {\n 'en': '%a, %d %b %Y',\n 'ja': '%Y-%m-%d(%a)',\n}\n\nTHEME = './vendor/nest'\nSITESUBTITLE = u'chan_memo'\n\nMENUITEMS = [('Categories', '/categories.html')]\n\n# index.html\nNEST_INDEX_HEAD_TITLE = u'Homepage'\nNEST_INDEX_HEADER_TITLE = u'ちゃんがみのメモ'\nNEST_INDEX_HEADER_SUBTITLE = u'chan_gami\\'s memoirs as a passionate core gamer.'\nNEST_INDEX_CONTENT_TITLE = u'Latest Posts'\nNEST_HEADER_IMAGES = 'background.jpg'\nNEST_HEADER_LOGO = '/images/icon.png'\n# archives.html\nNEST_ARCHIVES_HEAD_TITLE = u'Archives'\nNEST_ARCHIVES_HEAD_DESCRIPTION = u'Posts Archives'\nNEST_ARCHIVES_HEADER_TITLE = u'Archives'\nNEST_ARCHIVES_HEADER_SUBTITLE = u'Archives for all posts'\nNEST_ARCHIVES_CONTENT_TITLE = u'Archives'\n# article.html\nNEST_ARTICLE_HEADER_BY = u'By'\nNEST_ARTICLE_HEADER_MODIFIED = u'modified'\nNEST_ARTICLE_HEADER_IN = u'in category'\n# author.html\nNEST_AUTHOR_HEAD_TITLE = u'Posts by'\nNEST_AUTHOR_HEAD_DESCRIPTION = u'Posts by'\nNEST_AUTHOR_HEADER_SUBTITLE = u'Posts archives'\nNEST_AUTHOR_CONTENT_TITLE = u'Posts'\n# authors.html\nNEST_AUTHORS_HEAD_TITLE = u'Author list'\nNEST_AUTHORS_HEAD_DESCRIPTION = u'Author list'\nNEST_AUTHORS_HEADER_TITLE = u'Author list'\nNEST_AUTHORS_HEADER_SUBTITLE = u'Archives listed by author'\n# categories.html\nNEST_CATEGORIES_HEAD_TITLE = u'Categories'\nNEST_CATEGORIES_HEAD_DESCRIPTION = u'Archives listed by category'\nNEST_CATEGORIES_HEADER_TITLE = u'Categories'\nNEST_CATEGORIES_HEADER_SUBTITLE = u'Archives listed by category'\n# category.html\nNEST_CATEGORY_HEAD_TITLE = u'Category Archive'\nNEST_CATEGORY_HEAD_DESCRIPTION = u'Category Archive'\nNEST_CATEGORY_HEADER_TITLE = u'Category'\nNEST_CATEGORY_HEADER_SUBTITLE = u'Category Archive'\n# pagination.html\nNEST_PAGINATION_PREVIOUS = u'Previous'\nNEST_PAGINATION_NEXT = u'Next'\n# period_archives.html\nNEST_PERIOD_ARCHIVES_HEAD_TITLE = u'Archives for'\nNEST_PERIOD_ARCHIVES_HEAD_DESCRIPTION = u'Archives for'\nNEST_PERIOD_ARCHIVES_HEADER_TITLE = u'Archives'\nNEST_PERIOD_ARCHIVES_HEADER_SUBTITLE = u'Archives for'\nNEST_PERIOD_ARCHIVES_CONTENT_TITLE = u'Archives for'\n# tag.html\nNEST_TAG_HEAD_TITLE = u'Tag archives'\nNEST_TAG_HEAD_DESCRIPTION = u'Tag archives'\nNEST_TAG_HEADER_TITLE = u'Tag'\nNEST_TAG_HEADER_SUBTITLE = u'Tag archives'\n# tags.html\nNEST_TAGS_HEAD_TITLE = u'Tags'\nNEST_TAGS_HEAD_DESCRIPTION = u'Tags List'\nNEST_TAGS_HEADER_TITLE = u'Tags'\nNEST_TAGS_HEADER_SUBTITLE = u'Tags List'\nNEST_TAGS_CONTENT_TITLE = u'Tags List'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nFEED_ALL_RSS = 'feeds/all.rss.xml'\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Blogroll\nNEST_SITEMAP_COLUMN_TITLE = u'Sitemap'\nNEST_SITEMAP_MENU = [('Archives', '/archives.html'),\n ('Tags', '/tags.html'),\n ('Authors', '/authors.html')]\nNEST_COPYRIGHT = u'© chan_gami 2015'\n\n# Link widget\nNEST_LINKS_COLUMN_TITLE = u'Links'\nLINKS = (('Pelican', 'http://getpelican.com/'),\n ('Python.org', 'http://python.org/'),\n ('Jinja2', 'http://jinja.pocoo.org/'),)\n\n# Social widget\nNEST_SOCIAL_COLUMN_TITLE = u'Social'\nSOCIAL = (('GitHub', 'https://github.com/changami'),\n ('Twitter', 'https://twitter.com/chan_gami'),)\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = False\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"195393624","text":"import math\nimport os\nimport time\nimport tempfile\nfrom termcolor import colored\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nimport config\nfrom function_generator_chained_gru import lstmnet_chain\nimport gen_data\n\nGENERATE_DATA = False\n\ndef main():\n\n # Create checkpoint+checkpoint_path\n if not os.path.exists(config.checkpoint_path):\n os.makedirs(config.checkpoint_path)\n\n # Create training data.\n if GENERATE_DATA or not os.path.exists(config.data_tmp_folder):\n if not os.path.exists(config.data_tmp_folder):\n os.makedirs(config.data_tmp_folder)\n print(\"Generating Data CSV\")\n # List of lambdas: [lambda x: math.sin(x)]\n gen_data.gen_function_vals_csv(-50, -50 + (config.epoch_size + config.test_epoch_size + config.sequence_length)*0.02, 0.02, lambda x: math.sin(x),\n config.data_tmp_folder + 'sine.csv')\n gen_data.gen_function_vals_csv(-50, -50 + (config.epoch_size + config.test_epoch_size + config.sequence_length)*0.02, 0.02, lambda x: 0.4*x+1,\n config.data_tmp_folder + 'lin.csv')\n\n print(\"Reading Data from CSV\")\n sine_x, data_sine = gen_data.read_function_vals_csv('x', 'y', config.data_tmp_folder + 'sine.csv')\n # sine_x: [TOTAL_LENGTH, 1]\n # data_sine: [TOTAL_LENGTH, 1]\n lin_x, data_lin = gen_data.read_function_vals_csv('x', 'y', config.data_tmp_folder + 'lin.csv')\n # lin_x: [TOTAL_LENGTH, 1]\n # data_lin: [TOTAL_LENGTH, 1]\n\n print(\"Writing TFRecords\")\n datasequences = np.concatenate([data_sine, data_lin], 1)\n # datasequences: [ TOTAL_LENGTH, DIMENSION ]\n\n functionsequences, controlvals = gen_data.all_sequences_from_datasequence(datasequences, config.sequence_length, config.chain_size, config.link_size)\n # functionsequences: [ TOTAL_SEQUENCE_NUM, SEQUENCE_LENGTH, DIMENSION ]\n # controlvals: [ TOTAL_SEQUENCE_NUM, CHAIN_SIZE, DIMENSION ]\n # Set apart some test data\n test_functionsequences, test_controlvals = gen_data.rand_sequences_from_datasequences(functionsequences, controlvals, config.test_epoch_size, True)\n # test_functionsequences: [ TEST_EPOCH_SIZE, SEQUENCE_LENGTH, DIMENSION ]\n # test_controlvals: [ TEST_EPOCH_SIZE, CHAIN_SIZE, DIMENSION ]\n # functionsequences: [ SEQUENCE_NUM, SEQUENCE_LENGTH, DIMENSION ]\n # controlvals: [ SEQUENCE_NUM, CHAIN_SIZE, DIMENSION ]\n\n gen_data.function_sequences_to_tfrecord(functionsequences, controlvals, config.data_tmp_folder+config.data_tfrecord_filename)\n gen_data.function_sequences_to_tfrecord(test_functionsequences, test_controlvals, config.data_tmp_folder+config.test_tfrecord_filename)\n\n print(\"Configuring Input Queue\")\n with tf.name_scope('Input_Queue') as scope:\n\n data_queue = tf.train.string_input_producer([config.data_tmp_folder + config.data_tfrecord_filename])\n test_queue = tf.train.string_input_producer([config.data_tmp_folder + config.test_tfrecord_filename])\n sequences_batch, labels_batch = gen_data.read_and_decode(data_queue, config.batch_size, config.sequence_length, config.chain_size, config.dimension, config.shuffle_capacity, config.shuffle_threads, config.shuffle_min_after_dequeue)\n test_sequences_batch, test_labels_batch = gen_data.read_and_decode(test_queue, config.batch_size, config.sequence_length, config.chain_size, config.dimension, config.shuffle_capacity, config.shuffle_threads, config.shuffle_min_after_dequeue)\n\n # Global Step Counter\n with tf.name_scope('Global_Step') as scope:\n global_step = tf.Variable(0, trainable=False, name='Global_Step_Var')\n increment_global_step_op = tf.assign(global_step, global_step + 1)\n\n # Create model\n print(\"Creating Model\")\n\n # Model\n Hin = np.zeros([config.batch_size, config.hidden_layer_size *\n config.hidden_layer_depth], dtype=np.float32)\n # Hin: [ BATCH_SIZE, INTERNALSIZE * NLAYERS ]\n\n train_H, train_keep, train_step, train_summary_op = lstmnet_chain(sequences_batch, labels_batch, global_step, \"Train\", False)\n test_H, test_keep, test_step, test_summary_op = lstmnet_chain(test_sequences_batch, test_labels_batch, global_step, \"Test\", True)\n\n # Setup logging with Tensorboard\n print(\"Setup Tensorboard\")\n timestamp = str(math.trunc(time.time()))\n graph_location = \"log\" + tempfile.mkdtemp()\n print(colored(' Saving graph to: ' + graph_location, 'red'))\n writer = tf.summary.FileWriter(graph_location, graph=tf.get_default_graph())\n saver = tf.train.Saver()\n\n # Limit used gpu memory.\n print(\"Configuring Tensorflow\")\n tfconfig = tf.ConfigProto()\n tfconfig.gpu_options.per_process_gpu_memory_fraction = 0.25\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n\n # train model.\n with tf.Session(config=tfconfig) as sess:\n print(\"Setup\")\n sess.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n\n print(\"Training\")\n for step in range(config.iters):\n\n if step % config.summary_iters == 0: # summary step\n _, training_summary, test_summary = sess.run([train_step, train_summary_op, test_summary_op],\n feed_dict={train_keep: config.pkeep, train_H: Hin,\n test_keep: 1.0, test_H: Hin})\n\n saver.save(sess, config.checkpoint_path)\n writer.add_summary(training_summary, step)\n writer.add_summary(test_summary, step)\n else:\n _ = sess.run([train_step], feed_dict={train_keep: config.pkeep, train_H: Hin})\n\n # Increment global step Counter\n # sess.run(increment_global_step_op)\n\n coord.request_stop()\n coord.join(threads)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"function_generator_chained_gru/train_function_chained_generator.py","file_name":"train_function_chained_generator.py","file_ext":"py","file_size_in_byte":6078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"118964453","text":"\"\"\"\nA simple selenium test example written by python\n\"\"\"\n\nimport unittest\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import NoSuchElementException\n\nclass TestTemplate(unittest.TestCase):\n \"\"\"Include test cases on a given url\"\"\"\n\n def setUp(self):\n \"\"\"Start web driver\"\"\"\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--no-sandbox')\n # chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--disable-dev-shm-usage')\n chrome_options.add_argument(\"--window-size=1920,1080\")\n self.driver = webdriver.Chrome(options=chrome_options)\n self.driver.implicitly_wait(10)\n\n def tearDown(self):\n \"\"\"Stop web self.driver\"\"\"\n self.driver.quit()\n\n def test_case_1(self):\n \"\"\"Find and click top-left logo button\"\"\"\n try:\n self.driver.get('https://www.naver.com')\n time.sleep(1)\n\n login_button = self.driver.find_element_by_class_name('ico_naver')\n login_button.click()\n\n id_input = self.driver.find_element_by_name('id')\n pw_input = self.driver.find_element_by_name('pw')\n\n id_input.clear()\n time.sleep(1)\n\n import pyperclip\n id_input.click()\n pyperclip.copy('id')\n id_input.send_keys(Keys.CONTROL, 'v')\n time.sleep(1)\n\n pw_input.click()\n pyperclip.copy('pw')\n pw_input.send_keys(Keys.CONTROL, 'v')\n time.sleep(1)\n\n login_button2 = self.driver.find_element_by_id('log.login')\n login_button2.click()\n\n from bs4 import BeautifulSoup\n\n self.driver.get('https://order.pay.naver.com/home')\n html = self.driver.page_source\n bsObj = BeautifulSoup(html, 'html.parser')\n print(bsObj)\n except NoSuchElementException as ex:\n self.fail(ex.msg)\n\n # def test_case_2(self):\n # \"\"\"Find and click top-right Start your project button\"\"\"\n # try:\n # self.driver.get('https://www.oursky.com/')\n # el = self.driver.find_element_by_class_name(\"header__cta\")\n # el.click()\n # except NoSuchElementException as ex:\n # self.fail(ex.msg)\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TestTemplate)\n unittest.TextTestRunner(verbosity=2).run(suite)","sub_path":"Python/WebCrawling/day4/seleniumPart/seleniumEx03_.py","file_name":"seleniumEx03_.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"165552865","text":"import os\r\nimport cv2\r\nimport numpy as np\r\nfrom sklearn import decomposition\r\nimport tensorflow as tf\r\nfrom sklearn import preprocessing\r\n\r\ncorel_path= 'G:/PyCharm/Lunwen3/W_corel'\r\ncorel_name=os.listdir(corel_path)\r\n\r\n#############################################数据导入#########################################\r\ndef corel_read(corel_path):\r\n imgs = []\r\n for file in corel_name:\r\n img = cv2.imread(corel_path + \"/\" + file)[:, :, ::-1]\r\n imgs.append(img)\r\n imgs = np.array(imgs, dtype=float)\r\n return imgs\r\n\r\n###############################################################cut_data#############################################################\r\ndef divide_method3(data, m, n): # 分割成m行n列\r\n\r\n h, w = data.shape[0], data.shape[1]\r\n grid_h = int(h * 1.0 / (m - 1) + 0.5)\r\n grid_w = int(w * 1.0 / (n - 1) + 0.5)\r\n h = grid_h * (m - 1)\r\n w = grid_w * (n - 1)\r\n data=data[0:h,0:w]\r\n gx, gy = np.meshgrid(np.linspace(0, w, n), np.linspace(0, h, m))\r\n gx = gx.astype(np.int)\r\n gy = gy.astype(np.int)\r\n New_data = np.zeros([m - 1, n - 1, grid_h, grid_w, data.shape[2]],np.uint8) # 这是一个五维的张量,前面两维表示分块后图像的位置(第m行,第n列)\r\n\r\n for i in range(m - 1):\r\n for j in range(n - 1):\r\n New_data[i, j, ...] = data[gy[i][j]:gy[i + 1][j + 1], gx[i][j]:gx[i + 1][j + 1], :]\r\n\r\n return New_data\r\n\r\n\r\ndef cut_feature(datas,cut_size1,cut_size2):\r\n cut_datas=[]\r\n for i in range(len(datas)):\r\n cut_data=divide_method3(datas[i],cut_size1,cut_size2)\r\n cut_datas.append(cut_data)\r\n\r\n return cut_datas\r\n\r\n#############################################################PCA_feature##############################################################\r\ndef pca_feature(datas,ksize,number):\r\n ksize1=ksize\r\n ksize2=ksize\r\n datas = np.array(datas)\r\n filter_number=datas.shape[5]\r\n news = []\r\n for i in range(datas.shape[0]):\r\n for j in range(datas.shape[1]):\r\n for k in range(datas.shape[2]):\r\n new1 = datas[i, j, k, :, :, :]\r\n news.append(new1) # 去前三维,只保留卷积核大小和通道数,现在news是四维\r\n\r\n news=np.array(news)\r\n news=news.transpose((3,1,2,0))\r\n Ws=[]\r\n for i in range(news.shape[0]):\r\n new2=news[i]\r\n new2=new2.reshape((ksize1*ksize2,-1))\r\n pca = decomposition.PCA(n_components=number, copy=True, whiten=False)\r\n W=pca.fit_transform(new2)\r\n W=W.reshape((-1,1))\r\n Ws.append(W)\r\n\r\n Ws=np.array(Ws)\r\n Ws=Ws.reshape((filter_number,ksize1,ksize2,-1))\r\n Ws=Ws.transpose((3,1,2,0))\r\n\r\n return Ws\r\n\r\n#################################################################################################################\r\ndef PCA_feature(datas,number,cut_size1,cut_size2,ksize,pca_number,save_number):\r\n datas=np.array(datas)\r\n array_size=int(datas.shape[0]/number)\r\n ws=[]\r\n for i in range(number):\r\n cut=cut_feature(datas[i*array_size:(i+1)*array_size,:,:],cut_size1,cut_size2)\r\n w=pca_feature(cut,ksize,pca_number)\r\n w=w.reshape((1,-1))\r\n ws.append(w)\r\n ws=np.array(ws)\r\n ws=ws.reshape((pca_number*number,ksize,ksize,-1))\r\n ws=ws[0:save_number,:,:,:]\r\n\r\n return ws\r\n\r\n###########################################################任意单次卷积####################################################################\r\ndef myconv(datas,kernels):\r\n kernels = kernels.transpose((1, 2, 3, 0))\r\n feature_imgs = tf.nn.conv2d(datas, kernels, strides=[1, 1, 1, 1], padding='SAME')\r\n feature_imgs = tf.nn.relu(feature_imgs)\r\n feature_imgs = tf.nn.max_pool(value=feature_imgs,\r\n ksize=[1, 2, 2, 1],\r\n strides=[1, 1, 1, 1],\r\n padding='SAME')\r\n sess = tf.Session()\r\n sess.run(tf.global_variables_initializer())\r\n feature_imgs = feature_imgs.eval(session=sess)\r\n\r\n return feature_imgs\r\n\r\n#########################################################归一化########################################################\r\ndef z_score(W):\r\n W=np.array(W)\r\n W_shape=W.shape\r\n W=W.reshape((-1, 1))\r\n W = preprocessing.minmax_scale(W, feature_range=(0, 1), axis=0, copy=True)\r\n W=W.reshape((W_shape))\r\n\r\n return W\r\n\r\n###########################################################测试cifar-10##########################################################\r\n#第一层权重与第一个特征图\r\ncorel_data=corel_read(corel_path)\r\nW1=PCA_feature(corel_data, 1, 52, 77, 5, 6, 6)\r\n# W1=z_score(W1)\r\nfeature1_imgs=myconv(corel_data, W1)\r\n\r\n#第二层权重与第二个特征图\r\nW2=PCA_feature(feature1_imgs,10,86,129,3,4,32)\r\n# W2=z_score(W2)\r\nfeature2_imgs=myconv(feature1_imgs,W2)\r\n\r\n#第三层权重与第三个特征图\r\nW3=PCA_feature(feature2_imgs,20,86,129,3,4,64)\r\n# W3=z_score(W3)\r\n#\r\nnp.save(r\"G:\\PyCharm\\Lunwen3\\Ws_PCA_corel\\W1.npy\", W1)\r\nnp.save(r\"G:\\PyCharm\\Lunwen3\\Ws_PCA_corel\\W2.npy\", W2)\r\nnp.save(r\"G:\\PyCharm\\Lunwen3\\Ws_PCA_corel\\W3.npy\", W3)\r\n\r\n#6,32,64\r\n","sub_path":"8_Me_paper_two/PCA_Corel_W.py","file_name":"PCA_Corel_W.py","file_ext":"py","file_size_in_byte":5110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"193254297","text":"from scipy.stats import norm\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\n\ntf.logging.set_verbosity(tf.logging.INFO)\ndata_folder = \"./data/\"\nmodels_folder = \"./models/\"\n# tf.get_logger().setLevel(\"INFO\")\n# Read in the dataset created by \"create_dataset.py\".\ndf = pd.read_csv(data_folder + \"data.csv\")\ndataset_size_original = len(df.index)\n\n# Declare the columns we are interested in.\n# columns = [\"old_terrain_source\", \"old_terrain_target\", \"old_hp_source\", \"old_attack_source\", \"old_defence_source\",\n# \"old_hp_target\", \"old_attack_target\", \"old_defence_target\", \"new_hp_source\", \"new_hp_target\"]\n\n# The input features.\nfeature_names = [\"old_terrain_source\", \"old_terrain_target\", \"old_hp_source\", \"old_attack_source\", \"old_defence_source\",\n \"old_hp_target\", \"old_attack_target\", \"old_defence_target\"]\n\n# What we want to predict.\nclassification_output_features = [\"result\"]\nregression_output_features = [\"new_hp_source\", \"new_hp_target\"]\n\n# Discard rows that start the action with 0 hp.\ndf = df.loc[(df[\"old_hp_source\"] > 0.0) & (df[\"old_hp_target\"] > 0.0)]\n\n# We now shuffle the data\ndf = df.sample(frac=1, random_state=190561673).reset_index(drop=True)\n\n# Split the data into train, eval, and test sets with 80/10/10 split.\ndataset_size_filtered = len(df.index)\ntrain_end = int(dataset_size_filtered * 0.8)\nvalidation_end = train_end + int(dataset_size_filtered * 0.1)\n\ntrain_frame = df.loc[:train_end].reset_index(drop=True)\nX_train = train_frame.loc[:, feature_names]\ny_train_classification = train_frame.loc[:, classification_output_features]\ny_train_regression = train_frame.loc[:, regression_output_features]\nvalidation_frame = df.loc[train_end:validation_end].reset_index(drop=True)\nX_eval = validation_frame.loc[:, feature_names]\ny_eval_classification = validation_frame.loc[:, classification_output_features]\ny_eval_regression = validation_frame.loc[:, regression_output_features]\ntest_frame = df.loc[validation_end:].reset_index(drop=True)\nprint(len(df.index))\n# Free memory.\ndel df\n\n# Write the resulting sets to CSV files.\ntrain_frame.to_csv(data_folder + 'train.csv', index=False)\nvalidation_frame.to_csv(data_folder + 'validation.csv', index=False)\ntest_frame.to_csv(data_folder + 'test.csv', index=False)\n\n# We normalize the data so we have a normal distribution around 0 and a standard deviation of 1. We do not normalize\n# the data directly, we just save the parameters for normalization and let our Estimator features perform normalization.\nname_to_normalization = {}\n\nfor column in train_frame:\n mu, sigma = norm.fit(train_frame[column])\n min_value = train_frame[column].min()\n max_value = train_frame[column].max()\n name_to_normalization[column] = {\"mu\": mu, \"sigma\": sigma, \"min\": min_value, \"max\": max_value}\n\n\n# Estimators need an input_fn for training and validation,this is the function that will provide the Tensorflow nodes\n# for the input.\ndef make_input_fn(data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):\n def input_function():\n ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df))\n if shuffle:\n ds = ds.shuffle(1024)\n ds = ds.batch(batch_size).repeat(num_epochs)\n return ds\n\n return input_function\n\n\ntrain_input_fn_classification = make_input_fn(X_train, y_train_classification)\ntrain_input_fn_regression = make_input_fn(X_train, y_train_regression)\neval_input_fn_classification = make_input_fn(X_eval, y_eval_classification, num_epochs=1, shuffle=False)\neval_input_fn_regression = make_input_fn(X_eval, y_eval_regression, num_epochs=1, shuffle=False)\n\n\n# train_input_fn = tf.estimator.inputs.pandas_input_fn(X_train, y_train, batch_size=8, num_epochs=100, shuffle=True)\n# eval_input_fn = tf.estimator.inputs.pandas_input_fn(X_eval, y_eval, batch_size=8, num_epochs=1, shuffle=False)\n\n\n# Now we need to define for our Estimators what the input_fn delivers and how to treat / preprocess it.\ndef build_normalizer_fn(feature_name, normalization):\n def normalizer_fn(tensor):\n with tf.name_scope(feature_name + '_normalize'):\n clipped = tf.clip_by_value(tensor, normalization[\"min\"], normalization[\"max\"])\n return (clipped - normalization[\"mu\"]) / normalization[\"sigma\"]\n\n return normalizer_fn\n\n\n# Terrain type needs no normalization.\nfeature_columns = [tf.feature_column.numeric_column('old_terrain_source'),\n tf.feature_column.numeric_column('old_terrain_target')]\n# Append all other feature columns with appropriate normalization.\nfor feature_name in feature_names[2:]:\n feature_columns.append(tf.feature_column.numeric_column(\n feature_name,\n normalizer_fn=build_normalizer_fn(feature_name, name_to_normalization[feature_name])\n ))\nprint(feature_columns)\n\n# # Linear regression using a pre-built estimator.\n# linear_regressor = tf.estimator.LinearRegressor(feature_columns=feature_columns)\n# linear_regressor.train(train_input_fn)\n# result = linear_regressor.evaluate(eval_input_fn)\n# print(result)\n\n# Regression using Neural Network.\ndnn_regressor = tf.estimator.DNNRegressor(feature_columns=feature_columns, label_dimension=2, hidden_units=[128, 64, 32])\ndnn_regressor.train(train_input_fn_regression)\n\n\n# # Classification using Linear Classifier.\n# linear_classifier = tf.estimator.LinearClassifier(feature_columns=feature_columns, n_classes=3)\n# linear_classifier.train(train_input_fn)\n# result = linear_classifier.evaluate(eval_input_fn)\n# print(result)\n\n# # Classification using Neural Network.\n# dnn_classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns, n_classes=3, hidden_units=[256, 128, 64])\n# dnn_classifier.train(train_input_fn_classification)\n\n# Evaluate Regressor.\nresult = dnn_regressor.evaluate(eval_input_fn_regression)\nprint(result)\n\n# # Evaluate Classifier.\n# result = dnn_classifier.evaluate(eval_input_fn_classification)\n# print(result)\n\n\n# # Export as a Saved Model so that we can load it from the Tensorflow Java Library.\n# feature_spec = {\"old_terrain_source\": tf.placeholder(tf.string, shape=[None], name=\"old_terrain_source\"),\n# \"old_terrain_target\": tf.placeholder(tf.string, shape=[None], name=\"old_terrain_target\")}\n#\n# for feature_name in feature_names:\n# feature_spec[feature_name] = tf.placeholder(tf.float32, shape=[None], name=feature_name)\n#\n# serving_input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(feature_spec)\n# dnn_regressor.export_saved_model(\"./models/regressor\", serving_input_fn)\n# dnn_classifier.export_saved_model(\"./models/classifier\", serving_input_fn)\n\n# def build_input_fn(file_path, perform_shuffle=False, epochs=1, batch_size=32):\n# def decode_csv(line_tensor):\n# \"\"\"Builds nodes that process one line of CSV. The input is *not*\n# a string, but a tensor providing the strings when the graph is run.\n# We do not parse anything here but build a subgraph that will do the parsing.\"\"\"\n# parsed_line_tensors = tf.io.decode_csv(line_tensor, [[\"\"],\n# [0.], [0.], [0.], [0.], [0.],\n# [0.], [0.], [0.], [0.]], name='csv_parser')\n# # Last element is the label\n# label = parsed_line_tensors[-1:]\n# # remove label from list\n# del parsed_line_tensors[-1]\n# # Everything remaining are the features\n# features = parsed_line_tensors[1:]\n# features_and_label = (dict(zip(feature_names, features)), label)\n# print(features_and_label)\n# return features_and_label\n#\n# # build a dataset that uses the helper function to parse the input\n# dataset = (\n# # Create a dataset based on a text file.\n# tf.data.TextLineDataset(file_path)\n# # Skip header row.\n# .skip(1)\n# # Transform each elem by inserting the result of decode_csv.\n# .map(decode_csv)\n# )\n#\n# if perform_shuffle:\n# # Randomizes input using a window of 1024 elements (those are read into memory).\n# dataset = dataset.shuffle(buffer_size=1024)\n#\n# dataset = (dataset\n# # Repeats dataset this many times.\n# .repeat(epochs)\n# # Batch size to use.\n# .batch(batch_size)\n# )\n#\n# # Now return a function that uses a reference to our dataset\n# # to provide new data on each call.\n# def input_fn():\n# iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)\n# batch_features, batch_labels = iterator.get_next()\n# return batch_features, batch_labels\n#\n# return input_fn\n","sub_path":"py/learning_FMs/forward_model_attack.py","file_name":"forward_model_attack.py","file_ext":"py","file_size_in_byte":8595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"447082768","text":"import socket\nimport msgpack\nimport struct\n\nfrom socket import MSG_PEEK\n\nfrom _enum import Enum\n\n\"\"\"\nserverside abstr over app layer for sending/recving game events\n\"\"\"\n\n\"\"\"\nnestable pseudo-dictionarish thing which uses attrs instead of keys,\nsorta similar to how our custom _enum.Enum works only not with ints\n\nused here to sort opcodes/errors by context and client/server\n\"\"\"\nclass _OpEnum():\n def __init__(self, **items):\n for key, item in items.items():\n if key.startswith('_'):\n raise ValueError(\"_OpEnum keys may not start with '_'\")\n\n setattr(self, key, item)\n\"\"\"\ndef and name ALL the ops and error codes our entire API uses\n\"\"\"\nOPS = _OpEnum(\n LOBBY=_OpEnum(\n CLIENT=Enum(\n 'ERROR',\n 'KICK',\n 'JOINED',\n 'READY',\n ),\n\n SERVER=Enum(\n 'JOIN',\n 'ACK',\n )\n ),\n\n GAME=_OpEnum(\n CLIENT=Enum(\n 'START',\n ),\n\n SERVER=Enum(\n\n )\n )\n)\n\nERR = _OpEnum(\n LOBBY=_OpEnum(\n CLIENT=Enum(\n 'DENY',\n 'FULL',\n 'ALREADY_JOINED',\n 'INVALID_PASSWORD',\n 'ALIAS_EMPTY',\n 'ALIAS_IN_USE',\n )\n ),\n\n GAME=_OpEnum(\n CLIENT=Enum(\n\n )\n )\n)\n\n\"\"\"\nsocket wrapper to read and write packed \"messages\" in the format (opcode, *op_args)\nuse nearly identically to socket obj\n\"\"\"\nclass Messenger():\n def __init__(self, sock):\n self.sock = sock\n self._expected = 0\n self._buffered = []\n\n def fileno(self):\n return self.sock.fileno()\n\n def send(self, opcode, *args):\n payload = msgpack.packb((opcode,) + args)\n\n # prepend length header and ship\n self.sock.send(struct.pack('!I', len(payload)) + payload)\n\n # receive any waiting data and return complete message if any, None otherwise\n def recv(self):\n if self._expected == 0:\n # peek for length header. if present, consume it and set expected payload size\n if len(self.sock.recv(4, MSG_PEEK)) == 4:\n self._expected = struct.unpack(\"!I\", self.sock.recv(4))[0]\n else:\n # receive up to expected waiting data and decrement expected by amount received.\n # if expected is decremented to zero in this way, flush the internal buffer and return the unpacked message\n data = self.sock.recv(self._expected)\n self._expected -= len(data)\n self._buffered.append(data)\n\n if self._expected == 0:\n message = msgpack.unpackb(b''.join(self._buffered), raw=False)\n self._buffered = []\n\n return message\n\n return None\n\n","sub_path":"server/src/_api.py","file_name":"_api.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"515245599","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport pandas as pd\n\nstyle.use('ggplot')\n\nclass K_Means:\n\tdef __init__(self, k =3, tolerance = 0.0001, max_iterations = 500):\n\t\tself.k = k\n\t\tself.tolerance = tolerance\n\t\tself.max_iterations = max_iterations\n\n\tdef fit(self, data):\n\n\t\tself.centroids = {}\n\n\t\t#initialize the centroids center at random k elements\n\t\tcent = np.random.choice(range(len(data)),len(data), replace=False)\n\t\tfor i in range(self.k):\n\t\t\tself.centroids[i] = data[cent[i]]\n\n\t\t#begin iterations\n\t\tfor i in range(self.max_iterations):\n\t\t\tself.classes = {}\n\t\t\tfor i in range(self.k):\n\t\t\t\tself.classes[i] = []\n\n\t\t\t#find the distance between the point and cluster; choose the nearest centroid\n\t\t\tfor coordinate in data:\n\t\t\t\tdistances = [np.linalg.norm(coordinate - self.centroids[centroid]) for centroid in self.centroids]\n\t\t\t\tclassification = distances.index(min(distances))\n\t\t\t\tself.classes[classification].append(coordinate)\n\n\t\t\tprevious = dict(self.centroids)\n\n\t\t\t#average the cluster datapoints to re-calculate the centroids\n\t\t\tfor classification in self.classes:\n\t\t\t\tself.centroids[classification] = np.average(self.classes[classification], axis = 0)\n\n\t\t\tisOptimal = True\n\n\t\t\tfor centroid in self.centroids:\n\n\t\t\t\toriginal_centroid = previous[centroid]\n\t\t\t\tcurr = self.centroids[centroid]\n\n\t\t\t\t# check the centroids don't change their positions more than our tolerance\n\t\t\t\tif np.sum((curr - original_centroid)/original_centroid * 100.0) > self.tolerance:\n\t\t\t\t\tisOptimal = False\n\n\t\t\t#break out of the main loop if the results are optimal\n\t\t\tif isOptimal:\n\t\t\t\tbreak\n\n\tdef pred(self, data):\n\t\tdistances = [np.linalg.norm(data - self.centroids[centroid]) for centroid in self.centroids]\n\t\tclassification = distances.index(min(distances))\n\t\treturn classification\n\ndef main():\n\n\tdf = pd.read_csv(r\"./data/ipl.csv\")\n\tdf = df[['one', 'two']]\n\tdataset = df.astype(float).values.tolist()\n\n\tX = df.values #returns a numpy array\n\n\tkm = K_Means(3)\n\tkm.fit(X)\n\n\t# Plotting starts here\n\tcolors = 10*[\"r\", \"g\", \"c\", \"b\", \"k\"]\n\n\tfor centroid in km.centroids:\n\t\tplt.scatter(km.centroids[centroid][0], km.centroids[centroid][1], s = 130, marker = \"x\")\n\n\tfor classification in km.classes:\n\t\tcolor = colors[classification]\n\t\tfor coordinate in km.classes[classification]:\n\t\t\tplt.scatter(coordinate[0], coordinate[1], color = color,s = 30)\n\n\tplt.show()\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"k_means.py","file_name":"k_means.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"356281138","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if root is None:\n return []\n def helper(cur_res, tree_root, height):\n if tree_root is None:\n return\n if height >= len(cur_res):\n cur_res.append([])\n cur_res[height].append(tree_root.val)\n helper(cur_res, tree_root.left, height+1)\n helper(cur_res, tree_root.right, height + 1)\n\n res = [[]]\n helper(res, root, 0)\n return res\n\n\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.left.left = TreeNode(3)\n root.left.left.left = TreeNode(4)\n root.left.left.left.left = TreeNode(5)\n print(sol.levelOrder(root))\n","sub_path":"lc_102.py","file_name":"lc_102.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"428045635","text":"#!/usr/bin/python3\n\"\"\"\n\nClass Student that defines a student by: (based on 11-student.py)\n\n\"\"\"\n\n\nclass Student:\n \"\"\"Class Student that defines a student by: (based on 11-student.py)\"\"\"\n\n def __init__(self, first_name, last_name, age):\n \"\"\"Initializes the data\n Args:\n first_name (str): firstname\n last_name (str): lastname\n age (int): age\n \"\"\"\n self.first_name = first_name\n self.last_name = last_name\n self.age = age\n\n def to_json(self, attrs=None):\n \"\"\"Retrieves a dictionary representation of a Student instance\n (same as 10-class_to_json.py)\n Args:\n attrs (str): a list of strings\n \"\"\"\n if attrs is None:\n return self.__dict__\n new = {}\n for attrib in attrs:\n if attrib in self.__dict__:\n new[attrib] = self.__dict__[attrib]\n return(new)\n","sub_path":"0x0B-python-input_output/12-student.py","file_name":"12-student.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"252687733","text":"import pybullet as p\r\nimport time\r\nimport pybullet_data\r\n\r\nphysicsClient=p.connect(p.GUI)\r\np.setAdditionalSearchPath(pybullet_data.getDataPath())\r\np.setGravity(0,0,-10)\r\nplaneID=p.loadURDF(\"plane.urdf\")\r\nstart_pos=[0,0,3]\r\nstart_orient=p.getQuaternionFromEuler([0,0,0])\r\ncubeIDs=[]\r\n\r\nfor i in range(6):\r\n cubeIDs.append(p.loadURDF(\"cube_small.urdf\",start_pos,start_orient,useFixedBase=True))\r\n start_pos[1]+=0.11 #kept 1.11 so that the spheres can also be kept at such a distance\r\n\r\nsphere_startpos=[0,0,1]\r\nsphereIDs=[]\r\n\r\nfor i in range(6):\r\n sphereIDs.append(p.loadURDF(\"sphere.urdf\",sphere_startpos,start_orient))\r\n p.changeDynamics(sphereIDs[i],-1,restitution=0.999) #using ChangeDynamics to make the restitution of the ball = 1 \r\n sphere_startpos[1]+=0.11 #the spheres were kept a little bit apart so that collisions can occur as two body collisions\r\n\r\nfor i in range(6):\r\n p.createConstraint(cubeIDs[i],-1,sphereIDs[i],-1,p.JOINT_POINT2POINT,[0,0,1],[0,0,0],[0,0,2]) #constraints between the cube and the spheres\r\n\r\nsphere_pos,sphere_orient=p.getBasePositionAndOrientation(sphereIDs[0])\r\n\r\nwhile sphere_pos[2]<1.3:\r\n p.applyExternalForce(sphereIDs[0],-1,[0,-150,0],[0,0,0],p.LINK_FRAME) #moving the initial sphere upto a particular height using external force\r\n p.stepSimulation()\r\n sphere_pos,sphere_orient=p.getBasePositionAndOrientation(sphereIDs[0])\r\n time.sleep(1/100)\r\nwhile True:\r\n p.stepSimulation()\r\n time.sleep(1/100)\r\np.disconnect()","sub_path":"Part2/Subpart 3/SOLUTION/Subpart3_Task2.py","file_name":"Subpart3_Task2.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"508052713","text":"# Copyright 1999-2018 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport uuid\nimport weakref\n\nimport numpy as np\nimport gevent\nfrom numpy.testing import assert_array_equal\n\nfrom mars.actors import create_actor_pool\nfrom mars.compat import six\nfrom mars.utils import get_next_port, serialize_graph\nfrom mars.cluster_info import ClusterInfoActor\nfrom mars.scheduler.kvstore import KVStoreActor\nfrom mars.worker.tests.base import WorkerCase\nfrom mars.worker import *\nfrom mars.worker.utils import WorkerActor\n\n\nclass ExecuteTestActor(WorkerActor):\n def __init__(self):\n super(ExecuteTestActor, self).__init__()\n self._exc_info = None\n self._finished = False\n\n def run_test(self):\n import mars.tensor as mt\n from mars.tensor.expressions.datasource import TensorOnes, TensorFetchChunk\n arr = mt.ones((10, 8), chunks=10)\n arr_add = mt.ones((10, 8), chunks=10)\n arr2 = arr + arr_add\n graph = arr2.build_graph(compose=False, tiled=True)\n\n for chunk in graph:\n if isinstance(chunk.op, TensorOnes):\n chunk._op = TensorFetchChunk(\n dtype=chunk.dtype, _outputs=[weakref.ref(o) for o in chunk.op.outputs],\n _key=chunk.op.key)\n\n session_id = str(uuid.uuid4())\n op_key = str(uuid.uuid4())\n\n self._kv_store.write('/sessions/%s/operands/%s/execution_graph'\n % (session_id, op_key), serialize_graph(graph))\n chunk_holder_ref = self.promise_ref(ChunkHolderActor.default_name())\n\n refs = self._chunk_store.put(session_id, arr.chunks[0].key, np.ones((10, 8), dtype=np.int16))\n chunk_holder_ref.register_chunk(session_id, arr.chunks[0].key)\n del refs\n\n refs = self._chunk_store.put(session_id, arr_add.chunks[0].key, np.ones((10, 8), dtype=np.int16))\n chunk_holder_ref.register_chunk(session_id, arr_add.chunks[0].key)\n del refs\n\n executor_ref = self.promise_ref(ExecutionActor.default_name())\n\n def _validate(_):\n data = self._chunk_store.get(session_id, arr2.chunks[0].key)\n assert_array_equal(data, 2 * np.ones((10, 8)))\n\n executor_ref.execute_graph(session_id, str(id(graph)), serialize_graph(graph),\n dict(chunks=[arr2.chunks[0].key]), None, _promise=True) \\\n .then(_validate) \\\n .catch(lambda *exc: setattr(self, '_exc_info', exc)) \\\n .then(lambda *_: setattr(self, '_finished', True))\n\n def get_exc_info(self):\n return self._finished, self._exc_info\n\n\nclass Test(WorkerCase):\n def testExecute(self):\n pool_address = '127.0.0.1:%d' % get_next_port()\n with create_actor_pool(n_process=1, backend='gevent', address=pool_address) as pool:\n pool.create_actor(ClusterInfoActor, schedulers=[pool_address],\n uid=ClusterInfoActor.default_name())\n cache_ref = pool.create_actor(ChunkHolderActor, self.plasma_storage_size,\n uid=ChunkHolderActor.default_name())\n pool.create_actor(KVStoreActor, uid=KVStoreActor.default_name())\n pool.create_actor(DispatchActor, uid=DispatchActor.default_name())\n pool.create_actor(QuotaActor, 1024 * 1024, uid=MemQuotaActor.default_name())\n pool.create_actor(CpuCalcActor)\n pool.create_actor(ExecutionActor, uid=ExecutionActor.default_name())\n\n try:\n test_ref = pool.create_actor(ExecuteTestActor)\n test_ref.run_test()\n while not test_ref.get_exc_info()[0]:\n gevent.sleep(0.1)\n exc_info = test_ref.get_exc_info()[1]\n if exc_info:\n six.reraise(*exc_info)\n finally:\n pool.destroy_actor(cache_ref)\n","sub_path":"mars/worker/tests/test_execution.py","file_name":"test_execution.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"164737671","text":"import logging\nimport logging.config\nimport logging.handlers\nimport os\nimport sys\n\nimport coloredlogs\n\n\nclass IOCLogger(object):\n def __init__(self):\n self.cli_logger = logging.getLogger(\"iocage\")\n self.log_file = os.environ.get(\"IOCAGE_LOGFILE\", \"/var/log/iocage.log\")\n\n default_logging = {\n 'version' : 1,\n 'disable_existing_loggers': False,\n 'formatters' : {\n 'log': {\n 'format' : '%(asctime)s (%(levelname)s) %(message)s',\n 'datefmt': '%Y/%m/%d %H:%M:%S',\n },\n },\n 'handlers' : {\n 'file': {\n 'level' : 'DEBUG',\n 'class' : 'logging.handlers.RotatingFileHandler',\n 'filename' : f'{self.log_file}',\n 'mode' : 'a',\n 'maxBytes' : 10485760,\n 'backupCount': 5,\n 'encoding' : 'utf-8',\n 'formatter' : 'log',\n },\n },\n 'loggers' : {\n '': {\n 'handlers' : ['file'],\n 'level' : 'DEBUG',\n 'propagate': True\n },\n },\n }\n\n cli_colors = {\n 'info' : {'color': 'white'},\n 'notice' : {'color': 'magenta'},\n 'verbose' : {'color': 'blue'},\n 'spam' : {'color': 'green'},\n 'critical': {'color': 'red', 'bold': True},\n 'error' : {'color': 'red'},\n 'debug' : {'color': 'green'},\n 'warning' : {'color': 'yellow'}\n }\n\n if os.geteuid() == 0:\n logging.config.dictConfig(default_logging)\n\n coloredlogs.install(level=\"INFO\", logger=self.cli_logger,\n fmt=\"%(message)s\",\n stream=sys.stdout, level_styles=cli_colors)\n\n def cli_log(self):\n return self.cli_logger\n","sub_path":"iocage/lib/ioc_logger.py","file_name":"ioc_logger.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"619939596","text":"import os, time\nimport pandas as pd\nfrom selenium import webdriver\n\n# initialization values\nhow_long_second_you_wait = 10\nwhat_period_button_you_click = '1Y' # you must choose one only among (1D, 1M, 6M, 1Y).\ndownload_subpath = 'C:\\\\Users\\\\20160169\\\\Downloads\\\\'\ndownloaded_csv_file_path = download_subpath + 'data.csv'\nprint('initialzation values loaded.')\n\n# initialize\ndriver = webdriver.Chrome('C:\\\\chromedriver.exe')\ndriver.get('https://marketdata.krx.co.kr/mdi#document=040312')\ndriver.implicitly_wait(how_long_second_you_wait)\nprint('initialzation completed.')\n\n# set up the inputs.\nwhat_period_button_you_click = what_period_button_you_click.upper()\nif what_period_button_you_click == '1D':\n oneDayBtn = driver.find_element_by_class_name('cal-btn-range1d').click()\nelif what_period_button_you_click == '1M':\n oneMonthBtn = driver.find_element_by_class_name('cal-btn-range1m').click()\nelif what_period_button_you_click == '6M':\n sixMonthBtn = driver.find_element_by_class_name('cal-btn-range6m').click()\nelif what_period_button_you_click == '1Y':\n oneYearBtn = driver.find_element_by_class_name('cal-btn-range1y').click()\nelse:\n print('You did not write among (1D, 1M, 6M, 1Y).')\n exit(1)\nprint('period button clicked.')\n\n# click the search button.\ndriver.find_element_by_class_name('btn-board').click()\nprint('search button clicked.')\n\ntry:\n # click the csv file download button.\n driver.find_element_by_xpath('//*[@id=\"1679091c5a880faf6fb5e6087eb1b2dc\"]/button[3]').click()\n print('csv file download button clicked.')\n\n # wait for downloading.\n remainedTime = how_long_second_you_wait\n while 'data.csv' not in os.listdir(download_subpath): # wait for the csv file to be downloaded completely.\n time.sleep(1)\n remainedTime -= 1\n if remainedTime == 0:\n print('\\ncsv file download has failed. : TimeoutError raised!!!\\n')\n raise TimeoutError\nexcept TimeoutError as TOE:\n print(TOE)\n # click the csv file download button.\n driver.find_element_by_xpath('//*[@id=\"1679091c5a880faf6fb5e6087eb1b2dc\"]/button[3]').click()\n print('csv file download button \\'re\\'clicked.')\n\n # wait for downloading.\n remainedTime = how_long_second_you_wait\n while 'data.csv' not in os.listdir(download_subpath): # wait for the csv file to be downloaded completely.\n time.sleep(1)\n remainedTime -= 1\n if remainedTime == 0:\n print('\\ncsv file download has \\'re\\'failed. : program closed!!!\\n')\n exit(1)\n\n# close the driver.\ndriver.close()\ndriver.quit()\n\n# arrange the csv file loaded & remove it.\ncsv = pd.read_csv(downloaded_csv_file_path)\ncsv['종목단축코드'] = ['A'+str(each).zfill(6) for each in csv['종목단축코드']]\ncsv['지정일자'] = [int(each.replace('/', '')) for each in csv['지정일자']]\ncsv['해제일자'] = [int(each.replace('/', '')) for each in csv['해제일자']]\ndel csv['종목구분'], csv['당일종가'], csv['전일대비']\ncsv.columns = ('코드', '종목명', '단기과열', '투자경고', '투자위험', '지정일', '해제일')\nos.remove(downloaded_csv_file_path)\nprint('csv file load, arrangement, removing are completed')\n\nprint(csv)\ncsvnp = csv.to_numpy()\n\n\n\n\n# 'headless option' caused the download step not to go.\n#options = webdriver.ChromeOptions()\n#options.add_argument('headless')\n#options.add_argument('disable-gpu') # or '--disable-gpu'\n#driver = webdriver.Chrome('C:\\\\chromedriver.exe', options=options)","sub_path":"Scrap.py","file_name":"Scrap.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"623390114","text":"from django.db.backends.base.base import BaseDatabaseWrapper\nfrom operations import DatabaseOperations\nfrom features import DatabaseFeatures\nfrom creation import DatabaseCreation\nfrom database import Database\nfrom django.db.backends.base.validation import BaseDatabaseValidation\nfrom introspection import DatabaseIntrospection\nfrom schema import DatabaseSchemaEditor\nfrom pymongo.mongo_client import MongoClient\nfrom django.db import DEFAULT_DB_ALIAS\nimport re\nfrom ..pymongo_custom.collection import Collection\nimport logging\n\nlogger = logging.getLogger('django.db.backends')\n\nOPERATORS_MAP = {\n 'text': lambda val: {'$text': val},\n 'where': lambda val: {'$where': val},\n 'exact': lambda val: val,\n 'gt': lambda val: {'$gt': val},\n 'gte': lambda val: {'$gte': val},\n 'lt': lambda val: {'$lt': val},\n 'lte': lambda val: {'$lte': val},\n 'in': lambda val: {'$in': val},\n 'range': lambda val: {'$gte': val[0], '$lte': val[1]},\n 'isnull': lambda val: None if val else {'$ne': None},\n 'iexact': lambda val: {'$regex': '^%s$' % re.escape(val), '$options':'i'},\n 'startswith': lambda val: {'$regex': '^%s' % re.escape(val)},\n 'istartswith': lambda val: {'$regex': '^%s' % re.escape(val), '$options':'i'},\n 'endswith': lambda val: {'$regex': '%s$' % re.escape(val)},\n 'iendswith': lambda val: {'$regex': '%s$' % re.escape(val), '$options': 'i'},\n 'contains': lambda val: {'$regex': re.escape(val)},\n 'icontains': lambda val: {'$regex': re.escape(val), '$options': 'i'},\n 'regex': lambda val: {'$regex': val},\n 'iregex': lambda val: {'$regex': val, '$options': 'i'},\n 'len': lambda val: {'$size': val},\n 'slice': lambda val: {'$slice': val}\n}\n\nNEGATED_OPERATORS_MAP = {\n 'exact': lambda val: {'$ne': val},\n 'gt': lambda val: {'$lte': val},\n 'gte': lambda val: {'$lt': val},\n 'lt': lambda val: {'$gte': val},\n 'lte': lambda val: {'$gt': val},\n 'in': lambda val: {'$nin': val},\n 'range': lambda val: {'$not': {'$gte': val[0], '$lte': val[1]}},\n 'isnull': lambda val: {'$ne': None} if val else None,\n 'iexact': lambda val: {'$regex': '^(?!%s$).*$' % re.escape(val), '$options': 'i'},\n 'startswith': lambda val: {'$regex': '^(?!%s).+' % re.escape(val)},\n 'istartswith': lambda val: {'$regex': '^(?!%s).+' % re.escape(val), '$options': 'i'},\n 'endswith': lambda val: {'$regex': '.*(? 3:\n raise ValueError\n\n db.add_show(data[0], message.from_user.id, data[1], data[2])\n\n reply = f'Added {data[0]} ... '\n\n except Exception as e:\n reply = f'Not valid format! must bee title-season-episode'\n\n finally:\n bot.send_message(message.chat.id, reply)\n\n\n@bot.message_handler(content_types=['text'])\n@bot.edited_message_handler(content_types=['text'])\ndef update_show(message: types.Message):\n\n reply = ''\n\n try:\n data = message.text.split('-')\n\n int(data[1])\n int(data[2])\n\n if len(data) > 3 :\n raise ValueError\n\n db.update_show(data[0], message.from_user.id, data[1], data[2])\n\n reply = f'Updated {data[0]} ... '\n\n except Exception as e:\n reply = f'Not valid format! must bee title-season-episode'\n\n finally:\n bot.send_message(message.chat.id, reply)\n\n\n@bot.message_handler(content_types=['text'])\n@bot.edited_message_handler(content_types=['text'])\ndef delete_show(message: types.Message):\n\n reply = ''\n data = message.text.strip()\n try:\n db.delete_show(data, message.from_user.id)\n reply = f'Deleted {data}'\n\n except Exception as e:\n reply = 'Not found or invalid format!'\n\n finally:\n bot.send_message(message.chat.id, reply)\n\n\ndef get_all_shows(user_id):\n\n reply = ''\n shows = db.get_all_shows(user_id)\n\n if not shows:\n reply = 'I am scared! It\\'s empty.'\n\n else:\n for show in shows:\n string = f'''Show - {show[2]}\\nSeason - {show[3]}\\nEpisode - {show[4]}\\n\\n'''\n reply = ''.join([reply, string])\n\n return reply\n\n\nbot.polling()\n","sub_path":"tele_bot.py","file_name":"tele_bot.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"560057614","text":"import requests\nimport json\nfrom .models import CarDealer, DealerReview, CarModel, CarMake\nfrom requests.auth import HTTPBasicAuth\nimport datetime\n\n# Create a `get_request` to make HTTP GET requests\n# e.g., response = requests.get(url, params=params, headers={'Content-Type': 'application/json'},\n# auth=HTTPBasicAuth('apikey', api_key))\ndef get_request(url,**kwargs):\n print(kwargs)\n print(\"GET from {} \".format(url))\n try:\n # Call get method of requests library with URL and parameters\n if \"api_key\" in kwargs:\n api_key= kwargs[\"api_key\"]\n response = requests.get(url, headers={'Content-Type': 'application/json'},\n params=kwargs, auth=HTTPBasicAuth('apikey', api_key))\n else:\n response = requests.get(url, headers={'Content-Type': 'application/json'},\n params=kwargs)\n except Error as val:\n # If any error occurs\n print(\"Network exception occurred\", val)\n\n \n status_code = response.status_code\n if status_code!=200:\n print(\"Server Error\")\n print(\"With status {}\".format(status_code))\n json_data = json.loads(response.text)\n return json_data\n\n# Create a `post_request` to make HTTP POST requests\n# e.g., response = requests.post(url, params=kwargs, json=payload)\ndef post_request(url, payload, **kwargs):\n print(\"POST Request from \", url)\n # try:\n response = requests.post(url, params=kwargs, json=payload)\n# except:\n # If any error occurs\n print(\"Network exception occurred\")\n status_code = response.status_code\n print(\"With status {}\".format(status_code))\n json_data = json.loads(response.text)\n return json_data\n\n# Create a get_dealers_from_cf method to get dealers from a cloud function\ndef get_dealers_from_cf(**kwargs):\n results = []\n url = \"https://7a6d4448.us-south.apigw.appdomain.cloud/api/dealership\"\n # Call get_request with a URL parameter\n json_result = get_request(url)\n if \"dealerships\" in json_result:\n # Get the row list in JSON as dealers\n dealers = json_result[\"dealerships\"]\n # For each dealer object\n for dealer in dealers:\n # Create a CarDealer object with values in `doc` object\n dealer_obj = CarDealer(address=dealer[\"address\"], city=dealer[\"city\"], full_name=dealer[\"full_name\"],\n id=dealer[\"id\"], lat=dealer[\"lat\"], long=dealer[\"long\"],\n short_name=dealer[\"short_name\"], state=dealer[\"state\"],\n st=dealer[\"st\"], zip=dealer[\"zip\"])\n results.append(dealer_obj)\n return results\n\n# Create a get_dealer_reviews_from_cf method to get reviews by dealer id from a cloud function\ndef get_dealer_by_state_from_cf(url, state_code):\n# - Call get_request() with specified arguments \n # query = {'state':state_code}\n url = 'https://7a6d4448.us-south.apigw.appdomain.cloud/api/dealership'\n json_response = get_request(url, state=state_code)\n\n results = []\n# - Parse JSON results into a DealerView object list\n if json_response:\n dealers = json_response[\"dealerships\"]\n # For each dealer object\n for dealer in dealers:\n # Create a CarDealer object with values in `doc` object\n dealer_obj = CarDealer(address=dealer[\"address\"], city=dealer[\"city\"], full_name=dealer[\"full_name\"],\n id=dealer[\"id\"], lat=dealer[\"lat\"], long=dealer[\"long\"],\n short_name=dealer[\"short_name\"], state=dealer[\"state\"],\n st=dealer[\"st\"], zip=dealer[\"zip\"])\n results.append(dealer_obj)\n\n return results \n\ndef get_dealer_reviews_from_cf(dealerId):\n url = 'https://7a6d4448.us-south.apigw.appdomain.cloud/api/review'\n json_response = get_request(url,dealerId=dealerId)\n results = []\n if \"reviews\" in json_response:\n reviews = json_response[\"reviews\"]\n for review in reviews:\n review_object = DealerReview(dealership=review[\"dealership\"],name = review[\"name\"],\n purchase = review[\"purchase\"], review = review[\"review\"], purchase_date = review[\"purchase_date\"],\n car_make = review[\"car_make\"], car_model = review[\"car_model\"],car_year=review[\"car_year\"],\n id = review[\"id\"])\n carmake = CarMake.objects.get_or_create(name = review[\"car_make\"], description = review[\"car_make\"])[0]\n car = CarModel.objects.create(dealerId=dealerId,name=review['car_model'],make=carmake, year=datetime.date(int(review[\"car_year\"]),1,1), Type=\"Sedan\")\n sentiment = analyze_review_sentiments(review_object.review)\n if \"error\" in sentiment:\n review_object.sentiment = \"neutral\"\n else:\n review_object.sentiment=sentiment[\"sentiment\"][\"document\"][\"label\"]\n results.append(review_object)\n else: \n return 500\n return results\n\n \n\n# Create an `analyze_review_sentiments` method to call Watson NLU and analyze text\ndef analyze_review_sentiments(text):\n# - Call get_request() with specified arguments\n# - Get the returned sentiment label such as Positive or Negative\n version = '2021-03-25'\n features = {\"sentiment\" }\n return_analyzed_text =True\n url = ''\n api_key = ''\n response = get_request(url, text = text, version=version, features = features, return_analyzed_text = return_analyzed_text, api_key=api_key)\n return response","sub_path":"server/djangoapp/restapis.py","file_name":"restapis.py","file_ext":"py","file_size_in_byte":5579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"248167876","text":"from collections import namedtuple\nfrom itertools import product\n\nItem = namedtuple('Item', ['name', 'cost', 'damage', 'armor'])\nPlayer = namedtuple('Player', ['hp', 'cost', 'damage', 'armor', 'equipment'])\nBoss = namedtuple('Boss', ['hp', 'damage', 'armor'])\n\nweapons = [\n Item('Dagger', 8, 4, 0),\n Item('Shortsword', 10, 5, 0),\n Item('Warhammer', 25, 6, 0),\n Item('Longsword', 40, 7, 0),\n Item('Greataxe', 74, 8, 0),\n]\n\narmor = [\n Item('Leather', 13, 0, 1),\n Item('Chainmail', 31, 0, 2),\n Item('Splintmail', 53, 0, 3),\n Item('Bandedmail', 75, 0, 4),\n Item('Platemail', 102, 0, 5),\n Item('Dummy', 0, 0, 0),\n]\n\nrings = [\n Item('Damage +1', 25, 1, 0),\n Item('Damage +2', 50, 2, 0),\n Item('Damage +3', 100, 3, 0),\n Item('Defense +1', 20, 0, 1),\n Item('Defense +2', 40, 0, 2),\n Item('Defense +3', 80, 0, 3),\n Item('Dummy1', 0, 0, 0),\n Item('Dummy2', 0, 0, 0),\n]\n\n\ndef equip_player(equipment, hp=100):\n stats = [sum(x[y] for x in equipment) for y in (1, 2, 3)]\n return Player(hp, *stats, equipment)\n\n\ndef visit_shop():\n for equipment in product(weapons, armor, rings, rings):\n # make sure we didn't pick the same ring twice\n if equipment[2] == equipment[3]:\n continue\n yield equip_player(equipment)\n\n\ndef fight(player, boss):\n player = player._asdict()\n boss = boss._asdict()\n i = 0\n while True:\n if not i % 2:\n # player's move\n boss['hp'] -= max(player['damage'] - boss['armor'], 1)\n if boss['hp'] <= 0:\n return True\n else:\n player['hp'] -= max(boss['damage'] - player['armor'], 1)\n if player['hp'] <= 0:\n return False\n i += 1\n\n\ndef rpg_simulator_20xx():\n won = set()\n lost = set()\n for player in visit_shop():\n boss = Boss(hp=109, damage=8, armor=2)\n outcome = fight(player, boss)\n if outcome:\n won.add(player)\n else:\n lost.add(player)\n\n min_spent_and_won = min(won, key=lambda x: x.cost)\n max_spent_and_lost = max(lost, key=lambda x: x.cost)\n print(min_spent_and_won.cost)\n print(max_spent_and_lost.cost)\n\n\nrpg_simulator_20xx()\n","sub_path":"day_21.py","file_name":"day_21.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"123531283","text":"from os import path\nfrom simpletransformers.classification import ClassificationModel\nimport pandas as pd\n\nmodel = ClassificationModel(\n \"roberta\",\n \"model/outputs/best\",\n args={\n \"fp16\": False,\n \"use_multiprocessing\": False,\n },\n)\n\ndf = pd.read_json(\"data/ready/predict.json\", orient=\"records\")\n\nsentences = df[\"text\"].tolist()\nlabels, _ = model.predict(sentences)\n\ndf.insert(2, \"predicted_labels\", labels, True)\n\nwith open(\"data/done/predict.json\", \"w\") as file:\n df.to_json(file, orient=\"records\")\n","sub_path":"src/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"96362327","text":"import math\ndef armstrongUreteci():\n w=[]\n for i in range(1,10):\n for j in range(0,10):\n for k in range(0,10):\n hedef=math.pow(i,3)+math.pow(j,3)+math.pow(k,3)\n sayi=100*i+10*j+k\n if(hedef==sayi):\n w.append(sayi)\n return w\n\ndef main():\n for i in armstrongUreteci():\n print(i)\n\nmain()\n\n","sub_path":"armstrongsayi.py","file_name":"armstrongsayi.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"108526232","text":"\n#!/usr/bin/env python3\n'''\n#euler 20:sum of digits of 100!\n'''\nfrom math import factorial\na=(factorial(100))\nb=str(a)\nb=[int(b[i]) for i in range(0,len(b))]\nprint(sum(b))\n#answer 648","sub_path":"euler20.py","file_name":"euler20.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"571490518","text":"#\n# Word count for text functions\n#\n\nimport string\nPUNC = string.punctuation\n\ndef remove_punctuation(s):\n return s.translate(None, PUNC)\n\n\ndef each_to_lowercase(arr):\n newarr = []\n for word in arr:\n newarr.append(word.lower())\n return newarr\n\n\ndef words_array(s):\n # remove all punctuation\n news = remove_punctuation(s)\n # create an array of words\n arr = each_to_lowercase(news.split())\n return arr\n\n\ndef word_count(word, arr):\n count = 0\n word = word.lower()\n for w in arr:\n if word == w: \n count += 1\n return count\n\n\ndef return_count_dictionary(text):\n dictionary = {}\n # create an array of words\n words = words_array(text)\n # go through each word \n for word in words:\n if word not in dictionary:\n dictionary.update({word: 1})\n else:\n # get the count of this word\n count = dictionary[word]\n # increase count by 1\n dictionary[word] = count + 1\n return dictionary\n\n\ndef return_superword(text):\n superword = ''\n largest_count = 0\n # create a dictionary of words and counts\n dictionary = return_count_dictionary(text)\n # go through each word in dictionary and find largest count\n for word in dictionary:\n this_count = dictionary[word]\n if this_count > largest_count:\n largest_count = this_count\n superword = word\n return [superword, largest_count]","sub_path":"words_count.py","file_name":"words_count.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"186782308","text":"import sys\nfrom dqmdata import db\nfrom dqmdata.hcal_online.dqmio import load_dqm_object\nfrom dqmdata.common.models.serializable import Serializable\nfrom dqmdata.hcal_local.models.channel import Channel\nfrom dqmdata.common.models.online_run import OnlineRun, add_run\nfrom dqmdata.common.utilities import *\n\nclass TDCTime_Run_Channel(Serializable, db.Model):\n\t__tablename__ = 'tdctime_run_channel'\n\tid = db.Column(db.Integer, primary_key=True)\n\trun = db.Column(db.Integer, db.ForeignKey('online_run.run'), index=True)\n\tchannel_id = db.Column(db.BigInteger, db.ForeignKey('channel.id'), index=True)\n\tvalue = db.Column(db.Float)\n\n\tdef __repr__(self):\n\t\treturn \"id {}, channel {}, run {} => {}\".format(self.id, self.channel_id, self.run, self.value)\n\t\t#return \"Detector: ({}, {}, {}, {}) | Electronics: ({}, {}, {}, {}) | emap {}\".format(self.subdet, self.ieta, self.iphi, self.depth, self.crate, self.slot, self.fiber, self.fiber_channel, self.emap_version)\n\n\t# Extract data from DQM histogram\n\tdef extract(self, run, emap_version=\"2018\", overwrite=False):\n\t\tprint(\"[TDCTime_Run_Channel::extract] Extracting for run {}\".format(run))\n\n\t\t# Check that this run is not already in DB\n\t\tif not check_overwrite(TDCTime_Run_Channel, run, emap_version, overwrite=overwrite):\n\t\t\treturn\n\n\t\t# Make sure run is in the run database\n\t\tadd_run(run, overwrite=False)\n\n\t\t# Get data\n\t\tdqm_data = load_dqm_object(run, \"Hcal/DigiTask/LETDCTime/depth\")\n\t\tif len(dqm_data) == 0:\n\t\t\tprint(\"[TDCTime_Run_Channel::extract] ERROR : DQM data is empty! Skipping.\")\n\t\t\treturn \n\t\t#print(dqm_data)\n\n\t\t# Get histograms\n\t\thist_pedestal_mean = {}\n\t\tfor depth in range(1, 8):\n\t\t\thist_pedestal_mean[depth] = dqm_data[\"depth{}\".format(depth)]\n\t\t\n\t\t# Which channels actually have TDC?\n\t\ttdc_subdets = []\n\t\tif emap_version == \"2017J\":\n\t\t\ttdc_subdets = [\"HEP17\", \"HF\"]\n\t\telif emap_version == \"2018\":\n\t\t\ttdc_subdets = [\"HE\", \"HF\"]\n\n\t\t# Extract all pedestals from the DQM histograms here\n\t\tchannels = Channel.query.filter(Channel.emap_version==emap_version)\n\t\tfor channel in channels:\n\t\t\tif not channel.subdet in tdc_subdets:\n\t\t\t\tcontinue\n\t\t\txbin, ybin = detid_to_histbins(channel.subdet, channel.ieta, channel.iphi)\n\t\t\tthis_pedestal_mean = hist_pedestal_mean[channel.depth].GetBinContent(xbin, ybin)\n\t\t\tif this_pedestal_mean == 0: # Zero suppress. This plot monitors drifts, not errors.\n\t\t\t\tcontinue\n\t\t\tthis_reading = TDCTime_Run_Channel(run=run, value=this_pedestal_mean, channel_id=channel.id)\n\t\t\t#print(this_reading)\n\t\t\tdb.session.add(this_reading)\n\t\tdb.session.commit()\n","sub_path":"dqmdata/hcal_online/models/tdctime_run_channel.py","file_name":"tdctime_run_channel.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"317682666","text":"#!/usr/bin/env python\n# _*_ coding: utf-8 _*_\n'''\nCreated on 2019-05-24 18:36:07\n@author: wind\n'''\nfrom tqdm import tqdm\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\n\n\nclass NewsDataset(Dataset):\n def __init__(self,data_file,max_seq_len):\n super().__init__()\n\n self.data = []\n \n with open(data_file,'r',encoding='utf-8') as f: \n for line in tqdm(f,desc=\"加载数据\"):\n arr = line.strip().split(\"\\t\")\n if len(arr)<2:\n continue\n\n label_id,sentence = arr\n segment = sentence.split(\" \")\n \n label_id = int(label_id)\n segment_ids = [int(i) for i in segment]\n segment_ids = segment_ids[:max_seq_len]\n\n seq_len = len(segment_ids)\n # padding\n padding = [0]*(max_seq_len-len(segment_ids))\n segment_ids += padding\n\n self.data.append({\n \"label_id\":torch.LongTensor([label_id]).to('cpu'),\n \"seq_len\":seq_len,\n \"segment_ids\":torch.LongTensor(segment_ids).to('cpu')\n })\n \n def __getitem__(self,item):\n return self.data[item]\n \n def __len__(self):\n return len(self.data)\n\ndef get_pre_embedding_matrix(src_file):\n arr = []\n with open(src_file,'r',encoding='utf-8') as f:\n for line in f:\n vec = line.strip().split(\" \")[1:]\n vec = [float(i) for i in vec]\n arr.append(vec)\n return arr\n\ndef get_labels(src_file):\n with open(src_file,'r',encoding='utf-8') as f:\n return [line.strip() for line in f.readlines()]\n \n\nif __name__ == \"__main__\":\n # ds = NewsDataset(\"./data/cnews_final_test.txt\",300)\n # print(ds[0])\n # get_pre_embedding_matrix(\"./data/final_vectors\")\n print(get_labels('./data/label'))\n","sub_path":"codes/textrnn/datahelper.py","file_name":"datahelper.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"633609464","text":"def sum_to_even(list):\n sum = 0\n for num in list:\n if num%2 == 0:\n return sum\n sum += num\n return sum\n\n\ndef test(list):\n print(str(list) + ' => ' + str(sum_to_even(list)))\n\n\nprint('if there is no even number, the sum of all elements is returned')\ntest([-1, 9])\ntest([3, 9, 10, 9])\ntest([2, 9, 10])\ntest([-5, -9, 3, -4])","sub_path":"CES-22/lista1/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"141202753","text":"from interface.main_window import DrawAndPredict\nfrom utils.module_checker import check_modules\n\n_version_ = '1.1.0'\n\nif __name__ == \"__main__\":\n print(f'Welcome to DLTI v{_version_}!')\n print(f'Checking Modules...')\n if not check_modules():\n quit()\n\n title = 'Deep Learning Training Interface'\n App = DrawAndPredict(title)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"156400853","text":"import os\n\nbatch_dir = os.path.join(os.environ['HOME'], 'batch_emerge')\nos.system(\"cd \"+batch_dir)\n\nimport glob \nimport numpy as n\n\ninput_list = n.array(glob.glob(\"/u/joco/data/MD/MD_0.4Gpc/hlists/hlist_*.list\"))\ninput_list.sort()\nsnapshot_names = n.array([ os.path.basename(el)[:-5] for el in input_list ])\noutput_list = n.array([ os.path.join(\"/u/joco/data/MD/MD_0.4Gpc/emerge/\", name+\".data\") for name in snapshot_names])\n\nmain_text = lambda snap_name : \"\"\"\n# @ shell=/bin/bash\n#\n# Sample script for LoadLeveler\n#\n# @ error = /u/joco/run_monitor/smd\"\"\"+snap_name+\"\"\".err.$(jobid)\n# @ output = /u/joco/run_monitor/smd\"\"\"+snap_name+\"\"\".out.$(jobid)\n# @ job_type = parallel\n# @ node_usage= not_shared\n# @ node = 1\n# @ tasks_per_node = 1\n# @ resources = ConsumableCpus(1)\n# @ wall_clock_limit = 01:00:00\n# @ notification = error\n# @ notify_user = comparat@mpe.mpg.de\n# @ queue \n\nsource /etc/profile.d/modules.sh\nmodule load anaconda\nexport PYTHONPATH=\"${PYTHONPATH}:/u/joco/software/pyEmerge/python/\"\n\ncd /u/joco/software/pyEmerge/bin/\n\"\"\"\n\nfor path_2_in, path_2_out, snap_name in zip(input_list, output_list, snapshot_names)[:13]:\n print(path_2_in, path_2_out, snap_name)\n batch_file = os.path.join(batch_dir, snap_name+\"_smd.sh\")\n f=open( batch_file, 'w')\n f.write(main_text(snap_name))\n command = \"python MD04-write-smallFile.py \"+path_2_in+\" \"+path_2_out\n print(command)\n f.write(command)\n f.close()\n \n os.system(\"llsubmit \" + batch_file )\n\n","sub_path":"bin/generate_and_submit_MD04-write-smallFile.py","file_name":"generate_and_submit_MD04-write-smallFile.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"643779769","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 11 09:37:29 2020\n\n@author: admin\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n# 0 이 10개, 1이 90개인 ndarray 생성\n\nlist1 = []\nfor i in range(0, 10, 1) :\n list1.append(0)\n\nlist2 = []\nfor i in range(0, 90, 1) :\n list2.append(1)\n \n# 2 개의 list를 가지고 하나의 array를 생성\ntarget = np.array(list1 + list2)\nprint(target)\n\n# 분류 알고리즘에 위의 데이터를 이용하는 경우\n# 0:10% 1:90%\n\n# 분류 알고리즘\nfrom sklearn.ensemble import RandomForestClassifier\n\n# 데이터의 비율이 현저히 다르므로 가중치 설정 필\nweights = {0:.9, 1:.1} #비율은 반대로 작성해야 함\n\nrfc = RandomForestClassifier(class_weight = weights)\nprint(rfc)\n\n# 가중치를 직접 설정하지 않고 분류기 판단에 맡기는 옵션(시간은 좀 더 걸림)\nrfc = RandomForestClassifier(class_weight = 'balanced')\nprint(rfc)\n\n# 샘플링 비율 조정\n# np.where는 array에서 조건에 맞는 데이터만 추출\n# np.where(target == 0)\n# target 행렬에서 값이 0인 데이터의 행번호를 리턴\n# (행번호 행렬, 자료형)으로 결과를 리턴\n# 행번호 행렬만 가져오기 위해서 [0]을 추\nclass0 = np.where(target == 0)[0]\nclass1 = np.where(target == 1)[0]\nprint(len(class0)) #10\nprint(len(class1)) #90\n\n# target이 1인 데이터에서 target이 0인 데이터만큼 다운 샘플링을 해서 새로운 데이터 셋을 생성\n# 새로운 데이터 셋을 생성\n# class1에서 class0의 데이터 개수만큼 비복원 추출(나온 것은 제거)\ndownsample = np.random.choice(class1, size = len(class0), replace = False)\nresult = np.hstack((target[class0], target[downsample]))\nprint(result)\n\n# 표준화\n# student.csv 파일의 내용을 가져오기\n# index로 이름을 설정\n#import os\n#print(os.getcwd())\n\ndata = pd.read_csv('./data/student.csv', index_col = '이름', encoding = 'cp949')\nprint(data)\n\nimport matplotlib.pyplot as plt\n\n# matplotlib 한글 폰트 오류 문제 해결\nfrom matplotlib import font_manager, rc\nimport platform\n\n# 그래프에 한글을 출력하기 위한 설\n#매킨토시의 경우\nif platform.system() == 'Darwin':\n rc('font', family='AppleGothic')\n\n#윈도우의 경우\nelif platform.system() == 'Windows':\n font_name = font_manager.FontProperties(fname=\"c:/Windows/Fonts/malgun.ttf\").get_name()\n rc('font', family=font_name)\n\n# 인덱스를 기준으로 하여 막대 그래프 그리기\ndata.plot(kind = 'bar')\n\n# 표준값 작\n# 각 과목의 평균과 표준편차 구하기\nkormean, korstd = data['국어'].mean(), data['국어'].std()\nengmean, engstd = data['영어'].mean(), data['영어'].std()\nmatmean, matstd = data['수학'].mean(), data['수학'].std()\n\n# 표준값 구하기\n# (해당 값 - 평균) / 표준편차\n# 0.0이면 중간\n# 1.0이면 상하위 15%\n# 2.0이면 상하위 1.1%\ndata['국어표준값'] = (data['국어'] - kormean)/korstd\ndata['영어표준값'] = (data['영어'] - engmean)/engstd\ndata['수학표준값'] = (data['수학'] - matmean)/matstd\n\nprint(data[['국어표준값', '영어표준값', '수학표준값']])\n\n# 표준값은 비교가 가능하나 사람이 알아보기 불편\n# 표준값 *10 + 50을 하여 편차값을 조정하고 보고서 작성\ndata['국어편차값'] = data['국어표준값']*10 + 50\ndata['영어편차값'] = data['영어표준값']*10 + 50\ndata['수학편차값'] = data['수학표준값']*10 + 50\n\nprint(data[['국어편차값', '영어편차값', '수학편차값']])\ndata[['국어편차값', '영어편차값', '수학편차값']].plot(kind = 'bar')\n\n# 최댓값으로 나누어서 표준화하기도 함 -> 정규화\n# 해당값-최솟값/최댓값-최솟값 으로 하기도 함\ndata['국어정규화1'] = data['국어']/data['국어'].max()\ndata['국어정규화2'] = (data['국어'] - data['국어'].min()) / (data['국어'].max() - data['국어'].min())\n\n##sklearn을 이용한 scailing\nfrom sklearn import preprocessing\n\n# StandardScaler\n# 평균은 0 표준편차는 1이 되도록 표준화\nscaler = preprocessing.StandardScaler()\n\n# 국어 점수만 이용하는 경우 data['국어']가 아니고 data[['국어']]\n# 머신러닝의 데이터들은 행렬을 이용하는데 data['국어']하게 되면\n# 컬럼이름이 1개라서 하나의 열로 리턴되어 1차원 데이터가 됨\n# data[['국어']] 할 시 list를 대입하였기 때문에 DataFrame으로 리\nresult = scaler.fit_transform(data['국어'].values)\nprint(result) # 표준값 구한 것\nprint(np.mean(result))\nprint(np.std(result))\n\n# 이차원 행렬을 생성\nmatrix = data[['국어', '영어']].values\nprint(matrix)\n\nprint()\n\nmatrix = np.array([[30, 20], [10, 30], [30, 40]])\nprint(matrix)\n\nfrom sklearn import preprocessing\n\n# 정규화 객체 생성 - 유클리디안 거리 사용\nnorm = preprocessing.Normalizer(norm = '12')\nprint(norm.transform(matrix))\nnorm = preprocessing.Normalizer(norm = '11')\nprint(norm.transform(matrix))\nnorm = preprocessing.Normalizer(norm = 'max')\nprint(norm.transform(matrix))\n\n# 다항과 교차항을 만들어주는 객체를 생성\n# degree = 2 : 제곱한 것까지 생성\n# [4, 7] -> [4, 7, 46, 28, 49]\npolynomial = preprocessing.PolynomialFeatures(degree = 2, include_bias = False)\nresult = polynomial.fit_transform(matrix)\nprint(result)\n\npolynomial = preprocessing.PolynomialFeatures(degree = 3, include_bias = False)\nresult = polynomial.fit_transform(matrix)\nprint(result)\n\n# 함수 적용하기\nmatrix = np.array([[100, 200], [300, 150]])\nprint(matrix)\n\n# 100을 결합하기\ndef intconvert(x):\n return x + 100\n\ntransformer = preprocessing.FunctionTransformer(intconvert)\nresult = transformer.transform(matrix)\nprint(result)\n\nprint(data['국어'])\nprint(data['국어'].apply(intconvert))\n\nimport numpy as np\nimport pandas as pd\n\n# array를 입력받아서 z 점수(평균의 표준편차 3 범위)\n# 밖에 있는 데이터를 리턴해주는 함수\n\ndef z_score_outlier(ar) :\n threshold = 3\n # 평균 가져오기\n meandata = np.mean(ar)\n stdevdata = np.std(ar)\n # ar의 요소를 y에 하나씩 대입하여 앞의 수식을 적용하고 그 결과를 가지고 다시 list로 생성\n z_scores = [(y - meandata) / stdevdata for y in ar]\n return np.where(np.abs(z_scores) > threshold)\n\n# z score 보정\n# 범위를 3.5배를 늘리고 표준편차 0.6875를 곱해줌\ndef modify_z_score_outlier(ar) :\n threshold = 3.5\n # 평균 가져오기\n meandata = np.mean(ar)\n stdevdata = np.std(ar)\n # ar의 요소를 y에 하나씩 대입하여 앞의 수식을 적용하고 그 결과를 가지고 다시 list로 생성\n z_scores = [0.6875 * (y - meandata) / stdevdata for y in ar]\n return np.where(np.abs(z_scores) > threshold)\n\n# IQR 이용\n# 3사분위수 - 1사분위수 +- 1.5배 이상 차이나면 이상치로 간주\ndef iqr_outlier(ar) :\n # 25%와 75% 값 찾기\n q1, q3 = np.percentile(ar, [25, 75])\n # iqr 값 찾기\n iqr = q3 -q1\n # 25% 값과 1.5iqr보다 작은 값 찾\n lower = q1 - (iqr * 1.5)\n upper = q3 + (iqr * 1.5)\n return np.where((ar > upper) | (ar < lower))\n \n\n# 샘플 데이터 생성\nfeatures = np.array([[10, 30, 13, -20, 4, 12, 10, 30, 13, 10, 30, 13, 10, 30, 13], [2, 3, 5, 4, 2, 1000, 3, 5, 4, 3, 5, 4, 3, 5, 4]])\nfeatures = np.array([[10, 30, 13, -20, 4, 12], [2, 3, 5, 4, 2, 1000]])\n\n\nresult = z_score_outlier(features)\n#1 z_score_outlier(ar)\n#(array([1], dtype=int64), array([5], dtype=int64))\n#features = np.array([[10, 30, 13, -20, 4, 12], [2000, 3, 5, 4, 2, 1000]])\n#(array([], dtype=int64), array([], dtype=int64))\n# 데이터 양이 적은 상태에서 2개 이상의 outlier는 나오기 어려움\n# 데이터 양 늘렸을 때\n#(array([0, 1], dtype=int64), array([5, 5], dtype=int64))\nresult = modify_z_score_outlier(features)\n#2 modify_z_score_outlier(ar)\n#(array([1], dtype=int64), array([5], dtype=int64)) (데이터 양 많아야 함)\nresult = iqr_outlier(features)\n#3 iqr_outlier(features)\n#(array([0, 0, 0, 0, 0, 1], dtype=int64), array([ 1, 3, 7, 10, 13, 5], dtype=int64))\n#(array([0, 0, 1], dtype=int64), array([1, 3, 5], dtype=int64))\nprint(result)\n\n\nhouse = pd.DataFrame()\nhouse['price'] = [100000, 200000, 150000, 10000000]\nhouse['rooms'] = [1, 3, 2, 100]\nhouse['square'] = [11, 23, 16, 1200]\nprint(house)\n\n# 이상한 데이터 제거\n# 방이 5개 이상 제거\nprint(house[house['rooms'] < 6])\n\n# 이상한 데이터를 별도로 표시\nhouse['outlier'] = np.where(house['rooms'] < 6, 0, 1)\nprint(house)\n\n\n# 값의 범위 줄이기 - np.log는 자연로그를 계산\nhouse['log'] = [np.log(x) for x in house['rooms']]\nprint(house)\n\n# 문자 데이터를 pandas의 시계열 데이터로 만들기\ndf = pd.read_csv('./data/stock-data.csv')\nprint(df)\n\n# 자료형 확인\ndf.info()\n\"\"\"\n\nRangeIndex: 20 entries, 0 to 19\nData columns (total 6 columns):\nDate 20 non-null object\nClose 20 non-null int64\nStart 20 non-null int64\nHigh 20 non-null int64\nLow 20 non-null int64\nVolume 20 non-null int64\ndtypes: int64(5), object(1)\nmemory usage: 1.1+ KB\n\"\"\"\n\n# Date 컬럼의 값을 시계열로 변경하여 추가\ndf['newDate'] = pd.to_datetime(df['Date'])\ndf.info()\n\"\"\"\n\nRangeIndex: 20 entries, 0 to 19\nData columns (total 7 columns): #<<<<\nDate 20 non-null object\nClose 20 non-null int64\nStart 20 non-null int64\nHigh 20 non-null int64\nLow 20 non-null int64\nVolume 20 non-null int64\nnewDate 20 non-null datetime64[ns]\ndtypes: datetime64[ns](1), int64(5), object(1)\nmemory usage: 1.2+ KB\n\"\"\"\n\n# 위와 같은 데이터프레임에서는\n# 날짜를 index로 설정하는 경우가 많음\ndf.set_index('newDate', inplace = True)\ndf.drop('Date', axis = 1, inplace = True)\nprint(df.head())\n\n# 일정한 간격을 갖는 날짜 만들기\ndates = ['2017-03-01', '2017-06-01', '2019-12-01']\n\n# 날짜로 변경\npddates = pd.to_datetime(dates)\nprint(pddates)\n\n# Period로 변환\npdperiod = pddates.to_period(freq = 'D')\nprint(pdperiod)\n\npdperiod = pddates.to_period(freq = 'M')\nprint(pdperiod)\n\npdperiod = pddates.to_period(freq = 'Q')\nprint(pdperiod)\n\npdperiod = pddates.to_period(freq = 'A')\nprint(pdperiod)\n\npdperiod = pddates.to_period(freq = 'W')\nprint(pdperiod)\n\n\n# 일정한 간격을 가진 날짜 데이터 생성\nts_ms = pd.date_range(start = '2018-01-01'\n , end = None\n , periods = 12\n , freq = 'M')\n\nprint(ts_ms)\n\nts_ms = pd.date_range(start = '2018-01-01'\n , end = None\n , periods = 12\n , freq = '2H')\n\nprint(ts_ms)\n\n\n# 문자 데이터를 pandas의 시계열 데이터로 만들기\ndf = pd.read_csv('./data/stock-data.csv')\n\n# Date 컬럼의 값을 시계열로 변경하여 추가\ndf['newDate'] = pd.to_datetime(df['Date'])\n\ndf['year'] = df['newDate'].dt.year\nprint(df['year'])\n\n\n# python의 날짜 패키지\nfrom datetime import datetime\n\ndates = [datetime(2017, 1, 1)\n , datetime(2017, 1, 4)\n , datetime(2017, 1, 7)]\nts = pd.Series(np.random.randn(3)\n , index = dates)\nprint(ts)\n\nprint(ts.shift(-1))\n\nran = pd.date_range('11/3/2020'\n , periods = 20\n , freq = 'T')\nprint(ran)\n\nts = pd.Series(np.arange(20), index = ran)\nprint(ts)\n\n# 5분 단위로 합계\nprint(ts.resample('5T').sum())\n\n# 7분 단위로 평균\nprint(ts.resample('7T').mean())\n\n\n## 단순이동평균과 지수이동평균\n# 월 단위로 12개의 시간을 생성\nts = pd.date_range('2020/01/01'\n , periods = 12\n , freq = 'M')\n\ndf = pd.DataFrame(index = ts)\nprint(df)\n\ndf['data'] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]\nprint(df)\n\n# 단순이동평균 - 개수만 설정해서 평균내기\nprint(df.rolling(window = 2).mean())\n\nprint(df.rolling(window = 3).mean())\n\n\n\n\n\n\n\n","sub_path":"200311_Data/py0311.py","file_name":"py0311.py","file_ext":"py","file_size_in_byte":11920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"521565910","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 12/3/2018 3:39 PM\n# @Author : ZackChao\n# @Site : \n# @File : 自由落体.py\n# @Software: PyCharm\n\n\n\n# 4、一球从100米高度自由落下,每次落地后反跳回原高度的一半,再落下,求他在第10次落地时,共经过多少米?第10次反弹多高?\n# 分析, 高度100米 h\n# h=0.5*h 再落下 2h\n# 10次 共经米数 sum1=2h , sum2=2h,...\n\n\nh=100\nhsum=0\nfor i in range(1,11):\n h=0.5*h\n hsum+=h*2\n\nprint(h,hsum)\n","sub_path":"PythonSloution/0000/自由落体.py","file_name":"自由落体.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"293636644","text":"from urllib.request import urlopen\nfrom urllib.error import HTTPError\nimport io\nfrom PIL import Image\n\nCLOUD_WNID = \"n09247410\"\nFACE_WNID = \"n09618957\"\n\ndef get_urls(wnid=FACE_WNID, handler=lambda x: x): \n url = \"http://image-net.org/api/text/imagenet.synset.geturls?wnid=\" + wnid\n\n with urlopen(url) as response:\n urls = response.read().decode('utf-8')\n for img_url in urls.splitlines():\n print(\"Downloading %s\" % img_url, end=\"\")\n try:\n with urlopen(img_url) as img_response:\n print(\"...done\")\n img = Image.open(io.BytesIO(img_response.read()))\n img.name=img_url.split('/')[-1]\n handler(img)\n except HTTPError as e:\n print(\"...failed: %s\" % e.code)\n except:\n print(\"...failed: unknown\")\n\nif __name__ == \"__main__\":\n def handler(img):\n img.save(\"./data/clouds/\" + img.name)\n get_urls(CLOUD_WNID, handler=handler)\n","sub_path":"imagenet.py","file_name":"imagenet.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"246759538","text":"from os import listdir\nfrom os.path import isfile, join, splitext\nimport zipfile\n\n#this is only for windows\n#testing\n\n\npath = 'C:\\\\Users\\\\gonzalo.sanchez\\\\Documents\\\\Kaggle\\\\BBVA-Challenge\\\\Datasets'\nfinal_directory='C:\\\\Users\\\\gonzalo.sanchez\\\\Documents\\\\Kaggle\\\\BBVA-Challenge\\\\Datasets'\nfiles = [f for f in listdir(path) if isfile(join(path, f))]\nprint(files)\n#break\nfor f in files:\n current_path = join(path, f)\n current_file, file_extension = splitext(current_path)\n print(current_file)\n if(file_extension == '.zip'):\n with zipfile.ZipFile(current_path, 'r') as zip_ref:\n zip_ref.extractall(final_directory)\n","sub_path":"get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"189779285","text":"\"\"\"Low-level interface that spouts/bolts use to talk with Storm\"\"\"\n\nimport os\nimport socket\nimport sys\nimport logging\nimport time\nimport traceback\n\nfrom collections import deque\n\n\n# Use simplejson, but only with speedups\ntry:\n import simplejson as json\n if json._import_c_make_encoder() is None:\n import json\nexcept ImportError:\n import json\n\nlog = logging.getLogger(__name__)\nstdout = sys.stdout\n\nclass StormIPCException(Exception):\n pass\n\n\nclass LogStream(object):\n \"\"\"Logging class to mimic stdin/out so we don't mess up Storm IPC\n\n \"\"\"\n def __init__(self, logger):\n self.logger = logger\n\n def write(self, message):\n self.logger.info(message)\n\n\ndef initialize():\n \"\"\"Read initialization message and perform init tasks\n\n Redirects stdin/stderr to loggers so print statements\n don't mess up communications with storm.\n\n :returns: (conf, context) from storm\n \"\"\"\n sys.stdout = LogStream(logging.getLogger('storm.stdout'))\n sys.stderr = LogStream(logging.getLogger('storm.stderr'))\n\n setup = read()\n log.info('Task config: %s', setup['conf'])\n log.info('Task context: %s', setup['context'])\n\n # Write the pidfile and tell Storm about it\n send_pid(setup['pidDir'])\n\n return setup['conf'], setup['context']\n\n\n##\n## Basic i/o\n##\n\ndef read(max_message_lines=100,\n max_message_size=16777216,\n max_blank_lines=20):\n \"\"\"Read an incoming message from Storm\"\"\"\n def line_gen():\n \"\"\"Generator to read lines from stdin\"\"\"\n blank_lines = 0\n line_count = 0\n message_size = 0\n while True:\n line = sys.stdin.readline()\n if line == \"end\\n\":\n break\n line_count += 1\n\n # Check 1. If message_size gets too large, we're probably reading\n # blank lines from a dead IPC connection.\n message_size += len(line)\n if max_message_size and message_size > max_message_size:\n raise StormIPCException('Message size exceeds maximum (%i). '\n 'Assuming IPC connection dead' % message_size)\n\n # Check 2. A great number of blank lines also indicates the IPC\n # conneciton is dead\n if not line:\n blank_lines += 1\n storm_log.debug('Message line #%d is blank. %i blank '\n 'lines so far.' % (line_count, blank_lines))\n if max_blank_lines and blank_lines > max_blank_lines:\n raise StormIPCException(\n 'Blank lines exceeds maximum (%i). Assuming IPC '\n 'connection dead' % max_blank_lines\n )\n # Check 3. Maximum number of overall lines could be a problem\n if line_count > 100:\n raise StormIPCException(\n 'Message lines exceeds maximum (%i). Assuming IPC '\n 'connection dead' % max_message_lines\n )\n\n # Looks good\n yield line\n\n msg = ''.join(line for line in line_gen())\n log.debug('stdin: %s', msg)\n return json.loads(msg)\n\n\ndef write(msg):\n msg = json.dumps(msg)\n stdout.write(msg)\n stdout.write('\\nend\\n') # \\n at start avoids an unnecessary string copy\n try:\n stdout.flush()\n except (IOError, OSError) as e:\n log.exception(str(e))\n raise StormIPCException('%s error [Errno %d] in sendMsgToParent: %s' % (\n type(e).__name__,\n e.errno,\n str(e)))\n log.debug('stdout: %s', msg)\n\n\n##\n## Command implementations\n##\n\ndef send_ack(tup):\n \"\"\"ACK a Tuple\"\"\"\n write({\"command\": \"ack\", \"id\": tup.id})\n\ndef send_error(msg):\n \"\"\"Send error message to Storm\"\"\"\n write({\"command\": \"error\", \"msg\": msg})\n\ndef send_fail(tup):\n \"\"\"Fail a tuple\"\"\"\n write({\"command\": \"fail\", \"id\": tup.id})\n\ndef send_log(msg):\n write({\"command\": \"log\", \"msg\": msg})\n\ndef send_pid(pid_dir):\n \"\"\"Write pidfile and send pid to Storm\"\"\"\n pid = os.getpid()\n open(os.path.join(pid_dir, str(pid)), \"w\").close()\n write({'pid':pid})\n log.info('Task pid sent to Storm')\n\ndef send_sync():\n write({'command':'sync'})\n\n################################################################################\n################################################################################\n################################################################################\n################################################################################\n################################################################################\n\n#queue up commands we read while trying to read taskids\npending_commands = deque()\n\ndef readTaskIds():\n if pending_taskids:\n return pending_taskids.popleft()\n else:\n msg = readMsg()\n while type(msg) is not list:\n pending_commands.append(msg)\n msg = readMsg()\n return msg\n\n#queue up taskids we read while trying to read commands/tuples\npending_taskids = deque()\n\ndef readCommand():\n if pending_commands:\n return pending_commands.popleft()\n else:\n msg = readMsg()\n while type(msg) is list:\n pending_taskids.append(msg)\n msg = readMsg()\n return msg\n\ndef readTuple():\n cmd = readCommand()\n return Tuple(cmd[\"id\"], cmd[\"comp\"], cmd[\"stream\"], cmd[\"task\"], cmd[\"tuple\"])\n\ndef sendMsgToParent(msg):\n print >> old_stdout, json_encode(msg)\n print >> old_stdout, \"end\"\n try:\n old_stdout.flush()\n except (IOError, OSError) as e:\n storm_log.exception(str(e))\n raise StormIPCException('%s error [Errno %d] in sendMsgToParent: %s' % (\n type(e).__name__,\n e.errno,\n str(e)))\n\n# This function is probably obsolete with the addition of the new\n# reportError() function.\n# TODO: Consider getting rid of this function and call reportError() instead.\n# However, need to consider the case where we are running on an older version\n# of Storm where the Storm back end does not support reportError()? Can we\n# detect that case and use this function instead?\ndef sendFailureMsgToParent(msg):\n \"\"\"This function is kind of a hack, but useful when a Python task\n encounters a fatal exception. \"msg\" should be a simple string like\n \"E_SPOUTFAILED\". This function sends \"msg\" as-is to the Storm worker,\n which tries to parse it as JSON. The hacky aspect is that we\n *deliberately* make it fail by sending it non-JSON data. This causes\n the Storm worker to throw an error and restart the Python task. This\n is cleaner than simply letting the task die without notifying Storm,\n because this way Storm restarts the task more quickly.\"\"\"\n assert isinstance(msg, basestring)\n print >> old_stdout, msg\n print >> old_stdout, \"end\"\n storm_log.error('Sent failure message (\"%s\") to Storm', msg)\n\n\ndef emit(*args, **kwargs):\n result = __emit(*args, **kwargs)\n if result:\n return readTaskIds()\n\ndef emitMany(*args, **kwargs):\n \"\"\"A more efficient way to emit a number of tuples at once.\"\"\"\n global MODE\n if MODE == Bolt:\n emitManyBolt(*args, **kwargs)\n elif MODE == Spout:\n emitManySpout(*args, **kwargs)\n\ndef emitDirect(task, *args, **kwargs):\n kwargs[\"directTask\"] = task\n __emit(*args, **kwargs)\n\ndef __emit(*args, **kwargs):\n global MODE\n if MODE == Bolt:\n return emitBolt(*args, **kwargs)\n elif MODE == Spout:\n return emitSpout(*args, **kwargs)\n\ndef emitManyBolt(tuples, stream=None, anchors = [], directTask=None):\n global ANCHOR_TUPLE\n if ANCHOR_TUPLE is not None:\n anchors = [ANCHOR_TUPLE]\n m = {\n \"command\": \"emit\",\n \"anchors\": [a.id for a in anchors],\n \"tuple\": None,\n \"need_task_ids\": False,\n }\n if stream is not None:\n m[\"stream\"] = stream\n if directTask is not None:\n m[\"task\"] = directTask\n\n lines = []\n for tup in tuples:\n m[\"tuple\"] = tup\n lines.append(json_encode(m))\n lines.append('end')\n print >> old_stdout, '\\n'.join(lines)\n\ndef emitBolt(tup, stream=None, anchors = [], directTask=None, need_task_ids=False):\n global ANCHOR_TUPLE\n if ANCHOR_TUPLE is not None:\n anchors = [ANCHOR_TUPLE]\n m = {\n \"command\": \"emit\",\n \"anchors\": [a.id for a in anchors],\n \"tuple\": tup,\n \"need_task_ids\": need_task_ids,\n }\n if stream is not None:\n m[\"stream\"] = stream\n if directTask is not None:\n m[\"task\"] = directTask\n sendMsgToParent(m)\n return need_task_ids\n\ndef emitManySpout(tuples, stream=None, id=None, directTask=None):\n m = {\n \"command\": \"emit\",\n \"tuple\": None,\n \"need_task_ids\": need_task_ids,\n }\n if id is not None:\n m[\"id\"] = id\n if stream is not None:\n m[\"stream\"] = stream\n if directTask is not None:\n m[\"task\"] = directTask\n\n lines = []\n for tup in tuples:\n m[\"tuple\"] = tup\n lines.append(json_encode(m))\n lines.append('end')\n print >> old_stdout, '\\n'.join(lines)\n\ndef emitSpout(tup, stream=None, id=None, directTask=None, need_task_ids=False):\n m = {\n \"command\": \"emit\",\n \"tuple\": tup,\n \"need_task_ids\": need_task_ids,\n }\n if id is not None:\n m[\"id\"] = id\n if stream is not None:\n m[\"stream\"] = stream\n if directTask is not None:\n m[\"task\"] = directTask\n sendMsgToParent(m)\n return need_task_ids\n\ndef ackId(tupid):\n \"\"\"Acknowledge a tuple when you only have its ID\"\"\"\n sendMsgToParent({\"command\": \"ack\", \"id\": tupid})\n\n\ndef initialize_profiling():\n global TUPLE_PROFILING\n TUPLE_PROFILING = storm_log.isEnabledFor(logging.DEBUG)\n if TUPLE_PROFILING:\n storm_log.info('Tuple profiling enabled. Will log tuple processing times.')\n else:\n storm_log.info('Tuple profiling NOT enabled. Will not log tuple processing times.')\n","sub_path":"petrel/petrel/ipc.py","file_name":"ipc.py","file_ext":"py","file_size_in_byte":9985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"289113262","text":"from selenium import webdriver\nimport time\nimport os\n\nfrom selenium.webdriver.support.select import Select\nfrom tqdm import tqdm\nimport pandas as pd\n\nchrome = os.path.abspath('chromedriver.exe')\ndriver = webdriver.Chrome(chrome)\n\n# driver.get('https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1')\n# driver.get('https://tfhub.dev/google/universal-sentence-encoder-large/5')\n# driver.get('https://tfhub.dev/google/nonsemantic-speech-benchmark/trill/3')\ndriver.get('https://tfhub.dev/tensorflow/coral-model/mobilenet_v1_1.0_224_quantized/1/default/1')\n\ndata = pd.DataFrame(columns=['Name', 'Format', 'Downloads', 'language', 'Description', 'Tunable', 'model_link',\n 'Version', 'Size'])\n\ntime.sleep(2)\n\nform = 0\nwhile True:\n Formats = driver.find_elements_by_css_selector('div[role=\\'tab\\']')\n Formats[form].click()\n time.sleep(0.5)\n break_point = False\n i = 0\n\n while not break_point:\n time.sleep(0.5)\n # get versions\n try:\n Version_button = driver.find_element_by_css_selector(\n 'section.title > mat-form-field div.mat-form-field-wrapper '\n 'div.mat-form-field-flex div.mat-form-field-infix mat-select '\n 'div.mat-select-trigger')\n version = Version_button.find_element_by_css_selector('div span span').text\n Version_button.click()\n Options = driver.find_elements_by_css_selector('div[role=\"listbox\"] > mat-option')\n total_versions = str(len(Options))\n except:\n version = '1'\n total_versions = '1'\n Options = []\n break_point = True\n\n # Format\n try:\n Format = driver.find_element_by_css_selector('section.overview div p.tag:nth-child(4) span').text\n except:\n Format = None\n\n # downloads\n try:\n downloads = \\\n driver.find_element_by_css_selector('section.detail-content div.model-formats model-format-tabset '\n 'mat-tab-group div.mat-tab-body-wrapper._mat-animation-noopable'\n ' mat-tab-body div model-format-tab div download-count-label '\n 'div span').text.split()[0]\n except:\n downloads = None\n\n # Name,Downloads, Tunable, model, size,Description\n\n # language\n try:\n language = driver.find_element_by_xpath('//div[contains(text(), \"Language:\")]/parent::div/a').text\n except:\n language = None\n\n # links\n a_links = driver.find_elements_by_css_selector('section.documentation markdown-snippet div a')\n links_associated = [x.get_attribute(\"href\") for x in a_links]\n data_model = {\n 'Name': driver.find_element_by_css_selector('div.overview h2').text,\n 'Format': Format,\n 'Version': version,\n 'Downloads': downloads,\n 'Tunable': driver.find_element_by_css_selector('section.overview div p.tag:nth-child(1) span').text,\n 'model_link': driver.find_element_by_css_selector('download-button.ng-star-inserted a').get_attribute(\n \"href\"),\n 'Size': driver.find_element_by_css_selector('download-button.ng-star-inserted a button span span').text,\n 'Description': driver.find_element_by_css_selector('section.overview div p.description').text,\n 'total_versions': total_versions,\n 'links_associated': links_associated,\n 'language': language,\n }\n data = data.append(data_model, ignore_index=True)\n\n i += 1\n\n if i >= len(Options):\n break_point = True\n else:\n Options[i].click()\n\n form += 1\n if form >= len(Formats):\n break\n\ndata.to_csv(\"model_sample.csv\")\ndriver.close()\n","sub_path":"Get_model.py","file_name":"Get_model.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"109407721","text":"\"\"\"Tracks SQL timing stats and prints results periodically or on exit.\"\"\"\n\nimport time\nimport re\nimport atexit\nfrom hive.utils.system import colorize, peak_usage_mb\n\n# pylint: disable=missing-docstring\n\nclass QueryStats:\n SLOW_QUERY_MS = 250\n\n stats = {}\n ttl_time = 0.0\n\n def __init__(self):\n atexit.register(QueryStats.print)\n\n def __call__(self, fn):\n def wrap(*args, **kwargs):\n time_start = time.perf_counter()\n result = fn(*args, **kwargs)\n time_end = time.perf_counter()\n QueryStats.log(args[1], (time_end - time_start) * 1000)\n return result\n return wrap\n\n @classmethod\n def log(cls, sql, ms):\n nsql = cls.normalize_sql(sql)\n cls.add_nsql_ms(nsql, ms)\n cls.check_timing(nsql, ms)\n if cls.ttl_time > 30 * 60 * 1000:\n cls.print()\n\n @classmethod\n def add_nsql_ms(cls, nsql, ms):\n if nsql not in cls.stats:\n cls.stats[nsql] = [ms, 1]\n else:\n cls.stats[nsql][0] += ms\n cls.stats[nsql][1] += 1\n cls.ttl_time += ms\n\n @classmethod\n def normalize_sql(cls, sql):\n nsql = re.sub(r'\\s+', ' ', sql).strip()[0:256]\n nsql = re.sub(r'VALUES (\\s*\\([^)]+\\),?)+', 'VALUES (...)', nsql)\n return nsql\n\n @classmethod\n def check_timing(cls, nsql, ms):\n if ms > cls.SLOW_QUERY_MS:\n print(colorize(\"[SQL-SLOW][%dms] %s\" % (ms, nsql[:250])))\n\n @classmethod\n def print(cls):\n if not cls.stats:\n return\n ttl = cls.ttl_time\n print(\"[STATS] sampled SQL time: {}s\".format(int(ttl / 1000)))\n for arr in sorted(cls.stats.items(), key=lambda x: -x[1][0])[0:40]:\n sql, vals = arr\n ms, calls = vals\n print(\"% 5.1f%% % 7dms % 9.2favg % 8dx -- %s\"\n % (100 * ms/ttl, ms, ms/calls, calls, sql[0:180]))\n print(\"[STATS] peak memory usage: %.2fMB\" % peak_usage_mb())\n cls.clear()\n\n @classmethod\n def clear(cls):\n cls.stats = {}\n cls.ttl_time = 0\n","sub_path":"hive/db/query_stats.py","file_name":"query_stats.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"151049043","text":"\"\"\"Les documentation nécessaires sont disponible dans le dossier \r\ndocumentation de ce projet.\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef sigmoid(x):\r\n \"\"\"Fonction d'activation sigmoid. Borne la sortie dans une valeur \r\n décimale comprise entre 0 et 1\"\"\"\r\n return 1 / (1 + np.exp(-x))\r\n\r\nclass Neuron :\r\n def __init__(self, weights, bias):\r\n self.weights = weights\r\n self.bias = bias\r\n \r\n def feedforward(self, inputs):\r\n \"\"\"Produit scalaire de weight et inputs. Passage du résultat dans \r\n la fonction sigmoid\"\"\"\r\n total = np.dot(self.weights, inputs) + self.bias\r\n return sigmoid(total)\r\n \r\nweights = np.array([0, 1])\r\nbias = 4 \r\nn = Neuron(weights, bias)\r\n\r\nx = np.array([2, 3])\r\nprint(n.feedforward(x))\r\n","sub_path":"Neuron.py","file_name":"Neuron.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"307330686","text":"import unittest\nfrom Visualization.underoverfitting import plot\nimport MNIST.blog\nimport underoverfitting\nimport time\nimport copy\n\n\nclass TestPlots(unittest.TestCase):\n\n def test_underoverfitting(self):\n plot([(0.9, 0.8), (0.6, 0.65), (0.77, 0.81), (0.89, 0.86)])\n\n def test_MNINST(self):\n train_data, train_truths, dev_data, dev_truths, _, __ = MNIST.blog.load_dataset()\n\n p = underoverfitting.train_and_predict(train_data, train_truths, dev_data, dev_truths,\n MNIST.blog.create_net_shape,\n max_epochs=2,\n output_num_units=10)[-1]\n\n self.assertIsInstance(p[0], float)\n self.assertIsInstance(p[1], float)\n\n def test_plot_MNIST(self):\n train_data, train_truths, dev_data, dev_truths, _, __ = MNIST.blog.load_dataset()\n\n underoverfitting.train_and_predict_and_plot(train_data, train_truths, dev_data, dev_truths,\n MNIST.blog.create_net_shape,\n max_epochs=5,\n output_num_units=10)\n\n def test_plot_thread(self):\n pts = [[0.1, 0.2], [0.3, 0.4]]\n plot(copy.copy(pts))\n\n time.sleep(3)\n pts.append([0.15, 0.16])\n pts.append([0.07, 0.08])\n plot(pts)\n","sub_path":"Visualization/test_underoverfitting.py","file_name":"test_underoverfitting.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"511194437","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 8 15:12:59 2021\r\n\r\n@author: Erlend Tøssebro\r\n\"\"\"\r\n\r\nfortsetter = True\r\nwhile fortsetter:\r\n filnavn = input(\"Hvilken fil skal leses? \")\r\n try:\r\n fila = open(filnavn, \"r\", encoding=\"UTF8\")\r\n fortsetter = False\r\n except FileNotFoundError:\r\n print(\"Kan ikke finne fila\")\r\n print(\"prøv på nytt\")\r\n \r\nsummen = 0\r\nfor linje in fila:\r\n try:\r\n summen += int(linje)\r\n except ValueError:\r\n print(\"Fant ei linje som ikke kan tolkes som et tall!\")\r\nfila.close()\r\nprint(f\"Summen ble: {summen}\")\r\n","sub_path":"10. Filer og exeptions (45-50)/tallfil_leser.py","file_name":"tallfil_leser.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"296278221","text":"\"\"\"\n给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。\n\n示例:\n输入: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"],\n输出:\n[\n [\"ate\",\"eat\",\"tea\"],\n [\"nat\",\"tan\"],\n [\"bat\"]\n]\n\n说明:\n所有输入均为小写字母。\n不考虑答案输出的顺序。\n\"\"\"\n\n\nclass Solution(object):\n def groupAnagrams(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: List[List[str]]\n \"\"\"\n di = {}\n for i in strs:\n tmp = ''.join(sorted(i))\n if tmp not in di:\n di[tmp] = [i]\n else:\n di[tmp].append(i)\n\n return list(di.values())\n","sub_path":"LeedCode/字符串/49. 字母异位词分组.py","file_name":"49. 字母异位词分组.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"129285184","text":"from tools.runTests import run_tests\nfrom tools.compileTests import compile_tests\nfrom tools.createTests import create_tests\nfrom tools.processStats import process_dir, stats_headers\nfrom tools.processLinStats import process_lin_stats, lin_stats_headers\nfrom pathlib import Path\n\n\nimport argparse\nimport time\nimport os\nimport sys\n\n\ncurr_dir = Path(os.path.realpath(__file__)).parents[1]\n\nmin_depth = 1\nmax_depth = 4\n\n# prepare result files\nresult_history = curr_dir.joinpath(\"results/table1.txt\")\nresult_schedule = curr_dir.joinpath(\"results/table2.txt\")\nresult_linear = curr_dir.joinpath(\"results/table3.txt\")\n\nBENCHMARKS =[\n (\"ArrayBlockingQueue\", \"ABQ\", \"java.util.concurrent.ArrayBlockingQueue\")\n ]\n\n\ndef main(selected_name):\n # prepare result files\n result_history = \"results/table1.txt\"\n result_schedule = \"results/table2.txt\"\n result_linear = \"results/table3.txt\"\n\n stats_headers(result_history, result_schedule)\n lin_stats_headers(result_linear)\n\n # 1. Create tests\n start_all = time.time()\n for (benchmark, name, classUnderTest) in BENCHMARKS:\n if selected_name and selected_name != name:\n continue\n\n startB = time.time()\n\n print(\"Creating linearizability checking tests for %s\" % benchmark)\n\n stat_subdir = \"stats%s\" % (name, )\n create_tests(classUnderTest,\n \"example/histories/%s\" % (benchmark, ),\n \"produced.test%s\" % (name, ),\n \"Test%s\" % (name, ),\n stat_subdir,\n \"Stat%s\" % (name, ),\n min_depth, max_depth + 1)\n\n # History and Schedule Results\n print(\"Writing history and schedule results: [%s] -> [%s, %s]\" % (benchmark, result_history, result_schedule))\n process_dir(name, os.path.join(\"stat\", stat_subdir), result_history, result_schedule)\n\n # Compile and test the generated .java files\n for d in range(min_depth, max_depth + 1):\n print(\"Compiling linearizability checking tests: [%s] [d=%s]\" % (benchmark, d))\n test_path = \"produced/test{0}/D{1}\".format(name, d)\n compile_tests(test_path)\n\n out_file = \"out/{0}/D{1}.txt\".format(name, d)\n print(\"Running linearizability checking tests:[%s] [d=%s]\" % (benchmark, d))\n run_tests(test_path, out_file)\n\n # Count linearizable histories:\n process_lin_stats(name, out_file, d, result_linear)\n\n endB = time.time()\n\n elapsedSec = endB - startB\n print(\"The linearizability tests are generated, compiled and ran for the benchmark %s \\n\" % benchmark)\n print(\"All Seconds for checking %s: %s\" % (benchmark, elapsedSec))\n print(\"All Minutes for checking %s: %s\" % (benchmark, elapsedSec / 60))\n\n endAll = time.time()\n elapsedSec = endAll - start_all\n print(\"All Seconds for all benchmarks: %s\" % elapsedSec)\n print(\"All Minutes for all benchnarks: %s\" % (elapsedSec / 60))\n\n\ndef sbt_create_tests():\n\n # Prepare results file name\n stats_headers(result_history, result_schedule)\n lin_stats_headers(result_linear)\n\n start = time.time()\n\n for (benchmark, name, classUnderTest) in BENCHMARKS:\n\n print(\"Creating linearizability checking tests for %s\" % benchmark)\n\n stat_subdir = \"stats%s\" % (name, )\n create_tests(classUnderTest,\n \"example/histories/%s\" % (benchmark, ),\n \"produced.test%s\" % (name, ),\n \"Test%s\" % (name, ),\n stat_subdir,\n \"Stat%s\" % (name, ),\n min_depth, max_depth + 1)\n\n # History and Schedule Results\n print(\"Writing history and schedule results: [%s] -> [%s, %s]\" % (benchmark, result_history, result_schedule))\n process_dir(name, os.path.join(curr_dir, \"stat\", stat_subdir), result_history, result_schedule)\n\n elapsed_secs = time.time() - start\n print(\"Test creation successful: %s\" % elapsed_secs)\n\n\ndef sbt_compile_tests():\n from subprocess import call\n start = time.time()\n for (benchmark, name, classUnderTest) in BENCHMARKS:\n # Compile and test the generated .java files\n all_java_files = ''\n for d in range(min_depth, max_depth + 1):\n\n test_path = \"produced/test{0}/D{1}\".format(name, d)\n all_java_files = ''.join((all_java_files, ' ', compile_tests(curr_dir.joinpath(test_path))))\n\n print(\"Compiling linearizability checking tests.\")\n call(\"javac -J-Xmx1000m -J-Xmx1000m {0}\".format(all_java_files), shell=True)\n\n elapsed_secs = time.time() - start\n print(\"Java files compiled successfully: %s\" % elapsed_secs)\n\n\ndef java_execute_tests():\n\n start = time.time()\n for (benchmark, name, classUnderTest) in BENCHMARKS:\n # Compile and test the generated .java files\n for d in range(min_depth, max_depth + 1):\n\n test_path = curr_dir\n java_class_path = \"produced/test{0}/D{1}\".format(name, d)\n out_file = curr_dir.joinpath(\"out/{0}/D{1}.txt\".format(name, d))\n print(\"Running Linearizability checking tests:[%s] [d=%s]\" % (benchmark, d))\n\n run_tests(java_class_path, test_path, out_file)\n\n # Count linearizable histories:\n process_lin_stats(name, out_file, d, result_linear)\n\n elapsed_secs = time.time() - start\n print(\"Java Linearizability tests successfully completed: %s\" % elapsed_secs)\n print(\"Please execute the operation \\\"plot_results\\\" to plot results\")\n\n\ndef set_project_root():\n for path in Path.cwd().parents:\n if path.name == 'check_lin':\n return path\n\n\ndef plot_results():\n import matplotlib.pyplot as plt\n from matplotlib.ticker import StrMethodFormatter\n import matplotlib.ticker as mtick\n header = None\n deph_data = []\n found_lin = []\n\n with open(result_linear, \"r\") as stats:\n for line in stats:\n values = line.split(\"\\t\")\n if values[0] == \"name\":\n header = line[1:]\n elif values[0] == \"ABQ\":\n deph_data.append(int(values[3].strip()))\n found_lin.append(int(int(values[4].strip())*100/15))\n\n plt.rc('font', size=12)\n plt.rc('axes', titlesize=16)\n plt.rc('axes', labelsize=13)\n\n fig, ax1 = plt.subplots(figsize=(6, 5))\n fig.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}'))\n ax1.yaxis.set_major_formatter(mtick.PercentFormatter())\n rects = ax1.bar(deph_data, found_lin, alpha=0.8)\n\n d1, d2, d3, d4 = rects\n\n autolabel(rects, ax1)\n\n d1.set_facecolor('#9aeda5')\n d2.set_facecolor('#53c262')\n d3.set_facecolor('#29ab3b')\n d4.set_facecolor('#128c23')\n\n plt.xticks(deph_data)\n plt.yticks(range(0,110,20))\n\n plt.ylabel('Linerializable traces encountered (%)')\n plt.xlabel('Search Hitting Families Depth (D)')\n\n plt.title('ArrayBlockingQueue Linearizability Results')\n\n plt.savefig('output.png')\n #plt.show()\n\n\ndef autolabel(rects,ax):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}%'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\n# Cleans all the extra files generated by running the experiment operations\ndef clean_all():\n import shutil\n\n produced_folder = curr_dir.joinpath(\"produced\")\n project_folder = curr_dir.joinpath(\"project\")\n results_folder = curr_dir.joinpath(\"results\")\n stat_folder = curr_dir.joinpath(\"stat\")\n target_folder = curr_dir.joinpath(\"target\")\n out_folder = curr_dir.joinpath(\"out\")\n\n if os.path.exists(produced_folder):\n print(\"The folder \\\"produced\\\" was successfully deleted!\")\n shutil.rmtree(produced_folder)\n\n if os.path.exists(project_folder):\n print(\"The folder \\\"project\\\" was successfully deleted!\")\n shutil.rmtree(project_folder)\n\n if os.path.exists(results_folder):\n print(\"The folder \\\"results\\\" was successfully deleted!\")\n shutil.rmtree(results_folder)\n\n if os.path.exists(stat_folder):\n print(\"The folder \\\"stat\\\" was successfully deleted!\")\n shutil.rmtree(stat_folder)\n\n if os.path.exists(target_folder):\n print(\"The folder \\\"target\\\" was successfully deleted!\")\n shutil.rmtree(target_folder)\n\n if os.path.exists(out_folder):\n print(\"The folder \\\"out\\\" was successfully deleted!\")\n shutil.rmtree(out_folder)\n\n\nif __name__ == '__main__':\n short_name = None\n if len(sys.argv) == 2:\n short_name = sys.argv[1]\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-o\", \"--operation\", help=\"Please, specify one operation!\", type=str, required=True)\n\n args = parser.parse_args()\n\n if args.operation == \"sbt_create_tests\":\n sbt_create_tests()\n elif args.operation == \"sbt_compile_tests\":\n sbt_compile_tests()\n elif args.operation == \"java_execute_tests\":\n java_execute_tests()\n elif args.operation == \"plot_results\":\n plot_results()\n elif args.operation == \"clean_all\":\n clean_all()\n else:\n print(\"The operation {} does not exist. Please make sure that you are using the correct operation.\".format(args.operation))\n","sub_path":"scripts/check_lin.py","file_name":"check_lin.py","file_ext":"py","file_size_in_byte":9507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"472242608","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom models.ResNet50Encoder import Bottleneck\n\n\nclass DeepLabClassificationHead(nn.Module):\n\n def __init__(self, num_classes):\n super().__init__()\n self.aspp = ASPP(2048, 256)\n self.low_level_feature_reducer = nn.Sequential(\n nn.Conv2d(256, 48, 1),\n nn.BatchNorm2d(48, momentum=0.0003),\n nn.ReLU(),\n )\n self.decoder = nn.Sequential(\n nn.Conv2d(256 + 48, 256, 3, padding=1),\n nn.BatchNorm2d(256, momentum=0.0003),\n nn.ReLU(),\n nn.Conv2d(256, 256, 3, padding=1),\n nn.BatchNorm2d(256, momentum=0.0003),\n nn.ReLU(),\n nn.Conv2d(256, num_classes, 3, padding=1),\n )\n self.classifier = nn.Sequential(\n nn.Flatten(),\n nn.Linear(7*7*256, num_classes),\n )\n\n\n def forward(self, x):\n # l2_size = tuple(x[\"block1\"].shape[-2:])\n # label_size = tuple(x[\"img\"].shape[-2:])\n\n x_backbone = x[\"block4\"].float()\n\n x_aspp = self.aspp(x_backbone)\n # x_aspp = nn.Upsample(l2_size, mode='bilinear', align_corners=True)(x_aspp)\n x = self.classifier(x_aspp)\n # x = torch.cat((self.low_level_feature_reducer(x[\"block1\"]), x_aspp), dim=1)\n # x = self.decoder(x)\n # x = nn.Upsample(label_size, mode='bilinear', align_corners=True)(x)\n return x\n\n def eval(self):\n # self.block4.eval()\n self.aspp.eval()\n self.decoder.eval()\n return self\n\n def train(self, mode=True):\n # self.block4.eval()\n self.aspp.train(mode)\n self.decoder.train(mode)\n return self\n\n def required_encoding(self):\n return [\"block4\"]\n\nclass ASPP(nn.Module):\n\n def __init__(self, C, depth, conv=nn.Conv2d, norm=nn.BatchNorm2d, momentum=0.0003, mult=1):\n super(ASPP, self).__init__()\n self._C = C\n self._depth = depth\n\n self.global_pooling = nn.AdaptiveAvgPool2d(1)\n self.relu = nn.ReLU(inplace=True)\n self.aspp1 = conv(C, depth, kernel_size=1, stride=1, bias=False)\n self.aspp2 = conv(C, depth, kernel_size=3, stride=1,\n dilation=int(6*mult), padding=int(6*mult),\n bias=False)\n self.aspp3 = conv(C, depth, kernel_size=3, stride=1,\n dilation=int(12*mult), padding=int(12*mult),\n bias=False)\n self.aspp4 = conv(C, depth, kernel_size=3, stride=1,\n dilation=int(18*mult), padding=int(18*mult),\n bias=False)\n self.aspp5 = conv(C, depth, kernel_size=1, stride=1, bias=False)\n self.aspp1_bn = norm(depth, momentum)\n self.aspp2_bn = norm(depth, momentum)\n self.aspp3_bn = norm(depth, momentum)\n self.aspp4_bn = norm(depth, momentum)\n self.aspp5_bn = norm(depth, momentum)\n self.conv2 = conv(depth * 5, depth, kernel_size=1, stride=1,\n bias=False)\n self.bn2 = norm(depth, momentum)\n\n def forward(self, x):\n x1 = self.aspp1(x)\n x1 = self.aspp1_bn(x1)\n x1 = self.relu(x1)\n x2 = self.aspp2(x)\n x2 = self.aspp2_bn(x2)\n x2 = self.relu(x2)\n x3 = self.aspp3(x)\n x3 = self.aspp3_bn(x3)\n x3 = self.relu(x3)\n x4 = self.aspp4(x)\n x4 = self.aspp4_bn(x4)\n x4 = self.relu(x4)\n x5 = self.global_pooling(x)\n x5 = self.aspp5(x5)\n x5 = self.aspp5_bn(x5)\n x5 = self.relu(x5)\n x5 = nn.Upsample((x.shape[2], x.shape[3]), mode='bilinear',\n align_corners=True)(x5)\n x = torch.cat((x1, x2, x3, x4, x5), 1)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n return x\n\n\nclass CascadeBlock(nn.Module):\n\n def __init__(self, block, planes, inplanes, blocks, stride=1, dilation=1):\n super(CascadeBlock, self).__init__()\n self.conv = nn.Conv2d\n # downsample = None\n # if stride != 1 or dilation != 1 or inplanes != planes * block.expansion:\n # downsample = nn.Sequential(\n # self.conv(inplanes, planes * block.expansion,\n # kernel_size=1, stride=stride, dilation=max(1, dilation // 2), bias=False),\n # self._make_norm(planes * block.expansion),\n # )\n #\n # layers = []\n # self.upsample_layer = block(inplanes, planes, stride, downsample, dilation=max(1, dilation // 2),\n # conv=self.conv, norm=self._make_norm)\n # inplanes = planes * block.expansion\n # for i in range(1, blocks):\n # layers.append(block(inplanes, planes, dilation=dilation, conv=self.conv, norm=self._make_norm))\n # self.conv = nn.Sequential(*layers)\n\n downsample = nn.Sequential(\n self.conv(inplanes, planes*block.expansion, kernel_size=1, stride=stride,\n dilation=dilation, bias=False),\n self._make_norm(planes * block.expansion),\n )\n self.upsample_layer = block(inplanes, planes, stride, downsample, dilation=dilation,\n conv=self.conv, norm=self._make_norm)\n inplanes = planes * block.expansion\n self.conv = nn.Sequential(\n block(inplanes, planes, dilation=dilation*2, conv=self.conv, norm=self._make_norm),\n block(inplanes, planes, dilation=dilation, conv=self.conv, norm=self._make_norm)\n )\n\n def forward(self, x, backbone=None):\n out = self.upsample_layer(x)\n if backbone is not None:\n out = out + backbone\n out = self.conv(out)\n return out\n\n def _make_norm(self, planes, momentum=0.05):\n return nn.BatchNorm2d(planes, momentum=momentum)\n","sub_path":"models/DeepLabClassificationHead.py","file_name":"DeepLabClassificationHead.py","file_ext":"py","file_size_in_byte":5911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"573629846","text":"words = [input() for _ in range(int(input()))]\n\nrepeat = dict()\nfor w in words:\n if repeat.get(w):\n repeat[w] += 1\n else:\n repeat[w] = 1\n\nprint(len(repeat.keys()))\nprint(' '.join(map(str,repeat.values())))\n","sub_path":"hackerrank/python/collections/word_order.py","file_name":"word_order.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"333956771","text":"import sys\nimport uuid\nfrom dataclasses import dataclass\nfrom dataclasses import field\nfrom dataclasses import fields\nfrom dataclasses import make_dataclass\nfrom typing import Dict\nfrom typing import get_type_hints\nfrom typing import Iterator\nfrom typing import List\nfrom typing import Type\nfrom typing import Union\nfrom unittest import mock\nfrom unittest import TestCase\n\nfrom tests.fixtures.artists import Artist\nfrom tests.fixtures.books import BookForm\nfrom tests.fixtures.series import Country\nfrom xsdata.exceptions import XmlContextError\nfrom xsdata.formats.dataclass.models.builders import XmlMetaBuilder\nfrom xsdata.formats.dataclass.models.builders import XmlVarBuilder\nfrom xsdata.formats.dataclass.models.elements import XmlType\nfrom xsdata.models.datatype import XmlDate\nfrom xsdata.utils import text\nfrom xsdata.utils.constants import return_input\nfrom xsdata.utils.constants import return_true\nfrom xsdata.utils.namespaces import build_qname\nfrom xsdata.utils.testing import FactoryTestCase\nfrom xsdata.utils.testing import XmlMetaFactory\nfrom xsdata.utils.testing import XmlVarFactory\n\n\nclass XmlMetaBuilderTests(FactoryTestCase):\n @mock.patch.object(XmlMetaBuilder, \"build_vars\")\n def test_build(self, mock_build_vars):\n var = XmlVarFactory.create(\n xml_type=XmlType.ELEMENT, name=\"foo\", qname=\"{foo}bar\", types=(int,)\n )\n mock_build_vars.return_value = [var]\n\n result = XmlMetaBuilder.build(Artist, None, return_input, return_input)\n expected = XmlMetaFactory.create(\n clazz=Artist,\n qname=\"{http://musicbrainz.org/ns/mmd-2.0#}artist\",\n elements={var.qname: [var]},\n )\n\n self.assertEqual(expected, result)\n mock_build_vars.assert_called_once_with(\n Artist, \"http://musicbrainz.org/ns/mmd-2.0#\", return_input, return_input\n )\n\n @mock.patch.object(XmlMetaBuilder, \"build_vars\", return_value=[])\n def test_build_with_parent_namespace(self, mock_build_vars):\n result = XmlMetaBuilder.build(\n Country, \"http://xsdata\", return_input, return_input\n )\n\n self.assertEqual(build_qname(\"http://xsdata\", \"country\"), result.qname)\n mock_build_vars.assert_called_once_with(\n Country, \"http://xsdata\", return_input, return_input\n )\n\n @mock.patch.object(XmlMetaBuilder, \"build_vars\", return_value=[])\n def test_build_with_no_meta_name_and_name_generator(self, *args):\n result = XmlMetaBuilder.build(BookForm, None, text.snake_case, return_input)\n\n self.assertEqual(\"book_form\", result.qname)\n\n def test_build_block_meta_inheritance(self):\n @dataclass\n class Bar:\n class Meta:\n name = \"bar\"\n\n @dataclass\n class Foo(Bar):\n pass\n\n @dataclass\n class Thug(Bar):\n class Meta:\n name = \"thug\"\n\n result = XmlMetaBuilder.build(Foo, None, return_input, return_input)\n self.assertEqual(\"Foo\", result.qname)\n\n result = XmlMetaBuilder.build(Thug, None, return_input, return_input)\n self.assertEqual(\"thug\", result.qname)\n\n def test_build_with_no_dataclass_raises_exception(self, *args):\n with self.assertRaises(XmlContextError) as cm:\n XmlMetaBuilder.build(int, None, return_input, return_input)\n\n self.assertEqual(f\"Type '{int}' is not a dataclass.\", str(cm.exception))\n\n def test_build_vars(self):\n result = XmlMetaBuilder.build_vars(BookForm, None, text.pascal_case, str.upper)\n self.assertIsInstance(result, Iterator)\n\n expected = [\n XmlVarFactory.create(\n xml_type=XmlType.ELEMENT,\n index=1,\n name=\"author\",\n qname=\"Author\",\n types=(str,),\n ),\n XmlVarFactory.create(\n xml_type=XmlType.ELEMENT,\n index=2,\n name=\"title\",\n qname=\"Title\",\n types=(str,),\n ),\n XmlVarFactory.create(\n xml_type=XmlType.ELEMENT,\n index=3,\n name=\"genre\",\n qname=\"Genre\",\n types=(str,),\n ),\n XmlVarFactory.create(\n xml_type=XmlType.ELEMENT,\n index=4,\n name=\"price\",\n qname=\"Price\",\n types=(float,),\n ),\n XmlVarFactory.create(\n xml_type=XmlType.ELEMENT,\n index=5,\n name=\"pub_date\",\n qname=\"PubDate\",\n types=(XmlDate,),\n ),\n XmlVarFactory.create(\n xml_type=XmlType.ELEMENT,\n index=6,\n name=\"review\",\n qname=\"Review\",\n types=(str,),\n ),\n XmlVarFactory.create(\n xml_type=XmlType.ATTRIBUTE, index=7, name=\"id\", qname=\"ID\", types=(str,)\n ),\n XmlVarFactory.create(\n xml_type=XmlType.ATTRIBUTE,\n index=8,\n name=\"lang\",\n qname=\"LANG\",\n types=(str,),\n init=False,\n default=\"en\",\n ),\n ]\n\n result = list(result)\n self.assertEqual(expected, result)\n for var in result:\n self.assertIsNone(var.clazz)\n\n def test_default_xml_type(self):\n cls = make_dataclass(\"a\", [(\"x\", int)])\n self.assertEqual(XmlType.TEXT, XmlMetaBuilder.default_xml_type(cls))\n\n cls = make_dataclass(\"b\", [(\"x\", int), (\"y\", int)])\n self.assertEqual(XmlType.ELEMENT, XmlMetaBuilder.default_xml_type(cls))\n\n cls = make_dataclass(\n \"c\", [(\"x\", int), (\"y\", int, field(metadata=dict(type=\"Text\")))]\n )\n self.assertEqual(XmlType.ELEMENT, XmlMetaBuilder.default_xml_type(cls))\n\n cls = make_dataclass(\n \"d\", [(\"x\", int), (\"y\", int, field(metadata=dict(type=\"Element\")))]\n )\n self.assertEqual(XmlType.TEXT, XmlMetaBuilder.default_xml_type(cls))\n\n with self.assertRaises(XmlContextError) as cm:\n cls = make_dataclass(\n \"e\",\n [\n (\"x\", int, field(metadata=dict(type=\"Text\"))),\n (\"y\", int, field(metadata=dict(type=\"Text\"))),\n ],\n )\n XmlMetaBuilder.default_xml_type(cls)\n\n self.assertEqual(\n \"Dataclass `e` includes more than one text node!\", str(cm.exception)\n )\n\n\nclass XmlVarBuilderTests(TestCase):\n def setUp(self) -> None:\n self.builder = XmlVarBuilder(\n default_xml_type=XmlType.ELEMENT,\n parent_ns=None,\n element_name_generator=return_input,\n attribute_name_generator=return_input,\n )\n\n super().setUp()\n\n def test_build_with_choice_field(self):\n globalns = sys.modules[CompoundFieldExample.__module__].__dict__\n type_hints = get_type_hints(CompoundFieldExample)\n class_field = fields(CompoundFieldExample)[0]\n\n builder = XmlVarBuilder(XmlType.ELEMENT, \"bar\", return_input, return_input)\n\n actual = builder.build(\n 66,\n \"compound\",\n type_hints[\"compound\"],\n class_field.metadata,\n True,\n list,\n globalns,\n )\n expected = XmlVarFactory.create(\n index=67,\n xml_type=XmlType.ELEMENTS,\n name=\"compound\",\n qname=\"compound\",\n list_element=True,\n any_type=True,\n default=list,\n elements={\n \"{foo}node\": XmlVarFactory.create(\n index=1,\n xml_type=XmlType.ELEMENT,\n name=\"compound\",\n qname=\"{foo}node\",\n list_element=True,\n types=(CompoundFieldExample,),\n namespaces=(\"foo\",),\n derived=False,\n ),\n \"{bar}x\": XmlVarFactory.create(\n index=2,\n xml_type=XmlType.ELEMENT,\n name=\"compound\",\n qname=\"{bar}x\",\n tokens=True,\n list_element=True,\n types=(str,),\n namespaces=(\"bar\",),\n derived=False,\n default=return_true,\n format=\"Nope\",\n ),\n \"{bar}y\": XmlVarFactory.create(\n index=3,\n xml_type=XmlType.ELEMENT,\n name=\"compound\",\n qname=\"{bar}y\",\n nillable=True,\n list_element=True,\n types=(int,),\n namespaces=(\"bar\",),\n derived=False,\n ),\n \"{bar}z\": XmlVarFactory.create(\n index=4,\n xml_type=XmlType.ELEMENT,\n name=\"compound\",\n qname=\"{bar}z\",\n nillable=False,\n list_element=True,\n types=(int,),\n namespaces=(\"bar\",),\n derived=True,\n ),\n \"{bar}o\": XmlVarFactory.create(\n index=5,\n xml_type=XmlType.ELEMENT,\n name=\"compound\",\n qname=\"{bar}o\",\n nillable=False,\n list_element=True,\n types=(object,),\n namespaces=(\"bar\",),\n derived=True,\n any_type=True,\n ),\n \"{bar}p\": XmlVarFactory.create(\n index=6,\n xml_type=XmlType.ELEMENT,\n name=\"compound\",\n qname=\"{bar}p\",\n types=(float,),\n list_element=True,\n namespaces=(\"bar\",),\n default=1.1,\n ),\n },\n wildcards=[\n XmlVarFactory.create(\n index=7,\n xml_type=XmlType.WILDCARD,\n name=\"compound\",\n qname=\"{http://www.w3.org/1999/xhtml}any\",\n types=(object,),\n namespaces=(\"http://www.w3.org/1999/xhtml\",),\n derived=True,\n any_type=False,\n list_element=True,\n )\n ],\n types=(object,),\n )\n self.assertEqual(expected, actual)\n\n def test_build_validates_result(self):\n with self.assertRaises(XmlContextError) as cm:\n self.builder.build(\n 1, \"foo\", List[int], {\"type\": \"Attributes\"}, True, None, None\n )\n\n self.assertEqual(\n \"Xml type 'Attributes' does not support typing: typing.List[int]\",\n str(cm.exception),\n )\n\n def test_resolve_namespaces(self):\n func = self.builder.resolve_namespaces\n self.builder.parent_ns = \"bar\"\n\n self.assertEqual((\"foo\",), func(XmlType.ELEMENT, \"foo\"))\n self.assertEqual((), func(XmlType.ELEMENT, \"\"))\n self.assertEqual((\"bar\",), func(XmlType.ELEMENT, None))\n\n self.assertEqual((), func(XmlType.ATTRIBUTE, None))\n\n self.assertEqual((\"bar\",), func(XmlType.WILDCARD, None))\n self.assertEqual((\"##any\",), func(XmlType.WILDCARD, \"##any\"))\n\n self.builder.parent_ns = \"\"\n self.assertEqual((\"##any\",), func(XmlType.WILDCARD, \"##targetNamespace\"))\n\n self.builder.parent_ns = None\n self.assertEqual((\"##any\",), func(XmlType.WILDCARD, \"##targetNamespace\"))\n\n self.builder.parent_ns = \"p\"\n self.assertEqual((\"p\",), func(XmlType.WILDCARD, \"##targetNamespace\"))\n self.assertEqual((\"\",), func(XmlType.WILDCARD, \"##local\"))\n self.assertEqual((\"!p\",), func(XmlType.WILDCARD, \"##other\"))\n self.assertEqual(\n (\"\", \"!p\"), tuple(sorted(func(XmlType.WILDCARD, \"##other ##local\")))\n )\n\n self.assertEqual(\n (\"foo\", \"p\"),\n tuple(sorted(func(XmlType.WILDCARD, \"##targetNamespace foo\"))),\n )\n\n def test_analyze_types(self):\n actual = self.builder.analyze_types(List[List[Union[str, int]]], None)\n self.assertEqual((list, list, (int, str)), actual)\n\n actual = self.builder.analyze_types(Union[str, int], None)\n self.assertEqual((None, None, (int, str)), actual)\n\n actual = self.builder.analyze_types(Dict[str, int], None)\n self.assertEqual((dict, None, (int, str)), actual)\n\n with self.assertRaises(XmlContextError) as cm:\n self.builder.analyze_types(List[List[List[int]]], None)\n\n self.assertEqual(\n \"Unsupported typing: typing.List[typing.List[typing.List[int]]]\",\n str(cm.exception),\n )\n\n def test_is_valid(self):\n # Attributes need origin dict\n self.assertFalse(\n self.builder.is_valid(XmlType.ATTRIBUTES, None, None, (), False, True)\n )\n\n # Attributes don't support any origin\n self.assertFalse(\n self.builder.is_valid(XmlType.ATTRIBUTES, dict, list, (), False, True)\n )\n\n # Attributes don't support xs:NMTOKENS\n self.assertFalse(\n self.builder.is_valid(XmlType.ATTRIBUTES, dict, None, (), True, True)\n )\n\n self.assertTrue(\n self.builder.is_valid(\n XmlType.ATTRIBUTES, dict, None, (str, str), False, True\n )\n )\n\n # xs:NMTOKENS need origin list\n self.assertFalse(\n self.builder.is_valid(XmlType.TEXT, dict, None, (), True, True)\n )\n\n # xs:NMTOKENS need origin list\n self.assertFalse(self.builder.is_valid(XmlType.TEXT, set, None, (), True, True))\n\n # Any type object is a superset, it's only supported alone\n self.assertFalse(\n self.builder.is_valid(\n XmlType.ELEMENT, None, None, (object, int), False, True\n )\n )\n\n # Type is not registered in converter.\n self.assertFalse(\n self.builder.is_valid(\n XmlType.TEXT, None, None, (int, uuid.UUID), False, True\n )\n )\n\n # init false vars are ignored!\n self.assertTrue(\n self.builder.is_valid(\n XmlType.TEXT, None, None, (int, uuid.UUID), False, False\n )\n )\n\n\n@dataclass\nclass CompoundFieldExample:\n\n compound: List[object] = field(\n default_factory=list,\n metadata={\n \"type\": \"Elements\",\n \"choices\": (\n {\n \"name\": \"node\",\n \"type\": Type[\"CompoundFieldExample\"],\n \"namespace\": \"foo\",\n },\n {\n \"name\": \"x\",\n \"type\": List[str],\n \"tokens\": True,\n \"default_factory\": return_true,\n \"format\": \"Nope\",\n },\n {\"name\": \"y\", \"type\": List[int], \"nillable\": True},\n {\"name\": \"z\", \"type\": List[int]},\n {\"name\": \"o\", \"type\": object},\n {\"name\": \"p\", \"type\": float, \"fixed\": True, \"default\": 1.1},\n {\n \"wildcard\": True,\n \"type\": object,\n \"namespace\": \"http://www.w3.org/1999/xhtml\",\n },\n ),\n },\n )\n","sub_path":"tests/formats/dataclass/models/test_builders.py","file_name":"test_builders.py","file_ext":"py","file_size_in_byte":15693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"335322015","text":"import requests\nfrom bs4 import BeautifulSoup\nimport lxml\nfrom flask import Flask\nfrom flask_restful import Resource, Api\nfrom sqlalchemy import create_engine\nfrom json import dumps\nfrom flask import jsonify\nimport flask_excel as excel\n\napp = Flask(__name__)\napi = Api(app)\n\nmyWebsiteUrl = ['https://www.mobile-mart.com.au/product/iphone-x-battery/',\n\t\t\t\t\t'https://www.mobile-mart.com.au/product/iphone-x-antenna-flex/',\n\t\t\t\t\t'https://www.mobile-mart.com.au/product/iphone-x-vibrator/',\n\t\t\t\t\t'https://www.mobile-mart.com.au/product/iphone-x-loud-speaker/',\n\t\t\t\t\t'https://www.mobile-mart.com.au/product/lcd-assembly-with-force-touch-panel-for-iphone-x-premium-quality/'\n\t\t\t\t\t]\n\ncompWebsitUrl = ['https://www.easyphix.com.au/battery-for-iphone-x',\n\t\t\t\t\t'https://www.easyphix.com.au/loud-speaker-for-iphone-x',\n\t\t\t\t\t'https://www.easyphix.com.au/vibrator-for-iphone-x',\n\t\t\t\t\t'https://www.easyphix.com.au/loud-speaker-for-iphone-x~40963',\n\t\t\t\t\t'https://www.easyphix.com.au/lcd-and-digitizer-touch-screen-assembly-for-iphone~44599'\n\t\t\t\t\t]\ndata = []\n\ndef getPageContent(url):\n\theaders = {'user-agent': 'Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0'}\n\tresult = requests.get(url, headers = headers)\n\tsrc = result.content\n\treturn BeautifulSoup(src, \"lxml\")\n\ndef getContent():\n\tfor idx,url in enumerate(myWebsiteUrl):\n\t\tmyPageContent = getPageContent(url)\n\t\tcompPageContent = getPageContent(compWebsitUrl[idx])\n\n\t\tdatas = [\n\t\t\tmyPageContent.select('.sku')[0].get_text(),\n\t\t\tmyPageContent.select('h2.product_title.entry-title.show-product-nav')[0].get_text(),\n\t\t\tmyPageContent.select('span.woocommerce-Price-amount.amount')[0].get_text(),\n\t\t\tcompPageContent.select('#specifications > table > tbody > tr:nth-child(1) > td:nth-child(2)')[0].get_text(),\n\t\t\tcompPageContent.select('.page-header > h1')[0].get_text(),\n\t\t\tcompPageContent.select('.productprice')[0].get_text()\n\t\t]\n\t\tdata.append(datas)\n\n@app.route('/')\ndef index():\n\tgetContent()\n\treturn jsonify(data)\n\n@app.route('/download')\ndef download():\n\treturn excel.make_response_from_array(data, \"csv\",file_name=\"export_data\")\n\nif __name__ == '__main__':\n\texcel.init_excel(app)\n\tapp.run()","sub_path":"compareprice.py","file_name":"compareprice.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"443711932","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport inspect\nfrom datetime import date as Date, datetime as Datetime\nfrom igor.jsutil import jsobj\nfrom igor.serialize import serialize_dict, serialize_object\n\n\n#----------------------------------------------------------------------------//\ndef serialize_locals(vars):\n from igor.serialize import kPrimitives\n ret = {}\n\n def dumpval(name, val):\n if isinstance(val, (Date, Datetime)):\n return val.isoformat()\n return val\n\n # Filter callables\n vars = dict((n, v) for n, v in vars.items() if not callable(v))\n for name, value in vars.items():\n if isinstance(value, kPrimitives):\n ret[name] = dumpval(name, value)\n elif isinstance(value, dict):\n ret[name] = serialize_dict(value, '*', dumpval)\n elif isinstance(value, object):\n # Check if it's not a file object, or the iterable serializer will\n # iterate over it and we'll get a bad behaviour\n if not(hasattr(value, 'flush') and hasattr(value, 'readline')):\n ret[name] = serialize_object(value, '*', dumpval)\n else:\n ret[name] = repr(value)\n\n return ret\n\n\n#----------------------------------------------------------------------------//\ndef process_frames(frames):\n dump = []\n for frame, filename, lineno, func, src, srcidx in frames:\n dump.append(jsobj.mkflat({\n 'filename': filename,\n 'lineno': lineno,\n 'func': func,\n 'srccontext': src[0],\n 'src': inspect.getsourcelines(frame),\n 'srcidx': srcidx,\n 'locals': serialize_locals(frame.f_locals)\n }))\n return dump\n\n\n#----------------------------------------------------------------------------//\ndef get_current_stack(context = 1):\n frame = inspect.currentframe().f_back\n framelist = []\n while frame:\n try:\n finfo = inspect.getframeinfo(frame, context)\n except:\n break\n\n framelist.append((frame,) + finfo)\n frame = frame.f_back\n return framelist\n\n\n#----------------------------------------------------------------------------//\ndef dump_stack(include_caller = True):\n \"\"\"\n :arg include_caller: If set to ``False`` it won't include the function\n calling ``dump_trace()`` withing\n \"\"\"\n stack = get_current_stack()\n #stack = inspect.stack()\n stack = stack[1 if include_caller else 2:]\n stack.reverse()\n return process_frames(stack)\n\n\n#----------------------------------------------------------------------------//\ndef dump_trace(include_caller = True):\n return process_frames(inspect.trace())\n\n\n#----------------------------------------------------------------------------//\ndef print_dump(dump):\n for f in dump:\n print('\\n')\n print('-' * 80)\n print(\"{0}:{1}: {2}\".format(f.filename, f.lineno, f.func))\n for line in f.src[0]:\n print('{0} {1}'.format(\n '>>>' if line == f.srccontext else '...',\n line.rstrip()\n ))\n\n print('\\nLocals:')\n for name, value in f.locals.items():\n print(' {0:15}: {1}'.format(name, value))\n","sub_path":"igor/util/pystack.py","file_name":"pystack.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"41593305","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 ('life_activity', '0005_auto_20151206_1209'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='step',\n name='step_minutes',\n field=models.IntegerField(default=15),\n ),\n ]\n","sub_path":"life_activity/migrations/0006_step_step_minutes.py","file_name":"0006_step_step_minutes.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"174760196","text":"import os\nimport subprocess\nimport sys\nimport time\nimport unittest\n\nimport tests.utils\n\n\nclass SubmitAtCoderTest(unittest.TestCase):\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_practice_1(self):\n\n url = 'https://atcoder.jp/contests/practice/tasks/practice_1'\n code = '''\\\n#include \nusing namespace std;\nint main() {\n int a; cin >> a;\n int b, c; cin >> b >> c;\n string s; cin >> s;\n cout << a + b + c << ' ' << s << endl;\n return 0;\n}\n'''\n files = [\n {\n 'path': 'main.cpp',\n 'data': code\n },\n ]\n\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 'submit', '-y', '--no-open', url, 'main.cpp'], stdout=sys.stdout, stderr=sys.stderr)\n\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_practice_2(self):\n\n url = 'https://atcoder.jp/contests/practice/tasks/practice_2'\n code = '''\\\n# Python Version: 3.x\nimport string\nimport sys\ndef quick_sort(s):\n if len(s) <= 1:\n return s\n pivot = s[0]\n lo, hi = '', ''\n for c in s[1 :]:\n print('?', pivot, c)\n sys.stdout.flush()\n if input() == '<':\n hi += c\n else:\n lo += c\n return quick_sort(lo) + pivot + quick_sort(hi)\nn, q = map(int, input().split())\nassert n == 26 and q == 1000\nprint('!', ''.join(quick_sort(string.ascii_uppercase[: n])))\n'''\n files = [\n {\n 'path': 'main.py',\n 'data': code\n },\n ]\n\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 'submit', '-y', '--no-open', url, 'main.py'], stdout=sys.stdout, stderr=sys.stderr)\n\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_practice_1_with_history(self):\n\n url = 'https://atcoder.jp/contests/practice/tasks/practice_1'\n files = [\n {\n 'path': 'a.pl',\n 'data': 'print<>+(<>=~$\",$`+$\\'),$\",<>'\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 'dl', url], stdout=sys.stdout, stderr=sys.stderr)\n subprocess.check_call([ojtools, 's', '-y', '--no-open', 'a.pl'], stdout=sys.stdout, stderr=sys.stderr)\n\n\nclass SubmitCodeforcesTest(unittest.TestCase):\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_beta_1_a(self):\n\n url = 'https://codeforces.com/contest/1/problem/A'\n code = '\\n'.join([\n '#!/usr/bin/env python3',\n 'h, w, a = map(int, input().split())',\n 'print(((h + a - 1) // a) * ((w + a - 1) // a))',\n '# ' + str(int(time.time())), # to bypass the \"You have submitted exactly the same code before\" error\n ]) + '\\n'\n files = [\n {\n 'path': 'a.py',\n 'data': code\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 's', '-y', '--no-open', url, 'a.py'], stdout=sys.stdout, stderr=sys.stderr)\n\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_beta_3_b(self):\n\n url = 'https://codeforces.com/contest/3/problem/B'\n code = r'''#include \n#define REP(i, n) for (int i = 0; (i) < (int)(n); ++ (i))\n#define ALL(x) begin(x), end(x)\nusing namespace std;\n\nint main() {\n // input\n int n, v; cin >> n >> v;\n vector > one;\n vector > two;\n REP (i, n) {\n int t, p; cin >> t >> p;\n if (t == 1) {\n one.emplace_back(p, i);\n } else {\n two.emplace_back(p, i, -1);\n }\n }\n\n // solve\n int sum_p = 0;\n vector used;\n sort(ALL(one));\n if (v % 2 == 1 and not one.empty()) {\n int p_i, i; tie(p_i, i) = one.back();\n one.pop_back();\n sum_p += p_i;\n used.push_back(i);\n v -= 1;\n }\n while (one.size() >= 2) {\n int p_i, i; tie(p_i, i) = one.back();\n one.pop_back();\n int p_j, j; tie(p_j, j) = one.back();\n one.pop_back();\n two.emplace_back(p_i + p_j, i, j);\n }\n if (one.size() == 1) {\n int p_i, i; tie(p_i, i) = one.back();\n two.emplace_back(p_i, i, -1);\n one.pop_back();\n }\n sort(ALL(two));\n while (v >= 2 and not two.empty()) {\n int p, i, j; tie(p, i, j) = two.back();\n two.pop_back();\n sum_p += p;\n used.push_back(i);\n if (j != -1) used.push_back(j);\n v -= 2;\n }\n\n // output\n cout << sum_p << endl;\n REP (i, used.size()) {\n cout << used[i] + 1 << (i + 1 < used.size() ? ' ' : '\\n');\n }\n return 0;\n}\n''' + '// ' + str(int(time.time())) + '\\n' # to bypass the \"You have submitted exactly the same code before\" error\n files = [\n {\n 'path': 'main.cpp',\n 'data': code\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 's', '-y', '--no-open', url, 'main.cpp'], stdout=sys.stdout, stderr=sys.stderr)\n\n\nclass SubmitYukicoderTest(unittest.TestCase):\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_9000(self):\n\n url = 'https://yukicoder.me/problems/no/9000'\n code = '\\n'.join([\n '#!/usr/bin/env python2',\n 'print \"Hello World!\"',\n ]) + '\\n'\n files = [\n {\n 'path': 'a.py',\n 'data': code\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 's', '-y', '--no-open', url, 'a.py'], stdout=sys.stdout, stderr=sys.stderr)\n\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_beta_3_b(self):\n\n url = 'https://yukicoder.me/problems/527'\n code = r'''#include \nusing namespace std;\nint main() {\n int a, b; cin >> a >> b;\n string s; cin >> s;\n cout << a + b << ' ' << s << endl;\n return 0;\n}\n'''\n files = [\n {\n 'path': 'main.cpp',\n 'data': code\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 's', '-y', '--no-open', url, 'main.cpp'], stdout=sys.stdout, stderr=sys.stderr)\n\n\nclass SubmitHackerRankTest(unittest.TestCase):\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_worldcodesprint_mars_exploration(self):\n url = 'https://www.hackerrank.com/contests/worldcodesprint/challenges/mars-exploration'\n code = '''#!/usr/bin/env python3\ns = input()\nans = 0\nfor i in range(len(s) // 3):\n if s[3 * i] != 'S':\n ans += 1\n if s[3 * i + 1] != 'O':\n ans += 1\n if s[3 * i + 2] != 'S':\n ans += 1\nprint(ans)\n'''\n files = [\n {\n 'path': 'a.py',\n 'data': code\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 's', '-y', '--no-open', url, 'a.py'], stdout=sys.stdout, stderr=sys.stderr)\n\n\nclass SubmitTophTest(unittest.TestCase):\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_copycat(self):\n url = 'https://toph.co/p/copycat'\n code = '''#!/usr/bin/env python3\ns = input()\nprint(s)\n'''\n files = [\n {\n 'path': 'a.py',\n 'data': code\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 's', '-l', '58482c1804469e2585024324', '-y', '--no-open', url, 'a.py'], stdout=sys.stdout, stderr=sys.stderr)\n\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_add_them_up(self):\n url = 'https://toph.co/p/add-them-up'\n code = '''#!/usr/bin/env python3\nnums = map(int, input().split())\nprint(sum(nums))\n'''\n files = [\n {\n 'path': 'a.py',\n 'data': code\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 's', '-l', '58482c1804469e2585024324', '-y', '--no-open', url, 'a.py'], stdout=sys.stdout, stderr=sys.stderr)\n\n @unittest.skipIf('CI' in os.environ, 'login is required')\n def test_call_submit_divisors(self):\n url = 'https://toph.co/p/divisors'\n code = '''#include\nusing namespace std;\nint main()\n{\n int a;\n cin>>a;\n for (int i=1;i<=a;i++)\n {\n if (a%i==0)\n {\n cout <\nusing namespace std;\n\ntypedef long long int LL;\nconst int MOD = 993344777;\nconst int N = 1e6 + 1;\n\nint n;\nint a[ N ];\nint cnt[ 62 ];\nint mask[ 62 ];\nvector prime;\nint id[ 62 ];\nLL dp[ 62 ][ ( 1 << 17 ) + 1 ][ 2 ][ 2 ];\n\nbool isprime( int x ) {\n for( int i = 2; i*i <= x; i++ ) if( x%i == 0 ) return false;\n return true;\n}\nLL solve( int cur , int msk , int sz , int taken ) {\n if( cur == 61 ) {\n if( !taken ) return 0;\n if( sz&1 ) return msk != 0;\n else return msk == 0;\n }\n if( dp[cur][msk][sz][taken] != -1 ) return dp[cur][msk][sz][taken] ;\n LL ret = 0;\n if( cnt[cur] == 0 ) {\n ret = ( ret%MOD + solve( cur + 1 , msk , sz%2 , taken )%MOD )%MOD;\n }\n else {\n ret = ( ret%MOD + cnt[cur]%MOD * solve( cur + 1 , msk^mask[cur] , (sz%2+1%2)%2 , 1 )%MOD )%MOD;\n ret = ( ret%MOD + solve( cur + 1 , msk , sz%2 , taken )%MOD )%MOD;\n }\n return dp[cur][msk][sz][taken] = ret%MOD;\n}\nint main( int argc , char const *argv[] ) {\n scanf(\"%d\",&n);\n for( int i = 1; i <= n; i++ ) scanf(\"%d\",&a[i]) , cnt[ a[i] ]++;\n prime.push_back( 2 );\n int t = 0;\n id[2] = ++t;\n for( int i = 3; i <= 60; i += 2 ) {\n if( isprime( i ) ) prime.push_back( i ) , id[i] = ++t;\n }\n for( int i = 1; i <= 60; i++ ) {\n int num = i;\n for( auto x : prime ) {\n if( num%x == 0 ) {\n mask[i] ^= ( 1 << id[x] );\n num /= x;\n while( num%x == 0 ) num /= x , mask[i] ^= ( 1 << id[x] );\n }\n }\n if( num != 1 ) mask[i] ^= ( 1 << id[num] );\n }\n memset( dp , -1 , sizeof( dp ) );\n cout << solve( 1 , 0 , 0 , 0 )%MOD << endl;\n return 0;\n}\n'''\n files = [\n {\n 'path': 'a.cpp',\n 'data': code\n },\n ]\n ojtools = os.path.abspath('oj')\n with tests.utils.sandbox(files):\n subprocess.check_call([ojtools, 's', '-y', '--no-open', url, 'a.cpp'], stdout=sys.stdout, stderr=sys.stderr)\n","sub_path":"tests/command_submit.py","file_name":"command_submit.py","file_ext":"py","file_size_in_byte":11923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"109529119","text":"import threading\nimport pytest\n\nfrom utils.classes import Publisher, Consumer, ConnectorInfo\n\n\nclass TestClass(object):\n\n @staticmethod\n def stp(timeout):\n con_info = ConnectorInfo()\n publisher = Publisher()\n consumer = Consumer()\n\n consumer.setup(con_info, timeout=timeout)\n publisher.setup(con_info)\n\n return consumer, publisher\n\n @staticmethod\n def run(consumer, publisher, cur_name, callback):\n concumer_thread = threading.Thread(target=consumer.consume, args=(callback,))\n publisher_thread = threading.Thread(target=publisher.send, args=(cur_name,))\n\n concumer_thread.start()\n publisher_thread.start()\n\n publisher_thread.join()\n\n return concumer_thread, publisher_thread\n\n @staticmethod\n def run2(consumer, publisher, cur_name, callback, time):\n\n consumer_thread = threading.Thread(target=consumer.consume, args=(callback,))\n\n consumer_thread.start()\n publisher.send(cur_name)\n\n return consumer_thread\n\n @staticmethod\n def trdwn(consumer, publisher, need_del_result=False):\n\n consumer.close()\n publisher.close()\n\n if need_del_result:\n global result\n result = {}\n\n\n\n\nif __name__ == '__main__':\n\n\n #given\n c, p = TestClass.stp(2)\n\n def callback(ch, method, properties, body):\n msg = body.decode('utf-8')\n\n global result\n result = msg\n\n TestClass.trdwn(c, p)\n\n #twhen\n cT = TestClass.run2(c, p, \"CUR_1\", callback, 3)\n print(result)\n\n #then\n TestClass.trdwn(c, p, True)\n\n","sub_path":"test_r_d_fm.py","file_name":"test_r_d_fm.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"197153429","text":"\"\"\"\n\n\"\"\"\nclass Solution:\n def numberOfArrays(self, s: str, k: int) -> int:\n dp = [0] * (len(s) + 1)\n dp[-1] = 1\n temp = \"\"\n for i in range(len(s)-1, -1, -1):\n if s[i] == '0':\n continue\n n = 0\n for j in range(1, len(s)-i+1):\n n = n * 10 + ord(s[i+j-1]) - ord('0')\n if n > k:\n break\n dp[i] += dp[i+j]\n dp[i] = dp[i] % (10**9+7)\n return dp[0]\n \n","sub_path":"DP/1416. Restore The Array.py","file_name":"1416. Restore The Array.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"484146200","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 11/19/2018 10:45 AM\n# @Author : ZackChao\n# @Site : \n# @File : 0000.py\n# @Software: PyCharm'\n\n\n#第 0001 题: 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?\n# 分析:\n# 激活码、优惠券 一串number+str\n# 激活码长度 length\n# 200个 数量 num\n\n\nimport random\n\ndef make_number(num,length):\n str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\n # chars=string.letters+string.digits\n b=set()\n\n i=0\n while i` to change subscription\" +\n (f\", or `{command.prefix()}unsub` to unsubscribe\" if subscription else \"\") +\n \".\"\n )\n await command.respond(content, embed=embed)\n return\n\n if not await validate_filter(command, _filter, filter_context):\n return # `validate_filter` will respond for us.\n\n subscribe(command.context.channel, _filter)\n\n embed = Embed()\n embed.colour = Colour.from_rgb(255, 170, 50)\n embed.add_field(\n name=\"🔔\\u2000Subscribed to\",\n value=f\"\"\"\n {escape_markdown(_filter)}\n `{expand(_filter)}`\n \"\"\"\n )\n\n await command.respond(\"✓\", embed=embed)","sub_path":"bot/cmd_modules/cmd_sub.py","file_name":"cmd_sub.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"416546611","text":"class Solution(object):\n def isAlienSorted(self, words, order):\n \"\"\"\n :type words: List[str]\n :type order: str\n :rtype: bool\n \"\"\"\n order_map = {}\n for index, val in enumerate(order):\n order_map[val] = index\n\n for i in range(len(words)-1):\n\n letter = 0\n while letter + 1 < min(len(words[i]), len(words[i+1])) and words[i][letter] == words[i+1][letter]:\n letter += 1\n\n # Check if tie breaking letter breaks order\n if order_map[words[i][letter]] > order_map[words[i+1][letter]]:\n return False\n # If it's all tied, BUT first element is longer then it is still a fail\n elif order_map[words[i][letter]] == order_map[words[i+1][letter]] and len(words[i]) > len(words[i+1]):\n return False\n\n return True\n\n \n\n\nz = Solution()\nwords = [\"apple\",\"app\"]\norder = \"abcdefghijklmnopqrstuvwxyz\"\nprint(z.isAlienSorted(words, order))","sub_path":"Leetcode/953.verifying-an-alien-dictionary.py","file_name":"953.verifying-an-alien-dictionary.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"547691724","text":"# exh_example.py\n# Copyright (c) 2013-2016 Pablo Acosta-Serafini\n# See LICENSE for details\n# pylint: disable=C0111,C0302,W0212,W0640\n\nfrom __future__ import print_function\nimport putil.exh\n\nEXHOBJ = putil.exh.ExHandle()\n\ndef my_func(name):\n \"\"\" Sample function \"\"\"\n EXHOBJ.add_exception(\n exname='illegal_name',\n extype=TypeError,\n exmsg='Argument `name` is not valid'\n )\n EXHOBJ.raise_exception_if(\n exname='illegal_name',\n condition=not isinstance(name, str)\n )\n print('My name is {0}'.format(name))\n","sub_path":"docs/support/exh_example.py","file_name":"exh_example.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"42468438","text":"#!/usr/bin/python3\n\nfrom . import factory, path\nfrom .action import Action\nfrom .definition import Definition\nfrom .environment import Environment\nfrom .revision import Revision\n\nimport codecs\nimport json\nimport os\nimport shutil\nimport tempfile\n\n\ndef _read_json(base_path, json_or_path, default):\n # Input looks like a JSON object\n if json_or_path[0:1] == '{':\n contents = json_or_path\n file_name = None\n\n # Otherwise consider it as a file path\n else:\n file_name = json_or_path[0:1] == '@' and json_or_path[1:] or json_or_path\n file_path = os.path.join(base_path, file_name)\n\n if not os.path.isfile(file_path):\n return (default, None)\n\n reader = codecs.getreader('utf-8')\n\n with open(file_path, 'rb') as file:\n contents = reader(file).read()\n\n return (json.loads(contents), file_name)\n\n\nclass Deployer:\n def __init__(self, logger, definition, environment, yes):\n self.definition = definition\n self.environment = environment\n self.logger = logger\n self.yes = yes\n\n def deploy(self, base_path, names, append_files, remove_files, rev_from, rev_to):\n # Ensure base directory is valid\n if not os.path.isdir(base_path):\n self.logger.error('Base directory \"{0}\" doesn\\'t exist.'.format(base_path))\n\n return False\n\n ignores = []\n\n # Load environment configuration from command line argument or file\n (environment_config, environment_name) = _read_json(base_path, self.environment, None)\n\n if environment_config is None:\n self.logger.error('Environment file \"{0}\" doesn\\'t exist.'.format(file_path))\n\n return False\n\n if environment_name is not None:\n ignores.append(environment_name)\n\n environment = Environment(self.logger, environment_config)\n\n # Read definition configuration from command line argument or file\n (definition_config, definition_name) = _read_json(base_path, self.definition, {})\n\n if definition_name is not None:\n ignores.append(definition_name)\n\n definition = Definition(self.logger, definition_config, ignores)\n\n # Expand location names\n if len(names) < 1:\n names.append('default')\n elif len(names) == 1 and names[0] == '*':\n names = environment.locations.keys()\n\n # Deploy to target locations\n ok = True\n\n for name in names:\n location = environment.get_location(name)\n\n if location is None:\n self.logger.warning('There is no location \"{0}\" in your environment file.'.format(name))\n\n continue\n\n if location.connection is not None:\n self.logger.info('Deploying to location \"{0}\"...'.format(name))\n\n if not self.sync(base_path, definition, location, name, append_files, remove_files, rev_from, rev_to):\n ok = False\n\n continue\n\n for cascade_path, cascade_names in location.cascades.items():\n full_path = os.path.join(base_path, cascade_path)\n\n self.logger.info('Cascading to path \"{0}\"...'.format(full_path))\n self.logger.enter()\n\n ok = self.deploy(full_path, cascade_names, [], [], None, None) and ok\n\n self.logger.leave()\n\n return ok\n\n def prompt(self, question):\n if self.yes:\n return True\n\n self.logger.info(question)\n\n while True:\n answer = input()\n\n if answer == 'N' or answer == 'n':\n return False\n elif answer == 'Y' or answer == 'y':\n return True\n\n self.logger.warning('Invalid answer')\n\n def sync(self, base_path, definition, location, name, append_files, remove_files, rev_from, rev_to):\n # Build source repository reader from current directory and target from location connection string\n source = factory.create_source(self.logger, definition.source, definition.options, base_path)\n target = factory.create_target(self.logger, location.connection, location.options, base_path)\n\n if source is None or target is None:\n return False\n\n # Read revision file\n if not location.local:\n data = target.read(self.logger, location.state)\n elif os.path.exists(os.path.join(base_path, location.state)):\n data = open(os.path.join(base_path, location.state), 'rb').read()\n else:\n data = ''\n\n if data is None:\n self.logger.error(\n 'Can\\'t read revision file \"{0}\", check connection string and ensure parent directory exists.'.format(\n location.state))\n\n return False\n\n try:\n revision = Revision(data)\n except Exception as e:\n self.logger.error('Can\\'t parse revision from file \"{0}\": {1}.'.format(location.state, e))\n\n return False\n\n # Retrieve source and target revision\n if rev_from is None:\n rev_from = revision.get(name)\n\n if rev_from is None and not self.prompt(\n 'No current revision found, are you deploying for the first time? [Y/N]'):\n return True\n\n if rev_to is None:\n rev_to = source.current(base_path)\n\n if rev_to is None:\n self.logger.error(\n 'Can\\'t find source version, please ensure your environment file is correctly defined.')\n\n return False\n\n revision.set(name, rev_to)\n\n # Prepare actions\n work_path = tempfile.mkdtemp()\n\n try:\n # Append actions from revision diff\n source_actions = source.diff(self.logger, base_path, work_path, rev_from, rev_to)\n\n if source_actions is None:\n return False\n\n # Append actions for manually specified files\n manual_actions = []\n\n for append in location.append_files + append_files:\n full_path = os.path.join(base_path, append)\n\n if os.path.isdir(full_path):\n for (dirpath, dirnames, filenames) in os.walk(full_path):\n parent_path = os.path.relpath(dirpath, base_path)\n\n manual_actions.extend(\n (Action(os.path.join(parent_path, filename), Action.ADD) for filename in filenames))\n elif os.path.isfile(full_path):\n manual_actions.append(Action(append, Action.ADD))\n else:\n self.logger.warning('Can\\'t append missing file \"{0}\".'.format(append))\n\n for action in manual_actions:\n if not path.duplicate(os.path.join(base_path, action.path), work_path, action.path):\n self.logger.warning('Can\\'t copy file \"{0}\".'.format(action.path))\n\n for remove in location.remove_files + remove_files:\n full_path = os.path.join(base_path, remove)\n\n if os.path.isdir(full_path):\n for (dirpath, dirnames, filenames) in os.walk(full_path):\n parent_path = os.path.relpath(dirpath, base_path)\n\n manual_actions.extend(\n (Action(os.path.join(parent_path, filename), Action.DEL) for filename in filenames))\n else:\n manual_actions.append(Action(remove, Action.DEL))\n\n # Apply pre-processing modifiers on actions\n actions = []\n used = set()\n\n for command in source_actions + manual_actions:\n actions.extend(definition.apply(work_path, command.path, command.type, used))\n\n # Update current revision (remote mode)\n if rev_from != rev_to and not location.local:\n with open(os.path.join(work_path, location.state), 'wb') as file:\n file.write(revision.serialize().encode('utf-8'))\n\n actions.append(Action(location.state, Action.ADD))\n\n # Display processed actions using console target\n if len(actions) < 1:\n self.logger.info('No deployment required.')\n\n return True\n\n from .targets.console import ConsoleTarget\n\n console = ConsoleTarget()\n console.send(self.logger, work_path, actions)\n\n if not self.prompt('Deploy? [Y/N]'):\n return True\n\n # Execute processed actions after ordering them by precedence\n actions.sort(key=lambda action: (action.order(), action.path))\n\n if not target.send(self.logger, work_path, actions):\n return False\n\n # Update current revision (local mode)\n if location.local:\n with open(os.path.join(base_path, location.state), 'wb') as file:\n file.write(revision.serialize().encode('utf-8'))\n\n finally:\n shutil.rmtree(work_path)\n\n self.logger.info('Deployment done.')\n\n return True\n\n\n# Hack for Python 2 + 3 compatibility\ntry:\n input = raw_input\nexcept NameError:\n pass\n","sub_path":"creep/src/deployer.py","file_name":"deployer.py","file_ext":"py","file_size_in_byte":9234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"467644650","text":"import os\nimport sys\nimport json\nimport torch\nfrom pathlib import Path\nfrom azureml.pipeline.wrapper.dsl.module import ModuleExecutor, InputDirectory, OutputDirectory\nfrom azureml.pipeline.wrapper import dsl\nfrom utils import load_dataset, DataIter, test\n\n\n@dsl.module(\n name=\"FastText Evaluation\",\n version='0.0.4',\n description='Evaluate the trained FastText model'\n)\ndef fasttext_evaluation(\n model_testing_result: OutputDirectory(type='AnyDirectory'),\n trained_model_dir: InputDirectory(type='AnyDirectory') = None,\n test_data_dir: InputDirectory(type='AnyDirectory') = None,\n char2index_dir: InputDirectory(type='AnyDirectory') = None\n):\n print('=====================================================')\n print(f'trained_model_dir: {Path(trained_model_dir).resolve()}')\n print(f'test_data_dir: {Path(test_data_dir).resolve()}')\n print(f'char2index_dir: {Path(char2index_dir).resolve()}')\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n max_len_ = 38\n path = os.path.join(test_data_dir, 'test.txt')\n test_samples = load_dataset(file_path=path, max_len=max_len_, char2index_dir=char2index_dir)\n\n test_iter = DataIter(test_samples)\n\n path = os.path.join(trained_model_dir, 'BestModel')\n model = torch.load(f=path)\n\n path = os.path.join(model_testing_result, 'result.json')\n acc_ = test(model, test_iter, device)\n json.dump({\"acc\": acc_}, open(path, 'w'))\n print('\\n============================================')\n\n\nif __name__ == '__main__':\n ModuleExecutor(fasttext_evaluation).execute(sys.argv)","sub_path":"fasttext_evaluation/fasttext_evaluation.py","file_name":"fasttext_evaluation.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"401893002","text":"\nfrom typing import List\n\n\nNB_ROOT = './notebooks'\nNB_PATHS = './scripts/notebook_paths.txt'\n\n\ndef check_file(filename: str, goal_names: List[str]) -> None:\n with open(filename, encoding='utf-8') as f:\n content: str = f.read()\n for line in content.split('\\n'):\n if '(goal=\\\\\"' in line:\n name = line.split('\"')[2].strip('\\\\')\n if name in goal_names:\n raise ValueError(\n f'Found multiple quizzes with goal name \"{name}\"'\n )\n else:\n goal_names.append(name)\n\n\nif __name__ == '__main__':\n goal_names: List[str] = []\n with open(NB_PATHS, encoding='utf-8') as f:\n file_names: List[str] = f.readlines()\n for filename in file_names:\n if not filename.strip():\n # blank line\n continue\n if filename.startswith('#'):\n print(f'Skipping: {filename}')\n else:\n print(f'Goals check: {filename}')\n check_file(f'{NB_ROOT}/{filename.strip()}.ipynb', goal_names)\n","sub_path":"scripts/goals.py","file_name":"goals.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"512245893","text":"import os\nimport unittest\nimport requests\nfrom lxml import etree\n\nimport src.data_test_develop as dtd\nimport config.constants as constant\n\nclass TestMlsMethods(unittest.TestCase):\n\n def setUp(self):\n self.test_valid = '{}/test/config/single_record_valid.xml'.format(os.getcwd())\n self.test_invalid = '{}/test/config/single_record_invalid.xml'.format(os.getcwd())\n\n def test_xml_data(self):\n response = requests.get(constant.CONST_MLS_URL)\n self.assertEqual(response.status_code, 200)\n\n def test_process_mls_xml_valid(self):\n context = etree.iterparse(self.test_valid, events=(\"end\",), tag='Listing')\n\n for event, elem in context:\n df = dtd.process_mls_xml(elem)\n self.assertIsNotNone(df)\n\n def test_process_mls_xml_invalid(self):\n context = etree.iterparse(self.test_invalid, events=(\"end\",), tag='Listing')\n\n for event, elem in context:\n df = dtd.process_mls_xml(elem)\n self.assertIsNone(df)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_mls.py","file_name":"test_mls.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"229317176","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 6 19:01:55 2016\n\n@author: aitor\n\"\"\"\n\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Flatten, Dense, Dropout, Lambda, ELU\nfrom keras.layers.convolutional import Convolution2D\n\n#Based on:\n# 75% NVIDIA's end-to-end paper: https://arxiv.org/pdf/1604.07316v1.pdf\n# 25% Comma.ai research: https://github.com/commaai/research/blob/master/SelfSteering.md\ndef getNNModel(model_path=None, reg_lambda=0.0):\n \n if model_path:\n model = load_model(model_path)\n else:\n\n ch, width, height = 3, 200, 66\n \n model = Sequential()\n model.add(Lambda(lambda x: x/127.5 - 1., input_shape=(height, width, ch), output_shape=(height, width, ch)))\n \n model.add(Convolution2D(24, 5, 5, subsample=(2,2), border_mode='same', init='he_normal', name='conv1'))\n model.add(ELU())\n #model.add(MaxPooling2D((2,2)))\n \n model.add(Convolution2D(36, 5, 5, subsample=(2,2), border_mode='same', init='he_normal', name='conv2'))\n model.add(ELU())\n #model.add(MaxPooling2D((2,2), strides=(2,2)))\n #model.add(MaxPooling2D((2,2)))\n \n model.add(Convolution2D(48, 5, 5, subsample=(2,2), border_mode='same', init='he_normal', name='conv3'))\n model.add(ELU())\n #model.add(MaxPooling2D((2,2), strides=(2,2)))\n #model.add(MaxPooling2D((2,2)))\n \n model.add(Convolution2D(64, 3, 3, border_mode='same', init='he_normal', name='conv4'))\n model.add(ELU())\n #model.add(MaxPooling2D((2,2), strides=(2,2)))\n #model.add(MaxPooling2D((2,2)))\n \n model.add(Convolution2D(64, 3, 3, border_mode='same', init='he_normal', name='conv5'))\n #model.add(MaxPooling2D((2,2), strides=(2,2)))\n #model.add(MaxPooling2D((2,2)))\n \n model.add(Flatten())\n model.add(ELU())\n model.add(Dropout(0.2))\n \n model.add(Dense(100, init='he_normal', name='dense_1'))\n model.add(ELU())\n model.add(Dropout(0.5))\n model.add(Dense(50, init='he_normal', name='dense_2'))\n model.add(ELU())\n model.add(Dropout(0.5))\n model.add(Dense(10, init='he_normal', name='dense_3'))\n model.add(ELU())\n model.add(Dropout(0.5))\n model.add(Dense(1, init='he_normal', name='output'))\n\n return model\n","sub_path":"ai-tor/nnmodel.py","file_name":"nnmodel.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"414136905","text":"import numpy as np\nimport gym\nimport json\n\n\n\nfrom matplotlib import pyplot\nfrom matplotlib.ticker import FuncFormatter\nfrom keras.models import model_from_json\n\n\n### batch size comparison: 32, 64, 96, fixed: Boltzman0.8, 0.1, lr=0.01\n\n\nwith open('save/history5_2018-07-04 14:29:38', 'r') as f:\n pp1_1 = json.load(f)\n f.close()\n\nwith open('save/history5_2018-07-04 14:29:54', 'r') as f:\n pp1_2 = json.load(f)\n f.close()\n\nwith open('save/history5_2018-07-04 14:30:10', 'r') as f:\n pp1_3 = json.load(f)\n f.close()\n\n\nwith open('save/history3_2018-07-04 10:28:40', 'r') as f:\n pp2_1 = json.load(f)\n f.close()\n\nwith open('save/history3_2018-07-04 10:30:46', 'r') as f:\n pp2_2 = json.load(f)\n f.close()\n\nwith open('save/history3_2018-07-04 10:31:26', 'r') as f:\n pp2_3 = json.load(f)\n f.close()\n\n\nwith open('save/history4_2018-07-04 10:17:11', 'r') as f:\n pp3_1 = json.load(f)\n f.close()\n\nwith open('save/history4_2018-07-04 10:17:45', 'r') as f:\n pp3_2 = json.load(f)\n f.close()\n\nwith open('save/history4_2018-07-04 10:23:04', 'r') as f:\n pp3_3 = json.load(f)\n f.close()\n\n\nduration1 = (sum(pp1_1['duration'])+sum(pp1_2['duration'])+sum(pp1_3['duration']))/3\nduration2 = (sum(pp2_1['duration'])+sum(pp2_2['duration'])+sum(pp2_3['duration']))/3\nduration3 = (sum(pp3_1['duration'])+sum(pp3_2['duration'])+sum(pp3_3['duration']))/3\n\nprint('Duration1:{}, Duration2:{}, Duration3:{}'.format(duration1,duration2,duration3))\n\ner_ave1 = [(pp1_1['episode_reward'][i] + pp1_2['episode_reward'][i]+pp1_3['episode_reward'][i])/3 for i in range(len(pp1_1['episode_reward']))]\ner_ave2 = [(pp2_1['episode_reward'][i] + pp2_2['episode_reward'][i]+pp2_3['episode_reward'][i])/3 for i in range(len(pp2_1['episode_reward']))]\ner_ave3 = [(pp3_1['episode_reward'][i] + pp3_2['episode_reward'][i]+pp3_3['episode_reward'][i])/3 for i in range(len(pp3_1['episode_reward']))]\n#er_ave4 = [(pp4_1['episode_reward'][i] + pp4_2['episode_reward'][i]+pp4_3['episode_reward'][i]+pp4_4['episode_reward'][i]+pp4_5['episode_reward'][i])/5 for i in range(len(pp4_1['episode_reward']))]\n\nst_ave1 = [(pp1_1['nb_steps'][i] + pp1_2['nb_steps'][i]+pp1_3['nb_steps'][i])/3 for i in range(len(pp1_1['nb_steps']))]\nst_ave2 = [(pp2_1['nb_steps'][i] + pp2_2['nb_steps'][i]+pp2_3['nb_steps'][i])/3 for i in range(len(pp2_1['nb_steps']))]\nst_ave3 = [(pp3_1['nb_steps'][i] + pp3_2['nb_steps'][i]+pp3_3['nb_steps'][i])/3 for i in range(len(pp3_1['nb_steps']))]\n\nest_ave1 = [(pp1_1['nb_episode_steps'][i] + pp1_2['nb_episode_steps'][i]+pp1_3['nb_episode_steps'][i])/3 for i in range(len(pp1_1['nb_episode_steps']))]\nest_ave2 = [(pp2_1['nb_episode_steps'][i] + pp2_2['nb_episode_steps'][i]+pp2_3['nb_episode_steps'][i])/3 for i in range(len(pp2_1['nb_episode_steps']))]\nest_ave3 = [(pp3_1['nb_episode_steps'][i] + pp3_2['nb_episode_steps'][i]+pp3_3['nb_episode_steps'][i])/3 for i in range(len(pp3_1['nb_episode_steps']))]\n\n#pyplot.subplot(2, 1, 1)\n\npyplot.figure(num=1, figsize=(20, 10),)\npyplot.xlabel('total steps', fontsize=24)\npyplot.ylabel('rewards per episode', fontsize=24)\npyplot.title('batch size comparison-reward', fontsize=24)\nnew_ticks = np.linspace(0, 1200000, 30)\nnew_ticksy = np.linspace(-200, 1500, 18)\n\npyplot.xticks(new_ticks)\npyplot.yticks(new_ticksy)\n\npyplot.plot(st_ave1, er_ave1, 'hotpink', label='batch_size=32')\npyplot.plot(st_ave2, er_ave2, 'palegreen', label='batch_size=64')\npyplot.plot(st_ave3, er_ave3, 'deepskyblue', label='batch_size=96')\npyplot.legend()\npyplot.savefig('save/pics/cirturtle_batch_size_reward2.png',bbox_inches='tight')\n\n\n\npyplot.figure(num=4, figsize=(20, 10),)\npyplot.xlabel('total episodes', fontsize=24)\npyplot.ylabel('rewards per episode', fontsize=24)\npyplot.title('batch size comparison-reward', fontsize=24)\nnew_ticks = np.linspace(0, 2500, 30)\nnew_ticksy = np.linspace(-200, 1500, 18)\n\npyplot.xticks(new_ticks)\npyplot.yticks(new_ticksy)\npyplot.plot(er_ave1, 'hotpink', label='batch_size=32')\npyplot.plot(er_ave2, 'palegreen', label='batch_size=64')\npyplot.plot(er_ave3, 'deepskyblue', label='batch_size=96')\npyplot.legend()\npyplot.savefig('save/pics/cirturtle_batch_size_reward.png',bbox_inches='tight')\n\n\n\npyplot.figure(num=2, figsize=(20, 10),)\npyplot.xlabel('total steps', fontsize=24)\npyplot.ylabel('steps per episode', fontsize=24)\npyplot.title('batch size comparison-steps', fontsize=24)\nnew_ticks = np.linspace(0, 1200000, 30)\n\npyplot.xticks(new_ticks)\n\npyplot.plot(st_ave1, est_ave1, 'hotpink', label='batch_size=32')\npyplot.plot(st_ave2, est_ave2, 'palegreen', label='batch_size=64')\npyplot.plot(st_ave3, est_ave3, 'deepskyblue', label='batch_size=96')\n#pyplot.plot(pp1_4['nb_steps'], pp1_4['episode_reward'], 'y', label='640,0.1')\n#pyplot.plot(pp1_5['nb_steps'], pp1_5['episode_reward'], 'orange', label='960,0.1')\npyplot.legend()\npyplot.savefig('save/pics/cirturtle_batch_size_steps.png',bbox_inches='tight')\n\n\n\npyplot.figure(num=3, figsize=(8, 5),)\nwidth = 0.2\nx = np.arange(3)\nduration_compare = [duration1,duration2,duration3]\nfig, ax = pyplot.subplots()\nrects1 = ax.bar(x, duration_compare, width)\n\npyplot.xticks(x, ('batch_size=32', 'batch_size=64', 'batch_size=96'))\nax.set_ylabel('Duration')\nax.set_title('Training time with different batch size')\npyplot.savefig('save/pics/cirturtle_duration_BS.png',bbox_inches='tight')\n\npyplot.show()\n","sub_path":"DQN/CirTurtleBot/batch_size_comparison.py","file_name":"batch_size_comparison.py","file_ext":"py","file_size_in_byte":5308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"162549719","text":"from main.page.desktop_v3.header import *\nfrom main.page.base import *\nfrom selenium import webdriver\nfrom main.page.desktop_v3.product.pe_talk_product import *\nfrom main.page.desktop_v3.product.pe_product import *\nfrom main.page.desktop_v3.shop.pe_shop import *\nfrom main.activity.desktop_v3.activity_inbox_talk import *\nfrom main.activity.desktop_v3.activity_login import *\nfrom main.page.desktop_v3.login.pe_login import *\nfrom main.page.desktop_v3.login.pe_logout import *\nfrom utils.lib.user_data import *\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.common.exceptions import NoSuchElementException\n\n\n\nclass talkProductActivity:\n\tdef __init__(self, driver):\n\t\tself.login = LoginPage(driver)\n\t\tself.logout = LogoutPage(driver)\n\t\tself.shop = ShopPage(driver)\n\t\tself.prod = ProductPage(driver)\n\t\tself.talk = TalkProductPage(driver)\n\t\tself.inbox = inboxTalkActivity()\n\t\tself.inbox.setObject(driver)\n\t\t\n\n\tdef set_parameter(self, parameter):\n\t\tself.dict = parameter\n\t\tself.sender = self.dict['sender']\n\t\tself.receiver = self.dict['receiver']\n\n\tdef test_input_talk(self, driver, site, talk_message):\n\t\tself.login.open(site)\n\t\tself.login.do_login(self.sender['email'], self.sender['password'])\n\t\tif self.dict['end_to_end'] == True:\n\t\t\tprint('Sending talk end-to-end\\n')\n\t\t\tprint(\"SENDER ACTIVITY\")\n\t\t\tself.shop.domain(site, self.receiver['domain'])\n\t\t\tprint('Entered Shop' + str(self.receiver['domain']))\n\t\t\tprint('Randomly choose product')\n\t\t\tself.shop.choose_product()\n\t\t\tself.prod.go_to_talk() #enter discussion tab\n\t\t\tprint('Entered talk tab')\n\t\t\ttime.sleep(1)\n\t\t\ttotal_message_old = self.talk.get_jumlah_message()\n\t\t\tprint('Total Talk (old): ' + str(total_message_old))\n\t\t\tself.talk.input_talk(talk_message)\n\t\t\ttry:\n\t\t\t\ttotal_message_new = self.talk.get_jumlah_message()\n\t\t\t\tprint('Total Talk (new): ' + str(total_message_new))\n\t\t\t\tend_of_list = total_message_new - total_message_old\n\t\t\t\tprint(end_of_list)\n\t\t\t\tnew_ID_message = self.talk.list_new_message(end_of_list)\n\t\t\texcept TimeoutException:\n\t\t\t\tprint ('Loading time too long. Test terminated.')\n\t\t\t\tnew_ID_message = 'none'\n\t\t\texcept NoSuchElementException:\n\t\t\t\tprint ('Element Not Found. Test terminated.')\n\t\t\t\tnew_ID_message = 'none'\n\t\t\tself.logout.open(site)\n\t\t\tprint('SENDER ACTIVITY DONE')\n\t\t\tprint('==========================')\n\t\t\tprint('RECEIVER ACTIVITY')\n\t\t\tself.login.open(site)\n\t\t\tself.login.do_login(self.receiver['email'], self.receiver['password'])\n\t\t\ttime.sleep(2)\n\t\t\tself.inbox.is_message_received(site, new_ID_message)\n\t\telif self.dict['end_to_end'] == False:\n\t\t\tn = 0\n\t\t\twhile n < self.dict['loop']:\n\t\t\t\tprint(\"Auto Send Talk #\" + str(n+1))\n\t\t\t\tself.shop.domain(site, self.receiver['domain'])\n\t\t\t\tprint('Entered Shop' + str(self.receiver['domain']))\n\t\t\t\tself.shop.choose_product()\n\t\t\t\tprint('Choose random product')\n\t\t\t\tself.prod.go_to_talk() #enter discussion tab\n\t\t\t\tprint('Entered talk tab')\n\t\t\t\ttime.sleep(1)\n\t\t\t\tself.talk.input_talk(talk_message)\n\t\t\t\tn+=1\n\t\t\t\ttime.sleep(15)\n\t\t\t\tprint(\"\")\n","sub_path":"main/activity/desktop_v3/activity_talk_product.py","file_name":"activity_talk_product.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"616016325","text":"from requests_aws4auth import AWS4Auth\nimport boto3\nimport requests\n\ndef detect_labels(photo, bucket):\n\n client=boto3.client('rekognition')\n\n response = client.detect_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}},\n MaxLabels=10)\n\n print('Detected labels for ' + photo)\n labels = []\n for label in response['Labels']:\n labels.append(label['Name'])\n print(labels)\n return labels\n\n\ndef lambda_handler(event, context):\n # The domain with https:// and trailing slash. For example, https://my-test-domain.us-east-1.es.amazonaws.com/\n host = 'https://vpc-photos-owcvu6ex4q3ap3sgeav4ochzfm.us-east-1.es.amazonaws.com/'\n path = 'photos/_doc/' # the Elasticsearch API endpoint\n region = 'us-east-1' # For example, us-west-1\n service = 'es'\n credentials = boto3.Session().get_credentials()\n awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)\n url = host + path\n for record in event['Records']:\n bucket = record['s3']['bucket']['name']\n photo = record['s3']['object']['key']\n labels = detect_labels(photo, bucket)\n payload = {\n \"objectKey\": photo,\n \"bucket\": bucket,\n \"createdTimestamp\": record[\"eventTime\"],\n \"labels\": labels\n }\n r = requests.post(url, auth=awsauth, json=payload) # requests.get, post, and delete have similar syntax\n print(r.text)\n\n return {\n 'statusCode': 200,\n 'body': 'get new image'\n }\n","sub_path":"index-photos/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"129271589","text":"import numpy as np\nfrom simpleInitialization import simpleInitialization\n\n\ndef kmeans(X, k):\n # Intialize centroids\n centroids = simpleInitialization(X, k)\n labels = np.zeros(X.shape[0])\n n_it = 100\n # ====================== ADD YOUR CODE HERE ======================\n # Instructions: Run the main k-means algorithm. Follow the steps \n # given in the description. Compute the distance \n # between each instance and each centroid. Assign \n # the instance to the cluster described by the closest\n # centroid. Repeat the above steps until the centroids\n # stop moving or reached a certain number of iterations\n # (e.g., 100).\n\n\n\n\n \n # ===============================================================\n \n # Run main k-means algorithm\n for i in range(n_it):\n # Compute distances from the centroid to points\n distances = np.array([np.linalg.norm(X-centroid, axis = 1)\n for centroid in centroids]).T\n \n #Compute nearest centroid indices \n labels = np.argmin(distances, axis = 1)\n \n # Find new centroids \n before_centroids = np.copy(centroids)\n centroids = np.array([np.mean(X[labels == i], axis = 0)\n for i in range(k)])\n \n if (np.array_equal(before_centroids,centroids)):\n break\n print('We found the solution in ' + str(i) + ' iterations!')\n\n return labels","sub_path":"2EL1730-ML-Lab9/spectral_clustering/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"205659829","text":"# Created by bszmit on 11/23/15\n\nfrom codeanalyzer.utils.codemetrics.codemetric import CodeMetric\n\n__author__ = 'bszmit'\n\n\n# noinspection SpellCheckingInspection\nclass CCMetric(CodeMetric):\n \"\"\"\n Stores information about Cyclomatic Complexity.\n \"\"\"\n def __init__(self, json_data):\n fields = ('col_offset', 'complexity', 'endline', 'lineno')\n CodeMetric.__init__(self, json_data, fields)\n\n @property\n def col_offset(self):\n \"\"\"\n Column offset of code.\n How much indented it is.\n \"\"\"\n return self.json_data['col_offset']\n\n @property\n def complexity(self):\n \"\"\"\n Complexity of code.\n Determined by counting if, for, while ....\n \"\"\"\n return self.json_data['complexity']\n\n @property\n def endline(self):\n \"\"\"\n Number fo last line of code\n \"\"\"\n return self.json_data['endline']\n\n @property\n def lineno(self):\n \"\"\"\n Number of first line of code\n \"\"\"\n return self.json_data['lineno']\n\n @staticmethod\n def complexity_rank(complexity):\n if complexity <= 5: return 'A (low risk)'\n if complexity <= 10: return 'B (low risk)'\n if complexity <= 20: return 'C (moderate risk)'\n if complexity <= 30: return 'D (more than moderate risk)'\n if complexity <= 40: return 'E (high risk)'\n return 'F (very high risk)'\n\n\nif __name__ == '__main__':\n # noinspection SpellCheckingInspection\n j = {\n \"col_offset\": 4,\n \"complexity\": 1,\n \"endline\": 77,\n \"lineno\": 65,\n }\n\n cc1 = CCMetric(j)\n cc2 = CCMetric(j)\n cc3 = cc1 + cc2\n print(cc1.col_offset)\n print(cc1.complexity)\n print(cc1.endline)\n print(cc1.lineno)\n print(cc1)\n print(cc2)\n print(cc3)\n print(cc3/3)\n","sub_path":"codeanalyzer/utils/codemetrics/ccmetric.py","file_name":"ccmetric.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"208584218","text":"# Uses python3\n\ndef fibonacci(n):\n if n<0:\n return 0\n if n<=1:\n return n\n b = 0\n a = 1\n for i in range(1,n):\n b,a = a,a+b\n return a\n\ndef calc_fib(n):\n if (n <= 1):\n return n\n\n return calc_fib(n - 1) + calc_fib(n - 2)\n\nn = int(input())\nprint(fibonacci(n))\n","sub_path":"week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"237675973","text":"# import os\nimport json\n\nfrom django.http import HttpResponse\nfrom django.utils.module_loading import import_string\nimport datetime\n\n# from io import BytesIO\n# from datetime import datetime\n# from pdf2docx import Converter\n# from docx import Document\n# import fitz\n# from pdf2docx import Page\n# from appconf.manager import SettingManager\nfrom forms.sql_func import get_covid_to_json\nfrom laboratory.settings import COVID_RESEARCHES_PK, CENTRE_GIGIEN_EPIDEMIOLOGY, REGION, EXCLUDE_HOSP_SEND_EPGU\n\n\ndef pdf(request):\n \"\"\"\n Get form's number (decimal type: 101.15 - where \"101\" is form's group and \"15\"-number itsels).\n Can't use 1,2,3,4,5,6,7,8,9 for number itsels - which stands after the point.\n Bacause in database field store in decimal format xxx.yy - two number after dot, and active status.\n Must use: 01,02,03-09,10,11,12-19,20,21,22-29,30,31.....\n :param request:\n :return:\n \"\"\"\n response = HttpResponse(content_type='application/pdf')\n t = request.GET.get(\"type\")\n response['Content-Disposition'] = 'inline; filename=\"form-' + t + '.pdf\"'\n\n f = import_string('forms.forms' + t[0:3] + '.form_' + t[4:6])\n response.write(\n f(\n request_data={\n **dict(request.GET.items()),\n \"user\": request.user,\n \"hospital\": request.user.doctorprofile.get_hospital(),\n }\n )\n )\n return response\n\n\n# def docx(request):\n# response = HttpResponse(content_type='application/application/vnd.openxmlformats-officedocument.wordprocessingml.document')\n# t = request.GET.get(\"type\")\n# f = import_string('forms.forms' + t[0:3] + '.form_' + t[4:6])\n# pdf = f(\n# request_data={\n# **dict(request.GET.items()),\n# \"user\": request.user,\n# \"hospital\": request.user.doctorprofile.get_hospital(),\n# }\n# )\n#\n# buffer = BytesIO()\n# buffer.write(pdf)\n# buffer.seek(0)\n#\n# today = datetime.now()\n# date_now1 = datetime.strftime(today, \"%y%m%d%H%M%S%f\")[:-3]\n# date_now_str = str(date_now1)\n# dir_param = SettingManager.get(\"dir_param\", default='/tmp', default_type='s')\n# docx_file = os.path.join(dir_param, date_now_str + '_dir.docx')\n# cv = MyConverter(buffer)\n# cv.convert(docx_file, start=0, end=None)\n# cv.close()\n# doc = Document(docx_file)\n# os.remove(docx_file)\n# buffer.close()\n#\n# response['Content-Disposition'] = 'attachment; filename=\"form-' + t + '.docx\"'\n# doc.save(response)\n#\n# return response\n\n\n# def save(form, filename: str):\n# with open(filename, 'wb') as f:\n# f.write(form.read())\n#\n#\n# class MyConverter(Converter):\n# def __init__(self, buffer):\n# self.filename_pdf = 'xx.pdf'\n# self._fitz_doc = fitz.Document(stream=buffer, filename=self.filename_pdf)\n# self._pages = [Page(fitz_page) for fitz_page in self._fitz_doc]\n\n\ndef extra_nofication(request):\n # Результат Экстренные извещения\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'inline; filename=\"extra_note.pdf\"'\n\n f = import_string('forms.forms110.form_01')\n response.write(\n f(\n request_data={\n **dict(request.GET.items()),\n }\n )\n )\n return response\n\n\ndef covid_result(request):\n response = HttpResponse(content_type='application/json')\n if not request.user.doctorprofile.has_group('Заполнение экстренных извещений'):\n response.write(json.dumps({\"error\": \"Access denied\"}, ensure_ascii=False))\n return response\n\n request_data = {**dict(request.GET.items())}\n date = request_data[\"date\"]\n time_start = f'{date} {request_data.get(\"time_start\", \"00:00\")}:00'\n time_end = f'{date} {request_data.get(\"time_end\", \"23:59\")}:59:999999'\n datetime_start = datetime.datetime.strptime(time_start, '%Y-%m-%d %H:%M:%S')\n datetime_end = datetime.datetime.strptime(time_end, '%Y-%m-%d %H:%M:%S:%f')\n result = get_covid_to_json(COVID_RESEARCHES_PK, datetime_start, datetime_end)\n data_return = []\n count = 0\n for i in result:\n if i.hosp_id in EXCLUDE_HOSP_SEND_EPGU:\n continue\n if not i.value_result:\n continue\n result_value = i.value_result.lower()\n if result_value.find('отрицат') != -1:\n result_value = 0\n elif result_value.find('поло') != -1:\n result_value = 1\n enp = \"\"\n if i.oms_number:\n enp = i.oms_number\n snils_number = \"\"\n if i.snils_number:\n snils_number = i.snils_number\n\n passport_serial, passport_number = \"\", \"\"\n if i.passport_serial and i.passport_number:\n passport_serial = i.passport_serial\n passport_number = i.passport_number\n\n sex = None\n if i.psex == \"ж\":\n sex = 2\n elif i.psex == \"м\":\n sex = 1\n\n laboratory_ogrn = i.laboratoryogrn or \"\"\n laboratory_name = i.laboratoryname or \"\"\n get_tubes = i.get_tubes or i.date_confirm\n data_return.append(\n {\n \"order\": {\n \"number\": str(i.number_direction),\n \"depart\": CENTRE_GIGIEN_EPIDEMIOLOGY,\n \"laboratoryName\": laboratory_name,\n \"laboratoryOgrn\": laboratory_ogrn,\n \"name\": i.title_org_initiator or laboratory_name,\n \"ogrn\": i.ogrn_org_initiator or laboratory_ogrn,\n \"orderDate\": get_tubes,\n \"serv\": [\n {\n \"code\": i.fsli,\n \"name\": i.title,\n \"testSystem\": \"\",\n \"biomaterDate\": get_tubes,\n \"readyDate\": i.date_confirm,\n \"result\": result_value,\n \"type\": 1,\n }\n ],\n \"patient\": {\n \"surname\": i.pfam,\n \"name\": i.pname,\n \"patronymic\": i.twoname,\n \"gender\": sex or \"\",\n \"birthday\": i.birthday,\n \"phone\": \"\",\n \"email\": \"\",\n \"documentType\": \"Паспорт гражданина РФ\",\n \"documentNumber\": passport_number,\n \"documentSerNumber\": passport_serial,\n \"snils\": snils_number,\n \"oms\": enp,\n \"address\": {\n \"regAddress\": {\n \"town\": \"\",\n \"house\": \"\",\n \"region\": REGION,\n \"building\": \"\",\n \"district\": \"\",\n \"appartament\": \"\",\n \"streetName\": \"\",\n },\n \"factAddress\": {\"town\": \"\", \"house\": \"\", \"region\": REGION, \"building\": \"\", \"district\": \"\", \"appartament\": \"\", \"streetName\": \"\"},\n },\n },\n }\n }\n )\n count += 1\n response['Content-Disposition'] = f\"attachment; filename=\\\"{date}-covid-{count}.json\\\"\"\n response.write(json.dumps(data_return, ensure_ascii=False))\n\n return response\n","sub_path":"forms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"548484355","text":"import decimal\nimport inspect\nimport itertools\nfrom collections import deque\nfrom dataclasses import fields, is_dataclass\nfrom typing import (\n List, Set, FrozenSet, Deque, Any, Callable,\n Dict, Collection, Type, get_type_hints,\n Optional, Tuple, Union, Sequence\n)\n\nfrom .common import Parser, T\nfrom .exceptions import InvalidFieldError\nfrom .path_utils import Path\nfrom .schema import Schema, get_dataclass_fields\nfrom .type_detection import (\n is_tuple, is_collection, is_any, hasargs, is_optional,\n is_none, is_union, is_dict, is_enum,\n is_generic_concrete, fill_type_args, args_unspecified,\n is_literal, is_literal36, is_typeddict,\n)\n\nPARSER_EXCEPTIONS = (ValueError, TypeError, AttributeError, LookupError)\n\n\ndef element_parser(parser: Parser[T], data: Any, key: Any) -> T:\n try:\n return parser(data)\n except InvalidFieldError as e:\n e._append_path(str(key))\n raise\n except PARSER_EXCEPTIONS as e:\n raise InvalidFieldError(str(e), [str(key)])\n\n\ndef parse_stub(data: T) -> T:\n return data\n\n\ndef parse_none(data: Any) -> None:\n if data is not None:\n raise ValueError(\"None expected\")\n\n\ndef get_parser_with_check(cls: Type[T]) -> Parser[T]:\n def parser(data):\n if isinstance(data, cls):\n return data\n raise ValueError(\"data type is not %s\" % cls)\n\n return parser\n\n\ndef get_collection_parser(\n collection_factory: Callable,\n item_parser: Parser[T],\n debug_path: bool\n) -> Parser[Collection[T]]:\n if debug_path:\n def collection_parser(data):\n return collection_factory(\n element_parser(item_parser, x, i) for i, x in enumerate(data)\n )\n else:\n def collection_parser(data):\n return collection_factory(\n item_parser(x) for x in data\n )\n return collection_parser\n\n\ndef get_union_parser(parsers: Collection[Callable]) -> Parser:\n def union_parser(data):\n for p in parsers:\n try:\n return p(data)\n except PARSER_EXCEPTIONS as e:\n continue\n raise ValueError(\"No suitable parsers in union found for `%s`\" % data)\n\n return union_parser\n\n\ntuple_any_parser = tuple\n\n\ndef get_tuple_parser(parsers: Collection[Callable], debug_path: bool) -> Parser[Tuple]:\n if debug_path:\n def tuple_parser(data):\n if len(data) != len(parsers):\n raise ValueError(\"Incorrect length of data, expected %s, got %s\" % (len(parsers), len(data)))\n return tuple(element_parser(parser, x, i) for x, parser, i in zip(data, parsers, itertools.count()))\n else:\n def tuple_parser(data):\n if len(data) != len(parsers):\n raise ValueError(\"Incorrect length of data, expected %s, got %s\" % (len(parsers), len(data)))\n return tuple(parser(x) for x, parser in zip(data, parsers))\n return tuple_parser\n\n\ndef get_path_parser(parser: Parser[T], path: Path) -> Parser[T]:\n def path_parser(data):\n if data is None:\n return parser(data)\n for x in path:\n data = data[x]\n if data is None:\n return parser(data)\n return parser(data)\n\n return path_parser\n\n\ndef get_field_parser(item: Union[str, int, Path], parser: Parser[T]) -> Tuple[Union[str, int], Parser[T]]:\n if isinstance(item, tuple):\n if len(item) == 1:\n return item[0], parser\n return item[0], get_path_parser(parser, item[1:])\n else:\n return item, parser\n\n\ndef get_dataclass_parser(class_: Type[T],\n parsers: Dict[str, Parser],\n schema: Schema[T],\n debug_path: bool, ) -> Parser[T]:\n field_info = tuple(\n (field_name, *get_field_parser(item, parsers[field_name]))\n for field_name, item, default in get_dataclass_fields(schema, class_)\n )\n\n list_mode = any(isinstance(name, int) for _, name, _ in field_info)\n\n if debug_path:\n if list_mode:\n def dataclass_parser(data):\n count = len(data)\n return class_(**{\n field_name: element_parser(parser, data[item_idx], field_name)\n for field_name, item_idx, parser in field_info\n if item_idx < count\n })\n else:\n def dataclass_parser(data):\n return class_(**{\n field_name: element_parser(parser, data[name], field_name)\n for field_name, name, parser in field_info\n if name in data\n })\n else:\n if list_mode:\n def dataclass_parser(data):\n count = len(data)\n return class_(**{\n field_name: parser(data[item_idx])\n for field_name, item_idx, parser in field_info\n if item_idx < count\n })\n else:\n def dataclass_parser(data):\n return class_(**{\n field_name: parser(data[item_name])\n for field_name, item_name, parser in field_info\n if item_name in data\n })\n\n return dataclass_parser\n\n\ndef get_typed_dict_parser(class_: Any, parsers: Dict[str, Parser], schema: Schema[T]):\n parsers_list = tuple(parsers.items())\n if class_.__total__:\n def parser(data):\n return {\n name: field_parser(data[name])\n for name, field_parser in parsers_list\n }\n else:\n def parser(data):\n return {\n name: field_parser(data[name])\n for name, field_parser in parsers_list\n if name in data\n }\n return parser\n\n\ndef get_optional_parser(parser: Parser[T]) -> Parser[Optional[T]]:\n def optional_parser(data):\n return parser(data) if data is not None else None\n\n return optional_parser\n\n\ndef decimal_parse(data) -> decimal.Decimal:\n try:\n return decimal.Decimal(data)\n except (decimal.InvalidOperation, TypeError, ValueError):\n raise ValueError(f'Invalid decimal string representation {data}')\n\n\ndef get_collection_factory(cls) -> Type:\n origin = cls.__origin__ or cls\n res = {\n List: list,\n list: list,\n Set: set,\n set: set,\n FrozenSet: frozenset,\n frozenset: frozenset,\n Deque: deque,\n deque: deque,\n }.get(origin)\n if not res:\n raise NotImplementedError(\"Class %s not supported\" % cls)\n return res\n\n\ndef get_dict_parser(key_parser, value_parser) -> Parser:\n return lambda data: {key_parser(k): value_parser(v) for k, v in data.items()}\n\n\ndef get_class_parser(cls, parsers: Dict[str, Callable], debug_path: bool) -> Parser:\n if debug_path:\n def class_parser(data):\n return cls(**{\n k: element_parser(parser, data.get(k), k) for k, parser in parsers.items() if k in data\n })\n else:\n def class_parser(data):\n return cls(**{\n k: parser(data.get(k)) for k, parser in parsers.items() if k in data\n })\n return class_parser\n\n\ndef get_literal_parser(factory, values: Sequence[Any]) -> Parser:\n def literal_parser(data: Any):\n for v in values:\n if (type(v), v) == (type(data), data):\n return data\n raise ValueError(\"Invalid literal data\")\n\n return literal_parser\n\n\ndef get_lazy_parser(factory, class_: Type) -> Parser:\n # return partial(factory.load, class_=class_)\n def lazy_parser(data):\n return factory.load(data, class_)\n\n return lazy_parser\n\n\ndef create_parser(factory, schema: Schema, debug_path: bool, cls: Type) -> Parser:\n parser = create_parser_impl(factory, schema, debug_path, cls)\n pre = schema.pre_parse\n post = schema.post_parse\n if pre or post:\n def parser_with_steps(data):\n if pre:\n data = pre(data)\n data = parser(data)\n if post:\n return post(data)\n return data\n\n return parser_with_steps\n return parser\n\n\ndef create_parser_impl(factory, schema: Schema, debug_path: bool, cls: Type) -> Parser:\n if is_any(cls):\n return parse_stub\n if is_none(cls):\n return parse_none\n if is_literal(cls):\n return get_literal_parser(factory, cls.__args__)\n if is_literal36(cls):\n return get_literal_parser(factory, cls.__values__)\n if is_optional(cls):\n return get_optional_parser(factory.parser(cls.__args__[0]))\n if cls in (str, bytearray, bytes):\n return get_parser_with_check(cls)\n if cls in (int, float, complex, bool):\n return cls\n if cls in (decimal.Decimal,):\n return decimal_parse\n if is_enum(cls):\n return cls\n if is_tuple(cls):\n if not hasargs(cls):\n return tuple_any_parser\n elif len(cls.__args__) == 2 and cls.__args__[1] is Ellipsis:\n item_parser = factory.parser(cls.__args__[0])\n return get_collection_parser(tuple, item_parser, debug_path)\n else:\n return get_tuple_parser(tuple(factory.parser(x) for x in cls.__args__), debug_path)\n if is_dict(cls):\n if args_unspecified(cls):\n key_type_arg = Any\n value_type_arg = Any\n else:\n key_type_arg = cls.__args__[0]\n value_type_arg = cls.__args__[1]\n return get_dict_parser(factory.parser(key_type_arg), factory.parser(value_type_arg))\n if is_typeddict(cls):\n resolved_hints = get_type_hints(cls)\n parsers = {field: factory.parser(type_) for field, type_ in resolved_hints.items()}\n return get_typed_dict_parser(\n cls,\n parsers,\n schema,\n )\n if is_collection(cls):\n if args_unspecified(cls):\n value_type_arg = Any\n else:\n value_type_arg = cls.__args__[0]\n collection_factory = get_collection_factory(cls)\n item_parser = factory.parser(value_type_arg)\n return get_collection_parser(collection_factory, item_parser, debug_path)\n if is_union(cls):\n return get_union_parser(tuple(factory.parser(x) for x in cls.__args__))\n if is_generic_concrete(cls) and is_dataclass(cls.__origin__):\n args = dict(zip(cls.__origin__.__parameters__, cls.__args__))\n resolved_hints = get_type_hints(cls.__origin__)\n parsers = {\n field.name: factory.parser(fill_type_args(args, resolved_hints[field.name]))\n for field in fields(cls.__origin__)\n }\n return get_dataclass_parser(\n cls.__origin__,\n parsers,\n schema,\n debug_path,\n )\n if is_dataclass(cls):\n resolved_hints = get_type_hints(cls)\n parsers = {\n field.name: factory.parser(resolved_hints[field.name])\n for field in fields(cls)\n }\n return get_dataclass_parser(\n cls,\n parsers,\n schema,\n debug_path,\n )\n try:\n arguments = inspect.signature(cls.__init__).parameters\n parsers = {\n k: factory.parser(v.annotation) for k, v in arguments.items()\n }\n return get_class_parser(cls, parsers, debug_path)\n except PARSER_EXCEPTIONS:\n raise ValueError(\"Cannot find parser for `%s`\" % repr(cls))\n","sub_path":"dataclass_factory/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":11475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"240296706","text":"#!/usr/bin/python\n\nimport sys, os, uuid, time\nsys.path.append(os.path.join(os.path.dirname(__file__),'../bindings/python/'))\nimport serverboards\n\nfrom libcloud.compute.types import Provider\nfrom libcloud.compute.providers import get_driver\n\nconnections={}\nuri_type_to_connection={}\ntimer_refcount={} # connhash -> (timerid, refcount)\ntimerid_to_connhash={} # timerid -> connhash\n\ndef connection_hash(type, **extra):\n return hash( (repr(sorted(extra.items())),type) )\n\n@serverboards.rpc_method\ndef providers():\n return ['libvirt']\n\n@serverboards.rpc_method\ndef connect(type, **extra):\n urik=connection_hash(type=type, **extra)\n if urik in uri_type_to_connection: # already exists\n return uri_type_to_connection[urik]\n\n driver = None\n if type == 'libvirt':\n cls=get_driver(Provider.LIBVIRT)\n driver=cls( \"qemu+ssh://%s/system\"%extra['server'] )\n elif type == 'digitalocean':\n cls=get_driver(Provider.DIGITAL_OCEAN)\n driver=cls(extra['token'], api_version='v2')\n if not driver:\n raise Exception(\"Could not create connexion to remote cloud provider\")\n\n id = str(uuid.uuid4())\n connections[id]=dict( driver=driver, type=type, urik=urik )\n uri_type_to_connection[urik]=id\n return id\n\n@serverboards.rpc_method\ndef disconnect(id):\n conn=connections[id]\n del conn['driver']\n del connections[id]\n del uri_type_to_connection[conn['urik']]\n return True\n\ndef guess_icon(node):\n nodename=node.name.lower()\n if 'debian' in nodename:\n return 'debian.svg'\n if 'fedora' in nodename:\n return 'fedora.svg'\n if 'ubuntu' in nodename:\n return 'ubuntu.svg'\n if 'linux' in nodename:\n return 'linux'\n return None\n\ndef get_description(node):\n extra=node[\"extra\"]\n desc=[]\n if 'used_memory' in extra:\n desc.append( '%s MB RAM'%(extra[\"used_memory\"]) )\n if 'memory' in extra:\n desc.append( '%s MB RAM'%(extra[\"memory\"]) )\n if 'disk' in extra:\n desc.append( '%.2f GB'%(extra['disk']) )\n if 'public_ips' in node:\n desc.append( ' '.join(node['public_ips']) )\n return ', '.join(desc)\n\n@serverboards.rpc_method(\"list\")\ndef _list(uuid=None):\n if uuid is None:\n lists=[_list(uuid) for uuid in connections.keys()]\n return reduce(list.__add__, lists, [])\n driver=connections[uuid]['driver']\n def decorate(node):\n return {\n 'connection':uuid,\n 'name':node.name,\n 'id':node.uuid,\n 'extra':node.extra,\n 'private_ips':node.private_ips,\n 'public_ips':node.public_ips,\n 'created_at':str(node.created_at),\n 'state':node.state,\n 'icon':guess_icon(node)\n }\n\n return [decorate(node) for node in driver.list_nodes()]\n\n@serverboards.rpc_method\ndef start(connection, node):\n driver=connections[connection]\n conn=driver['driver']\n return conn.ex_start_node( conn.ex_get_node_by_uuid(node) )\n\n@serverboards.rpc_method\ndef force_stop(connection, node):\n driver=connections[connection]\n conn=driver['driver']\n if driver['type']=='libvirt':\n n = conn.connection.lookupByUUIDString(node)\n n.destroy()\n return True\n return conn.ex_stop_node( conn.ex_get_node_by_uuid(node) )\n\n@serverboards.rpc_method\ndef shutdown(connection, node):\n driver=connections[connection]\n conn=driver['driver']\n return conn.ex_shutdown_node( conn.ex_get_node_by_uuid(node) )\n\n@serverboards.rpc_method\ndef reboot(connection, node):\n driver=connections[connection]\n conn=driver['driver']\n return conn.reboot_node( conn.ex_get_node_by_uuid(node) )\n\n@serverboards.rpc_method\ndef virtual_nodes(**config):\n connection = connect(**config)\n def decorate(node):\n serverboards.rpc.debug(repr(node))\n return {\n 'type': 'serverboards.core.cloud/cloud.node', # optional, if not, can not be instantiated.\n 'id': node['id'],\n 'name': node['name'],\n 'tags': [ \"stopped\" if node['state']==\"terminated\" else \"running\" ],\n 'description': get_description(node),\n 'traits': ['core.cloud.node'],\n 'config': {\n 'node': node['id'],\n 'connection': connection\n },\n 'icon': node['icon']\n }\n return [decorate(node) for node in _list(connection)]\n\n@serverboards.rpc_method\ndef virtual_nodes_subscribe(**config):\n h=connection_hash(**config)\n if h in timer_refcount:\n timer_refcount[h]=(timer_refcount[h][0], timer_refcount[h][1]+1)\n return timer_refcount[h][0]\n\n nodes=dict( (x['id'], x) for x in virtual_nodes(**config) )\n def send_changes():\n #serverboards.rpc.debug(\"tick\")\n changes=[]\n nnodes=dict( (x['id'], x) for x in virtual_nodes(**config) )\n\n for (k,v) in nnodes.items():\n if not k in nodes:\n changes.append(v) # added\n nodes[k]=v\n elif v != nodes[k]:\n changes.append(v) # changed\n nodes[k]=v\n for k in nodes.keys(): # removed\n if not k in nnodes:\n changes.append({'id':k, '_removed': True})\n del nodes[k]\n\n for c in changes:\n serverboards.rpc.event(\"event.emit\", \"service.updated\", {\"service\":c})\n\n\n # this subscription is via polling. If in the future there are better options, use them.\n timerid=serverboards.rpc.add_timer(10.0, send_changes)\n\n timerid_to_connhash[timerid]=h\n timer_refcount[h]=(timerid, 1)\n return timerid\n\n@serverboards.rpc_method\ndef virtual_nodes_unsubscribe(timerid):\n h=timerid_to_connhash[timerid]\n if timer_refcount[h][1]==1:\n #serverboards.rpc.debug(\"Unsubscribe\")\n serverboards.rpc.remove_timer(timerid)\n del timer_refcount[h]\n del timerid_to_connhash[timerid]\n else:\n timer_refcount[h]=(timer_refcount[h][0], timer_refcount[h][1]-1)\n return True\n\ndef test():\n\n tid=virtual_nodes_subscribe(type=\"libvirt\",server=\"localhost\")\n serverboards.rpc.set_debug(sys.stderr)\n serverboards.rpc.loop()\n\n\n #uuid=connect(uri=\"qemu:///system\",type=\"libvirt\")\n uuid=connect(type=\"libvirt\",server=\"localhost\")\n print(_list())\n print(disconnect(uuid))\n\n uuid=connect(type=\"libvirt\",server=\"localhost\")\n # reconnect\n assert uuid==connect(type=\"libvirt\",server=\"localhost\")\n\n l = _list(uuid)\n print(l)\n node = l[0]['id']\n time.sleep(1)\n try:\n print(start(uuid,node))\n except:\n import traceback; traceback.print_exc()\n time.sleep(1)\n print(reboot(uuid,node))\n time.sleep(1)\n print(shutdown(uuid,node))\n time.sleep(1)\n try:\n print(force_stop(uuid,node))\n except:\n import traceback; traceback.print_exc()\n print(disconnect(uuid))\n print(_list())\n\n\ndef main():\n serverboards.rpc.set_debug(sys.stderr)\n serverboards.loop()\n\nif __name__=='__main__':\n if len(sys.argv)>=2 and sys.argv[1] == 'test':\n test()\n else:\n main()\n","sub_path":"plugins/core-cloud/serverboards-cloud.py","file_name":"serverboards-cloud.py","file_ext":"py","file_size_in_byte":7068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"107640022","text":"from itertools import count\nfrom Reinforcement import Utils, Agent, Experience, QValues\nfrom Environment import DungeonEnv, MapHandler, StateUpdateHandler\nfrom GameConnection import GameConnection\nfrom WebtilesHandler import GameHandler\nfrom threading import Thread\nimport torch.nn.functional as F\nimport torch\nimport os\nimport time\n\n\nclass RunNetwork():\n\tdef __init__(self):\n\t\tself.totalReward = 0\n\t\tpass\n\n\tdef run(self, utils, environment, policyNet, targetNet, networkName, networkDir):\n\t\tif( not os.path.exists(networkDir)):\n\t\t\tos.makedirs(networkDir)\n\n\t\tnetworkPath = networkDir + \"/network.pth\"\n\t\tfileTime = time.localtime()\n\t\tstringTime = time.strftime(\"%m_%d_%Y_%H_%M\", fileTime)\n\t\tlossPath = networkDir + \"/loss-\" + stringTime + \".txt\"\n\t\tlossFile = open(lossPath, \"w+\")\n\n\t\tga = GameHandler()\n\t\tagent = Agent(utils, environment)\n\n\t\tif os.path.isfile(networkPath):\n\t\t\tpolicyNet = torch.load(networkPath)\n\t\t\tpolicyNet.eval()\n\n\t\tutils.startOptimizer(policyNet)\n\n\t\ttargetNet.load_state_dict(policyNet.state_dict())\n\t\ttargetNet.eval()\n\n\t\tstate = environment.getState()\n\t\tepisode = 0\n\t\t\n\t\twhile(episode < utils.NumEpisodes and not environment.done):\n\n\t\t\taction = agent.selectAction(state, policyNet)\n\t\t\treward = environment.step(action)\n\t\t\tself.totalReward = self.totalReward + reward\n\t\t\tnextState = environment.getState()\n\t\t\t\n\t\t\tif(environment.ResetCount > 5):\n\t\t\t\tbreak\n\n\t\t\tutils.Memory.push(Experience(state, action, nextState, reward))\n\t\t\tstate = nextState\n\n\t\t\tif(utils.Memory.canProvideSample(utils.BatchSize)):\n\t\t\t\texperiences = utils.Memory.sample(utils.BatchSize)\n\t\t\t\tstates, actions, rewards, nextStates = utils.extractTensors(experiences)\n\n\t\t\t\tcurrentQValues = QValues.getCurrent(policyNet, states, actions)\n\t\t\t\tnextQValues = QValues.getNext(targetNet,nextStates, utils)\n\t\t\t\ttargetQValues = (nextQValues * utils.Gamma) + rewards\n\n\t\t\t\ttargetQValues = targetQValues.unsqueeze(1)\n\t\t\t\t\n\t\t\t\tloss = F.mse_loss(currentQValues, targetQValues)\n\t\t\t\tutils.optimizer.zero_grad()\n\t\t\t\tloss.backward()\n\t\t\t\tutils.optimizer.step()\n\n\t\t\t\tlossFile.write(str(episode) + \" loss: \" + str(loss.item()) + \"\\n\")\n\t\t\t\tlossFile.write(\"Reward: \" + str(self.totalReward) + \"\\n\")\n\t\t\t\tprint(str(episode) + \" loss: \" + str(loss.item()))\n\n\n\t\t\tif episode%utils.TargetUpdate == 0:\n\t\t\t\ttargetNet.load_state_dict(policyNet.state_dict())\n\n\t\t\tepisode = episode + 1\n\n\t\t\tprint(episode)\n\t\t\t\n\t\t\tif episode%100 == 0:\n\t\t\t\tnamed_tuple = time.localtime()\n\t\t\t\ttime_string = time.strftime(\"%m/%d/%Y, %H:%M:%S\", named_tuple)\n\t\t\t\tlossFile.write(\"Valid Moves: \" + str(environment.ValidMoves) + \" \" + str(environment.InvalidMoves) + \" \" + time_string+ \"\\n\")\n\n\t\t\tif episode % 1000 == 0:\n\t\t\t\ttorch.save(policyNet, networkPath)\n\n\t\t\tif environment.done:\n\t\t\t\tnamed_tuple = time.localtime()\n\t\t\t\ttime_string = time.strftime(\"%m/%d/%Y, %H:%M:%S\", named_tuple)\n\t\t\t\tlossFile.write(\"Valid Moves: \" + str(environment.ValidMoves) + \" \" + str(environment.InvalidMoves) + \" \" + time_string + \"\\n\")\n\t\t\t\tlossFile.write(\"##############################################\" + \"\\n\")\n\t\t\t\tlossFile.write(\"##############################################\" + \"\\n\")\n\t\t\t\tlossFile.write(\"##############################################\" + \"\\n\")\n\t\t\t\tprint(\"Valid Moves: \" + str(environment.ValidMoves) + \" \" + str(environment.InvalidMoves) + \"\\n\")\n\t\t\t\tenvironment.reset()\n\t\t\t\ttime.sleep(4)\n\t\t\t\tprint(\"restarting\")\n\t\t\t\tga.RestartGame()\n\t\t\t\t\n\t\tprint(str(episode) + \" \" + str(utils.NumEpisodes) + \" \" +str(environment.done) )\n\t\tnamed_tuple = time.localtime()\n\t\ttime_string = time.strftime(\"%m/%d/%Y, %H:%M:%S\", named_tuple)\n\n\t\tlossFile.close()\n\t\tprint(\"Done \" + networkName)\n","sub_path":"src/ReinforcementBot/RunNetwork.py","file_name":"RunNetwork.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"25344266","text":"\"\"\"\nWhat parameters should be sent to the range constructor, to produce a range with values 50, 60, 70, 80?\n\"\"\"\n\n\nresult = range(50, 90, 10)\n\n\nif __name__ == \"__main__\":\n assert list(result) == [50, 60, 70, 80]\n","sub_path":"DSAP/ch01/r_1_9.py","file_name":"r_1_9.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"143245845","text":"#-*- encoding: utf-8 -*-\nfrom cs1graphics import Canvas, Layer, Rectangle, Image, Text, Circle, Point\nimport os, sys\nimport random as rd\nfrom time import sleep\n\ndef resource_path(relative_path):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n try:\n # PyInstaller creates a temp folder and stores path in _MEIPASS\n base_path = sys._MEIPASS\n except Exception:\n base_path = os.path.abspath(\".\")\n\n return os.path.join(base_path, relative_path)\n\n################################## Initializing Variables ##################################\n\npaper = Canvas()\nuserName = givenNumber = predictedNumber = \"\"\nballs = strikes = tries = 0\nconsole_clear = \"cls\" if os.name == \"nt\" else \"clear\"\n\n##################################### Display Functions #####################################\n\ndef image_set(name_image): # 이미지 기본 셋팅\n global paper\n name_image.moveTo(400,300) \n name_image.setDepth(50) \n paper.add(name_image)\n\ndef displayFix(name_image): #고정멘트 이미지 추가\n global fix\n fix = Image(resource_path(\"images/fix/\"+name_image+\".png\"))\n image_set(fix)\n return\n\ndef displayCheck(name_image): #비고정멘트 이미지 추가\n global check\n check = Image(resource_path(\"images/check/\"+name_image+\".png\"))\n image_set(check)\n return\n\ndef displayInit(): #그래픽 초기 설정 메소드\n global paper\n paper.setWidth(800) # 가로\n paper.setHeight(600) # 세로\n paper.setBackgroundColor(\"skyblue\")\n\ndef displayingame(): # 인게임 바탕화면\n global paper\n background_image = Image(resource_path(\"images/image/background.png\"))\n image_set(background_image)\n\ndef displayMainScreen(): # 게임 메인 화면(메뉴)\n global paper\n\n paper.clear()\n Main = Layer()\n\n start = Rectangle(150, 100, Point(115, 450))\n start.setFillColor('yellow')\n Main.add(start)\n way = Rectangle(150, 100, Point(305, 450))\n way.setFillColor('yellow')\n Main.add(way)\n score = Rectangle(150, 100, Point(495, 450))\n score.setFillColor('yellow')\n Main.add(score)\n exit = Rectangle(150, 100, Point(685, 450))\n exit.setFillColor('yellow')\n Main.add(exit)\n paper.add(Main)\n\n Man = Layer()\n man = Image(resource_path(\"images/man.png\"))\n Man.setDepth(80)\n Man.add(man)\n Man.moveTo(390,350)\n paper.add(Man)\n\n Txt = Layer()\n startTxt = Text(\"1. START\", 25)\n startTxt.moveTo(115, 450) \n Txt.add(startTxt)\n howplayTxt = Text(\"2. HOW\", 25)\n howplayTxt.moveTo(305, 450)\n Txt.add(howplayTxt)\n numberTxt = Text(\"NUMBER\", 45)\n numberTxt.moveTo(140, 320)\n Txt.add(numberTxt)\n baseballTxt = Text(\"BASEBALL\", 45)\n baseballTxt.moveTo(660, 350)\n Txt.add(baseballTxt)\n scoreTxt = Text(\"3. SCORE\", 25)\n scoreTxt.moveTo(495, 450)\n Txt.add(scoreTxt)\n exitTxt = Text(\"4. EXIT\", 25)\n exitTxt.moveTo(685, 450)\n Txt.add(exitTxt)\n\n # 구름\n Cloud = Layer()\n flcloud = Circle(30, Point(80, 70))\n slcloud = Circle(30, Point(130, 70))\n thlcloud = Circle(30, Point(180, 70))\n flcloud.setFillColor('white')\n slcloud.setFillColor('white')\n thlcloud.setFillColor('white')\n flcloud.setBorderColor('white')\n slcloud.setBorderColor('white')\n thlcloud.setBorderColor('white')\n Cloud.add(flcloud)\n Cloud.add(slcloud)\n Cloud.add(thlcloud)\n Cloud.scale(5)\n Cloud.moveTo(-250, 0)\n Cloud.setDepth(100)\n paper.add(Cloud)\n\n # 대화상자\n Input_a = Layer()\n input_bar = Rectangle(1000, 50, Point(500, 575))\n input_bar.setFillColor('black')\n input_bar.setBorderWidth(0)\n Input_a.add(input_bar)\n paper.add(Input_a)\n\n #명령 입력\n welcome = Text(\"☆☆☆ Welcome to Number Baseball Game!! ☆☆☆\",20)\n welcome.moveTo(390,575)\n welcome.setFontColor(\"white\")\n\n introduction1 = Text(\"게임을 시작하려면 '1'을 입력하세요\",20)\n introduction1.moveTo(390,575)\n introduction1.setFontColor(\"white\")\n\n introduction2 = Text(\"게임방법을 알고싶다면 '2'를 입력하세요\",20)\n introduction2.moveTo(390,575)\n introduction2.setFontColor(\"white\")\n\n introduction3 = Text(\"게임순위를 보고싶다면 '3'을 입력하세요\",20)\n introduction3.moveTo(390,575)\n introduction3.setFontColor(\"white\")\n\n introduction4 = Text(\"게임을 종료하려면 '4'를 입력하세요\",20)\n introduction4.moveTo(390,575)\n introduction4.setFontColor(\"white\")\n\n introduction5 = Text(\"옵션을 선택해주세요!\",20)\n introduction5.moveTo(390,575)\n introduction5.setFontColor(\"white\")\n\n for _ in range(3):\n paper.add(Txt)\n sleep(0.5)\n paper.remove(Txt)\n sleep(0.5)\n\n paper.add(Txt)\n\n paper.add(welcome)\n sleep(1.5)\n paper.remove(welcome)\n paper.add(introduction1)\n sleep(1.5)\n paper.remove(introduction1)\n paper.add(introduction2)\n sleep(1.5)\n paper.remove(introduction2)\n paper.add(introduction3)\n sleep(1.5)\n paper.remove(introduction3)\n paper.add(introduction4)\n sleep(1.5)\n paper.remove(introduction4)\n sleep(1.5)\n paper.add(introduction5)\n return\n\ndef displayHowToPlay(): # 게임 방법을 알려주는 화면\n global paper\n\n paper.clear()\n HowToPlay = Layer()\n HowToPlay_background = Image(resource_path(\"images/how_to_back.png\"))\n HowToPlay_background.setDepth(100)\n HowToPlay_background.moveTo(400, 300)\n what_is = Text(\"숫자 야구란?\", 20)\n FirstTxt = Text(\"감춰진 3개의 숫자가 무엇인지 맞추는 게임입니다.\", 20)\n wayTxt = Text(\"게임 방법\", 20)\n SecondTxt = Text(\"1. 숫자는 0~9까지 구성되어 있으며, 각 숫자는 한번씩만 사용 가능합니다\", 20)\n ThirdTxt = Text(\"2. 숫자와 자리의 위치가 맞으면 스트라이크(S), 숫자만 맞으면 볼(B) 입니다.\", 20)\n FourthTxt = Text(\"3. 숫자가 하나도 맞지 않을 경우 아웃(OUT)으로 표시됩니다.\", 20)\n\n HowToPlay.add(what_is)\n HowToPlay.add(FirstTxt)\n HowToPlay.add(wayTxt)\n HowToPlay.add(SecondTxt)\n HowToPlay.add(ThirdTxt)\n HowToPlay.add(FourthTxt)\n HowToPlay.add(HowToPlay_background)\n\n what_is.moveTo(400, 80)\n FirstTxt.moveTo(400, 160)\n wayTxt.moveTo(400, 240)\n SecondTxt.moveTo(400, 320)\n ThirdTxt.moveTo(400, 390)\n FourthTxt.moveTo(400, 460)\n paper.add(HowToPlay)\n return\n\ndef displayRetry(): # 게임 오버 후 새 게임 시작 여부를 묻는 화면\n global paper\n retry_image = Image(resource_path(\"images/image/retry.png\")) # Try Again? 이미지\n image_set(retry_image)\n\ndef displayStartGame(): # 게임 설정 완료 후 게임 진행 화면으로 이동\n global givenNumber\n return\n\ndef displayOutSituation(): # 예측 숫자 입력 결과가 '아웃'일 때 화면\n global paper\n out_image = Image(resource_path(\"images/image/out.png\"))\n image_set(out_image)\n sleep(1)\n paper.remove(out_image)\n return\n\ndef displayGameOverByWinning(): # 정답을 맞추어 게임이 끝났을 때 화면\n global paper\n end_image = Image(resource_path(\"images/image/end.png\"))\n image_set(end_image)\n sleep(3)\n paper.remove(end_image)\n return\n\ndef displayEvaluationResult(): # 스트라이크, 볼, 아웃 화면\n global strikes, balls, paper\n judge_image = Image(resource_path(\"images/image/judge.png\")) # 볼 스트라이크 판정 이미지\n image_set(judge_image)\n\n directory_s = resource_path(\"images/num/num\" + str(strikes) + \"_s.png\")\n directory_b = resource_path(\"images/num/num\" + str(balls) + \"_b.png\")\n strike_num_image = Image(directory_s)\n ball_num_image = Image(directory_b)\n\n image_set(strike_num_image)\n image_set(ball_num_image)\n \n for i in range(3, 0, -1):\n __clear() \n print(i, \"초 뒤 사라집니다.\")\n sleep(1)\n paper.remove(judge_image)\n paper.remove(strike_num_image)\n paper.remove(ball_num_image)\n return\n\ndef displayNameCheck(): #'이름 이(가) 맞습니까?' 화면\n displayCheck(\"namecheck\")\n \n global l_nameCheck\n l_nameCheck = Layer()\n \n nameBox = Rectangle(230,50,Point(148,255))\n nameBox.setBorderWidth(3)\n nameCk = Text(str(userName),40)\n nameCk.moveTo(148,255)\n\n l_nameCheck.add(nameBox)\n l_nameCheck.add(nameCk)\n paper.add(l_nameCheck)\n return\n\ndef displayStartSec(): # n초후 시작합니다\n displayCheck(\"startsec\")\n for i in range(5, 0, -1):\n __clear()\n secNum = Image(resource_path(\"images/numbers13pt/num\"+str(i)+\".png\"))\n secNum.moveTo(100,300)\n secNum.setDepth(50)\n paper.add(secNum)\n sleep(1)\n paper.remove(secNum)\n paper.remove(check)\n return\n\n\n##################################### Other Functions #####################################\n\ndef __clear(): # 콘솔 초기화\n os.system(console_clear)\n \ndef how_to_play(): # 게임 방법\n __clear()\n displayHowToPlay()\n input(\"메인으로 가려면 아무키나 입력하세요: \")\n\ndef view_scores(): # 점수 보기\n __clear()\n paper.clear()\n bg = Image(resource_path(\"images/image/background.png\"))\n bg.moveTo(400, 300)\n paper.add(bg)\n Prize = Layer()\n grade = Text(\" Rank Name Tries\", 25)\n grade.moveTo(400, 100)\n firstEmpty = Text(\"-----------------------------------------------------\", 25)\n firstEmpty.moveTo(400, 130)\n Prize.add(grade)\n Prize.add(firstEmpty)\n paper.add(Prize)\n ThirdEmpty = Text(\"-----------------------------------------------------\", 25)\n ThirdEmpty.moveTo(400, 550)\n paper.add(ThirdEmpty)\n\n tempDict = dict()\n \n with open(resource_path(\"best_user_score.txt\"), \"r\", encoding='utf8') as f:\n while True:\n read = list(f.readline().split())\n if not read:\n break \n user_name, tries = read[0], int(read[1])\n if user_name not in tempDict: \n tempDict[user_name] = tries \n else: \n if tempDict[user_name] > tries:\n tempDict[user_name] = tries\n\n sorted_list = sorted(tempDict.items(), key = lambda x : x[1])\n ranking = 1\n ran = len(sorted_list) if len(sorted_list) <= 10 else 10\n for i in range(ran):\n if sorted_list[i - 1][1] < sorted_list[i][1]:\n ranking += 1\n data = \"%2sth\\t%10s\\t\\t%2d\" % (ranking, sorted_list[i][0], sorted_list[i][1])\n data_text = Text(data, 25)\n data_text.moveTo(400, 160+40*i)\n paper.add(data_text)\n \n input(\"메인으로 가려면 아무키나 입력하세요\")\n\ndef __getRandomNumber(count): # 랜덤한 count자리수 숫자 생성기\n randomList = rd.sample([i for i in range(0, 10)], count)\n returnStr = \"\".join([str(i) for i in randomList])\n return returnStr\n\ndef execute(): # 프로그램 시작\n __clear()\n displayInit()\n choose_option = \"\"\n displayMainScreen()\n while True:\n try:\n choose_option = input(\"옵션을 선택해주세요 : \")\n except:\n __clear()\n continue\n if choose_option == '1':\n while True:\n gs = game_start()\n if gs == -1:\n execute()\n return\n elif choose_option == '2':\n how_to_play()\n execute()\n return\n elif choose_option == '3':\n view_scores()\n execute()\n return\n elif choose_option == '4':\n __clear()\n paper.close()\n return\n \ndef game_start(): # 게임 시작 -> 인게임 -> Retry\n global balls\n global strikes\n global tries\n global givenNumber\n global predictedNumber\n global userName\n\n balls = strikes = tries = 0\n givenNumber = predictedNumber = userName = ans = \"\"\n \n displayingame()\n \n while True:\n displayFix(\"name_input\")\n\n while True:\n __clear()\n userName = input(\"플레이어의 이름을 입력하세요(6자리 최대): \")\n if len(userName) > 6 or \" \" in userName or len(userName) <= 0:\n continue\n else:\n break\n \n paper.remove(fix)\n displayNameCheck()\n __clear()\n ans = input(\"'\" + userName + \"' 이(가) 맞습니까? [Y / N]: \")\n \n if ans[0] == \"y\" or ans[0] == \"Y\":\n paper.remove(l_nameCheck)\n paper.remove(check)\n break\n\n paper.remove(l_nameCheck)\n paper.remove(check)\n continue\n\n __clear()\n ans = \"\"\n while True:\n __clear()\n displayFix(\"choosenum\")\n ans = input(\"사용자가 숫자를 선택할까요? [Y / N]: \")\n if ans not in [\"y\", \"Y\", \"n\", \"N\"]:\n paper.remove(fix)\n continue\n else:\n paper.remove(fix)\n break\n\n ugn = True if (ans == \"y\" or ans == \"Y\") else False\n tries = playGame(ugn)\n \n score = tries\n with open(resource_path(\"best_user_score.txt\"), \"a+\", encoding=\"utf-8\") as f:\n f.write(\"%s %d\\n\" % (userName, score))\n \n displayRetry()\n while True:\n __clear()\n ans = input(\"다시 플레이 하시겠습니까? [Y / N]: \")\n if ans == \"y\" or ans == \"Y\":\n paper.clear()\n return 1\n elif ans == \"n\" or ans == \"N\":\n paper.clear()\n return -1\n else:\n continue\n\ndef playGame(userGivesNumber=False): # 인게임\n global strikes\n global balls\n global tries\n global givenNumber\n global predictedNumber\n \n ask = \" \"\n if userGivesNumber:\n displayFix(\"digit\")\n while True:\n try:\n __clear() \n ask = input(\"자릿수를 입력해주세요 (3 또는 4) : \")\n except:\n continue\n\n if ask == '3' or ask == '4':\n break\n \n givenNumber = __getRandomNumber(int(ask))\n paper.remove(fix)\n\n else:\n __clear()\n givenNumber = __getRandomNumber(rd.randint(3, 4))\n\n displayStartSec()\n __clear()\n displayStartGame()\n\n while True:\n __clear()\n balls = strikes = 0\n while True:\n __clear()\n displayFix(\"guess\")\n t = \"< \" + str(len(givenNumber)) + \"자리수 >\"\n len_givenNumber = Text(t, 30)\n len_givenNumber.moveTo(400, 400)\n paper.add(len_givenNumber)\n predictedNumber = input(\"숫자를 추측하세요: \")\n paper.remove(fix)\n paper.remove(len_givenNumber)\n\n if not predictedNumber.isdigit():\n continue\n\n if len(predictedNumber) != len(givenNumber):\n continue\n\n isDuplicate = False\n for i in range(len(predictedNumber)):\n if not isDuplicate:\n for j in range(len(predictedNumber)):\n if i != j and predictedNumber[i] == predictedNumber[j]:\n displayFix(\"dupl_input\")\n sleep(1)\n paper.remove(fix)\n isDuplicate = not isDuplicate\n break\n\n if isDuplicate == False:\n tries += 1\n break\n\n for i in range(len(givenNumber)):\n for j in range(len(predictedNumber)):\n if givenNumber[i] == predictedNumber[j]:\n if i == j:\n strikes += 1\n else:\n balls += 1\n\n if strikes == 0 and balls == 0:\n displayOutSituation()\n elif strikes == len(givenNumber):\n displayGameOverByWinning()\n return tries\n else:\n __clear()\n displayEvaluationResult()\n continue\n\nexecute()","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":14547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"541158142","text":"import json\n\n\ndef get_server_data(logger):\n # Read the SERVER info from the json.\n try:\n with open('server.json') as data:\n serverdata = json.load(data)\n except Exception as err:\n logger.error(\"av_funcs:get_server_data: failed to read server file {0}: {1}\"\n .format(\"server.json\", err), exc_info=True)\n return False\n data.close()\n # Get the version info\n try:\n version = serverdata[\"credits\"][0][\"version\"]\n except (KeyError, ValueError):\n logger.info(\"Version not found in server.json.\")\n version = '0.0.0'\n # Split version into two floats.\n sv = version.split(\".\")\n v1 = 0\n v2 = 0\n if len(sv) > 0:\n v1 = int(sv[0])\n if len(sv) > 1:\n v2 = int(sv[2])\n serverdata[\"version\"] = version\n serverdata[\"version_major\"] = v1\n serverdata[\"version_minor\"] = v2\n return serverdata\n\n\ndef get_profile_info(logger):\n pvf = \"profile/version.txt\"\n try:\n with open(pvf) as f:\n pv = f.read().replace('\\n', '')\n except Exception as err:\n logger.error(\"get_profile_info: failed to read file {0}: {1}\".format(pvf, err), exc_info=True)\n pv = 0\n return {\"version\": pv}\n","sub_path":"av_funcs.py","file_name":"av_funcs.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"477277482","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.autograd import Variable\nimport torch\n\n\nclass GNNWE(nn.Module):\n def __init__(self, input_dim, output_dim, in_matrix, intermediary_dim = 384, num_classes = 80):\n super(GNNWE, self).__init__()\n self.input_dim = input_dim # 300\n self.intermediary_dim = intermediary_dim # 512\n self.output_dim = output_dim # 1024\n self.in_matrix = in_matrix # 80 * 80\n self.in_matrix = self.in_matrix + torch.eye(num_classes).cuda()\n self.w1 = nn.Linear(input_dim, intermediary_dim)\n self.w2 = nn.Linear(intermediary_dim, output_dim)\n\n self.act = nn.LeakyReLU(0.2)\n\n\n def forward(self, input):\n # input: (80,300)\n node_bf_act = self.in_matrix.mm(input)\n node_bf_act = self.w1(node_bf_act)\n node_af_act = self.act(node_bf_act)\n\n # node_af_act: (80,512)\n node_bf_act = self.in_matrix.mm(node_af_act)\n node_af_act = self.w2(node_bf_act)\n #node_af_act = self.act(node_af_act)\n return node_af_act","sub_path":"TMembedding.py","file_name":"TMembedding.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"110446636","text":"import bpy\nimport bmesh\nfrom .floor_types import create_floors\n\nfrom ...utils import select, get_edit_mesh\n\n\nclass Floor:\n has_mat_groups = False\n\n @classmethod\n def build(cls, context, prop):\n \"\"\"Use floor types and properties to create geometry\n\n Args:\n context (bpy.context): blender context\n prop (bpy.types.PropertyGroup): FloorProperty\n \"\"\"\n\n me = get_edit_mesh()\n bm = bmesh.from_edit_mesh(me)\n\n if cls.validate(bm):\n if any([f for f in bm.faces if f.select]):\n create_floors(bm, None, prop)\n else:\n edges = [e for e in bm.edges if e.is_boundary]\n create_floors(bm, edges, prop)\n bmesh.update_edit_mesh(me, True)\n return {\"FINISHED\"}\n return {\"CANCELLED\"}\n\n @classmethod\n def validate(cls, bm):\n \"\"\" Validate input if any \"\"\"\n if len(list({v.co.z for v in bm.verts})) == 1:\n return True\n elif any([f for f in bm.faces if f.select]):\n return True\n return False\n","sub_path":"core/floor/floor.py","file_name":"floor.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"533422330","text":"# -*- coding:utf-8 _*_\r\n\r\n\"\"\"\r\n第一个测试python程序\r\n\"\"\"\r\n\r\nfrom __future__ import print_function, division\r\nfrom PIL import Image\r\n\r\n\r\ndef main():\r\n\r\n im = Image.open('./autojump.png')\r\n w, h = im.size\r\n print(w, h)\r\n print('we are in' + __name__)\r\n ii = True\r\n te = '哈哈' if ii else '呵呵'\r\n print(te)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"mypython.py","file_name":"mypython.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"487817461","text":"from django.urls import include, path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('gene/', views.gene, name='gene'),\n path('list/', views.list, name='list'),\n path('poslist/', views.poslist, name='poslist'),\n path('delete/', views.delete, name='delete'),\n]\n","sub_path":"files/topic2/bioweb/genedata/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"558329134","text":"class Node():\n \"\"\"节点\"\"\"\n\n def __init__(self, elem):\n self.elem = elem\n self.next = None\n\n\nclass Single_CYCLE_LinkList():\n \"\"\"单向循环链表\"\"\"\n\n def __init__(self, node=None):\n self._head = node\n if node:\n node.next = node\n\n def is_empty(self):\n # 链表是否为空\n if self._head == None:\n return True\n else:\n return False\n\n def length(self):\n # 链表长度\n if self.is_empty():\n return 0\n cur = self._head\n count = 1\n while cur.next != self._head:\n count += 1\n cur = cur.next\n return count\n\n def travel(self):\n # 遍历整个链表\n if self.is_empty():\n return\n else:\n cur = self._head\n while cur.next != self._head:\n print(cur.elem, end=' ')\n cur = cur.next\n print(cur.elem)\n\n def add(self, item):\n node = Node(item)\n if self.is_empty():\n self._head = node\n node.next = node\n else:\n cur = self._head\n while cur.next != self._head:\n cur = cur.next\n node.next = self._head\n self._head = node\n cur.next = node\n\n def append(self, item):\n node = Node(item)\n if self._head == None:\n self._head = node\n node.next = node\n else:\n cur = self._head\n while cur.next != self._head:\n cur = cur.next\n cur.next = node\n node.next = self._head\n\n def insert(self, pos, item):\n if pos <= 0:\n self.add(item)\n elif pos >= self.length():\n self.append(item)\n else:\n node = Node(item)\n pre = self._head\n count = 0\n while count < pos - 1:\n count += 1\n pre = pre.next\n node.next = pre.next\n pre.next = node\n\n def remove(self, item):\n \"\"\"删除一个节点\"\"\"\n # 若链表为空,则直接返回\n if self.is_empty():\n return\n # 将cur指向头节点\n pre = None\n cur = self._head\n while cur.next != self._head:\n if cur.elem == item:\n # 先判断此节点是否是头结点\n if cur == self._head:\n # 先找到尾节点\n rear = self._head\n while rear.next != self._head:\n rear = rear.next\n rear.next = self._head\n self._head = cur.next\n\n else:\n # 中间节点\n pre.next = cur.next\n return\n else:\n pre = cur\n cur = cur.next\n # 退出循环,cur指向尾节点\n if cur.elem == item:\n if self.length() == 1:\n self._head = None\n else:\n pre.next = cur.next\n\n def search(self, item):\n if self.is_empty():\n return False\n cur = self._head\n while cur.next != self._head:\n if cur.elem == item:\n return True\n else:\n cur = cur.next\n if cur.elem == item:\n return True\n return False\n\n\nif __name__ == '__main__':\n single_obj = Single_CYCLE_LinkList()\n print(single_obj.is_empty())\n print(single_obj.length())\n single_obj.append(1)\n single_obj.append(2)\n single_obj.append(3)\n single_obj.append(4)\n single_obj.append(5)\n single_obj.travel()\n single_obj.add(-1)\n single_obj.travel()\n single_obj.insert(-1, -2)\n single_obj.travel()\n single_obj.insert(2, 0)\n single_obj.travel()\n print(single_obj.search(0))\n single_obj.remove(2)\n single_obj.travel()\n single_obj.remove(5)\n single_obj.travel()\n single_obj.remove(-2)\n single_obj.travel()\n","sub_path":"python/linked_list/cycle_list.py","file_name":"cycle_list.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"497280598","text":"# -*- coding: utf-8 -*-\n#######################################################################\n# ----------------------------------------------------------------------------\n# \"THE BEER-WARE LICENSE\" (Revision 42):\n# As long as you retain this notice you\n# can do whatever you want with this stuff. If we meet some day, and you think\n# this stuff is worth it, you can buy me a beer in return. - Muad'Dib\n# ----------------------------------------------------------------------------\n#######################################################################\n\n# Addon Name: Atreides\n# Addon id: plugin.video.atreides\n# Addon Provider: House Atreides\n\n# 3/30/2019 - Sent to me from another addon dev, credit on their work (asked to be left anon)\n# 5/28/2019 - Fixed\n\nimport re\nimport traceback\nimport urllib\nimport urlparse\nimport requests\n\nfrom resources.lib.modules import cleantitle, client, control, debrid, dom_parser2, log_utils, source_utils, workers\n\n\nclass source:\n def __init__(self):\n self.priority = 1\n self.source = ['www']\n self.domains = ['scnsrc.me']\n self.base_link = 'https://www.scnsrc.me'\n\n def movie(self, imdb, title, localtitle, aliases, year):\n try:\n url = {'imdb': imdb, 'title': title, 'year': year}\n url = urllib.urlencode(url)\n return url\n except Exception:\n failure = traceback.format_exc()\n log_utils.log('ScnSrc - Exception: \\n' + str(failure))\n return\n\n def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):\n try:\n url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}\n url = urllib.urlencode(url)\n return url\n except Exception:\n failure = traceback.format_exc()\n log_utils.log('ScnSrc - Exception: \\n' + str(failure))\n return\n\n def episode(self, url, imdb, tvdb, title, premiered, season, episode):\n try:\n if url is None:\n return\n\n url = urlparse.parse_qs(url)\n url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])\n url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode\n url = urllib.urlencode(url)\n return url\n except Exception:\n failure = traceback.format_exc()\n log_utils.log('ScnSrc - Exception: \\n' + str(failure))\n return\n\n def sources(self, url, hostDict, hostprDict, sc_timeout):\n try:\n self._sources = []\n if url is None:\n return self._sources\n\n data = urlparse.parse_qs(url)\n data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])\n\n query = '%s S%02dE%02d' % (\n data['tvshowtitle'],\n int(data['season']),\n int(data['episode'])) if 'tvshowtitle' in data else '%s %s' % (\n data['title'],\n data['year'])\n query = re.sub('(\\\\\\|/| -|:|;|\\*|\\?|\"|\\'|<|>|\\|)', ' ', query)\n\n query = cleantitle.geturl(query)\n url = urlparse.urljoin(self.base_link, query)\n\n self.timer = control.Time(start=True)\n\n shell = requests.Session()\n\n headers = {\n 'Referer': url,\n 'User-Agent':\n 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'}\n r = shell.get(url, headers=headers)\n r = r.headers['Location']\n r = shell.get(r).content\n posts = dom_parser2.parse_dom(r, 'li', {'class': re.compile('.+?'), 'id': re.compile('comment-.+?')})\n self.hostDict = hostDict + hostprDict\n threads = []\n\n for i in posts:\n threads.append(workers.Thread(self._get_sources, i.content, sc_timeout))\n [i.start() for i in threads]\n [i.join() for i in threads]\n\n return self._sources\n except Exception:\n return self._sources\n\n def _get_sources(self, item, sc_timeout):\n try:\n links = dom_parser2.parse_dom(item, 'a', req='href')\n links = [i.attrs['href'] for i in links]\n info = []\n try:\n size = re.findall('((?:\\d+\\.\\d+|\\d+\\,\\d+|\\d+)\\s*(?:GiB|MiB|GB|MB))', item)[0]\n div = 1 if size.endswith('GB') else 1024\n size = float(re.sub('[^0-9|/.|/,]', '', size)) / div\n size = '%.2f GB' % size\n info.append(size)\n except Exception:\n pass\n info = ' | '.join(info)\n for url in links:\n # Stop searching 8 seconds before the provider timeout, otherwise might continue searching, not complete in time, and therefore not returning any links.\n if self.timer.elapsed() > sc_timeout:\n log_utils.log('Scnsrc - Timeout Reached')\n break\n\n if 'youtube' in url:\n continue\n if any(x in url for x in ['.rar.', '.zip.', '.iso.']) or any(\n url.endswith(x) for x in ['.rar', '.zip', '.iso']):\n raise Exception()\n valid, host = source_utils.is_host_valid(url, self.hostDict)\n if not valid:\n continue\n host = client.replaceHTMLCodes(host)\n host = host.encode('utf-8')\n quality, info2 = source_utils.get_release_quality(url, url)\n if url in str(self._sources):\n continue\n self._sources.append(\n {'source': host, 'quality': quality, 'language': 'en', 'url': url, 'info': info, 'direct': False,\n 'debridonly': debrid.status()})\n except Exception:\n pass\n\n def resolve(self, url):\n return url\n","sub_path":"script.module.atreides/lib/resources/lib/sources/www/scnsrc.py","file_name":"scnsrc.py","file_ext":"py","file_size_in_byte":5987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"368599659","text":"import json\nimport os\nimport threading\n\nfrom django.db import transaction\nfrom django.db.models import F\n\nfrom Mryang_App.models import Dir, PhotoWall, Photo\nfrom frames import yutils\nfrom frames.xml import XMLBase\n\npic_config = XMLBase.list_cfg_infos('pic_info') # XMLMedia.get_infos()\n\n\ndef get_base_info():\n bi = {'pic_dir':pic_config.dir_root,'pic_thum':pic_config.thum,'pic_mid':pic_config.middle}\n return bi\n\n\ndef batch_create_on_dir():\n dir_query = Dir.objects.filter(type=yutils.M_FTYPE_PIC)\n dir_names = []\n for dir_db in dir_query:\n if dir_db.parent_dir == None:\n continue\n dir_names.append(os.path.basename(dir_db.rel_path))\n # if dir_db.rel_path:\n pw_query = PhotoWall.objects.all()\n for pw_db in pw_query:\n try:\n dir_names.remove(pw_db.name)\n except:\n pass\n print(dir_names)\n pw_create_list = []\n for d_name in dir_names:\n pw_db = PhotoWall()\n pw_db.nick = pw_db.name = d_name\n pw_create_list.append(pw_db)\n if len(pw_create_list) > 0:\n PhotoWall.objects.bulk_create(pw_create_list)\n return json.dumps({1: '转换成功'})\n return json.dumps({2: '没有可以转换的目标'})\n\n\nin_sync_photo = False\nlock = threading.Lock()\n\n\ndef batch_photo_to_wall():\n global in_sync_photo\n\n def begin():\n batch_create_on_dir()\n pw_query = PhotoWall.objects.all()\n dir_names = {}\n for pw_db in pw_query:\n dir_names[pw_db.name] = pw_db\n with transaction.atomic():\n for p in Photo.objects.all():\n if p.photo_wall_id == None:\n wall_name = os.path.basename(os.path.dirname(p.src_abs_path))\n if wall_name in dir_names:\n p.photo_wall_id = dir_names[wall_name].id\n p.save()\n # 将没有归类的图片自动归类.\n with transaction.atomic():\n for item in dir_names:\n if dir_names[item].thum_photo == None:\n dir_names[item].thum_photo = Photo.objects.filter(photo_wall_id=dir_names[item].id).first()\n dir_names[item].save()\n global in_sync_photo\n in_sync_photo = False\n\n with lock:\n if in_sync_photo:\n return json.dumps({2: '正在转换,请稍等'})\n in_sync_photo = True\n\n threading.Thread(target=begin).start()\n return json.dumps({1: '正在后台同步'})\n\n\ndef photo_wall_list(show_level):\n pw_query = PhotoWall.objects.filter(level__lt=show_level + 1, hidden=False).annotate(\n photo_path=F('thum_photo__desc_rela_path'), mpath=F('thum_photo__desc_mpath__param1')).values('nick', 'id',\n 'intro', 'time',\n 'level',\n 'photo_path',\n 'mpath')\n pw_list= []\n for pw in pw_query:\n pw_list.append(pw)\n pw['pic_count']=Photo.objects.filter(photo_wall_id=pw[\"id\"]).count()\n return json.dumps(list(pw_query))\n\n\ndef photo_list(wall_id):\n pl_query = Photo.objects.filter(photo_wall_id=wall_id).values('desc_rela_path')\n return json.dumps(list(pl_query))\n","sub_path":"MrYangServer/Mryang_App/controlls/PhotoWallCtrl.py","file_name":"PhotoWallCtrl.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"67215668","text":"import nltk\nimport sys\n\nif __name__ == \"__main__\":\n\n text = nltk.word_tokenize(\"Did Mary put the book on the shelf\")\n print(nltk.pos_tag(text))\n\n if (len(sys.argv) >=2):\n fcfg_grammar_file = sys.argv[1]\n sentences_filename = sys.argv[2]\n output_filename = sys.argv[3]\n else:\n fcfg_grammar_file = \"../data/hw5_feature_grammar.fcfg\"\n sentences_filename = \"../data/sent.txt\"\n output_filename = \"../data/ex_sentences_output.txt\"\n #print(\"Incorrect number of arguments\")\n\n # Loading grammar\n grammar = nltk.data.load(fcfg_grammar_file,'fcfg')\n\n # Setting the parser\n parser = nltk.parse.FeatureEarleyChartParser(grammar)\n\n # Opening the sentence file that needs to be parsed\n sentence_file = open(sentences_filename)\n\n sentences = sentence_file.read().split('\\n')\n sentence_count = 0\n overall_parse_count = 0\n\n with open(output_filename, 'w') as op_file:\n for sentence in sentences:\n if (len(sentence) > 0):\n # increment number of sentences\n sentence_count += 1\n sentence = sentence.strip() # strip extra whitepaces if any\n\n # split_sentence = re.findall(r\"[\\w']+|[.,!?;]\", sentence) # splitting using regex\n\n split_sentence = nltk.word_tokenize(sentence) # split sentence\n trees = parser.parse(split_sentence) # parse the sentence\n parse_count = 0\n\n tree_strings = \"\"\n\n\n if not trees:\n tree_strings = ['()']\n else:\n first = True\n for t in trees:\n if first:\n tree_strings = t.pformat(margin=sys.maxsize)\n first = False\n\n op_file.write(tree_strings + '\\n')\n\n # increment overall parse count\n overall_parse_count += parse_count\n\n\n # Compute average and print the average parses per sentence\n #op_file.write('Average parses per sentence: ' + str(overall_parse_count / float(sentence_count)))\n print('Parsing complete')\n #print('Average parses per sentence: ' + str(round((overall_parse_count / float(sentence_count)), 3)))","sub_path":"linguistic_constraints/src/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"9554359","text":"import uuid\n\nfrom django.db import models\nfrom django.utils.translation import ugettext as _\n\n\nclass MenuItemManager(models.Manager):\n \"\"\"Менеджер модели MenuItem.\"\"\"\n def get_queryset(self):\n return super(MenuItemManager, self).get_queryset().select_related('menu', 'domain')\n\n\nclass MenuItem(models.Model):\n \"\"\"Пункты меню с произвольными ссылками (абсолютными внешними или относительными локальными).\n\n Attributes:\n objects (MenuItemManager): Description\n id (UUIDField): Уникальный идентификатор.\n title (CharField): Название.\n slug (SlugField): Псевдоним.\n is_published (BooleanField): Опубликовано (``True``) или НЕ опубликовано (``False``).\n order (PositiveSmallIntegerField): Порядок пунктов меню в меню.\n menu (ForeignKey): Привязка с меню.\n domain (ForeignKey): Привязка с сайту.\n \"\"\"\n objects = MenuItemManager()\n\n id = models.UUIDField(\n primary_key=True,\n default=uuid.uuid4,\n editable=False,\n )\n title = models.CharField(\n max_length=64,\n verbose_name=_('menuitem_title'),\n )\n slug = models.CharField(\n max_length=128,\n blank=True,\n verbose_name=_('menuitem_slug'),\n )\n is_published = models.BooleanField(\n default=False,\n verbose_name=_('menuitem_is_published'),\n )\n order = models.PositiveSmallIntegerField(\n default=1,\n verbose_name=_('menuitem_order'),\n )\n menu = models.ForeignKey(\n 'menu.Menu',\n on_delete=models.CASCADE,\n db_column='menu_id',\n verbose_name=_('menuitem_menu'),\n )\n domain = models.ForeignKey(\n 'location.Domain',\n on_delete=models.CASCADE,\n db_column='domain_id',\n verbose_name=_('menuitem_domain'),\n )\n\n class Meta:\n app_label = 'menu'\n db_table = 'bezantrakta_menu_item'\n verbose_name = _('menuitem')\n verbose_name_plural = _('menuitems')\n ordering = ('order', 'domain', 'menu', 'title',)\n unique_together = (\n ('domain', 'menu', 'slug',),\n )\n\n def __str__(self):\n return self.title\n","sub_path":"bezantrakta/menu/models/menu_item.py","file_name":"menu_item.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"133939276","text":"info = {\n\"name\": \"mbr-sagor\",\n\"age\": 24,\n\"phone\": 474709,\n\"is_programmer\": True\n}\n\nprint(info.get(\"names\", \"Not found\"))\n\nprint('\\n')\n\nfor i in info.values():\n print(i)\n\nuser_input = input(\"Write something: \")\nprint(info[user_input])\n","sub_path":"basic/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"464669486","text":"import sqlite3\nfrom qgis.core import QgsVectorLayer,QgsDataSourceUri,QgsProject\n#from qgis.core import QgsMapLayerRegistry\n\nlayers = QgsProject.instance().mapLayersByName('ResultLayer')\nfor layer in layers:\n QgsProject.instance().removeMapLayer(layer)\n\nwith open(\"M:\\\\Spring18\\\\AdvDB\\\\Project\\\\2.0\\\\input.txt\", \"r\") as ins:\n array = []\n for line in ins:\n array.append(line)\n\nsource=array[0].rstrip()\nradius=float(array[1].rstrip())\nradius=radius*0.00001\ncategory=array[2]\n\n\nwith sqlite3.connect(\"M:\\\\Spring18\\\\AdvDB\\\\Project\\\\2.0\\\\FullMap.sqlite\") as conn:\n conn.enable_load_extension(True)\n conn.load_extension(\"mod_spatialite\")\n\nc=conn.cursor()\n\nif source == \"Source\":\n query = \"select Name from 'UTA_Full_Map Polygon' where description='\"+category+\"'\"\nelse:\n if category==\"Category\":\n query = \"select b2.Name from 'UTA_Full_Map Polygon' b1,'UTA_Full_Map Polygon' b2 where intersects(b2.geom, buffer(b1.geom,\"+str(radius)+\")) and b1.Name='\"+source+\"' and b2.Name!='\"+source+\"'\"\n else:\n query = \"select b2.Name from 'UTA_Full_Map Polygon' b1,'UTA_Full_Map Polygon' b2 where intersects(b2.geom, buffer(b1.geom,\"+str(radius)+\")) and b1.Name='\"+source+\"' and b2.Name!='\"+source+\"' and b2.description='\"+category+\"'\"\n\n#print(\"select b2.Name from 'UTA_Full_Map Polygon' b1,'UTA_Full_Map Polygon' b2 where intersects(b2.geom, buffer(b1.geom,\"+str(radius)+\")) and b1.Name='\"+source+\"' and b2.Name!='\"+source+\"'\")\n\nopfile = open(\"M:\\\\Spring18\\\\AdvDB\\\\Project\\\\2.0\\\\output.txt\",\"w\")\n\nfor row in c.execute(query):\n for member in row:\n uri = QgsDataSourceUri()\n uri.setDatabase('M:\\\\Spring18\\\\AdvDB\\\\Project\\\\2.0\\\\FullMap.sqlite')\n uri.setDataSource('', 'uta_full_map polygon', 'geom',\"Name = '\"+member+\"'\",'')\n vlayer = QgsVectorLayer(uri.uri(), 'ResultLayer', 'spatialite')\n QgsProject.instance().addMapLayer(vlayer)\n vlayer.isValid()\n opfile.write(member+\"\\n\")\n \nopfile.close()\nins.close()\nc.close()\n\n","sub_path":"withinmiles-new.py","file_name":"withinmiles-new.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"576278476","text":"import logging\nimport pandas as pd\nimport numpy as np\nfrom motu_utils.utils_cas import authenticate_CAS_for_URL\nfrom motu_utils.utils_http import open_url\nimport xarray as xr\nfrom datetime import datetime, timedelta\nimport time\nfrom pathlib import Path\nfrom bs4 import BeautifulSoup\nfrom ais import check_dir\nfrom xarray.backends import NetCDF4DataStore\nfrom siphon.catalog import TDSCatalog\nfrom siphon import http_util\n# utils to convert dates\nfrom check_connection import CheckConnection\n\nstr_to_date = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')\ndate_to_str = lambda x: x.strftime('%Y-%m-%dT%H:%M:%SZ')\nimport os\n\nlogger = logging.getLogger(__name__)\n\n# credentials for the dataset\nUN_CMEMS = os.environ['UN_CMEMS']\nPW_CMEMS = os.environ['PW_CMEMS']\nUN_RDA = os.environ['UN_RDA']\nPW_RDA = os.environ['PW_RDA']\n\nGFS_VAR_LIST = ['Temperature_surface', 'Wind_speed_gust_surface', 'u-component_of_wind_maximum_wind',\n 'v-component_of_wind_maximum_wind', 'Dewpoint_temperature_height_above_ground',\n 'U-Component_Storm_Motion_height_above_ground_layer',\n 'V-Component_Storm_Motion_height_above_ground_layer', 'Relative_humidity_height_above_ground']\n\n\ndef get_global_wave(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi):\n \"\"\"\n retrieve all wave variables for a specific timestamp, latitude, longitude concidering\n the temporal resolution of the dataset to calculate interpolated values\n \"\"\"\n logger.debug('obtaining GLOBAL_REANALYSIS_WAV dataset for DATE [%s, %s] LAT [%s, %s] LON [%s, %s]' % (\n str(date_lo), str(date_hi), str(lat_lo), str(lat_hi), str(lon_lo), str(lon_hi)))\n\n if date_lo < datetime(2019, 1, 1):\n CheckConnection.set_url('my.cmems-du.eu')\n base_url = 'https://my.cmems-du.eu/motu-web/Motu?action=productdownload'\n service = 'GLOBAL_REANALYSIS_WAV_001_032-TDS'\n product = 'global-reanalysis-wav-001-032'\n else:\n CheckConnection.set_url('nrt.cmems-du.eu')\n base_url = 'https://nrt.cmems-du.eu/motu-web/Motu?action=productdownload'\n service = 'GLOBAL_ANALYSIS_FORECAST_WAV_001_027-TDS'\n product = 'global-analysis-forecast-wav-001-027'\n dataset_temporal_resolution = 180\n\n y_lo = float(lat_lo)\n y_hi = float(lat_hi)\n x_lo = float(lon_lo)\n x_hi = float(lon_hi)\n\n # time lower\n time_in_min = (date_lo.hour * 60) + date_lo.minute\n rest = time_in_min % dataset_temporal_resolution\n t_lo = date_lo - timedelta(minutes=rest)\n\n # time upper\n time_in_min = (date_hi.hour * 60) + date_hi.minute\n rest = time_in_min % dataset_temporal_resolution\n t_hi = date_hi + timedelta(minutes=dataset_temporal_resolution - rest)\n\n url = base_url + '&service=' + service + '&product=' + product + '&x_lo={0}&x_hi={1}&y_lo={2}&y_hi={3}&t_lo={4}&t_hi={5}&mode=console'.format(\n x_lo, x_hi, y_lo,\n y_hi,\n date_to_str(\n t_lo),\n date_to_str(\n t_hi))\n\n data = try_get_data(url)\n return data\n\n\ndef get_global_phy_hourly(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi):\n \"\"\"\n retrieve including ... variables for a specific timestamp, latitude, longitude considering\n the temporal resolution of the dataset to calculate interpolated values\n \"\"\"\n\n logger.debug('obtaining GLOBAL_ANALYSIS_FORECAST_PHY Hourly dataset for DATE [%s, %s] LAT [%s, %s] LON [%s, %s]' % (\n str(date_lo), str(date_hi), str(lat_lo), str(lat_hi), str(lon_lo), str(lon_hi)))\n\n CheckConnection.set_url('nrt.cmems-du.eu')\n base_url = 'https://nrt.cmems-du.eu/motu-web/Motu?action=productdownload&service=GLOBAL_ANALYSIS_FORECAST_PHY_001_024-TDS'\n products = ['global-analysis-forecast-phy-001-024-hourly-t-u-v-ssh',\n 'global-analysis-forecast-phy-001-024-hourly-merged-uv']\n dataset_temporal_resolution = 60\n time_in_min = (date_lo.hour * 60) + date_lo.minute\n rest = time_in_min % dataset_temporal_resolution\n\n # available times are at min 30 of each hour\n if date_lo.minute >= 30:\n t_lo = date_lo - timedelta(minutes=rest) + timedelta(minutes=30)\n else:\n t_lo = date_lo - timedelta(minutes=rest) - timedelta(minutes=30)\n\n time_in_min = (date_hi.hour * 60) + date_hi.minute\n rest = time_in_min % dataset_temporal_resolution\n\n if date_hi.minute >= 30:\n t_hi = date_hi + timedelta(minutes=(dataset_temporal_resolution - rest)) + timedelta(minutes=30)\n else:\n t_hi = date_hi + timedelta(minutes=(dataset_temporal_resolution - rest)) - timedelta(minutes=30)\n\n # coordinates\n y_lo = float(lat_lo)\n y_hi = float(lat_hi)\n x_lo = float(lon_lo)\n x_hi = float(lon_hi)\n\n # depth\n z_hi = 0.50\n z_lo = 0.49\n\n url = base_url + '&product=' + products[0] + '&product=global-analysis-forecast-phy-001-024-hourly-t-u-v-ssh' + \\\n '&x_lo={0}&x_hi={1}&y_lo={2}&y_hi={3}&t_lo={4}&t_hi={5}&z_lo={6}&z_hi={7}&mode=console'.format(x_lo, x_hi,\n y_lo,\n y_hi,\n date_to_str(\n t_lo)\n , date_to_str(\n t_hi), z_lo, z_hi)\n data = try_get_data(url)\n time.sleep(1)\n\n url = base_url + '&product=' + products[1] + '&product=global-analysis-forecast-phy-001-024-hourly-t-u-v-ssh' + \\\n '&x_lo={0}&x_hi={1}&y_lo={2}&y_hi={3}&t_lo={4}&t_hi={5}&z_lo={6}&z_hi={7}&mode=console'.format(x_lo, x_hi,\n y_lo,\n y_hi,\n date_to_str(\n t_lo)\n , date_to_str(\n t_hi), z_lo, z_hi)\n\n data1 = try_get_data(url)\n return data, data1\n\n\ndef try_get_data(url):\n try:\n CheckConnection.is_online()\n url_auth = authenticate_CAS_for_URL(url, UN_CMEMS, PW_CMEMS)\n CheckConnection.is_online()\n bytes_data = open_url(url_auth).read()\n CheckConnection.is_online()\n return xr.open_dataset(bytes_data)\n except Exception as e:\n raise ValueError('Error:', BeautifulSoup(bytes_data, 'html.parser').find('p', {\"class\": \"error\"}), 'Request: ',\n url)\n\n\ndef get_global_wind(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi):\n\n logger.debug('obtaining WIND_GLO_WIND_L4_NRT_OBSERVATIONS dataset for DATE [%s, %s] LAT [%s, %s] LON [%s, %s]' % (\n str(date_lo), str(date_hi), str(lat_lo), str(lat_hi), str(lon_lo), str(lon_hi)))\n CheckConnection.set_url('nrt.cmems-du.eu')\n base_url = 'https://nrt.cmems-du.eu/motu-web/Motu?action=productdownload'\n service = 'WIND_GLO_WIND_L4_NRT_OBSERVATIONS_012_004-TDS'\n product = 'CERSAT-GLO-BLENDED_WIND_L4-V6-OBS_FULL_TIME_SERIE'\n dataset_temporal_resolution = 360\n time_in_min = (date_lo.hour * 60) + date_lo.minute\n rest = time_in_min % dataset_temporal_resolution\n t_lo = date_lo - timedelta(minutes=rest) # extract the lower bound\n\n time_in_min = (date_hi.hour * 60) + date_hi.minute\n rest = time_in_min % dataset_temporal_resolution\n t_hi = date_hi + timedelta(minutes=dataset_temporal_resolution - rest)\n\n y_lo = float(lat_lo)\n y_hi = float(lat_hi)\n x_lo = float(lon_lo)\n x_hi = float(lon_hi)\n\n url = base_url + '&service=' + service + '&product=' + product + '&x_lo={0}&x_hi={1}&y_lo={2}&y_hi={3}&t_lo={4}&t_hi={5}&mode=console'.format(\n x_lo, x_hi, y_lo,\n y_hi,\n date_to_str(\n t_lo),\n date_to_str(\n t_hi))\n data = try_get_data(url)\n return data\n\n\ndef get_cached(dataset, date, lat, lon, name):\n if name in ['wave', 'phy_0', 'phy_1']:\n df = dataset.interp(longitude=[lon], latitude=[lat], time=[date], method='linear').to_dataframe()\n if name == 'phy_1':\n df.drop(columns=['uo', 'vo'], inplace=True)\n elif name == 'wind':\n df = dataset.interp(lon=[lon], lat=[lat], time=[date], method='linear').to_dataframe()\n elif name == 'phy_daily':\n df = dataset.sel(longitude=[lon], latitude=[lat], time=[date], method='nearest').to_dataframe()\n df.drop(columns=['thetao', 'uo', 'vo', 'zos'], inplace=True)\n elif name == 'gfs50':\n df = dataset.sel(lon=[lon], lat=[lat], time=[date], time1=[date], method='nearest').to_dataframe()\n df.drop(columns=['LatLon_Projection'], inplace=True)\n elif name == 'gfs25':\n lon = ((lon + 180) % 360) + 180\n df = dataset.interp(latitude=[lat], longitude=[lon], bounds_dim=1, time=[date]).to_dataframe()\n df = df[GFS_VAR_LIST]\n return np.ravel(df.values), list(df.columns)\n\n\ndef get_GFS_25(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi):\n logger.debug('obtaining GFS 0.25 dataset for DATE [%s, %s] LAT [%s, %s] LON [%s, %s]' % (\n str(date_lo), str(date_hi), str(lat_lo), str(lat_hi), str(lon_lo), str(lon_hi)))\n x_arr_list = []\n base_url = 'https://rda.ucar.edu/thredds/catalog/files/g/ds084.1'\n CheckConnection.set_url('rda.ucar.edu')\n # calculate a day prior for midnight interpolation\n http_util.session_manager.set_session_options(auth=(UN_RDA, PW_RDA))\n start_date = datetime(date_lo.year, date_lo.month, date_lo.day) - timedelta(days=1)\n start_cat = TDSCatalog(\n \"%s/%s/%s%.2d%.2d/catalog.xml\" % (base_url, start_date.year, start_date.year, start_date.month, start_date.day))\n ds_subset = start_cat.datasets[\n 'gfs.0p25.%s%.2d%.2d18.f006.grib2' % (start_date.year, start_date.month, start_date.day)].subset()\n query = ds_subset.query().lonlat_box(north=lat_hi, south=lat_lo, east=lon_hi, west=lon_lo).variables(\n *GFS_VAR_LIST)\n CheckConnection.is_online()\n data = ds_subset.get_data(query)\n x_arr = xr.open_dataset(NetCDF4DataStore(data))\n if 'time1' in list(x_arr.coords):\n x_arr = x_arr.rename({'time1': 'time'})\n x_arr_list.append(x_arr)\n\n for day in range((date_hi - date_lo).days + 1):\n end_date = datetime(date_lo.year, date_lo.month, date_lo.day) + timedelta(days=day)\n end_cat = TDSCatalog(\n \"%s/%s/%s%.2d%.2d/catalog.xml\" % (base_url, end_date.year, end_date.year, end_date.month, end_date.day))\n for cycle in [0, 6, 12, 18]:\n for hours in [3, 6]:\n name = 'gfs.0p25.%s%.2d%.2d%.2d.f0%.2d.grib2' % (\n end_date.year, end_date.month, end_date.day, cycle, hours)\n ds_subset = end_cat.datasets[name].subset()\n query = ds_subset.query().lonlat_box(north=lat_hi, south=lat_lo, east=lon_hi, west=lon_lo).variables(\n *GFS_VAR_LIST)\n CheckConnection.is_online()\n data = ds_subset.get_data(query)\n x_arr = xr.open_dataset(NetCDF4DataStore(data))\n if 'time1' in list(x_arr.coords):\n x_arr = x_arr.rename({'time1': 'time'})\n x_arr_list.append(x_arr)\n return xr.combine_by_coords(x_arr_list).squeeze()\n\n\ndef get_GFS(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi):\n logger.debug('obtaining GFS 0.50 dataset for DATE [%s, %s] LAT [%s, %s] LON [%s, %s]' % (\n str(date_lo), str(date_hi), str(lat_lo), str(lat_hi), str(lon_lo), str(lon_hi)))\n vars = {'0': [\n 'Temperature_surface',\n 'Wind_speed_gust_surface',\n 'u-component_of_wind_maximum_wind',\n 'v-component_of_wind_maximum_wind',\n 'Dewpoint_temperature_height_above_ground',\n 'U-Component_Storm_Motion_height_above_ground_layer',\n 'V-Component_Storm_Motion_height_above_ground_layer',\n 'Relative_humidity_height_above_ground'],\n\n '3': ['Precipitation_rate_surface_3_Hour_Average',\n 'Temperature_surface',\n 'Wind_speed_gust_surface',\n 'u-component_of_wind_maximum_wind',\n 'v-component_of_wind_maximum_wind',\n 'Categorical_Freezing_Rain_surface_3_Hour_Average',\n 'Categorical_Ice_Pellets_surface_3_Hour_Average',\n 'Categorical_Rain_surface_3_Hour_Average',\n 'Categorical_Snow_surface_3_Hour_Average',\n 'Dewpoint_temperature_height_above_ground',\n 'U-Component_Storm_Motion_height_above_ground_layer',\n 'V-Component_Storm_Motion_height_above_ground_layer',\n 'Relative_humidity_height_above_ground'],\n\n '6': ['Precipitation_rate_surface_6_Hour_Average',\n 'Temperature_surface',\n 'Wind_speed_gust_surface',\n 'u-component_of_wind_maximum_wind',\n 'v-component_of_wind_maximum_wind',\n 'Dewpoint_temperature_height_above_ground',\n 'U-Component_Storm_Motion_height_above_ground_layer',\n 'V-Component_Storm_Motion_height_above_ground_layer',\n 'Relative_humidity_height_above_ground']}\n\n base_url = 'https://www.ncei.noaa.gov/thredds/model-gfs-g4-anl-files-old/'\n CheckConnection.set_url('https://ncei.noaa.gov')\n\n dataList = []\n for day in range((date_hi - date_lo).days + 1):\n Hour_Averages = [0, 3, 6]\n for Hour_Average in Hour_Averages:\n for a in [0, 6, 12, 18]:\n attempts = 0\n while True:\n try:\n attempts += 1\n dt = datetime(date_lo.year, date_lo.month, date_lo.day, a) + timedelta(days=day)\n catalog = TDSCatalog(\n '%s%s%.2d/%s%.2d%.2d/catalog.xml' % (\n base_url, dt.year, dt.month, dt.year, dt.month, dt.day))\n ds_name = 'gfsanl_4_%s%.2d%.2d_%.2d00_00%s.grb2' % (\n dt.year, dt.month, dt.day, dt.hour, Hour_Average)\n datasets = list(catalog.datasets)\n if ds_name in datasets:\n ncss = catalog.datasets[ds_name].subset()\n query = ncss.query().time(dt + timedelta(hours=Hour_Average)).lonlat_box(\n north=lat_hi, south=lat_lo, east=lon_hi, west=lon_lo).variables(\n *vars[str(Hour_Average)])\n data = ncss.get_data(query)\n ncss.unit_handler(data)\n x_arr = xr.open_dataset(NetCDF4DataStore(data))\n dataList.append(x_arr)\n else:\n logger.warning('dataset %s is not found' % ds_name)\n break\n except Exception as e:\n CheckConnection.is_online()\n time.sleep(1.5)\n if attempts % 20 == 0:\n logger.error(e)\n logger.error('Filename %s - Failed connecting to GFS Server - number of attempts: %d' % (\n ds_name, attempts))\n return xr.merge(dataList, compat='override').squeeze().ffill(dim='time1').ffill(dim='time')\n\n\ndef get_global_phy_daily(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi):\n logger.debug('obtaining GLOBAL_ANALYSIS_FORECAST_PHY Daily dataset for DATE [%s, %s] LAT [%s, %s] LON [%s, %s]' % (\n str(date_lo), str(date_hi), str(lat_lo), str(lat_hi), str(lon_lo), str(lon_hi)))\n CheckConnection.set_url('nrt.cmems-du.eu')\n base_url = 'https://nrt.cmems-du.eu/motu-web/Motu?action=productdownload&service=GLOBAL_ANALYSIS_FORECAST_PHY_001_024-TDS'\n product = 'global-analysis-forecast-phy-001-024'\n\n t_lo = datetime(date_lo.year, date_lo.month, date_lo.day, 12)\n t_hi = datetime(date_hi.year, date_hi.month, date_hi.day, 12) + timedelta(days=1)\n\n # coordinates\n y_lo = float(lat_lo)\n y_hi = float(lat_hi)\n x_lo = float(lon_lo)\n x_hi = float(lon_hi)\n\n # depth\n z_hi = 0.50\n z_lo = 0.49\n\n url = base_url + '&product=' + product + '&product=global-analysis-forecast-phy-001-024-hourly-t-u-v-ssh' + \\\n '&x_lo={0}&x_hi={1}&y_lo={2}&y_hi={3}&t_lo={4}&t_hi={5}&z_lo={6}&z_hi={7}&mode=console'.format(x_lo, x_hi,\n y_lo,\n y_hi,\n date_to_str(\n t_lo)\n , date_to_str(\n t_hi), z_lo, z_hi)\n data = try_get_data(url)\n return data\n\n\ndef append_to_csv(in_path, out_path):\n # get extracted AIS data and remove index column\n df = pd.read_csv(in_path, parse_dates=['BaseDateTime'], date_parser=str_to_date)\n df.drop(['Unnamed: 0'], axis=1, errors='ignore', inplace=True)\n\n # retrieve the data for each file once\n lat_hi = df.LAT.max()\n lon_hi = df.LON.max()\n\n lat_lo = df.LAT.min()\n lon_lo = df.LON.min()\n\n date_lo = df.BaseDateTime.min()\n date_hi = df.BaseDateTime.max()\n\n # the datasets could have different resolutions\n gfs_dataset = get_GFS_25(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi)\n daily_phy_dataset = get_global_phy_daily(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi)\n wind_dataset = get_global_wind(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi)\n wave_dataset = get_global_wave(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi)\n phy_0_dataset, phy_1_dataset = get_global_phy_hourly(date_lo, date_hi, lat_lo, lat_hi, lon_lo, lon_hi)\n\n # define new columns for the output dataframe\n cols = list(df.columns)\n data_list = []\n for x in df.values:\n logger.debug('Interpolate cached data for DATE %s, LAT %s and LON %s' % (\n str(date), str(lat), str(lon)))\n date, lat, lon = x[:3]\n\n wind_val, wind_cols = get_cached(wind_dataset, date, lat, lon, 'wind')\n\n wave_val, wave_cols = get_cached(wave_dataset, date, lat, lon, 'wave')\n\n phy_0_val, phy_cols_0 = get_cached(phy_0_dataset, date, lat, lon, 'phy_0')\n\n phy_1_val, phy_cols_1 = get_cached(phy_1_dataset, date, lat, lon, 'phy_1')\n\n daily_phy_val, daily_phy_cols = get_cached(daily_phy_dataset, date, lat, lon, 'phy_daily')\n\n gfs_val, gfs_cols = get_cached(gfs_dataset, date, lat, lon, 'gfs25')\n\n data_list.append(np.concatenate([x, wind_val, wave_val, phy_0_val, phy_1_val, daily_phy_val, gfs_val]))\n pd.DataFrame(data_list,\n columns=cols + wind_cols + wave_cols + phy_cols_0 + phy_cols_1 + daily_phy_cols + gfs_cols).to_csv(\n out_path)\n\n\ndef append_environment_data(year, min_time_interval, work_dir):\n src_csv_path = Path(work_dir, str(year) + '_filtered_%s' % min_time_interval)\n output_csv_path = Path(work_dir, str(year) + '_merged_%s' % min_time_interval)\n Path(output_csv_path).mkdir(parents=True, exist_ok=True)\n csv_list = check_dir(src_csv_path)\n for file in csv_list:\n if Path(output_csv_path, file).exists(): continue\n logger.debug('append_environment_data in file %s' % str(Path(src_csv_path, file)))\n append_to_csv(Path(src_csv_path, file), Path(output_csv_path, file))\n","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":20139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"13202355","text":"from tornado.web import RequestHandler\r\nimport services.version\r\n\r\nclass ChangesController(RequestHandler):\r\n\tdef get(self, edition, version, current_version=\"\"):\r\n\t\tedition = edition.lower()\r\n\t\tif version == \"latest\":\r\n\t\t\tversion = services.version.get_latest_version(edition)\r\n\t\tchange = {\r\n\t\t\t\"files_status\": {\r\n\t\t\t\t\"VisualSubtitle.Application.dll\": True,\r\n\t\t\t\t\"VisualSubtitle.exe\": True,\r\n\t\t\t\t\"Test/Test.exe\": False\r\n\t\t\t},\r\n\t\t\t\"change_log\": {\r\n\t\t\t\t\"new_functions\": [\r\n\t\t\t\t\t\t\"搜索替换功能\",\r\n\t\t\t\t\t\t\"使用全新图标和名称\",\r\n\t\t\t\t\t\t\"错误日志\"\r\n\t\t\t\t],\r\n\t\t\t\t\"fixed_bugs\":\t[\r\n\r\n\t\t\t\t],\r\n\t\t\t\t\"known_issues\": [\r\n\t\t\t\t\t\t\"双语轴处理ComboBox选取困难\",\r\n\t\t\t\t\t\t\"标签栏不会自动移动到已激活标签\",\r\n\t\t\t\t\t\t\"不同标签共享一套滚动条\",\r\n\t\t\t\t\t\t\"程序为非异步程序,单线程执行\"\r\n\t\t\t\t],\r\n\t\t\t\t\"fixed_issues\":\t[\r\n\r\n\t\t\t\t]\r\n\t\t\t},\r\n\t\t\t\"debug\": {\r\n\t\t\t\t\"current_version\": current_version\r\n\t\t\t}\r\n\t\t}\r\n\t\tself.write(change)","sub_path":"app/update/changes.py","file_name":"changes.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"324366563","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 12 14:46:42 2017\n\n@author: xavierbrochet\n\"\"\"\n\nimport csv\nimport codecs\nimport os\nimport time\nimport sys, datetime\nimport re\nfrom multiprocessing import Pool\n\nfrom objects_new.Families_new import *\nfrom objects_new.Genus_new import *\nfrom objects_new.Species_new import *\nfrom objects_new.Strains_new import *\n\nfrom objects_new.WholeDNA_new import *\nfrom objects_new.Organisms_new import *\nfrom objects_new.Contigs_new import *\n\nfrom objects_new.Proteins_new import *\nfrom objects_new.Gene_new import *\n\nfrom files_treatment.fasta_parsing import *\nfrom files_treatment.fasta_parsing2 import *\n\nfrom objects_new.Couples_new import *\n\n#dirData = '/Users/xavierbrochet/Documents/projets/INPHINITY/Database/TestloadDatabase'\ndirData = '/home/diogo.leite/Scripts_xavier/data'\ncouplePhageBact = dirData+'/InteractionFound.csv'\ndirBac = dirData+'/bacteria/'\ndirPhage = dirData+'/phages2/'\nGENOME = '_COMPLETE.fasta'\nWGS = '_WHOLESHOTGUN.fasta'\nCDS = '_DNA_CS.fasta'\nPROT = '_PROTEIN_CS.fasta'\nlevel = {'strain': 4, 'specie': 3}\n\nmissingData = dirData+'/missingData.txt'\n\ndef parse_organism(taxon, dic_genome, dict_prot, dict_nn, source, orga, AC_Orga):\n \n #%% Taxonomy insertion insertion dans la base de données\n family_obj = Family(designation=taxon['family'])\n id_family = family_obj.create_family()\n genus_obj = Genus(designation=taxon['genus'], fk_family=id_family)\n id_genus = genus_obj.create_genus()\n specie_obj = Specie(designation=taxon['specie'], fk_genus=id_genus)\n id_specie = specie_obj.create_specie()\n strain_obj = Strain(designation=taxon['strain'], fk_specie=id_specie)\n id_strain = strain_obj.create_strain()\n\n #%% Whole_Genome\n if len(dic_genome) == 1:\n for genome_key in dic_genome.keys():\n whole_genome_obj = WholeDNA(head=str(dic_genome[genome_key][1]), head_id=AC_Orga, sequence=str(dic_genome[genome_key][2]))\n id_whole_genome = whole_genome_obj.create_whole_dna()\n else:\n compteur = 0;\n for genome_key in dic_genome.keys():\n if compteur == 0 :\n head = taxon['specie']+'_'+taxon['strain']\n whole_genome_obj = WholeDNA(head = head, head_id = AC_Orga, sequence=\"NA\")\n id_whole_genome = whole_genome_obj.create_whole_dna()\n contig_obj = Contig(id_contig_db_outside = str(dic_genome[genome_key][0]), head=str(dic_genome[genome_key][1]), sequence = str(dic_genome[genome_key][2]), fk_id_whole_genome=id_whole_genome)\n id_contig = contig_obj.create_contig()\n compteur+=1\n \n #%% Organism \n #source phagedb= 2; NCBI=1\n if len(dic_genome) == 1: #(assemble...)\n for genome_key in dic_genome.keys():\n organism_obj = Organism(id_organism=-1, gi='NA', acc_num=AC_Orga, qty_proteins=len(dict_prot.keys()), assembled=1, qty_contig=0, fk_source=1, fk_strain=id_strain, fk_type = orga, fk_whole_genome = id_whole_genome, fk_source_data=source)\n id_organism = organism_obj.create_organism()\n else:\n organism_obj = Organism(id_organism=-1, gi='NA', acc_num=AC_Orga, qty_proteins=len(dict_prot.keys()), assembled=0, qty_contig=len(dic_genome), fk_source =1, fk_strain=id_strain, fk_type=orga, fk_whole_genome=id_whole_genome, fk_source_data=source)\n id_organism = organism_obj.create_organism()\n\n#%% Protein treatment \n list_of_proteins = []\n\n aux = 0\n for protein_key in dict_prot.keys():\n if dict_nn is not None:\n try:\n seq_nc = dict_nn[protein_key.replace('prot','cds')]\n protein_obj = Protein(id_protein = -1, id_accession = dict_prot[protein_key][0], designation = dict_prot[protein_key][4], sequence_prot = str(dict_prot[protein_key][5]), sequence_dna = str(seq_nc[5]), start_point = dict_prot[protein_key][1], end_point = dict_prot[protein_key][2], start_point_cnt = -1, end_point_cnt = -1, fk_id_contig = -1)\n except KeyError:\n protein_obj = Protein(id_protein = -1, id_accession = dict_prot[protein_key][0], designation = dict_prot[protein_key][4], sequence_prot = str(dict_prot[protein_key][5]), sequence_dna = \"\", start_point = dict_prot[protein_key][1], end_point = dict_prot[protein_key][2], start_point_cnt = -1, end_point_cnt = -1, fk_id_contig = -1)\n else:\n protein_obj = Protein(id_protein = -1, id_accession = dict_prot[protein_key][0], designation = dict_prot[protein_key][4], sequence_prot = str(dict_prot[protein_key][5]), sequence_dna = \"\", start_point = dict_prot[protein_key][1], end_point = dict_prot[protein_key][2], start_point_cnt = -1, end_point_cnt = -1, fk_id_contig = -1) #peut etreje ne sais pas trop les valeurs... ici a voir\n \n list_of_proteins.append(protein_obj)\n for protein in list_of_proteins:\n id_protein = protein.create_protein()\n gene_obj = Gene(FK_id_organism=id_organism, FK_id_protein=id_protein)\n value_id_gene = gene_obj.create_gene()\n aux += 1\n if aux % 1500 == 0:\n time.sleep(3)\n \n return id_organism\n\ndef setPhage(row, source):\n \n taxon = {}\n phageName = row[0]\n phage_acc = row[1]\n\n id_phage = Organism.get_organism_id_by_acc_or_designation(phage_acc, row[0].strip())\n if id_phage == -1:\n \n if row[1]!='NA':\n if source==2:\n phage = row[1]+\"_\"+row[0]\n elif source==1:\n phage = row[1]\n else:\n phage = row[0]\n\n if row[1]!='NA':\n if source==2:\n filePhageGen = dirPhage+row[1]+\"_\"+row[0]+GENOME \n filePhageWGS = dirPhage+row[1]+\"_\"+row[0]+WGS\n elif source == 1:\n filePhageGen = dirPhage+row[1]+GENOME \n filePhageWGS = dirPhage+row[1]+WGS\n filePhageCDS = dirPhage+row[1]+CDS\n filePhagePROT = dirPhage+row[1]+PROT\n else:\n filePhageGen = dirPhage+row[0]+GENOME\n filePhageWGS = dirPhage+row[0]+WGS\n filePhageCDS = dirPhage+row[0]+CDS\n filePhagePROT = dirPhage+row[0]+PROT\n \n if os.path.isfile(filePhageGen):\n fasta_file_genome = Fasta_parsing2(filePhageGen)\n dict_values_genome = fasta_file_genome.parse_fasta_genome()\n elif os.path.isfile(filePhageWGS):\n fasta_file_genome = Fasta_parsing2(filePhageWGS)\n dict_values_genome = fasta_file_genome.parse_fasta_WGS()\n else:\n with open(missingData,'a') as file:\n file.write(str(row)+': Phage -> manque le fichier GENOME')\n return None\n \n if os.path.isfile(filePhageCDS):\n fasta_file_cds = Fasta_parsing2(filePhageCDS)\n if row[1]!='NA':\n dict_values_cds = fasta_file_cds.parse_fasta_ncbi()\n else:\n dict_values_cds = fasta_file_cds.parse_fasta_GeneMark()\n else:\n dict_values_cds = None\n \n if os.path.isfile(filePhagePROT):\n fasta_file_protein = Fasta_parsing2(filePhagePROT)\n if row[1]!='NA':\n dict_values_proteins = fasta_file_protein.parse_fasta_ncbi()\n else:\n dict_values_proteins = fasta_file_protein.parse_fasta_GeneMark()\n else:\n with open(missingData,'a') as file:\n file.write(str(row)+': Phage -> manque le fichier PROTEIN')\n return None\n \n taxon = {'family': 'Phage no family', 'genus': 'Phage no genuse', 'specie': 'Phage no Specie', 'strain': row[0].strip()}\n id_phage = parse_organism(taxon, dict_values_genome, dict_values_proteins, dict_values_cds, source, 2, phage_acc)\n \n return id_phage\n \ndef SetBacterium(row, source):\n \n bacterium = row[0]\n \n id_bact = Organism.get_id_organism_by_acc(bacterium)\n if id_bact == -1:\n taxon = {}\n fileBactGen = dirBac+bacterium+GENOME\n fileBactWGS = dirBac+bacterium+WGS\n fileBactCDS = dirBac+bacterium+CDS\n fileBactPROT = dirBac+bacterium+PROT\n \n if os.path.isfile(fileBactGen):\n fasta_file_genome = Fasta_parsing2(fileBactGen)\n dict_values_genome = fasta_file_genome.parse_fasta_genome()\n elif os.path.isfile(fileBactWGS):\n fasta_file_genome = Fasta_parsing2(fileBactWGS)\n dict_values_genome = fasta_file_genome.parse_fasta_WGS()\n else:\n #ecrire dans un fichier... manque le fichier Genome ou WGS pour la bacterie truc\n with open(missingData,'a') as file:\n file.write(str(row[0])+': Bacterium -> manque le fichier Genome')\n return None\n \n if os.path.isfile(fileBactCDS):\n fasta_file_cds = Fasta_parsing2(fileBactCDS)\n dict_values_cds = fasta_file_cds.parse_fasta_ncbi()\n else:\n dict_values_cds = None\n \n if os.path.isfile(fileBactPROT):\n fasta_file_protein = Fasta_parsing2(fileBactPROT)\n with open(fileBactPROT,'r') as f:\n firstligne = f.readline()\n matchObj = re.search('^>gene_', firstligne)\n if matchObj:\n dict_values_proteins = fasta_file_protein.parse_fasta_GeneMark()\n else:\n dict_values_proteins = fasta_file_protein.parse_fasta_ncbi()\n else:\n with open(missingData,'a') as file:\n file.write(str(row[0])+': Bacterium -> manque le fichier PROTEIN')\n return None\n \n #preparation de la taxonomie...\n posL = len(row)\n strain= row[posL-1]\n if 'group' in row[posL-3]:\n specie = row[posL-4]+' '+row[posL-2]\n genus = row[posL-4]\n family = row[posL-5]\n else:\n specie = row[posL-3]+' '+row[posL-2]\n genus = row[posL-3]\n family = row[posL-4]\n \n taxon = {'family': family, 'genus': genus, 'specie': specie.strip(), 'strain': strain}\n id_bact = parse_organism(taxon, dict_values_genome, dict_values_proteins, dict_values_cds, source, 1, bacterium)\n \n return id_bact\n\n#%% Parse fichier Couple\ndef parseCSV(row):\n\n print('######## COUPLE:########')\n print('row:'+str(row))\n if row[4]=='phagedb':\n source = 2\n else:\n source = 1\n id_phage = setPhage(row[0:3], source)\n \n id_bact = SetBacterium(row[3:len(row)], 1)\n typeOfInteraction = row[2]\n \n \n #si une des deux valeur son None pas de fichier pour cet organism alors il faut écrire dans un fichier de valeur manquantes et ne pas charger le couple....\n if id_phage is not None and id_bact is not None: \n ####### Couples ######\n couple_obj = Couple(id_couple = -1, interact_pn = 1, fk_bacteria=id_bact, fk_phage=id_phage, fk_type_inter=2, fk_level_interact=level[row[2]], fk_data_source=source)\n id_couple = couple_obj.create_couple()\n else:\n with open(missingData,'a') as file:\n file.write('---> PB (ci-dessus) avec le couple couple: '+str(row))\n\n#%% Main\nif __name__ == '__main__':\n start = time.time()\n\n file = open(couplePhageBact, \"rb\")\n decode = codecs.getreader('utf-8')\n cr = csv.reader(decode(file), delimiter=';')\n coupleL = list(cr)\n for val in coupleL:\n parseCSV(val)\n \n #multiprocessing \n# with Pool(processes=None) as pool:\n# pool.map(parseCSV, coupleL)\n \n end = time.time()\n print(str(datetime.timedelta(seconds=int(end-start))))\n","sub_path":"Importation_insertion_data/import_from_publicDB.py","file_name":"import_from_publicDB.py","file_ext":"py","file_size_in_byte":11649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"552920696","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 21 10:20:36 2017\n\n@author: Alex\n\"\"\"\n\n#Based on the following: http://www.geeksforgeeks.org/counting-inversions/\n\ndef findInversions(arr):\n count = 0\n for i in range(len(arr)):\n for j in range(i, len(arr)):\n if(arr[j] < arr[i]):\n count = count + 1\n return count\n\narr = np.random.randint(6, size=15)\nprint(arr)\nnum = findInversions(arr)\nprint(num)","sub_path":"NumInversions.py","file_name":"NumInversions.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"592653286","text":"import textwrap, traceback\nfrom time import sleep\nfrom miniboa import TelnetServer\n\nfrom utils.log import log\nfrom lib.mudserver import mudserver\nfrom lib import globals\nfrom lib.database import database\n\nfrom game.world import world\n\nfrom utils.scheduler import schedule_event, do_tick\n\nsubtick = 0\nworldsavetime = (0.05 * 20) * 60 # server tick time is 0.05s * 20 = 1s * 60 = 1 min\n\ndef doworldsave(world):\n log(\">> Processing world save...\")\n\n if globals.world.rooms:\n for room in globals.world.rooms:\n globals.db.save_rooms(room)\n if globals.world.players:\n for aplayer in globals.world.players:\n globals.db.save_player(aplayer)\n\n log(\">> World save complete.\")\n\nif __name__ == '__main__':\n\n # Create a telnet server with a port, address,\n # a function to call with new connections\n # and one to call with lost connections.\\\n \n globals.mud = mudserver()\n globals.db = database()\n globals.world = world()\n \n telnet_server = TelnetServer(\n port=23,\n address='',\n on_connect=globals.mud.on_connect,\n on_disconnect=globals.mud.on_disconnect,\n timeout = 0.05\n )\n\n log(\">> Listening for connections on port {}. CTRL-C to break.\".format(telnet_server.port))\n\n # Server Loop\n try:\n while True:\n telnet_server.poll() # Send, Recv, and look for new connections\n globals.mud.kick_idle() # Check for idle clients\n globals.mud.process_clients() # Check for client input\n \n do_tick() # Push the scheduler time ahead.\n\n subtick += 0.05\n\n if subtick >= worldsavetime:\n doworldsave(globals.world)\n subtick = 0\n\n \n except:\n tb = traceback.format_exc()\n log(\"xx ERROR\\n\" + tb)\n \n log(\"-- Server shutting down.\")\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"402620658","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport requests, bs4\nimport pandas as pd\nfrom itertools import chain\nimport requests\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nimport json\nimport time\nimport webbrowser\nfrom pandas.io.json import json_normalize\nfrom rauth import OAuth1Service\nfrom rauth.utils import parse_utf8_qsl\n\n\n# In[ ]:\n\n\nimport os\nimport time\n\nfrom rauth import OAuth2Service\n\n\nclass ClientKey(object):\n def __init__(self, client_id, client_secret):\n self.client_id = client_id\n self.client_secret = client_secret\n\n @classmethod\n def from_file(cls, key_file):\n with open(key_file, \"r\") as f:\n keys = f.read().splitlines()\n\n if len(keys) != 2:\n raise RuntimeError(\"Incorrect number of keys found\")\n\n return cls(*keys)\n\n\nclass Token(object):\n def __init__(self, access_token=None, refresh_token=None):\n self.access_token = access_token\n self.refresh_token = refresh_token\n self.expiration_time = 0\n\n @property\n def expires_in(self):\n return self.expiration_time - time.time()\n\n @property\n def is_expired(self):\n return self.expires_in <= 0\n\n def get(self, oauth_service):\n if self.refresh_token:\n data = {\n \"refresh_token\": self.refresh_token,\n \"redirect_uri\": \"oob\",\n \"grant_type\": \"refresh_token\",\n }\n else:\n data = {\n \"code\": self._get_code(oauth_service),\n \"redirect_uri\": \"oob\",\n \"grant_type\": \"authorization_code\",\n }\n\n self._get_token(oauth_service, data)\n\n def _get_code(self, oauth_service):\n params = {\n \"redirect_uri\": \"oob\",\n \"response_type\": \"code\",\n }\n authorize_url = oauth_service.get_authorize_url(**params)\n\n print (\"Sign in here: \" + str(authorize_url))\n return input(\"Enter code: \")\n\n def _get_token(self, oauth_service, data):\n raw_token = oauth_service.get_raw_access_token(data=data)\n\n parsed_token = raw_token.json()\n self.access_token = parsed_token[\"access_token\"]\n self.refresh_token = parsed_token[\"refresh_token\"]\n self.expiration_time = time.time() + parsed_token[\"expires_in\"]\n\n @classmethod\n def from_file(cls, token_file):\n with open(token_file, \"r\") as f:\n token = f.read().strip()\n\n if len(token.splitlines()) != 1:\n raise RuntimeError(\"Incorrect token format\")\n\n return cls(refresh_token=token)\n\n def save(self, token_file):\n with open(token_file, \"w\") as f:\n f.write(self.refresh_token)\n\n\nclass YahooAPI(object):\n def __init__(self, keyfile, tokenfile=None,\n base_url=\"https://fantasysports.yahooapis.com\",\n request_period=0):\n\n self.key = ClientKey.from_file(keyfile)\n\n self.tokenfile = tokenfile\n if self.tokenfile and os.path.exists(self.tokenfile):\n self.token = Token.from_file(self.tokenfile)\n else:\n self.token = Token()\n\n self.oauth = OAuth2Service(\n client_id=self.key.client_id,\n client_secret=self.key.client_secret,\n name=\"yahoo\",\n authorize_url=\"https://api.login.yahoo.com/oauth2/request_auth\",\n access_token_url=\"https://api.login.yahoo.com/oauth2/get_token\",\n base_url=base_url,\n )\n\n self.session = None\n\n self._update_token()\n\n self.session = self.oauth.get_session(self.token.access_token)\n\n self.last_request = time.time()\n self.request_period = request_period\n\n def _update_token(self):\n self.token.get(self.oauth)\n\n if self.tokenfile:\n self.token.save(self.tokenfile)\n\n if self.session:\n self.session.access_token = self.token.access_token\n\n def request(self, request_str, params={}):\n \"\"\"get json instead of xml like this params={'format': 'json'}\"\"\"\n\n tdiff = max(0, time.time() - self.last_request)\n if tdiff >= 0 and tdiff < self.request_period:\n time.sleep(self.request_period - tdiff)\n\n self.last_request = time.time()\n\n # refresh access token 60 seconds before it expires\n if self.token.expires_in < 60:\n self._update_token()\n\n return self.session.get(url=request_str, params=params)\n\n\n# In[2]:\n\n\napp_id=\"7UtKtr5g\"\nconsumer_key=\"dj0yJmk9UjV2YTZQQjZ3YmVNJmQ9WVdrOU4xVjBTM1J5TldjbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD05Ng--\"\nconsumer_secret=\"f4373a8a691565e9df3fc325cceb6ea3e58ab01f\"\n\n\n# In[3]:\n\n\ncredentials = {}\ncredentials['consumer_key']=consumer_key\ncredentials['consumer_secret']=consumer_secret\ncredentials['app_id']=app_id\n#credentials=json.dumps(data)\ncredentials\n\n\n# In[4]:\n\n\noauth = OAuth1Service(consumer_key = credentials['consumer_key'],\n consumer_secret = credentials['consumer_secret'],\n name = \"yahoo\",\n request_token_url = \"https://api.login.yahoo.com/oauth/v2/get_request_token\",\n access_token_url = \"https://api.login.yahoo.com/oauth/v2/get_token\",\n authorize_url = \"https://api.login.yahoo.com/oauth/v2/request_auth\",\n base_url = \"http://fantasysports.yahooapis.com/\")\n\n\n# In[5]:\n\n\nrequest_token, request_token_secret = oauth.get_request_token(params={\"oauth_callback\": \"oob\"})\n\n\n# In[7]:\n\n\nauthorize_url = oauth.get_authorize_url(request_token)\nwebbrowser.open(authorize_url)\nverify = input('Enter code: ')\n\n\n# In[8]:\n\n\nraw_access = oauth.get_raw_access_token(request_token,\n request_token_secret,\n params={\"oauth_verifier\": verify})\n\nparsed_access_token = parse_utf8_qsl(raw_access.content)\naccess_token = (parsed_access_token['oauth_token'], parsed_access_token['oauth_token_secret'])\n\nstart_time = time.time()\nend_time = start_time + 3600\n\ncredentials['access_token'] = parsed_access_token['oauth_token']\ncredentials['access_token_secret'] = parsed_access_token['oauth_token_secret']\ntokens = (credentials['access_token'], credentials['access_token_secret'])\n\n\n# In[ ]:\n\n\n#request_token, request_token_secret = oauth.get_request_token(params={\"oauth_callback\": \"oob\"})\n\n\n# In[9]:\n\n\ns = oauth.get_session(tokens)\n\n\n# In[10]:\n\n\n#https://basketball.fantasysports.yahoo.com/nba/162585/1\nurl = 'http://fantasysports.yahooapis.com/fantasy/v2/league/nba.l.162585'\nr = s.get(url, params={'format': 'json'})\nr.status_code\n\n\n# In[ ]:\n\n\nr\n\n\n# In[ ]:\n\n\nhandler=YahooAPI(\"keyfile.txt\")\n\n","sub_path":"read_simmons.py","file_name":"read_simmons.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"533003277","text":"\n\nfrom xai.brain.wordbase.nouns._alcoholic import _ALCOHOLIC\n\n#calss header\nclass _ALCOHOLICS(_ALCOHOLIC, ):\n\tdef __init__(self,): \n\t\t_ALCOHOLIC.__init__(self)\n\t\tself.name = \"ALCOHOLICS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"alcoholic\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_alcoholics.py","file_name":"_alcoholics.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"135104572","text":"from sklearn.cluster import KMeans\nfrom sklearn.metrics import pairwise_distances_argmin_min\nimport numpy as np\nimport sys\nsets = []\nfor i in range(12):\n sets.append(np.load(\"Data/\"+str(i)+\"ClusterDesc.npy\"))\n\n\narr = np.vstack(sets)\npos = np.load(\"Data/posSF.npy\")\nprint(pos)\nprint(arr)\nprint(np.average(pos))\nprint(np.average(arr))\narr = np.vstack((arr,pos))\n\nprint(arr.shape)\n\n\nkmeans = KMeans(n_clusters=int(sys.argv[1])).fit(arr)\n\nj = 0\n\nnp.save(\"Predictions/NCIClusterLabels\",kmeans.labels_[:-len(pos)])\nnp.save(\"Predictions/POSClusterLabels\",kmeans.labels_[-len(pos):])\n\nposU, posC = np.unique(kmeans.labels_[:-len(pos)],return_counts=True)\nnciU, nciC = np.unique(kmeans.labels_[-len(pos):],return_counts=True)\n\nposD = dict(zip(posU,posC))\nnciD = dict(zip(nciU,nciC))\n\nprint(posD)\nprint(nciD)\n\nclosest, _ = pairwise_distances_argmin_min(kmeans.cluster_centers_,arr)\n\nprint(closest)\n\nmolNames = np.loadtxt(\"Predictions/MolNameAll\",delimiter=\",\")\nprint(molNames.shape)\nmolNames = np.append(molNames,np.array([\"RAGE\"]*182))\nprint(np.take(molNames,closest,0))\nnp.save(\"Predictions/RepresentativeMol\",np.take(molNames,closest,0))\n","sub_path":"cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"571891661","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport warnings\nimport math\n\nclass Plotter(object):\n \"\"\"Class to plot loss and accuracy charts (for training and validation data).\"\"\"\n def __init__(self,\n title=None,\n save_to_filepath=None,\n show_loss_plot=True,\n show_acc_plot=True,\n show_plot_window=True,\n x_label=\"Epoch\"):\n \"\"\"Constructs the plotter.\n\n Args:\n title: An optional title which will be shown at the top of the\n plot. E.g. the name of the experiment or some info about it.\n If set to None, no title will be shown. (Default is None.)\n save_to_filepath: The path to a file in which the plot will be saved,\n e.g. \"/tmp/last_plot.png\". If set to None, the chart will not be\n saved to a file. (Default is None.)\n show_loss_plot: Whether to show the chart for the loss values. If\n set to False, only the accuracy chart will be shown. (Default\n is True.)\n show_acc_plot: Whether to show the chart for the accuracy value. If\n set to False, only the loss chart will be shown. (Default is True.)\n show_plot_window: Whether to show the plot in a window (True)\n or hide it (False). Hiding it makes only sense if you\n set save_to_filepath. (Default is True.)\n x_label: Label on the x-axes of the charts. Reasonable choices\n would be: \"Epoch\", \"Batch\" or \"Example\". (Default is \"Epoch\".)\n \"\"\"\n assert show_loss_plot or show_acc_plot\n assert save_to_filepath is not None or show_plot_window\n\n self.title = title\n self.show_loss_plot = show_loss_plot\n self.show_acc_plot = show_acc_plot\n self.show_plot_window = show_plot_window\n self.save_to_filepath = save_to_filepath\n self.x_label = x_label\n\n # whether to show grids in both charts\n self.grid = True\n\n # the colors of the lines, tuple(x / 255 for x in colors)\n self.colors = np.array([[0.11764705882352941, 0.5647058823529412, 1.0],[1,0,0],[0.19607843137254902, 0.803921568627451, 0.19607843137254902], [0.5411764705882353, 0.16862745098039217, 0.8862745098039215]])\n # these values will be set in _initialize_plot() upon the first call\n # of redraw()\n # fig: the figure of the whole plot\n # ax_loss: loss chart (left)\n # ax_acc: accuracy chart (right)\n self.fig = None\n self.ax_loss = None\n self.ax_acc = None \n\n def plot_values(self, labels=None, loss_train=None, loss_test=None, acc_train=None,\n acc_test=None):\n \"\"\"\n Args:\n The () gives the size of each parameter.\n labels: (number of models/exits) model name or exits index; will be shown as legend;\n loss_train: (number of epoches x number of models/exits)\n loss_val: (number of epoches x number of models/exits)\n acc_train: (number of epoches x number of models/exits)\n acc_val: (number of epoches x number of models/exits)\n \n \"\"\"\n loss_train = loss_train.T\n loss_test = loss_test.T\n acc_train = acc_train.T\n acc_test = acc_test.T\n epoch = np.arange(loss_train.shape[1])\n num = loss_train.shape[0] # number of exits/models\n if num > 4: # the default color list is not enough\n for i in range(num-3):\n self.colors = np.append(self.colors, np.random.uniform(0,1,3).reshape(1,3), 0) # randomly generate the new color\n fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(24, 8))\n self.fig = fig\n \n for ax, label in zip([ax1, ax2], [\"Loss\", \"Accuracy\"]):\n if ax:\n ax.clear()\n ax.set_title(label)\n ax.set_ylabel(label)\n ax.set_xlabel(self.x_label)\n ax.grid(self.grid)\n \n # plot the loss\n for i in range(num):\n ax1.plot(epoch, loss_train[i], c = self.colors[i], label =labels[i] + \" training loss\")\n for i in range(num):\n ax1.plot(epoch, loss_test[i], c = self.colors[i], label = labels[i] + \" testing loss\", alpha = 0.75)\n \n # plot the acc\n for i in range(num):\n ax2.plot(epoch, acc_train[i], c = self.colors[i], label = labels[i] + \" training accuracy\")\n for i in range(num):\n ax2.plot(epoch, acc_test[i], c = self.colors[i], label = labels[i] + \" testing accuracy\", alpha = 0.75)\n \n ax1.legend(loc=\"upper center\",\n bbox_to_anchor=(0.5, -0.08),\n ncol=2, fontsize = 15)\n \n ax2.legend(loc=\"upper center\",\n bbox_to_anchor=(0.5, -0.08),\n ncol=2, fontsize = 15)\n \n fig.suptitle(self.title, fontsize = 23)\n plt.draw()\n\n # save the redrawn plot to a file upon every redraw.\n if self.save_to_filepath is not None:\n self.save_plot(self.save_to_filepath)\n \n \n def save_plot(self, filepath):\n \"\"\"Saves the current plot to a file.\n\n Args:\n filepath: The path to the file, e.g. \"/tmp/last_plot.png\".\n \"\"\"\n self.fig.savefig(filepath, bbox_inches=\"tight\")\n\n \n \n \n ","sub_path":"resnet/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":5505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"115338273","text":"# Import from the file lifemat.py in the same directory.\nfrom lifemat import Matrix2D\n\nrows = 20\ncols = 40\nlife_mat = Matrix2D(rows, cols)\nnc_mat = Matrix2D(rows, cols)\nlife_mat.set_cells(1, (1,1), (2,2), (3,0), (3,1), (3,2))\nborder_str = '_' * cols # Create border string.\n\ndef get_mat_str(a_mat):\n disp_str = ''\n for i in range(rows):\n lst = [get_chr(a_mat,i,j) for j in range(cols)]\n disp_str += ''.join(lst) + '\\n'\n return disp_str\n\ndef get_chr(a_mat, r, c):\n return 'X' if a_mat.get_cell(r, c) > 0 else ' '\n\n# Do Generation function.\n# Print the current state of life_mat, and then process\n# one generation.\n\ndef do_generation():\n\n # Pring the current 'Life' state\n print(border_str + '\\n' + get_mat_str(life_mat))\n \n nc_mat.set_all_cells(0)\n\n # Populate nc_mat, but 1) looking at each living\n # cell in life_mat, and for each, increment all\n # surrounding positions... in nc_mat. Use % op\n # to implement \"wrap around\" at edges & corners.\n\n for i in range(rows):\n for j in range(cols):\n if life_mat.get_cell(i, j):\n im = (i - 1) % rows\n ip = (i + 1) % rows\n jm = (j - 1) % cols\n jp = (j + 1) % cols\n\n nc_mat.inc_cells( (im, jm), (im, j),\n (im, jp), (i, jm), (i, jp), \n (ip, jm), (ip, j), (ip, jp) )\n\n # Process a generation, by comparing neighbor\n # counts to living cells, and applying the 2 rules.\n\n for i in range(rows):\n for j in range(cols):\n n = nc_mat.get_cell(i, j)\n if n < 2 or n > 3: # Death.\n life_mat.set_cells(0, (i, j))\n elif n == 3: # Birth \n life_mat.set_cells(1, (i, j))\n\nn = int(input(\"How many generations of slider? \"))\nfor i in range(n):\n do_generation()\n\n\n\n\n \n","sub_path":"Archive/life.py","file_name":"life.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"470818913","text":"from moderngl import Texture\nfrom moderngl_window.geometry import cube\nimport numpy as np\nimport typing as tp\n\nfrom lab2.core.model.components.component import Component\n\n\ndef _update_rotation_cord(rotation_cord: float, time: float):\n result = rotation_cord + time * 1.0\n if result > 1.0:\n result -= 1.0\n return result\n\n\nclass Cube(Component):\n\n def __init__(self, texture: Texture, translation: tp.Tuple[float, float, float],\n rotation: tp.Tuple[float, float, float], size: float):\n super().__init__(translation, rotation, cube(size=(size, size, size)))\n self.texture = texture\n self.base_translation = translation\n self.size = size\n self.texture.use(location=0)\n\n def update(self, time: float, interval: float):\n self.rotation = tuple([_update_rotation_cord(rotation_cord, interval) for rotation_cord in self.rotation])\n self.translation = (self.base_translation[0] + np.sin(time), self.base_translation[1] + np.cos(time),\n self.base_translation[2] + (np.sin(time) + np.cos(time)) * self.size)\n","sub_path":"lab2/core/model/components/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"441755925","text":"import requests, csv, os\nimport sqlite3\n\nconn = sqlite3.connect(\"wages - Copy.db\")\ncur = conn.cursor()\n\n# page = 'AF Wage Schedules96.html'\n# page2 = 'AF Schedule Area 077R Northern Mississippi (RUS) Effective_ 17 April 2016.html'\n#'AF Schedule Area 124R Memphis, Tennessee (RUS) Effective_ 17 April 2016.html'\n\n\ndef table_parser(page):\n file = open(page)\n # page = page.split('\\n')\n table = []\n num = 0\n for line in file:\n if 'Grade' in line:\n num += 1\n if num > 0:\n num += 1\n if 3 <= num < 21:\n line = line.rstrip()\n if line != '':\n split_line = line.split(' ')\n split_line = [x for x in split_line if x != '']\n strip_line = split_line[:16]\n table.append(strip_line)\n WG = []\n WL = []\n WS = []\n for l in table:\n # WG.append(l[0:1])\n # WL.append(l[0:1])\n # WS.append(l[0:1])\n WG.append((l[1:6]))\n WL.append(l[6:11])\n WS.append(l[11:16])\n\n file.close()\n return WG, WL, WS\n\ncur.execute('select link from counties where county=\"150,150,RUS,Washakie County\" and date=\"12Mar1996\"')\nlink = cur.fetchall()[0][0]\n\nres = requests.get(link,verify=False)\nhtml = res.text\nos.makedirs('test/test', exist_ok=True)\nfile = open('test/test.html','w')\nfor line in html:\n line = line.strip('\\n')\n file.write(line)\nfile.close()\n\ndata = table_parser('test.html')\n\n\nwith open('test_wg.csv','w', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(data[0])\nwith open('test_wl.csv','w', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(data[1])\nwith open('test_ws.csv','w', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(data[2])\n\n","sub_path":"Pay/payPaser.py","file_name":"payPaser.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"385387139","text":"import numpy as np\n\nfrom ram.strategy.analyst_estimates.base.position import Position\n\nclass HedgedPosition(Position):\n\n def __init__(self, symbol, price, comm=0.0225):\n \"\"\"\n Parameters\n ----------\n symbol : str\n Symbol level identifier\n price : float\n This is important as it will be the value that new shares\n are calculated from.\n comm : float\n Commissions\n \"\"\"\n super(HedgedPosition, self).__init__(symbol, price, comm)\n self.market_entry_price = 0.\n self.market_curent_price = 0.\n self.market_return = 0.\n\n def update_hedge_price(self, market_price):\n if 'HEDGE' not in market_price.keys():\n raise ValueError('HEDGE must be in key value in arg')\n mkt_px = market_price['HEDGE']\n\n # No position or just closed\n if self.exposure == 0.:\n self.market_entry_price = 0.\n self.market_curent_price = 0.\n return\n # Position just initiated\n elif self.market_entry_price == 0.:\n self.market_entry_price = mkt_px\n self.market_curent_price = mkt_px\n return\n\n self.market_curent_price = mkt_px\n self.market_return = (self.market_curent_price /\n self.market_entry_price) - 1\n hedge_ret = self.market_return * np.sign(self.exposure)\n self.cumulative_return -= hedge_ret\n self.return_peak = np.max([self.cumulative_return, self.return_peak])\n\n","sub_path":"ram/strategy/analyst_estimates/base/hedged_position.py","file_name":"hedged_position.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"167800724","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, division, print_function #Py2\n\n__author__ = \"Daniel van Niekerk\"\n__email__ = \"dvn.demitasse@gmail.com\"\n\nimport sys\nimport os\nimport multiprocessing\nfrom glob import glob\nimport subprocess\n\n\ndef extract_lf0(parms):\n cmds = \"python scripts/wav2lf0.py %(infn)s %(outfn)s %(lowerf0)s %(upperf0)s\"\n subprocess.call(cmds % parms, shell=True)\n\nif __name__ == \"__main__\":\n try:\n import multiprocessing\n POOL = multiprocessing.Pool(processes=multiprocessing.cpu_count())\n def map(f, i):\n return POOL.map(f, i, chunksize=1)\n except ImportError:\n pass\n\n argnames = [\"lowerf0\", \"upperf0\"]\n assert len(argnames) == len(sys.argv[1:])\n args = dict(zip(argnames, sys.argv[1:]))\n #make parms:\n parms = []\n for fn in glob(os.path.join(\"wav\", \"*.wav\")):\n tempd = dict(args)\n tempd[\"infn\"] = fn\n base = os.path.basename(fn).rstrip(\".wav\")\n tempd[\"outfn\"] = os.path.join(\"lf0\", base + \".lf0\")\n parms.append(tempd)\n #run:\n map(extract_lf0, parms)\n","sub_path":"voicetools/HTS-template_48k_MELP/data/scripts/extract_f0.py","file_name":"extract_f0.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"59290592","text":"from stack import Stack\n\n\ndef main():\n stack = Stack(100)\n stack.push(1)\n print(stack.peek())\n stack.pop()\n stack.pop()\n for i in range(0, 101):\n stack.push(i)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"581040536","text":"import io\nfrom PIL import Image\nimport torch\nfrom torchvision import models, transforms, datasets\nfrom torch.autograd import Variable\nimport torch.utils.data as data\nimport numpy as np\n\nfrom PIL import Image\nimport os\nimport os.path\n\n\nIMG_EXTENSIONS = [\n '.jpg', '.JPG', '.jpeg', '.JPEG',\n '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',\n]\n\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\ndef find_classes(dir):\n classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]\n classes.sort()\n class_to_idx = {classes[i]: i for i in range(len(classes))}\n return classes, class_to_idx\n\n\ndef load_labels_file(path):\n print(path)\n labels = {}\n tags = {'Sad':0, 'Fear':1, 'Angry':2, 'Disgust':3, 'Neutral':4, 'Happy':5, 'Surprise':6}\n with open(path,'r') as stream:\n for line in stream:\n [file_id, tag] = line.strip().split()\n labels[file_id] = tags[tag]\n return labels, tags\n\ndef make_dataset_seq(dir, class_to_idx):\n sequences = []\n dir = os.path.expanduser(dir)\n for target in sorted(os.listdir(dir)):\n images = []\n d = os.path.join(dir, target)\n if not os.path.isdir(d):\n continue\n\n for root, _, fnames in sorted(os.walk(d)):\n for fname in sorted(fnames):\n if is_image_file(fname):\n path = os.path.join(root, fname)\n item = (path, class_to_idx[target])\n images.append(item)\n sequences.append(images)\n return sequences\n\n\ndef pil_loader(path):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n return img.convert('RGB')\n\n\ndef accimage_loader(path):\n import accimage\n try:\n return accimage.Image(path)\n except IOError:\n # Potentially a decoding problem, fall back to PIL.Image\n return pil_loader(path)\n\n\ndef default_loader2(path):\n from torchvision import get_image_backend\n if get_image_backend() == 'accimage':\n return accimage_loader(path)\n else:\n return pil_loader(path)\n\n \ndef default_loader(path):\n return Image.open(path).convert('RGB')\n\ndef imagepath_to_frame_index(path):\n filename = path.strip().split('/')[-1].split('.')[0]\n return int(filename.replace('I_1',''))-1\n \n\nclass ImageFolderSequences(data.Dataset):\n \"\"\"A generic data loader where the images are arranged in this way: ::\n\n root/dog/xxx.png\n root/dog/xxy.png\n root/dog/xxz.png\n\n root/cat/123.png\n root/cat/nsdf3.png\n root/cat/asd932_.png\n\n Args:\n root (string): Root directory path.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n loader (callable, optional): A function to load an image given its path.\n\n Attributes:\n classes (list): List of the class names.\n class_to_idx (dict): Dict with items (class_name, class_index).\n imgs (list): List of (image path, class_index) tuples\n \"\"\"\n\n def __init__(self, root, transform=None, target_transform=None,\n loader=default_loader):\n classes, class_to_idx = find_classes(root)\n imgs = make_dataset_seq(root, class_to_idx)\n if len(imgs) == 0:\n raise(RuntimeError(\"Found 0 images in subfolders of: \" + root + \"\\n\"\n \"Supported image extensions are: \" + \",\".join(IMG_EXTENSIONS)))\n\n self.root = root\n self.imgs = imgs\n self.classes = classes\n self.class_to_idx = class_to_idx\n self.idx_to_class = {v: k for k, v in class_to_idx.items()}\n self.transform = transform\n self.target_transform = target_transform\n self.loader = loader\n self.pad_image = np.uint8( np.zeros([3,128,128]) )\n self.pad_image = Image.fromarray(np.rollaxis(self.pad_image, 0,3))\n if self.transform is not None:\n self.pad_image = self.transform(self.pad_image)\n self.labels, self.tags = load_labels_file(root + '/../../labels.txt')\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: ([images], target) where target is class_index of the target class.\n \"\"\"\n images = []\n sequence_index = 0\n for item in self.imgs[index]:\n path, target = item\n dirname = self.idx_to_class[target]\n target_class = self.labels[dirname]\n# print(dirname, target_class, target)\n target = target_class\n img = self.loader(path)\n if self.transform is not None:\n img = self.transform(img)\n frame_index = imagepath_to_frame_index(path)\n if self.target_transform is not None:\n frame_index = self.target_transform( frame_index )\n if sequence_index > 0:\n count_pad=0\n while sequence_index < frame_index: \n sequence_index_tmp = sequence_index\n if self.target_transform is not None:\n sequence_index_tmp = self.target_transform( sequence_index_tmp )\n good_image = False\n images.append([ self.pad_image, sequence_index_tmp, good_image])\n sequence_index = sequence_index +1\n count_pad=count_pad+1\n if count_pad > 1:\n sequence_index = frame_index\n break\n\n good_image = True \n images.append([img,frame_index, good_image])\n sequence_index = sequence_index +1\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return images, target\n\n def __len__(self):\n return len(self.imgs)\n \n \ndef my_collate(batch):\n _prueba_batch = batch\n max_length=0\n for n in range(len(_prueba_batch)):\n nphotos = len(_prueba_batch[n][0])\n if nphotos > max_length:\n max_length = nphotos\n\n data_tensor = torch.FloatTensor(\n len(_prueba_batch), \n max_length, \n (_prueba_batch[0][0][0][0]).size()[0], \n (_prueba_batch[0][0][0][0]).size()[1], \n (_prueba_batch[0][0][0][0]).size()[2]\n ).zero_()\n data_tensor.size()\n\n for n in range(len(_prueba_batch)):\n nphotos = len(_prueba_batch[n][0])\n #photos_tensor = torch.FloatTensor(max_length,\n #(_prueba_batch[0][0][0][0]).size()[0],\n #(_prueba_batch[0][0][0][0]).size()[1], \n #(_prueba_batch[0][0][0][0]).size()[2]\n #).zero_()\n for p in range(nphotos):\n # photos_tensor[p]=_prueba_batch[n][0][p][0]\n# try:\n data_tensor[n][p] = _prueba_batch[n][0][p][0]\n# except:\n# print(\"n \", n)\n# print(\"p \", p)\n# print(\"data_tensor \", data_tensor.size())\n# print(\"_prueba_batch \", len(_prueba_batch[n][0]))\n# print(\"_prueba_batch \", len(_prueba_batch[n][0][p]))\n\n target = torch.LongTensor( len(_prueba_batch), 1).zero_()\n for n in range(len(_prueba_batch)):\n target[n] = _prueba_batch[n][1]\n\n\n return((data_tensor, target))\n \ndef my_collate_percentile(batch):\n _prueba_batch = batch\n max_length=0\n lengths=[]\n for n in range(len(_prueba_batch)):\n nphotos = len(_prueba_batch[n][0])\n if nphotos > max_length:\n max_length = nphotos\n lengths.append(nphotos)\n# print(nphotos)\n# print(max_length)\n median_length = np.ceil(np.median(np.asarray(lengths)))\n percentile_length = int(np.ceil(np.percentile(np.asarray(lengths), 75)))\n\n\n data_tensor = torch.FloatTensor(\n len(_prueba_batch), \n percentile_length, \n (_prueba_batch[0][0][0][0]).size()[0], \n (_prueba_batch[0][0][0][0]).size()[1], \n (_prueba_batch[0][0][0][0]).size()[2]\n ).zero_()\n data_tensor.size()\n\n for n in range(len(_prueba_batch)):\n nphotos = len(_prueba_batch[n][0])\n if nphotos > percentile_length:\n rest = nphotos - percentile_length\n rand_start = np.random.randint(rest)\n else:\n rand_start = np.random.randint(nphotos)\n #data_tensor[n] = _prueba_batch[n][0][rand_start:(rand_start+percentile_length)][0]\n for p in range(percentile_length): \n data_tensor[n][p] = _prueba_batch[n][0][((p+rand_start)%nphotos + int((p+rand_start)/nphotos))%nphotos][0] #circular buffer, with one single padding image when starting over\n\n\n target = torch.LongTensor( len(_prueba_batch), 1).zero_()\n for n in range(len(_prueba_batch)):\n target[n] = _prueba_batch[n][1]\n\n\n return((data_tensor, target))\n","sub_path":"data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":9278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"127345987","text":"from sys import argv\nfrom scanner import scanner\nfrom parser import parser\n\nimport imageio\nfrom PIL import Image\nimport numpy as np\n\n\nclass FlipBook :\n \"\"\" Parent class which will contain all required helper functions and \n store necessary variables to produce required flipbook \"\"\"\n \n def __init__(self):\n self.frame_list = []\n self.dim = 720\n self.blank = np.zeros([self.dim,self.dim,3],dtype=np.uint8)\n self.blank.fill(0)\n \n def generate_gif(self, frames):\n for frame in frames:\n startFrame = frame[0]\n endFrame = frame[1]\n # print (frame, len(frame))\n if len(frame) == 3: # standard appending\n imageName = frame[2]\n else:\n imageName = self.combine_images(frame[2:])\n self.add_image_to_frame_list(startFrame, endFrame, imageName)\n\n imageio.mimsave('flipbook.gif', self.frame_list)\n print(\"GIF named flipbook.gif has been generated\")\n \n def combine_images(self, imageList):\n #assume 2 images being horizontally concatenated\n n = len(imageList)\n im1 = Image.open(imageList[0])\n im2 = Image.open(imageList[1])\n # dst = Image.new('RGB', (im1.width + im2.width, min(im1.height, im2.height)))\n dst = Image.new('RGB', (self.dim, self.dim))\n dst.paste(im1, (0, 0))\n # dst.paste(im2, (im1.width, (im1.height - im2.height) // 2))\n dst.paste(im2, (im1.width, 0))\n return dst\n\n def add_image_to_frame_list(self,startFrame, endFrame, imageName):\n \"\"\" add other params/functions to do resizing/positioning etc \"\"\" \n for i in range(startFrame-1, endFrame-1):\n try:\n # image = imageio.imread(imageName)\n im = Image.open(imageName)\n im = im.resize((720, 720))\n self.frame_list.append(im)\n # self.frame_list.append(im)\n\n except:\n print (imageName, \" not found.\")\n # BufferedImage bi= new BufferedImage(320,240,BufferedImage.TYPE_BYTE_GRAY);\n im=self.blank\n self.frame_list.append(im)\n\n\n def parse_input(self, text, markers):\n code, frames = parser(text, markers)\n if code:\n self.generate_gif(frames)\n else:\n exit()\n\n def scan_input(self, text):\n code, markers = scanner(text)\n if code:\n self.parse_input(text, markers)\n else:\n exit()\n\ndef main(argv):\n if len(argv) != 2:\n print(\"Usage: python3 main.py \")\n return\n\n #read input file contents\n ipfile = argv[1]\n if ipfile.endswith(\".flip\") is False:\n print (\"Input a .flip file\")\n exit()\n file_obj = open(ipfile,\"r\")\n if file_obj.mode==\"r\":\n text = file_obj.read()\n # print (text)\n FB = FlipBook()\n FB.scan_input(text)\n\n\n\nif __name__ == '__main__':\n main(argv)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"566746155","text":"def get_bmi(height, weight):\n bmi = weight / height ** 2 * 10000\n return bmi\n\ndef get_category(bmi):\n if bmi <= 18.5:\n category = '저체중'\n elif 18.5 < bmi <= 25:\n category = '정상'\n else:\n category = '비만'\n return category\n\nwhile True:\n height = int(input('신장을 입력하세요(cm): '))\n weight = float(input('체중을 입력하세요(kg): '))\n bmi = get_bmi(height, weight)\n category = get_category(bmi)\n\n print('[저체중-18.5-정상-25-비만]')\n print('나의 신체질량지수(BMI) {:.2f} {}\\n'.format(bmi, category))\n","sub_path":"sources/chapter1/bmi_v5.py","file_name":"bmi_v5.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"235603360","text":"import os\nimport torch\nimport numpy as np\n\nfrom scipy.spatial import distance_matrix\n\ndataset = 'diab'\nmodel_info = 'lstm+tanh'\n\ndirname = '../outputs/' + dataset + '/' + model_info\ndirs = [d for d in os.listdir(dirname) if\n 'enc.th' in os.listdir(os.path.join(dirname, d))]\n# print(dirs)\n\ndistance_matrices = []\nfor dir in dirs:\n pth = os.path.join(dirname, dir, 'enc.th')\n enc = torch.load(pth)\n enc = enc['embedding.weight'].cpu().numpy()\n print(enc.shape)\n distance_matrices.append(\n distance_matrix(enc, enc)) # Minkowski distance with p-norm=2\nimport pickle\n\nfile_name = dataset + model_info + \"-distance-matrices.pkl\"\npkl_file = open(file_name, 'wb')\npickle.dump(distance_matrices, pkl_file)\npkl_file.close()\n","sub_path":"temp-files/embeddings-distance-matrix.py","file_name":"embeddings-distance-matrix.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"367464987","text":"import os\nimport shutil\n\nimport virtool.db.files\nimport virtool.db.samples\nimport virtool.jobs.job\nimport virtool.samples\nimport virtool.utils\n\n\ndef handle_base_quality_nan(split):\n values = split[1:]\n\n for value in split[1:]:\n try:\n value = round(int(value.split(\".\")[0]), 2)\n return [value for _ in values]\n except ValueError:\n pass\n\n raise ValueError(\"Could not parse base quality values\")\n\n\ndef move_trimming_results(path, paired):\n if paired:\n shutil.move(\n os.path.join(path, \"reads-trimmed-pair1.fastq\"),\n os.path.join(path, \"reads_1.fastq\")\n )\n\n shutil.move(\n os.path.join(path, \"reads-trimmed-pair2.fastq\"),\n os.path.join(path, \"reads_2.fastq\")\n )\n\n else:\n shutil.move(\n os.path.join(path, \"reads-trimmed.fastq\"),\n os.path.join(path, \"reads_1.fastq\")\n )\n\n shutil.move(\n os.path.join(path, \"reads-trimmed.log\"),\n os.path.join(path, \"trim.log\")\n )\n\n\nclass Job(virtool.jobs.job.Job):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n #: The ordered list of :ref:`stage methods ` that are called by the job.\n self._stage_list = [\n self.make_sample_dir,\n self.trim_reads,\n self.save_trimmed,\n self.fastqc,\n self.parse_fastqc,\n self.clean_watch\n ]\n\n def check_db(self):\n self.params = dict(self.task_args)\n\n self.params[\"sample_path\"] = os.path.join(\n self.settings[\"data_path\"],\n \"samples\",\n self.params[\"sample_id\"]\n )\n\n self.params[\"analysis_path\"] = os.path.join(self.params[\"sample_path\"], \"analysis\")\n\n self.params.update({\n \"fastqc_path\": os.path.join(self.params[\"sample_path\"], \"fastqc\"),\n \"paired\": len(self.params[\"files\"]) == 2\n })\n\n def make_sample_dir(self):\n \"\"\"\n Make a data directory for the sample and a subdirectory for analyses. Read files, quality data from FastQC, and\n analysis data will be stored here.\n\n \"\"\"\n\n try:\n os.makedirs(self.params[\"analysis_path\"])\n os.makedirs(self.params[\"fastqc_path\"])\n except OSError:\n # If the path already exists, remove it and try again.\n shutil.rmtree(self.params[\"sample_path\"])\n os.makedirs(self.params[\"analysis_path\"])\n os.makedirs(self.params[\"fastqc_path\"])\n\n def trim_reads(self):\n \"\"\"\n Trim the reads by calling Skewer.\n\n \"\"\"\n input_paths = [os.path.join(self.settings[\"data_path\"], \"files\", file_id) for file_id in self.params[\"files\"]]\n\n command = [\n \"skewer\",\n \"-m\", \"pe\" if self.params[\"paired\"] else \"any\",\n \"-l\", \"20\" if self.params[\"srna\"] else \"50\",\n \"-q\", \"20\",\n \"-Q\", \"25\",\n \"-t\", str(self.settings[\"create_sample_proc\"]),\n \"-o\", os.path.join(self.params[\"sample_path\"], \"reads\"),\n \"--quiet\"\n ]\n\n # Trim reads to max length of 23 if the sample is sRNA.\n if self.params[\"srna\"]:\n command += [\n \"-L\", \"23\",\n \"-e\"\n ]\n\n command += input_paths\n\n # Prevents an error from skewer when called inside a subprocess.\n env = dict(os.environ, LD_LIBRARY_PATH=\"/usr/lib/x86_64-linux-gnu\")\n\n self.run_subprocess(command, env=env)\n\n def save_trimmed(self):\n \"\"\"\n Give the trimmed FASTQ and log files generated by skewer more readable names.\n\n \"\"\"\n move_trimming_results(self.params[\"sample_path\"], self.params[\"paired\"])\n\n def fastqc(self):\n \"\"\"\n Runs FastQC on the renamed, trimmed read files.\n\n \"\"\"\n command = [\n \"fastqc\",\n \"-f\", \"fastq\",\n \"-o\", self.params[\"fastqc_path\"],\n \"-t\", \"2\",\n \"--extract\",\n self.params[\"sample_path\"] + \"/reads_1.fastq\"\n ]\n\n if self.params[\"paired\"]:\n command.append(os.path.join(self.params[\"sample_path\"], \"reads_2.fastq\"))\n\n self.run_subprocess(command)\n\n def parse_fastqc(self):\n \"\"\"\n Capture the desired data from the FastQC output. The data is added to the samples database\n in the main run() method\n\n \"\"\"\n # Get the text data files from the FastQC output\n for name in os.listdir(self.params[\"fastqc_path\"]):\n if \"reads\" in name and \".\" not in name:\n suffix = name.split(\"_\")[1]\n shutil.move(\n os.path.join(self.params[\"fastqc_path\"], name, \"fastqc_data.txt\"),\n os.path.join(self.params[\"sample_path\"], \"fastqc_{}.txt\".format(suffix))\n )\n\n # Dispose of the rest of the data files.\n shutil.rmtree(self.params[\"fastqc_path\"])\n\n fastqc = {\n \"count\": 0\n }\n\n # Parse data file(s)\n for suffix in [1, 2]:\n path = os.path.join(self.params[\"sample_path\"], \"fastqc_{}.txt\".format(suffix))\n\n try:\n handle = open(path, \"r\")\n except IOError:\n if suffix == 2:\n continue\n else:\n raise\n\n flag = None\n\n for line in handle:\n # Turn off flag if the end of a module is encountered\n if flag is not None and \"END_MODULE\" in line:\n flag = None\n\n # Total sequences\n elif \"Total Sequences\" in line:\n fastqc[\"count\"] += int(line.split(\"\\t\")[1])\n\n # Read encoding (eg. Illumina 1.9)\n elif \"encoding\" not in fastqc and \"Encoding\" in line:\n fastqc[\"encoding\"] = line.split(\"\\t\")[1]\n\n # Length\n elif \"Sequence length\" in line:\n split_length = [int(s) for s in line.split(\"\\t\")[1].split('-')]\n\n if suffix == 1:\n if len(split_length) == 2:\n fastqc[\"length\"] = split_length\n else:\n fastqc[\"length\"] = [split_length[0], split_length[0]]\n else:\n fastqc_min_length, fastqc_max_length = fastqc[\"length\"]\n\n if len(split_length) == 2:\n fastqc[\"length\"] = [\n min(fastqc_min_length, split_length[0]),\n max(fastqc_max_length, split_length[1])\n ]\n else:\n fastqc[\"length\"] = [\n min(fastqc_min_length, split_length[0]),\n max(fastqc_max_length, split_length[0])\n ]\n\n # GC-content\n elif \"%GC\" in line and \"#\" not in line:\n gc = float(line.split(\"\\t\")[1])\n\n if suffix == 1:\n fastqc[\"gc\"] = gc\n else:\n fastqc[\"gc\"] = (fastqc[\"gc\"] + gc) / 2\n\n # The statements below handle the beginning of multi-line FastQC sections. They set the flag\n # value to the found section and allow it to be further parsed.\n elif \"Per base sequence quality\" in line:\n flag = \"bases\"\n if suffix == 1:\n fastqc[flag] = [None] * fastqc[\"length\"][1]\n\n elif \"Per sequence quality scores\" in line:\n flag = \"sequences\"\n if suffix == 1:\n fastqc[flag] = [0] * 50\n\n elif \"Per base sequence content\" in line:\n flag = \"composition\"\n if suffix == 1:\n fastqc[flag] = [None] * fastqc[\"length\"][1]\n\n # The statements below handle the parsing of lines when the flag has been set for a multi-line\n # section. This ends when the 'END_MODULE' line is encountered and the flag is reset to none\n elif flag in [\"composition\", \"bases\"] and \"#\" not in line:\n # Split line around whitespace.\n split = line.rstrip().split()\n\n # Convert all fields except first to 2-decimal floats.\n try:\n values = [round(int(value.split(\".\")[0]), 1) for value in split[1:]]\n\n except ValueError as err:\n if \"NaN\" in str(err):\n values = handle_base_quality_nan(split)\n\n # Convert to position field to a one- or two-member tuple.\n pos = [int(x) for x in split[0].split('-')]\n\n if len(pos) > 1:\n pos = range(pos[0], pos[1] + 1)\n else:\n pos = [pos[0]]\n\n if suffix == 1:\n for i in pos:\n fastqc[flag][i - 1] = values\n else:\n for i in pos:\n fastqc[flag][i - 1] = virtool.utils.average_list(fastqc[flag][i - 1], values)\n\n elif flag == \"sequences\" and \"#\" not in line:\n line = line.rstrip().split()\n\n quality = int(line[0])\n\n fastqc[\"sequences\"][quality] += int(line[1].split(\".\")[0])\n\n self.db.samples.update_one({\"_id\": self.params[\"sample_id\"]}, {\n \"$set\": {\n \"quality\": fastqc,\n \"imported\": False\n }\n })\n\n self.dispatch(\"samples\", \"update\", [self.params[\"sample_id\"]])\n\n def clean_watch(self):\n \"\"\" Remove the original read files from the files directory \"\"\"\n self.db.files.delete_many({\"_id\": {\"$in\": self.params[\"files\"]}})\n self.dispatch(\"files\", \"delete\", self.params[\"files\"])\n\n def cleanup(self):\n for file_id in self.params[\"files\"]:\n self.db.files.update_many({\"_id\": file_id}, {\n \"$set\": {\n \"reserved\": False\n }\n })\n\n self.dispatch(\"files\", \"update\", self.params[\"files\"])\n\n try:\n shutil.rmtree(self.params[\"sample_path\"])\n except FileNotFoundError:\n pass\n\n self.db.samples.delete_one({\"_id\": self.params[\"sample_id\"]})\n\n self.dispatch(\"samples\", \"delete\", [self.params[\"sample_id\"]])\n","sub_path":"virtool/jobs/create_sample.py","file_name":"create_sample.py","file_ext":"py","file_size_in_byte":10733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"349833451","text":"\"\"\"\nSubsample OceanDataset objects.\n\"\"\"\n\n# Instructions for developers:\n# 1) Every function operates on od, and returns od.\n# 2) Only use od._ds and od._grid \n# 3) Make sure you don't lose global attributes (e.g., when merging)\n# 4) Always cutout at the beginning, and use **kwargs for customized cutouts\n# 5) Add new functions in _subsampleMethdos\n# 6) Add new functions in docs/api.rst\n# 7) Add tests\n\nimport xarray as _xr\nimport pandas as _pd\nimport numpy as _np\nimport copy as _copy\nimport warnings as _warnings\nimport oceanspy as _ospy\nimport functools as _functools\n\nfrom . import utils as _utils\nfrom . import compute as _compute\n\ntry: from geopy.distance import great_circle as _great_circle\nexcept ImportError: pass\ntry: import xesmf as _xe\nexcept ImportError: pass\n\ndef cutout(od,\n varList = None,\n YRange = None,\n XRange = None,\n add_Hbdr = False,\n mask_outside = False,\n ZRange = None,\n add_Vbdr = False,\n timeRange = None,\n timeFreq = None,\n sampMethod = 'snapshot',\n dropAxes = False):\n \"\"\"\n Cutout the original dataset in space and time preserving the original grid structure. \n\n Parameters\n ----------\n od: OceanDataset\n oceandataset to subsample\n varList: 1D array_like, str, or None\n List of variables (strings). \n YRange: 1D array_like, scalar, or None\n Y axis limits (e.g., latitudes). \n If len(YRange)>2, max and min values are used.\n XRange: 1D array_like, scalar, or None\n X axis limits (e.g., longitudes). \n If len(XRange)>2, max and min values are used.\n add_Hbdr: bool, scal\n If scalar, add (subtract) add_Hbdr to the max (min) values of the horizontal ranges.\n If True, automatically estimate add_Hbdr.\n If False, add_Hbdr is set to zero.\n mask_outside: bool \n If True, set all values in areas outside specified (Y,X)ranges to NaNs.\n (Useless for rectilinear grids).\n ZRange: 1D array_like, scalar, or None\n Z axis limits. \n If len(ZRange)>2, max and min values are used.\n timeRange: 1D array_like np.ScalarType, or None\n time axis limits. \n If len(timeRange)>2, max and min values are used.\n timeFreq: str or None\n Time frequency. Available optionts are pandas Offset Aliases (e.g., '6H'):\n http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases\n sampMethod: {'snapshot', 'mean'}\n Downsampling method (only if timeFreq is not None)\n dropAxes: 1D array_like, str, or bool\n List of axes to remove from Grid object if one point only is in the range.\n If True, set dropAxes=od.grid_coords.\n If False, preserve original grid.\n \n Returns\n -------\n od: OceanDataset\n Subsampled oceandataset\n \n Notes\n -----\n If any of the horizontal ranges is not None, \n the horizontal dimensions of the cutout will have len(Xp1)>len(X) and len(Yp1)>len(Y) \n even if the original oceandataset had len(Xp1)==len(X) or len(Yp1)==len(Y). \n \"\"\"\n \n # Check\n for wrong_dim in ['mooring', 'station', 'particle']:\n if wrong_dim in od._ds.dims and (XRange is not None or YRange is not None):\n raise ValueError('`cutout` cannot subsample in the horizontal plain oceandatasets with dimension [{}]'.format(wrong_dim))\n \n # Convert variables to numpy arrays and make some check\n if not isinstance(od, _ospy.OceanDataset):\n raise TypeError('`od` must be OceanDataset')\n \n if varList is not None:\n varList = _np.asarray(varList, dtype='str')\n if varList.ndim == 0: varList = varList.reshape(1)\n elif varList.ndim >1: raise TypeError('Invalid `varList`')\n \n if not isinstance(add_Hbdr, (float, int, bool)):\n raise TypeError('`add_Hbdr` must be float, int, or bool')\n \n if not isinstance(mask_outside, bool):\n raise TypeError('`add_Hbdr` must be bool')\n \n if YRange is not None:\n YRange = _np.asarray(YRange, dtype=od._ds['YG'].dtype)\n if YRange.ndim == 0: YRange = YRange.reshape(1)\n elif YRange.ndim >1: raise TypeError('Invalid `YRange`')\n Ymax = od._ds['YG'].max().values\n Ymin = od._ds['YG'].min().values\n if any(YRangeYmax):\n _warnings.warn(\"\\nThe Y range of the oceandataset is: {}\"\n \"\\nYRange has values outside the oceandataset range.\".format([Ymin, Ymax]), stacklevel=2)\n \n if XRange is not None:\n XRange = _np.asarray(XRange, dtype=od._ds['XG'].dtype)\n if XRange.ndim == 0: XRange = XRange.reshape(1)\n elif XRange.ndim >1: raise TypeError('Invalid `XRange`')\n Xmax = od._ds['XG'].max().values\n Xmin = od._ds['XG'].min().values\n if any(XRangeXmax):\n _warnings.warn(\"\\nThe X range of the oceandataset is: {}\"\n \"\\nXRange has values outside the oceandataset range.\".format([Xmin, Xmax]), stacklevel=2)\n if ZRange is not None:\n ZRange = _np.asarray(ZRange, dtype=od._ds['Zp1'].dtype)\n if ZRange.ndim == 0: ZRange = ZRange.reshape(1)\n elif ZRange.ndim >1: raise TypeError('Invalid `ZRange`')\n Zmax = od._ds['Zp1'].max().values\n Zmin = od._ds['Zp1'].min().values\n if any(ZRangeZmax):\n _warnings.warn(\"\\nThe Z range of the oceandataset is: {}\"\n \"\\nZRange has values outside the the oceandataset range.\".format([Zmin, Zmax]), stacklevel=2)\n \n if timeRange is not None:\n timeRange = _np.asarray(timeRange, dtype=od._ds['time'].dtype)\n if timeRange.ndim == 0: timeRange = timeRange.reshape(1)\n elif timeRange.ndim >1: raise TypeError('Invalid `timeRange`')\n timemax = od._ds['time'].max().values\n timemin = od._ds['time'].min().values\n if any(timeRangetimemax):\n _warnings.warn(\"\\nThe time range of the oceandataset is: {}\"\n \"\\ntimeRange has values outside the the oceandataset range.\".format([timemin, timemax]), stacklevel=2)\n \n if not isinstance(timeFreq, (str, type(None))):\n raise TypeError('`timeFreq` must None or str')\n \n sampMethod_list = ['snapshot', 'mean']\n if sampMethod not in sampMethod_list:\n raise ValueError('[{}] is not an available `sampMethod`.'\n '\\nOptions: {}'.format(sampMethod, sampMethod_list))\n \n if not isinstance(dropAxes, bool):\n dropAxes = _np.asarray(dropAxes, dtype='str')\n if dropAxes.ndim == 0: dropAxes = dropAxes.reshape(1)\n elif dropAxes.ndim >1: raise TypeError('Invalid `dropAxes`')\n axis_error = [axis for axis in dropAxes if axis not in od.grid_coords]\n if len(axis_error)!=0:\n raise ValueError('{} are not in od.grid_coords and can not be dropped'.format(axis_error))\n dropAxes = {d: od.grid_coords[d] for d in dropAxes}\n elif dropAxes is True:\n dropAxes = od.grid_coords\n if YRange is None : dropAxes.pop('Y', None)\n if XRange is None : dropAxes.pop('X', None)\n if ZRange is None : dropAxes.pop('Z', None)\n if timeRange is None: dropAxes.pop('time', None)\n else:\n dropAxes = {}\n \n # Message\n print('Cutting out the oceandataset.')\n \n # Copy\n od = _copy.copy(od)\n \n # Unpack\n ds = od._ds\n periodic = od.grid_periodic\n \n # ---------------------------\n # Horizontal CUTOUT\n # ---------------------------\n \n if add_Hbdr is True:\n add_Hbdr = (_np.mean([_np.fabs(od._ds['XG'].max() - od._ds['XG'].min()),\n _np.fabs(od._ds['YG'].max() - od._ds['YG'].min())]) / \n _np.mean([len(od._ds['X']), len(od._ds['Y'])]))\n elif add_Hbdr is False:\n add_Hbdr = 0\n \n if add_Vbdr is True:\n add_Vbdr = _np.fabs(od._ds['Zp1'].diff('Zp1')).max().values\n elif add_Vbdr is False:\n add_Vbdr = 0\n \n # Initialize horizontal mask\n if XRange is not None or YRange is not None:\n maskH = _xr.ones_like(ds['XG'])\n\n if YRange is not None: \n # Use arrays\n YRange = _np.asarray([_np.min(YRange)-add_Hbdr, _np.max(YRange)+add_Hbdr]).astype(ds['YG'].dtype)\n\n # Get the closest \n for i, Y in enumerate(YRange):\n diff = _np.fabs(ds['YG']-Y)\n YRange[i] = ds['YG'].where(diff==diff.min()).min().values \n maskH = maskH.where(_np.logical_and(ds['YG']>=YRange[0], ds['YG']<=YRange[-1]), 0)\n maskHY = maskH\n\n if XRange is not None:\n # Use arrays\n XRange = _np.asarray([_np.min(XRange)-add_Hbdr, _np.max(XRange)+add_Hbdr]).astype(ds['XG'].dtype)\n\n # Get the closest \n for i, X in enumerate(XRange):\n diff = _np.fabs(ds['XG']-X)\n XRange[i] = ds['XG'].where(diff==diff.min()).min().values \n maskH = maskH.where(_np.logical_and(ds['XG']>=XRange[0], ds['XG']<=XRange[-1]), 0)\n\n # Can't be all zeros\n if maskH.sum()==0: raise ValueError('Zero grid points in the horizontal range')\n\n # Find horizontal indexes\n maskH['Yp1'].values = _np.arange(len(maskH['Yp1']))\n maskH['Xp1'].values = _np.arange(len(maskH['Xp1']))\n dmaskH = maskH.where(maskH, drop=True)\n dYp1 = dmaskH['Yp1'].values\n dXp1 = dmaskH['Xp1'].values\n iY = [_np.min(dYp1), _np.max(dYp1)]\n iX = [_np.min(dXp1), _np.max(dXp1)]\n maskH['Yp1'] = ds['Yp1']\n maskH['Xp1'] = ds['Xp1']\n \n # Original length\n lenY = len(ds['Yp1'])\n lenX = len(ds['Xp1']) \n \n # Indexis\n if iY[0]==iY[1]:\n if 'Y' not in dropAxes:\n if iY[0]>0: iY[0]=iY[0]-1\n else: iY[1]=iY[1]+1\n else: dropAxes.pop('Y', None)\n \n\n if iX[0]==iX[1]:\n if 'X' not in dropAxes:\n if iX[0]>0: iX[0]=iX[0]-1\n else: iX[1]=iX[1]+1\n else: dropAxes.pop('X', None)\n \n # Cutout\n ds = ds.isel(Yp1 = slice(iY[0], iY[1]+1),\n Xp1 = slice(iX[0], iX[1]+1))\n \n if 'X' in dropAxes:\n if iX[0]==len(ds['X']):\n iX[0]=iX[0]-1\n iX[1]=iX[1]-1\n ds = ds.isel(X = slice(iX[0], iX[1]+1))\n elif (('outer' in od._grid.axes['X'].coords and od._grid.axes['X'].coords['outer'].name == 'Xp1') or \n ('left' in od._grid.axes['X'].coords and od._grid.axes['X'].coords['left'].name == 'Xp1')):\n ds = ds.isel(X = slice(iX[0], iX[1]))\n elif 'right' in od._grid.axes['X'].coords and od._grid.axes['X'].coords['right'].name =='Xp1':\n ds = ds.isel(X = slice(iX[0]+1, iX[1]+1)) \n \n if 'Y' in dropAxes:\n if iY[0]==len(ds['Y']):\n iY[0]=iY[0]-1\n iY[1]=iY[1]-1\n ds = ds.isel(Y = slice(iY[0], iY[1]+1))\n elif (('outer' in od._grid.axes['Y'].coords and od._grid.axes['Y'].coords['outer'].name == 'Yp1') or \n ('left' in od._grid.axes['Y'].coords and od._grid.axes['Y'].coords['left'].name == 'Yp1')):\n ds = ds.isel(Y = slice(iY[0], iY[1]))\n elif 'right' in od._grid.axes['Y'].coords and od._grid.axes['Y'].coords['right'].name =='Yp1':\n ds = ds.isel(Y = slice(iY[0]+1, iY[1]+1))\n \n # Cut axis can't be periodic\n if (len(ds['Yp1']) < lenY or 'Y' in dropAxes) and 'Y' in periodic: periodic.remove('Y')\n if (len(ds['Xp1']) < lenX or 'X' in dropAxes) and 'X' in periodic: periodic.remove('X')\n \n # ---------------------------\n # Vertical CUTOUT\n # ---------------------------\n \n # Initialize vertical mask\n maskV = _xr.ones_like(ds['Zp1'])\n \n if ZRange is not None:\n # Use arrays\n ZRange = _np.asarray([_np.min(ZRange)-add_Vbdr, _np.max(ZRange)+add_Vbdr]).astype(ds['Zp1'].dtype)\n \n # Get the closest \n for i, Z in enumerate(ZRange):\n diff = _np.fabs(ds['Zp1']-Z)\n ZRange[i] = ds['Zp1'].where(diff==diff.min()).min().values \n maskV = maskV.where(_np.logical_and(ds['Zp1']>=ZRange[0], ds['Zp1']<=ZRange[-1]), 0) \n \n # Find vertical indexes\n maskV['Zp1'].values = _np.arange(len(maskV['Zp1']))\n dmaskV = maskV.where(maskV, drop=True)\n dZp1 = dmaskV['Zp1'].values\n iZ = [_np.min(dZp1), _np.max(dZp1)]\n maskV['Zp1'] = ds['Zp1']\n \n # Original length\n lenZ = len(ds['Zp1']) \n \n # Indexis\n if iZ[0]==iZ[1]:\n if 'Z' not in dropAxes:\n if iZ[0]>0: iZ[0]=iZ[0]-1\n else: iZ[1]=iZ[1]+1\n else: dropAxes.pop('Z', None)\n \n # Cutout\n ds = ds.isel(Zp1 = slice(iZ[0], iZ[1]+1))\n if 'Z' in dropAxes:\n if iZ[0]==len(ds['Z']):\n iZ[0]=iZ[0]-1\n iZ[1]=iZ[1]-1\n ds = ds.isel(Z = slice(iZ[0], iZ[1]+1))\n if 'Zu' in ds.dims and len(ds['Zu'])>1:\n ds = ds.sel(Zu=ds['Zp1'].values, method='nearest')\n if 'Zl' in ds.dims and len(ds['Zl'])>1:\n ds = ds.sel(Zl=ds['Zp1'].values, method='nearest')\n \n else:\n ds = ds.isel(Z = slice(iZ[0], iZ[1]))\n \n if 'Zu' in ds.dims and len(ds['Zu'])>1:\n ds = ds.sel(Zu = slice(ds['Zp1'].isel(Zp1=0).values, ds['Zp1'].isel(Zp1=-1).values))\n\n if 'Zl' in ds.dims and len(ds['Zl'])>1:\n ds = ds.sel(Zl = slice(ds['Zp1'].isel(Zp1=0).values, ds['Z'].isel(Z=-1).values))\n \n # Cut axis can't be periodic\n if (len(ds['Z']) < lenZ or 'Z' in dropAxes) and 'Z' in periodic: periodic.remove('Z')\n \n # ---------------------------\n # Time CUTOUT\n # ---------------------------\n \n # Initialize vertical mask\n maskT = _xr.ones_like(ds['time']).astype('int')\n \n if timeRange is not None:\n \n # Use arrays\n timeRange = _np.asarray([_np.min(timeRange), _np.max(timeRange)]).astype(ds['time'].dtype)\n \n # Get the closest \n for i, time in enumerate(timeRange):\n if _np.issubdtype(ds['time'].dtype, _np.datetime64):\n diff = _np.fabs(ds['time'].astype('float64') - time.astype('float64'))\n else:\n diff = _np.fabs(ds['time']-time)\n timeRange[i] = ds['time'].where(diff==diff.min()).min().values \n # return maskT, ds['time'], timeRange[0], timeRange[-1]\n maskT = maskT.where(_np.logical_and(ds['time']>=timeRange[0], ds['time']<=timeRange[-1]), 0) \n \n # Find vertical indexes\n maskT['time'].values = _np.arange(len(maskT['time']))\n dmaskT = maskT.where(maskT, drop=True)\n dtime = dmaskT['time'].values\n iT = [min(dtime), max(dtime)]\n maskT['time'] = ds['time']\n \n # Original length\n lenT = len(ds['time'])\n \n # Indexis\n if iT[0]==iT[1]:\n if 'time' not in dropAxes:\n if iT[0]>0: iT[0]=iT[0]-1\n else: iT[1]=iT[1]+1\n else: dropAxes.pop('time', None)\n \n # Cutout\n ds = ds.isel(time = slice(iT[0], iT[1]+1))\n if 'time' in dropAxes:\n if iT[0]==len(ds['time_midp']):\n iT[0]=iT[0]-1\n iT[1]=iT[1]-1\n ds = ds.isel(time_midp = slice(iT[0], iT[1]+1))\n else:\n ds = ds.isel(time_midp = slice(iT[0], iT[1]))\n \n # Cut axis can't be periodic\n if (len(ds['time']) < lenT or 'T' in dropAxes) and 'time' in periodic: periodic.remove('time')\n \n # ---------------------------\n # Horizontal MASK\n # ---------------------------\n \n if mask_outside and (YRange is not None or XRange is not None):\n if YRange is not None: minY = YRange[0]; maxY = YRange[1]\n else: minY = ds['YG'].min().values; maxY = ds['YG'].max().values\n if XRange is not None: minX = XRange[0]; maxX = XRange[1]\n else: minX = ds['XG'].min().values; maxX = ds['XG'].max().values \n \n maskC = _xr.where(_np.logical_and(_np.logical_and(ds['YC']>=minY, ds['YC']<=maxY),\n _np.logical_and(ds['XC']>=minX, ds['XC']<=maxX)), 1,0).persist()\n maskG = _xr.where(_np.logical_and(_np.logical_and(ds['YG']>=minY, ds['YG']<=maxY),\n _np.logical_and(ds['XG']>=minX, ds['XG']<=maxX)), 1,0).persist()\n maskU = _xr.where(_np.logical_and(_np.logical_and(ds['YU']>=minY, ds['YU']<=maxY),\n _np.logical_and(ds['XU']>=minX, ds['XU']<=maxX)), 1,0).persist()\n maskV = _xr.where(_np.logical_and(_np.logical_and(ds['YV']>=minY, ds['YV']<=maxY),\n _np.logical_and(ds['XV']>=minX, ds['XV']<=maxX)), 1,0).persist()\n for var in ds.data_vars:\n if set(['X', 'Y']).issubset(ds[var].dims): ds[var] = ds[var].where(maskC)\n elif set(['Xp1', 'Yp1']).issubset(ds[var].dims): ds[var] = ds[var].where(maskG)\n elif set(['Xp1', 'Y']).issubset(ds[var].dims): ds[var] = ds[var].where(maskU)\n elif set(['X', 'Yp1']).issubset(ds[var].dims): ds[var] = ds[var].where(maskV)\n \n # ---------------------------\n # TIME RESAMPLING\n # ---------------------------\n # Resample in time\n if timeFreq:\n \n # Infer original frequency\n inFreq=_pd.infer_freq(ds.time.values); \n if timeFreq[0].isdigit() and not inFreq[0].isdigit(): inFreq='1'+inFreq\n \n # Same frequency: Skip\n if timeFreq==inFreq:\n _warnings.warn(\"\\nInput time freq: [{}] = Output time frequency: [{}]:\"\n \"\\nSkip time resampling.\".format(inFreq, timeFreq), stacklevel=2)\n \n else:\n \n # Remove time_midp and warn\n vars2drop = [var for var in ds.variables if 'time_midp' in ds[var].dims]\n if vars2drop:\n _warnings.warn(\"\\nTime resampling drops variables on `time_midp` dimension.\"\n \"\\nDropped variables: {}.\".format(vars2drop), stacklevel=2)\n ds = ds.drop(vars2drop)\n if 'time_midp' in ds.dims: ds = ds.drop('time_midp')\n \n # Snapshot\n if sampMethod=='snapshot': \n # Find new times\n newtime = ds['time'].sel(time=ds['time'].resample(time=timeFreq).first())\n\n # Use slice when possible\n inds = [i for i, t in enumerate(ds['time'].values) if t in newtime.values]\n inds_diff = _np.diff(inds)\n if all(inds_diff==inds_diff[0]): \n ds = ds.isel(time = slice(inds[0], inds[-1]+1, inds_diff[0]))\n else: \n # TODO: is this an xarray bug od just bad chunking/bad coding/bad SciServe compute performances?\n # Make test case and open issue!\n attrs = ds.attrs\n ds = _xr.concat([ds.sel(time = time) for i, time in enumerate(newtime)], dim='time')\n ds.attrs = attrs\n # Mean\n elif sampMethod=='mean':\n\n # Separate time and timeless\n attrs = ds.attrs\n ds_dims = ds.drop([var for var in ds.variables if not var in ds.dims])\n ds_time = ds.drop([var for var in ds.variables if not 'time' in ds[var].dims])\n ds_timeless = ds.drop([var for var in ds.variables if 'time' in ds[var].dims])\n\n # Resample\n ds_time = ds_time.resample(time=timeFreq).mean('time')\n\n # Add all dimensions to ds, and fix attributes\n for dim in ds_time.dims:\n if dim=='time': ds_time[dim].attrs = ds_dims[dim].attrs\n else: ds_time[dim] = ds_dims[dim]\n\n # Merge\n ds = _xr.merge([ds_time, ds_timeless])\n ds.attrs = attrs\n \n # Update oceandataset\n od._ds = ds\n \n # Add time midp\n if timeFreq and 'time' not in dropAxes:\n od = od.set_grid_coords({**od.grid_coords, 'time' : {'time': -0.5}}, add_midp=True, overwrite=True)\n\n # Drop axes\n grid_coords = od.grid_coords\n for coord in list(grid_coords): \n if coord in dropAxes: grid_coords.pop(coord, None)\n od = od.set_grid_coords(grid_coords, overwrite=True)\n \n # Cut axis can't be periodic \n od = od.set_grid_periodic(periodic, overwrite = True)\n \n # Drop variables\n if varList is not None: \n if isinstance(varList, str): varList = [varList]\n \n # Compute missing variables\n od = _compute._add_missing_variables(od, varList)\n \n # Drop useless\n od._ds = od._ds.drop([v for v in od._ds.variables if (v not in od._ds.dims and v not in od._ds.coords and v not in varList)])\n \n return od\n\n\ndef mooring_array(od, Ymoor, Xmoor, \n **kwargs):\n \n \"\"\"\n Extract a mooring array section following the grid.\n Trajectories are great circle paths when coordinates are spherical.\n \n Parameters\n ----------\n od: OceanDataset\n od that will be subsampled\n Ymoor: 1D array_like, scalar\n Y coordinates of moorings. \n Xmoor: 1D array_like, scalar\n X coordinates of moorings.\n **kwargs: \n Keyword arguments for subsample.cutout\n\n Returns\n -------\n od: OceanDataset\n Subsampled oceandataset\n \n See Also\n --------\n subsample.cutout\n \"\"\" \n \n # Check\n for wrong_dim in ['mooring', 'station', 'particle']:\n if wrong_dim in od._ds.dims:\n raise ValueError('`mooring_array` cannot subsample oceandatasets with dimension [{}]'.format(wrong_dim))\n \n # Convert variables to numpy arrays and make some check\n Ymoor = _np.asarray(Ymoor, dtype=od._ds['YC'].dtype)\n if Ymoor.ndim == 0: Ymoor = Ymoor.reshape(1)\n elif Ymoor.ndim>1: raise TypeError('Invalid `Y`')\n\n Xmoor = _np.asarray(Xmoor, dtype=od._ds['XC'].dtype)\n if Xmoor.ndim == 0: Xmoor = Xmoor.reshape(1)\n elif Xmoor.ndim >1: raise TypeError('Invalid `X`')\n \n # Cutout\n if \"YRange\" not in kwargs: kwargs['YRange'] = Ymoor\n if \"XRange\" not in kwargs: kwargs['XRange'] = Xmoor\n if \"add_Hbdr\" not in kwargs: kwargs['add_Hbdr'] = True\n od = od.subsample.cutout(**kwargs)\n\n # Message\n print('Extracting mooring array.')\n \n # Unpack ds\n ds = od._ds\n \n # Useful variables\n YC = od._ds['YC']\n XC = od._ds['XC']\n R = od.parameters['rSphere']\n shape = XC.shape\n Yindex = XC.dims.index('Y')\n Xindex = XC.dims.index('X')\n \n # Convert to cartesian if spherical\n if R is not None:\n x, y, z = _utils.spherical2cartesian(Y = Ymoor, X = Xmoor, R = R)\n else:\n x = Xmoor; y = Ymoor; z = _np.zeros(Ymoor.shape)\n \n # Create tree\n tree = od.create_tree(grid_pos = 'C')\n \n # Indexes of nearest grid points\n _, indexes = tree.query(_np.column_stack((x, y, z)))\n indexes = _np.unravel_index(indexes, shape)\n iY = _np.ndarray.tolist(indexes[Yindex])\n iX = _np.ndarray.tolist(indexes[Xindex])\n \n # Remove duplicates\n diff_iY = _np.diff(iY)\n diff_iX = _np.diff(iX) \n to_rem = []\n for k, (diY, diX) in enumerate(zip(diff_iY, diff_iX)): \n if diY==0 and diX==0: to_rem = to_rem + [k]\n iY = _np.asarray([i for j, i in enumerate(iY) if j not in to_rem])\n iX = _np.asarray([i for j, i in enumerate(iX) if j not in to_rem])\n \n # Nearest coordinates\n near_Y = YC.isel(Y=_xr.DataArray(iY, dims=('tmp')), \n X=_xr.DataArray(iX, dims=('tmp'))).values\n near_X = XC.isel(Y=_xr.DataArray(iY, dims=('tmp')), \n X=_xr.DataArray(iX, dims=('tmp'))).values\n \n # Steps\n diff_iY = _np.fabs(_np.diff(iY))\n diff_iX = _np.fabs(_np.diff(iX))\n \n # Loop until all steps are 1\n while any(diff_iY+diff_iX!=1):\n \n # Find where need to add grid points\n k = _np.argwhere(diff_iY+diff_iX!=1)[0][0]\n lat0 = near_Y[k]; lon0 = near_X[k]\n lat1 = near_Y[k+1]; lon1 = near_X[k+1]\n \n # Find grid point in the middle \n if R is not None:\n # SPHERICAL: follow great circle path\n dist = _great_circle((lat0, lon0), (lat1, lon1), radius = R).km\n \n # Divide dist by 2.1 to make sure that returns 3 points\n dist = dist/2.1\n this_Y, this_X, this_dists = _utils.great_circle_path(lat0, lon0, lat1, lon1, dist) \n \n # Cartesian coordinate of point in the middle\n x, y, z = _utils.spherical2cartesian(this_Y[1], this_X[1], R)\n else:\n # CARTESIAN: take the average\n x = (lon0 + lon1)/2\n y = (lat0 + lat1)/2\n z = 0\n \n # Indexes of 3 nearest grid point\n _, indexes = tree.query(_np.column_stack((x, y, z)), k=3)\n indexes = _np.unravel_index(indexes, shape)\n new_iY = _np.ndarray.tolist(indexes[Yindex])[0]\n new_iX = _np.ndarray.tolist(indexes[Xindex])[0]\n\n # Extract just one point\n to_rem = []\n for i, (this_iY, this_iX) in enumerate(zip(new_iY, new_iX)):\n if (this_iY==iY[k] and this_iX==iX[k]) or (this_iY==iY[k+1] and this_iX==iX[k+1]): to_rem = to_rem+[i]\n new_iY = _np.asarray([i for j, i in enumerate(new_iY) if j not in to_rem])[0]\n new_iX = _np.asarray([i for j, i in enumerate(new_iX) if j not in to_rem])[0]\n \n # Extract new lat and lon\n new_lat = YC.isel(Y=new_iY, X=new_iX).values\n new_lon = XC.isel(Y=new_iY, X=new_iX).values\n \n # Insert\n near_Y = _np.insert(near_Y,k+1,new_lat)\n near_X = _np.insert(near_X,k+1,new_lon)\n iY = _np.insert(iY,k+1,new_iY)\n iX = _np.insert(iX,k+1,new_iX)\n\n # Steps\n diff_iY = _np.fabs(_np.diff(iY))\n diff_iX = _np.fabs(_np.diff(iX))\n \n # New dimensions\n mooring = _xr.DataArray(_np.arange(len(iX)), \n dims=('mooring'),\n attrs={'long_name': 'index of mooring',\n 'units': 'none'})\n y = _xr.DataArray(_np.arange(1), \n dims=('y'),\n attrs={'long_name': 'j-index of cell center',\n 'units': 'none'})\n x = _xr.DataArray(_np.arange(1), \n dims=('x'),\n attrs={'long_name': 'i-index of cell corner',\n 'units': 'none'})\n yp1 = _xr.DataArray(_np.arange(2), \n dims=('yp1'),\n attrs={'long_name': 'j-index of cell center',\n 'units': 'none'})\n xp1 = _xr.DataArray(_np.arange(2), \n dims=('xp1'),\n attrs={'long_name': 'i-index of cell corner',\n 'units': 'none'})\n \n # Transform indexes in DataArray\n iy = _xr.DataArray(_np.reshape(iY, (len(mooring), len(y))), \n coords={'mooring': mooring, 'y': y}, \n dims=('mooring', 'y'))\n ix = _xr.DataArray(_np.reshape(iX, (len(mooring), len(x))), \n coords={'mooring': mooring, 'x': x},\n dims=('mooring', 'x'))\n iyp1 = _xr.DataArray( _np.stack((iY, iY+1), 1), \n coords={'mooring': mooring, 'yp1': yp1},\n dims=('mooring', 'yp1'))\n ixp1 = _xr.DataArray( _np.stack((iX, iX+1), 1), \n coords={'mooring': mooring, 'xp1': xp1},\n dims=('mooring', 'xp1'))\n \n # Initialize new dataset\n new_ds = _xr.Dataset({'mooring': mooring, \n 'Y': y.rename(y = 'Y'), 'Yp1': yp1.rename(yp1 = 'Yp1'),\n 'X': x.rename(x = 'X'), 'Xp1': xp1.rename(xp1 = 'Xp1')},\n attrs = ds.attrs)\n \n # Loop and take out (looping is faster than apply to the whole dataset)\n for var in ds.variables:\n if var in ['X', 'Y', 'Xp1', 'Yp1']:\n new_ds[var].attrs.update({attr: ds[var].attrs[attr] for attr in ds[var].attrs if attr not in ['units', 'long_name']})\n continue\n elif not any(dim in ds[var].dims for dim in ['X', 'Y', 'Xp1', 'Yp1']): \n da = ds[var]\n else:\n for this_dims in [['Y', 'X'], ['Yp1', 'Xp1'], ['Y', 'Xp1'], ['Yp1', 'X']]:\n if set(this_dims).issubset(ds[var].dims):\n eval('iy', {}, {'iy': iy, 'ix': ix, 'iyp1': iyp1, 'ixp1': ixp1})\n da = ds[var].isel({dim : eval('i'+dim.lower(),\n {},\n {'iy': iy, 'ix': ix, 'iyp1': iyp1, 'ixp1': ixp1}) for dim in this_dims})\n da = da.drop(this_dims).rename({dim.lower():dim for dim in this_dims})\n\n # Merge\n new_ds = _xr.merge([new_ds, da.reset_coords()])\n \n # Merge removes the attributes: put them back! \n new_ds.attrs = ds.attrs\n\n # Add distance\n dists = _np.zeros(near_Y.shape)\n for i in range(1,len(dists)):\n coord1 = (near_Y[i-1], near_X[i-1])\n coord2 = (near_Y[i], near_X[i])\n \n if R is not None:\n # SPHERICAL\n dists[i] = _great_circle(coord1, coord2, radius = R).km\n else:\n # CARTESIAN\n dists[i] = _np.sqrt((coord2[0]-coord1[0])**2+(coord2[1]-coord1[1])**2)\n \n dists = _np.cumsum(dists)\n distance = _xr.DataArray(dists, \n coords={'mooring': mooring},\n dims=('mooring'),\n attrs={'long_name': 'Distance from first mooring'})\n \n if R is not None:\n # SPHERICAL\n distance.attrs['units'] = 'km'\n else:\n # CARTESIAN\n if 'units' in XC.attrs:\n distance.attrs['units'] = XC.attrs['units']\n new_ds['mooring_dist'] = distance\n \n # Reset coordinates\n new_ds = new_ds.set_coords([coord for coord in ds.coords]+['mooring_dist'])\n \n # Recreate od\n od._ds = new_ds\n od = od.set_grid_coords({'mooring': {'mooring': -0.5}}, add_midp=True, overwrite=False)\n \n # Create dist_midp\n dist_midp = _xr.DataArray(od._grid.interp(od._ds['mooring_dist'], 'mooring'),\n attrs=od._ds['mooring_dist'].attrs)\n od = od.merge_into_oceandataset(dist_midp.rename('mooring_midp_dist'))\n od._ds = od._ds.set_coords([coord for coord in od._ds.coords]+['mooring_midp_dist'])\n\n return od\n\ndef survey_stations(od, Ysurv, Xsurv, delta=None,\n xesmf_regridder_kwargs = {'method': 'bilinear'}, **kwargs):\n \n \"\"\"\n Extract survey stations with regular spacing.\n Trajectories are great circle paths when coordinates are spherical.\n \n Parameters\n ----------\n od: OceanDataset\n od that will be subsampled\n Ysurv: 1D array_like\n Y coordinates of stations. \n Xsurv: 1D array_like,\n X coordinates of stations.\n delta: scalar, None\n Distance between stations.\n Units are km for spherical coordinate, same units of coordinates for cartesian.\n If None, only (Ysurv, Xsurv) stations are used.\n xesmf_regridder_kwargs: dict\n Keyword arguments for xesmf.regridder, such as `method`.\n Defaul method: `bilinear`. \n Available methods: {‘bilinear’, ‘conservative’, ‘patch’, ‘nearest_s2d’, ‘nearest_d2s’}\n **kwargs: \n Keyword arguments for subsample.cutout\n\n Returns\n -------\n od: OceanDataset\n Subsampled oceandataset\n \n See Also\n --------\n subsample.cutout\n \n References\n ----------\n https://xesmf.readthedocs.io/en/stable/user_api.html#regridder\n \n Notes\n -----\n By default, kwargs['add_Hbdr'] = True. Try to play with add_Hbdr values if zeros/nans are returned.\n ospy.survey_stations interpolates using xesmf.regridder. THIS FUNCTION DOES NOT SUPPORT LAZY COMPUTATION!\n \n xesmf.regridder currently dosen't allow to set the coordinates system (default is spherical).\n Surveys using cartesian coordinates can be made by changing the xesmf source code as explained here: https://github.com/JiaweiZhuang/xESMF/issues/39\n \"\"\"\n \n # Check\n for wrong_dim in ['mooring', 'station', 'particle']:\n if wrong_dim in od._ds.dims:\n raise ValueError('`survey_stations` cannot subsample oceandatasets with dimension [{}]'.format(wrong_dim))\n \n # Convert variables to numpy arrays and make some check\n Ysurv = _np.asarray(Ysurv, dtype=od._ds['YC'].dtype)\n if Ysurv.ndim == 0: Ysurv = Ysurv.reshape(1)\n elif Ysurv.ndim>1: raise TypeError('Invalid `Y`')\n\n Xsurv = _np.asarray(Xsurv, dtype=od._ds['XC'].dtype)\n if Xsurv.ndim == 0: Xsurv = Xsurv.reshape(1)\n elif Xsurv.ndim >1: raise TypeError('Invalid `X`')\n \n if not isinstance(xesmf_regridder_kwargs, dict):\n raise TypeError('`xesmf_regridder_kwargs` must be dict')\n \n # Earth Radius\n R = od.parameters['rSphere']\n if R is None:\n _warnings.warn(\"\\nospy.survey_stations interpolates using xesmf.regridder.\"\n \"\\nxesmf.regridder currently dosen't allow to set the coordinates system (default is spherical).\"\n \"\\nSurveys using cartesian coordinates can be made by changing the xesmf source code as explained here:\"\n \"https://github.com/JiaweiZhuang/xESMF/issues/39\", stacklevel=2)\n \n # Compute trajectory\n for i, (lat0, lon0, lat1, lon1) in enumerate(zip(Ysurv[:-1], Xsurv[:-1], Ysurv[1:], Xsurv[1:])):\n if R is not None:\n # SPHERICAL: follow great circle path\n this_Y, this_X, this_dists = _utils.great_circle_path(lat0,lon0,lat1,lon1,delta, R=R)\n else:\n # CARTESIAN: just a simple interpolation\n this_Y, this_X, this_dists = _utils.cartesian_path(lat0,lon0,lat1,lon1,delta)\n if i==0: \n Y_surv = this_Y\n X_surv = this_X\n dists_surv = this_dists\n else:\n this_Y = _np.delete(this_Y, 0, axis=None)\n this_X = _np.delete(this_X, 0, axis=None) \n this_dists = _np.delete(this_dists, 0, axis=None) \n if len(this_dists)==0: continue\n this_dists = this_dists + dists_surv[-1]\n Y_surv = _np.concatenate((Y_surv, this_Y))\n X_surv = _np.concatenate((X_surv, this_X))\n dists_surv = _np.concatenate((dists_surv, this_dists)) \n\n # Cutout\n if \"YRange\" not in kwargs: kwargs['YRange'] = Y_surv\n if \"XRange\" not in kwargs: kwargs['XRange'] = X_surv\n if \"add_Hbdr\" not in kwargs: kwargs['add_Hbdr'] = True\n od = od.subsample.cutout(**kwargs)\n\n # Message\n print('Carrying out survey.') \n \n # Unpack ds and grid\n ds = od._ds\n grid = od._grid\n \n # TODO: This is probably slowing everything down, and perhaps adding some extra error.\n # I think we should have separate xesmf interpolations for different grids, then merge.\n # Move all variables on same spatial grid\n for var in [var for var in ds.variables if var not in ds.dims]:\n for dim in ['Xp1', 'Yp1']:\n if dim in ds[var].dims and var!=dim:\n attrs = ds[var].attrs\n ds[var] = grid.interp(ds[var], axis=dim[0], to='center', boundary='fill', fill_value=_np.nan)\n ds[var].attrs = attrs\n \n # Create xesmf datsets \n ds_in = ds\n coords_in = ds_in.coords\n ds_in = ds_in.reset_coords()\n ds_in['lat'] = ds_in['YC']\n ds_in['lon'] = ds_in['XC']\n ds = _xr.Dataset({'lat': (['lat'], Y_surv),\n 'lon': (['lon'], X_surv)},\n attrs = ds.attrs)\n\n # Interpolate\n regridder = _xe.Regridder(ds_in, ds, **xesmf_regridder_kwargs) \n interp_vars = [var for var in ds_in.variables if var not in ['lon', 'lat', 'X', 'Y']]\n print('Variables to interpolate: {}.'.format([var for var in interp_vars if set(['X', 'Y']).issubset(ds_in[var].dims)]))\n for var in interp_vars:\n if set(['X', 'Y']).issubset(ds_in[var].dims):\n print('Interpolating [{}].'.format(var))\n attrs = ds_in[var].attrs\n ds[var] = regridder(ds_in[var])\n ds[var].attrs = attrs\n elif var not in ['Xp1', 'Yp1']: \n ds[var] = ds_in[var].reset_coords(drop=True)\n regridder.clean_weight_file() \n \n # Extract transect \n ds = ds.isel(lat=_xr.DataArray(_np.arange(len(Y_surv)), dims='station'),\n lon=_xr.DataArray(_np.arange(len(X_surv)), dims='station'))\n \n # Add station dimension\n ds['station'] = _xr.DataArray(_np.arange(len(X_surv)), \n dims=('station'),\n attrs={'long_name': 'index of survey station',\n 'units': 'none'}) \n \n # Add distance\n ds['station_dist'] = _xr.DataArray(dists_surv,\n dims=('station'),\n attrs={'long_name': 'Distance from first station'})\n if R is not None:\n # SPHERICAL\n ds['station_dist'].attrs['units'] = 'km'\n else:\n # CARTESIAN\n if 'units' in ds['lat'].attrs:\n ds['station_dist'].attrs['units'] = ds['lat'].attrs['units']\n ds = ds.set_coords('station_dist')\n \n # Return od\n od._ds = ds\n grid_coords = od.grid_coords\n grid_coords.pop('X', None)\n grid_coords.pop('Y', None)\n od = od.set_grid_coords(grid_coords, overwrite=True)\n od = od.set_grid_coords({'station': {'station': -0.5}}, add_midp=True, overwrite=False)\n \n # Create dist_midp\n dist_midp = _xr.DataArray(od._grid.interp(od._ds['station_dist'], 'station'),\n attrs=od._ds['station_dist'].attrs)\n od = od.merge_into_oceandataset(dist_midp.rename('station_midp_dist'))\n od._ds = od._ds.set_coords([coord for coord in od._ds.coords]+['station_midp_dist'])\n \n return od\n\n\n\n\n\ndef particle_properties(od, times, Ypart, Xpart, Zpart, **kwargs):\n \n \"\"\"\n Extract Eulerian properties of particles using nearest-neighbor interpolation.\n \n Parameters\n ----------\n od: OceanDataset\n od that will be subsampled.\n times: 1D array_like or scalar\n time of particles.\n Ypart: 2D array_like or 1D array_like if times is scalar\n Y coordinates of particles. Dimensions order: (time, particle)\n Xpart: 2D array_like or 1D array_like if times is scalar\n X coordinates of particles. Dimensions order: (time, particle)\n Zpart: 2D array_like or 1D array_like if times is scalar\n Z of particles. Dimensions order: (time, particle)\n **kwargs: \n Keyword arguments for subsample.cutout\n\n Returns\n -------\n od: OceanDataset\n Subsampled oceandataset\n \n See Also\n --------\n subsample.cutout\n OceanDataset.create_tree\n \"\"\"\n # TODO: add different interpolations. Renske already has some code.\n \n # Check\n for wrong_dim in ['mooring', 'station', 'particle']:\n if wrong_dim in od._ds.dims:\n raise ValueError('`particle_properties` cannot subsample oceandatasets with dimension [{}]'.format(wrong_dim))\n \n # Convert variables to numpy arrays and make some check\n times = _np.asarray(times, dtype = od._ds['time'].dtype)\n if times.ndim == 0: times = times.reshape(1)\n elif times.ndim >1: raise TypeError('Invalid `times`')\n \n Ypart = _np.asarray(Ypart)\n if Ypart.ndim <2 and Ypart.size==1: Ypart = Ypart.reshape((1, Ypart.size))\n elif Ypart.ndim >2: raise TypeError('Invalid `Ypart`')\n \n Xpart = _np.asarray(Xpart)\n if Xpart.ndim <2 and Xpart.size==1: Xpart = Xpart.reshape((1, Xpart.size))\n elif Xpart.ndim >2: raise TypeError('Invalid `Xpart`')\n \n Zpart = _np.asarray(Zpart)\n if Zpart.ndim <2 and Zpart.size==1: Zpart = Zpart.reshape((1, Zpart.size))\n elif Zpart.ndim >2: raise TypeError('Invalid `Zpart`')\n\n if (not Ypart.ndim==Xpart.ndim==Zpart.ndim or not times.size==Ypart.shape[0]):\n TypeError('`times`, `Xpart`, `Ypart`, and `Zpart` have inconsistent shape')\n \n # Cutout\n if \"timeRange\" not in kwargs: kwargs['timeRange'] = times\n if \"YRange\" not in kwargs: kwargs['YRange'] = [_np.min(Ypart), _np.max(Ypart)]\n if \"XRange\" not in kwargs: kwargs['XRange'] = [_np.min(Xpart), _np.max(Xpart)]\n if \"ZRange\" not in kwargs: kwargs['ZRange'] = [_np.min(Zpart), _np.max(Zpart)]\n if \"add_Hbdr\" not in kwargs: kwargs['add_Hbdr'] = True\n if \"add_Vbdr\" not in kwargs: kwargs['add_Vbdr'] = True \n od = od.subsample.cutout(**kwargs)\n \n # Message\n print('Extracting Eulerian properties of particles.')\n \n # Unpack ds and info\n ds = od._ds\n R = od.parameters['rSphere']\n\n # Remove time_midp and warn\n vars2drop = [var for var in ds.variables if 'time_midp' in ds[var].dims]\n if vars2drop:\n _warnings.warn(\"\\nParticle properties extraction drops variables on `time_midp` dimension. \\nDropped variables: {}.\".format(vars2drop), stacklevel=2)\n ds = ds.drop(vars2drop)\n if 'time_midp' in ds.dims: ds = ds.drop('time_midp')\n \n # New dimensions\n time = _xr.DataArray(times,\n dims = ('time'),\n attrs = ds['time'].attrs)\n particle = _xr.DataArray(_np.arange(Ypart.shape[1]), \n dims = ('particle'),\n attrs={'long_name': 'index of particle',\n 'units': 'none'})\n i_ds = _xr.Dataset({'time': time, 'particle': particle})\n \n # Find vertical and time indexes\n for dim in ds.dims:\n if dim=='time':\n tmp = _xr.DataArray(times,\n dims = ('time'))\n elif dim[0]=='Z':\n tmp = _xr.DataArray(Zpart,\n dims = ('time', 'particle'))\n else: continue\n itmp = _xr.DataArray(_np.arange(len(ds[dim])),\n coords = {dim: ds[dim].values},\n dims = {dim})\n itmp = itmp.sel({dim: tmp}, method='nearest')\n i_ds['i'+dim] = itmp\n \n # Convert 2 cartesian\n if R is not None:\n x, y, z = _utils.spherical2cartesian(Y = Ypart, X = Xpart, R = R)\n else:\n x = Xpart; y = Ypart; z = _np.zeros(Y.shape)\n \n # Find horizontal indexes\n for grid_pos in ['C', 'U', 'V', 'G']:\n \n # Don't create tree if no variables\n var_grid_pos = [var for var in ds.variables \n if var not in ds.coords and set(['X'+grid_pos, 'Y'+grid_pos]).issubset(ds[var].coords)]\n if not var_grid_pos: continue\n \n # Useful variables\n Y = od._ds['Y' + grid_pos]\n X = od._ds['X' + grid_pos]\n shape = X.shape\n Yname = [dim for dim in Y.dims if dim[0]=='Y'][0]\n Xname = [dim for dim in X.dims if dim[0]=='X'][0]\n Yindex = X.dims.index(Yname)\n Xindex = X.dims.index(Xname)\n \n # Create tree\n tree = od.create_tree(grid_pos = grid_pos)\n\n # Indexes of nearest grid points\n _, indexes = tree.query(_np.column_stack((x.flatten(), y.flatten(), z.flatten())))\n indexes = _np.unravel_index(indexes, shape)\n iY = _xr.DataArray(_np.reshape(indexes[Yindex], y.shape),\n dims = ('time', 'particle'))\n iX = _xr.DataArray(_np.reshape(indexes[Xindex], x.shape),\n dims = ('time', 'particle')) \n \n # Transform indexes in DataArray and add to dictionary\n i_ds['i'+Yname] = iY\n i_ds['i'+Xname] = iX\n \n # Subsample (looping is faster)\n for var in var_grid_pos:\n i_ds[var] = ds[var].isel({dim: i_ds['i'+dim] for dim in ds[var].dims})\n \n # Remove indexes\n i_ds = i_ds.drop([var for var in i_ds.variables if var not in ds.variables and var not in i_ds.dims])\n \n # Recreate od\n od._ds = i_ds\n \n # Add time midp\n od = od.set_grid_coords({'time' : {'time': -0.5}}, add_midp=True, overwrite=True)\n \n return od\n\n\nclass _subsampleMethdos(object):\n \"\"\"\n Enables use of oceanspy.subsample functions as attributes on a OceanDataset.\n For example, OceanDataset.subsample.cutout\n \"\"\"\n \n def __init__(self, od):\n self._od = od\n\n @_functools.wraps(cutout)\n def cutout(self, **kwargs):\n return cutout(self._od, **kwargs)\n \n @_functools.wraps(mooring_array)\n def mooring_array(self, **kwargs):\n return mooring_array(self._od, **kwargs)\n \n @_functools.wraps(survey_stations)\n def survey_stations(self, **kwargs):\n return survey_stations(self._od, **kwargs)\n \n @_functools.wraps(particle_properties)\n def particle_properties(self, **kwargs):\n return particle_properties(self._od, **kwargs)\n\n","sub_path":"oceanspy/subsample.py","file_name":"subsample.py","file_ext":"py","file_size_in_byte":46009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"104613077","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\n\ndef make_features(x):\n \"\"\"Builds features i.e. a matrix with colums [x,x^2,x^3]. \"\"\"\n x=x.unsqueeze(1)\n return torch.cat([x**i for i in range(1,4)],1)\n\nw_target=torch.FloatTensor([0.5,3,2.4]).unsqueeze(1)\nb_target=torch.FloatTensor([0.9])\n\ndef f(x):\n \"\"\" Approximated funhction.\"\"\"\n return x.mm(w_target)+b_target[0]\n\ndef get_batch(batch_size=32):\n \"\"\"Build a batch i.e. (x,f(x)) pair.\"\"\"\n random=torch.randn(batch_size)\n x=make_features(random)\n y=f(x)\n\n if torch.cuda.is_available():\n return Variable(x).cuda(),Variable(y).cuda()\n else:\n return Variable(x),Variable(y)\n\n#Define model\nclass PolyModel(nn.Module):\n def __init__(self):\n super(PolyModel, self).__init__()\n self.poly=nn.Linear(3,1)\n def forward(self,x):\n return self.poly(x)\n\nif torch.cuda.is_available():\n model=PolyModel().cuda()\nelse:\n model=PolyModel()\n\ncriterion=nn.MSELoss()\noptimizer=optim.SGD(model.parameters(),lr=1e-3)\n\nepoch=0\n\nwhile True:\n #Get data\n batch_x,batch_y=get_batch()\n # Forward pass\n output=model(batch_x)\n loss=criterion(output,batch_y)\n print_loss=loss.data[0]\n # Reset gradients\n optimizer.zero_grad()\n # Backward pass\n loss.backward()\n # update parameters\n optimizer.step()\n epoch+=1\n if print_loss<1e-3:\n break\n\nprint(\"----->\",)\n\n","sub_path":"pytorch-regression.py","file_name":"pytorch-regression.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"169291229","text":"############################################################################################################################################\n# This script is used to sync 3rd party dependencies from `.\\sdk\\spring\\spring_boot_SPRING_BOOT_VERSION_managed_external_dependencies.txt`\n# to `eng/versioning/external_dependencies.txt`.\n#\n# How to use this script.\n# 1. Get `SPRING_BOOT_VERSION` from https://github.com/spring-projects/spring-boot/tags.\n# 2. Make sure file(`.\\sdk\\spring\\spring_boot_${SPRING_BOOT_VERSION}_managed_external_dependencies.txt`) exist. If it doesn't exist, please run\n# `.\\sdk\\spring\\scripts\\get_spring_boot_managed_external_dependencies.py` to create that file.\n# 3. Run command: `python .\\sdk\\spring\\scripts\\sync_external_dependencies.py -b 2.7.0`.\n# Or `python .\\sdk\\spring\\scripts\\sync_external_dependencies.py --spring_boot_dependencies_version 2.7.0`.\n# 4. Then `eng/versioning/external_dependencies.txt` will be updated.\n#\n# Please refer to ./README.md to get more information about this script.\n############################################################################################################################################\n\nimport in_place\nimport time\nimport os\nimport unittest\nimport argparse\nfrom itertools import takewhile\n\nfrom log import log\n\nEXTERNAL_DEPENDENCIES_FILE = 'eng/versioning/external_dependencies.txt'\nSKIP_IDS = [\n 'org.eclipse.jgit:org.eclipse.jgit' # Refs: https://github.com/Azure/azure-sdk-for-java/pull/13956/files#r468368271\n]\n\n\ndef get_spring_boot_managed_external_dependencies_file_name(spring_boot_version):\n return 'sdk/spring/scripts/spring_boot_{}_managed_external_dependencies.txt'.format(spring_boot_version)\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-b', '--spring_boot_dependencies_version', type = str, required = True)\n parser.add_argument(\n '--log',\n type = str,\n choices = ['debug', 'info', 'warn', 'error', 'none'],\n required = False,\n default = 'info',\n help = 'Set log level.'\n )\n args = parser.parse_args()\n log.set_log_level(args.log)\n return args\n\n\ndef main():\n start_time = time.time()\n change_to_repo_root_dir()\n args = get_args()\n log.debug('Current working directory = {}.'.format(os.getcwd()))\n sync_external_dependencies(get_spring_boot_managed_external_dependencies_file_name(args.spring_boot_dependencies_version), EXTERNAL_DEPENDENCIES_FILE)\n elapsed_time = time.time() - start_time\n log.info('elapsed_time = {}'.format(elapsed_time))\n\n\ndef change_to_repo_root_dir():\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n os.chdir('../../..')\n\n\ndef sync_external_dependencies(source_file, target_file):\n # Read artifact version from source_file.\n dependency_dict = {}\n with open(source_file) as file:\n for line in file:\n line = line.strip()\n if line.startswith('#') or not line:\n file.write(line)\n else:\n key_value = line.split(';', 1)\n key = key_value[0]\n value = key_value[1]\n dependency_dict[key] = value\n # Write artifact versions into target file.\n with in_place.InPlace(target_file) as file:\n for line in file:\n line = line.strip()\n if line.startswith('#') or not line:\n file.write(line)\n else:\n key_value = line.split(';', 1)\n key = key_value[0]\n value = key_value[1]\n if key not in SKIP_IDS and key in dependency_dict:\n value_in_dict = dependency_dict[key]\n if version_bigger_than(value, value_in_dict):\n log.warn('Version update skipped. key = {}, value = {}, new_value = {}'.format(key, value, value_in_dict))\n file.write(line)\n elif version_bigger_than(value_in_dict, value):\n log.info('Version updated. key = {}, value = {}, new_value = {}'.format(key, value, value_in_dict))\n file.write('{};{}'.format(key, value_in_dict))\n else:\n file.write(line)\n else:\n file.write(line)\n file.write('\\n')\n\n\ndef version_bigger_than(version1, version2):\n v1 = version1.split('.')\n v2 = version2.split('.')\n len_1 = len(v1)\n len_2 = len(v2)\n max_len = max(len_1, len_1)\n for i in range(max_len):\n if i < len_1 and i < len_2:\n int_1 = int('0' + ''.join(takewhile(str.isdigit, v1[i])))\n int_2 = int('0' + ''.join(takewhile(str.isdigit, v2[i])))\n if int_1 != int_2:\n return int_1 > int_2\n elif i < len_1:\n return True\n else:\n return False\n return False\n\n\nclass Tests(unittest.TestCase):\n def test_version_bigger_than(self):\n self.assertEqual(version_bigger_than('1', '2'), False)\n self.assertEqual(version_bigger_than('2', '1'), True)\n self.assertEqual(version_bigger_than('1.0', '2'), False)\n self.assertEqual(version_bigger_than('2.0', '1'), True)\n self.assertEqual(version_bigger_than('1.1', '1'), True)\n self.assertEqual(version_bigger_than('1', '1.1'), False)\n self.assertEqual(version_bigger_than('1.0-RELEASE', '1.1'), False)\n self.assertEqual(version_bigger_than('1.1-RELEASE', '1'), True)\n self.assertEqual(version_bigger_than('1.1-RELEASE', '1.0'), True)\n self.assertEqual(version_bigger_than('1.1-RELEASE', '1.0.1'), True)\n self.assertEqual(version_bigger_than('1.1-RELEASE', '1.0.1-RELEASE'), True)\n self.assertEqual(version_bigger_than('1.1-RELEASE', '1.1.1-RELEASE'), False)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sdk/spring/scripts/sync_external_dependencies.py","file_name":"sync_external_dependencies.py","file_ext":"py","file_size_in_byte":5843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"186953646","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2016-2019 Intel, Inc. All rights reserved.\n# $COPYRIGHT$\n#\n# Additional copyrights may follow\n#\n# $HEADER$\n#\n\nimport os\nimport sys\ntry:\n from queue import *\nexcept:\n from queue import *\nimport threading\nfrom CNCMTTTool import *\n\nclass workerThread(threading.Thread):\n def __init__(self, threadID, queue, status, lock, testDef):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.queue = queue\n self.lock = lock\n self.status = status\n self.testDef = testDef\n return\n\n def run(self):\n self.testDef.logger.verbose_print(\"IPMITool: Thread \" + str(self.threadID) + \" is active\")\n while True:\n self.lock.acquire()\n if not self.queue.empty():\n task = self.queue.get()\n self.lock.release()\n self.testDef.logger.verbose_print(\"IPMITool: Thread \" + str(self.threadID) + \" received task \" + ' '.join(task['cmd']))\n # we should have received a dictionary - check for dryrun\n dryrun = False\n try:\n if task['dryrun']:\n dryrun = True\n except:\n pass\n # check the cmd\n try:\n if task['reset']:\n if dryrun:\n # just record a result\n self.testDef.logger.verbose_print(\"IPMITool: Thread \" + str(self.threadID) + \" dryrun reset \" + task['target'])\n self.lock.acquire()\n self.status.append((0, ' '.join(task['cmd']), None))\n self.lock.release()\n continue\n # ping until we get a response\n ntries = 0\n while True:\n ++ntries\n results = self.testDef.execmd.execute(None, task['cmd'], self.testDef)\n if 0 == results['status'] or ntries == task['maxtries']:\n self.testDef.logger.verbose_print(\"IPMITool: node \" + task['target'] + \" is back\")\n break\n # record the result\n self.lock.acquire()\n if 0 != results['status'] and ntries >= task['maxtries']:\n msg = \"Operation timed out on node \" + task['target']\n self.status.append((-1, ' '.join(task['cmd']), msg))\n else:\n self.status.append((results['status'], results['stdout'], results['stderr']))\n self.lock.release()\n continue\n except:\n try:\n if task['cmd'] is not None:\n if dryrun:\n # just record a result\n self.testDef.logger.verbose_print(\"IPMITool: Thread \" + str(self.threadID) + \" dryrun \" + ' '.join(task['cmd']))\n self.lock.acquire()\n self.status.append((0, ' '.join(task['cmd']), None))\n # add reset command if required\n try:\n if task['target'] is not None:\n # add the reset command to the queue\n ckcmd = {}\n ckcmd['reset'] = True\n ckcmd['cmd'] = [\"ping\", \"-c\", \"1\", task['target']]\n ckcmd['maxtries'] = task['maxtries']\n ckcmd['target'] = task['target'] # just for debug purposes\n ckcmd['dryrun'] = dryrun\n # add it to the queue\n self.queue.put(ckcmd)\n except:\n pass\n self.lock.release()\n continue\n # send it off to ipmitool to execute\n self.testDef.logger.verbose_print(\"IPMITool: \" + ' '.join(task['cmd']))\n results = self.testDef.execmd.execute(None, task['cmd'], self.testDef)\n self.lock.acquire()\n self.status.append((results['status'], results['stdout'], results['stderr']))\n try:\n if task['target'] is not None:\n # add the reset command to the queue\n ckcmd['reset'] = True\n ckcmd['cmd'] = [\"ping\", \"-c\", \"1\", task['target']]\n ckcmd['maxtries'] = task['maxtries']\n ckcmd['target'] = task['target'] # just for debug purposes\n ckcmd['dryrun'] = dryrun\n # add it to the queue\n self.queue.put(ckcmd)\n except:\n pass\n self.lock.release()\n continue\n else:\n # mark as a bad command\n self.lock.acquire()\n self.status.append((2, \"NULL\", \"Missing command\"))\n self.lock.release()\n continue\n except:\n # bad input\n self.lock.acquire()\n self.status.append((2, \"NULL\", \"Missing command\"))\n self.lock.release()\n continue\n else:\n # if the queue is empty, then we are done\n self.lock.release()\n return\n\n## @addtogroup Tools\n# @{\n# @addtogroup CNC\n# @section IPMITool\n# Interface to the ipmitool cmd line\n# @param target List of remote host names or LAN interfaces to monitor during reset operations\n# @param controller List of IP addresses of remote node controllers/BMCs\n# @param username Remote session username\n# @param password Remote session password\n# @param pwfile File containing remote session password\n# @param command Command to be sent\n# @param maxtries Max number of times to ping each host before declaring reset to fail\n# @param numthreads Number of worker threads to use\n# @param dryrun Dryrun - print out commands but do not execute\n# @param sudo Use sudo to exeute privilaged comands\n# @param modules_unload Modules to unload\n# @param modules Modules to load\n# @param modules_swap Modules to swap\n# @}\nclass IPMITool(CNCMTTTool):\n def __init__(self):\n CNCMTTTool.__init__(self)\n self.options = {}\n self.options['target'] = (None, \"List of remote host names or LAN interfaces to monitor during reset operations\")\n self.options['controller'] = (None, \"List of IP addresses of remote node controllers/BMCs\")\n self.options['username'] = (None, \"Remote controller username\")\n self.options['password'] = (None, \"Remote controller password\")\n self.options['pwfile'] = (None, \"File containing remote controller password\")\n self.options['command'] = (None, \"Command to be sent\")\n self.options['maxtries'] = (100, \"Max number of times to ping each host before declaring reset to fail\")\n self.options['numthreads'] = (30, \"Number of worker threads to use\")\n self.options['dryrun'] = (False, \"Dryrun - print out commands but do not execute\")\n self.options['sudo'] = (False, \"Use sudo to execute privileged commands\")\n self.options['modules_unload'] = (None, \"Modules to unload\")\n self.options['modules'] = (None, \"Modules to load\")\n self.options['modules_swap'] = (None, \"Modules to swap\")\n self.lock = threading.Lock()\n self.threads = []\n self.threadID = 0\n self.status = []\n return\n\n def activate(self):\n # use the automatic procedure from IPlugin\n IPlugin.activate(self)\n return\n\n def deactivate(self):\n IPlugin.deactivate(self)\n\n def print_name(self):\n return \"IPMITool\"\n\n def print_options(self, testDef, prefix):\n lines = testDef.printOptions(self.options)\n for line in lines:\n print((prefix + line))\n return\n\n def execute(self, log, keyvals, testDef):\n testDef.logger.verbose_print(\"IPMITool execute\")\n\n # parse what we were given against our defined options\n cmds = {}\n testDef.parseOptions(log, self.options, keyvals, cmds)\n testDef.logger.verbose_print(\"IPMITool: \" + ' '.join(cmds))\n\n # Apply any requested environment module settings\n status,stdout,stderr = testDef.modcmd.applyModules(log['section'], cmds, testDef)\n if 0 != status:\n log['status'] = status\n log['stdout'] = stdout\n log['stderr'] = stderr\n return\n\n # must have given us at least one controller address\n try:\n if cmds['controller'] is None:\n log['status'] = 1\n log['stderr'] = \"No target controllers identified\"\n return\n else:\n # convert to a list\n controllers = cmds['controller'].split(',')\n except:\n log['status'] = 1\n log['stderr'] = \"No target controllers identified\"\n return\n # and a command\n try:\n if cmds['command'] is None:\n log['status'] = 1\n log['stderr'] = \"No IPMI command given\"\n return\n except:\n log['status'] = 1\n log['stderr'] = \"No IPMI command given\"\n return\n # if this is a reset command, then we must have targets\n # for each controller\n try:\n if cmds['target'] is None:\n log['status'] = 1\n log['stderr'] = \"No target nodes identified\"\n return\n else:\n # convert it to a list\n targets = cmds['target'].split(\",\")\n # must match number of controllers\n if len(targets) != len(controllers):\n log['status'] = 1\n log['stderr'] = \"Number of targets doesn't equal number of controllers\"\n return\n reset = True\n except:\n reset = False\n # Setup the queue - we need a spot for the command to be sent to each\n # identified target. If it is a command that will result in cycling\n # the node, then we need to double it so we can execute the loop of\n # \"ping\" commands to detect node restart\n if reset:\n ipmiQueue = Queue(2 * len(controllers))\n else:\n ipmiQueue = Queue(len(controllers))\n\n # Fill the queue\n self.lock.acquire()\n for n in range(0, len(controllers)):\n # construct the cmd\n cmd = {}\n ipmicmd = cmds['command'].split()\n ipmicmd.insert(0, \"chassis\")\n ipmicmd.insert(0, \"ipmitool\")\n if cmds['sudo']:\n ipmicmd.insert(0, \"sudo\")\n ipmicmd.append(\"-H\")\n ipmicmd.append(controllers[n])\n if cmds['username'] is not None:\n ipmicmd.append(\"-U\")\n ipmicmd.append(cmds['username'])\n if cmds['password'] is not None:\n ipmicmd.append(\"-P\")\n ipmicmd.append(cmds['password'])\n try:\n if cmds['pwfile'] is not None:\n if os.path.exists(cmds['pwfile']):\n f = open(cmds['pwfile'], 'r')\n password = f.readline().strip()\n ipmicmd.append(\"-P\")\n ipmicmd.append(password)\n f.close()\n else:\n log['stdout'] = None\n log['status'] = 1;\n log['stderr'] = \"Password file \" + cmds['pwfile'] + \" does not exist\"\n return\n except KeyError:\n pass\n cmd['cmd'] = ipmicmd\n if reset:\n cmd['target'] = targets[n]\n cmd['maxtries'] = cmds['maxtries']\n cmd['dryrun'] = cmds['dryrun']\n # add it to the queue\n ipmiQueue.put(cmd)\n # setup the response\n self.status = []\n # spin up the threads\n self.threads = []\n # release the queue\n self.lock.release()\n if len(targets) < cmds['numthreads']:\n rng = len(targets)\n else:\n rng = cmds['numthreads']\n for n in range(0, rng):\n thread = workerThread(self.threadID, ipmiQueue, self.status, self.lock, testDef)\n thread.start()\n self.threads.append(thread)\n self.threadID += 1\n # wait for completion\n while not ipmiQueue.empty():\n pass\n # wait for all threads to complete/terminate\n for t in self.threads:\n t.join()\n # set our default log\n log['status'] = 0\n # use an empty string so we can easily collect all of the stdouts\n log['stdout'] = \"\"\n log['stderr'] = None\n # determine our final status - if any of the steps failed, then\n # set the status to the first one that did\n for st in self.status:\n # Collect all of the stdouts\n newlog = log['stdout'] + \" \" + ''.join(st[1])\n log['stdout'] = newlog\n if 0 != st[0]:\n log['status'] = st[0]\n log['stderr'] = st[2]\n\n # Revert any requested environment module settings\n status,stdout,stderr = testDef.modcmd.revertModules(log['section'], testDef)\n if 0 != status:\n log['status'] = status\n log['stdout'] = stdout\n log['stderr'] = stderr\n return\n\n return\n","sub_path":"pylib/Tools/CNC/IPMITool.py","file_name":"IPMITool.py","file_ext":"py","file_size_in_byte":14537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"317324267","text":"# -*- coding: utf-8 -*-\n##----------------------------------------------------------------------\n## ObjectStatus\n## Updated by SAE according to ping check changes\n##----------------------------------------------------------------------\n## Copyright (C) 2007-2013 The NOC Project\n## See LICENSE for details\n##----------------------------------------------------------------------\n\n## NOC modules\nfrom noc.lib.nosql import Document, IntField, BooleanField\n\n\nclass ObjectStatus(Document):\n meta = {\n \"collection\": \"noc.cache.object_status\",\n \"allow_inheritance\": False,\n \"indexes\": [\"object\"]\n }\n # Object id\n object = IntField(required=True)\n # True - object is Up\n # False - object is Down\n status = BooleanField()\n\n def __unicode__(self):\n return u\"%s: %s\" % (self.object, self.status)\n\n @classmethod\n def get_status(cls, object):\n s = cls.objects.filter(object=object.id).first()\n if s:\n return s.status\n else:\n return True\n\n @classmethod\n def set_status(cls, object, status):\n from noc.fm.models.outage import Outage\n from noc.inv.models.discoveryjob import DiscoveryJob\n\n s = cls.objects.filter(object=object.id).first()\n if s:\n if s.status != status:\n s.status = status\n s.save()\n if status:\n # False -> True transition\n DiscoveryJob.reset_deferred(object)\n else:\n # True -> False transition\n DiscoveryJob.set_deferred(object)\n else:\n cls(object=object.id, status=status).save()\n Outage.register_outage(object, not status)\n","sub_path":"sa/models/objectstatus.py","file_name":"objectstatus.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"12818246","text":"from django.test import TestCase\n\n\nclass TestTreatmentViews(TestCase):\n ''' test the treatments view '''\n\n def test_treatments_view(self):\n # direct to the treatments view\n page = self.client.get(\"/home/treatments/\", follow=True)\n # check if it has a status code 200\n self.assertEqual(page.status_code, 200)\n # check that you are directed to the treatments.html page\n self.assertTemplateUsed(page, \"treatments.html\")\n","sub_path":"home/tests_views.py","file_name":"tests_views.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"376780124","text":"polynomial=[-15,9,-20,12,-5,3]#3x 5 − 5x 4 + 12x 3 − 20x 2 + 9x − 15\n#polynomial=[-12,13,-5,3]\ndef nullstelle(p,a=-5,b=5,c=0,delta=5):\n\twhile(abs(f(p,c))>10**(-delta)):\n\t\tc=(a+b)/2\n\t\tif f(p,c)<0.0:\n\t\t\ta=c\n\t\tif f(p,c)>0.0:\n\t\t\tb=c\n\t\telif f(p,c)==0:\n\t\t\treturn c;\n\treturn c;\ndef f(p,s):\n\tres=0\n\tfor i,v in enumerate(p):\n\t\tres+=v*(s**i)\n\treturn res\ndef a(p):\n\tif p<0:\n\t\treturn -p\n\tif p>=0:\n\t\treturn p\nprint(nullstelle(polynomial,-10,11,3,12))\n","sub_path":"Ws1718/Kurse/KuABöhm/Übungen/11/nullstellen.py","file_name":"nullstellen.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"467696319","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'Laurent Huang'\n\n\n'''\nasync web application.\n\n'''\n\n'''\n你提出的问题很好,很多时候混用会造成实际输出的html并非vue能识别的\n\n方法1:尽量用
而不是
{{ abc }}
\n\n方法2:把vue相关代码集中到一块,用raw:\n\n{% raw %}\n
    \n
  • {{ item }}
  • \n
\n{% endraw %}\n'''\n\n\n\nimport logging; logging.basicConfig(level=logging.INFO)\n\nimport asyncio,os,json,time\n\nfrom datetime import datetime\n\nfrom aiohttp import web\n\nfrom jinja2 import Environment,FileSystemLoader\n\nimport orm\n\nfrom coroweb import add_routes, add_static\n\nfrom config import configs\n\nfrom handlers import cookie2user, COOKIE_NAME\n\n\n\ndef init_jinja2(app,**kw):\n\tlogging.info('init jinja2...')\n\toptions = dict(\n\t\tautoescape = kw.get('autoescape',True),\n\t\tblock_start_string = kw.get('block_start_string','{%'),\n\t\tblock_end_string = kw.get('block_end_string','%}'),\n\t\tvariable_start_string = kw.get('variable_start_string','{{'),\n\t\tvariable_end_string = kw.get('variable_end_string','}}'),\n\t\tauto_reload = kw.get('auto_reload',True)\n\t)\n\tpath = kw.get('path',None)\n\tif path is None:\n\t\tpath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'templates')\n\tlogging.info('set jinja2 template path: %s' % path)\n\tenv = Environment(loader=FileSystemLoader(path),**options)\n\tfilters = kw.get('filters',None)\n\tif filters is not None:\n\t\tfor name,f in filters.items():\n\t\t\tenv.filters[name] = f \n\tapp['__templating__'] = env\n\n\n\ndef index(request):\n\treturn web.Response(body='

Awesome

',headers={'content-type':'text/html'})\n\nasync def logger_factory(app,handler):\n\tasync def logger(request):\n\t\tlogging.info('Request: %s %s' % (request.method,request.path))\n\t\t# await asynico.sleep(0.3)\n\t\treturn (await handler(request))\n\treturn logger\n\n\nasync def auth_factory(app,handler):\n\tasync def auth(request):\n\t\tlogging.info('check user: %s %s' % (request.method,request.path))\n\t\trequest.__user__ = None\n\t\tcookie_str = request.cookies.get(COOKIE_NAME)\n\t\tif cookie_str:\n\t\t\tuser = await cookie2user(cookie_str)\n\t\t\tif user:\n\t\t\t\tlogging.info('set current user: %s' % user.email)\n\t\t\t\trequest.__user__ = user\n\t\tif request.path.startswith('/manage/') and (request.__user__ is None or not request.__user__.admin):\n\t\t\treturn web.HTTPFound('/signin')\n\t\treturn (await handler(request))\n\treturn auth\n\n\n# 而response这个middleware把返回值转换为web.Response对象再返回,以保证满足aiohttp的要求:\nasync def response_factory(app,handler):\n\tasync def response(request):\n\t\tlogging.info('Response handler...')\n\t\tr = await handler(request)\n\t\tif isinstance(r,web.StreamResponse):\n\t\t\treturn r \n\t\tif isinstance(r,bytes):\n\t\t\tresp = web.Response(body = r)\n\t\t\tresp.content_type = 'application/octet-stream'\n\t\t\treturn resp\n\t\tif isinstance(r,str):\n\t\t\tif r.startswith('redirect:'):\n\t\t\t\treturn web.HTTPFound(r[9:])\n\t\t\tresp = web.Response(body = r.encode('utf-8'))\n\t\t\tresp.content_type = 'text/html;charset=utf-8'\n\t\t\treturn resp\n\t\tif isinstance(r,dict):\n\t\t\ttemplate = r.get('__template__')\n\t\t\tif template is None:\n\t\t\t\tresp = web.Response(body = json.dumps(r,ensure_ascii = False,default=lambda o:o.__dict__).encode('utf-8'))\n\t\t\t\tresp.content_type = 'application/json;charset=utf-8'\n\t\t\t\treturn resp\n\t\t\telse:\n\t\t\t\t# plus request.__user__ function\n\t\t\t\tr['__user__'] = request.__user__\n\t\t\t\tresp = web.Response(body=app['__templating__'].get_template(template).render(**r).encode('utf-8'))\n\t\t\t\tresp.content_type = 'text/html;charset=utf-8'\n\t\t\t\treturn resp\n\n\t\tif isinstance(r,int) and r>=100 and r<600:\n\t\t\treturn web.Response(r)\n\t\tif isinstance(r,tuple) and len(r) == 2:\n\t\t\tt,m = r \n\t\t\tif isinstance(t,int) and t>=100 and t<600:\n\t\t\t\treturn web.Response(t,str(m))\n\t\t# default\n\t\tresp = web.Response(body=str(r).encode('utf-8'))\n\t\tresp.content_type = 'text/plain;charset=utf-8'\n\t\treturn resp\n\treturn response\n\n\ndef datetime_filter(t):\n\tdelta = int(time.time() - t)\n\tif delta < 60:\n\t\treturn u'1分钟前'\n\tif delta < 3600:\n\t\treturn u'%s分钟前' % (delta // 60)\n\tif delta < 86400:\n\t\treturn u'%s小时前' % (delta // 3600)\n\tif delta < 604800:\n\t\treturn u'%s天前' % (delta // 86400)\n\tdt = datetime.fromtimestamp(t)\n\treturn u'%s年%s月%s日' % (dt.year,dt.month,dt.day)\n\n\nasync def init(loop): \n\tawait orm.create_pool(loop=loop,**configs.db)\n\tapp = web.Application(loop=loop,middlewares=[\n \t\tlogger_factory, auth_factory, response_factory\n\t])\n\tinit_jinja2(app,filters=dict(datetime=datetime_filter))\n\tadd_routes(app,'handlers')\n\tadd_static(app)\n\tsrv = await loop.create_server(app.make_handler(),'127.0.0.1',9000)\n\tlogging.info('server started at http://127.0.0.1:9000...')\n\treturn srv\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(init(loop))\nloop.run_forever()","sub_path":"www/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"78006522","text":"N = int(input(\"Enter a number: \"))\ntekToplam = 0\ntekCarp = 1\nciftKTop = 0\nfor x in range(1, N, 2):\n tekToplam += x\n tekCarp *= x\n ciftKTop += (x**2)\nprint(\"Tek sayıların toplamı:\", tekToplam, \"\\nTek sayıların çarpımı:\", tekCarp,\n \"\\nÇift sayıların karelerinin toplamı:\", ciftKTop)\n\n","sub_path":"code/Problem 47.py","file_name":"Problem 47.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345334625","text":"import itertools\nimport poker\n\nclass Game():\n\tdef __init__(self, numOpponents):\n\t\tself._deck = poker.Deck()\n\t\tself._me = self._drawCards(2) # draw myself 2 cards\n\t\tself._play(numOpponents)\n\n\tdef __init__(self, numOpponents, myHand):\n\t\t''' Force my hand '''\n\t\tself._deck = poker.Deck()\n\t\tself._me = myHand\n\t\tself._deck.remove(myHand[0])\n\t\tself._deck.remove(myHand[1])\n\t\tself._play(numOpponents)\n\n\tdef _play(self, numOpponents):\n\t\t# The order of the dealt cards doesn't matter since it's all random anyway; as is burning.\n\n\t\t# and the opponents\t\t\n\t\tself._opponents = dict()\n\t\tfor x in range(numOpponents):\n\t\t\tself._opponents[x] = self._drawCards(2)\n\n\t\tself._flop = self._drawCards(3)\n\t\tself._turn = self._deck.draw()\n\t\tself._river = self._deck.draw()\t\t\n\n\tdef win(self):\n\t\t''' Did I win? '''\n\t\tmyHand = self._bestHand(self._me)\n\t\treturn all(myHand.beats(self._bestHand(x)) for x in self._opponents.values())\n\n\tdef _drawCards(self, num):\n\t\treturn [self._deck.draw() for i in range(num)]\n\t\t\n\tdef _bestHand(self, cards):\n\t\tallOtherCards = list(self._flop)\n\t\tallOtherCards.append(self._turn)\n\t\tallOtherCards.append(self._river)\n\t\tbestHand = None\n\t\tfor otherCards in itertools.combinations(allOtherCards, 3):\n\t\t\tpotentialHand = poker.Hand(itertools.chain(cards, otherCards))\n\t\t\tif bestHand is None or potentialHand.beats(bestHand):\n\t\t\t\tbestHand = potentialHand\n\t\treturn bestHand\n\n\nmaxIters = 1000\n\nc1 = poker.Card(0, 0)\nc2 = poker.Card(1, 0)\n\nc3 = poker.Card(0, 11)\nc4 = poker.Card(0, 12)\n\nprint(\"{0},{1},{2}\".format(\"opponents\", \"22\", \"AK\"))\nfor opponents in xrange(1, 10):\n\tresult22 = 0\n\tresultAK = 0\n\tfor x in xrange(maxIters):\n\t\tgame = Game(opponents, [c1, c2])\n\t\tif game.win(): result22 += 1\n\n\tfor x in xrange(maxIters):\n\t\tgame = Game(opponents, [c3, c4])\n\t\tif game.win(): resultAK += 1\n\n\tprint(\"{0},{1:.1f}, {2:.1f}\".format(opponents, float(result22)/maxIters, float(resultAK)/maxIters))\n\n\n\n\n\n","sub_path":"texasholdem.py","file_name":"texasholdem.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"139440903","text":"from redis_conn import redis_conn_util\nif __name__ == '__main__':\n coon = redis_conn_util.Redis_Conn.get_windows_coon(3)\n # lrange(name, start, end) \t返回key为name的list中start至end之间的元素\n users = coon.lrange(\"users\",0,-1)\n for user in users:\n print(bytes(user).decode(\"utf-8\"))\n # lindex(name, index) 返回key为name的list中index位置的元素\n user = coon.lindex(\"users\", 1)\n print(\"users[1] = %s\" % bytes(user).decode(\"utf-8\"))\n # llen(name) 返回key为name的list的长度\n user_count = coon.llen(\"users\")\n print(\"users中有%d个元素\" % user_count)","sub_path":"redis_admin/oplist/list_lrange_index_llen.py","file_name":"list_lrange_index_llen.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"492739666","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 16 21:58:49 2018\n\n@author: Chandrika\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 5 21:22:37 2018\n\n@author: Chandrika\n\"\"\"\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom keras.preprocessing.image import ImageDataGenerator\nimport time\nfrom keras.callbacks import TensorBoard\n\n#i = 64\n\ndense_layers = [1, 2]\nfilter_size = [32, 32, 64, 64, 64, 128, 128]\nconv_layers = [5, 6, 7]\nfor dense_layer in dense_layers:\n for conv_layer in conv_layers:\n train_data = ImageDataGenerator(rescale=1./255,shear_range=0.2,zoom_range=0.2,horizontal_flip = False)\n test_data = ImageDataGenerator(rescale=1./255)\n\n training = train_data.flow_from_directory('TrainAll',target_size=(64,64), batch_size=32,class_mode='categorical')\n test = test_data.flow_from_directory('TestAll',target_size=(64,64), batch_size=32,class_mode='categorical')\n\n NAME = \"Bangla_ALL-{}-conv-{}-dense-{}\".format(conv_layer,dense_layer,int(time.time()))\n print(NAME)\n model = Sequential()\n tensorboard = TensorBoard(log_dir='logs/{}'.format(NAME), histogram_freq=0, write_images=True, write_graph=True, update_freq='epoch')\n model.add(Conv2D(32,(3,3),input_shape=(64,64,3),padding=\"same\",activation=\"relu\"))\n model.add(Dropout(0.25))\n model.add(MaxPooling2D(pool_size=(2,2),padding=\"same\"))\n \n for l in range(conv_layer-1):\n model.add(Conv2D(filter_size[l+1],(3,3),padding=\"same\",activation=\"relu\"))\n model.add(Dropout(0.3))\n model.add(MaxPooling2D(pool_size=(2,2),padding=\"same\"))\n \n model.add(Flatten())\n \n for k in range(dense_layer):\n model.add(Dense(units=filter_size[k+5],activation=\"relu\"))\n model.add(Dropout(0.1))\n model.add(Dense(units=231,activation=\"softmax\"))\n \n model.compile(optimizer=\"adam\", loss = \"categorical_crossentropy\", metrics= [\"accuracy\"])\n \n model.fit_generator(training, epochs=40, validation_data=test, callbacks=[tensorboard])\n# if i==256:\n# i=64\n# else:\n# i = i*2\n \n","sub_path":"cnnAllClasses.py","file_name":"cnnAllClasses.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"213111708","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'Jack River'\n\nimport json\nimport datetime\nimport hashlib\nfrom fabric.api import local, lcd\nfrom django.conf import settings\nfrom django.db import models\nfrom scrapy.utils.serialize import ScrapyJSONEncoder\nfrom model_utils import Choices\n\nfrom apscheduler.scheduler import Scheduler\n\nglobal_schedulers = {}\n\n\nclass Application(models.Model):\n \"\"\" application model\n \"\"\"\n name = models.CharField(max_length=255, unique=True, verbose_name=u'Name')\n display_name = models.CharField(max_length=255, verbose_name=u'Display Name')\n\n class Meta(object):\n app_label = u'barrow'\n verbose_name = u'Application'\n verbose_name_plural = u'Application'\n\n def __unicode__(self):\n return self.display_name\n\n\ndef run_spider_task(spider):\n SpiderTask.objects.create_and_run(spider)\n\n\nclass Spider(models.Model):\n \"\"\" spider model\n \"\"\"\n application = models.ForeignKey(Application, verbose_name=u'Application')\n name = models.CharField(max_length=255, verbose_name=u'Spider Name', default=u'Default Spider')\n config = models.TextField(verbose_name=u'Spider Config')\n\n class Meta(object):\n app_label = u'barrow'\n verbose_name = u'Spider'\n verbose_name_plural = u'Spider'\n\n def __unicode__(self):\n return self.name\n\n\nclass SpiderTaskManager(models.Manager):\n \"\"\" spider task model manager\n \"\"\"\n\n def create_and_run(self, spider):\n task = self.create(spider=spider)\n task.run()\n\n\nclass SpiderTask(models.Model):\n \"\"\" spider task model\n \"\"\"\n objects = SpiderTaskManager()\n\n SPIDER_TASK_STATE = Choices((0, 'initial', u'Initial'),\n (1, 'running', u'Running'),\n (2, 'finished', u'Finished'),\n (3, 'error', u'Error'))\n\n spider = models.ForeignKey(Spider, verbose_name=u'Spider')\n start_time = models.DateTimeField(auto_now_add=True, verbose_name=u'Start Time')\n end_time = models.DateTimeField(default=None, null=True, blank=True, verbose_name=u'End Time')\n state = models.IntegerField(choices=SPIDER_TASK_STATE, default=SPIDER_TASK_STATE.initial, verbose_name=u'State')\n\n def run(self):\n \"\"\" run task\n \"\"\"\n # change to running state\n self.state = self.SPIDER_TASK_STATE.running\n self.save()\n\n # run scrap from management command\n with lcd(settings.BASE_DIR):\n local('%s manage.py run_scrap --task_id=%d' % (settings.PYTHON_BIN, self.pk))\n\n # change to finish state\n self.state = self.SPIDER_TASK_STATE.finished\n self.end_time = datetime.datetime.now()\n self.save()\n\n class Meta(object):\n app_label = u'barrow'\n verbose_name = u'Spider Task'\n verbose_name_plural = u'Spider Task'\n\n\ndef add_spider_to_scheduler(spider):\n # manage scheduler\n key = spider.pk\n if key in global_schedulers.keys():\n scheduler = global_schedulers.pop(key)\n scheduler.shutdown()\n\n scheduler = Scheduler()\n scheduler.start()\n cron_config = json.loads(spider.config)['cron']\n minute, hour, day, month, day_of_week = cron_config.split(' ')\n scheduler.add_cron_job(run_spider_task,\n minute=minute,\n hour=hour,\n day=day,\n month=month,\n day_of_week=day_of_week,\n kwargs={'spider': spider})\n global_schedulers[spider.pk] = scheduler\n\n\nclass SpiderResultManager(models.Manager):\n \"\"\" spider result model manager\n \"\"\"\n\n def add_result(self, spider_task, item, unique=False, unique_keys=None):\n sha = hashlib.sha256()\n json_item = ScrapyJSONEncoder().encode(item)\n if unique:\n for key in unique_keys:\n sha.update(item[key].encode('utf8'))\n hash_value = sha.hexdigest()\n\n if self.filter(hash_value=hash_value).exists():\n return None\n else:\n hash_value = sha.update(json_item).hexdigest()\n\n return self.create(spider_task=spider_task,\n hash_value=hash_value,\n content=json_item)\n\n\nclass SpiderResult(models.Model):\n \"\"\" spider result model\n \"\"\"\n objects = SpiderResultManager()\n\n spider_task = models.ForeignKey(SpiderTask, verbose_name=u'Spider Task')\n hash_value = models.CharField(max_length=256, verbose_name=u'Hash')\n content = models.TextField(verbose_name=u'Result Content')\n\n class Meta(object):\n app_label = u'barrow'\n verbose_name = u'Spider Result'\n verbose_name_plural = u'Spider Result'\n\n def __unicode__(self):\n return self.hash_value","sub_path":"barrow/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"69600227","text":"from __future__ import annotations\n\nimport importlib\nimport logging\nimport re\nfrom argparse import ArgumentParser\nfrom pathlib import Path\n\nfrom pybind11_stubgen.parser.interface import IParser\nfrom pybind11_stubgen.parser.mixins.error_handlers import (\n IgnoreAllErrors,\n IgnoreInvalidExpressionErrors,\n IgnoreInvalidIdentifierErrors,\n IgnoreUnresolvedNameErrors,\n LogErrors,\n SuggestCxxSignatureFix,\n TerminateOnFatalErrors,\n)\nfrom pybind11_stubgen.parser.mixins.filter import (\n FilterClassMembers,\n FilterInvalidIdentifiers,\n FilterPybindInternals,\n)\nfrom pybind11_stubgen.parser.mixins.fix import (\n FixBuiltinTypes,\n FixCurrentModulePrefixInTypeNames,\n FixMissing__all__Attribute,\n FixMissing__future__AnnotationsImport,\n FixMissingEnumMembersAnnotation,\n FixMissingFixedSizeImport,\n FixMissingImports,\n FixMissingNoneHashFieldAnnotation,\n FixNumpyArrayDimAnnotation,\n FixNumpyArrayFlags,\n FixNumpyArrayRemoveParameters,\n FixPEP585CollectionNames,\n FixPybind11EnumStrDoc,\n FixRedundantBuiltinsAnnotation,\n FixRedundantMethodsFromBuiltinObject,\n FixTypingExtTypeNames,\n FixTypingTypeNames,\n FixValueReprRandomAddress,\n RemoveSelfAnnotation,\n ReplaceReadWritePropertyWithField,\n)\nfrom pybind11_stubgen.parser.mixins.parse import (\n BaseParser,\n ExtractSignaturesFromPybind11Docstrings,\n ParserDispatchMixin,\n)\nfrom pybind11_stubgen.printer import Printer\nfrom pybind11_stubgen.structs import QualifiedName\nfrom pybind11_stubgen.writer import Writer\n\n\ndef arg_parser() -> ArgumentParser:\n def regex(pattern_str: str) -> re.Pattern:\n try:\n return re.compile(pattern_str)\n except re.error as e:\n raise ValueError(f\"Invalid REGEX pattern: {e}\")\n\n parser = ArgumentParser(\n prog=\"pybind11-stubgen\", description=\"Generates stubs for specified modules\"\n )\n parser.add_argument(\n \"-o\",\n \"--output-dir\",\n help=\"The root directory for output stubs\",\n default=\"./stubs\",\n )\n parser.add_argument(\n \"--root-suffix\",\n type=str,\n default=None,\n dest=\"root_suffix\",\n help=\"Top-level module directory suffix\",\n )\n\n parser.add_argument(\n \"--ignore-invalid-expressions\",\n metavar=\"REGEX\",\n default=None,\n type=regex,\n help=\"Ignore invalid expressions matching REGEX\",\n )\n parser.add_argument(\n \"--ignore-invalid-identifiers\",\n metavar=\"REGEX\",\n default=None,\n type=regex,\n help=\"Ignore invalid identifiers matching REGEX\",\n )\n\n parser.add_argument(\n \"--ignore-unresolved-names\",\n metavar=\"REGEX\",\n default=None,\n type=regex,\n help=\"Ignore unresolved names matching REGEX\",\n )\n\n parser.add_argument(\n \"--ignore-all-errors\",\n default=False,\n action=\"store_true\",\n help=\"Ignore all errors during module parsing\",\n )\n\n numpy_array_fix = parser.add_mutually_exclusive_group()\n numpy_array_fix.add_argument(\n \"--numpy-array-wrap-with-annotated\",\n default=False,\n action=\"store_true\",\n help=\"Replace numpy/scipy arrays of \"\n \"'ARRAY_T[TYPE, [*DIMS], *FLAGS]' format with \"\n \"'Annotated[ARRAY_T, TYPE, FixedSize|DynamicSize(*DIMS), *FLAGS]'\",\n )\n\n numpy_array_fix.add_argument(\n \"--numpy-array-remove-parameters\",\n default=False,\n action=\"store_true\",\n help=\"Replace 'numpy.ndarray[...]' with 'numpy.ndarray'\",\n )\n\n parser.add_argument(\n \"--print-invalid-expressions-as-is\",\n default=False,\n action=\"store_true\",\n help=\"Suppress invalid expression replacement with '...'\",\n )\n\n parser.add_argument(\n \"--exit-code\",\n action=\"store_true\",\n dest=\"exit_code\",\n help=\"On error exits with 1 and skips stub generation\",\n )\n\n parser.add_argument(\n \"--dry-run\",\n action=\"store_true\",\n dest=\"dry_run\",\n help=\"Don't write stubs. Parses module and report errors\",\n )\n\n parser.add_argument(\n \"module_name\",\n metavar=\"MODULE_NAME\",\n type=str,\n help=\"module name\",\n )\n\n return parser\n\n\ndef stub_parser_from_args(args) -> IParser:\n error_handlers_top: list[type] = [\n *([IgnoreAllErrors] if args.ignore_all_errors else []),\n *([IgnoreInvalidIdentifierErrors] if args.ignore_invalid_identifiers else []),\n *([IgnoreInvalidExpressionErrors] if args.ignore_invalid_expressions else []),\n *([IgnoreUnresolvedNameErrors] if args.ignore_unresolved_names else []),\n ]\n error_handlers_bottom: list[type] = [\n LogErrors,\n SuggestCxxSignatureFix,\n *([TerminateOnFatalErrors] if args.exit_code else []),\n ]\n\n numpy_fixes: list[type] = [\n *([FixNumpyArrayDimAnnotation] if args.numpy_array_wrap_with_annotated else []),\n *(\n [FixNumpyArrayRemoveParameters]\n if args.numpy_array_remove_parameters\n else []\n ),\n ]\n\n class Parser(\n *error_handlers_top, # type: ignore[misc]\n FixMissing__future__AnnotationsImport,\n FixMissing__all__Attribute,\n FixMissingNoneHashFieldAnnotation,\n FixMissingImports,\n FixPEP585CollectionNames,\n FixTypingTypeNames,\n FixTypingExtTypeNames,\n FixMissingFixedSizeImport,\n FixMissingEnumMembersAnnotation,\n *numpy_fixes, # type: ignore[misc]\n FixNumpyArrayFlags,\n FixCurrentModulePrefixInTypeNames,\n FixBuiltinTypes,\n FilterClassMembers,\n ReplaceReadWritePropertyWithField,\n FilterInvalidIdentifiers,\n FixValueReprRandomAddress,\n FixRedundantBuiltinsAnnotation,\n FilterPybindInternals,\n FixRedundantMethodsFromBuiltinObject,\n RemoveSelfAnnotation,\n FixPybind11EnumStrDoc,\n ExtractSignaturesFromPybind11Docstrings,\n ParserDispatchMixin,\n BaseParser,\n *error_handlers_bottom, # type: ignore[misc]\n ):\n pass\n\n parser = Parser()\n\n if args.ignore_invalid_identifiers is not None:\n parser.set_ignored_invalid_identifiers(args.ignore_invalid_identifiers)\n if args.ignore_invalid_expressions is not None:\n parser.set_ignored_invalid_expressions(args.ignore_invalid_expressions)\n if args.ignore_unresolved_names is not None:\n parser.set_ignored_unresolved_names(args.ignore_unresolved_names)\n return parser\n\n\ndef main():\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(name)s - [%(levelname)7s] %(message)s\",\n )\n args = arg_parser().parse_args()\n\n parser = stub_parser_from_args(args)\n printer = Printer(invalid_expr_as_ellipses=not args.print_invalid_expressions_as_is)\n\n out_dir = Path(args.output_dir)\n out_dir.mkdir(exist_ok=True)\n\n if args.root_suffix is None:\n sub_dir = None\n else:\n sub_dir = Path(f\"{args.module_name}{args.root_suffix}\")\n run(\n parser,\n printer,\n args.module_name,\n out_dir,\n sub_dir=sub_dir,\n dry_run=args.dry_run,\n )\n\n\ndef run(\n parser: IParser,\n printer: Printer,\n module_name: str,\n out_dir: Path,\n sub_dir: Path | None,\n dry_run: bool,\n):\n module = parser.handle_module(\n QualifiedName.from_str(module_name), importlib.import_module(module_name)\n )\n parser.finalize()\n\n if module is None:\n raise RuntimeError(f\"Can't parse {module_name}\")\n\n if dry_run:\n return\n\n writer = Writer()\n\n out_dir.mkdir(exist_ok=True)\n writer.write_module(module, printer, to=out_dir, sub_dir=sub_dir)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pybind11_stubgen/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"29728324","text":"# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th)\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nfrom odoo import fields, models\n\n\nclass ProjectProject(models.Model):\n _inherit = \"project.project\"\n\n date_sale_order = fields.Datetime(\n related=\"sale_order_id.date_order\",\n string=\"Sale Order Date/Project Date\",\n store=True,\n )\n sale_order_type_id = fields.Many2one(\n comodel_name=\"sale.order.type\",\n related=\"sale_order_id.type_id\",\n store=True,\n )\n sale_order_subject = fields.Char(\n related=\"sale_order_id.subject\",\n string=\"Project Description\",\n store=True,\n )\n","sub_path":"odoo/custom/src/private/faf_sale_project/models/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"157109876","text":"import os\nimport aiohttp\nimport asyncio\nimport asyncpg\n\nfrom config import POSTGRES\n\n\nclass Client:\n def __init__(self):\n self.loop = asyncio.get_event_loop()\n asyncio.set_event_loop(self.loop)\n\n self.scripts = [\n x[:-4] for x in os.listdir(\"./data/scripts\") if x.endswith(\".sql\")\n ]\n self.session = aiohttp.ClientSession(loop=self.loop)\n self.cxn = self.loop.run_until_complete(\n asyncpg.create_pool(POSTGRES.uri)\n )\n\n self.loop.run_until_complete(self.scriptexec())\n\n async def scriptexec(self):\n # We execute the SQL scripts to make sure we have all our tables.\n for script in self.scripts:\n with open(f\"./data/scripts/{script}.sql\", \"r\", encoding=\"utf-8\") as script:\n await self.cxn.execute(script.read())\n\n ##############################\n ## Aiohttp Helper Functions ##\n ##############################\n\n async def query(self, url, method=\"get\", res_method=\"json\", *args, **kwargs):\n async with getattr(self.session, method.lower())(url, *args, **kwargs) as res:\n if res_method:\n return await getattr(res, res_method)()\n\n async def get(self, url, *args, **kwargs):\n return await self.query(url, \"get\", *args, **kwargs)\n\n async def post(self, url, *args, **kwargs):\n return await self.query(url, \"post\", *args, **kwargs)\n\n async def put(self, url, *args, **kwargs):\n return await self.query(url, \"put\", *args, **kwargs)\n\n async def patch(self, url, *args, **kwargs):\n return await self.query(url, \"patch\", *args, **kwargs)\n\n\n\n\nclient = Client()\n","sub_path":"web/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"225434555","text":"import plotly.graph_objects as go\nfrom plotly.io._html import to_html\nfrom django.db.models import Count, Avg, Q\nfrom . import models\n\n#Code for barchart from plot_aggregate\ndef barchart_html(agg, inv, model, meta):\n Operation = None\n title = None\n type = None\n metaType = None\n\n investigations = models.Investigation.objects.filter(pk__in=inv)\n inv_titles = [i.name for i in investigations]\n #Assign aggregate operation\n if agg == '1':\n Operation = Count\n title = \"Count\"\n elif agg == '2':\n Operation = Avg\n title = \"Average\"\n #Assign Model type\n if model == '1':\n type = models.Sample\n model_choice = \"Sample\"\n metaType = models.SampleMetadata\n elif model == '2':\n type = models.BiologicalReplicate\n model_choice = \"Biological Replicate\"\n metaType = models.BiologicalReplicateMetadata\n #using this conditional will allow later additions to this method.\n if metaType:\n #create qs for each selected investigation\n sets = []\n for inv in investigations:\n sets.append({'title': inv.name,\n 'data': metaType.objects.filter(sample__in=models.Sample.objects.filter(investigation=inv)).filter(key=meta).values('value').order_by(\n 'value').annotate(agg=Operation('value'))})\n\n #create values for plotly\n graph_values = []\n for qs in sets:\n graph_values.append(\n {'x': [s['value'] for s in qs['data']],\n 'y': [s['agg'] for s in qs['data']],\n 'title': qs['title']}\n )\n\n data = []\n for bar in graph_values:\n data.append(go.Bar(\n x=bar['x'],\n y=bar['y'],\n text=bar['y'],\n textposition = 'auto',\n name=bar['title'],\n ))\n\n layout = go.Layout(title=(title + \" by \" + meta),\n xaxis={'title': meta},\n yaxis={'title': title})\n\n figure = go.Figure(data=data, layout=layout)\n return to_html(figure, full_html=False), {'agg':title,\n 'inv': inv_titles,\n 'type':model_choice,\n 'meta':meta}\n return None\n\n#Code for trendline/scatterplot\ndef trendchart_html(invs, x_val, x_val_category, y_val, y_val_category, operation):\n #To save code, use a dict that maps numerical field vals to django model\n cat_map = {'1': (models.Sample, models.SampleMetadata, 'sample__in', \"Sample\"),\n '2': (models.BiologicalReplicate, models.BiologicalReplicateMetadata, 'biological_replicate__in', \"Biological Replicate\"),\n }\n op_map = {'1': 'markers', '2': 'lines+markers'}\n\n x = None\n y = None\n xqs = None\n yqs = None\n\n x_type, x_subtype, x_search, x_cat = cat_map[x_val_category]\n y_type, y_subtype, y_search, y_cat = cat_map[y_val_category]\n\n #For now,there are no cases that don't have subtypes. Later, however, we might\n #expect those cases and will make the code execute condiitionally.\n\n\n #TODO: abstract out the terms'key' and 'value' from this query.\n if x_type is models.Sample:\n xqs = x_subtype.objects.filter(**{x_search: x_type.objects.filter(\n investigation__in=invs)}).filter(\n key=x_val).values('value').order_by('value')\n\n elif x_type is models.BiologicalReplicate:\n xqs = x_subtype.objects.filter(**{x_search: x_type.objects.filter(\n sample__in=models.Sample.objects.filter(\n investigation__in=invs))}).filter(\n key=x_val).values('value').order_by('value')\n\n if y_type is models.Sample:\n yqs = y_subtype.objects.filter(**{y_search: y_type.objects.filter(\n investigation__in=invs)}).filter(\n key=y_val).values('value').order_by('value')\n\n elif y_type is models.BiologicalReplicate:\n yqs = y_subtype.objects.filter(**{y_search: y_type.objects.filter(\n sample__in=models.Sample.objects.filter(\n investigation__in=invs))}).filter(\n key=y_val).values('value').order_by('value')\n\n x = [s['value'] for s in xqs]\n y = [s['value'] for s in yqs]\n\n fig = go.Figure()\n fig.add_trace(go.Scatter(x=x, y=y,\n mode=op_map[operation],\n marker_color='rgba(152, 0, 0,0.9)'))\n layout = go.Layout(title=x_val + \" vs \" + y_val,\n xaxis={'title':x_val},\n yaxis={'title':y_val})\n fig.layout = layout\n return to_html(fig, full_html=False), {'style': op_map[operation],\n 'inv': [i.name for i in models.Investigation.objects.filter(pk__in=invs)],\n 'x_cat': x_cat,\n 'x_val': x_val,\n 'y_cat': y_cat,\n 'y_val': y_val}\n","sub_path":"db/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"104159526","text":"from bs4 import BeautifulSoup\nimport os,sys\nimport urllib.request, urllib.parse, http.cookiejar\nimport requests\n'''\n著作权归作者所有。\n商业转载请联系作者获得授权,非商业转载请注明出处。\n作者:深海鱼\n链接:https://www.zhihu.com/question/37469400/answer/72120725\n来源:知乎\n\nimport urllib.request\nurl = r'http://www.zhihu.com/question/37469400'\nres = urllib.request.urlopen(url)\ncontent_type = res.info().get('Content-Type')\nencoding = content_type.strip().split('=')[1]\nhtml = res.read().decode(encoding)\n这样就可以了。如果使用第三方库requests则非常简单,上面的代码可以缩减到三行:\nimport requests\nurl = r'http://www.zhihu.com/question/37469400'\nhtml = requests.get(url).text\n'''\ndef getHtml(url):\n \"\"\"\n 伪装头部并得到网页内容\n\n cj = http.cookiejar.CookieJar()\n opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))\n opener.addheaders = [('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36'),\n ('Cookie', '4564564564564564565646540')]\n\n urllib.request.install_opener(opener) #安装为默认浏览器,使之后的 urlopen方法可直接调用\n \n html_bytes = urllib.request.urlopen(url, timeout = 0) #urlopen\n content_type = html_bytes.info().get('Content-Type')\n encoding = content_type.strip().split('=')[1]\n html_string = html_bytes.read().decode(encoding)\n return html_string\n \"\"\"\n \n html_string = requests.get(url).text\n return html_string\n \"\"\"\n urlop = urllib.request.urlopen(url) \n if 'html' not in urlop.getheader('Content-Type'):\n pass\n else:\n data = urlop.read().decode('utf-8')\n\n return data \n \n # 避免程序异常中止, 用try..catch处理异常\n try:\n data = urlop.read().decode('utf-8')\n except:\n pass #continue\n return data \n \n try:\n html_bytes = urllib.request.urlopen(url, timeout = 0).read()\n html_string = html_bytes.decode('utf-8')\n except Exception as e:\n html_string = \n print(e)\n return html_string\n \"\"\" \n\n \n\n \ndef qccr(url_content):\n \"\"\"\n 输入网页内容进行轮胎爬取\n 返回轮胎信息元组\n \"\"\"\n qccrs = []\n soup1 = BeautifulSoup(url_content, 'html.parser') # 开始解析 \n # qccrtable = soup.select('div.indent table div a')\n qccrtable = soup1.find(\"div\",attrs={\"class\": \"thislist\"}) # 找到所有轮胎所在标记\n soup2 = BeautifulSoup(str(qccrtable), 'html.parser')\n qccrtable1 = soup2.find_all(\"li\")\n \n\n # 循环遍历轮胎列表\n for qccr in qccrtable1:\n simpleqccr = qccr\n\n subsoup = BeautifulSoup(str(simpleqccr), 'html.parser')\n \n wangzhi = subsoup.find('a')['href']\n xinghao = subsoup.find('p',attrs={\"class\": \"name\"}).string\n xiaoliang = subsoup.find('span',attrs={\"class\": \"saleNum\"}).string\n pr = subsoup.find('p',attrs={\"class\": \"price\"}).span #返回的是一个列表\n price = list(pr.strings)[1]\n '''\n if subsoup.find('p',attrs={\"class\": \"price\"}).span is None:\n price = '0'\n else:\n pr = subsoup.find('p',attrs={\"class\": \"price\"}).span\n price = list(pr.strings)[1]\n '''\n \n\n qccrs.append((wangzhi,xinghao, xiaoliang,str(price)))\n # 返回轮胎列表\n return qccrs\n\ndef saveFile(qccrslist):\n '''\n 保存文件\n '''\n save_path = os.path.join(sys.path[0], \"qccr.csv\")\n f_obj = open(save_path, 'w',encoding='utf-8') # w 表示打开方式\n \n title = ['网址','轮胎名称', '销量','价格']\n html = '\\t'.join(title)+ '\\n'\n for page in qccrslist:\n for luntai in page:\n if luntai is not None:\n html += '\\t'.join(luntai) + '\\n'\n #html += luntai + '\\n'\n else: pass\n \n f_obj.write(html)\n f_obj.close()\n\n\n\n# 爬取得网页\nurllist = [] # 要爬取的网页\nurl = 'http://www.qccr.com/list_lt/sub_c' # 基础网址\npage = 22 # 总共爬到多少页\nfor i in range(1,page): #第1页 第8页有问题 原因不明\n urllist.append(url+str(i)+'_s25_o0_d1')\n\n\n# 一张张爬取所有轮胎列表\nqccrslist = []\nfor url in urllist:\n print(url)\n html_doc = getHtml(url) #返回一个 'utf-8' 网页文本文档\n qccrslist.append(qccr(html_doc))\n \nsaveFile(qccrslist)\n# 生成的csv默认为ASCII编码,用记事本打开另存为ASCII编码,然后打开再转Excel等\n","sub_path":"qccr_luntai.py","file_name":"qccr_luntai.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"434167695","text":"import re\nimport copy\n# structure of data\n# factor: [[a, e], [b, e], [c, e], [d, e]]\n# init_list like:['-334x^6342', '+', '2x^3', '+', '3']\n# position 0 is coefficient, position 1 is exponential\n# class instance: factor, init_list, result_str, init_polynoimal\nclass Polynomial(object):\n def __init__(self, polynomial = None):\n self.init_polynomial = polynomial\n self.factor = []\n self.init_list = []\n self.result_str = ''\n if polynomial != None:\n self.init_list = re.split(' ', self.init_polynomial)\n self.get_factor()\n self.get_result_str()\n def get_factor(self):\n if self.init_list == []:\n return self.factor\n factor_1 = 0\n factor_2 = 0\n i = -1\n for item in self.init_list:\n new_item_2 = []\n i += 1\n if item in ['+', '-']:\n continue\n else:\n if 'x^' in item and item[0] != 'x':\n new_item_1 = re.split('[x^]', item)\n for element in new_item_1:\n if element != '':\n new_item_2.append(element)\n if new_item_2[0] == '-':\n factor_1 = -1\n factor_2 = int(new_item_2[1])\n else:\n if self.init_list[i-1] == '-':\n factor_1 = -int(new_item_2[0])\n else:\n factor_1 = int(new_item_2[0])\n factor_2 = int(new_item_2[1])\n elif 'x^' in item and item[0] == 'x':\n new_item_1 = re.split('[x^]', item)\n for element in new_item_1:\n if element != '':\n new_item_2.append(element)\n if self.init_list[i-1] == '-':\n factor_1 = -1\n else:\n factor_1 = 1\n factor_2 = int(new_item_2[0]) \n elif 'x' in item and '^' not in item:\n new_item_1 = re.split('x', item)\n for element in new_item_1:\n if element != '':\n new_item_2.append(element)\n if len(new_item_2) == 0:\n if self.init_list[i-1] == '-':\n factor_1 = -1\n else:\n factor_1 = 1\n factor_2 = 1\n if len(new_item_2) == 1:\n if self.init_list[i-1] == '-':\n factor_1 = -int(new_item_2[0])\n else:\n factor_1 = int(new_item_2[0])\n factor_2 = 1\n else:\n if self.init_list[i-1] == '-':\n factor_1 = -int(item)\n else:\n factor_1 = int(item)\n factor_2 = 0 \n self.factor.append([factor_1, factor_2])\n return self.factor\n # be careful about the first item, you need to handle it special\n # first code the normal item and second code the first item\n def get_result_str(self):\n pass\n if self.factor == []:\n return self.result_str\n i = 0\n for factor in self.factor:\n i += 1\n if i == 1:\n if factor[0] in [-1, 1] and factor[1] != 0:\n if factor[0] == -1 and factor[1] != 1:\n self.result_str +='-' + 'x^' + str(factor[1])\n elif factor[0] == -1 and factor[1] == 1:\n self.result_str +='-' + 'x'\n elif factor[0] == 1 and factor[1] != 1:\n self.result_str +='x^' + str(factor[1])\n else:\n self.result_str +='x'\n elif factor[0] in [-1, 1] and factor[1] == 0:\n if factor[0] == -1:\n self.result_str += '-' + '1'\n else:\n self.result_str += '1'\n elif factor[0] not in [-1, 1] and factor[1] != 0:\n if factor[1] != 1:\n self.result_str += str(factor[0]) + 'x^' + str(factor[1])\n else:\n self.result_str += str(factor[0]) + 'x'\n else:\n if factor[0] > 0:\n self.result_str += str(factor[0])\n else:\n self.result_str += '-' + str(factor[0])\n else:\n if factor[0] in [-1, 1] and factor[1] != 0:\n if factor[0] == -1 and factor[1] != 1:\n self.result_str +=' - ' + 'x^' + str(factor[1])\n elif factor[0] == -1 and factor[1] == 1:\n self.result_str +=' - ' + 'x'\n elif factor[0] == 1 and factor[1] != 1:\n self.result_str +=' + ' + 'x^' + str(factor[1])\n else:\n self.result_str +=' + ' + 'x'\n elif factor[0] in [-1, 1] and factor[1] == 0:\n if factor[0] == -1:\n self.result_str += ' - ' + '1'\n else:\n self.result_str += ' + ' + '1'\n elif factor[0] not in [-1, 1] and factor[1] != 0:\n if factor[0] > 0 and factor[1] != 1:\n self.result_str += ' + ' + str(factor[0]) + 'x^' + str(factor[1])\n elif factor[0] > 0 and factor[1] == 1:\n self.result_str += ' + ' + str(factor[0]) + 'x'\n elif factor[0] < 0 and factor[1] != 1:\n self.result_str += ' - ' + str(factor[0]) + 'x^' + str(factor[1])\n else:\n self.result_str += ' - ' + str(factor[0]) + 'x'\n else:\n if factor[0] > 0:\n self.result_str += ' + ' + str(factor[0])\n else:\n self.result_str += ' - ' + str(factor[0])\n # for __add__ we need to create a new object to receive the add result\n # and we need to use add and merge\n # for __iadd__ we need to update the left object\n def __add__(self, other):\n new_object = Polynomial()\n i = 0\n j = 0\n while i < len(self.factor) and j < len(other.factor):\n if self.factor[i][1] > other.factor[j][1]:\n new_object.factor.append(self.factor[i])\n i += 1\n if i == len(self.factor):\n break\n elif self.factor[i][1] < other.factor[j][1]:\n new_object.factor.append(other.factor[j])\n j += 1\n if j == len(other.factor):\n break\n else:\n factor_1 = self.factor[i][0] + other.factor[j][0]\n if factor_1 != 0:\n new_object.factor.append([factor_1, self.factor[i][1]])\n i += 1\n j += 1\n if i == len(self.factor) or j == len(self.factor):\n break\n if i == len(self.factor):\n new_object.factor += other.factor[j:]\n if j == len(other.factor):\n new_object.factor += self.factor[i:]\n new_object.get_result_str()\n return new_object \n def __str__(self):\n if self.result_str != '':\n return self.result_str\n else:\n return '0'\np = Polynomial('-3')\nprint(p+Polynomial('-x^234 - x - 1'))\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"9021/quiz/quiz_8.py","file_name":"quiz_8.py","file_ext":"py","file_size_in_byte":7813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"36998077","text":"import numpy as np \n# 데이터\nx = np.array([range(1, 101), range(101, 201), range(301, 401)])\ny = np.array([range(101, 201)])\nprint(x.shape) #(3, 100)\nprint(y.shape) #(1, 100)\n\nx = np.transpose(x)\ny = np.transpose(y)\nprint(x.shape) #(100, 3) input\nprint(y.shape) #(100, 1) output\n\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.6, random_state=66, shuffle = False) # x, y -> (train(60%), test(40%))\nx_val, x_test, y_val, y_test = train_test_split(x_test, y_test, test_size=0.5, random_state=66, shuffle = False) # test(40%) -> (val(50%), test(50%))\n\n# 모델구성\nfrom keras.models import load_model, Model\nfrom keras.layers import Dense, Input\n\nmodel = load_model('./save/savetest01.h5')\n\noutput1 = model.output\ndense1 = Dense(10, name='dense_a')(output1)\ndense1 = Dense(10, name='dense_b')(dense1)\noutput2 = Dense(1, name='dense_c')(dense1)\nmodel = Model(inputs = model.input, outputs=output2)\n\n# model.add(Dense(10, name='dense_a')(output1))\n# model.add(Dense(1, name='dense_c')(dense1))\n\nmodel.summary\n\n# 훈련\nmodel.compile(loss='mse', optimizer='adam', metrics=['mse']) # mse, mae 사용\n\nfrom keras.callbacks import EarlyStopping, TensorBoard\ntb_hist = TensorBoard(log_dir='./graph', histogram_freq=0, write_graph=True, write_images=True)\n\nearly_stopping = EarlyStopping(monitor = 'loss', patience = 40, mode = 'min') # monitor=loss(mode=auto/min), monitor=accuracy(mode=max)\nmodel.fit(x_train, y_train, epochs=100, batch_size = 1, validation_split = 0, validation_data = (x_val, y_val), callbacks=[early_stopping, tb_hist]) \n\n# 평가예측 #evaluate 반환값 2개 loss, mse 각 1개씩\nloss, mse = model.evaluate(x_test, y_test, batch_size = 1)\nprint('mse:', mse)\n\n# # 예측\nx_pred = np.array([[200, 201, 202], [203, 204, 205], [206, 207, 208]])\nx_pred = np.transpose(x_pred)\naaa = model.predict(x_pred, batch_size = 1)\nprint(aaa)\n\ny_pred = model.predict(x_test, batch_size = 1)\n\n# RMSE\nfrom sklearn.metrics import mean_squared_error\ndef RMSE(y_test, y_pred):\n return np.sqrt(mean_squared_error(y_test, y_pred))\nprint('RMSE : ', RMSE(y_test, y_pred)) # 오차값이기 때문에 값이 적을수록 좋음\n\n# RMSE2\nprint('print r_mse :', np.sqrt(mse))\n\nfrom sklearn.metrics import r2_score\nr2_y_predict = r2_score(y_test, y_pred)\nprint('R2 : ', r2_y_predict) #R2는 최대값이 1로 1에 가까울수록 정확함","sub_path":"keras21_2_load.py","file_name":"keras21_2_load.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"51593285","text":"# imports and env-variable\nimport numpy as np\nimport os\nimport glob\nimport nltk\nfrom nltk.tokenize import RegexpTokenizer\nimport urllib3\nimport tarfile\n\nBASE_DIR = '/home/ubuntu/CyrusProjects/mxnet-notebooks/python/tutorials'\nPATH='/aclImdb'\n\nwith open('aclImdb/imdb.vocab') as vocab_file:\n vocab_array = vocab_file.readlines()\nvocab_array = [x.strip() for x in vocab_array]\nprint(len(vocab_array))\n\n\nwith open(BASE_DIR + PATH + '/imdb.vocab') as f:\n dic = f.readlines()\ndic= [x.strip() for x in dic]\ndic = np.array(np.sort(dic))\ndic = np.unique(dic)\ndic = dic.tolist()\n\n\n# tokenizer.perl is from Moses: https://github.com/moses-smt/mosesdecoder/tree/master/scripts/tokenizer\ndef sentence_array_creator(path, root_dir):\n os.chdir(path)\n sentences = []\n for file in list(glob.glob(\"*.txt\")):\n with open(file, 'r') as f:\n sentences.append(f.readline().strip().lower())\n return sentences\n os.chdir(root_dir)\n\nos.chdir(BASE_DIR)\nroot_dir = os.getcwd()\n\nbase_dir = BASE_DIR + PATH\npos_train_path = base_dir + '/train/pos'\nneg_train_path = base_dir + '/train/neg'\npos_test_path = base_dir + '/test/pos'\nneg_test_path = base_dir + '/test/neg'\n\n\npos_train_sentences = sentence_array_creator(pos_train_path, root_dir)\nneg_train_sentences = sentence_array_creator(neg_train_path, root_dir)\npos_test_sentences = sentence_array_creator(pos_test_path, root_dir)\nneg_test_sentences = sentence_array_creator(neg_test_path, root_dir)\n\n\nprint(\"{}, {}, {}, {}\".format(len(pos_train_sentences), len(neg_train_sentences), len(pos_test_sentences), len(neg_test_sentences)))\n\n\ndef get_dic_index(word, dic):\n try:\n ret_val = dic.index(word)\n except ValueError: \n ret_val = -1\n return ret_val\n\n\n\ndef sentence_encoder(sentences, vocab):\n bow = []\n t = RegexpTokenizer(r'\\w+')\n prog = 0\n for sentence in sentences:\n if prog % 10 == 0:\n print(prog, sep=' ', end='-',flush=True)\n s = ''.join(sentence)\n tokens = t.tokenize(s)\n indexes = []\n for token in tokens:\n idx = get_dic_index(token, vocab)\n if idx != -1:\n indexes.append(idx)\n prog += 1\n bow.append(indexes)\n return bow\n\ndef sentence_tokenizer(sentences):\n bow = []\n t = RegexpTokenizer(r'\\w+')\n for sentence in sentences:\n s = ''.join(sentence)\n tokens = t.tokenize(s)\n bow.append(tokens)\n return bow\n\n\ndef print_items(array):\n for i in array:\n print('{} \\n'.format(i))\n \nsentences = [\n [\"elizabeth ashley is receiving phone calls from her nephew michael--he's crying, screaming and asking for help. the problem is michael died 15 years ago.

this film scared me silly back in 1972 when it aired on abc. seeing it again, years later, it still works.

the movie is a little slow and predictable, the deaths are very tame and there's a tacked-on happy ending, but this is a tv movie so you have to give it room. elizabeth ashley is excellent, ben gazzara is ok and it's fun to see michael douglas so young. and those telephone calls still scare the living daylights out of me. i actually had to turn a light on during one of them!

a creepy little tv movie. worth seeing.\"],\n [\"big fat liar is the best movie ever! it is funny, and cool. jason shepherd (frankie muniz) proves that he was not lying and goes to los angeles to get his paper back from marty wolf( paul giamatti). along with friend kaylee(amanda bynes), mess up his life since marty won't call jasons' dad and say he wrote the paper! yet it all turns out good and is a good movie to watch!\"],\n [\"out of any category, this is one demented and over the edge film, even in todays standards. filmed entirely in crap-o-rama, this film will blow your mind (and something else too!)

the amount of hilarious bad taste and sleaze is astonishing. the dialog is breathtakingly fast and campy. you'll either love or hate this film, but give it go. i've seen it 4 times and absolutely love it. divine is in the quest for being the filthiest person alive, but so are her rivals too in this obscene and disgusting (but funny) and stylish little film.

divine was phenomenal, and she will always be missed greatly. edith massey does the unforgettable performance as the egglady and don't forget the energetic mink stole!

über crazy s**t!

recommended also for you sick little puppies;

female trouble

desperate living

polyester\"]\n ]\n\n\nprint(\"now calculating bow_pos_train_sentences...\")\nbow_pos_train_sentences = sentence_encoder(pos_train_sentences, dic)\nnp.save(BASE_DIR + PATH + '/bow_pos_train_sentences_batch', bow_pos_train_sentences)\n\nprint(\"now calculating bow_neg_train_sentences...\")\nbow_neg_train_sentences = sentence_encoder(neg_train_sentences, dic)\nnp.save(BASE_DIR + PATH + '/bow_neg_train_sentences_batch', bow_neg_train_sentences)\n\nprint(\"now calculating bow_pos_test_sentences...\")\nbow_pos_test_sentences = sentence_encoder(pos_test_sentences, dic)\nnp.save(BASE_DIR + PATH + '/bow_pos_test_sentences_batch', bow_pos_test_sentences)\n\nprint(\"now calculating bow_neg_test_sentences...\")\nbow_neg_test_sentences = sentence_encoder(neg_test_sentences, dic)\nnp.save(BASE_DIR + PATH + '/bow_neg_test_sentences_batch', bow_neg_test_sentences)\n\nprint(\"DONE...\")\n\nprint(len(bow_neg_test_sentences))\nprint(len(bow_neg_train_sentences))\nprint(len(bow_pos_test_sentences))\nprint(len(bow_pos_train_sentences))\n\n\nprint(len(np.load(BASE_DIR + PATH + '/bow_neg_test_sentences_batch.npy')))\nprint(len(np.load(BASE_DIR + PATH + '/bow_neg_train_sentences_batch.npy')))\nprint(len(np.load(BASE_DIR + PATH + '/bow_pos_test_sentences_batch.npy')))\nprint(len(np.load(BASE_DIR + PATH + '/bow_pos_train_sentences_batch.npy')))\n\n","sub_path":"python/tutorials/pre_proc_imdb.py","file_name":"pre_proc_imdb.py","file_ext":"py","file_size_in_byte":5883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"36625961","text":"import httplib\nimport time\n\nliveUrl = 'wac.5f48.edgecastcdn.net'\nliveSSL = 'gs1.wac.edgecastcdn.net'\nQAUrl = 'haproxy-staging-west.bingo.buffalo-ggn.net'\nedgecastFolder = '/805F48/bingoblitz'\nversionNumber = '/v159-3'\ncityBackgrounds = '/game/img/city_backgrounds/'\nassetList = []\nassetList.append(cityBackgrounds + 'Madrid.jpg')\nassetList.append(cityBackgrounds + 'fail.jpg')\nassetList.append(cityBackgrounds + 'Plano.jpg')\nassetList.append(cityBackgrounds + '12358593202.jpg')\n\ndef testAssets(host, versionNumber, assetList):\n try:\n #path = edgecastFolder + versionNumber + cityBackgrounds + 'Marid.jpg'\n conn = httplib.HTTPConnection(host)\n #conn.set_debuglevel(1)\n for fname in assetList:\n try:\n #fname = \n conn.request(\"HEAD\", versionNumber + fname)\n #print('request ok')\n response = conn.getresponse()\n #print(asdf.reason())\n #print('response ok')\n if response.getheaders()[0][0] == 'date':\n print(\"missing asset: \" + host + versionNumber + fname)\n response.close() # have to kill response before sending another request\n #print('getheaders ok')\n except:\n print(\"missing asset: \" + host + fname)\n conn.close()\n print(\"http connection success\")\n except:\n conn.close()\n print(\"http connection failure\")\n conn.close()\n\n#print(QAUrl)\ntestAssets(liveUrl + edgecastFolder, versionNumber, assetList)\n\n","sub_path":"code/Python/image_finder.py","file_name":"image_finder.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"176336104","text":"# -*- coding: utf-8 -*- \n# @Time : 2020/10/28 10:18 \n# @Author : xu \n# @File : 并发vs并行.py\n\nimport requests\nimport time\n\nts = time.time()\nreq = requests.get(\"https://www.yiibai.com\")\npagehtml = req.text\nte = time.time()\nprint(f\"read yiibai use {te - ts} Seconds\")\n\n","sub_path":"note-taking/concurrence/并发vs并行.py","file_name":"并发vs并行.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"253616816","text":"from django.db import models\n\nclass ImageManager(models.Manager):\n\n def get_weighted_random_object(self):\n from django.db import connection\n cursor = connection.cursor()\n cursor.execute(\"\"\"\n SELECT id, filename, score, votecount\n FROM %s\n ORDER BY RANDOM ()\n LIMIT 1\n \"\"\" % self.model._meta.db_table)\n res = cursor.fetchone()\n cursor.close()\n if not res:\n return None\n i = self.model(id=res[0], filename=res[1],\n score=res[2], votecount=res[3])\n return i\n\nclass Image(models.Model):\n filename = models.CharField(max_length=10)\n score = models.IntegerField()\n votecount = models.IntegerField()\n session = models.CharField(max_length=40) # Same size as the column in the session table\n\n objects = ImageManager()\n\n def __unicode__(self):\n return \"%s : %d/%d\" % (self.filename, self.score, self.votecount)\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"248458500","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nThis python script uses the Beautiful Soup module to scrape images\nfrom https://unsplash.com - a high-quality image supplier.\n\nOnce the user enters their desired image category, the top three \nimages of the entered category as well as a .txt file containing\nthe image links are saved to a newly created directory.\n'''\n\nimport urllib.request\nfrom urllib.request import urlopen\nfrom urllib.request import urlretrieve\nimport bs4 as bs\nimport os\n\n# get user input\nsearchInput = input(\"Search: \")\n# if search is multiple words, join them with a \"-\"\nsearch = '-'.join(searchInput.split(\" \"))\nwebLink = \"https://unsplash.com/s/photos/\" + search\nsource = urlopen(webLink).read()\n# create beautiful soup object\nsoup = bs.BeautifulSoup(source, \"html.parser\")\n\n# find divs containing the images we desire\ndivTags = soup.findAll(\"div\",{\"class\":\"_1ZjfQ _2T3hc Xl8Lr\"})\nprint(type(divTags))\n# for each div, isolate the img tag and add it to the imgTags list\nimgTags = [div.find(\"img\") for div in divTags]\n\n# retrieve directory of scraper file\nscraperDir = os.path.dirname(os.path.realpath(__file__)) \n# create new directory to write images and image links to\nos.makedirs(scraperDir + \"/\" + search + \" scrape\")\nfolderPath = scraperDir + \"/\" + search + \" scrape\"\n\ncount = 1\n# open new test file \"f\"\nwith open(folderPath + '/imgLinks.txt', 'w+') as f:\n # iterate each tag to find individual images\n for img in imgTags:\n # we only want the src images\n if img.has_attr(\"src\"):\n imgLink = img.get(\"src\")\n f.write(imgLink + \"\\n\") # write image link to imgLinks.txt\n # download the image into the newly created folder\n urllib.request.urlretrieve(imgLink, folderPath + \"/image\" + str(count) + \".jpg\")\n count += 1\nf.close()\n\nprint(\"Scrape completed.\")","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"135796080","text":"\"\"\"\nViewport Colors - Scripts Package v1.0\nThanks for download - for commercial and personal uses.\nThe Viewport Colors v1.0 granted shall not be copied, distributed, or-sold, offered for resale, transferred in whole or in part except that you may make one copy for archive purposes only.\n\nbe.net/dyne\nWriten by: Carlos Dordelly\nSpecial thanks: Pancho Contreras, Terry Williams & Roberto Gonzalez\n\nNow you can easily add a quickly reference colors to your objects without lost your applied materials (from any render engine).\nDate: 29/07/2017\nWritten and tested in Cinema 4D R18 / R17 / R16 - Not tested in older versions.\n\n\"\"\"\n\nimport c4d\nfrom c4d import gui\n\n#color id to apply\nvcolor = c4d.Vector(0,1,1) #cyan\n\ndef vp_color():\n \n #get Active Objects\n activeObjects = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_CHILDREN)\n if not activeObjects:\n gui.MessageDialog('Please select one or more objects.')\n return\n \n #start undo action\n doc.StartUndo()\n\n #viewport color actions\n for obj in activeObjects:\n doc.AddUndo(c4d.UNDOTYPE_CHANGE,obj)\n #shorcuts to random functions\n bc = c4d.BaseContainer()\n if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD,c4d.BFM_INPUT_CHANNEL,bc):\n if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QSHIFT: \n obj[c4d.ID_BASEOBJECT_USECOLOR]=2\n obj[c4d.ID_BASEOBJECT_COLOR]=vcolor\n tag = obj.MakeTag(c4d.Tdisplay)\n doc.AddUndo(c4d.UNDOTYPE_CHANGE,tag)\n tag[c4d.DISPLAYTAG_AFFECT_DISPLAYMODE]=True\n tag[c4d.DISPLAYTAG_SDISPLAYMODE]=6\n tag[c4d.DISPLAYTAG_WDISPLAYMODE]=1\n tag[c4d.ID_BASELIST_NAME]=\"Geo Wire Color\"\n\n #if obj is a null delete vcolor \n obj_type=obj.GetType()\n null_id = 5140\n if obj_type == null_id:\n obj[c4d.ID_BASEOBJECT_COLOR]=c4d.Vector(1,1,1) #set to default\n obj[c4d.ID_BASEOBJECT_USECOLOR]=0 #set to default\n obj[c4d.ID_BASEOBJECT_XRAY]=False #set to default\n obj.KillTag(c4d.Tdisplay) #delete display tag\n \n elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: \n obj[c4d.ID_BASEOBJECT_USECOLOR]=2\n obj[c4d.ID_BASEOBJECT_COLOR]=vcolor\n obj[c4d.ID_BASEOBJECT_XRAY]=True\n obj.KillTag(c4d.Tdisplay)\n\n #if obj is a null delete vcolor \n obj_type=obj.GetType()\n null_id = 5140\n if obj_type == null_id:\n obj[c4d.ID_BASEOBJECT_COLOR]=c4d.Vector(1,1,1) #set to default\n obj[c4d.ID_BASEOBJECT_USECOLOR]=0 #set to default\n obj[c4d.ID_BASEOBJECT_XRAY]=False #set to default\n obj.KillTag(c4d.Tdisplay) #delete display tag\n\n else:\n #obj actions\n obj[c4d.ID_BASEOBJECT_USECOLOR]=2\n obj[c4d.ID_BASEOBJECT_COLOR]=vcolor\n obj[c4d.ID_BASEOBJECT_XRAY]=False\n obj.KillTag(c4d.Tdisplay)\n\n #if obj is a null delete vcolor \n obj_type=obj.GetType()\n null_id = 5140\n if obj_type == null_id:\n obj[c4d.ID_BASEOBJECT_COLOR]=c4d.Vector(1,1,1) #set to default\n obj[c4d.ID_BASEOBJECT_USECOLOR]=0 #set to default\n obj[c4d.ID_BASEOBJECT_XRAY]=False #set to default\n obj.KillTag(c4d.Tdisplay) #delete display tag\n\n #end undo action\n doc.EndUndo()\n\n #do redo action\n doc.DoRedo()\n\n #update scene\n c4d.EventAdd()\n \n \nif __name__=='__main__':\n vp_color()","sub_path":"delivery-pre-builds/VP Direct Color 1.0/VP Cyan.py","file_name":"VP Cyan.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"48739797","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport tensorflow as tf\nimport os\nimport zipfile\nfrom os import path, getcwd, chdir\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndef conv_classifier():\n\n DESIRED_ACCURACY = 0.999\n\n class myCallback(tf.keras.callbacks.Callback):\n def on_epoch_end(self, callback, logs={}):\n if (logs.get('acc') > DESIRED_ACCURACY):\n print(\"\\nReached {}/% accuracy, stopping training\".format(DESIRED_ACCURACY*100))\n self.model.stop_training = True\n\n callbacks = myCallback()\n \n # This Code Block should Define and Compile the Model. Please assume the images are 150 X 150 in your implementation.\n model = tf.keras.models.Sequential([\n # Your Code Here\n tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150,150,3)),\n tf.keras.layers.MaxPooling2D(2, 2),\n tf.keras.layers.Conv2D(16, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2, 2),\n tf.keras.layers.Conv2D(16, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2, 2),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')\n ])\n\n\n model.compile(loss='binary_crossentropy', optimizer=RMSprop(lr=0.001), metrics=['acc'])\n \n\n # This code block should create an instance of an ImageDataGenerator called train_datagen \n # And a train_generator by calling train_datagen.flow_from_directory\n\n train_datagen = ImageDataGenerator(rescale=1./255)\n\n # target_size of 150 X 150.\n train_generator = train_datagen.flow_from_directory(\n '/train/',\n target_size=(150, 150),\n batch_size=10,\n class_mode='binary'\n )\n\n # This code block should call model.fit_generator and train for\n # a number of epochs.\n # model fitting\n history = model.fit_generator(\n train_generator,\n steps_per_epoch=8,\n epochs=15,\n verbose=1,\n callbacks=[callbacks]\n )\n # model fitting\n return history.history['acc'][-1]\n\n\nprint(conv_classifier())\n","sub_path":"CNN_classification_real_images.py","file_name":"CNN_classification_real_images.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"169259520","text":"'''azurerm - unit tests - keyvault''' \n# to run tests: python -m unittest keyvault_test.py\n\nimport sys\nimport unittest\nfrom haikunator import Haikunator\nimport json\nimport azurerm\nimport time\n\nclass TestAzurermPy(unittest.TestCase):\n\n def setUp(self):\n # Load Azure app defaults\n try:\n with open('azurermconfig.json') as config_data:\n config_data = json.load(config_data)\n except FileNotFoundError:\n sys.exit(\"Error: Expecting azurermconfig.json in current folder\")\n self.tenant_id = config_data['tenantId']\n self.app_id = config_data['appId']\n app_secret = config_data['appSecret']\n self.subscription_id = config_data['subscriptionId']\n self.access_token = azurerm.get_access_token(self.tenant_id, self.app_id, app_secret)\n self.location = config_data['location']\n h = Haikunator()\n self.rgname = h.haikunate()\n self.vault_name = h.haikunate()\n\n # create resource group\n print('Creating resource group: ' + self.rgname)\n response = azurerm.create_resource_group(self.access_token, self.subscription_id, \\\n self.rgname, self.location)\n self.assertEqual(response.status_code, 201)\n\n\n def tearDown(self):\n # delete resource group\n print('Deleting resource group: ' + self.rgname)\n response = azurerm.delete_resource_group(self.access_token, self.subscription_id, \n self.rgname)\n self.assertEqual(response.status_code, 202)\n\n def test_keyvault(self):\n # create key vault\n print('Creating key vault: ' + self.vault_name)\n response = azurerm.create_keyvault(self.access_token, self.subscription_id, \\\n self.rgname, self.vault_name, self.location, tenant_id=self.tenant_id, \n object_id=self.app_id)\n # print(response.text)\n self.assertEqual(response.status_code, 200)\n\n # list keyvaults\n print('List key vaults')\n response = azurerm.list_keyvaults(self.access_token, self.subscription_id, self.rgname)\n # print(json.dumps(response, sort_keys=False, indent=2, separators=(',', ': ')))\n self.assertTrue('value' in response)\n\n # list keyvaults in subscription\n print('List key vaults in subscription')\n response = azurerm.list_keyvaults_sub(self.access_token, self.subscription_id)\n # print(json.dumps(response, sort_keys=False, indent=2, separators=(',', ': ')))\n self.assertTrue('value' in response)\n\n # get key vault\n print('Get key vault')\n response = azurerm.get_keyvault(self.access_token, self.subscription_id, self.rgname, self.vault_name)\n # print(json.dumps(response, sort_keys=False, indent=2, separators=(',', ': ')))\n self.assertEqual(response['name'], self.vault_name)\n\n # delete key vault\n print('Delete key vault: ' + self.vault_name)\n response = azurerm.delete_keyvault(self.access_token, self.subscription_id, \\\n self.rgname, self.vault_name)\n self.assertEqual(response.status_code, 200)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"test/keyvault_test.py","file_name":"keyvault_test.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"565760011","text":"from retrieve_tweet_keywords import summarize\nfrom retrieve_tweet_text import getText\nfrom get_articles import getArticles\nfrom article_summariser import getSummary\n\ndef getMatchingArticles(url):\n\n res = {}\n tweet_text = getText(url)\n tweet_summary = summarize(tweet_text)\n all_articles = getArticles(tweet_summary)\n\n for article in all_articles:\n article[\"summary\"] = getSummary(article[\"text\"])\n del article[\"text\"]\n \n res[\"tweet_url\"] = url\n res[\"tweet_summary\"] = tweet_summary\n res[\"articles\"] = all_articles\n \n return res","sub_path":"utils/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"497872685","text":"def readdata(filepath, yfield):\r\n f = open(filepath, 'r')\r\n str = f.readline()\r\n attribute = str.split(',')\r\n yindx = attribute.index(yfield)\r\n y = []\r\n X = []\r\n str = f.readline()\r\n\r\n while str:\r\n attribute_num = str.split(',')\r\n y_tmp = int(float(attribute_num[yindx]))\r\n y.append(y_tmp)\r\n x_tmp = attribute_num[yindx+1:]\r\n x_tmp = [float(int(float(i))) for i in x_tmp]\r\n X.append(x_tmp)\r\n str = f.readline()\r\n return X, y\r\n\r\n\r\ndef standardize_X(X):\r\n # this function will convert the feature X in to Z score\r\n import sklearn.preprocessing as pre\r\n scaler = pre.MinMaxScaler()\r\n X_minmax = scaler.fit_transform(X)\r\n return X_minmax, scaler\r\n\r\n\r\ndef split_data(X, y):\r\n from sklearn.model_selection import train_test_split\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n return X_train, X_test, y_train, y_test\r\n\r\n\r\ndef plot_data(X, y, list1):\r\n import matplotlib.pyplot as plt\r\n stdz_X, avg_X, std_X = standardize_X(X)\r\n x1 = stdz_X[:, list1[0]]\r\n x2 = stdz_X[:, list1[1]]\r\n plt.scatter(x1, x2, s=75, c=y)\r\n plt.show()\r\n\r\n\r\ndef countClassNum():\r\n import pickle\r\n ylist = pickle.load(open('y_train.p'))\r\n sety = list(set(ylist))\r\n sety.sort()\r\n num = []\r\n for i in sety:\r\n tmpnum = 0\r\n for j in ylist:\r\n if j == i:\r\n tmpnum += 1\r\n\r\n num.append(tmpnum)\r\n return sety, num\r\n\r\ndef exportData(xpicklefile, ypicklefile):\r\n import pickle\r\n xlist = pickle.load(open(xpicklefile))\r\n ylist = pickle.load(open(ypicklefile))\r\n sety = list(set(ylist))\r\n sety.sort()\r\n num = []\r\n for i in sety:\r\n tmpnum = 0\r\n for j in ylist:\r\n if j == i:\r\n tmpnum += 1\r\n\r\n num.append(tmpnum)\r\n return sety, num\r\n\r\n\r\ndef polynomialLayer(intifImg, d, outtifImg):\r\n from sklearn.preprocessing import PolynomialFeatures\r\n from osgeo import gdal\r\n from osgeo import gdalconst\r\n import sys\r\n\r\n driver = gdal.GetDriverByName('GTiff')\r\n driver.Register()\r\n ImgDs = gdal.Open(intifImg, gdalconst.GA_ReadOnly)\r\n if ImgDs is None:\r\n print('Error Could not read')\r\n sys.exit()\r\n\r\n cols =ImgDs.RasterXSize\r\n rows = ImgDs.RasterYSize\r\n bands = ImgDs.RasterCount\r\n projection = ImgDs.GetProjection()\r\n datatype = gdal.GetDataTypeName(ImgDs.GetRasterBand(1).DataType)\r\n nodataval = ImgDs.GetRasterBand(1).GetNoDataValue()\r\n geotransform = ImgDs.GetGeoTransform()\r\n\r\n import numpy as np\r\n\r\n poly = PolynomialFeatures(d)\r\n\r\n sampleFeat = []\r\n mask = ImgDs.GetRasterBand(1).ReadAsArray(0, 0, cols, rows)\r\n for i in range(bands):\r\n band = ImgDs.GetRasterBand(i+1)\r\n data = band.ReadAsArray(int(cols/2), int(rows/2), 1, 1)\r\n value = data[0][0]\r\n sampleFeat.append(value)\r\n band = None\r\n polyfeat = poly.fit_transform([sampleFeat])\r\n outbands = len(polyfeat[0])\r\n polyfeat = None\r\n\r\n ImgDsOut = driver.Create(outtifImg, cols, rows, outbands, gdal.GDT_Float32)\r\n\r\n for l in range(outbands):\r\n imgInFeat = mask\r\n for r in range(rows):\r\n for c in range(cols):\r\n feat = []\r\n if imgInFeat[r][c] != nodataval:\r\n for i in range(bands):\r\n band = ImgDs.GetRasterBand(i + 1)\r\n data = band.ReadAsArray(c, r, 1, 1)\r\n value = data[0][0]\r\n feat.append(value)\r\n band = None\r\n polyFeat = poly.fit_transform([feat])\r\n imgInFeat[r][c] = polyFeat[0][l]\r\n\r\n imgInFeat = np.array(imgInFeat)\r\n print ('this is img')\r\n print (imgInFeat)\r\n out_band = ImgDsOut.GetRasterBand(l+1)\r\n \r\n out_band.WriteArray(imgInFeat, 0, 0)\r\n out_band.SetNoDataValue(nodataval)\r\n print ('Done layer {0}'.format(l+1))\r\n out_band = None\r\n\r\n allband = None\r\n ImgDsOut.SetProjection(projection)\r\n ImgDsOut.SetGeoTransform(geotransform)\r\n ImgDsOut = None\r\n\r\n print('Done poly!')\r\n\r\n\r\ndef loadHyperTxt(filepath):\r\n import numpy as np\r\n data = np.loadtxt(filepath, skiprows=1)\r\n x = sorted(set(data[:,0].tolist()))\r\n y = sorted(set(data[:,1].tolist()))\r\n X, Y = np.meshgrid(x, y)\r\n Z = np.zeros((len(y), len(x)))\r\n\r\n for i in data:\r\n Xindex = x.index(i[0])\r\n Yindex = y.index(i[1])\r\n Z[Yindex][Xindex] = i[2]\r\n Z = np.around(Z, decimals=5)\r\n Z = Z.tolist()\r\n return X, Y, Z\r\n\r\n\r\ndef plotContour(d1, d2, accu):\r\n\r\n import matplotlib\r\n import matplotlib.cm as cm\r\n import matplotlib.pyplot as plt\r\n\r\n matplotlib.rcParams['xtick.direction'] = 'out'\r\n matplotlib.rcParams['ytick.direction'] = 'out'\r\n\r\n x = d1\r\n y = d2\r\n z = accu\r\n plt.figure()\r\n cp = plt.contourf(x, y, z, cmap=cm.gray)\r\n plt.colorbar(cp)\r\n plt.title('(d)')\r\n plt.xlabel('C')\r\n plt.ylabel('gamma')\r\n plt.show()\r\n\r\n '''\r\n import plotly\r\n plotly.tools.set_credentials_file(username='ace780208', api_key='Qtz6Z2VayGWH9wKYOB6n')\r\n import plotly.plotly as py\r\n import plotly.graph_objs as go\r\n data = [\r\n go.Contour(\r\n z=accu,\r\n x=d1,\r\n y=d2,\r\n line=dict(smoothing=0.85),\r\n )]\r\n py.iplot(data)\r\n'''\r\n\r\n\r\ndef raster2txt(img, outtxt):\r\n from osgeo import gdal\r\n from osgeo import gdalconst\r\n import sys\r\n\r\n driver = gdal.GetDriverByName('GTiff')\r\n driver.Register()\r\n ImgDs = gdal.Open(img, gdalconst.GA_ReadOnly)\r\n if ImgDs is None:\r\n print('Error Could not read')\r\n sys.exit()\r\n\r\n cols =ImgDs.RasterXSize\r\n rows = ImgDs.RasterYSize\r\n bands = ImgDs.RasterCount\r\n projection = ImgDs.GetProjection()\r\n datatype = gdal.GetDataTypeName(ImgDs.GetRasterBand(1).DataType)\r\n nodataval = ImgDs.GetRasterBand(1).GetNoDataValue()\r\n geotransform = ImgDs.GetGeoTransform()\r\n\r\n f = open(outtxt, 'w')\r\n f.write('ncols\\t' + str(cols) + '\\n')\r\n f.write('nrows\\t' + str(rows) + '\\n')\r\n f.write('xllcorner\\t' + str(geotransform[0]) + '\\n')\r\n f.write('yllcorner\\t' + str(geotransform[3]) + '\\n')\r\n f.write('cellsize\\t' + str(geotransform[1]) + '\\n')\r\n f.write('NODATA_value\\t' + str(nodataval) + '\\n')\r\n\r\n for i in range(bands):\r\n if i != bands-1:\r\n f.write('band' + str(i+1) + '\\t')\r\n else:\r\n f.write('band' + str(i+1) + '\\n')\r\n\r\n for r in range(rows):\r\n for c in range(cols):\r\n for i in range(bands):\r\n band = ImgDs.GetRasterBand(i + 1)\r\n data = band.ReadAsArray(c, r, 1, 1)\r\n value = data[0][0]\r\n if i != bands - 1:\r\n f.write(str(value) + '\\t')\r\n else:\r\n f.write(str(value) + '\\n')\r\n band = None\r\n print('done row ' + str(r))\r\n f.flush()\r\n f.close()\r\n ImgDs = None\r\n print('done img2txt!')\r\n\r\n\"\"\"\r\nX, Y, Z = loadHyperTxt('./output/FNNR/FNNR_SVM_cst2.txt')\r\nplotContour(X, Y, Z)\r\n\"\"\"","sub_path":"dataProc.py","file_name":"dataProc.py","file_ext":"py","file_size_in_byte":7213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"222183935","text":"# -*- coding: utf-8 -*-\n\nimport core.handlers as handlers\n\nrouted_handlers = [\n (r'/', handlers.IndexHandler),\n (r'/chat', handlers.WebSocketChatHandler),\n (r'/login', handlers.LoginHandler),\n (r'/logout', handlers.LogoutHandler),\n (r'/static/(.*)', handlers.StaticFileHandler, {'path': './assetscore'})\n]\n","sub_path":"core/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"485192554","text":"from django.contrib import admin\nfrom .models import UsuarioEgresado, InteresesEgresado, AmigosEgresado, ProgramaAcademico, GraduadosPersonas, Graduados\nadmin.site.register (UsuarioEgresado)\n\n@admin.register(InteresesEgresado)\nclass InteresesEgresado_Admin(admin.ModelAdmin):\n\tlist_display = (\"userEgre\", \"interes\", )\n\tlist_filter = (\"userEgre\", \"interes\",)\n\n@admin.register(AmigosEgresado)\nclass AmigosEgresado_Admin(admin.ModelAdmin):\n\tlist_display = (\"userEgre\", \"amigoDNI\", \"estado\",)\n\tlist_filter = (\"userEgre\", \"amigoDNI\", \"estado\",)\n\nadmin.site.register(ProgramaAcademico)\nadmin.site.register(GraduadosPersonas)\nadmin.site.register(Graduados)\n","sub_path":"webEgresados/usuarioEgresado/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"361314172","text":"def knapsackProblem(items, capacity):\n # Write your code here.\n # return [\n # 10, // total value\n # [1, 2], // item indices\n # ]\n if len(items) == 0:\n \treturn [0, []]\n\n maxCap = [[0 for col in range(capacity + 1)] for row in range(len(items))]\n\n for row in range(len(maxCap)):\n \tvalue = items[row][0]\n \tweight = items[row][1]\n \tfor col in range(1, len(maxCap[row])):\n \t\tcurCapacity = col\n \t\tif curCapacity == weight:\n \t\t\tmaxCap[row][col] = value\n \t\tif row == 0:\n \t\t\tmaxCap[row][col] = max(maxCap[row][col], maxCap[row][col - 1])\n \t\t\tcontinue\n \n \t\tprevWeight = curCapacity - weight\n \t\tif prevWeight < 1 :\n \t\t\tmaxCap[row][col] = max(maxCap[row][col], maxCap[row][col - 1], maxCap[row - 1][col])\n \t\t\tcontinue\n \n \t\tvalAtPrevWeight = maxCap[row - 1][prevWeight]\n \t\tif valAtPrevWeight + value > maxCap[row][col]:\n \t\t\tmaxCap[row][col] = valAtPrevWeight + value\n \n \t\tmaxCap[row][col] = max(maxCap[row][col], maxCap[row][col - 1], maxCap[row - 1][col])\n\n print(maxCap)\n totValue = maxCap[-1][-1]\n index = []\n i = len(maxCap) - 1\n j = len(maxCap[i]) - 1\n\n while i >= 0 and j >= 0:\n if maxCap[i][j] == maxCap[i - 1][j]:\n \ti -= 1\n else:\n index.append(i)\n weight = items[i][1]\n j -= weight\n\n if i == 0:\n\t if maxCap[i][j] == maxCap[i + 1][j]:\n\t \t index.append(i)\n \n\n return [totValue, list(reversed(index))]\t\t\t\n\nitems = [[1, 2], [4, 3], [5, 6], [6, 9]]\ncapacity = 11\n\nprint(knapsackProblem(items, capacity))\n\n","sub_path":"Revision/DynamicProgramming/KnapsacProb.py","file_name":"KnapsacProb.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"11045231","text":"# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\n# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nimport mdp, util\n\nfrom learningAgents import ValueEstimationAgent\nfrom util import PriorityQueue\nimport collections\n\nclass ValueIterationAgent(ValueEstimationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n A ValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs value iteration\n for a given number of iterations using the supplied\n discount factor.\n \"\"\"\n def __init__(self, mdp, discount = 0.9, iterations = 100):\n \"\"\"\n Your value iteration agent should take an mdp on\n construction, run the indicated number of iterations\n and then act according to the resulting policy.\n\n Some useful mdp methods you will use:\n mdp.getStates()\n mdp.getPossibleActions(state)\n mdp.getTransitionStatesAndProbs(state, action)\n mdp.getReward(state, action, nextState)\n mdp.isTerminal(state)\n \"\"\"\n self.mdp = mdp\n self.discount = discount\n self.iterations = iterations\n self.values = util.Counter() # A Counter is a dict with default 0\n self.runValueIteration()\n\n def runValueIteration(self):\n # Write value iteration code here\n \"*** YOUR CODE HERE ***\"\n allStates = self.mdp.getStates()\n while self.iterations > 0 :\n dic = {}\n for s in allStates:\n if self.mdp.isTerminal(s):\n continue\n dic[s] = self.computeQValueFromValues(s,self.computeActionFromValues(s))\n for s,v in dic.items():\n self.values[s] = v\n self.iterations -= 1\n\n\n\n def getValue(self, state):\n \"\"\"\n Return the value of the state (computed in __init__).\n \"\"\"\n return self.values[state]\n\n\n def computeQValueFromValues(self, state, action):\n \"\"\"\n Compute the Q-value of action in state from the\n value function stored in self.values.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n qValue = 0\n for nextState, prob in self.mdp.getTransitionStatesAndProbs(state,action):\n qValue += prob*(self.mdp.getReward(state,action,nextState)+self.discount*self.values[nextState])\n # print(qValue)\n return qValue\n\n def computeActionFromValues(self, state):\n \"\"\"\n The policy is the best action in the given state\n according to the values currently stored in self.values.\n\n You may break ties any way you see fit. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return None.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n largestV = float('-inf') \n argMax = None\n\n for act in self.mdp.getPossibleActions(state):\n q = self.computeQValueFromValues(state,act)\n if q > largestV:\n largestV = q\n argMax = act\n # print(argMax)\n return argMax\n \n\n def getPolicy(self, state):\n return self.computeActionFromValues(state)\n\n def getAction(self, state):\n \"Returns the policy at the state (no exploration).\"\n return self.computeActionFromValues(state)\n\n def getQValue(self, state, action):\n return self.computeQValueFromValues(state, action)\n\nclass AsynchronousValueIterationAgent(ValueIterationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n An AsynchronousValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs cyclic value iteration\n for a given number of iterations using the supplied\n discount factor.\n \"\"\"\n def __init__(self, mdp, discount = 0.9, iterations = 1000):\n \"\"\"\n Your cyclic value iteration agent should take an mdp on\n construction, run the indicated number of iterations,\n and then act according to the resulting policy. Each iteration\n updates the value of only one state, which cycles through\n the states list. If the chosen state is terminal, nothing\n happens in that iteration.\n\n Some useful mdp methods you will use:\n mdp.getStates()\n mdp.getPossibleActions(state)\n mdp.getTransitionStatesAndProbs(state, action)\n mdp.getReward(state)\n mdp.isTerminal(state)\n \"\"\"\n ValueIterationAgent.__init__(self, mdp, discount, iterations)\n\n def runValueIteration(self):\n \"*** YOUR CODE HERE ***\"\n allStates = self.mdp.getStates()\n length = len(allStates)\n index = 0\n while index < self.iterations:\n s = allStates[index % length]\n if self.mdp.isTerminal(s):\n index += 1\n continue\n self.values[s] = self.computeQValueFromValues(s,self.computeActionFromValues(s))\n index += 1\n\n\nclass PrioritizedSweepingValueIterationAgent(AsynchronousValueIterationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n A PrioritizedSweepingValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs prioritized sweeping value iteration\n for a given number of iterations using the supplied parameters.\n \"\"\"\n def __init__(self, mdp, discount = 0.9, iterations = 100, theta = 1e-5):\n \"\"\"\n Your prioritized sweeping value iteration agent should take an mdp on\n construction, run the indicated number of iterations,\n and then act according to the resulting policy.\n \"\"\"\n self.theta = theta\n ValueIterationAgent.__init__(self, mdp, discount, iterations)\n\n def runValueIteration(self):\n \"*** YOUR CODE HERE ***\"\n allStates = self.mdp.getStates()\n preds = {}\n for s in allStates:\n for act in self.mdp.getPossibleActions(s):\n for nextState, prob in self.mdp.getTransitionStatesAndProbs(s,act):\n if prob:\n preds[nextState] = preds.get(nextState,set()).union({s})\n\n priorityQueue = PriorityQueue()\n\n for s in allStates:\n if self.mdp.isTerminal(s):\n continue\n diff = abs(self.values[s] - self.computeQValueFromValues(s,self.computeActionFromValues(s)))\n priorityQueue.push(s,-diff)\n\n while self.iterations > 0 and not priorityQueue.isEmpty():\n popcorn = priorityQueue.pop()\n self.values[popcorn] = self.computeQValueFromValues(popcorn,self.computeActionFromValues(popcorn))\n\n for pre in preds.get(popcorn,{}):\n diff = abs(self.values[pre]-self.computeQValueFromValues(pre,self.computeActionFromValues(pre)))\n if diff > self.theta:\n priorityQueue.update(pre,-diff)\n self.iterations -= 1\n\n","sub_path":"Artificial Intelligence/Pacman AI/reinforcement/valueIterationAgents.py","file_name":"valueIterationAgents.py","file_ext":"py","file_size_in_byte":8224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"342415969","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def FindGreatestSumOfSubArray(self, array):\n # write code here\n if not array:\n return None\n cur = 0\n great_sum = -0xffffffff\n for i in array:\n if cur <= 0:\n cur = i\n else:\n cur += i\n if great_sum < cur:\n great_sum = cur\n return great_sum","sub_path":"30_连续子数组最大和.py","file_name":"30_连续子数组最大和.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"87763122","text":"import torch\nimport numpy as np\nimport spotlight.optimizers as optimizers\nimport math\nimport logging\n\nfrom spotlight.dataset_manilupation import train_test_timebased_split\nfrom implicit import ImplicitFactorizationModel\nfrom spotlight.sampling import get_negative_samples\nfrom utils.arg_extractor import get_args\nfrom spotlight.dnn_models.mlp import MLP as mlp\nfrom spotlight.dnn_models.neuMF import NeuMF as neuMF\nfrom utils.data_provider import data_provider\n\n\nlogging.basicConfig(format='%(message)s',level=logging.INFO)\n\nargs = get_args() # get arguments from command line\nuse_cuda=args.use_gpu\ndataset_name = args.dataset\n\nlogging.info(\"DataSet MovieLens_%s will be used\"%dataset_name)\n\nif args.on_cluster:\n path = '/disk/scratch/s1877727/datasets/movielens/'\nelse:\n path = 'datasets/movielens/'\n\nrmse_flag = args.rmse\npre_recall_flag = args.precision_recall\nmap_recall_flag= args.map_recall\n\n#Reproducability of results \nseed = 0 \nrandom_state = np.random.RandomState(seed) \ntorch.manual_seed(seed)\n\n# Get data for train and test\ndata_loader = data_provider(path,dataset_name,args.neg_examples,movies_to_keep=-1)\ntrain,valid,test,neg_examples,item_popularity = data_loader.get_timebased_data()\n\n#Training parameters\nusers, movies = train.num_users,train.num_items\ntraining_epochs = args.training_epochs\nlearning_rate = args.learning_rate\nl2_regularizer = args.l2_regularizer\nbatch_size = 256\n\n\n# Choose training model\n\n\nmodel_name = 'mlp'\nmlp_embedding_dim = args.mlp_embedding_dim\ntop = math.log2(mlp_embedding_dim*2)\nmlp_layers = [2**x for x in reversed(range(3,int(top)+1))] \nlogging.info(mlp_layers)\ntechnique = mlp(layers=mlp_layers,num_users=users,num_items=movies,embedding_dim = mlp_embedding_dim)\nlogging.info(technique)\n# Choose optimizer \noptim = getattr(optimizers, args.optim + '_optimizer')\n\n#Initialize model\nmodel = ImplicitFactorizationModel( n_iter=training_epochs,neg_examples = neg_examples,\n num_negative_samples = args.neg_examples,model_name = model_name,\n embedding_dim=mlp_embedding_dim,l2=l2_regularizer,\n representation=technique,random_state=random_state,\n batch_size = batch_size,use_cuda=use_cuda,learning_rate=learning_rate,\n optimizer_func=optim,experiment_name=args.experiment_name)\nexperiment_folder = 'experiments_results/re_trying_mlp/saved_models/best_model'\nmodel.set_users(users,movies)\nstate = torch.load(experiment_folder,map_location='cpu')\ntechnique.load_state_dict(state['network'])\ntechnique.eval()\nmodel._net = technique\n\n\nfor k_loop in [1,3,5,10]:\n results = model.test(test,item_popularity,k = k_loop,rmse_flag=rmse_flag, precision_recall=pre_recall_flag, map_recall=map_recall_flag)\n # print(k_loop,results['precision'],results['recall'])\n\n# Print statistics of the experiment\nlogging.info(\"Training session: {} latent dimensions, {} epochs, {} batch size {} learning rate {} l2_regularizer. {} users x {} items\".format(mlp_embedding_dim, training_epochs,batch_size,learning_rate,l2_regularizer,users,movies))\n\n\n\n\n\n\n\n\n\n\n\n# if args.model == 'mlp':\n# model_name = 'mlp'\n# mlp_embedding_dim = args.mlp_embedding_dim\n# top = math.log2(mlp_embedding_dim*2)\n# mlp_layers = [2**x for x in reversed(range(3,int(top)+1))] \n# technique = mlp(layers=mlp_layers,num_users=users,num_items=movies,embedding_dim = mlp_embedding_dim)\n# elif args.model == 'neuMF':\n# model_name = 'neuMF'\n# mf_embedding_dim = args.mf_embedding_dim\n# mlp_embedding_dim = args.mlp_embedding_dim\n# top = math.log2(mlp_embedding_dim*2)\n# mlp_layers = [2**x for x in reversed(range(3,int(top)+1))] \n# technique = neuMF(mlp_layers=mlp_layers,num_users= users, num_items= movies, mf_embedding_dim=mf_embedding_dim,mlp_embedding_dim=mlp_embedding_dim)\n# embedding_dim = mlp_embedding_dim if args.model == 'mlp' else mf_embedding_dim","sub_path":"test_mlp.py","file_name":"test_mlp.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"480074796","text":"# -*- coding: utf-8 -*-\n\nfrom os.path import getmtime, abspath, join, dirname\nfrom random import shuffle\n\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\nfrom django.urls import reverse\n\nfrom config.utils import get_active_event\nfrom sponsors.choices import SPONSOR_TYPES\nfrom sponsors.models import Sponsor\nfrom usergroups.models import UserGroup\n\n\ndef navigation(request):\n return {\n \"navigation\": [\n (\"Info\", \"/info/\"),\n (\"Venue\", reverse(\"venue\")),\n # (\"Timeline\", \"/timeline/\"),\n (\"Workshops\", reverse('workshops_list_workshops')),\n (\"Talks\", reverse('talks_list_talks')),\n (\"Schedule\", reverse('schedule_list_schedule')),\n (\"News\", reverse('blog_list_posts')),\n (\"Jobs\", reverse('jobs_list_jobs')),\n # (\"Code\", \"/code/\"),\n (\"Team\", \"/team/\"),\n ]\n }\n\n\ndef footer_links(request):\n return {\n \"footer_links\": [\n (\"Info\", \"/info/\"),\n (\"Venue\", reverse(\"venue\")),\n (\"Timeline\", \"/timeline/\"),\n (\"Workshops\", reverse('workshops_list_workshops')),\n (\"Talks\", reverse('talks_list_talks')),\n (\"Schedule\", reverse('schedule_list_schedule')),\n (\"News\", reverse('blog_list_posts')),\n (\"Jobs\", reverse('jobs_list_jobs')),\n (\"Code\", \"/code/\"),\n (\"Team\", \"/team/\"),\n ]\n }\n\n\ndef sponsors(request):\n active = Sponsor.objects.active()\n sponsors = {t: active.filter(type=t).order_by('order') for t, _ in SPONSOR_TYPES}\n\n return {\n \"sponsors\": sponsors\n }\n\n\ndef usergroups(request):\n return {\n \"usergroups\": UserGroup.objects.order_by(\"name\").filter(is_active=True)\n }\n\n\ndef event(request):\n event = get_active_event()\n\n return {\n 'event': event,\n 'cfp': event.get_cfp(),\n }\n\n\ndef webcamp(request):\n \"\"\"Conference-related strings\"\"\"\n # TODO: move to database?\n\n abs_uri = request.build_absolute_uri\n\n return {\n \"base_url\": abs_uri('/').rstrip('/'),\n \"links\": {\n \"sponsors_pdf\": abs_uri('/media/wczg_2018_sponsors_brochure.pdf'),\n \"volunteer_application\": \"http://goo.gl/forms/1LYfr3TEGs\",\n \"entrio\": \"https://www.entrio.hr/en/event/webcamp-zagreb-2017-4261\",\n \"facebook\": \"https://www.facebook.com/WebCampZagreb/\",\n \"twitter\": \"https://twitter.com/webcampzagreb/\",\n \"youtube\": \"https://www.youtube.com/user/WebCampZg\",\n \"linkedin\": \"https://www.linkedin.com/company-beta/6397140/\",\n \"github\": \"https://github.com/webcampzg\",\n \"google_plus\": \"https://plus.google.com/+WebcampzgOrgHR\",\n },\n \"webcamp\": {\n \"og_image\": {\n \"url\": abs_uri(static(\"images/2018/og_image.png\")),\n \"width\": 1200,\n \"height\": 630\n }\n }\n }\n\n\ndef team(request):\n team = [\n {\n \"name\": \"Luka Mužinić\",\n \"image\": \"images/team/luka.jpg\",\n \"twitter\": \"lmuzinic\",\n \"job\": \"Pencil pusher\"\n },\n {\n \"name\": \"Martina Dumančić\",\n \"image\": \"images/team/martina.jpg\",\n \"twitter\": \"\",\n \"job\": \"Procurement\",\n },\n {\n \"name\": \"Filip Gjurin\",\n \"image\": \"images/team/filip.jpg\",\n \"twitter\": \"FilipGjurin\",\n \"job\": \"Graphic design\",\n },\n {\n \"name\": \"Ivan Habunek\",\n \"image\": \"images/team/ivan.jpg\",\n \"twitter\": \"ihabunek\",\n \"job\": \"Speakers & tech\"\n },\n {\n \"name\": \"Tomislav Capan\",\n \"image\": \"images/team/tomislav.jpg\",\n \"twitter\": \"tomislavcapan\",\n \"job\": \"Volunteers\"\n },\n {\n \"name\": \"Steve Tauber\",\n \"image\": \"images/team/steve.png\",\n \"twitter\": \"stevetauber\",\n \"job\": \"Master of ceremonies\"\n },\n {\n \"name\": \"Senko Rašić\",\n \"image\": \"images/team/senko.jpg\",\n \"twitter\": \"senkorasic\",\n \"job\": \"Beloved leader\"\n },\n {\n \"name\": \"Elizabeth Salazar\",\n \"image\": \"images/team/elizabeth.jpg\",\n \"twitter\": \"\",\n \"job\": \"Master of ceremonies\"\n },\n {\n \"name\": \"Miro Svrtan\",\n \"image\": \"images/team/miro.png\",\n \"twitter\": \"msvrtan\",\n \"job\": \"Workshops\"\n },\n {\n \"name\": \"Goran Jurić\",\n \"image\": \"images/team/goran.jpg\",\n \"twitter\": \"goran_juric\",\n \"job\": \"Workshops\"\n },\n {\n \"name\": \"Zoran Antolović\",\n \"image\": \"images/team/zoka.jpg\",\n \"twitter\": \"zoran_antolovic\",\n \"job\": \"Venue\"\n },\n ]\n\n committee = [\n {\n \"name\": \"Emanuel Blagonić\",\n \"image\": \"images/team/emanuel.png\",\n \"twitter\": \"eblagonic\",\n },\n {\n \"name\": \"Goran Jurić\",\n \"image\": \"images/team/goran.jpg\",\n \"twitter\": \"goran_juric\",\n },\n {\n \"name\": \"Saša Jurić\",\n \"image\": \"images/team/sasa.png\",\n \"twitter\": \"sasajuric\",\n },\n {\n \"name\": \"Neven Munđar\",\n \"image\": \"images/team/neven.jpg\",\n \"twitter\": \"nmundar\",\n },\n {\n \"name\": \"Andrea Knez Karačić\",\n \"image\": \"images/team/andrea.jpg\",\n \"twitter\": \"CodeWithCream\",\n },\n {\n \"name\": \"Ivan Čurić\",\n \"image\": \"images/team/ivan_curic.jpg\",\n \"twitter\": \"_baxuz\",\n },\n {\n \"name\": \"Davor Tomić\",\n \"image\": \"images/team/davor_tomic.jpg\",\n \"twitter\": \"davortomic\",\n },\n {\n \"name\": \"Slaven Tomac\",\n \"image\": \"images/team/slaven.png\",\n \"twitter\": \"slaventomac\",\n },\n ]\n\n shuffle(team)\n shuffle(committee)\n\n return {\n \"team\": team,\n \"committee\": committee,\n }\n\n\ndef css_last_modified(request):\n css_last_modified = getmtime(abspath(join(dirname(__file__), 'dist/styles/style.css')))\n return {\n 'css_last_modified': css_last_modified\n }\n","sub_path":"ui/ctx.py","file_name":"ctx.py","file_ext":"py","file_size_in_byte":6399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"429058450","text":"upfile = 'upfile.txt'\n\nnewlines = []\n\nfor line in open(upfile):\n if line.startswith('#'):\n newlines.append(line)\n continue\n line = line.split()[0].strip()\n line = line.strip('?')\n line = line.replace('/', '\\\\')\n line = line.lstrip('\\\\')\n if line.startswith('com\\\\'):\n if line.endswith('.java'):\n line = 'src\\\\' + line\n else:\n line = 'config\\\\' + line\n if line.endswith('.js') or line.endswith('.jsp'):\n if not line.startswith('html'):\n line = 'html\\\\' + line\n\n newlines.append(line + '\\n')\n\nopen(upfile, 'w').writelines(newlines)\nraw_input('Press Enter to exit')\n","sub_path":"scripts/fixupfile.py","file_name":"fixupfile.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"29586351","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom urllib.request import urlopen, hashlib\nimport sys, os, time\nimport sqlite3\n\nclass bcolors:\n\tGREEN = '\\033[1;39m'\n\tBLUE = '\\033[1;34m'\n\tRED = '\\033[1;31m'\n\nbanner = bcolors.RED + '''\n ___ __ _ __ \n / _ )______ __/ /____ / |/ /__ _ _____ _ \n / _ / __/ // / __/ _ \\/ / _ \\ |/ / _ `/ \n /____/_/ \\_,_/\\__/\\___/_/|_/\\___/___/\\_,_/ \n \n'''\n\ndef hashDB():\n\tos.system('clear')\n\tprint(banner)\n\tprint(bcolors.BLUE + \" 1. \" + bcolors.GREEN + \"Add Single MD5 Hash to Database\")\n\tprint(bcolors.BLUE + \" 2. \" + bcolors.GREEN + \"Add Wordlist to MD5 Database\")\n\tprint(bcolors.BLUE + \" 3. \" + bcolors.GREEN + \"Search MD5 Database\\n\")\n\tprint(bcolors.BLUE + \" [\" + bcolors.GREEN + \"?\" + bcolors.BLUE + \"] Enter \" + bcolors.GREEN + \"#//\" + bcolors.BLUE + \" to return to menu \" + bcolors.BLUE + \"[\" + bcolors.GREEN + \"?\" + bcolors.BLUE + \"]\")\n\n\tmd5option = str(input(bcolors.BLUE + \" Option: \" + bcolors.GREEN))\n\t\t\n\tconn = sqlite3.connect(\"db/bruto.db\")\n\tcursor = conn.cursor()\n\tcursor.execute('''CREATE TABLE IF NOT EXISTS hashes (\n\t\tid\t\tinteger \t\t\tPRIMARY KEY\tAUTOINCREMENT,\n\t\tplain_text\ttext \t\tNOT NULL\tUNIQUE,\n\t\thash\t\ttext\n\t\t);''')\n\tconn.commit()\n\t\t\n\tif md5option == \"1\":\n\t\tplainText = input(bcolors.BLUE + \" Enter Word as Plain-Text: \" + bcolors.GREEN)\n\t\tif plainText == \"\":\n\t\t\tprint(bcolors.BLUE + \" HASH ERROR: \" + bcolors.RED + \" Hash value cannot be empty\")\n\t\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\t\thashDB()\n\t\t\t\n\t\telse:\n\t\t\tmd = hashlib.md5(plainText.encode('utf-8'))\n\t\t\tx = md.hexdigest()\n\n\t\t\ttry:\n\t\t\t\tcursor.execute(\"INSERT INTO hashes (plain_text, hash) VALUES (?,?) \", (plainText, x))\n\t\t\t\tconn.commit()\n\t\t\t\tprint(bcolors.BLUE + \"\\n [\"+ bcolors.GREEN +\"+\" +bcolors.BLUE + \"] Hash Successfully Added [\" + bcolors.GREEN + \"+\" + bcolors.BLUE + \"]\")\n\t\t\t\tprint(bcolors.BLUE + \" Plain-Text: \" + bcolors.GREEN + plainText)\n\t\t\t\tprint(bcolors.BLUE + \" Hash: \" + bcolors.GREEN + x)\n\n\t\t\texcept Exception:\n\t\t\t\tprint(bcolors.BLUE + \" HASH ERROR: \" + bcolors.RED + \"Hash Failed\")\n\t\t\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\t\t\thashDB()\n\t\t\n\t\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\t\thashDB()\n\t\t\t\t\n\telif md5option == \"2\":\n\t\twordlist = input(bcolors.BLUE + \" Local Wordlist: \" + bcolors.GREEN)\n\t\tif wordlist == \"\":\n\t\t\tprint(bcolors.BLUE + \" WORDLIST ERROR: \" + bcolors.RED + \" Wordlist value cannot be empty\")\n\t\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\t\thashDB()\n\t\telse:\n\t\t\ttry:\n\t\t\t\twords = open(wordlist, \"r+\")\n\t\t\texcept Exception:\n\t\t\t\tprint(bcolors.BLUE + \" FILE ERROR: \" + bcolors.RED + \"Failed to open \" + wordlist)\n\t\t\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\t\t\thashDB()\n\n\t\t\tcount = 0\n\n\t\t\tfor word in words:\n\t\t\t\tos.system('clear')\n\t\t\t\tprint(banner)\n\t\t\t\tmd = hashlib.md5(word.encode('utf-8'))\n\t\t\t\tstatus = bcolors.BLUE + \" Hashing: \" + bcolors.GREEN + str(word.replace(\"\\n\", \"\"))\n\t\t\t\tx = md.hexdigest()\n\n\t\t\t\tprint(bcolors.BLUE + \" Updating Database with wordlist: \" + bcolors.GREEN + wordlist)\n\t\t\t\tprint(status + bcolors.BLUE + \"\t\" + bcolors.RED + x)\n\t\t\t\ttry:\n\t\t\t\t\tcursor.execute(\"INSERT INTO hashes (plain_text, hash) VALUES (?,?) \", (word, x))\n\t\t\t\t\tconn.commit()\n\t\t\t\t\tcount += 1\n\t\t\t\texcept sqlite3.IntegrityError:\n\t\t\t\t\tpass\n\t\t\t\n\t\t\tos.system('clear')\n\t\t\tprint(banner)\n\t\t\tprint(bcolors.BLUE + \" Updated Database with wordlist: \" + bcolors.GREEN + wordlist)\n\t\t\tprint(bcolors.BLUE + \" [\"+ bcolors.GREEN + \"+\" +bcolors.BLUE + \"] \" + str(count) + \" Hashes Successfully Added to Database [\" + bcolors.GREEN + \"+\" + bcolors.BLUE + \"]\\n\")\n\t\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\t\thashDB()\n\t\t\n\telif md5option == \"3\":\n\t\thashToSearch = str(input(bcolors.BLUE + \" Hash to Search: \" + bcolors.GREEN))\n\t\tif hashToSearch == \"\":\n\t\t\tprint(bcolors.BLUE + \" HASH ERROR: \" + bcolors.RED + \" Hash value cannot be empty\")\n\t\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\t\thashDB()\n\t\telse:\n\t\t\tcursor.execute(\"SELECT * FROM hashes WHERE hash='\"+hashToSearch+\"';\")\n\t\t\tres = cursor.fetchall()\n\t\t\n\t\t\tfor row in res:\n\t\t\t\tprint(bcolors.BLUE + \"\\n [\" + bcolors.GREEN + \"*\" + bcolors.BLUE + \"] Matching hash has been found [\" + bcolors.GREEN + \"*\" + bcolors.BLUE + \"]\")\n\t\t\t\tprint(bcolors.BLUE + \" Database ID: \" + bcolors.GREEN + str(row[0]))\n\t\t\t\tprint(bcolors.BLUE + \" Plain-Text: \" + bcolors.GREEN + row[1])\n\t\t\t\tprint(bcolors.BLUE + \" Hash: \" + bcolors.GREEN + row[2] + \"\\n\")\n\t\t\n\t\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\t\thashDB()\n\n\telif md5option == \"#//\":\n\t\tfrom brutonova import nova\n\t\tnova()\n\n\telse:\n\t\tprint(bcolors.BLUE + \" OPTION ERROR: \" + bcolors.RED + \" Invalid Option\")\n\t\tinput(bcolors.BLUE + \" Press Enter to Continue...\")\n\t\thashDB()\n","sub_path":"hashMD5.py","file_name":"hashMD5.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"292440967","text":"\ndef findNumRows(matrix):\n\treturn len(matrix)\n\ndef findNumCols(matrix):\n\tif len(matrix) > 0:\n\t\treturn len(matrix[0])\n\telse:\n\t\treturn 0\n\ndef askUserMatrix():\n\tnumRows = int(raw_input(\"Enter the number of rows: \"))\n\tnumCols = int(raw_input(\"Enter the number of cols: \"))\n\tmatrix = []\n\tfor i in range(0, numRows):\n\t\tmatrix.append([])\n\t\tfor j in range(0, numCols):\n\t\t\telement = int (raw_input(\"Enter the number [\" +str(i) + \", \" + str(j) + \"]\"))\n\t\t\tmatrix[i].append(element)\n\treturn matrix\n\t\ndef transposeMatrix(matrix):\n\ttransposed=[]\n\tif len(matrix)>0:\n\t\ttransrow=len(matrix[0])\n\t\ttranscol=len(matrix)\n\t\tfor i in range(0,transrow):\n\t\t\ttransposed.append([])\n\t\t\tfor j in range(0,transcol):\n\t\t\t\ttransposed[i].append(matrix[j][i])\n\telse:\n\t\treturn []\n\treturn transposed\n\n#inputMatrix = askUserMatrix()\n#print(inputMatrix)\n#print transposeMatrix(inputMatrix)\ndef diagonalmatrix(matrix):\n\t#all nondiagonal elements are zero\n\tfor i in range(0, findNumRows(matrix)):\n\t\tfor j in range(0, findNumCols(matrix)):\n\t\t\tif isdiagonal(i,j)==False and matrix[i][j]!=0:\n\t\t\t\treturn False\n\treturn True\n\n\t#if any of the non diagonal element is not zero then return non diagonal\n\n\ndef isdiagonal(i,j):\n\tif i==j:\n\t\treturn True\n\telse:\n\t\treturn False\n\n","sub_path":"RajCodes/matrixutil.py","file_name":"matrixutil.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"53875668","text":"\"\"\"\nPython exposes a terse and intuitive syntax for performing \nslicing on lists and strings. This makes it easy to reference\nonly a portion of a list or string. \n\nThis Stack Overflow answer provides a brief but thorough\noverview: https://stackoverflow.com/a/509295\n\nUse Python's slice syntax to achieve the following:\n\"\"\"\n\na = [2, 4, 1, 7, 9, 6]\n\n# Output the second element: 4:\nfourSlice = slice(1,2)\naSlice = a[fourSlice]\nfor item in aSlice:\n print(int(item))\n\n# Output the second-to-last element: 9\nnineSlice = slice(4, 5)\nsliceTheNine = a[nineSlice]\nfor item in sliceTheNine:\n print(int(item))\n\n# Output the last three elements in the array: [7, 9, 6]\nlastThreeSlice = slice(3, None)\nprint(a[lastThreeSlice])\n\n# Output the two middle elements in the array: [1, 7]\nmiddleSlice = slice(2,4)\nprint(a[middleSlice])\n\n# Output every element except the first one: [4, 1, 7, 9, 6]\nexceptTheFirst = slice(1, None)\nprint(a[exceptTheFirst])\n\n# Output every element except the last one: [2, 4, 1, 7, 9]\nexceptTheLast = slice(0,5)\nprint(a[exceptTheLast])\n\n# For string s...\n\ns = \"Hello, world!\"\n\n# Output just the 8th-12th characters: \"world\"\nworldSlice = slice(7, 12)\nsliceTheWorld = s[worldSlice]\nstringifyWorld = (F\"{sliceTheWorld}\")\nprint(stringifyWorld)","sub_path":"src/07_slices.py","file_name":"07_slices.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"84480983","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 28 15:04:49 2019\n\n@author: r00495138\n\"\"\"\nimport re\ntext = \"I'm a string that contains this characters {}, [], ()\"\nslice = \"this characters \\{}, \\[], \\(\\)\"\nprint([ m for m in re.finditer(slice, text) ])\n#print([ (m.start(0), m.end(0)) for m in re.finditer(slice, text) ])\n\n","sub_path":"04_playground/18_正規表現/learn_re3.py","file_name":"learn_re3.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"153271297","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#########################################################\n# Author: Author \n# Book : Book \n#########################################################\n# File: listagem34.py\n# Description: Exemplo de tela cheia\nimport pygame\n\nfrom pygame.locals import *\nfrom sys import exit \n\nbackground_image_filename = \"distro.jpg\"\n\npygame.init()\nscreen = pygame.display.set_mode((640, 480), 0, 32)\nbackground = pygame.image.load(background_image_filename).convert()\n\nfullscreen = False \n\nwhile True:\n\tfor event in pygame.event.get():\n\t\tif event.type == QUIT:\n\t\t\tpygame.quit()\n\t\t\texit()\n\t\tif event.type == KEYDOWN:\n\t\t\tif event.key == K_f: # Tecla responsavel em mudar a config. da janela\n\t\t\t\tfullscreen = not fullscreen\n\t\t\t\tif fullscreen:\n\t\t\t\t\tscreen = pygame.display.set_mode((640, 480), FULLSCREEN, 32)\n\t\t\t\telse:\n\t\t\t\t\tscreen = pygame.display.set_mode((640, 480), 0, 32)\n\t\tscreen.blit(background, (0,0))\n\t\tpygame.display.update()\n","sub_path":"cap03/listagem34.py","file_name":"listagem34.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"430556456","text":"#@+leo-ver=5-thin\n#@+node:ekr.20181209120925.1: * @file flaskapp.py\n#!flask/bin/python\nunicode = str # Assume python 3\n#@+<< flask imports >>\n#@+node:ekr.20181209122016.1: ** << flask imports >>\nimport sys\nassert sys.version_info >= (3, 0, 0), \"Not Python 3\"\nfrom flask import Flask\nfrom flask import abort\nfrom flask import jsonify\nfrom flask import make_response\nfrom flask import request\n#@-<< flask imports >>\n#@+<< curl reference >>\n#@+node:ekr.20181209131100.1: ** << curl reference >>\n#\n# List all tasks\n#\n# curl -i http://localhost:5000/todo/api/v1.0/tasks\n#\n# List task 2\n#\n# curl -i http://localhost:5000/todo/api/v1.0/tasks/2\n#\n# Delete task 2\n#\n# curl -i -H \"Content-Type: application/json\" -X PUT -d '{\"done\":true}' http://localhost:5000/todo/api/v1.0/tasks/2\n#@-<< curl reference >>\n# \n# pylint: disable=len-as-condition\n# pylint: disable=unidiomatic-typecheck\napp = Flask(__name__)\n#@+<< define tasks >>\n#@+node:ekr.20181209121948.1: ** << define tasks >>\ntasks = [\n {\n 'id': 1,\n 'title': u'Buy groceries',\n 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', \n 'done': False\n },\n {\n 'id': 2,\n 'title': u'Learn Python',\n 'description': u'Need to find a good Python tutorial on the web', \n 'done': False\n }\n]\n#@-<< define tasks >>\n#@+others\n#@+node:ekr.20181212042856.1: ** init\ndef init():\n '''Dummy top-level init for Leo's unit tests and TravisCI.'''\n return False\n#@+node:ekr.20181209123709.1: ** @app.errorhandler(404, 405)\n@app.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': '404: Not found'}), 404)\n \n@app.errorhandler(405)\ndef unauthorized(error):\n return make_response(jsonify({'error': '405: Unauthorized'}), 405)\n \n#@+node:ekr.20181209123711.2: ** @app.route DELETE\n@app.route('/todo/api/v1.0/tasks/', methods=['DELETE'])\ndef delete_task(task_id):\n task = [task for task in tasks if task['id'] == task_id]\n if len(task) == 0:\n abort(404)\n tasks.remove(task[0])\n return jsonify({'result': True})\n#@+node:ekr.20181209123710.1: ** @app.route GET: tasks, tasks/id\n@app.route('/todo/api/v1.0/tasks', methods=['GET'])\ndef get_tasks():\n return jsonify({'tasks': tasks})\n\n@app.route('/todo/api/v1.0/tasks/', methods=['GET'])\ndef get_task(task_id):\n task = [task for task in tasks if task['id'] == task_id]\n if len(task) == 0:\n abort(404)\n return jsonify({'task': task[0]})\n#@+node:ekr.20181209123710.2: ** @app.route POST\n@app.route('/todo/api/v1.0/tasks', methods=['POST'])\ndef create_task():\n if not request.json or not 'title' in request.json:\n abort(400)\n task = {\n 'id': tasks[-1]['id'] + 1,\n 'title': request.json['title'],\n 'description': request.json.get('description', \"\"),\n 'done': False\n }\n tasks.append(task)\n return jsonify({'task': task}), 201\n#@+node:ekr.20181209123711.1: ** @app.route PUT\n@app.route('/todo/api/v1.0/tasks/', methods=['PUT'])\ndef update_task(task_id):\n task = [task for task in tasks if task['id'] == task_id]\n if len(task) == 0:\n abort(404)\n if not request.json:\n abort(400)\n if 'title' in request.json and type(request.json['title']) != unicode:\n abort(400)\n if 'description' in request.json and type(request.json['description']) is not unicode:\n abort(400)\n if 'done' in request.json and type(request.json['done']) is not bool:\n abort(400)\n task[0]['title'] = request.json.get('title', task[0]['title'])\n task[0]['description'] = request.json.get('description', task[0]['description'])\n task[0]['done'] = request.json.get('done', task[0]['done'])\n return jsonify({'task': task[0]})\n\n#@-others\nif __name__ == '__main__':\n app.run(debug=True)\n#@-leo\n","sub_path":"leo/plugins/flaskapp.py","file_name":"flaskapp.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"91941769","text":"# -*- coding: utf-8 -*-\n\nimport sys, os\nimport numpy as np\nimport pandas as pd\nimport math\n\nimport chainer\nfrom chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils\nfrom chainer import Link, Chain, ChainList\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer.functions.loss.vae import gaussian_kl_divergence\n\nimport six\n\n\nclass EncodeDecode():\n def __init__(self, model_file, n_latent=1000, input_size=96, input_ch=3, output_ch=512):\n '''\n Arguments:\n model_file : 学習ずみモデルファイルのパス付きファイル名 [String]\n n_latent : 中間表現ベクトルzの次元数 [Integer]\n input_size : 入力画像のサイズ(正方形画像を想定) [Integer]\n input_ch : 入力画像のカラーチャネル [Integer]\n output_ch : Convolutionネットワークの最大チャネルサイズ [Integer]\n '''\n self.n_latent = n_latent\n self.input_size = input_size\n self.input_ch = input_ch\n self.output_ch = output_ch\n self.model_file = model_file\n self.model = VAE(n_latent=n_latent, input_size=input_size, input_ch=input_ch, output_ch=output_ch)\n serializers.load_hdf5(self.model_file, self.model)\n \n def getLatentVector(self, images):\n '''\n 中間表現ベクトルを取得する\n arguments:\n images : 画像データ.\n サイズ : [N, ch, width, height]\n N=画像枚数, ch=チャネル(カラーの場合3)\n 0~1に正規化されたデータ\n 型 : chainer.Variable()\n return:\n latent_vector : n_latent次元のベクトル\n '''\n mu, sig = self.model.encode(images)\n self.mu = mu\n self.sig = sig\n return mu\n \n def getReconstructImage(self, z):\n y = self.model.decode(z)\n return y\n \n\nclass VAE(chainer.Chain):\n \"\"\"AutoEncoder\"\"\"\n def __init__(self, n_latent=1000, input_size=128, input_ch=3, output_ch=512):\n '''\n Arguments:\n n_latent : 中間表現ベクトルzの次元数 [Integer]\n input_size : 入力画像のサイズ(正方形画像を想定) [Integer]\n input_ch : 入力画像のカラーチャネル [Integer]\n output_ch : Convolutionネットワークの最大チャネルサイズ [Integer]\n '''\n self.input_ch = input_ch\n self.output_ch = output_ch\n self.input_size = input_size\n self.out_size = input_size/(2**4)\n super(VAE, self).__init__(\n ## ネットワーク構造の定義\n # encoder\n c0 = L.Convolution2D(self.input_ch, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.input_ch)),\n c1 = L.Convolution2D(self.output_ch/8, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),\n c2 = L.Convolution2D(self.output_ch/4, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),\n c3 = L.Convolution2D(self.output_ch/2, self.output_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),\n l4_mu = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),\n l4_var = L.Linear(self.out_size*self.out_size*self.output_ch, n_latent, wscale=0.02*math.sqrt(self.out_size*self.out_size*self.output_ch)),\n bne0 = L.BatchNormalization(self.output_ch/8),\n bne1 = L.BatchNormalization(self.output_ch/4),\n bne2 = L.BatchNormalization(self.output_ch/2),\n bne3 = L.BatchNormalization(self.output_ch),\n # decoder\n l0z = L.Linear(n_latent, self.out_size*self.out_size*self.output_ch, wscale=0.02*math.sqrt(n_latent)),\n dc1 = L.Deconvolution2D(self.output_ch, self.output_ch/2, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch)),\n dc2 = L.Deconvolution2D(self.output_ch/2, self.output_ch/4, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/2)),\n dc3 = L.Deconvolution2D(self.output_ch/4, self.output_ch/8, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/4)),\n dc4 = L.Deconvolution2D(self.output_ch/8, self.input_ch, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*self.output_ch/8)),\n bnd0l = L.BatchNormalization(self.out_size*self.out_size*self.output_ch),\n bnd0 = L.BatchNormalization(self.output_ch),\n bnd1 = L.BatchNormalization(self.output_ch/2),\n bnd2 = L.BatchNormalization(self.output_ch/4),\n bnd3 = L.BatchNormalization(self.output_ch/8),\n )\n\n def __call__(self, x, sigmoid=True):\n \"\"\"AutoEncoder\"\"\"\n # 下記、encodeとdecodeの中身をこの中に書いても良いがencodeとdecodeは他でも使うので再利用性を高めるために\n return self.decode(self.encode(x)[0], sigmoid)\n \n def encode(self, x, test=False):\n # 推論モデル, 中間表現のベクトルqを学習\n h = F.relu(self.bne0(self.c0(x)))\n h = F.relu(self.bne1(self.c1(h), test=test))\n h = F.relu(self.bne2(self.c2(h), test=test))\n h = F.relu(self.bne3(self.c3(h), test=test))\n mu = (self.l4_mu(h))\n var = (self.l4_var(h))\n return mu, var\n\n def decode(self, z, sigmoid=True, test=False):\n # 中間表現ベクトルqを入力として(z), 画像を生成\n h = F.reshape(F.relu(self.bnd0l(self.l0z(z), test=test)), (z.data.shape[0], self.output_ch, self.out_size, self.out_size))\n h = F.relu(self.bnd1(self.dc1(h), test=test))\n h = F.relu(self.bnd2(self.dc2(h), test=test))\n h = F.relu(self.bnd3(self.dc3(h), test=test))\n x = (self.dc4(h))\n if sigmoid:\n return F.sigmoid(x)\n else:\n return x\n\n def get_loss_func(self, C=1.0, k=1, train=True):\n \"\"\"Get loss function of VAE.\n Args:\n C (int): Usually this is 1.0. Can be changed to control the\n second term of ELBO bound, which works as regularization.\n k (int): Number of Monte Carlo samples used in encoded vector.\n train (bool): If true loss_function is used for training.\n \"\"\"\n def lf(x):\n mu, ln_var = self.encode(x)\n batchsize = len(mu.data)\n # reconstruction loss\n rec_loss = 0\n for l in six.moves.range(k):\n z = F.gaussian(mu, ln_var)\n rec_loss += F.bernoulli_nll(x, self.decode(z, sigmoid=False)) / (k * batchsize)\n #rec_loss += F.mean_squared_error(x, self.decode(z)) / (k)\n self.rec_loss = rec_loss\n # reguralization\n self.loss = self.rec_loss + C * gaussian_kl_divergence(mu, ln_var) / batchsize\n return self.loss\n return lf\n","sub_path":"chainer-VAEGAN/model_VAE.py","file_name":"model_VAE.py","file_ext":"py","file_size_in_byte":6982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"504613938","text":"\"\"\"Chat Messages.\"\"\"\n\n\ndef parse_chat(line, timestamp, players, diplomacy_type=None, origination='game'):\n \"\"\"Initalize.\"\"\"\n data = {\n 'timestamp': timestamp,\n 'origination': origination\n }\n if line.find('Voobly: Ratings provided') > 0:\n _parse_ladder(data, line)\n elif line.find('Voobly') == 3:\n _parse_voobly(data, line)\n elif line.find('') > 0:\n _parse_rating(data, line)\n elif line.find('@#0<') == 0:\n _parse_injected(data, line)\n else:\n _parse_chat(data, line, players, diplomacy_type)\n return data\n\n\ndef _parse_ladder(data, line):\n start = line.find(\"'\") + 1\n end = line.find(\"'\", start)\n data.update({\n 'type': 'ladder',\n 'ladder': line[start:end]\n })\n\n\ndef _parse_voobly(data, line):\n message = line[11:]\n data.update({\n 'type': 'voobly',\n 'message': message\n })\n\n\ndef _parse_rating(data, line):\n player_start = line.find('>') + 2\n player_end = line.find(':', player_start)\n player = line[player_start:player_end]\n rating = int(line[player_end + 2:len(line)])\n data.update({\n 'type': 'rating',\n 'player': player,\n 'rating': rating\n })\n\ndef _parse_injected(data, line):\n prefix = ''\n if line.find('') > 0:\n line = line.replace('', '', 1)\n prefix = ';'\n origination_start = line.find('<') + 1\n origination_end = line.find('>', origination_start)\n origination = line[origination_start:origination_end]\n name_end = line.find(':', origination_end)\n name = line[origination_end + 2:name_end]\n message = line[name_end + 2:]\n data.update({\n 'type': 'injected',\n 'origination': origination.lower(),\n 'name': name,\n 'message': '{}{}'.format(prefix, message)\n })\n\n\ndef _parse_chat(data, line, players, diplomacy_type):\n player_start = line.find('#') + 2\n player_end = line.find(':', player_start)\n player = line[player_start:player_end]\n if data['timestamp'] == 0:\n group = 'All'\n elif diplomacy_type == 'TG':\n group = 'Team'\n else:\n group = 'All'\n if player.find('>') > 0:\n group = player[1:player.find('>')]\n player = player[player.find('>') + 1:]\n if group.lower() in ['todos', 'всем', 'tous']:\n group = 'All'\n elif group.lower() in ['隊伍', 'squadra']:\n group = 'Team'\n message = line[player_end + 2:]\n number = None\n for player_h in players:\n if player_h['name'] == player:\n number = player_h['number']\n data.update({\n 'type': 'chat',\n 'player_number': number,\n 'message': message.strip(),\n 'audience': group.lower()\n })\n","sub_path":"mgz/summary/chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"528018663","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport random\n\nclass Personnage:\n def __init__(self, name):\n self.name = name\n self.maxhealth = 100\n self.health = self.maxhealth\n self.basicattaq = 10\n self.jts = 20\n self.abo = 1\n self.abolvl = 1\n self.weap = None\n self.curweap = None\n\n @property\n def attaq(self):\n attaq = self.basicattaq\n if self.curweap == \"Epée Rouillée\":\n attaq += 0\n if self.curweap == \"Dague\":\n attaq += 5\n if self.curweap == \"Epée Large\":\n attaq += 15\n return attaq\n\n # def level(self):\n # while self.xp >= self.xplvl:\n # self.lvl += 1\n # self.xp = self.xp - self.xplvl\n # self.xplvl = round(self.xplvl) *1.5\n\n\nclass Avatar(Personnage):\n def __init__(self, name):\n self.name = name\n self.maxhealth = 100\n self.health = self.maxhealth\n self.basicattaq = 10\n self.jts = 20\n self.abo = 100\n self.lvl = 1\n self.abolvl = 1\n self.serum = 2\n self.weap = \"Mains Nues\"\n self.curweap = \"Maines Nues\"\n\n def quitter():\n os.system(\"clear\")\n sys.exit()\n\n def fuir():\n os.system(\"clear\")\n runnum = random.randint(1, 3)\n if runnum == 1:\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print (\" Vous parvenez à fuir ! \")\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n option = input(\"Appuyez sur une touche pour continuer... \")\n start()\n else:\n os.system(\"clear\")\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print (\" Vous n'arrivez pas à vous échapper, vous devez combattre. \")\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n option = input(\"Appuyez sur une touche pour continuer... \")\n adv_attaque = adversaire.attaq\n avatar_actif.health -= adv_attaque\n if avatar_actif.health <= 0:\n dead()\n else:\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print (\" L'adversaire vous attaque dans le dos pour %i dégâts ! \" % adv_attaque)\n attaq()\n\n def serum():\n os.system(\"clear\")\n if avatar_actif.serum <= 0:\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print (\" Vous n'avez pas de serum.\")\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\")\n option = input(\"Appuyez sur une touche pour continuer... \")\n os.system(\"clear\")\n else:\n avatar_actif.health +=50\n if avatar_actif.health > avatar_actif.maxhealth:\n avatar_actif.health = avatar_actif.maxhealth\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print (\" Grace au serum, vous êtes de nouveau en pleine santé !\")\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n else:\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print (\" Le serum restaure 50 points de santé.\")\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n avatar_actif.serum -= 1\n option = input(\"Appuyez sur une touche pour continuer... \")\n os.system(\"clear\")\n attaq()\n\n def attaquer():\n os.system(\"clear\")\n PAttack = random.uniform(avatar_actif.attaq/2, avatar_actif.attaq)\n adv_attaque = random.uniform(adversaire.attaq/2, adversaire.attaq)\n if PAttack == avatar_actif.attaq/2:\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print (\" Raté !\")\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n else:\n adversaire.health -= PAttack\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print (\" Vous infligez %i dégâts !\\n\" % PAttack)\n if adversaire.health < 0:\n os.system(\"clear\")\n win()\n if adv_attaque == adversaire.attaq/2:\n print (\" L'adversaire rate son coup !\")\n print (\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n else:\n avatar_actif.health -= adv_attaque\n print (\" L'adversaire vous blesse pour %i dégâts !\" % adv_attaque)\n if avatar_actif.health < 0:\n dead()\n else:\n attaq()\n\n COMMANDES = {\n \"q\" : (\"Quitter\", quitter),\n \"a\" : (\"Attaquer\", attaquer),\n \"f\" : (\"Fuir\", fuir),\n \"s\" : (\"Serum\", serum)\n }\n\n\n # option = input(\"Votre choix -> \")\n # os.system(\"clear\")\n # if option ==\"1\":\n # attaq()\n # elif option == \"2\":\n # drinkpot()\n # elif option == \"3\":\n # fuir()\n # else:\n # attaq()\n\n\n\n\nclass Combattant(Avatar):\n def __init__():\n self.name = name\n self.maxhealth = 100\n self.health = self.maxhealth\n self.basicattaq = 10\n self.jts = 20\n self.abo = 100\n self.abolvl = 1\n self.serum = 2\n self.weap = None\n self.curweap = None\n return Combattant\n\n # def marchand(self):\n # return marchand\n #\n #\n # def esclave(self):\n # return esclave\n","sub_path":"avatar.py","file_name":"avatar.py","file_ext":"py","file_size_in_byte":5995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"6541921","text":"#1 milyondan küçük haangi sayı için collatz zinciri vardır?\n\nm = 2\nmaksimum = 0\nCollatz = 0\nwhile (m<1000000):\n n = m\n zincir = [n]\n while(n!=1):\n if(n%2==0):\n n = n/2\n else:\n n = 3*n+1\n zincir.append(n)\n if(len(zincir)>maksimum):\n maksimum = len(zincir)\n Collatz = m\n m += 1\nprint(Collatz)\n","sub_path":"PYTHON/DERS10-46.py","file_name":"DERS10-46.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"121871757","text":"from django.db import models\nfrom django.utils import timezone\n\n# Create your models here.\n\n\nclass BookJournalBase(models.Model):\n name = models.CharField(max_length=50)\n price = models.IntegerField(default=100)\n description = models.TextField(max_length=500)\n created_at = models.DateField(default=timezone.now)\n\n class Meta:\n abstract = True\n\n\nclass Book(BookJournalBase):\n num_pages = models.IntegerField(default=300)\n genre = models.CharField(max_length=50)\n\n class Meta:\n verbose_name = 'Book'\n verbose_name_plural = 'Books'\n\n def __str__(self):\n return self.name\n\n def to_json(self):\n return{\n 'id': self.id,\n 'name': self.name,\n 'price': self.price,\n 'description': self.description\n }\n\n\nclass Journal(BookJournalBase):\n BULLET = 'BT'\n FOOD = 'FT'\n TRAVEL = 'TL'\n SPORT = 'ST'\n JOURNAL_TYPE = (\n (BULLET, 'Bullet'),\n (FOOD, 'Foot'),\n (TRAVEL, 'Travel'),\n (SPORT, 'Sport'),\n )\n type = models.CharField(max_length=50, choices=JOURNAL_TYPE, default=SPORT)\n\n publisher = models.CharField(max_length=50)\n\n class Meta:\n verbose_name = 'Journal'\n verbose_name_plural = 'Journals'\n\n def __str__(self):\n return self.name\n\n def to_json(self):\n return{\n 'id': self.id,\n 'name': self.name,\n 'price': self.price,\n 'description': self.description\n }","sub_path":"midtermProject/main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"652857830","text":"\"\"\"Entry point to Zoyra.\"\"\"\nimport json\nimport logging\n\nfrom google.appengine.ext import deferred, ndb\n\nfrom flask import Flask, request\nfrom model.policymodel import PolicyModel\nfrom model.schedulesmodel import SchedulesModel\nfrom tasks import policy_tasks, schedule_tasks\nfrom util import tz\n\nAPI_VERSION = '/api/v1'\napp = Flask(__name__)\n\n\n@app.route('/tasks/schedule', methods=['GET'])\ndef schedule():\n \"\"\"\n Invoked by Cron scheduler (see cron.yaml).\n Schedules all defined policies for evaluation.\n Returns:\n\n \"\"\"\n logging.debug('GET /tasks/schedule started...')\n\n keys = PolicyModel.query().fetch(keys_only=True)\n logging.info('Found %s policies', len(keys))\n\n for key in keys:\n logging.info('Creating policy_checker deferred task for policy %s', key.id())\n deferred.defer(schedule_tasks.policy_checker, key.id())\n\n logging.debug('GET /tasks/schedule ended')\n return 'ok', 200\n\n\n@app.route('/tasks/change_state', methods=['GET'])\ndef change_state():\n \"\"\"\n Invoked by policy_tasks.policy_checker().\n Initiate change state.\n Returns:\n\n \"\"\"\n logging.debug('GET /tasks/change_state started...')\n\n policy = request.args['policy']\n state = request.args['state']\n\n logging.info('Change state requested for policy: \\'%s\\', state: \\'%s\\'', policy, state)\n policy_tasks.change_state(policy, state)\n\n logging.debug('GET /tasks/change_state ended')\n return 'ok', 200\n\n\n@app.route(API_VERSION + '/time_zones', methods=['GET'])\ndef time_zones():\n \"\"\"\n Get all time zones.\n :return: all time zone in the world wide world.\n \"\"\"\n return json.dumps({'Timezones': tz.get_all_timezones()})\n\n\n@app.route(API_VERSION + '/add_schedule', methods=['POST'])\ndef add_schedule():\n \"\"\"\n Add a schedule.\n Returns:\n\n \"\"\"\n schedules_model = SchedulesModel()\n schedules_model.Schedule = {\n 'dtype': request.json['dtype'],\n 'Corder': request.json['Corder'],\n 'Shape': request.json['Shape'],\n '__ndarray__': request.json['__ndarray__']\n }\n\n schedules_model.Name = request.json['name']\n schedules_model.Timezone = request.json['timezone']\n schedules_model.key = ndb.Key('SchedulesModel', request.json['name'])\n schedules_model.put()\n return 'ok', 200\n\n\n@app.route(API_VERSION + '/get_schedule', methods=['GET'])\ndef get_schedule():\n \"\"\"\n Get a schedule.\n Returns: schedule json\n\n \"\"\"\n name = request.args.get('schedule')\n res = SchedulesModel.query(SchedulesModel.Name == name).get()\n if not res:\n return 'not found', 404\n schedule = {}\n schedule.update({'name': res.Name})\n schedule.update(res.Schedule)\n schedule.update({'timezone': res.Timezone})\n logging.debug(json.dumps(res.Schedule))\n return json.dumps(schedule)\n\n\n@app.route(API_VERSION + '/list_schedules', methods=['GET'])\ndef list_schedules():\n \"\"\"\n Get all schedules.\n Returns: A list of schedules\n\n \"\"\"\n keys = SchedulesModel.query().fetch(keys_only=True)\n schedules_list = []\n for key in keys:\n schedules_list.append(key.id())\n return json.dumps(schedules_list)\n\n\n@app.route(API_VERSION + '/del_schedule', methods=['GET'])\ndef del_schedule():\n \"\"\"\n Delete a schedule.\n Returns:\n\n \"\"\"\n name = request.args.get('schedule')\n res = SchedulesModel.query(SchedulesModel.Name == name).get()\n if not res:\n return 'not found', 404\n policy = PolicyModel.query(PolicyModel.Schedule == name).get()\n if policy:\n return 'Forbidden policy {} is using the schedule'.format(\n policy.Name), 403\n res.key.delete()\n return 'ok', 200\n\n\n@app.route(API_VERSION + '/add_policy', methods=['POST'])\ndef add_policy():\n \"\"\"\n Add policy.\n Returns:\n\n \"\"\"\n logging.debug(json.dumps(request.json))\n name = request.json['name']\n projects = request.json['projects']\n clusters = request.json['clusters']\n nodePools = request.json['nodePools']\n schedule_name = request.json['schedulename']\n\n res = SchedulesModel.query(SchedulesModel.Name == schedule_name).get()\n if not res:\n return 'Schedule \\'{}\\' not found'.format(schedule_name), 404\n\n policy_model = PolicyModel()\n policy_model.Name = name\n policy_model.Projects = projects\n policy_model.Clusters = clusters\n policy_model.NodePools = nodePools\n policy_model.Schedule = schedule_name\n policy_model.key = ndb.Key('PolicyModel', name)\n policy_model.put()\n return 'ok', 200\n\n\n@app.route(API_VERSION + '/get_policy', methods=['GET'])\ndef get_policy():\n \"\"\"\n Get policy.\n Returns: policy json\n\n \"\"\"\n name = request.args.get('policy')\n res = PolicyModel.query(PolicyModel.Name == name).get()\n logging.debug(res)\n if not res:\n return 'not found', 404\n policy = {}\n policy.update({'name': res.Name})\n policy.update({'projects': res.Projects})\n policy.update({'clusters': res.Clusters})\n policy.update({'nodePools': res.NodePools})\n policy.update({'schedulename': res.Schedule})\n return json.dumps(policy)\n\n\n@app.route(API_VERSION + '/list_policies', methods=['GET'])\ndef list_policies():\n \"\"\"\n Get all polices.\n Returns: List of policies\n\n \"\"\"\n keys = PolicyModel.query().fetch(keys_only=True)\n policies_list = []\n for key in keys:\n policies_list.append(key.id())\n return json.dumps(policies_list)\n\n\n@app.route(API_VERSION + '/del_policy', methods=['GET'])\ndef del_policy():\n \"\"\"\n Delete a policy\n Returns:\n\n \"\"\"\n name = request.args.get('policy')\n res = PolicyModel.query(PolicyModel.Name == name).get()\n if not res:\n return 'not found', 404\n res.key.delete()\n return 'ok', 200\n\n\n@app.route('/')\ndef index():\n \"\"\"\n Main Page\n :return:\n \"\"\"\n return 'ok', 200\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"490723321","text":"# PIZZA ORDERING SOFTWARE\r\n# -- can I get 12 credits?\r\n# https://github.com/totenk0pf/ordering-software-3000\r\n\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox, simpledialog\r\nfrom tkinter.filedialog import askopenfilename, asksaveasfilename\r\n\r\nimport os\r\nimport json\r\n\r\nroot = Tk()\r\nroot.resizable(False, False)\r\n\r\n# Defining variables\r\nfirstname = ''\r\nlastname = ''\r\nphonein1 = ''\r\nphonein2 = ''\r\nphonein3 = ''\r\naddress = ''\r\n\r\n# Defining functions\r\ndef OpenFile():\r\n name = askopenfilename(initialdir=\"C:/Users/Admin/Desktop\",\r\n filetypes =((\"Text File\", \"*.txt\"),(\"All Files\",\"*.*\")),\r\n title = \"Choose a file.\"\r\n )\r\n print (name)\r\n try:\r\n with open(name,'r') as UseFile:\r\n print(UseFile.read())\r\n except:\r\n print(\"No file exists\")\r\n\r\ndef SaveFile():\r\n name = asksaveasfilename(initialdir=\"C:/Users/Admin/Desktop\",\r\n filetypes =((\"Text File\", \"*.txt\"),(\"All Files\",\"*.*\")),\r\n title = \"Choose a file.\"\r\n )\r\n\r\ndef aboutDisplay():\r\n about = Toplevel(root)\r\n about.title('About')\r\n pyzza = PhotoImage(file='pyzza.png')\r\n showPyzza = Label(about, image=pyzza)\r\n showPyzza.grid(column=1, row=1)\r\n about.lift(root)\r\n\r\ntitle = root.title(\"ultimate ordering software 3000\")\r\n\r\n# Top menu bar\r\nmenubar= Menu(root)\r\n\r\nfilemenu = Menu(menubar, tearoff=0)\r\nfilemenu.add_command(label=\"Open\", command=OpenFile)\r\nfilemenu.add_command(label=\"Save\", command=SaveFile)\r\nfilemenu.add_command(label=\"Exit\", command=root.quit)\r\nmenubar.add_cascade(label=\"File\", menu=filemenu)\r\n\r\ndef openConfig():\r\n ConfigWindow = Toplevel(root)\r\n\r\noptionmenu = Menu(menubar, tearoff=0)\r\n#optionmenu.add_command(Label=\"Configurations\", command=openConfig)\r\nmenubar.add_cascade(label=\"Options\", menu=optionmenu)\r\n\r\ndef openManual():\r\n os.system(\"start \\\"\\\" https://github.com/totenk0pf/ordering-software-3000/blob/master/README.md\")\r\n\r\nhelpmenu = Menu(menubar, tearoff=0)\r\nhelpmenu.add_command(label=\"Manual\", command=openManual)\r\nhelpmenu.add_command(label=\"About\", command=aboutDisplay)\r\nmenubar.add_cascade(label=\"Help\", menu=helpmenu)\r\n\r\n# Validation\r\ndef only_characters(char):\r\n return char.isalpha()\r\n\r\ndef only_numbers(char):\r\n return char.isdigit()\r\n\r\n# LETTERS ONLY\r\nccmd = root.register(only_characters)\r\n\r\n# NUMBERS ONLY\r\nncmd = root.register(only_numbers)\r\n\r\n# Main GUI\r\n# Customer's details frame\r\nCustomerFrame = LabelFrame(root, text=\"Customer's details\")\r\nCustomerFrame.grid(column=1, row=1, ipadx=10, ipady=10, padx=(20), pady=(10,5), sticky=\"ew\")\r\n\r\nfirstname = StringVar()\r\nlastname = StringVar()\r\n\r\n# Input customer's name\r\nNameLabel = Label(CustomerFrame, text=\"Customer's name:\")\r\nNameLabel.grid(column=1, row=1, padx=(20,10), pady=(15,5))\r\nFirstNameInput = Entry(CustomerFrame, textvariable=firstname, validate=\"key\", validatecommand=(ccmd, '%S'))\r\nFirstNameInput.grid(column=2, row=1, padx=(0,10), pady=(15,5), sticky=\"ew\")\r\nLastNameInput = Entry(CustomerFrame, textvariable=lastname, validate=\"key\", validatecommand=(ccmd, '%S'))\r\nLastNameInput.grid(column=3, row=1, padx=(0,10), pady=(15,5), sticky=\"ew\")\r\n\r\n# Input customer's phone number\r\nroot.columnconfigure(2, weight=0)\r\nroot.columnconfigure(3, weight=3)\r\nroot.columnconfigure(4, weight=4)\r\n\r\n# Defining text variables\r\nphonein1 = StringVar()\r\nphonein2 = StringVar()\r\nphonein3 = StringVar()\r\n\r\nPhoneLabel = Label(CustomerFrame, text=\"Phone number:\")\r\nPhoneLabel.grid(column=1, row=2, padx=(20,10), pady=5, sticky=\"ew\")\r\nPhoneInput1 = Entry(CustomerFrame, textvariable=phonein1, validate=\"key\", validatecommand=(ncmd, '%S'))\r\nPhoneInput1.grid(column=2, row=2, padx=(0,10), pady=5, sticky=\"ew\")\r\nPhoneInput2 = Entry(CustomerFrame, textvariable=phonein2, validate=\"key\", validatecommand=(ncmd, '%S'))\r\nPhoneInput2.grid(column=3, row=2, padx=(0,10), pady=5, sticky=\"ew\")\r\nPhoneInput3 = Entry(CustomerFrame, textvariable=phonein3, validate=\"key\", validatecommand=(ncmd, '%S'))\r\nPhoneInput3.grid(column=4, row=2, padx=(0,0), pady=5, sticky=\"ew\")\r\n\r\n# PHONEINPUT SWITCH\r\ndef phone1Limit(PhoneInput1):\r\n if len(phonein1.get()) == 3:\r\n PhoneInput2.focus()\r\ndef phone2Limit(PhoneInput2):\r\n if len(phonein2.get()) == 3:\r\n PhoneInput3.focus()\r\ndef phone3Limit(PhoneInput3):\r\n if len(phonein3.get()) == 3:\r\n DeliveryEntry.focus()\r\n\r\nphonein1.trace('w', lambda *args:phone1Limit(PhoneInput1))\r\nphonein2.trace('w', lambda *args:phone2Limit(PhoneInput2))\r\nphonein3.trace('w', lambda *args:phone3Limit(PhoneInput3))\r\n\r\n# Delivery/Pickup\r\ndpCheck = IntVar()\r\ndpCheck.set(0)\r\n\r\nDPLabel = Label(CustomerFrame, text=\"Delivery/Pickup:\")\r\nDPLabel.grid(column=1, row=3, padx=(20,10), pady=5)\r\n\r\naddress = StringVar()\r\n\r\nDeliveryAddress = Label(CustomerFrame, text=\"Customer's address:\")\r\nDeliveryAddress.grid(column=1, row=4, padx=(20,10), pady=5, sticky=\"ew\")\r\nDeliveryEntry = Entry(CustomerFrame, textvariable=address)\r\nDeliveryEntry.grid(column=2, columnspan=3, row=4, padx=(0,0), pady=5, sticky=\"ew\")\r\n\r\ndef showAddress():\r\n if dpCheck.get() == 1:\r\n DeliveryAddress.grid()\r\n DeliveryEntry.grid()\r\n elif dpCheck.get() == 0:\r\n DeliveryAddress.grid_remove()\r\n DeliveryEntry.grid_remove()\r\n\r\nDeliveryCheck = Checkbutton(CustomerFrame, text=\"Delivery\", variable=dpCheck, onvalue=1, offvalue=0, command=showAddress)\r\nDeliveryCheck.grid(column=2, row=3, padx=(0,10), pady=5)\r\nPickupCheck = Checkbutton(CustomerFrame, text=\"Pickup\", variable=dpCheck, onvalue=0, offvalue=1, command=showAddress)\r\nPickupCheck.grid(column=4, row=3, padx=(0,10), pady=5)\r\n\r\nDeliveryCheck.select()\r\n\r\ndef deselect():\r\n if dpCheck.get() == 1:\r\n PickupCheck.deselect()\r\n elif dpCheck.get() == 0:\r\n DeliveryCheck.deselect()\r\n\r\n# Pizza ordering frame\r\nPizzaFrame = LabelFrame(root, text=\"Order\")\r\nPizzaFrame.grid(column=1, row=5, ipadx=10, ipady=10, padx=(20,20), pady=(0,5), sticky=\"ew\")\r\nButtonFrame = Frame(PizzaFrame)\r\nButtonFrame.grid(column=2, row=1, padx=(20))\r\n\r\nPizzaList = ttk.Treeview(PizzaFrame, height=14)\r\nPizzaList[\"columns\"]=(\"one\")\r\nPizzaList.column(\"#0\", width=150, minwidth=150, stretch=NO)\r\nPizzaList.column(\"one\", width=50, minwidth=50, stretch=NO)\r\nPizzaList.heading(\"#0\", text=\"Name\", anchor=\"w\")\r\nPizzaList.heading(\"one\", text=\"Price\", anchor=\"w\")\r\n\r\n# INSERT LIST OF PIZZA\r\n# REGULAR PIZZAS\r\nRegularPizza = PizzaList.insert(\"\", 1, \"RGP\", text=\"Regular Pizzas\")\r\nPizzaList.item(RegularPizza, open=True)\r\nPizzaList.insert(RegularPizza, \"end\", 'HP', text=\"Hawaiian Pizza\", values=(\"$8.50\"))\r\nPizzaList.insert(RegularPizza, \"end\", 'SBP', text=\"Steak & Bacon Pizza\", values=(\"$8.50\"))\r\nPizzaList.insert(RegularPizza, \"end\", 'PP', text=\"Pepperoni Pizza\", values=(\"$8.50\"))\r\nPizzaList.insert(RegularPizza, \"end\", 'CP', text=\"Cheese Pizza\", values=(\"$8.50\"))\r\nPizzaList.insert(RegularPizza, \"end\", 'BOP', text=\"Beef & Onion Pizza\", values=(\"$8.50\"))\r\nPizzaList.insert(RegularPizza, \"end\", 'VP', text=\"Veggie Pizza\", values=(\"$8.50\"))\r\nPizzaList.insert(RegularPizza, \"end\", 'NYP', text=\"New Yorker Pizza\", values=(\"$8.50\"))\r\n# GOURMET PIZZAS\r\nGourmetPizza = PizzaList.insert(\"\", 2, \"GP\", text=\"Gourmet Pizzas\")\r\nPizzaList.item(GourmetPizza, open=True)\r\nPizzaList.insert(GourmetPizza, \"end\", 'RHP', text=\"Ramadan Halal Pizza\", values=(\"$13.50\"))\r\nPizzaList.insert(GourmetPizza, \"end\", 'POP', text=\"Pineapple Only Pizza\", values=(\"$13.50\"))\r\nPizzaList.insert(GourmetPizza, \"end\", 'COP', text=\"Crust Only Pizza\", values=(\"$13.50\"))\r\nPizzaList.insert(GourmetPizza, \"end\", 'PT', text=\"Pizza that's been in a tomb for 1000 years\", values=(\"$13.50\"))\r\nPizzaList.insert(GourmetPizza, \"end\", 'RP', text=\"Rice Pizza\", values=(\"$13.50\"))\r\nPizzaList.grid(column=1, row=1, padx=(20,0), pady=(10,0), sticky=\"ew\")\r\n\r\nTotalCost = 0\r\n\r\nOrderList = ttk.Treeview(PizzaFrame, height=14)\r\nOrderList[\"columns\"]=(\"one\")\r\nOrderList.column(\"#0\", width=150, minwidth=150, stretch=NO)\r\nOrderList.column(\"one\", width=50, minwidth=50, stretch=NO)\r\nOrderList.heading(\"#0\", text=\"Name\", anchor=\"w\")\r\nOrderList.heading(\"one\", text=\"Amount\", anchor=\"w\")\r\nOrderList.grid(column=3, row=1, padx=0, pady=(10,0), sticky=\"ew\")\r\nRegularPizza = OrderList.insert(\"\", 1, \"RGP\", text=\"Regular Pizzas\")\r\nOrderList.item(RegularPizza, open=True)\r\nGourmetPizza = OrderList.insert(\"\", 2, \"GP\", text=\"Gourmet Pizzas\")\r\nOrderList.item(GourmetPizza, open=True)\r\nTotalRow = OrderList.insert(\"\", 3, \"TT\", text=\"Total cost:\", values=(TotalCost))\r\n\r\nListAmountRegular = []\r\nListAmountGourmet = []\r\nTotalAmount = 0\r\n\r\ndynamicIID = 0\r\n\r\ndef addPizza():\r\n # DEPRECATED - MIGHT USE IN THE NEAR FUTURE\r\n ''' New window - insert amount\r\n AddWindow = Toplevel(root)\r\n AddLabel = Label(AddWindow, text=\"Please input amount of pizzas:\")\r\n AddLabel.pack(padx=20, pady=10)\r\n AddEntry = Entry(AddWindow, textvariable=phonein1, validate=\"key\", validatecommand=(ncmd, '%S'))\r\n AddEntry.pack(padx=20, pady=(0,10))\r\n AddOK = Button(AddWindow, text=\"OK\")\r\n AddOK.pack(side=LEFT, padx=(20,0), pady=10, ipadx=20)\r\n CancelButton = Button(AddWindow, text=\"Cancel\", command=AddWindow.\r\n CancelButton.pack(side=RIGHT, padx=(0,20), pady=10, ipadx=10)\r\n AddWindow.resizable(FALSE, FALSE)\r\n AddWindow.title(\"Amount\")\r\n AddWindow.lift(root) '''\r\n # Add the selected pizza\r\n global ListAmountRegular\r\n global ListAmountGourmet\r\n global TotalAmount\r\n global TotalCost\r\n AddPrompt = simpledialog.askinteger(\"Amount\", \"Enter the desired amount:\")\r\n if AddPrompt > 5:\r\n WarnMsg = messagebox.showwarning(\"Invalid\", \"Maximum amount of pizzas allowed is 5.\")\r\n if AddPrompt <= 5:\r\n selectedItem = PizzaList.focus()\r\n returnItem = PizzaList.item(selectedItem)\r\n getItemName = returnItem.get('text')\r\n global dynamicIID\r\n if PizzaList.parent(selectedItem) == RegularPizza:\r\n OrderList.insert(RegularPizza, \"end\", dynamicIID, text=getItemName, values=AddPrompt)\r\n elif PizzaList.parent(selectedItem) == GourmetPizza:\r\n OrderList.insert(GourmetPizza, \"end\", dynamicIID, text=getItemName, values=AddPrompt)\r\n RegularList = OrderList.get_children(RegularPizza)\r\n ''' DEPRECATED!\r\n for i in range(len(RegularList)):\r\n GetRegularValue = (OrderList.item(i))[\"values\"]\r\n if i < len(RegularList):\r\n i += 1\r\n ListAmountRegular += GetRegularValue\r\n GourmetList = OrderList.get_children(GourmetPizza)\r\n for i in range(len(GourmetList)):\r\n GetGourmetValue = (OrderList.item(i))[\"values\"]\r\n if i < len(GourmetList):\r\n i += 1\r\n ListAmountGourmet += GetGourmetValue\r\n '''\r\n dynamicIID += 1\r\n if not TotalAmount <= 5:\r\n WarnMsg = messagebox.showwarning(\"Invalid\", \"Maximum amount of pizzas allowed is 5.\")\r\n \r\ndef checkOrderList(): # Scans the order list for updates\r\n global ListAmountRegular\r\n global ListAmountGourmet\r\n global TotalAmount\r\n TotalAmountRegular = sum(ListAmountRegular)\r\n TotalAmountGourmet = sum(ListAmountGourmet)\r\n TotalAmount = TotalAmountGourmet + TotalAmountRegular\r\n TotalCost = (TotalAmountRegular * 8.50) + (TotalAmountGourmet * 13.50)\r\n print(TotalAmount, TotalCost)\r\n print('List amount regular:', ListAmountRegular)\r\n print('List amount gourmet:', ListAmountGourmet)\r\n print('Total amount gourmet:', TotalAmountGourmet)\r\n print('Total amount regular:', TotalAmountRegular)\r\n print('Total amount:', TotalAmount)\r\n print('Total cost:', TotalCost)\r\n root.after(2000, checkOrderList) # Loop every 2 seconds\r\nroot.after(2000, checkOrderList)\r\n\r\ndef removePizza():\r\n selectedOrderItem = OrderList.focus()\r\n returnOrderItem = OrderList.item(selectedOrderItem)\r\n getOrderItemName = returnOrderItem.get('text')\r\n global dynamicIID\r\n while getOrderItemName not in [\"Regular Pizzas\", \"Gourmet Pizzas\"]:\r\n OrderList.delete(selectedOrderItem)\r\n\r\nAddButton = Button(ButtonFrame, text=\"Add\", command=addPizza)\r\nAddButton.grid(column=1, row=1, padx=5, pady=(10,0), sticky=\"ew\")\r\nRemoveButton = Button(ButtonFrame, text=\"Remove\", command=removePizza)\r\nRemoveButton.grid(column=1, row=2, padx=5, pady=(10,0), sticky=\"ew\")\r\n#LoadButton = Button(ButtonFrame, text=\"Load\", command=OpenFile)\r\n#LoadButton.grid(column=1, row=3, padx=5, pady=(10,0), sticky=\"ew\")\r\n\r\ndef resetEntry():\r\n ResetPrompt = messagebox.askyesno(\"Reset\", \"Are you sure you want to reset the customer's information?\")\r\n if ResetPrompt == True:\r\n FirstNameInput.delete(0, 'end')\r\n LastNameInput.delete(0, 'end')\r\n PhoneInput1.delete(0, 'end')\r\n PhoneInput2.delete(0, 'end')\r\n PhoneInput3.delete(0, 'end')\r\n DeliveryEntry.delete(0, 'end')\r\n\r\ndef confirmEntry():\r\n ConfirmPrompt = messagebox.askyesno(\"Confirm\", \"Do you wish to confirm the order?\")\r\n if ConfirmPrompt == True:\r\n print('Something')\r\n\r\nOptionsFrame = LabelFrame(root, text=\"Options\")\r\nOptionsFrame.grid(column=1, row=6, ipadx=10, ipady=10, padx=(20,20), pady=(0,20), sticky=\"ew\")\r\nConfirmButton = Button(OptionsFrame, text=\"Confirm order\", command=confirmEntry)\r\nConfirmButton.grid(column=1, row=1, ipadx=20, ipady=20, padx=20, pady=(10,0), sticky=\"nesw\")\r\nResetButton = Button(OptionsFrame, text=\"Reset order\", command=resetEntry)\r\nResetButton.grid(column=2, row=1, ipadx=20, ipady=20, padx=(0,20), pady=(10,0), sticky=\"nesw\")\r\n\r\nroot.attributes(\"-topmost\", True)\r\nroot.config(menu=menubar)\r\nroot.mainloop()\r\n","sub_path":"order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":14078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"93329435","text":"# Solution to Project Euler Problem #23: Non-abundant sums\n# Copyright (c) MarcinSkrobczynski\n\nfrom solutions.utils import get_sums_of_divisors\n\n\ndef main(n: int) -> int:\n sums_of_divisors = get_sums_of_divisors(n)\n abundant = [i for (i, j) in enumerate(sums_of_divisors) if j > i]\n sums = {i + j for i in abundant for j in abundant if i + j <= n}\n valid_numbers = [i for i in range(1, n + 1) if i not in sums]\n return sum(valid_numbers)\n\n\ndef solution() -> int:\n return main(28123)\n\n\nif __name__ == \"__main__\":\n print(f\"{main(28123)}\")\n","sub_path":"solutions/problem_0023.py","file_name":"problem_0023.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"299791227","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 12 10:26:58 2019\n\n@author: chenxi\n\"\"\"\n\nfrom langconv import *\n\ndef Traditional2Simplified(sentence):\n '''\n 将sentence中的繁体字转为简体字\n :param sentence: 待转换的句子\n :return: 将句子中繁体字转换为简体字之后的句子\n '''\n sentence = Converter('zh-hans').convert(sentence)\n return sentence\n\ndef Simplified2Traditional(sentence):\n '''\n 将sentence中的简体字转为繁体字\n :param sentence: 待转换的句子\n :return: 将句子中简体字转换为繁体字之后的句子\n '''\n sentence = Converter('zh-hant').convert(sentence)\n return sentence\n\nif __name__==\"__main__\":\n traditional_sentence = '憂郁的臺灣烏龜'\n simplified_sentence = Traditional2Simplified(traditional_sentence)\n traditional_sentence = Simplified2Traditional(simplified_sentence)\n print(simplified_sentence)\n print(traditional_sentence)","sub_path":"sciencemap/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"235185479","text":"import os\nimport glob\nfiles = glob.glob(\"????.calibA\")\n#files=glob.glob(\"*sipm_gain*\")\nfor mfile in files:\n\tprint(mfile)\n\trun=mfile.split(\".\")[0]\n\t#run=mfile.split(\".\")[2]\n\toutname=\"InnerVeto.sipm_ampl.\"+run\n\tos.rename(mfile,outname)\n\n","sub_path":"calib/BDXminiPass1/rename.calibA.py","file_name":"rename.calibA.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"428047470","text":"# Uses python3\nimport sys\n\ndef get_change(m):\n #write your code here\n c = 0\n while m != 0:\n if m >= 10:\n c += 1\n m -=10\n elif m<10 and m>=5:\n c += 1\n m -= 5\n else:\n c += 1\n m -= 1\n return c\n\nif __name__ == '__main__':\n m = int(sys.stdin.read())\n print(get_change(m))\n\n#n = int(input())\n#print(get_change(n))\n","sub_path":"Algorithmic-ToolBox/week3_greedy_algorithms/1_money_change/change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"260641458","text":"par = \"Lorem ipsum dolor sit amet consectetur adipiscing elit Curabitur eget bibendum turpis Curabitur scelerisque eros ultricies venenatis mi at tempor nisl Integer tincidunt accumsan cursus\"\n\ncounts = {}\n#your code go here:\n\nfor i in par:\n i=i.lower()\n if i == ' ':\n ''\n else:\n if counts.__contains__(i):\n counts[i]=counts[i]+1\n else:\n counts[i]=1\n \n\nprint(counts)\n","sub_path":"exercises/14.2-letter_counter/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"137503759","text":"# Created: 9/1/2019\n# Author: Emiliano Jordan,\n# Project: WrapPlotLib\nfrom matplotlib.lines import Line2D\nfrom sejings import extract_sejings\n\nfrom wrapplotlib.mpl.artist import WplArtist\nfrom wrapplotlib.settings import settings\n\n\nclass WplLine2D(Line2D, WplArtist):\n\n @extract_sejings\n def __init__(\n self,\n xdata,\n ydata,\n\n linewidth=settings.lines.linewidth,\n linestyle=settings.lines.linestyle,\n color=settings.lines.color,\n marker=settings.lines.marker,\n markersize=settings.lines.markersize,\n markeredgewidth=settings.lines.markeredgewidth,\n markeredgecolor=settings.lines.markeredgecolor,\n markerfacecolor=settings.lines.markerfacecolor,\n markerfacecoloralt='none',\n fillstyle=settings.markers.fillstyle,\n antialiased=settings.lines.antialiased,\n dash_capstyle=settings.lines.dash_capstyle,\n solid_capstyle=settings.lines.solid_capstyle,\n dash_joinstyle=settings.lines.dash_joinstyle,\n solid_joinstyle=settings.lines.solid_joinstyle,\n pickradius=settings.lines.pickradius,\n drawstyle=settings.lines.drawstyle,\n markevery=settings.lines.markerevery,\n **kwargs\n ):\n super().__init__(\n xdata,\n ydata,\n linewidth=linewidth,\n linestyle=linestyle,\n color=color,\n marker=marker,\n markersize=markersize,\n markeredgewidth=markeredgewidth,\n markeredgecolor=markeredgecolor,\n markerfacecolor=markerfacecolor,\n markerfacecoloralt=markerfacecoloralt,\n fillstyle=fillstyle,\n antialiased=antialiased,\n dash_capstyle=dash_capstyle,\n solid_capstyle=solid_capstyle,\n dash_joinstyle=dash_joinstyle,\n solid_joinstyle=solid_joinstyle,\n pickradius=pickradius,\n drawstyle=drawstyle,\n markevery=markevery,\n **kwargs\n )\n\n def __str__(self):\n return 'Wpl' + super().__str__()\n","sub_path":"wrapplotlib/mpl/lines.py","file_name":"lines.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"171967613","text":"import unittest\nfrom unittest.mock import patch\n\nfrom convergence.core import friends\nfrom convergence.utils import exceptions\nfrom test import fakes\n\n\nclass TestGetFriendships(unittest.TestCase):\n\n @patch.object(friends, \"friend_store\")\n def test_get_friendships(self, mock_fs):\n mock_fs.get_friendships_by_user = fakes.get_fake_friendships_by_user\n friendships = friends.get_friendships(3)\n\n self.assertEqual(friendships[0][\"friend_a_id\"], 3)\n self.assertEqual(friendships[0][\"friend_b_id\"], 9)\n self.assertEqual(friendships[0][\"friend_name\"], \"Test Friend\")\n\n mock_fs.get_friendships_by_user = lambda _: None\n self.assertEqual(friends.get_friendships(3), [])\n\n\nclass TestProposeFriendship(unittest.TestCase):\n\n @patch.object(friends, \"friend_store\")\n @patch.object(friends, \"user_store\")\n def test_propose_friendship_success(self, mock_us, mock_fs):\n mock_us.get_user_by_id = fakes.get_fake_user_by_id\n mock_fs.get_invite_by_details = lambda *args: None\n friendinvite = friends.propose_friendship(3, 9)\n self.assertEqual(friendinvite[\"requesting_id\"], 3)\n self.assertEqual(friendinvite[\"requested_id\"], 9)\n mock_fs.add_friendinvite.assert_called_once()\n\n @patch.object(friends, \"friend_store\")\n @patch.object(friends, \"user_store\")\n def test_propose_friendship_fail(self, mock_us, mock_fs):\n mock_us.get_user_by_id = lambda *args: None\n mock_fs.get_invite_by_details = fakes.get_fake_friendinvite\n\n with self.assertRaises(exceptions.InvalidRequestError):\n friends.propose_friendship(3, 3)\n\n with self.assertRaises(exceptions.NotFoundError):\n friends.propose_friendship(3, 6)\n\n mock_us.get_user_by_id = fakes.get_fake_user_by_id\n with self.assertRaises(exceptions.InvalidRequestError):\n friends.propose_friendship(3, 7)\n\n mock_fs.add_friendship.assert_not_called()\n\n\nclass TestProposeFriendships(unittest.TestCase):\n\n @patch.object(friends, \"friend_store\")\n @patch.object(friends, \"user_store\")\n def test_propose_friendships_success(self, mock_us, mock_fs):\n mock_fs.get_pending_invites_sent = lambda *args: None\n mock_fs.get_friendships_by_user = lambda *args: None\n mock_us.get_users_by_emails = fakes.get_fake_users_by_emails\n\n emails = [\n \"testuser1@gmail.com\",\n \"testuser2@gmail.com\",\n \"testuser3@gmail.com\"\n ]\n response = friends.propose_friendships(3, emails)\n self.assertEqual(response, set())\n mock_fs.add_friendinvites.assert_called_once()\n\n mock_fs.get_pending_invites_sent = fakes.get_fake_friendinvites_by_user\n response = friends.propose_friendships(3, emails)\n self.assertEqual(len(response), 3)\n\n @patch.object(friends, \"friend_store\")\n @patch.object(friends, \"user_store\")\n def test_propose_friendships_fail(self, mock_us, mock_fs):\n mock_fs.get_pending_invites_sent = lambda *args: None\n mock_fs.get_friendships_by_user = lambda *args: None\n mock_us.get_users_by_emails = fakes.get_fake_users_by_emails\n\n emails = [\"testuser@gmail.com\"] * (friends.MAX_INVITES_PER_REQUEST + 1)\n with self.assertRaises(exceptions.InvalidRequestError):\n friends.propose_friendships(3, emails)\n\n\nclass TestGetInvites(unittest.TestCase):\n\n @patch.object(friends, \"friend_store\")\n def test_get_invites(self, mock_fs):\n mock_fs.get_pending_invites_received = fakes.get_fake_pending_invites_by_user\n response = friends.get_invites(3)\n self.assertEquals(len(response), 1)\n self.assertEquals(response[0][\"screen_name\"], \"Fake User\")\n self.assertEquals(response[0][\"requested_id\"], 3)\n self.assertEquals(response[0][\"requesting_id\"], 5)\n\n mock_fs.get_pending_invites_received = lambda *args: None\n response = friends.get_invites(3)\n self.assertEquals(response, [])\n\n\nclass TestRespondToInvite(unittest.TestCase):\n\n @patch.object(friends, \"friend_store\")\n def test_respond_to_invite_accept(self, mock_fs):\n mock_fs.get_invite_by_id = fakes.get_fake_friendinvite_by_id\n mock_fs.add_friendship_from_invite = fakes.get_fake_friendships_by_friendinvite\n response = friends.respond_to_invite(8, 9, True)\n self.assertEqual(len(response), 2)\n\n @patch.object(friends, \"friend_store\")\n def test_respond_to_invite_reject(self, mock_fs):\n mock_fs.get_invite_by_id = fakes.get_fake_friendinvite_by_id\n mock_fs.add_friendship_from_invite = fakes.get_fake_friendships_by_friendinvite\n response = friends.respond_to_invite(8, 9, False)\n self.assertEqual(response, [])\n mock_fs.delete_friendinvite.assert_called_once()\n\n @patch.object(friends, \"friend_store\")\n def test_respond_to_invite_fail(self, mock_fs):\n mock_fs.get_invite_by_id = fakes.get_fake_friendinvite_by_id\n mock_fs.add_friendship_from_invite = fakes.get_fake_friendships_by_friendinvite\n\n with self.assertRaises(exceptions.NotFoundError):\n friends.respond_to_invite(3, 9, True)\n\n mock_fs.get_invite_by_id = lambda *args: None\n with self.assertRaises(exceptions.NotFoundError):\n friends.respond_to_invite(8, 9, True)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test_friends.py","file_name":"test_friends.py","file_ext":"py","file_size_in_byte":5384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"308804021","text":"import xml.etree.ElementTree as ET\n\nwith open(\"./normal/train.en-de.en\", \"r\") as fin:\n for line in fin.readlines():\n # Strip endline\n line = line.strip()\n # Split tab\n keyword_raw, code, sentence = line.split('\\t')\n\n keyword_node = ET.fromstring(keyword_raw)\n\n keywords = keyword_node.text.split(', ')\n assert code in [\"en\", \"de\", \"nl\"]\n\n words = sentence.split()\n","sub_path":"iwslt2017/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"217297427","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport ast\nimport pandas as pd\n\n\n# In[2]:\n\n\ndata = pd.read_csv(\"data/processed.csv\").reset_index(drop=True)\n\n\n# ## Create features\n\n# In[4]:\n\n\ndef count_sentences(dist):\n return len(eval(dist))\n\n\n# In[5]:\n\n\n#remove records with too many sentences\ndata[\"no_of_sentences\"] = data[\"eucl_dis\"].apply(count_sentences)\ndata = data[data[\"no_of_sentences\"] < 13]\ndel data[\"no_of_sentences\"]\ndata = data.reset_index(drop=True)\n\n\n# In[8]:\n\n\nfeatures = pd.DataFrame()\n \nfor i in range(len(data[\"eucl_dis\"])):\n eucl_dis = eval(data[\"eucl_dis\"][i])\n for j in range(12):\n if j < len(eucl_dis):\n features.loc[i, \"eucl_dis_\" + str(j)] = eucl_dis[j]\n else: \n features.loc[i, \"eucl_dis_\" + str(j)] = 10\n\n\n# In[9]:\n\n\nfor i in range(len(data[\"cosine_dis\"])):\n cosine_dis = eval(data[\"cosine_dis\"][i].replace(\"nan\",\"1\"))\n for j in range(12):\n if j < len(cosine_dis):\n features.loc[i, \"cosine_dis_\" + str(j)] = cosine_dis[j]\n else:\n features.loc[i, \"cosine_dis_\" + str(j)] = 1\n\n\n# In[10]:\n\n\nfeatures[\"ans_sentence\"] = data[\"ans_sentence\"]\n\n\n# In[11]:\n\n\nfeatures\n\n\n# ## Split data and run models\n\n# In[43]:\n\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\n\nscaler = MinMaxScaler()\nfeatures_scaled = scaler.fit_transform(features.iloc[:,:-1])\n\n\n# In[44]:\n\n\ntrain_feat, test_feat, train_ans, test_ans = train_test_split(features_scaled, features.iloc[:,-1])\n\n\n# In[45]:\n\n\nfrom sklearn import linear_model\nfrom sklearn import metrics\nfrom sklearn.ensemble import RandomForestClassifier\nimport xgboost as xgb\n\n\n# In[46]:\n\n\nregression = linear_model.LogisticRegression(solver='saga', multi_class='multinomial')\nregression.fit(train_feat, train_ans)\n\nregression_train_predictions = regression.predict(train_feat)\nregression_test_predictions = regression.predict(test_feat)\n\nregression_train_acc = metrics.accuracy_score(train_ans, regression_train_predictions)\nregression_test_acc = metrics.accuracy_score(test_ans, regression_test_predictions)\n\nprint(\"Logistic regression results:\\ntrain set: \" + str(regression_train_acc) + \"\\ntest set: \" + str(regression_test_acc))\n\n\n# In[47]:\n\n\nforest = RandomForestClassifier(criterion='entropy')\nforest.fit(train_feat, train_ans)\n\nforest_train_predictions = forest.predict(train_feat)\nforest_test_predictions = forest.predict(test_feat)\n\nforest_train_acc = metrics.accuracy_score(train_ans, forest_train_predictions)\nforest_test_acc = metrics.accuracy_score(test_ans, forest_test_predictions)\n\nprint(\"Random forest results:\\ntrain set: \" + str(forest_train_acc) + \"\\ntest set: \" + str(forest_test_acc))\n\n\n# In[51]:\n\n\nxg = xgb.XGBClassifier(max_depth = 5)\nxg.fit(train_feat, train_ans)\nxg_train_predictions = xg.predict(train_feat)\nxg_test_predictions = xg.predict(test_feat)\n\nxg_train_acc = metrics.accuracy_score(train_ans, xg_train_predictions)\nxg_test_acc = metrics.accuracy_score(test_ans, xg_test_predictions)\n\nprint(\"XGBoost results:\\ntrain set: \" + str(xg_train_acc) + \"\\ntest set: \" + str(xg_test_acc))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Classical_ML/run_models.py","file_name":"run_models.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"138896621","text":"# Write a class to hold player information, e.g. what room they are in\n# currently.\n\nclass Player:\n def __init__(self, name, current_room):\n self.name = name\n self.current_room = current_room\n self.items = []\n\n def travel(self, direction):\n if getattr(self.current_room, f\"{direction}_to\") is not None:\n self.current_room = getattr(self.current_room, f\"{direction}_to\")\n print(self.current_room)\n else:\n print(\"you can not move in that direciton\")\n def on_take(self, take_item):\n # check if the item is in the room?\n # if it's in the room then remove it from room items? \n # only if you are successfull add it to he player item\n for item in self.current_room.items:\n if item.name == take_item:\n self.current_room.items.remove(item)\n self.items.append(item)\n return f\"You have picked up item {take_item}\"\n return f\"This room doesnt' contain {take_item}\"\n def on_drop(self,item_name):\n for item in self.items:\n if item.name == item_name:\n self.items.remove(item)\n self.current_room.items.append(item)\n return f\"You have dropped the item {item_name}\"\n return f\"This player doesnt' have the item {item_name}\"\n","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"70014050","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# __author__ = eyckwu\n\nimport cookielib\nimport urllib2\n\nurl = 'https://ssp.scnu.edu.cn/Default.aspx'\n\n\ncookie = cookielib.MozillaCookieJar()\ncookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)\nrequest = urllib2.Request('https://ssp.scnu.edu.cn/Default.aspx')\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))\nresponse = opener.open(request)\nprint(response.read())","sub_path":"ch06/load_cookie.py","file_name":"load_cookie.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"229770208","text":"import json\nfrom flask import Blueprint, flash, jsonify, redirect, render_template, request, make_response, url_for\nfrom globals import project\nfrom google.api_core.exceptions import NotFound\nfrom google.cloud import iot_v1\nfrom iot_database import IOTDatabase\n\n# Blueprint Configuration\niot_bp = Blueprint(\n 'iot_bp', __name__,\n url_prefix='/iot',\n template_folder='templates',\n static_folder='static'\n)\n\n\n@iot_bp.route('/', methods=['GET', 'POST'])\ndef setup():\n page_template = './iot_setup.jinja'\n cloud_region = 'us-central1'\n registry_id = 'cybergym-registry'\n\n # Initiate IoT client and get list of all registered IoT devices in project\n iot_client = iot_v1.DeviceManagerClient()\n devices_gen = iot_client.list_devices(parent=f'projects/{project}/locations/{cloud_region}/registries/{registry_id}')\n device_list = [i.id for i in devices_gen]\n\n if request.method == 'POST':\n print(request.data)\n resp = json.loads(request.data)\n device_id = resp['device_id']\n check_device = True if device_id in device_list else False\n if check_device:\n print(f'Recieved object {resp}')\n return jsonify({'url': url_for('iot_bp.index', device_id=device_id)})\n message = jsonify({'error_msg': f'Unrecognized device with ID: {device_id}'})\n return make_response(message, 400)\n return render_template(page_template)\n\n\n@iot_bp.route('/faq', methods=['GET'])\ndef faq():\n page_template = './faq.jinja'\n return render_template(page_template, project=project)\n\n\n@iot_bp.route('/commands/', methods=['GET'])\ndef index(device_id):\n page_template = './iot.jinja'\n\n # Used to get current registered device data\n cloud_region = 'us-central1'\n registry_id = 'cybergym-registry'\n client = iot_v1.DeviceManagerClient() # publishes to device\n iotdb = IOTDatabase()\n device_path = client.device_path(project, cloud_region, registry_id, device_id)\n device_num_id = str(client.get_device(request={\"name\": device_path}).num_id)\n print(device_num_id)\n\n # Pass level_1 flag back in override var to unlock level_2 of the challenge\n override = None\n # Supported Commands; Passed through template to generate buttons\n commands = {\n # banned_commands = ['green']\n 'functions': ['humidity', 'heart', 'pressure', 'temp'],\n 'colors': ['red', 'orange', 'yellow', 'purple', 'blue', 'teal']\n }\n\n iot_data = None\n if device_num_id:\n iot_data = iotdb.get_rpi_sense_hat_data(device_num_id=device_num_id)\n if iot_data is not None:\n iot_data['sensor_data'] = json.loads(iot_data['sensor_data'])\n print(f'database query returned: {iot_data}')\n return render_template(\n page_template,\n device_id=device_id,\n commands=commands,\n override=override,\n iot_data=iot_data\n )\n flash(\"Couldn\\'t connect to device. Is it online?\")\n return redirect(url_for('iot_bp.setup'))\n\n\n@iot_bp.route('/commands//submit', methods=['POST'])\ndef submit(device_id):\n cloud_region = 'us-central1'\n registry_id = 'cybergym-registry'\n\n # Init Publisher client for server\n client = iot_v1.DeviceManagerClient() # publishes to device\n device_path = client.device_path(project, cloud_region, registry_id, device_id)\n if request.method == 'POST':\n resp = json.loads(request.data)\n command = resp['command']\n data = command.encode(\"utf-8\")\n print(\"[+] Publishing to device topic\")\n try:\n client.send_command_to_device(\n request={\"name\": device_path, \"binary_data\": data}\n )\n except NotFound as e:\n print(e)\n flash(f'Device {device_id} responded with 404. Ensure the device is properly connected.', 'alert-warning')\n return jsonify(error=e)\n except Exception as e:\n return jsonify(error=e)\n finally:\n return jsonify(success=True)\n else:\n return jsonify({'resp': 404})\n","sub_path":"container-applications/IoT/GenCyberIoT/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"206506884","text":"#!/usr/bin/python3\n# _*_ coding:utf-8 _*_\n\n__author__ = 'zhangxun'\n\ndef main():\n couter = 0\n for i in range(int(input())):\n sure_solution = input().split()\n if(eval(\"+\".join(sure_solution)) >= 2):\n couter += 1\n\n print(couter)\n\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"Team.py","file_name":"Team.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"426697011","text":"class Solution:\n \"\"\"\n @param candidates: A list of integers\n @param target: An integer\n @return: A list of lists of integers\n \"\"\"\n def combinationSum(self, candidates, target):\n if candidates is None:\n return None\n \n # candidates去重\n candidates = self.deDuplicate(candidates)\n \n result = []\n tmp = []\n startIndex = 0\n \n self.dfsHelper(candidates, target, startIndex, tmp, result)\n \n return result\n \n def dfsHelper(self, candidates, target, startIndex, tmp, result):\n # 递归的出口\n if target == 0:\n result.append(tmp.copy())\n tmp = []\n return\n \n # 递归\n for i in range(startIndex, len(candidates)):\n if candidates[i] > target:\n return\n self.dfsHelper(candidates, target - candidates[i], i, tmp + [candidates[i]], result)\n \n return\n \n def deDuplicate(self, nums):\n nums = list(set(nums))\n nums.sort()\n return nums\n ","sub_path":"专题学习/DFS/CombinationSum.py","file_name":"CombinationSum.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"264623791","text":"#!/usr/bin/env python3\nimport time\nimport sys\n\n# ===== Timer =====\n\ndef timer(n, function, *argv):\n\n timeStat = []\n\n for i in range(n):\n # start timing\n start = time.perf_counter()\n print(\"Running round %s ...\" % (i + 1), end=\"\\r\")\n \n # exec function\n function(*argv)\n\n # stop timing\n timeStat.append(time.perf_counter() - start)\n \n # display time consuming for each round\n print(\"\\nRun %s times, best: %4fs, worst: %4fs, avg: %4fs.\\n\" \\\n % (n, max(timeStat), min(timeStat), sum(timeStat)/n))\n\n# ===== Loading Test =====\n\n# fibonacci function\ndef fib(n):\n if n == 1 or n == 2:\n return 1\n return fib(n - 2) + fib(n - 1)","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"63048624","text":"\"\"\"\nImplementation of T-MIN for Python. Designed to run on a host PC (the target board has a C version).\n\nAuthor: Ken Tindell\nCopyright (c) 2014-2017 JK Energy Ltd.\nLicensed under MIT License.\n\"\"\"\n\nfrom struct import pack\nfrom binascii import crc32\nfrom threading import Lock\nfrom serial import Serial, SerialException\nfrom time import time\n\n\ndef int32_to_bytes(value: int) -> bytes:\n return pack('>I', value)\n\n\nclass MINConnectionError(Exception):\n pass\n\n\nclass MINFrame:\n def __init__(self, min_id: int, payload: bytes, seq: int, transport: bool):\n self.min_id = min_id & 0x3f\n self.payload = payload\n self.seq = seq\n self.is_transport = transport\n self.last_sent_time = None # type: int\n\n\nclass MINTransport:\n \"\"\"\n Handle MIN Transport. Runs as a polled system; typically will be subclassed to run in a threaded environment that puts thread locks\n around API calls.\n \"\"\"\n\n # Calls to bind this to a serial system in a host\n def _now_ms(self) -> int:\n raise NotImplementedError\n\n def _serial_write(self, data):\n raise NotImplementedError\n\n def _serial_any(self) -> bool:\n raise NotImplementedError\n\n def _serial_read_all(self) -> bytes:\n raise NotImplementedError\n\n def _serial_close(self):\n raise NotImplementedError\n\n ACK = 0xff\n RESET = 0xfe\n\n HEADER_BYTE = 0xaa\n STUFF_BYTE = 0x55\n EOF_BYTE = 0x55\n\n SEARCHING_FOR_SOF = 0\n RECEIVING_ID_CONTROL = 1\n RECEIVING_LENGTH = 2\n RECEIVING_SEQ = 3\n RECEIVING_PAYLOAD = 4\n RECEIVING_CHECKSUM_3 = 5\n RECEIVING_CHECKSUM_2 = 6\n RECEIVING_CHECKSUM_1 = 7\n RECEIVING_CHECKSUM_0 = 8\n RECEIVING_EOF = 9\n\n def __init__(self, window_size=16, transport_fifo_size=100, idle_timeout_ms=500, ack_retransmit_timeout_ms=10, frame_retransmit_timeout_ms=10, debug=False):\n \"\"\"\n :param window_size: Number of outstanding unacknowledged frames permitted\n :param transport_fifo_size: Maximum number of outstanding frames\n :param idle_timeout_ms: Time before connection assumed to have been lost and retransmissions stopped\n :param ack_retransmit_timeout_ms: Time before ACK frames are resent\n :param frame_retransmit_timeout_ms: Time before frames are resent\n :param debug:\n \"\"\"\n self._debug = debug\n self._transport_fifo_size = transport_fifo_size\n self._ack_retransmit_timeout_ms = ack_retransmit_timeout_ms\n self._max_window_size = window_size\n self._idle_timeout_ms = idle_timeout_ms\n self._frame_retransmit_timeout_ms = frame_retransmit_timeout_ms\n\n # Stats about the link\n self._longest_transport_fifo = 0\n self._dropped_frames = 0\n self._spurious_acks = 0\n self._mismatched_acks = 0\n self._duplicate_frames = 0\n self._retransmitted_frames = 0\n self._resets_received = 0\n self._sequence_mismatch_drops = 0\n\n # State of transport FIFO\n self._transport_fifo = None # type: [MINFrame]\n self._last_sent_ack_time_ms = None # type: int\n self._last_received_anything_ms = None # type: int\n self._last_received_frame_ms = None # type: int\n self._last_sent_frame_ms = None # type: int\n\n # State for receiving a MIN frame\n self._rx_frame_buf = bytearray()\n self._rx_header_bytes_seen = 0\n self._rx_frame_state = self.SEARCHING_FOR_SOF\n self._rx_frame_checksum = 0\n self._rx_payload_bytes = bytearray()\n self._rx_frame_id_control = 0\n self._rx_frame_seq = 0\n self._rx_frame_length = 0\n self._rx_control = 0\n self._accepted_min_frames = []\n self._rx_list = []\n\n # Sequence numbers\n self._rn = 0\n self._sn_min = 0\n self._sn_max = 0\n\n self._transport_reset()\n\n def _transport_fifo_pop(self):\n assert len(self._transport_fifo) > 0\n\n del self._transport_fifo[0]\n\n def _transport_fifo_get(self, n: int) -> MINFrame:\n return self._transport_fifo[n]\n\n def _transport_fifo_send(self, frame: MINFrame):\n on_wire_bytes = self._on_wire_bytes(frame=frame)\n frame.last_sent_time = self._now_ms()\n self._serial_write(on_wire_bytes)\n\n def _send_ack(self):\n ack_frame = MINFrame(min_id=self.ACK, seq=self._rn, payload=bytes(), transport=True)\n on_wire_bytes = self._on_wire_bytes(frame=ack_frame)\n self._last_sent_ack_time_ms = self._now_ms()\n self._serial_write(on_wire_bytes)\n\n def _send_reset(self):\n reset_frame = MINFrame(min_id=self.RESET, seq=0, payload=bytes(), transport=True)\n on_wire_bytes = self._on_wire_bytes(frame=reset_frame)\n self._serial_write(on_wire_bytes)\n\n def _transport_fifo_reset(self):\n self._transport_fifo = []\n self._last_received_anything_ms = self._now_ms()\n self._last_sent_ack_time_ms = self._now_ms()\n self._last_sent_frame_ms = 0\n self._last_received_frame_ms = 0\n self._sn_min = 0\n self._sn_max = 0\n\n def _transport_reset(self):\n self._send_reset()\n self._send_reset()\n\n self._transport_fifo_reset()\n\n def send_frame(self, min_id: int, payload: bytes):\n \"\"\"\n Sends a MIN frame with a given ID directly on the wire. Will be silently discarded if any line noise.\n :param min_id: ID of MIN frame (0 .. 63)\n :param payload: up to 255 bytes of payload\n :return:\n \"\"\"\n if len(payload) not in range(256):\n raise ValueError(\"MIN payload too large\")\n if min_id not in range(64):\n raise ValueError(\"MIN ID out of range\")\n frame = MINFrame(min_id=min_id, payload=payload, transport=False, seq=0)\n on_wire_bytes = self._on_wire_bytes(frame=frame)\n self._serial_write(on_wire_bytes)\n\n def queue_frame(self, min_id: int, payload: bytes):\n \"\"\"\n Queues a MIN frame for transmission through the transport protocol. Will be retransmitted until it is\n delivered or the connection has timed out.\n\n :param min_id: ID of MIN frame (0 .. 63)\n :param payload: up to 255 bytes of payload\n :return:\n \"\"\"\n if len(payload) not in range(256):\n raise ValueError(\"MIN payload too large\")\n if min_id not in range(64):\n raise ValueError(\"MIN ID out of range\")\n # Frame put into the transport FIFO\n if len(self._transport_fifo) < self._transport_fifo_size:\n frame = MINFrame(min_id=min_id, payload=payload, seq=self._sn_max, transport=True)\n self._transport_fifo.append(frame)\n else:\n self._dropped_frames += 1\n raise MINConnectionError(\"No space in transport FIFO queue\")\n\n def _min_frame_received(self, min_id_control: int, min_payload: bytes, min_seq: int):\n self._last_received_anything_ms = self._now_ms()\n\n if min_id_control & 0x80:\n if min_id_control == self.ACK:\n # The ACK number indicates the serial number of the next packet wanted, so any previous packets can be marked off\n number_acked = (min_seq - self._sn_min) & 0xff\n number_in_window = (self._sn_max - self._sn_min) & 0xff\n # Need to guard against old ACKs from an old session still turning up\n if number_acked <= number_in_window:\n self._sn_min = min_seq\n\n assert len(self._transport_fifo) >= number_in_window\n assert number_in_window <= self._max_window_size\n\n new_number_in_window = (self._sn_max - self._sn_min) & 0xff\n if new_number_in_window + number_acked != number_in_window:\n raise AssertionError\n\n for i in range(number_acked):\n self._transport_fifo_pop()\n else:\n self._spurious_acks += 1\n elif min_id_control == self.RESET:\n self._resets_received += 1\n self._transport_fifo_reset()\n else:\n # MIN frame received\n if min_seq == self._rn:\n # The next frame in the sequence we are looking for\n self._rn = (self._rn + 1) & 0xff\n self._send_ack()\n self._last_received_frame_ms = self._now_ms()\n min_frame = MINFrame(min_id=min_id_control, payload=min_payload, seq=min_seq, transport=True)\n self._rx_list.append(min_frame)\n else:\n # Discarding because sequence number mismatch\n self._sequence_mismatch_drops += 1\n else:\n min_frame = MINFrame(min_id=min_id_control, payload=min_payload, seq=0, transport=False)\n self._rx_list.append(min_frame)\n\n def _rx_bytes(self, data: bytes):\n \"\"\"\n Called by handler to pass over a sequence of bytes\n :param data:\n \"\"\"\n for byte in data:\n if self._rx_header_bytes_seen == 2:\n self._rx_header_bytes_seen = 0\n if byte == self.HEADER_BYTE:\n self._rx_frame_state = self.RECEIVING_ID_CONTROL\n continue\n if byte == self.STUFF_BYTE:\n # Discard this byte; carry on receiving the next character\n continue\n # By here something must have gone wrong, give up on this frame and look for new header\n self._rx_frame_state = self.SEARCHING_FOR_SOF\n continue\n\n if byte == self.HEADER_BYTE:\n self._rx_header_bytes_seen += 1\n else:\n self._rx_header_bytes_seen = 0\n\n if self._rx_frame_state == self.SEARCHING_FOR_SOF:\n pass\n elif self._rx_frame_state == self.RECEIVING_ID_CONTROL:\n self._rx_frame_id_control = byte\n self._rx_payload_bytes = 0\n if self._rx_frame_id_control & 0x80:\n self._rx_frame_state = self.RECEIVING_SEQ\n else:\n self._rx_frame_state = self.RECEIVING_LENGTH\n elif self._rx_frame_state == self.RECEIVING_SEQ:\n self._rx_frame_seq = byte\n self._rx_frame_state = self.RECEIVING_LENGTH\n elif self._rx_frame_state == self.RECEIVING_LENGTH:\n self._rx_frame_length = byte\n self._rx_control = byte\n self._rx_frame_buf = bytearray()\n if self._rx_frame_length > 0:\n self._rx_frame_state = self.RECEIVING_PAYLOAD\n else:\n self._rx_frame_state = self.RECEIVING_CHECKSUM_3\n elif self._rx_frame_state == self.RECEIVING_PAYLOAD:\n self._rx_frame_buf.append(byte)\n self._rx_frame_length -= 1\n if self._rx_frame_length == 0:\n self._rx_frame_state = self.RECEIVING_CHECKSUM_3\n elif self._rx_frame_state == self.RECEIVING_CHECKSUM_3:\n self._rx_frame_checksum = byte << 24\n self._rx_frame_state = self.RECEIVING_CHECKSUM_2\n elif self._rx_frame_state == self.RECEIVING_CHECKSUM_2:\n self._rx_frame_checksum |= byte << 16\n self._rx_frame_state = self.RECEIVING_CHECKSUM_1\n elif self._rx_frame_state == self.RECEIVING_CHECKSUM_1:\n self._rx_frame_checksum |= byte << 8\n self._rx_frame_state = self.RECEIVING_CHECKSUM_0\n elif self._rx_frame_state == self.RECEIVING_CHECKSUM_0:\n self._rx_frame_checksum |= byte\n computed_checksum = self._crc32(bytearray([self._rx_frame_id_control, self._rx_frame_seq, self._rx_control]) + self._rx_frame_buf)\n if self._rx_frame_checksum != computed_checksum:\n # Frame fails checksum, is dropped\n self._rx_frame_state = self.SEARCHING_FOR_SOF\n else:\n # Checksum passes, wait for EOF\n self._rx_frame_state = self.RECEIVING_EOF\n elif self._rx_frame_state == self.RECEIVING_EOF:\n if byte == self.EOF_BYTE:\n # Frame received OK, pass up frame for handling\n self._min_frame_received(min_id_control=self._rx_frame_id_control, min_payload=bytes(self._rx_frame_buf), min_seq=self._rx_frame_seq)\n\n # Look for next frame\n self._rx_frame_state = self.SEARCHING_FOR_SOF\n else:\n # Should never get here but in case we do just reset\n self._rx_frame_state = self.SEARCHING_FOR_SOF\n\n def _on_wire_bytes(self, frame: MINFrame) -> bytes:\n \"\"\"\n Get the on-wire byte sequence for the frame, including stuff bytes after every 0xaa 0xaa pair\n \"\"\"\n if frame.is_transport:\n prolog = bytes([frame.min_id | 0x80, frame.seq, len(frame.payload)]) + frame.payload\n else:\n prolog = bytes([frame.min_id, len(frame.payload)]) + frame.payload\n\n crc = crc32(prolog, 0)\n raw = prolog + int32_to_bytes(crc)\n\n stuffed = bytearray([self.HEADER_BYTE, self.HEADER_BYTE, self.HEADER_BYTE])\n\n count = 0\n\n for i in raw:\n stuffed.append(i)\n if i == self.HEADER_BYTE:\n count += 1\n if count == 2:\n stuffed.append(self.STUFF_BYTE)\n count = 0\n else:\n count = 0\n\n stuffed.append(self.EOF_BYTE)\n\n return bytes(stuffed)\n\n @staticmethod\n def _crc32(checksummed_data):\n return crc32(checksummed_data)\n\n def transport_stats(self):\n \"\"\"\n Returns a tuple of all the transport stats\n \"\"\"\n return (self._longest_transport_fifo,\n self._last_sent_frame_ms,\n self._sequence_mismatch_drops,\n self._retransmitted_frames,\n self._resets_received,\n self._duplicate_frames,\n self._mismatched_acks,\n self._spurious_acks)\n\n def _find_oldest_frame(self):\n if len(self._transport_fifo) == 0:\n raise AssertionError\n\n window_size = (self._sn_max - self._sn_min) & 0xff\n oldest_frame = self._transport_fifo[0] # type: MINFrame\n longest_elapsed_time = (self._now_ms() - oldest_frame.last_sent_time)\n\n for i in range(window_size):\n elapsed = self._now_ms() - self._transport_fifo[i].last_sent_time\n if elapsed >= longest_elapsed_time:\n oldest_frame = self._transport_fifo[i]\n longest_elapsed_time = elapsed\n\n return oldest_frame\n\n def poll(self):\n \"\"\"\n Polls the serial line, runs through MIN, sends ACKs, handles retransmits where ACK has gone missing.\n\n :return: array of accepted MIN frames\n \"\"\"\n remote_connected = (self._now_ms() - self._last_received_anything_ms) < self._idle_timeout_ms\n remote_active = (self._now_ms() - self._last_received_frame_ms) < self._idle_timeout_ms\n\n self._rx_list = []\n\n data = self._serial_read_all()\n if data:\n self._rx_bytes(data=data)\n\n window_size = (self._sn_max - self._sn_min) & 0xff\n if window_size < self._max_window_size and len(self._transport_fifo) > window_size:\n # Frames still to send\n frame = self._transport_fifo_get(n=window_size)\n frame.seq = self._sn_max\n self._last_sent_frame_ms = self._now_ms()\n frame.last_sent_time = self._now_ms()\n self._transport_fifo_send(frame=frame)\n self._sn_max = (self._sn_max + 1) & 0xff\n else:\n # Maybe retransmits\n if window_size > 0 and remote_connected:\n oldest_frame = self._find_oldest_frame()\n if self._now_ms() - oldest_frame.last_sent_time > self._frame_retransmit_timeout_ms:\n self._transport_fifo_send(frame=oldest_frame)\n\n # Periodically transmit ACK\n if self._now_ms() - self._last_sent_ack_time_ms > self._ack_retransmit_timeout_ms:\n if remote_active:\n self._send_ack()\n\n if (self._sn_max - self._sn_max) & 0xff > window_size:\n raise AssertionError\n\n return self._rx_list\n\n def close(self):\n self._serial_close()\n\n\nclass MINTransportSerial(MINTransport):\n \"\"\"\n Bound to Pyserial driver. But not thread safe: must not call poll() and send() at the same time.\n \"\"\"\n def _now_ms(self):\n now = int(time() * 1000.0)\n return now\n\n def _serial_write(self, data):\n self._serial.write(data)\n\n def _serial_any(self):\n return self._serial.in_waiting > 0\n\n def _serial_read_all(self):\n return self._serial.read_all()\n\n def _serial_close(self):\n self._serial.close()\n\n def __init__(self, port, debug=True):\n \"\"\"\n Open MIN connection on a given port.\n :param port: serial port\n :param debug:\n \"\"\"\n try:\n self._serial = Serial(port=port, timeout=0.1, write_timeout=None)\n self._serial.read(1000) # Flush any stale input away (well, most of it)\n except SerialException:\n raise MINConnectionError(\"Transport MIN cannot open port '{}'\".format(port))\n super().__init__(debug=debug)\n\n\nclass ThreadsafeTransportMINSerialHandler(MINTransportSerial):\n \"\"\"\n This class wraps the API calls with thread locks to prevent concurrent access to the system.\n\n A typical usage is to create a simple thread that calls poll() in a loop which takes MIN frames received and puts them into a Python queue.\n The application can send directly and pick up incoming frames from the queue.\n \"\"\"\n def __init__(self, port, debug=False):\n super().__init__(port=port, debug=debug)\n self._thread_lock = Lock()\n\n def close(self):\n self._thread_lock.acquire()\n super().close()\n self._thread_lock.release()\n\n def transport_stats(self):\n self._thread_lock.acquire()\n result = super().transport_stats()\n self._thread_lock.release()\n\n return result\n\n def send_frame(self, min_id: int, payload: bytes):\n self._thread_lock.acquire()\n super().send_frame(min_id=min_id, payload=payload)\n self._thread_lock.release()\n\n def queue_frame(self, min_id: int, payload: bytes):\n self._thread_lock.acquire()\n super().queue_frame(min_id=min_id, payload=payload)\n self._thread_lock.release()\n\n def poll(self):\n self._thread_lock.acquire()\n result = super().poll()\n self._thread_lock.release()\n\n return result\n","sub_path":"host/min.py","file_name":"min.py","file_ext":"py","file_size_in_byte":18958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"38855061","text":"from .base import *\nfrom decouple import config\nfrom boto3.session import Session\n\nSECRET_KEY = config('SECRET_KEY')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# cloudwatch settings\nCLOUDWATCH_AWS_ID = config('CLOUDWATCH_AWS_ID')\nCLOUDWATCH_AWS_KEY = config('CLOUDWATCH_AWS_KEY')\nAWS_DEFAULT_REGION = config('region')\nlogger_boto3_session = Session(\n aws_access_key_id=CLOUDWATCH_AWS_ID,\n aws_secret_access_key=CLOUDWATCH_AWS_KEY,\n region_name=AWS_DEFAULT_REGION,\n)\n\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"aws\": {\n \"format\": \"%(asctime)s [%(levelname)-8s] %(message)s [%(pathname)s:%(lineno)d]\",\n \"datefmt\": \"%Y-%m-%d %H:%M:%S\",\n },\n },\n \"handlers\": {\n \"watchtower\": {\n \"level\": \"INFO\",\n \"class\": \"watchtower.CloudWatchLogHandler\",\n # From step 2\n \"boto3_session\": logger_boto3_session,\n \"log_group\": \"<>\",\n # Different stream for each environment\n \"stream_name\": \"logs\",\n \"formatter\": \"aws\",\n },\n \"console\": {\"class\": \"logging.StreamHandler\", \"formatter\": \"aws\", },\n },\n \"loggers\": {\n # Use this logger to send data just to Cloudwatch\n \"django\": {\"level\": \"INFO\", \"handlers\": [\"watchtower\"],\n \"propogate\": False, }\n },\n}\n","sub_path":"your_project/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"271428195","text":"import sys\nread=lambda:sys.stdin.readline().rstrip()\nwrite=lambda x:sys.stdout.write(str(x)+\"\\n\")\nN,M=map(int, read().split())\nns = list(map(int, read().split()))\nbest = M\nflag = 0\nfor i in range(N):\n if flag:\n break\n for j in range(N):\n if flag:\n break\n if i == j:\n continue\n for k in range(N):\n if flag:\n break\n if i == k or j == k:\n continue\n s = ns[i] + ns[j] + ns[k]\n if s == M:\n flag = 1\n if s > M:\n continue\n if best > (M-s):\n best = M-s\nif flag:\n write(M)\nelse:\n write(M-best)","sub_path":"implementation/blackjack_2798.py","file_name":"blackjack_2798.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"454269382","text":"#!/usr/bin/env python\nimport person\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nlist_of_names = ['Roger', 'Mary', 'Luisa', 'Elvis']\nlist_of_ages = [23, 24, 19, 86]\nlist_of_heights_cm = [175, 162, 178, 182]\n\nfor name in list_of_names:\n print(\"The name {:} is {:} letters long\".format(name, len(name)))\nprint(\"\\n\")\n\nlist_of_length = [len(name) for name in list_of_names]\n\npeople = {}\nfor name in list_of_names:\n new_person = person.person(name=name, age=list_of_ages[list_of_names.index(name)], height=list_of_heights_cm[list_of_names.index(name)])\n people.update({name:new_person.__repr__()})\n\nprint(f\"The dictionary of people is shown below: \\n {people}\\n\")\n\nages = np.array(list_of_ages)\nheights = np.array(list_of_heights_cm)\n\navg_age = np.mean(ages)\nprint(f\"The average age is {avg_age}.\\n\")\n\nplt.scatter(list_of_ages, list_of_heights_cm)\nplt.xlabel('Ages (year)')\nplt.ylabel('Heights (cm)')\nplt.title('Scatter Plot of Ages vs Heights')\nplt.grid(True)\nplt.savefig(\"ScatterPlotAgeVsHeight.png\")\nplt.show()","sub_path":"hw1_python_basics/hw1p1.py","file_name":"hw1p1.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"395785496","text":"from operator import itemgetter\r\n#Quick Sort\r\n#==========\r\ndef QuickSort(A,start,end):\r\n if start0:\n\t\t\t\t\tgame.cities = copy.copy(game.cities)\n\t\t\t\t\tgame.cities[self.position] = copy.copy(game.cities[self.position])\n\t\t\t\t\tgame.cities[self.position].disinfect(game,game.cities[self.position].disease_cubes[color],color)\n\t\t\t\t\tgame.log(\"MEDIC healed \"+str(color)+\" at \"+str(self.position))\n\t\telif self.playerrole == PlayerRole.QUARANTINE_SPECIALIST:\n\t\t\tgame.protected_cities = [self.position]\n\t\t\tgame.protected_cities.extend(game.cities[self.position].neighbors)\n\t\n\tdef must_discard(self):\n\t\tif self.playerrole == PlayerRole.CONTINGENCY_PLANNER:\n\t\t\t# TODO: Check if contingency planner has kept additional card\n\t\t\treturn len(self.cards)>7\n\t\telse:\n\t\t\treturn len(self.cards)>7\n\t\t\n\tdef no_action(self):\n\t\treturn True\n\t\t\n\t# Stub function, must be implemented in child\n\tdef request_action(self,game):\n\t\treturn self.no_action.__name__,{}\n\t\t\n\t# Stub function, must be implemented in child\n\tdef request_discard(self,game):\n\t\treturn self.cards[0]\n\t\n\tdef perform_action(self,game,action,kwargs):\n\t\tactions = {\n\t\t\tself.no_action.__name__: self.no_action,\n\t\t\tself.discard.__name__: self.discard,\n\t\t\tself.drive_ferry.__name__: self.drive_ferry,\n\t\t\tself.direct_flight.__name__: self.direct_flight,\n\t\t\tself.charter_flight.__name__: self.charter_flight,\n\t\t\tself.shuttle_flight.__name__: self.shuttle_flight,\n\t\t\tself.build_researchstation.__name__: self.build_researchstation ,\n\t\t\tself.treat_disease.__name__: self.treat_disease,\n\t\t\tself.give_knowledge.__name__: self.give_knowledge,\n\t\t\tself.receive_knowledge.__name__: self.receive_knowledge,\n\t\t\tself.discover_cure.__name__: self.discover_cure,\n\t\t\tself.rally_flight.__name__: self.rally_flight,\n\t\t\tself.special_charter_flight.__name__: self.special_charter_flight\n\t\t}\n\t\treturn actions[action](game,**kwargs) if action in actions else False\n\t\n\tdef available_actions(self,game):\n\t\tvalid_cities = [city for city in game.cities if city!=self.position]\n\t\tactions = {}\n\t\tif game.turn_phase==TurnPhase.ACTIONS:\n\t\t\tactions[self.drive_ferry.__name__] = [ {'target':city} for city in game.cities[self.position].neighbors ]\n\t\t\tactions[self.direct_flight.__name__] = [ {'target':card.name} for card in self.cards if (card.cardtype==CardType.CITY and card.name!=self.position) ]\n\t\t\tactions[self.charter_flight.__name__] = [ {'target':city} for city in valid_cities] if self.position in self.cards else []\n\t\t\tactions[self.shuttle_flight.__name__] = [ {'target':city} for city in valid_cities if game.cities[city].research_station] if (game.cities[self.position].research_station and game.research_station_counter>1) else []\n\t\t\tactions[self.build_researchstation.__name__] = ([{'replace':\"none\"}] if game.research_station_counter < 6 else [{'replace':city} for city in game.cities if game.cities[city].research_station]) if ((self.position in self.cards or self.playerrole == PlayerRole.OPERATIONS_EXPERT) and not game.cities[self.position].research_station) else []\n\t\t\tactions[self.treat_disease.__name__] = [ {'color':color} for color in game.commons['colors'] if game.cities[self.position].disease_cubes[color]>0 ]\n\t\t\tactions[self.give_knowledge.__name__] = [{'receiver':player.pid, 'target':card.name} for player in game.players for card in self.cards if (player!=self and self.position==player.position and card.cardtype==CardType.CITY and (self.position==card.name or self.playerrole==PlayerRole.RESEARCHER))]\n\t\t\tactions[self.receive_knowledge.__name__] = [{'giver':player.pid, 'target':card.name} for player in game.players for card in player.cards if (player!=self and self.position==player.position and card.cardtype==CardType.CITY and (self.position==card.name or player.playerrole==PlayerRole.RESEARCHER))]\n\t\t\tactions[self.discover_cure.__name__] = [{'color':color,'chosen_cards':[self.cards[i].name for i in chosen_cards]} for chosen_cards in list(itertools.combinations(np.arange(len(self.cards)),4 if self.playerrole==PlayerRole.SCIENTIST else 5)) for color in game.commons['colors'] if all([city in game.cities.keys() and game.cities[city].color==color for city in [self.cards[i].name for i in chosen_cards]])] if game.cities[self.position].research_station and len(self.cards)>=(4 if self.playerrole==PlayerRole.SCIENTIST else 5) else []\n\t\t\tactions[self.rally_flight.__name__] = [{'player':player.pid,'target_player':target.pid} for player in game.players for target in game.players if player.position!=target.position] if self.playerrole==PlayerRole.DISPATCHER else []\n\t\t\tactions[self.special_charter_flight.__name__] = [{'discard':card.name,'target':city} for card in self.cards for city in valid_cities if card.name in game.cities.keys()] if self.playerrole==PlayerRole.OPERATIONS_EXPERT and self.special_move and game.cities[self.position].research_station else []\n\t\telif game.turn_phase==TurnPhase.DISCARD:\n\t\t\tactions[self.discard.__name__] = [{'discard':card.name} for card in self.cards]\n\t\treturn actions\n\t\n\t# Card is a string with the card name\n\tdef discard(self,game,card):\n\t\tvalid = card in self.cards\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" discarded: \"+card)\n\t\t\tself.cards = copy.copy(self.cards)\n\t\t\tgame.player_deck = copy.copy(game.player_deck)\n\t\t\tcard = self.cards.pop(self.cards.index(card))\n\t\t\tself.colors = copy.copy(self.colors)\n\t\t\tself.colors[card.color]-=1\n\t\t\tgame.player_deck.discard = copy.copy(game.player_deck.discard)\n\t\t\tgame.player_deck.discard.append(card)\n\t\treturn valid\n\t\n\t# Target is string object to new position\n\tdef drive_ferry(self,game,target):\n\t\tvalid = target in game.cities[self.position].neighbors\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" drove to: \"+target)\n\t\t\tself.position = target\n\t\t\tself.move_triggers(game)\n\t\treturn valid\n\t\n\t# Target is string object to new position\n\tdef direct_flight(self,game,target):\n\t\tvalid = target in self.cards and self.position!=target and target in game.cities.keys()\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" direct flew to: \"+target)\n\t\t\tself.discard(game,target)\n\t\t\tself.position = target\n\t\t\tself.move_triggers(game)\n\t\treturn valid\n\t\n\t# Target is string object to new position\n\tdef charter_flight(self,game,target):\n\t\tvalid = self.position in self.cards and self.position!=target and target in game.cities.keys()\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" charter flew to: \"+target)\n\t\t\tself.discard(game,self.position)\n\t\t\tself.position = target\n\t\t\tself.move_triggers(game)\n\t\treturn valid\n\t\n\t# Target is string object to new position\n\tdef shuttle_flight(self,game,target):\n\t\tvalid = game.cities[self.position].research_station and self.position!=target and target in game.cities.keys() and game.cities[target].research_station\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" shuttle flew to: \"+target)\n\t\t\tself.position = target\n\t\t\tself.move_triggers(game)\n\t\treturn valid\n\t\n\t# Replace is None or string of city name in which research_station will be removed\n\tdef build_researchstation(self,game,replace=None):\n\t\tif replace==\"none\":\n\t\t\treplace=None\n\t\tvalid = (self.position in self.cards or self.playerrole == PlayerRole.OPERATIONS_EXPERT) and not game.cities[self.position].research_station and (game.research_station_counter<6 or (replace in game.cities.keys() and game.cities[replace].research_station))\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" built research station\")\n\t\t\tgame.cities = copy.copy(game.cities)\n\t\t\tif game.research_station_counter == 6:\n\t\t\t\tgame.cities[replace] = copy.copy(game.cities[replace])\n\t\t\t\tgame.cities[replace].research_station = False\n\t\t\t\tgame.log(self.playerrole.name+\" removed research station at: \"+replace)\n\t\t\telse:\n\t\t\t\tgame.research_station_counter += 1\n\t\t\tif self.playerrole != PlayerRole.OPERATIONS_EXPERT:\n\t\t\t\tself.discard(game,self.position)\n\t\t\tgame.cities[self.position] = copy.copy(game.cities[self.position])\n\t\t\tgame.cities[self.position].research_station = True\n\t\t\tgame.calculate_distances()\n\t\treturn valid\n\t\n\t# Color is string object of the color name\n\tdef treat_disease(self,game,color):\n\t\tvalid = game.cities[self.position].disease_cubes[color] > 0\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" treated: \"+color)\n\t\t\tgame.cities = copy.copy(game.cities)\n\t\t\tgame.cities[self.position] = copy.copy(game.cities[self.position])\n\t\t\tgame.cities[self.position].disinfect(game,game.cities[self.position].disease_cubes[color] if (self.playerrole == PlayerRole.MEDIC or game.cures[color]) else 1 ,color)\n\t\treturn valid\n\t\n\t# Receiver is pid number, target is string object\n\tdef give_knowledge(self,game,receiver,target):\n\t\tgame.players[receiver % len(game.players)] = copy.copy(game.players[receiver % len(game.players)])\n\t\treceiver_player = game.players[receiver % len(game.players)]\n\t\tvalid = receiver_player!=self and self.position==receiver_player.position and target in self.cards and (self.position==target or self.playerrole==PlayerRole.RESEARCHER)\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" gave \"+target+\" to: \"+receiver_player.playerrole.name)\n\t\t\treceiver_player.cards = copy.copy(receiver_player.cards)\n\t\t\tself.cards = copy.copy(self.cards)\n\t\t\treceiver_player.cards.append(self.cards.pop(self.cards.index(target)))\n\t\t\tif receiver_player.must_discard():\n\t\t\t\tgame.log(receiver_player.playerrole.name + \" must discard\")\n\t\t\t\tgame.real_current_player = game.current_player\n\t\t\t\tgame.current_player = receiver\n\t\t\t\tgame.turn_phase = TurnPhase.DISCARD\n\t\treturn valid\n\t\n\t# Giver is pid number, target is string object\n\tdef receive_knowledge(self,game,giver,target):\n\t\tgame.players[giver % len(game.players)] = copy.copy(game.players[giver % len(game.players)])\n\t\tgiver = game.players[giver % len(game.players)]\n\t\tvalid = giver!=self and self.position==giver.position and target in giver.cards and (self.position==target or giver.playerrole==PlayerRole.RESEARCHER)\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" received \"+target+\" from: \"+giver.playerrole.name)\n\t\t\tgiver.cards = copy.copy(giver.cards)\n\t\t\tself.cards = copy.copy(self.cards)\n\t\t\tself.cards.append(giver.cards.pop(giver.cards.index(target)))\n\t\t\tif self.must_discard():\n\t\t\t\tgame.log(self.playerrole.name + \" must discard\")\n\t\t\t\tgame.real_current_player = game.current_player\n\t\t\t\tgame.turn_phase = TurnPhase.DISCARD\n\t\treturn valid\n\t\n\t# Color is a string object, chosen_cards is an array containing string objects\n\tdef discover_cure(self,game,color,chosen_cards):\n\t\tvalid = game.cities[self.position].research_station and len(chosen_cards)==(4 if self.playerrole==PlayerRole.SCIENTIST else 5) and all([(card in self.cards and self.cards[self.cards.index(card)].cardtype==CardType.CITY and game.cities[card].color==color) for card in chosen_cards])\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" found cure for: \"+color)\n\t\t\tfor card in chosen_cards:\n\t\t\t\tself.discard(game,card)\n\t\t\tgame.cures = copy.copy(game.cures)\n\t\t\tgame.cures[color] = True\n\t\t\tif game.remaining_disease_cubes[color]==game.commons['number_cubes']:\n\t\t\t\tgame.eradicated = copy.copy(game.eradicated)\n\t\t\t\tgame.eradicated[color] = True\n\t\t\t\tgame.log(\"Eradicated \"+color+\" disease\")\n\t\t\tfor player in game.players:\n\t\t\t\tif player.playerrole == PlayerRole.MEDIC:\n\t\t\t\t\tplayer.move_triggers(game)\n\t\treturn valid\n\t\n\t# Player is pid number, target_player is pid number\n\tdef rally_flight(self,game,player,target_player):\n\t\tgame.players[player % len(game.players)] = copy.copy(game.players[player % len(game.players)])\n\t\tplayer = game.players[player % len(game.players)]\n\t\ttarget_player = game.players[target_player % len(game.players)]\n\t\tvalid = self.playerrole==PlayerRole.DISPATCHER and player.position!=target_player.position\n\t\tif valid:\n\t\t\tgame.log(\"DISPATCHER rallied \"+player.playerrole.name+\" to: \"+target_player.playerrole.name)\n\t\t\tplayer.position = target_player.position\n\t\t\tplayer.move_triggers(game)\n\t\treturn valid\n\t\n\t# Discard is a string of card name, target is a string to new location\n\tdef special_charter_flight(self,game,discard,target):\n\t\tvalid = self.playerrole==PlayerRole.OPERATIONS_EXPERT and self.special_move and game.cities[self.position].research_station and discard in self.cards and discard in game.cities.keys() and target!=self.position\n\t\tif valid:\n\t\t\tgame.log(self.playerrole.name+\" special charter flew to: \"+target+\" discarding: \"+discard)\n\t\t\tself.special_move = False\n\t\t\tself.discard(game,discard)\n\t\t\tself.position = target\n\t\treturn valid\n\t\n\t# TODO: Implement different event actions\n\tdef use_event(self,event):\n\t\tpass\n\n","sub_path":"game_files/players.py","file_name":"players.py","file_ext":"py","file_size_in_byte":14636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"424655994","text":"import random\nimport json\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\nimport torch\nfrom model import NeuralNet\nfrom nltk_utils import bag_of_words, tokenize\nimport time\nimport os\nimport emoji\n\n\napp = Flask(__name__, static_url_path='')\n\n#Este archivo permite recibir y enviar datos con la parte de Flutter\n\n\nCORS(app)\n\n#Get me permitira conseguir ls datos de Flutter\n@app.route(\"/\", methods=[\"GET\"])\ndef home():\n return '

Demo

'\n\n\nCORS(app)\n\n#POST me eprmitira enviar los datos a Flutter\n@app.route(\"/bot\", methods=[\"POST\"])\ndef response():\n app.logger.info('start')\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n app.logger.info(device)\n \n with open('intents.json', 'r') as json_data: #abro el archivo json que es el archivo con los comandos \n intents = json.load(json_data)\n app.logger.info(intents)\n \n \n FILE = \"data.pth\"\n data = torch.load(FILE) #abro el archivo data que es el archivo ya entrenado\n app.logger.info(data)\n input_size = data[\"input_size\"]#recogo el tamaño de los datos de entrada\n hidden_size = data[\"hidden_size\"]\n output_size = data[\"output_size\"] #recogo el tamaño de los datos de salida\n all_words = data['all_words'] #la bolsa de palabras del archivo entrenado\n tags = data['tags'] #las etiquetas tag del archivo entrenado\n model_state = data[\"model_state\"] #El modelo de datos del archivo emtrenad\n\n model = NeuralNet(input_size, hidden_size, output_size).to(device) #Selecciono los datos que voy ha utilizar\n model.load_state_dict(model_state)\n model.eval() #Evaluo los datos del modelo\n # return '

sdfjk

'\n query = dict(request.form)['query'] #Recogo los datos de Flutter que vienen con la etiqueta query\n\n res = query\n res = tokenize(res) #tokenizo los datos de flutter\n\n X = bag_of_words(res, all_words) #creo la bolsa de palabras\n X = X.reshape(1, X.shape[0]) #calculo su tamaño\n X = torch.from_numpy(X).to(device) #Solicito utilizar la libreria entrenada\n\n output = model(X) #selecciono el modelo\n _, predicted = torch.max(output, dim=1)\n tag = tags[predicted.item()] #selleciono la etiequeta que es la selleccionada a taves de las predicciones anteriores\n\n probs = torch.softmax(output, dim=1)\n prob = probs[0][predicted.item()] #ya seleccionadas las etiquetas miro la que mas probabilidad de que sea tenga\n\n if prob.item() > 0.75: #Si el comando tiene una probabilidad de que sea la acertada de mas del 70%....\n app.logger.info('%d logged in successfully', prob.item())\n app.logger.info(intents['intents'])\n for intent in intents['intents']:\n if tag == intent[\"tag\"]:\n if intent[\"tag\"] == \"goodbye\":\n os.remove(\"intents.json\")\n os.system('python database.py')\n # f = open(\"database.py\")\n #f = open(\"randomDatabase.py\")\n #f = open(\"train.py\")\n\n os.system('python train.py')\n return jsonify({\"response\": random.choice(intent['responses'])})\n # elif intent[\"tag\"] == \"goodbye\":\n # os.system('python train.py')\n # return jsonify({\"response\" : train.epoch})\n else:\n return jsonify({\"response\": random.choice(intent['responses'])})\n \n # elif prob.item() > 0.50 < 0.70:\n # app.logger.info('%d logged in successfully', prob.item())\n # app.logger.info(intents['intents']) \n # return jsonify({\"response\": random.choice(['I siee...', 'mmmmmm', 'ops..', 'O_O'])}) \n\n else:\n #return jsonify({\"response\": random.choice(['I siee...', 'mmmmmm', 'ops..', 'O_O', 'jumm..', 'okeyyy', 'ok', 'tell me more'])})\n #return jsonify({\"response\": random.choice(['I siee...', 'mmmmmm', ', 'jumm..', 'okeyyy', 'ok', 'tell me more', '\\N{thinking face} \\N{thinking face}', '\\N{face without mouth} ', '\\N{lying face} \\N{lying face} jajaj', '\\N{relieved face} \\N{relieved face}', '\\N{OK hand} \\N{OK hand} \\N{OK hand} \\N{OK hand}', '\\N{face with open mouth} \\N{face with open mouth} \\N{face with open mouth}', 'ou \\N{flexed biceps} \\N{flexed biceps}' , '.. \\N{eyes} \\N{eyes} ...' ])})\n return jsonify({\"response\": random.choice(['Sorry, I am not sure about the answer...', 'Wait, do you really told me something about that?', 'mmm I am not sure, may be you have to train me more', 'OPS, I dont have any information about that', 'OHh no ! I dont have the answer of that question :(', 'Ou... that... I dont have any response for that', 'I dont have the answer of that question, Are you sure that you trained me?'])})","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"590973033","text":"from application.models.customer import Customer\nimport application.base_support.sqlite_support as base\nimport sqlite3\nfrom os import _exists as file_exists\nfrom typing import List\nfrom application.abstraction.base_repository import BaseRepository\n\n\nclass CustomersRepository(Customer, BaseRepository):\n sqlite_path = \"sqlite.db\"\n\n def add(self, obj) -> None:\n connection = sqlite3.connect(self.sqlite_path)\n c = connection.cursor()\n request = \"INSERT INTO Customers(CustomerEmployeeId, AccountMgrId, IncomeLevel) VALUES (\\\"\"+str(obj.CustomEmployeeId)+\"\\\", \\\"\"+str(obj.AccountMgrId)+\"\\\", \\\"\"+str(obj.IncomeLevel)+\"\\\");\"\n c.execute(request)\n connection.commit()\n c.close()\n connection.close()\n\n def delete(self, id) -> None:\n connection = sqlite3.connect(self.sqlite_path)\n c = connection.cursor()\n request = \"DELETE FROM Customers WHERE CustomerId = \"+str(id)+\";\"\n c.execute(request)\n connection.commit()\n c.close()\n connection.close()\n\n def edit(self, id, obj) -> None:\n request = \"UPDATE Customers SET CustomerId = \" + str(obj.CustomId) + \" , CustomerEmployeeId = \" + str(obj.CustomerEmployeeId) + \",AccountMgrId = \" + str(obj.AccountMgrId) + \",IncomeLevel = \" + str(obj.IncomeLevel) + \" WHERE PersonId= \"+str(id)+\";\"\n connection = sqlite3.connect(self.sqlite_path)\n c = connection.cursor()\n c.execute(request)\n connection.commit()\n c.close()\n connection.close()\n\n def get(self) -> List[Customer]:\n connection = sqlite3.connect(self.sqlite_path)\n cursor = connection.cursor()\n request = \"SELECT CustomerId, PersonId, CustomerEmployeeId, AccountMgrId, IncomeLevel FROM Customers\"\n cursor.execute(request)\n fetch = cursor.fetchall()\n ls = []\n for each in fetch:\n customer = Customer()\n customer.load(each)\n ls.append(customer)\n return ls\n\n def get_id(self, id) -> Customer:\n connection = sqlite3.connect(self.sqlite_path)\n cursor = connection.cursor()\n request = \"SELECT * FROM Customers WHERE PersonId = \"+str(id)\n cursor.execute(request)\n fetch = cursor.fetchone()\n customer = Customer()\n customer.load(fetch)\n return customer\n\n ","sub_path":"WebService/application/repositories/customers_repository.py","file_name":"customers_repository.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"352083209","text":"# -*- coding: utf-8 -*-\n\n# Created by junfeng on 3/29/16.\n\n# logging config\nimport logging\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p',\n level=logging.DEBUG)\nlogger = logging.getLogger(__name__)","sub_path":"training/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"168976655","text":"\nimport numpy as np\n\nfrom base.atom import Atom\nfrom base.lattice import Lattice, get_reciprocal\n\n\nclass Crystal:\n def __init__(self, lattice, atomlist):\n self.lattice = lattice\n self.atomlist = atomlist\n\n @property\n def lattice(self):\n return self._lattice\n\n @lattice.setter\n def lattice(self, lattice):\n if not isinstance(lattice, Lattice):\n raise TypeError('lattice must be an instance of Lattice.')\n self._lattice = lattice\n\n @property\n def atomlist(self):\n return self._atomlist\n\n @atomlist.setter\n def atomlist(self, atomlist):\n if not isinstance(atomlist, list):\n raise TypeError('atomlist must be a \\'list\\'.')\n if not all(map(lambda atom: isinstance(atom, Atom), atomlist)):\n raise TypeError('atom in atomlist must be a \\'instance of Atom\\'.')\n self._atomlist = atomlist\n\n def get_atomlist_position(self):\n atomlist_position = []\n for atom in self.atomlist:\n atomlist_position.append(atom.position)\n return np.array(atomlist_position)\n \n def get_atomlist_name(self):\n atomlist_name = []\n for atom in self.atomlist:\n atomlist_name.append(atom.name)\n return atomlist_name\n\n def get_atomlist_as_tuplelist(self):\n atomlist_name = self.get_atomlist_name\n atomlist_position = self.get_atomlist_position\n return zip(atomlist_name, atomlist_position)\n\n def get_crystal_coordinate(self):\n unitcell = self.lattice.unitcell\n reciprocal = get_reciprocal(unitcell)\n position = self.get_atomlist_position()\n return np.dot(position, reciprocal)\n\n\ndef get_crystal_coordinate(position, reciprocal):\n if not isinstance(position, np.ndarray):\n raise TypeError('positions must be an ndarray.')\n if not isinstance(reciprocal, np.ndarray):\n raise TypeError('reciprocal must be an ndarray.')\n if reciprocal.shape != (3,3):\n raise TypeError('reciprocal must be an array of shape (3,3).')\n return np.dot(position, reciprocal)\n\n","sub_path":"base/crystal.py","file_name":"crystal.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"439645461","text":"import numpy as np\n\nclass game_agent:\n def __init__(self, input_string, status):\n self.input_string = input_string\n self.status = status\n self.verify_Matrix = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]\n self.verify_Matrix = np.array(self.verify_Matrix)\n #print(self.verify_Matrix.argmax())\n def restart(self):\n print(self.input_string)\n return('abc')\n def next_action(self):\n print('next action')\n def result(self):\n if self.input_string[1,1] == 1:\n return True\n else:\n return False\n def verify_result(self):\n status = False\n for i in range(0,8):\n a = self.input_string[self.verify_Matrix[i,0]]\n b = self.input_string[self.verify_Matrix[i,1]]\n c = self.input_string[self.verify_Matrix[i,2]]\n #print(a,b,c)\n if verify_3_same_value(a,b,c) == True:\n #print(1)\n #print(a,b,c)\n status = True\n break\n return status\n\ndef verify_3_same_value(a,b,c):\n if (a == b) & (b == c) & (a != 0):\n return True\n else:\n return False","sub_path":"Model/Game_Agent.py","file_name":"Game_Agent.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"517870690","text":"#!/usr/bin/env python3\nimport math\nimport numpy\nimport time\nimport csv\nimport bitalino\nimport multiprocessing\n\nfrom datetime import datetime\n\ndef read_data_bitalino(samplingFreq,running_time):\n\n device.start(samplingFreq, acqChannels)\n\n start = time.time()\n end = time.time()\n while (end - start) < running_time:\n # Read samples\n seconds = int(time.time())\n dataAcquired = device.read(samplingFreq)\n \n # Acc transfer function: ACC(g) = ((ADC - Cmin)/(Cmax - Cmin))*2-1\n # X = channel 5 --------- 9\n # Y = channel 4 --------- 8\n # Z = channel 3 --------- 7\n max_accZ = max(dataAcquired[:,5])\n min_accZ = min(dataAcquired[:,5])\n fill_AccDataZ = ((dataAcquired[:,5]-min_accZ)/(max_accZ-min_accZ))*2-1 # BITalino channel 3\n \n # HR and SpO2 sat transfer function: 0.25*ADC-0.8\n #fill_HR_oxy = 0.25*dataAcquired[:,6]-0.8 # BITalino channel 2\n #fill_SpO2_oxy = 0.25*dataAcquired[:,5]-0.8 # BITalino channel 3\n \n # Mean values (to print)\n Acc_meanZ = numpy.mean(fill_AccDataZ)\n #HR_oxy_mean = numpy.mean(fill_HR_oxy)\n #SpO2_oxy_mean = numpy.mean(fill_SpO2_oxy)\n\n # CSV Format\n with open('EE_Bitalino_Dataset.csv', 'a') as file:\n writer = csv.writer(file)\n for x in range(0,10):\n writer.writerow([seconds,\n round(fill_AccDataZ[x],5)\n #round(HR_oxy_mean,2),\n #round(SpO2_oxy_mean)\n ])\n print(\"\")\n print(\"Timestamp = \",seconds,\" AccZ = \",Acc_meanZ)\n #print(\"SpO2 = \",round(SpO2_oxy_mean))\n end = time.time()\n\n device.stop() # Stop acquisition\n device.close() # Close connection\n print(\"Connection closed.\")\n\n\nif __name__ == \"__main__\":\n\n macAddress = \"98:D3:81:FD:61:22\" # Device MacAddress: 98:D3:81:FD:61:22 or 20:15:12:22:81:68\n samplingFreq = 10 # Sampling Frequency (Hz)\n running_time = 10 # Acquisition Time (s) - None for Infinite\n acqChannels = [0,1,2,3,4,5] # Acquisition Channels ([0-5])\n\n print(\"\")\n print(\"Data Collection\")\n print(\"\")\n print(\"Searching for BITalino devices...\")\n\n device = bitalino.BITalino(macAddress)\n \n print(\"\")\n print(\"Device \" + str(macAddress) + \" connected.\")\n print(\"\")\n print(\"Starting acquisition.\")\n print(\"\")\n\n # Create processes\n p1 = multiprocessing.Process(target=read_data_bitalino,args=(samplingFreq,running_time))\n\n # Start processes\n p1.start()\n\n # Wait until processes are finished\n p1.join()\n\n print(\"Done!\")\n","sub_path":"Tests/test_Bitalino.py","file_name":"test_Bitalino.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"51552522","text":"import arcade\n\nfrom ev3dev2simulator.obstacle.ColorObstacle import ColorObstacle\nfrom ev3dev2simulator.util.Util import apply_scaling\n\n\nclass BorderObstacle(ColorObstacle):\n \"\"\"\n This class provides basic functionality for obstacles which act as a border.\n \"\"\"\n\n\n def __init__(self, cfg, color_code: int, depth: int, edge_spacing: float):\n super(BorderObstacle, self).__init__(color_code)\n\n self.screen_width = apply_scaling(cfg['screen_settings']['screen_width'])\n self.screen_height = apply_scaling(cfg['screen_settings']['screen_height'])\n self.depth = depth\n self.edge_spacing = edge_spacing\n\n self.top_points = None\n self.right_points = None\n self.bottom_points = None\n self.left_points = None\n\n self._calc_points()\n\n\n def _calc_points(self):\n \"\"\"\n Calculate the points of the polygon this BorderObstacle consist of.\n \"\"\"\n\n screen_center_x = self.screen_width / 2\n screen_center_y = self.screen_height / 2\n\n border_long_width = self.screen_width - self.edge_spacing * 2\n border_long_height = self.screen_height - self.edge_spacing * 2\n\n self.top_points = arcade.get_rectangle_points(screen_center_x,\n self.screen_height - self.edge_spacing - (self.depth / 2),\n border_long_width,\n self.depth)\n\n self.right_points = arcade.get_rectangle_points(self.screen_width - self.edge_spacing - (self.depth / 2),\n screen_center_y,\n self.depth,\n border_long_height)\n\n self.bottom_points = arcade.get_rectangle_points(screen_center_x,\n self.edge_spacing + (self.depth / 2),\n border_long_width,\n self.depth)\n\n self.left_points = arcade.get_rectangle_points(self.edge_spacing + (self.depth / 2),\n screen_center_y,\n self.depth,\n border_long_height)\n\n\n def collided_with(self, x: float, y: float) -> bool:\n if arcade.is_point_in_polygon(x, y, self.top_points):\n return True\n\n if arcade.is_point_in_polygon(x, y, self.left_points):\n return True\n\n if arcade.is_point_in_polygon(x, y, self.bottom_points):\n return True\n\n if arcade.is_point_in_polygon(x, y, self.right_points):\n return True\n\n return False\n","sub_path":"ev3dev2simulator/obstacle/BorderObstacle.py","file_name":"BorderObstacle.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"349933983","text":"\r\nimport random\r\n\r\n# cell\r\n# contains a value, a list of possible values,\r\n# and a flag for whether or not we have already\r\n# visited this cell (used for potential backtracking)\r\nclass cell():\r\n def __init__(self):\r\n self.valid = []\r\n self.val = 0\r\n self.visited = False\r\n self.lock = False\r\n\r\n def __str__(self):\r\n return str(self.val)\r\n\r\nclass sudoku():\r\n\r\n def __init__(self):\r\n self.grid = self.init_grid()\r\n \r\n def init_grid(self):\r\n # initialize grid with cells\r\n grid = []\r\n for r in range(9):\r\n grid.append([])\r\n for c in range(9):\r\n z = cell()\r\n grid[r].append(z)\r\n \r\n return grid\r\n\r\n\r\n # get neighbors; horizontal, vertical, and same-square\r\n def get_neighbors(self, x, y):\r\n lisNeighbors = []\r\n \r\n # horiz\r\n for r in range(0, 9):\r\n lisNeighbors.append(self.grid[r][y].val)\r\n \r\n # vert\r\n for c in range(0, 9):\r\n lisNeighbors.append(self.grid[x][c].val)\r\n \r\n # square\r\n sq_x = int(x / 3)\r\n sq_y = int(y / 3)\r\n for r in range(0, 3):\r\n for c in range(0, 3):\r\n lisNeighbors.append(self.grid[sq_x * 3 + r][sq_y * 3 + c].val)\r\n \r\n # clean list\r\n n_lis = []\r\n for itm in lisNeighbors:\r\n if itm != 0:\r\n if not itm in n_lis:\r\n n_lis.append(itm)\r\n \r\n return n_lis\r\n\r\n\r\n # get valid values for given x, y cell\r\n def get_valid(self, x, y):\r\n lisNeighbors = self.get_neighbors(x, y)\r\n lisValid = [1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n \r\n for itm in lisNeighbors:\r\n if itm in lisValid:\r\n lisValid.remove(itm)\r\n \r\n return lisValid\r\n \r\n def fill_blanks(self):\r\n # keep track of a simple 1-81 index of where we are\r\n # this makes decrementing a bit simpler when we need\r\n # to backtrack\r\n index = 0\r\n\r\n while index < 9 * 9:\r\n\r\n c = index % 9\r\n r = int(index / 9)\r\n\r\n # if this cell has a value, move on\r\n # (this can happen if we're solving a partially-filled puzzle)\r\n if self.grid[r][c].val in [1, 2, 3, 4, 5, 6, 7, 8, 9]:\r\n index += 1\r\n continue\r\n\r\n # new cell; check for valid neighbors\r\n if not self.grid[r][c].visited:\r\n self.grid[r][c].valid = self.get_valid(r, c)\r\n self.grid[r][c].visited = True\r\n \r\n # if there are no valid values, remove this value\r\n # then go back one and invalidate that value since it\r\n # leads to an unsolveable state\r\n if len(self.grid[r][c].valid) == 0:\r\n # this cell's possibilities must be\r\n # recalculated after we go back one\r\n self.grid[r][c].visited = False\r\n \r\n # decrement index, remove value of the cell\r\n # that lead to this unsolveable state\r\n index -= 1\r\n \r\n c = index % 9\r\n r = int(index / 9)\r\n \r\n # iterate backwards until we find a piece that doesn't have a lock on it\r\n while self.grid[r][c].lock:\r\n index -= 1\r\n \r\n c = index % 9\r\n r = int(index / 9)\r\n \r\n \r\n self.grid[r][c].valid.remove(self.grid[r][c].val)\r\n self.grid[r][c].val = 0\r\n \r\n # we have at least one valid value\r\n # pick from valid values at random\r\n else:\r\n self.grid[r][c].val = random.choice(self.grid[r][c].valid)\r\n index += 1\r\n \r\n def remove(self, amt):\r\n rem_amt = amt\r\n while rem_amt > 0:\r\n # get random x, y\r\n x = random.randint(0, 8)\r\n y = random.randint(0, 8)\r\n \r\n # don't remove a part that has already been removed\r\n while self.grid[x][y].val == ' ':\r\n x = random.randint(0, 8)\r\n y = random.randint(0, 8)\r\n \r\n # if value in cell, hide\r\n self.grid[x][y].val = ' '\r\n \r\n # decrement amt to hide\r\n rem_amt -= 1\r\n \r\n def lock(self):\r\n # lock all existing numbers from being changed again\r\n for r in range(9):\r\n for c in range(9):\r\n if not self.grid[r][c].val == ' ':\r\n self.grid[r][c].lock = True\r\n","sub_path":"oku.py","file_name":"oku.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"273377520","text":"# Copyright (c) 2019, IRIS-HEP\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nfrom asyncio import Queue\nfrom unittest.mock import call\n\nimport servicex\nfrom servicex.did_finder.lookup_request import LookupRequest\nfrom servicex.did_finder.rucio_adapter import RucioAdapter\nfrom servicex.did_finder.servicex_adapter import ServiceXAdapter\n\n\nclass TestLookupRequest:\n def test_init(self, mocker):\n mock_rucio = mocker.MagicMock(RucioAdapter)\n mock_servicex = mocker.MagicMock(ServiceXAdapter)\n request = LookupRequest(\"123-45\", \"my-did\", mock_rucio, mock_servicex)\n assert request.rucio_adapter == mock_rucio\n assert request.did == 'my-did'\n assert request.request_id == '123-45'\n assert request.chunk_size == 1000\n\n def test_lookup_files(self, mocker):\n mock_rucio = mocker.MagicMock(RucioAdapter)\n rucio_file_list = [\n {\n \"scope\": \"my-scope\",\n \"name\": \"file\"+str(i),\n \"bytes\": 31400,\n \"events\": 5000\n } for i in range(10)\n ]\n\n mock_rucio.list_files_for_did.return_value = rucio_file_list\n\n mock_thread = mocker.patch(\"threading.Thread\")\n mock_servicex = mocker.MagicMock(ServiceXAdapter)\n request = LookupRequest(\n \"123-45\",\n \"my-did\",\n mock_rucio, mock_servicex,\n threads=5,\n chunk_size=2)\n\n request.lookup_files()\n mock_rucio.list_files_for_did.assert_called_with(\"my-did\")\n assert mock_thread.call_count == 5\n\n def test_lookup_files_empty_did(self, mocker):\n mock_rucio = mocker.MagicMock(RucioAdapter)\n mock_rucio.list_files_for_did.return_value = iter([])\n\n mocker.patch(\"threading.Thread\")\n mock_servicex = mocker.MagicMock(ServiceXAdapter)\n request = LookupRequest(\n \"123-45\",\n \"my-did\",\n mock_rucio, mock_servicex,\n threads=5,\n chunk_size=2)\n\n request.lookup_files()\n mock_servicex.post_status_update.assert_called_with(\n \"DID Finder found zero files for dataset my-did\",\n severity='fatal')\n\n def test_lookup_files_did_not_found(self, mocker):\n mock_rucio = mocker.MagicMock(RucioAdapter)\n mock_rucio.list_files_for_did.return_value = None\n\n mocker.patch(\"threading.Thread\")\n mock_servicex = mocker.MagicMock(ServiceXAdapter)\n request = LookupRequest(\n \"123-45\",\n \"my-did\",\n mock_rucio, mock_servicex,\n threads=5,\n chunk_size=2)\n\n request.lookup_files()\n mock_servicex.post_status_update.assert_called_with(\n \"DID Not found my-did\", severity='fatal')\n\n def test_replica_lookup(self, mocker):\n mock_rucio = mocker.MagicMock(RucioAdapter)\n mock_rucio.find_replicas.return_value = [\n {\n \"adler32\": \"ad:efb2b057\",\n \"events\": 1000,\n \"bytes\": 689123\n }\n ]\n\n mock_sel_path = mocker.patch.object(\n servicex.did_finder.rucio_adapter.RucioAdapter, \"get_sel_path\")\n mock_sel_path.return_value = \"mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.1\"\n\n mock_servicex = mocker.MagicMock(ServiceXAdapter)\n request = LookupRequest(\"123-45\", \"my-did\", mock_rucio, mock_servicex, chunk_size=2)\n request.replica_lookup_queue = Queue(5)\n request.replica_lookup_queue.put_nowait([\"file1\", \"file2\"])\n request.replica_lookup()\n mock_rucio.find_replicas.assert_called_with([\"file1\", \"file2\"], None)\n mock_sel_path.assert_called_with(\n mock_rucio.find_replicas.return_value[0],\n '',\n None\n )\n\n mock_servicex.put_file_add.assert_called_with({\n 'adler32': 'ad:efb2b057',\n 'file_events': 0,\n 'file_path': 'mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.1',\n 'file_size': 689123,\n 'req_id': '123-45'\n })\n\n mock_servicex.post_preflight_check.assert_called_once()\n mock_servicex.post_preflight_check.assert_called_with({\n 'adler32': 'ad:efb2b057',\n 'file_events': 0,\n 'file_path': 'mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.1',\n 'file_size': 689123,\n 'req_id': '123-45'\n })\n\n def test_report_preflight_once(self, mocker):\n mock_rucio = mocker.MagicMock(RucioAdapter)\n mock_rucio.find_replicas.return_value = [\n {\n \"adler32\": \"ad:efb2b057\",\n \"events\": 1000,\n \"bytes\": 689123\n },\n {\n \"adler32\": \"ad:efb2b058\",\n \"events\": 2000,\n \"bytes\": 689124\n }\n ]\n\n mock_sel_path = mocker.patch.object(\n servicex.did_finder.rucio_adapter.RucioAdapter, \"get_sel_path\")\n mock_sel_path.side_effect = [\n \"mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.1\",\n \"mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.2\"\n ]\n\n mock_servicex = mocker.MagicMock(ServiceXAdapter)\n request = LookupRequest(\"123-45\", \"my-did\", mock_rucio, mock_servicex, chunk_size=2)\n request.sample_submitted = True\n\n request.replica_lookup_queue = Queue(5)\n request.replica_lookup_queue.put_nowait([\"file1\", \"file2\"])\n request.replica_lookup()\n\n mock_servicex.put_file_add.assert_has_calls(\n [\n call({\n 'adler32': 'ad:efb2b057',\n 'file_events': 0,\n 'file_path': 'mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.1',\n 'file_size': 689123,\n 'req_id': '123-45'\n }),\n call({\n 'adler32': 'ad:efb2b058',\n 'file_events': 0,\n 'file_path': 'mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.2',\n 'file_size': 689124,\n 'req_id': '123-45'\n })\n ])\n\n mock_servicex.post_preflight_check.assert_not_called()\n\n def test_fileset_complete(self, mocker):\n mock_rucio = mocker.MagicMock(RucioAdapter)\n mock_rucio.find_replicas.return_value = [\n {\n \"adler32\": \"ad:efb2b057\",\n \"events\": 1000,\n \"bytes\": 689123\n },\n {\n \"adler32\": \"ad:efb2b058\",\n \"events\": 2000,\n \"bytes\": 689124\n }\n ]\n\n mock_sel_path = mocker.patch.object(\n servicex.did_finder.rucio_adapter.RucioAdapter, \"get_sel_path\")\n mock_sel_path.side_effect = [\n \"mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.1\",\n \"mc15_13TeV:DAOD_STDM3.05630052._000013.pool.root.2\"\n ]\n\n mock_servicex = mocker.MagicMock(ServiceXAdapter)\n request = LookupRequest(\"123-45\", \"my-did\", mock_rucio, mock_servicex, chunk_size=2)\n request.sample_submitted = True\n request.file_list = [\"file1\", \"file2\"]\n\n request.replica_lookup_queue = Queue(5)\n request.replica_lookup_queue.put_nowait([\"file1\", \"file2\"])\n request.replica_lookup()\n\n mock_servicex.put_fileset_complete.assert_called_once()\n fileset_complete_args = mock_servicex.put_fileset_complete.call_args[0][0]\n assert fileset_complete_args['files'] == 2\n assert fileset_complete_args['total-bytes'] == 689123 + 689124\n","sub_path":"tests/did_finder/test_lookup_request.py","file_name":"test_lookup_request.py","file_ext":"py","file_size_in_byte":9073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"543123345","text":"from django.core.management.base import BaseCommand, CommandError\nfrom universe.models import Galaxy\nfrom universe.galaxy_generator import GeneratorGalaxy\n\nclass Command(BaseCommand):\n help = 'Simple generator'\n\n def add_arguments(self, parser):\n parser.add_argument('name', type=str)\n parser.add_argument('size_x', type=int)\n parser.add_argument('size_y', type=int)\n parser.add_argument('min',type=int)\n parser.add_argument('max',type=int)\n\n def handle(self, *args, **options):\n if Galaxy.objects.filter(name=options[\"name\"]).exists():\n raise CommandError(\"That universe already exist\")\n galaxy = Galaxy.objects.create(\n name=options[\"name\"],\n size_x=options[\"size_x\"],\n size_y=options[\"size_y\"]\n )\n generator = GeneratorGalaxy(galaxy)\n generator.generate_star_systems(start=options[\"min\"], end=options[\"max\"])\n self.stdout.write(self.style.SUCCESS('Hello galaxy %s' % options[\"name\"]))\n","sub_path":"universe/management/commands/generate_galaxy.py","file_name":"generate_galaxy.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"432923435","text":"# Class diary \n\nfrom random import randint\nfrom statistics import mean\nimport json\n\ndef add_class(classes, new_class):\n\tif new_class not in classes:\n\t\tclasses.update({new_class:[]})\n\ndef add_student(classes, student_class, name, surname):\n\tif student_class not in classes:\n\t\tprint('Class {} does not exist.'.format(student_class))\n\telse:\n\t\tstring = name + ' ' + surname\n\t\tstudent_dict = {}\n\t\tstudent_dict.update({string:{'scores':[],'attendance':[]}})\n\t\tfor s_dict in classes[student_class]:\n\t\t\tif string in s_dict:\n\t\t\t\tprint('Student {} already in the class.'.format(string))\n\t\t\t\tbreak\n\t\telse:\n\t\t\tclasses[student_class].append(student_dict)\n\ndef print_students(classes, proper_class = 'All'):\n\tif proper_class == 'All':\n\t\tfor class_name in classes:\n\t\t\tprint('Class {}:'.format(class_name))\n\t\t\tfor student_dict in classes[class_name]:\n\t\t\t\tfor student in student_dict:\n\t\t\t\t\tprint('\\t{}: grades: {}, attendance: {}'.format(student, student_dict[student]['scores'], student_dict[student]['attendance'] ))\n\telse:\n\t\tif proper_class not in classes:\n\t\t\tprint('Class {} does not exist.'.format(proper_class))\n\t\telse:\n\t\t\tprint('Class {}:'.format(proper_class))\n\t\t\tfor student_dict in classes[proper_class]:\n\t\t\t\tfor student in student_dict:\n\t\t\t\t\tprint('\\t{}: grades: {}, attendance: {}'.format(student, student_dict[student]['scores'], student_dict[student]['attendance'] ))\n\ndef be_present(classes, proper_class, name):\n\tif proper_class not in classes:\n\t\tprint('Class {} does not exist.'.format(proper_class))\n\telse:\n\t\tfor student_dict in classes[proper_class]:\n\t\t\tif name in student_dict:\n\t\t\t\tstudent_dict[name]['attendance'].append(True)\n\t\t\t\tbreak\n\t\telse:\n\t\t\tprint('Student {} does not exist in class {}.'.format(name, proper_class))\n\ndef add_grade(classes, proper_class, name, grade):\n\tif proper_class not in classes:\n\t\tprint('Class {} does not exist.'.format(proper_class))\n\telse:\n\t\tfor student_dict in classes[proper_class]:\n\t\t\tif name in student_dict:\n\t\t\t\tstudent_dict[name]['scores'].append(grade)\n\t\t\t\tbreak\n\t\telse:\n\t\t\tprint('Student {} does not exist in class {}.'.format(name, proper_class))\n\ndef stats_in_class(classes, proper_class):\n\tif proper_class not in classes:\n\t\tprint('Class {} does not exist.'.format(proper_class))\n\telse:\n\t\tprint('Statistics - class {}:'.format(proper_class))\n\t\tscores = []\n\t\tattendance = 0\n\t\tfor student_dict in classes[proper_class]:\n\t\t\tfor name in student_dict:\n\t\t\t\tprint('\\t{}: average = {}, attendance = {}'.format(name, mean(student_dict[name]['scores']), len(student_dict[name]['attendance'])))\n\t\t\t\tscores.extend(student_dict[name]['scores'])\n\t\t\t\tattendance += len(student_dict[name]['attendance'])\n\t\tprint('\\tAverage = {}, attendance = {}'.format(mean(scores), attendance))\n\ndef stats_in_school(classes):\n\tprint('Statistics - school:')\n\tscores = []\n\tattendance = 0\n\tfor class_name in classes:\n\t\tfor student_dict in classes[class_name]:\n\t\t\tfor name in student_dict:\n\t\t\t\tscores.extend(student_dict[name]['scores'])\n\t\t\t\tattendance += len(student_dict[name]['attendance'])\n\tprint('\\tAverage = {}, attendance = {}'.format(mean(scores), attendance))\n\n\ndef file_json(classes, file_name, operation = 'load'):\n\tif operation == 'save':\n\t\twith open(file_name, 'w') as outfile:\n\t\t\tjson.dump(classes, outfile)\n\t\t\treturn None\n\telse:\n\t\twith open(file_name, 'r') as infile:\n\t\t\treturn json.load(infile)\n\nif __name__ == \"__main__\":\n\n\tclasses = {}\n\n\t# classes = file_json(classes, 'classes.json')\n\n\tadd_class(classes, 'A')\n\tadd_class(classes, 'B')\n\n\tadd_student(classes, 'A', 'Eden', 'Hazard')\n\tadd_student(classes, 'A', 'Eden', 'Hazard')\n\tadd_student(classes, 'B', 'David', 'Luiz')\n\tadd_student(classes, 'A', 'Juan', 'Mata')\n\tadd_student(classes, 'C', 'Petr', 'Cech')\n\n\tbe_present(classes, 'B', 'David Luiz')\n\tbe_present(classes, 'A', 'Eden Hazard')\n\n\tadd_grade(classes, 'A', 'Juan Mata', randint(2,5))\n\tadd_grade(classes, 'A', 'Juan Mata', randint(2,5))\n\tadd_grade(classes, 'A', 'Eden Hazard', randint(2,5))\n\tadd_grade(classes, 'A', 'David Luiz', randint(2,5))\n\tadd_grade(classes, 'B', 'David Luiz', randint(2,5))\n\n\n\tprint_students(classes)\n\tstats_in_class(classes, 'A')\n\tstats_in_school(classes)\n\n\tfile_json(classes, 'classes.json', 'save')","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"427724260","text":"\"\"\"icompose_project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/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 icompose import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls import include\nfrom registration.backends.simple.views import RegistrationView\n\n\nclass MyRegistrationView(RegistrationView):\n def get_success_url(self, user):\n return '/icompose/'\n\nurlpatterns = [\n\n # Page: /\n # This is the homepage of iCompose\n url(r'^$', views.index, name='index'),\n\n # Page: /user/\n # Requests to the user page\n url(r'^user/(?P[\\w\\-]+)/$',\n views.user,\n name='user'),\n\n # Page: /user//popularajax/\n # Page used for AJAX response to view popular uploads with no limit\n url(r'^user/(?P[\\w\\-]+)/popularajax/$',\n views.user_popular_ajax,\n name='user_popular_ajax'),\n\n # Page: /user//latestajax/\n # Page used for AJAX response to view latest uploads with no limit\n url(r'^user/(?P[\\w\\-]+)/latestajax/$',\n views.user_latest_ajax,\n name='user_latest_ajax'),\n\n # Page: /user//play//\n # Requests to the play page\n url(r'^user/(?P[\\w\\-]+)/play/(?P[\\w\\-]+)/$',\n views.play,\n name='play'),\n\n # Page: /browse/\n # Browse page\n url(r'^browse/$',\n views.browse,\n name='browse'),\n\n # Page: /browse/genre/\n # Page to view all genres\n url(r'^browse/genre/$',\n views.browse_genres,\n name='browse_genres'),\n\n # Page: /browse/genre//\n # Page to view uploads of a specific genre\n url(r'^browse/genre/(?P[\\w\\-]+)/$',\n views.browse_genre,\n name='browse_genre'),\n\n # Page: /browse/popularuploads/\n # View popular uploads with no limit\n url(r'^browse/popularuploads/$',\n views.browse_popular_uploads,\n name='browse_popular_uploads'),\n\n # Page: /browse/popularuploads/ajax/\n # View table of popular uploads with no limit\n url(r'^browse/popularuploads/ajax/$',\n views.browse_popular_uploads_ajax,\n name='browse_popular_uploads_ajax'),\n\n # Page: /browse/popularusers/\n # View popular users with no limit\n url(r'^browse/popularusers/$',\n views.browse_popular_users,\n name='browse_popular_users'),\n\n # Page: /browse/popularusers/ajax/\n # View popular users with no limit\n url(r'^browse/popularusers/ajax/$',\n views.browse_popular_users_ajax,\n name='browse_popular_users_ajax'),\n\n # Page: /account/\n # View links to different pages to do with the user account.\n url(r'^account/$',\n views.account,\n name='account'),\n\n # Page: /account/editprofile/\n # Page to allow user to edit their profile.\n url(r'^account/editprofile/',\n views.edit_profile,\n name='edit_profile'),\n\n # Page: /account/upload/\n # Allows the user to upload a new song\n url(r'^account/upload/',\n views.upload_song,\n name='upload_song'),\n\n # Page: /about/\n # View details about iCompose\n url(r'^about/',\n views.about,\n name='about'),\n\n # Page: /FAQ/\n # View frequently asked questions about iCompose\n url(r'^FAQ/',\n views.FAQ,\n name='FAQ'),\n\n # Account login, logout, register, etc are handled by the registration module\n url(r'^accounts/',\n include('registration.backends.simple.urls')),\n\n # Requests to the admin interface are handled by django\n url(r'^admin/',\n admin.site.urls),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"icompose_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"353801584","text":"'''\r\nCopyright 2017 Dell Inc. or its subsidiaries. All Rights Reserved.\r\n\r\nAuthor(s):\r\nNorton Luo\r\nThis test validate the AMQP message send out in the workflow, and node delete and discover.\r\nIt also validate the web hook api and node registeration function.\r\nThs test will choose a node and reset it. After the system start reset. It will delete the node and let the node\r\nrun into discover workflow. AMQP and webhook are lunched before that in separate working thread to monitor the messages.\r\n'''\r\n\r\nfrom time import sleep\r\nimport Queue\r\nimport random\r\nimport socket\r\nimport flogging\r\nimport logging\r\nimport pika\r\nimport unittest\r\nimport json\r\nimport threading\r\nfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler\r\nimport fit_common\r\nimport test_api_utils\r\nfrom nose.plugins.attrib import attr\r\nlogs = flogging.get_loggers()\r\namqp_queue = Queue.Queue(maxsize=0)\r\nwebhook_port = 9889\r\nnodefound_id = \"\"\r\nwebhook_received = False\r\nwebhook_body = \"\"\r\n\r\n\r\nclass AmqpWorker(threading.Thread):\r\n '''\r\n This AMQP worker Class will creat another thread when initialized and runs asynchronously.\r\n The external_callback is the callback function entrance for user.\r\n The callback function will be call when AMQP message is received.\r\n Each test case can define its own callback and pass the function name to the AMQP class.\r\n The timeout parameter specify how long the AMQP daemon will run. self.panic is called when timeout.\r\n eg:\r\n def callback(self, ch, method, properties, body):\r\n logs.debug(\" [x] %r:%r\" % (method.routing_key, body))\r\n logs.debug(\" [x] %r:%r\" % (method.routing_key, body))\r\n\r\n td = fit_amqp.AMQP_worker(\"node.added.#\", callback)\r\n td.setDaemon(True)\r\n td.start()\r\n\r\n TODO:\r\n The common AMQP related test module of FIT is being refactoring. This AMQP test class is only for temporary use.\r\n It will be obsolete and replaced by a common AMQP test module.\r\n '''\r\n\r\n def __init__(self, exchange_name, topic_routing_key, external_callback, timeout=10):\r\n threading.Thread.__init__(self)\r\n pika_logger = logging.getLogger('pika')\r\n if fit_common.VERBOSITY >= 8:\r\n pika_logger.setLevel(logging.DEBUG)\r\n elif fit_common.VERBOSITY >= 4:\r\n pika_logger.setLevel(logging.WARNING)\r\n else:\r\n pika_logger.setLevel(logging.ERROR)\r\n amqp_port = fit_common.fitports()['amqp_ssl']\r\n self.connection = pika.BlockingConnection(\r\n pika.ConnectionParameters(host=fit_common.fitargs()[\"rackhd_host\"], port=amqp_port))\r\n self.channel = self.connection.channel()\r\n result = self.channel.queue_declare(exclusive=True)\r\n queue_name = result.method.queue\r\n self.channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key=topic_routing_key)\r\n self.channel.basic_consume(external_callback, queue=queue_name)\r\n self.connection.add_timeout(timeout, self.dispose)\r\n\r\n def dispose(self):\r\n logs.debug_7('Pika connection timeout')\r\n if self.connection.is_closed is False:\r\n self.channel.stop_consuming()\r\n self.connection.close()\r\n self.thread_stop = True\r\n\r\n def run(self):\r\n logs.debug_7('start consuming')\r\n self.channel.start_consuming()\r\n\r\n\r\nclass RequestHandler(BaseHTTPRequestHandler):\r\n def do_POST(self):\r\n request_headers = self.headers\r\n content_length = request_headers.getheaders('content-length')\r\n length = int(content_length[0]) if content_length else 0\r\n global webhook_received, webhook_body\r\n webhook_received = True\r\n webhook_body = str(self.rfile.read(length))\r\n logs.debug(webhook_body)\r\n self.send_response(200)\r\n\r\n\r\nclass HttpWorker(threading.Thread):\r\n def __init__(self, port, timeout=10):\r\n threading.Thread.__init__(self)\r\n self.server = HTTPServer(('', port), RequestHandler)\r\n self.server.timeout = timeout\r\n\r\n def dispose(self):\r\n logs.debug('http service shutdown')\r\n self.thread_stop = True\r\n\r\n def run(self):\r\n self.server.handle_request()\r\n self.dispose()\r\n\r\n\r\n@attr(all=True, regression=False, smoke=False)\r\nclass test_node_rediscover_amqp_message(unittest.TestCase):\r\n def setup(self):\r\n logs.debug_3('start rediscover')\r\n\r\n def teardown(self):\r\n logs.debug_3('finished rediscover')\r\n\r\n def _wait_for_discover(self, node_uuid):\r\n # start amqp thread\r\n timecount = 0\r\n while timecount < 600:\r\n if amqp_queue.empty() is False:\r\n check_message = amqp_queue.get()\r\n if check_message[0][0:10] == \"node.added\":\r\n if self._wait_for_uuid(node_uuid):\r\n self._process_message(\r\n \"added\", check_message[1], check_message[1], \"node\", check_message)\r\n global nodefound_id\r\n nodefound_id = check_message[1]\r\n return True\r\n sleep(1)\r\n timecount = timecount + 1\r\n logs.debug_2(\"Wait to rediscover Timeout!\")\r\n return False\r\n\r\n def _set_web_hook(self, ip, port):\r\n mondata = fit_common.rackhdapi('/api/current/hooks')\r\n self.assertTrue(\r\n mondata['status'] < 209,\r\n 'Incorrect HTTP return code, could not check hooks. expected<209, got:' + str(mondata['status']))\r\n hookurl = \"http://\" + str(ip) + \":\" + str(port)\r\n for hooks in mondata['json']:\r\n if hooks['url'] == hookurl:\r\n logs.debug(\"Hook URL already exist in RackHD\")\r\n return\r\n response = fit_common.rackhdapi(\r\n '/api/current/hooks',\r\n action='post',\r\n payload={\r\n \"name\": \"FITdiscovery\",\r\n \"url\": hookurl,\r\n \"filters\": [{\"type\": \"node\",\r\n \"action\": \"discovered\"}]})\r\n self.assertTrue(\r\n response['status'] < 209,\r\n 'Incorrect HTTP return code, expected<209, got:' + str(response['status']))\r\n\r\n def _apply_obmsetting_to_node(self, nodeid):\r\n # usr = ''\r\n # pwd = ''\r\n response = fit_common.rackhdapi(\r\n '/api/2.0/nodes/' + nodeid + '/catalogs/bmc')\r\n bmcip = response['json']['data']['IP Address']\r\n # Try credential record in config file\r\n for creds in fit_common.fitcreds()['bmc']:\r\n if fit_common.remote_shell(\r\n 'ipmitool -I lanplus -H ' + bmcip + ' -U ' + creds['username'] + ' -P ' +\r\n creds['password'] + ' fru')['exitcode'] == 0:\r\n usr = creds['username']\r\n pwd = creds['password']\r\n break\r\n # Put the credential to OBM settings\r\n if usr != \"\":\r\n payload = {\r\n \"service\": \"ipmi-obm-service\",\r\n \"config\": {\r\n \"host\": bmcip,\r\n \"user\": usr,\r\n \"password\": pwd},\r\n \"nodeId\": nodeid}\r\n api_data = fit_common.rackhdapi(\"/api/2.0/obms\", action='put', payload=payload)\r\n if api_data['status'] == 201:\r\n return True\r\n return False\r\n\r\n def _node_registration_validate(self, amqp_body):\r\n try:\r\n amqp_body_json = json.loads(amqp_body)\r\n except ValueError:\r\n self.fail(\"FAILURE - The message body is not json format!\")\r\n self.assertIn(\"nodeId\", amqp_body_json[\"data\"], \"nodeId is not contained in the discover message\")\r\n self.assertNotEquals(\r\n amqp_body_json[\"data\"][\"nodeId\"], \"\", \"nodeId generated in discovery doesn't include valid data \")\r\n self.assertIn(\r\n \"ipMacAddresses\", amqp_body_json[\"data\"], \"ipMacAddresses is not contained in the discover message\")\r\n self.assertNotEquals(\r\n amqp_body_json[\"data\"][\"ipMacAddresses\"], \"\",\r\n \"ipMacAddresses generated during node discovery doesn't include valid data \")\r\n\r\n def _wait_for_uuid(self, node_uuid):\r\n for dummy in range(0, 20):\r\n sleep(30)\r\n rest_data = fit_common.rackhdapi('/redfish/v1/Systems/')\r\n if rest_data['json']['Members@odata.count'] == 0:\r\n continue\r\n node_collection = rest_data['json']['Members']\r\n for computenode in node_collection:\r\n nodeidurl = computenode['@odata.id']\r\n api_data = fit_common.rackhdapi(nodeidurl)\r\n if api_data['status'] > 399:\r\n break\r\n if node_uuid == api_data['json']['UUID']:\r\n return True\r\n logs.debug_3(\"Time out to find the node with uuid!\")\r\n return False\r\n\r\n def _wait_amqp_message(self, timeout):\r\n timecount = 0\r\n while amqp_queue.empty() is True and timecount < timeout:\r\n sleep(1)\r\n timecount = timecount + 1\r\n self.assertNotEquals(\r\n timecount,\r\n timeout,\r\n \"AMQP message receive timeout\")\r\n\r\n def amqp_callback(self, ch, method, properties, body):\r\n logs.debug_3(\"Routing Key {0}:\".format(method.routing_key))\r\n logs.data_log.debug_3(body.__str__())\r\n global amqp_queue, nodefound_id\r\n amqp_queue.put(\r\n [method.routing_key, fit_common.json.loads(body)[\"nodeId\"], body])\r\n nodefound_id = fit_common.json.loads(body)[\"nodeId\"]\r\n\r\n def _check_skupack(self):\r\n sku_installed = fit_common.rackhdapi('/api/2.0/skus')['json']\r\n if len(sku_installed) < 2:\r\n return False\r\n else:\r\n return True\r\n\r\n def _get_tester_ip(self):\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n ip = fit_common.fitargs()['rackhd_host']\r\n logs.debug(\"pinging \" + ip)\r\n s.connect((ip, 0))\r\n logs.debug('My IP address is: ' + s.getsockname()[0])\r\n return str(s.getsockname()[0])\r\n\r\n def _process_web_message(self, timeout):\r\n global webhook_received, webhook_body\r\n timecount = 0\r\n while webhook_received is False and timecount < timeout:\r\n sleep(1)\r\n timecount = timecount + 1\r\n self.assertNotEquals(timecount, timeout, \"Web hook message receive timeout\")\r\n try:\r\n webhook_body_json = json.loads(webhook_body)\r\n except ValueError:\r\n self.fail(\"FAILURE - The message body is not json format!\")\r\n\r\n self.assertIn(\"action\", webhook_body_json, \"action field is not contained in the discover message\")\r\n self.assertEquals(\r\n webhook_body_json['action'], \"discovered\",\r\n \"action field not correct! expect {0}, get {1}\"\r\n .format(\"discovered\", webhook_body_json['action']))\r\n self.assertIn(\"data\", webhook_body_json, \"data field is not contained in the discover message\")\r\n self.assertIn(\"nodeId\", webhook_body_json[\"data\"], \"nodeId is not contained in the discover message\")\r\n self.assertNotEquals(\r\n webhook_body_json[\"data\"][\"nodeId\"], \"\", \"nodeId generated in discovery doesn't include valid data \")\r\n self.assertIn(\r\n \"ipMacAddresses\", webhook_body_json[\"data\"], \"ipMacAddresses is not contained in the discover message\")\r\n self.assertNotEquals(\r\n webhook_body_json[\"data\"][\"ipMacAddresses\"], \"\",\r\n \"ipMacAddresses generated during node discovery doesn't include valid data \")\r\n\r\n def _process_message(self, action, typeid, nodeid, messagetype, amqp_message_body):\r\n expected_key = messagetype + \".\" + action + \".information.\" + typeid + \".\" + nodeid\r\n expected_payload = {\r\n \"type\": messagetype,\r\n \"action\": action,\r\n \"typeId\": typeid,\r\n \"nodeId\": nodeid,\r\n \"severity\": \"information\",\r\n \"version\": \"1.0\"}\r\n self._compare_message(amqp_message_body, expected_key, expected_payload)\r\n\r\n def _compare_message(self, amqpmessage, expected_key, expected_payload):\r\n routing_key = amqpmessage[0]\r\n amqp_body = amqpmessage[2]\r\n self.assertEquals(\r\n routing_key, expected_key, \"Routing key is not expected! expect {0}, get {1}\"\r\n .format(expected_key, routing_key))\r\n try:\r\n amqp_body_json = fit_common.json.loads(amqp_body)\r\n except ValueError:\r\n self.fail(\"FAILURE - The message body is not json format!\")\r\n try:\r\n self.assertEquals(\r\n amqp_body_json['version'], expected_payload['version'],\r\n \"version field not correct! expect {0}, get {1}\"\r\n .format(expected_payload['version'], amqp_body_json['version']))\r\n self.assertEquals(\r\n amqp_body_json['typeId'], expected_payload['typeId'],\r\n \"typeId field not correct! expect {0}, get {1}\"\r\n .format(expected_payload['typeId'], amqp_body_json['typeId']))\r\n self.assertEquals(\r\n amqp_body_json['action'], expected_payload['action'],\r\n \"action field not correct! expect {0}, get {1}\"\r\n .format(expected_payload['action'], amqp_body_json['action']))\r\n self.assertEquals(\r\n amqp_body_json['severity'], expected_payload['severity'],\r\n \"serverity field not correct!\" .format(expected_payload['severity'], amqp_body_json['severity']))\r\n self.assertNotEquals(amqp_body_json['createdAt'], \"\", \"createdAt field is empty!\")\r\n self.assertNotEquals(amqp_body_json['data'], {}, \"data field is empty!\")\r\n except ValueError as e:\r\n self.fail(\"FAILURE - expected key is missing in the AMQP message!{0}\".format(e))\r\n\r\n def _select_node(self):\r\n node_collection = test_api_utils.get_node_list_by_type(\"compute\")\r\n self.assertNotEquals(node_collection, [], \"No compute node found!\")\r\n for dummy in node_collection:\r\n nodeid = node_collection[random.randint(0, len(node_collection) - 1)]\r\n if fit_common.rackhdapi('/api/2.0/nodes/' + nodeid)['json']['name'] != \"Management Server\":\r\n break\r\n return nodeid\r\n\r\n def _node_reboot(self, nodeid):\r\n # Reboot the node to begin rediscover.\r\n logs.debug_3('Running rediscover, resetting system node...')\r\n logs.debug('launch AMQP thread')\r\n reset_worker = AmqpWorker(\r\n exchange_name=\"on.events\", topic_routing_key=\"graph.#.\" + nodeid,\r\n external_callback=self.amqp_callback, timeout=100)\r\n reset_worker.setDaemon(True)\r\n reset_worker.start()\r\n\r\n # Reboot the node, wait reboot workflow start message.\r\n response = fit_common.rackhdapi(\r\n '/redfish/v1/Systems/' + nodeid + '/Actions/ComputerSystem.Reset', action='post',\r\n payload={\"reset_type\": \"ForceRestart\"})\r\n self.assertTrue(\r\n response['status'] < 209, 'Incorrect HTTP return code, expected<209, got:' + str(response['status']))\r\n graphid = response['json'][\"@odata.id\"].split('/redfish/v1/TaskService/Tasks/')[1]\r\n\r\n # wait for workflow started message.\r\n self._wait_amqp_message(10)\r\n workflow_amqp = amqp_queue.get()\r\n if workflow_amqp[0][0:14] == \"started\":\r\n self._process_message(\"started\", graphid, nodeid, \"graph\", workflow_amqp)\r\n else:\r\n self._process_message(\"progress.updated\", graphid, nodeid, \"graph\", workflow_amqp)\r\n\r\n # wait for progress update finish message.\r\n self._wait_amqp_message(10)\r\n workflow_amqp = amqp_queue.get()\r\n self._process_message(\"progress.updated\", graphid, nodeid, \"graph\", workflow_amqp)\r\n\r\n # wait for progress finish message.\r\n retry_count = 0\r\n while retry_count < 10:\r\n self._wait_amqp_message(60)\r\n workflow_amqp = amqp_queue.get()\r\n if workflow_amqp[0][0:14] == \"graph.finished\":\r\n self._process_message(\"finished\", graphid, nodeid, \"graph\", workflow_amqp)\r\n break\r\n retry_count = retry_count + 1\r\n self.assertNotEquals(retry_count, 10, \"No AMQP workflow finished message received\")\r\n reset_worker.dispose()\r\n\r\n def _node_delete(self, nodeid):\r\n logs.debug('launch node delete AMQP thread')\r\n td = AmqpWorker(\r\n exchange_name=\"on.events\", topic_routing_key=\"node.#.information.\" + nodeid + \".#\",\r\n external_callback=self.amqp_callback, timeout=30)\r\n td.setDaemon(True)\r\n td.start()\r\n result = fit_common.rackhdapi('/api/2.0/nodes/' + nodeid, action='delete')\r\n self.assertTrue(result['status'] < 209, 'Was expecting response code < 209. Got ' + str(result['status']))\r\n self._wait_amqp_message(10)\r\n amqp_message = amqp_queue.get()\r\n self._process_message(\"removed\", nodeid, nodeid, \"node\", amqp_message)\r\n td.dispose()\r\n\r\n def _node_discover(self, node_uuid):\r\n # start discovery\r\n logs.debug_2(\"Waiting node reboot and boot into microkernel........\")\r\n myip = self._get_tester_ip()\r\n self._set_web_hook(myip, webhook_port)\r\n logs.debug('Listening on localhost:%s' % webhook_port)\r\n global webhook_received\r\n webhook_received = False\r\n serverworker = HttpWorker(webhook_port, 300)\r\n serverworker.setDaemon(True)\r\n serverworker.start()\r\n\r\n # clear the amqp message queue\r\n while amqp_queue.empty is False:\r\n amqp_queue.get()\r\n\r\n logs.debug('launch AMQP thread for discovery')\r\n discover_worker = AmqpWorker(\r\n exchange_name=\"on.events\", topic_routing_key=\"node.#.information.#\", external_callback=self.amqp_callback,\r\n timeout=600)\r\n discover_worker.setDaemon(True)\r\n discover_worker.start()\r\n\r\n logs.debug('Wait for node added')\r\n # use the original node's UUID to verify the node discovered is the one we just deleted.\r\n self.assertTrue(self._wait_for_discover(node_uuid), \"Fail to find the orignial node after reboot!\")\r\n logs.debug_2(\"Found the original node. It is rediscovered successfully!\")\r\n\r\n logs.debug('Wait for node discovery')\r\n self._wait_amqp_message(60)\r\n amqp_message_discover = amqp_queue.get()\r\n self._process_message(\"discovered\", nodefound_id, nodefound_id, \"node\", amqp_message_discover)\r\n\r\n logs.debug('Validate node discovery registration AMQP Message')\r\n self._node_registration_validate(amqp_message_discover[2])\r\n logs.debug('Validate node discovery registration web hook Message')\r\n self._process_web_message(30)\r\n\r\n # skip sku.assigned message if no skupack is installed on RackHD\r\n skupack_intalled = self._check_skupack()\r\n if skupack_intalled:\r\n logs.debug_2(\"wait for skupack assign!\")\r\n self._wait_amqp_message(50)\r\n amqp_message_discover = amqp_queue.get()\r\n self._process_message(\"sku.assigned\", nodefound_id, nodefound_id, \"node\", amqp_message_discover)\r\n else:\r\n logs.warning(\"skupack is not installed, skip sku assigned message check!\")\r\n logs.debug_3(\"wait for obm assign!\")\r\n\r\n # re-apply obm setting to the node to generate obm.assigned message\r\n self.assertTrue(self._apply_obmsetting_to_node(nodefound_id), \"Fail to apply obm setting!\")\r\n self._wait_amqp_message(50)\r\n amqp_message_discover = amqp_queue.get()\r\n self._process_message(\"obms.assigned\", nodefound_id, nodefound_id, \"node\", amqp_message_discover)\r\n logs.debug_3(\"wait for accessible!\")\r\n self._wait_amqp_message(100)\r\n amqp_message_discover = amqp_queue.get()\r\n self._process_message(\"accessible\", nodefound_id, nodefound_id, \"node\", amqp_message_discover)\r\n discover_worker.dispose()\r\n\r\n def test_rediscover(self):\r\n nodeid = self._select_node()\r\n logs.debug_2('Checking OBM setting...')\r\n node_obm = fit_common.rackhdapi('/api/2.0/nodes/' + nodeid)['json']['obms']\r\n if node_obm == []:\r\n self.assertTrue(self._apply_obmsetting_to_node(nodeid), \"Fail to apply obm setting!\")\r\n node_uuid = fit_common.rackhdapi('/redfish/v1/Systems/' + nodeid)['json']['UUID']\r\n logs.debug_3('UUID of selected Node is:{}'.format(node_uuid))\r\n self._node_reboot(nodeid)\r\n self._node_delete(nodeid)\r\n self._node_discover(node_uuid)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"test/tests/amqp/test_amqp_node_rediscover.py","file_name":"test_amqp_node_rediscover.py","file_ext":"py","file_size_in_byte":20714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"353322508","text":"# !/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n'a test module'\n\n__author__ = 'Johnny Yao'\n\nimport sys\n\ndef test():\n args = sys.argv\n if len(args) == 1:\n print('hello,world')\n elif len(args) == 2:\n print('hello,%s'%args[1])\n else:\n print('too many argments!')\n\na = 100\n_a = 200\n__a = 300\n\nif __name__ == '__main__':\n test()\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"512666112","text":"# 如果要启动大量的紫禁城,可以用进程池的方式批量创建子进程\r\n\r\nfrom multiprocessing import Pool\r\nimport os,time,random\r\n\r\ndef long_time_task(name) :\r\n print('Run task %s (%s)...' % (name,os.getpid()))\r\n start = time.time()\r\n time.sleep(random.random() * 3)\r\n end = time.time()\r\n print('Task %s runs %0.2f seconds.' % (name,(end - start)))\r\n\r\nif __name__ == '__main__' :\r\n print('Parent process %s.' % os.getpid())\r\n p = Pool(4)\r\n for i in range(5):\r\n p.apply_async(long_time_task,args = (i,))\r\n print('Waiting for subprocesses done...')\r\n p.close()\r\n p.join()\r\n print('All subprocesses done.')\r\n'''\r\n# 子进程\r\n# 很多时候,子进程并不是自身,而是一个外部进程。我们创建了子进程后,还需要\r\n要控制子进程的输入和输出\r\nsubprocess可以让我们非常方便地启动一个子进程,然后控制其输入和输出\r\n'''\r\n\r\nimport subprocess\r\nprint('$ nslookup www.python.org')\r\nr = subprocess.call(['nslookup','www.python.org'])\r\nprint('Exit code:',r)\r\n\r\n# 如果子进程还需要输入,则可以通过communicate()输入:\r\np = subprocess.Popen(['nslookup'],stdin = subprocess.PIPE,\\\r\n stdout = subprocess.PIPE,stderr = subprocess.PIPE)","sub_path":"Python/1711122_poll.py","file_name":"1711122_poll.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"26137008","text":"# coding=utf-8\n\nimport socket\nimport threading\n\nclass FTPServer:\n\n \"\"\"\n 多线程的FTP服务端\n \"\"\"\n\n def __init__(self, host, port, backlog):\n \"\"\"\n 初始化Server\n :param host: 地址名\n :param port: 端口\n :param backlog: 最大等待数量\n :return:\n \"\"\"\n\n self.host = host\n self.port = port\n self.backlog = backlog\n # 存储已经连接的客户端\n self.clients = []\n # socket\n # 设置成 TCP , 面向连接\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # SO_REUSEPORT\n # https://my.oschina.net/miffa/blog/390931\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n # 绑定socket\n self.sock.bind((self.host, self.port))\n\n # 用于停止服务\n self.__stop = False\n\n def listen(self):\n # 开启监听\n print(\"Server: start listening\")\n self.sock.listen(self.backlog)\n\n def accept_connections(self, client_handler, command_handler, file_handler, new_threading=False, daemon=True):\n \"\"\"\n 开始监听\n :param client_handler: 处理和客户端的通信的类, 需要有recv方法, 初始化方法接受 command_handler 和 file_handler 为参数\n :param command_handler: 处理命令的handler\n :param file_handler: 处理文件的handler, 用于保存接受到的文件\n :param new_threading: 是否在新进程中运行\n :param daemon: 是否是后台线程\n :return:\n \"\"\"\n print(\"Server: start accepting connections\")\n if not callable(client_handler):\n raise TypeError(\"client_handler must be callable\")\n while not self.__stop:\n client_handler_obj = client_handler(command_handler, file_handler)\n # 接收请求\n client, address = self.sock.accept()\n print(\"new client:\", address)\n # 添加client到list中\n self.clients.append(client)\n # 设置超时时间\n # client.settimeout(60 * 10)\n # 是否开启新的线程\n if not new_threading:\n client_handler(client, address)\n else:\n # 在另外一个线程中进行服务\n thread = threading.Thread(target=client_handler_obj.recv, args=(client, address))\n thread.setDaemon(daemon)\n thread.start()\n\n def stop(self):\n self.__stop = True\n for client in self.clients:\n client.close()\n\n","sub_path":"server/threaded_server.py","file_name":"threaded_server.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"530411135","text":"from django.shortcuts import render, redirect\nfrom .models import *\nfrom django.contrib import messages\nimport bcrypt\n# Create your views here.\n\ndef index(request):\n return render(request, 'index.html')\n\ndef register(request):\n form = request.POST\n errors_returned = User.objects.register_validator(form)\n # print(errors_returned)\n if len(errors_returned) > 0:\n request.session['register_error'] = True\n for single_error in errors_returned.values():\n messages.error(request, single_error)\n return redirect('/')\n hashed_pw = bcrypt.hashpw(form['password'].encode(), bcrypt.gensalt()).decode()\n new_user = User.objects.create(first_name=form['first_name'], last_name=form['last_name'], username=form['username'], email=form['email'], password=hashed_pw)\n request.session['user_id']=new_user.id\n return redirect('/homepage')\n\ndef login(request):\n form = request.POST\n login_errors = User.objects.login_validator(form)\n if len(login_errors) > 0:\n request.session['register_error'] = False\n for login_error in login_errors.values():\n messages.error(request, login_error)\n return redirect('/')\n user_id = User.objects.get(username=form['username']).id\n request.session['user_id'] = user_id \n return redirect('/homepage')\n\ndef post_blogs(request):\n context = {\n 'current_user': User.objects.get(id=request.session['user_id'])\n }\n return render(request, 'post_blogs.html', context)\n\ndef process_blog(request):\n form = request.POST\n current_user = User.objects.get(id=request.session['user_id'])\n Blog.objects.create(title=form['title'], content=form['content'], created_by=current_user)\n return redirect('/post_blogs')\n\ndef homepage(request):\n if 'user_id' not in request.session:\n return redirect('/')\n context = {\n 'blogs': Blog.objects.all(),\n 'current_user': User.objects.get(id=request.session['user_id'])\n }\n return render(request, 'homepage.html', context)\n\ndef logout(request):\n request.session.clear()\n return redirect('/')","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"405554055","text":"# Copyright 2021 VMware, Inc.\n# SPDX-License-Identifier: Apache-2.0\nimport json\nimport logging\nimport time\nfrom typing import Optional\n\nfrom requests import post\nfrom requests.auth import HTTPBasicAuth\nfrom requests_oauthlib import OAuth2Session\nfrom vdk.internal.control.auth.auth_request_values import AuthRequestValues\nfrom vdk.internal.control.auth.login_types import LoginTypes\nfrom vdk.internal.control.configuration.vdk_config import VDKConfig\nfrom vdk.internal.control.configuration.vdk_config import VDKConfigFolder\nfrom vdk.internal.control.exception.vdk_exception import VDKException\n\nlog = logging.getLogger(__name__)\n\n\nclass AuthenticationCache:\n \"\"\"\n Class used to keep the fields in the vdk-cred.json file from which authorization and authentication\n tokens can be taken\n \"\"\"\n\n def __init__(\n self,\n authorization_url=None,\n refresh_token=None,\n access_token=None,\n access_token_expiration_time=0,\n client_id=\"not-used\",\n client_secret=\"not-used\",\n api_token=None,\n api_token_authorization_url=None,\n auth_type=None,\n **ignored_kwargs,\n ):\n \"\"\"\n\n :param authorization_url:\n Token or Authorization URI used to exchange grant for access token\n :param refresh_token:\n Used in refresh token grant type flow; See https://tools.ietf.org/html/rfc6749#section-1.5\n :param access_token:\n Cached access token used during requests; See https://tools.ietf.org/html/rfc6749#section-1.4\n :param access_token_expiration_time:\n When the access token expires (epoch seconds - same as time.time() return)\n :param client_id:\n The client identifier; See https://tools.ietf.org/html/rfc6749#section-2.3.1\n :param api_token:\n Token used to grant access to the API, including exchange for access token\n :param api_token_authorization_url:\n The URL which exchanges api_token for access token\n \"\"\"\n #\n self.authorization_url = authorization_url\n self.refresh_token = refresh_token\n self.access_token = access_token\n self.access_token_expiration_time = access_token_expiration_time\n self.client_id = client_id\n self.client_secret = client_secret\n self.api_token = api_token\n self.api_token_authorization_url = api_token_authorization_url\n self.auth_type = auth_type\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n\nclass AuthenticationCacheSerDe:\n @staticmethod\n def serialize(cache):\n return json.dumps(cache.__dict__)\n\n @staticmethod\n def deserialize(content: str):\n if content:\n return AuthenticationCache(**json.loads(content))\n else:\n return AuthenticationCache()\n\n\nclass Authentication:\n REFRESH_TOKEN_GRANT_TYPE = \"refresh_token\" # nosec\n\n def __init__(self, conf=VDKConfigFolder(), vdk_config=VDKConfig()):\n self._conf = conf\n self.__vdk_config = vdk_config\n self._cache = self.__load_cache()\n\n def __load_cache(self):\n content = self._conf.read_credentials()\n return AuthenticationCacheSerDe.deserialize(content)\n\n def __update_cache(self):\n self._conf.save_credentials(AuthenticationCacheSerDe.serialize(self._cache))\n\n def __exchange_api_for_access_token(self):\n try:\n log.debug(\n f\"Refresh API token against {self._cache.api_token_authorization_url} \"\n )\n client = OAuth2Session()\n token_response = client.refresh_token(\n self._cache.api_token_authorization_url,\n refresh_token=self._cache.api_token,\n )\n log.debug(\n f\"Token response received: \"\n f\"token_type: {token_response.get('token_type', None)}; \"\n f\"expires_in: {token_response.get('expires_in', None)}; \"\n f\"scope: {token_response.get('scope', None)}\"\n )\n except Exception as e:\n raise VDKException(\n what=\"Failed to login\",\n why=f\"Authorization server at {self._cache.api_token_authorization_url} returned error: {str(e)}\",\n consequence=\"Your credentials are not refreshed and VDK CLI operations that require authentication \"\n \"will not work.\",\n countermeasure=\"Check error message and follow instructions in it. Check your network connectivity.\"\n \" Check if you can access the Oauth2 server. Retry to login a few times again.\"\n \" Contact SRE Team operating Oauth2 server for help if nothing else works.\",\n ) from e\n # Response per spec in https://tools.ietf.org/html/rfc6750#section-4\n # see also https://www.oauth.com/oauth2-servers/access-tokens/access-token-response\n self.update_access_token(\n token_response[AuthRequestValues.ACCESS_TOKEN_KEY.value]\n )\n self.update_access_token_expiration_time(\n time.time()\n + int(token_response.get(AuthRequestValues.EXPIRATION_TIME_KEY.value, \"0\"))\n )\n\n def read_access_token(self) -> Optional[str]:\n \"\"\"\n Read access token from _cache or fetch it from Authorization server.\n If not available in _cache it will get it using provided configuration during VDK CLI login to fetch it.\n If it detects that token is about to expire it will try to refresh it.\n :return: the access token or None if it cannot detect any credentials.\n \"\"\"\n if (\n not self._cache.access_token\n or self._cache.access_token_expiration_time < time.time() + 60\n ):\n log.debug(\"Acquire access token (it's either expired or missing) ...\")\n self.acquire_and_cache_access_token()\n return self._cache.access_token\n\n def acquire_and_cache_access_token(self):\n \"\"\"\n Acquires and caches access token\n \"\"\"\n log.debug(f\"Using auth type {self._cache.auth_type} to acquire access token\")\n if (\n self._cache.auth_type == LoginTypes.API_TOKEN.value\n and self._configured_api_token()\n ):\n self.__exchange_api_for_access_token()\n elif (\n self._cache.auth_type == LoginTypes.CREDENTIALS.value\n and self._configured_refresh_token()\n ):\n self.__exchange_refresh_for_access_token()\n elif (\n self.__vdk_config.api_token\n and self.__vdk_config.api_token_authorization_url\n ):\n self.update_api_token(self.__vdk_config.api_token)\n self.update_api_token_authorization_url(\n self.__vdk_config.api_token_authorization_url\n )\n self.__exchange_api_for_access_token()\n else:\n log.debug(\n \"No authentication mechanism found. Will not cache access token.\"\n \"If Control Service authentication is enabled, API calls will fail.\"\n )\n\n def __exchange_refresh_for_access_token(self):\n basic_auth = HTTPBasicAuth(self._cache.client_id, self._cache.client_secret)\n headers = {\n AuthRequestValues.CONTENT_TYPE_HEADER.value: AuthRequestValues.CONTENT_TYPE_URLENCODED.value,\n }\n data = (\n f\"grant_type={self.REFRESH_TOKEN_GRANT_TYPE}&\"\n + f\"refresh_token={self._cache.refresh_token}\"\n )\n log.debug(\n f\"Refresh access token against {self._cache.authorization_url} grant_type={self.REFRESH_TOKEN_GRANT_TYPE}\"\n )\n response = post(\n self._cache.authorization_url, data=data, headers=headers, auth=basic_auth\n )\n json_data = json.loads(response.text)\n log.debug(\n f\"Refresh access token response received: status: {response.status_code}\"\n )\n self.update_access_token(json_data[AuthRequestValues.ACCESS_TOKEN_KEY.value])\n self.update_access_token_expiration_time(\n time.time() + int(json_data[AuthRequestValues.EXPIRATION_TIME_KEY.value])\n )\n\n def update_api_token_authorization_url(self, api_token_authorization_url):\n \"\"\"\n Updates and caches authorization URL\n \"\"\"\n self._cache.api_token_authorization_url = api_token_authorization_url\n self.__update_cache()\n\n def update_api_token(self, api_token):\n \"\"\"\n Updates and caches refresh token\n \"\"\"\n self._cache.api_token = api_token\n self.__update_cache()\n\n def update_refresh_token(self, refresh_token):\n \"\"\"\n Updates and caches refresh token\n \"\"\"\n self._cache.refresh_token = refresh_token\n self.__update_cache()\n\n def update_client_id(self, client_id):\n \"\"\"\n Updates and caches refresh token\n \"\"\"\n self._cache.client_id = client_id\n self.__update_cache()\n\n def update_client_secret(self, client_secret):\n \"\"\"\n Updates and caches refresh token\n \"\"\"\n self._cache.client_secret = client_secret\n self.__update_cache()\n\n def update_access_token(self, access_token):\n \"\"\"\n Updates and caches refresh token\n \"\"\"\n self._cache.access_token = access_token\n self.__update_cache()\n\n def update_access_token_expiration_time(self, access_token_expiration_time):\n \"\"\"\n Updates and caches refresh token\n \"\"\"\n self._cache.access_token_expiration_time = access_token_expiration_time\n self.__update_cache()\n\n def update_oauth2_authorization_url(self, authorization_url):\n self._cache.authorization_url = authorization_url\n self.__update_cache()\n\n def update_auth_type(self, auth_type):\n self._cache.auth_type = auth_type\n self.__update_cache()\n\n def _configured_api_token(self):\n return self._cache.api_token and self._cache.api_token_authorization_url\n\n def _configured_refresh_token(self):\n return (\n self._cache.refresh_token\n and self._cache.authorization_url\n and self._cache.client_id\n and self._cache.client_secret\n )\n","sub_path":"projects/vdk-control-cli/src/vdk/internal/control/auth/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":10272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"510305341","text":"from gym.envs import toy_text\nfrom collections import defaultdict\nfrom collections import namedtuple\nfrom typing import List\nimport numpy as np\nimport monte_carlo.plotting as plotting\n\nStep = namedtuple('Step', ('state', 'action', 'reward'))\n\n\ndef print_observation(observation):\n score, dealer_score, usable_ace = observation\n print(\"Player Score: {} (Usable Ace: {}), Dealer Score: {}\".format(\n score, usable_ace, dealer_score))\n\n\nenv = toy_text.BlackjackEnv()\n\n\nclass Policy(object):\n def __init__(self, env, epsilon, q):\n self.env = env\n self.epsilon = epsilon\n self.q = q\n\n def choose_action(self, state):\n def calc_prob(action, epsilon, a_size, best_action):\n if action == best_action:\n return 1 - epsilon + epsilon / a_size\n else:\n return epsilon / a_size\n\n q = self.q\n if len(q[state]) > 0:\n best_action = max(q[state], key=q[state].get)\n probs_dict = {a: calc_prob(a, self.epsilon, self.env.action_space.n, best_action)\n for a in range(self.env.action_space.n)}\n return np.random.choice(list(probs_dict.keys()), p=list(probs_dict.values()))\n else:\n return self.env.action_space.sample()\n\n\ndef create_episode(env, policy) -> List[Step]:\n ep = []\n s_i = env.reset()\n while True:\n a_i = policy.choose_action(s_i)\n s_i_1, r_i_1, done, _ = env.step(a_i)\n ep.append(Step(s_i, a_i, r_i_1))\n s_i = s_i_1\n if done:\n break\n return ep\n\n\ndef mc_control(env, num_episodes, gamma, epsilon):\n q = defaultdict(lambda: defaultdict(float))\n policy = Policy(env, epsilon, q)\n returns = defaultdict(list)\n\n for i in range(num_episodes):\n ep = create_episode(env, policy)\n g = 0\n visited_sa = set()\n for step in ep[::-1]:\n g = gamma * g + step.reward\n current_sa = (step.state, step.action)\n if current_sa not in visited_sa:\n returns[current_sa].append(g)\n q[step.state][step.action] = np.average(returns[current_sa])\n policy.q = q\n visited_sa.add(current_sa)\n if i % 100 == 0:\n print(\"Ep %s: %s\" % (i, check_win_ratio(env, policy, 10000)))\n return policy\n\n\ndef simulate_episode(env, policy):\n ep = []\n state = env.reset()\n for t in range(100):\n action = policy.choose_action(state)\n next_state, reward, done, info = env.step(action)\n ep.append(Step(state, action, reward)) # (S_i, A_i, R_(i+1))\n state = next_state\n if done:\n if reward == 1:\n result = 'win'\n elif reward == 0:\n result = 'draw'\n else:\n result = 'lose'\n ep.append((state, toy_text.blackjack.score(env.dealer), result))\n break\n return ep\n\n\ndef check_win_ratio(env, policy, num_ep):\n sim_results = [simulate_episode(env, policy) for i in range(num_ep)]\n total_wins = sum(1 if x[-1][-1]=='win' else 0 for x in sim_results)\n total_draw = sum(1 if x[-1][-1] == 'draw' else 0 for x in sim_results)\n total_lose = sum(1 if x[-1][-1] == 'lose' else 0 for x in sim_results)\n win_ratio = total_wins / num_ep\n draw_ratio = total_draw / num_ep\n lose_ratio = total_lose / num_ep\n return win_ratio, draw_ratio, lose_ratio\n\n\nif __name__ == \"__main__\":\n print(\"Training ....\")\n policy = mc_control(env, 10000, 0.99, 0.05)\n print(\"eval: \")\n print(check_win_ratio(env, policy, 10000))\n\n\n","sub_path":"src/monte_carlo_v2/epsilon_greedy_blackjack.py","file_name":"epsilon_greedy_blackjack.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"501469152","text":"#!/usr/bin/env python\n\nfrom pybroker import *\nfrom select import select\nfrom argparse import ArgumentParser\n\n\nintel_types = (\n\t'ADDR',\n\t'SUBNET',\n\t'URL',\n\t'SOFTWARE',\n\t'EMAIL',\n\t'DOMAIN',\n\t'USER_NAME',\n\t'CERT_HASH',\n\t'PUBKEY_HASH')\n\n\ndef get_arguments():\n\tparser = ArgumentParser(description='This script deletes intelligence'\n \t\t' indicators from Bro using broker.')\n\tparser.add_argument('indicator', metavar='INDICATOR', type=str,\n\t\thelp='Intel indicator')\n\tparser.add_argument('indicator_type', metavar='TYPE', type=str.upper,\n\t\tchoices=intel_types, help='Intel indicator\\'s type')\n\tparser.add_argument('-p', metavar='PORT', type=int, default=5012,\n\t\tdest='port', help='Broker port (default: 5012)')\n\tparser.add_argument('-a', metavar='IP', type=str, default='127.0.0.1',\n\t\tdest='host', help='Broker host (default: 127.0.0.1)')\n\treturn parser.parse_args()\n\n\ndef main():\n\targs = get_arguments()\n\n\tep_bro = endpoint(\"bro_conn\")\n\tep_bro.peer(args.host, args.port)\n\tepq_bro = ep_bro.outgoing_connection_status()\n\n\tselect([epq_bro.fd()],[],[])\n\tmsgs = epq_bro.want_pop()\n\tfor m in msgs:\n\t\tif m.status != outgoing_connection_status.tag_established:\n\t\t\tprint(\"Failed to establish connection!\")\n\t\t\treturn\n\n\tm = message([\n\t\tdata(\"Intel::remote_remove\"),\n\t\tdata(args.indicator),\n\t\tdata(args.indicator_type)])\n\tep_bro.send(\"bro/intel/remove\", m)\n\tprint(\"Sent remove command for \\\"%s\\\" (%s).\"\n\t\t% (args.indicator, args.indicator_type))\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"utils/delete_intel.py","file_name":"delete_intel.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"544408729","text":"# %% 6.1\nwith open('ospf.txt', 'r') as f:\n print(f.read().replace('Fast', 'Gigabit'))\n\n\n# %% 6.2\ndef task6_2(file_name):\n with open(file_name, 'r') as f:\n file = f.readlines()\n for s in file:\n if s[0] != '!':\n print(s.rstrip())\n\n\ntask6_2('config_sw1.txt')\n\n# %% 6.2 a\ndef task6_2_a(file_name):\n ignore = ['duplex', 'alias', 'Current\tconfiguration']\n with open(file_name, 'r') as f:\n file = f.readlines()\n for s in file:\n flag = True\n if s[0] == '!':\n flag = False\n for bw in ignore:\n if bw in s:\n flag = False\n if flag:\n print(s.rstrip())\n\n\ntask6_2_a('config_sw1.txt')\n\n\n# %% 6.2 b\ndef task6_2_b(file_name):\n ignore = ['duplex', 'alias', 'Current\tconfiguration']\n with open(file_name, 'r') as f:\n file = f.readlines()\n with open('config_sw1_cleared.txt', 'w') as f:\n f.write('')\n with open('config_sw1_cleared.txt', 'a') as f:\n for s in file:\n flag = True\n for bw in ignore:\n if bw in s:\n flag = False\n if flag:\n f.write(s)\n\n\ntask6_2_b('config_sw1.txt')\n\n\n# %% 6.2 c\ndef task6_2_c(input_file_name, output_file_name):\n ignore = ['duplex', 'alias', 'Current\tconfiguration']\n with open(input_file_name, 'r') as f:\n file = f.readlines()\n with open(output_file_name, 'w') as f:\n f.write('')\n with open(output_file_name, 'a') as f:\n for s in file:\n flag = True\n for bw in ignore:\n if bw in s:\n flag = False\n if flag:\n f.write(s)\n\n\ntask6_2_c('config_sw1.txt', 'config_sw1_cleared.txt')\n\n\n# %% 6.3\nwith open('CAM_table.txt', 'r') as f:\n file = f.readlines()\nmacs = []\nfor i in file[6:]:\n print(i.rstrip())\n macs.append(i.split()[1])\nprint(macs)\n\n\n# %% 6.3 a\nwith open('CAM_table.txt', 'r') as f:\n file = f.readlines()\nfile = sorted(file[6:], key=lambda e: e[1])\nfor i in file:\n print(i.rstrip())\n\n\n# %% 6.3 b\ninp_vlan = input('Введите VLAN id: ')\nwith open('CAM_table.txt', 'r') as f:\n file = f.readlines()\nfor i in file[6:]:\n if inp_vlan == i.split()[0]:\n print(i.rstrip())\n","sub_path":"python/LR3.py","file_name":"LR3.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"603268939","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\ndef func_fit(x,y,ncoeff,invvar=None,function_name='legendre',ia=None,inputans=None,inputfunc=None):\n \"\"\"Fit `x`, `y` positions to a functional form.\n\n Parameters\n ----------\n x : array-like\n X values (independent variable).\n y : array-like\n Y values (dependent variable).\n ncoeff : :class:`int`\n Number of coefficients to fit.\n invvar : array-like, optional\n Weight values; inverse variance.\n function_name : :class:`str`, optional\n Function name, default 'legendre'.\n ia : array-like, optional\n An array of bool of length `ncoeff` specifying free (``True``) and\n fixed (``False``) parameters.\n inputans : array-like, optional\n An array of values of length `ncoeff` specifying the values of\n the fixed parameters.\n inputfunc : array-like, optional\n Multiply the function fit by these values.\n\n Returns\n -------\n func_fit : :func:`tuple` of array-like\n Fit coefficients, length `ncoeff`; fitted values.\n\n Raises\n ------\n KeyError\n If an invalid function type is selected.\n ValueError\n If input dimensions do not agree.\n \"\"\"\n import numpy as np\n from . import fchebyshev, fchebyshev_split, fpoly\n from ...goddard.math import flegendre\n if x.shape != y.shape:\n raise ValueError('Dimensions of X and Y do not agree!')\n if invvar is None:\n invvar = np.ones(x.shape,dtype=x.dtype)\n else:\n if invvar.shape != x.shape:\n raise ValueError('Dimensions of X and invvar do not agree!')\n if ia is None:\n ia = np.ones((ncoeff,),dtype=np.bool)\n if not ia.all():\n if inputans is None:\n inputans = np.zeros((ncoeff,),dtype=x.dtype)\n #\n # Select unmasked points\n #\n igood = (invvar > 0).nonzero()[0]\n ngood = len(igood)\n res = np.zeros((ncoeff,),dtype=x.dtype)\n yfit = np.zeros(x.shape,dtype=x.dtype)\n if ngood == 0:\n pass\n elif ngood == 1:\n res[0] = y[igood[0]]\n yfit += y[igood[0]]\n else:\n ncfit = min(ngood,ncoeff)\n function_map = {\n 'legendre':flegendre,\n 'flegendre':flegendre,\n 'chebyshev':fchebyshev,\n 'fchebyshev':fchebyshev,\n 'chebyshev_split':fchebyshev_split,\n 'fchebyshev_split':fchebyshev_split,\n 'poly':fpoly,\n 'fpoly':fpoly\n }\n try:\n legarr = function_map[function_name](x,ncfit)\n except KeyError:\n raise KeyError('Unknown function type: {0}'.format(function_name))\n if inputfunc is not None:\n if inputfunc.shape != x.shape:\n raise ValueError('Dimensions of X and inputfunc do not agree!')\n legarr *= np.tile(inputfunc,ncfit).reshape(ncfit,x.shape[0])\n yfix = np.zeros(x.shape,dtype=x.dtype)\n nonfix = ia[0:ncfit].nonzero()[0]\n nparams = len(nonfix)\n fixed = (~ia[0:ncfit]).nonzero()[0]\n if len(fixed) > 0:\n yfix = np.dot(legarr.T,inputans * (1 - ia))\n ysub = y - yfix\n finalarr = legarr[nonfix,:]\n else:\n finalarr = legarr\n ysub = y\n # extra2 = finalarr * np.outer(np.ones((nparams,),dtype=x.dtype),(invvar > 0))\n extra2 = finalarr * np.outer(np.ones((nparams,),dtype=x.dtype),invvar)\n alpha = np.dot(finalarr,extra2.T)\n # assert alpha.dtype == x.dtype\n if nparams > 1:\n # beta = np.dot(ysub * (invvar > 0), finalarr.T)\n beta = np.dot(ysub * invvar, finalarr.T)\n assert beta.dtype == x.dtype\n # uu,ww,vv = np.linalg.svd(alpha,full_matrices=False)\n res[nonfix] = np.linalg.solve(alpha,beta)\n else:\n # res[nonfix] = (ysub * (invvar > 0) * finalarr).sum()/alpha\n res[nonfix] = (ysub * invvar * finalarr).sum()/alpha\n if len(fixed) > 0:\n res[fixed] = inputans[fixed]\n yfit = np.dot(legarr.T,res[0:ncfit])\n return (res,yfit)\n","sub_path":"pydl/pydlutils/trace/func_fit.py","file_name":"func_fit.py","file_ext":"py","file_size_in_byte":4122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"161748036","text":"import Common\n\nword1 = ['a', 'b', 'c', 'd', 'a', 'f']\nword2 = ['z', 'b', 'c', 'd', 'f']\nseq = []\n\ncolumns = len(word1) + 1\nrows = len(word2) + 1\nm = [[0 for _ in range(columns)] for _ in range(rows)]\n\ndef longestCommon():\n for row in range(1, rows):\n for column in range(1, columns):\n char1 = word1[column - 1]\n char2 = word2[row - 1]\n if char1 == char2:\n # Diagonal + 1\n diagonal = m[row - 1][column - 1]\n m[row][column] = diagonal + 1\n else:\n # Max of previous column or row\n m[row][column] = 0\n\ndef backtrack():\n # Find the max element\n maxValue = 0\n maxRowIndex = 0\n maxColumnIndex = 0\n for row in range(1, rows):\n rowMax = max(m[row])\n if rowMax > maxValue:\n maxValue = rowMax\n maxRowIndex = row\n maxColumnIndex = m[row].index(maxValue)\n \n while maxRowIndex > 0 and maxColumnIndex > 0:\n diagonal = m[maxRowIndex - 1][maxColumnIndex - 1]\n if diagonal == maxValue - 1:\n seq.insert(0, word1[maxColumnIndex - 1])\n maxValue = diagonal\n maxRowIndex = maxRowIndex - 1\n maxColumnIndex = maxColumnIndex - 1\n else:\n break;\n\nCommon.printVector(word1, label=\"word1\")\nCommon.printVector(word2, label=\"word2\")\nlongestCommon()\nCommon.printMatrix(m, r=\"word2\", c=\"word1\")\nbacktrack()\nCommon.printVector(seq, label=\"Common Substring\")","sub_path":"Python/DynamicProgramming/LongestCommonString.py","file_name":"LongestCommonString.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"69409192","text":"from unittest.mock import Mock\n\nimport pandas as pd\nimport pytest\n\nfrom weaverbird.backends.sql_translator.metadata import ColumnMetadata, SqlQueryMetadataManager\nfrom weaverbird.backends.sql_translator.steps import translate_pivot\nfrom weaverbird.backends.sql_translator.types import SQLQuery\nfrom weaverbird.pipeline.steps import PivotStep\n\n\n@pytest.fixture\ndef sql_query_executor():\n def f(domain, query_string):\n return Mock(df=pd.DataFrame({'CURRENCY': ['SPAIN', 'FRANCE']}))\n\n return f\n\n\ndef test_translate_pivot(sql_query_executor):\n query = SQLQuery(\n query_name='SELECT_STEP_0',\n transformed_query='WITH SELECT_STEP_0 AS (SELECT COMPANY, COUNTRY, CURRENCY, PROVIDER FROM PRODUCTS)',\n selection_query='SELECT COMPANY, COUNTRY, CURRENCY, PROVIDER FROM SELECT_STEP_0',\n metadata_manager=SqlQueryMetadataManager(\n tables_metadata={\n 'PRODUCTS': {\n 'COMPANY': 'text',\n 'COUNTRY': 'text',\n 'CURRENCY': 'text',\n 'PROVIDER': 'text',\n }\n },\n ),\n )\n step = PivotStep(\n name='pivot',\n index=['COMPANY', 'COUNTRY'],\n column_to_pivot='CURRENCY',\n value_column='PROVIDER',\n agg_function='sum',\n )\n res = translate_pivot(step, query, index=1, sql_query_executor=sql_query_executor)\n assert res.transformed_query == (\n \"\"\"WITH SELECT_STEP_0 AS (SELECT COMPANY, COUNTRY, CURRENCY, PROVIDER FROM PRODUCTS), \"\"\"\n \"\"\"PRE_PIVOT_STEP_1 AS (SELECT COMPANY, COUNTRY, CURRENCY, PROVIDER FROM SELECT_STEP_0), \"\"\"\n \"\"\"PIVOT_STEP_1 AS (SELECT COMPANY, COUNTRY, SPAIN, FRANCE \"\"\"\n \"\"\"FROM PRE_PIVOT_STEP_1 PIVOT(sum(PROVIDER) FOR CURRENCY IN ('SPAIN', 'FRANCE')) \"\"\"\n \"\"\"AS p (COMPANY, COUNTRY, SPAIN, FRANCE))\"\"\"\n )\n assert res.selection_query == 'SELECT COMPANY, COUNTRY, SPAIN, FRANCE FROM PIVOT_STEP_1'\n assert res.metadata_manager.retrieve_query_metadata_columns() == {\n 'COMPANY': ColumnMetadata(\n name='COMPANY',\n original_name='COMPANY',\n type='TEXT',\n original_type='text',\n alias=None,\n delete=False,\n ),\n 'COUNTRY': ColumnMetadata(\n name='COUNTRY',\n original_name='COUNTRY',\n type='TEXT',\n original_type='text',\n alias=None,\n delete=False,\n ),\n 'SPAIN': ColumnMetadata(\n name='SPAIN',\n original_name='\"\\'SPAIN\\'\"',\n type='TEXT',\n original_type='text',\n alias=None,\n delete=False,\n ),\n 'FRANCE': ColumnMetadata(\n name='FRANCE',\n original_name='\"\\'FRANCE\\'\"',\n type='TEXT',\n original_type='text',\n alias=None,\n delete=False,\n ),\n }\n\n\ndef test_translate_pivot_error(sql_query_executor, mocker):\n step = PivotStep(\n name='pivot',\n index=['COMPANY', 'COUNTRY'],\n column_to_pivot='CURRENCY',\n value_column='PROVIDER',\n agg_function='sum',\n )\n query = SQLQuery(\n query_name='SELECT_STEP_0',\n transformed_query='WITH SELECT_STEP_0 AS (SELECT COMPANY, COUNTRY, CURRENCY, PROVIDER FROM PRODUCTS)',\n selection_query='SELECT COMPANY, COUNTRY, CURRENCY, PROVIDER FROM SELECT_STEP_0',\n metadata_manager=SqlQueryMetadataManager(\n tables_metadata={\n 'PRODUCTS': {\n 'COMPANY': 'text',\n 'COUNTRY': 'text',\n 'CURRENCY': 'text',\n 'PROVIDER': 'text',\n }\n },\n ),\n )\n mocker.patch(\n 'weaverbird.backends.sql_translator.steps.pivot.build_selection_query',\n side_effect=Exception,\n )\n with pytest.raises(Exception):\n translate_pivot(step, query, index=1)\n","sub_path":"server/tests/steps/sql_translator/test_pivot.py","file_name":"test_pivot.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"243951439","text":"#!/usr/bin/python3\n\nimport pandas as pd\nfrom sqlalchemy import create_engine\n# from sqlalchemy.types import String\n# from sqlalchemy.types import Float\n\n# Parameters - later can be defined with JSON or script arguments\n# ==========\n# ==========\n\nworking_directory = './'\t\t\t # working directory\ninput_csv_files = ['some_csv_file_1.csv','some_csv_file_2.csv'] # \n\nseparator = ','\nheader_row = 0 # 0 means 1st line is header, use None (without quotes) for no header\nquotes = '\"'\nquoting_mode = 0 # QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3)\n\n# ==========\n# ==========\n\n# DB connection definition\nengine = create_engine('postgresql://postgres:postgres@localhost:5432/postgis') # dialect+driver://username:password@host:port/database\n\nfor csv_file in input_csv_files:\n # Table name - based on CSV file name\n table_name = csv_file[:-4]\n # Load data into pandas\n input_data = pd.read_csv(working_directory + \"/\" + csv_file, sep = separator, header = header_row, quotechar = quotes, quoting = quoting_mode)\n # convert bad column names\n new_column_names = []\n for i in input_data.columns:\n new_column_names.append(i.replace(' ','_').lower())\n input_data.columns = new_column_names\n # InputCsv to DB\n input_data.to_sql(table_name, engine, chunksize=10000, index = False)\n","sub_path":"pandas_csv2pgsql.py","file_name":"pandas_csv2pgsql.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"269402350","text":"import wmi \r\nc=wmi.WMI()\r\nglobal m\r\nwql=\"Select DeviceID from Win32_PnPEntity where name='HC-05'\"\r\nwql1=\"Select deviceid from win32_SerialPort\"\r\nglobal l1\r\nl=[]\r\nl1=[]\r\nl3=[]\r\n\r\nfor item in c.query(wql):\r\n s=str(item)\r\nfor item1 in c.query(wql1):\r\n l.append(item1)\r\nserial1=str(l)\r\nt=serial1.split('=\"')\r\nfor i in range(1,len(t)):\r\n serial3=str(t[i])\r\n l1.append(serial3[0:5])\r\n#print(l1)\r\n\r\nx=s.find(\"BLUETOOTHDEVICE\")\r\ns=s[x+16:]\r\n\r\nt=[]\r\nfor i in range(0,len(s)):\r\n if(s[i]=='\"'):\r\n break\r\n else:\r\n t.append(s[i])\r\n\r\nstr1=\"\"\r\nm=str1.join(t)\r\nprint(m)\r\nwql3=\"Select PNPDeviceID from win32_SerialPort where deviceid='\"\r\nfor i in range(0,len(l1)):\r\n \r\n wql4=wql3+l1[i]+str(\"'\")\r\n l3.append(wql4)\r\nfor i in range(0,len(l3)):\r\n \r\n wql5=str(l3[i])\r\n \r\n for item7 in c.query(wql5):\r\n \r\n sfinder=str(item7)\r\n \r\n x2=sfinder.find(m)\r\n \r\n if(x2>1):\r\n print(\"sucess\")\r\n global j\r\n j=i\r\n #print(j)\r\n \r\nprint(l1[j])\r\n\r\n\r\n \r\n","sub_path":"port_connection.py","file_name":"port_connection.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"270739550","text":"inv = {'gold coin': 42, 'rope': 1}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin']\n\n\ndef addToInventory(inventory, addeditem):\n\tdirloot={}\n\t#тут мы делаем из списка словарь\n\tfor i in addeditem:\n\t\tdirloot.update({i: addeditem.count(i)})\n\n\t#тут творится магия)\n\t# цикл перебирает ключи из лута\n\tfor k, v in dirloot.items():\n\t\tvar_loot = dirloot.get(k)\n\t\tvar_inv = inventory.get(k)\n\t\t#проверяем, есть ли в словаре ключ который есть в луте\n\t\t#если ключа нет, переменной присвается значение 0 \n\t\tif var_inv== None:\n\t\t\tvar_inv = 0\n\t\t#тут обновляется значение для ключа\n\t\tvar_fin = var_loot+var_inv\n\t\tinventory.update({k: var_fin})\n\tprint(inventory)\n\n\nprint(inv)\nprint(dragonLoot)\n\naddToInventory(inv, dragonLoot)\n","sub_path":"dragonloot.py","file_name":"dragonloot.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"31622269","text":"from itertools import count\nfrom sys import stdin\n\nbanks = [int(x) for x in stdin.read().split()]\n\n\ndef realloc():\n \"\"\"Reallocates blocks according to https://adventofcode.com/2017/day/6.\"\"\"\n i_max = banks.index(max(banks))\n num_blocks = banks[i_max]\n banks[i_max] = 0\n for _ in range(num_blocks):\n i_max = (i_max + 1) % len(banks)\n banks[i_max] += 1\n\n\nseen = set()\nwhile True:\n snapshot = tuple(banks)\n if snapshot in seen:\n break\n seen.add(snapshot)\n realloc()\n\nfor c in count(start=1):\n realloc()\n if snapshot == tuple(banks):\n print(c)\n break\n","sub_path":"2017/day6/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"538408582","text":"# https://github.com/ray-project/ray/blob/master/python/ray/rllib/rollout.py\n# copiar o arquivo e registrar o custom env aqui\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport pandas as pd\nimport gym\nfrom gym.spaces import Discrete, Box\nfrom sklearn.preprocessing import normalize\n\nimport os\nfrom configs.vars import *\n\n# import hypeindx\n\nimport ray\nfrom ray.tune import run_experiments, grid_search\n# from ray.tune.registry import register_env\n\ndef init_data(symbol):\n if not (os.path.exists('datasets/ETH-BTC_trading.csv')):\n df = pd.read_csv('datasets/ETH-BTC.csv')\n # df['Volume 24h $'] = df['Volume 24h $'] * 1e-11\n # df['Wikipedia views 30d'] = df['Wikipedia views 30d'] * 1e-5\n # df['Market Cap'] = df['Market Cap'] * 1e-11\n # df['Price EOS'] = df['Price EOS'] * 1e-3\n # df['Price XRP'] = df['Price XRP'] * 1e-3\n # df['Telegram Mood (total value for all messages)'] = df['Telegram Mood (total value for all messages)'] * 1e-3\n # df['Buy market 24h'] = df['Buy market 24h'] * 1e-3\n df['wallet_btc'] = WALLET_BTC\n df['wallet_symbol'] = 0.0\n df.to_csv('datasets/ETH-BTC_trading.csv')\n df.drop('Date', axis=1, inplace=True)\n df_array = df.values.tolist()\n keys = df.keys()\n ##############################\n # print(keys)\n # print(list(df.iloc[0].values))\n # print(df_array[0])\n # >>> list(df.iloc[0].values) == df_array[0]\n # >>> True\n ##############################\n else:\n df = pd.read_csv('datasets/ETH-BTC_trading.csv')\n df.drop('Date', axis=1, inplace=True)\n df_array = df.values.tolist()\n keys = df.keys()\n return keys, df_array\n\n\nclass TradingEnv(gym.Env):\n def __init__(self, config):\n # self.keys, self.symbol_list = init_data(FLAGS.symbol)\n self.keys = config['keys']\n self.symbol_list = config['symbols']\n self.index = 0\n self.dicount_rate = 0.999 # works like the tx\n self.wallet_btc = WALLET_BTC\n self.wallet_symbol = 0.0\n self.action_space = Discrete(3)\n self.observation_space = Box(\n low=-np.finfo(np.float32).max, high=np.finfo(np.float32).max,\n shape=(len(self.keys), ), dtype=np.float32\n )\n # low=-np.finfo(np.float32).max, high=np.finfo(np.float32).max, shape=(self.df_rows-2, ), dtype=np.float32) # shape=(number of columns,)\n\n def reset(self):\n self.index = 0\n self.wallet_btc = WALLET_BTC\n self.wallet_symbol = 0.0\n state = self.symbol_list[self.index]\n # print('state')\n # print(state)\n # normalized_state = normalize(state[:,np.newaxis], axis=0).ravel()\n # return normalized_state\n return state\n\n def step(self, action):\n if action not in [0,1,2]:\n raise AssertionError()\n\n price_btc_index = list(self.keys).index('close')\n wallet_btc_index = list(self.keys).index('wallet_btc')\n wallet_symbol_index = list(self.keys).index('wallet_symbol')\n observable_state = self.symbol_list[self.index]\n price_btc_before_action = observable_state[price_btc_index]\n\n total_portfolio_value_before_action = self.wallet_btc * price_btc_before_action\n\n if action == 0: # buy\n self.wallet_btc -= price_btc_before_action\n self.wallet_symbol += price_btc_before_action\n elif action == 1: # sell\n self.wallet_btc += price_btc_before_action\n self.wallet_symbol -= price_btc_before_action\n\n\n price_btc_after_action = observable_state[price_btc_index]\n\n total_portfolio_value_after_action = self.dicount_rate * (self.wallet_btc * price_btc_after_action)\n\n reward = total_portfolio_value_after_action - total_portfolio_value_before_action\n\n self.index += 1\n next_observable_state = self.symbol_list[self.index]\n\n next_observable_state[wallet_btc_index] = self.wallet_btc\n next_observable_state[wallet_symbol_index] = self.wallet_symbol\n\n # normalized_next_state = normalize(next_observable_state[:,np.newaxis], axis=0).ravel()\n\n done = self.wallet_btc < 0.0 or self.index >= len(self.symbol_list)-1\n\n # return normalized_next_state, reward, done, {}\n return next_observable_state, reward, done, {}\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description='\\n')\n parser.add_argument('--symbol', type=str, help='Choose coin to train')\n parser.add_argument('--algo', type=str, help='Choose algorithm to train')\n FLAGS = parser.parse_args()\n keys, symbols = init_data(FLAGS.symbol)\n # Can also register the env creator function explicitly with:\n # register_env(\"corridor\", lambda config: TradingEnv(config))\n ray.init()\n run_experiments({\n \"{}_{}_{}_{}\".format(FLAGS.symbol.upper(),TIME_INTERVAL,FROM_DATE,TO_DATE): {\n \"run\": FLAGS.algo,\n \"env\": TradingEnv, # or \"corridor\" if registered above\n \"stop\": {\n \"timesteps_total\": 1e6,\n },\n \"config\": {\n \"lr\": grid_search([\n # 1e-2,\n # 1e-4,\n # 1e-5,\n # 1e-6,\n 1e-7\n ]),\n \"num_workers\": 2, # parallelism\n 'observation_filter': 'MeanStdFilter',\n \"env_config\": {\n 'keys': keys,\n 'symbols': symbols\n },\n }\n }\n })","sub_path":"train_trading_bot.py","file_name":"train_trading_bot.py","file_ext":"py","file_size_in_byte":5679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"189819300","text":"# -*- coding: utf-8 -*- #\n# Copyright 2019 Google LLC. 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\"\"\"Flags and helpers for the compute reservations commands.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.calliope import arg_parsers\nfrom googlecloudsdk.calliope import base\n\n# TODO(b/129054682): fix the format in text render.\n\n\ndef GetDescriptionFlag():\n return base.Argument(\n '--description',\n help='An optional description of the reservation to create.')\n\n\ndef GetRequireSpecificAllocation():\n help_text = \"\"\"\\\nIndicates whether the reservation can be consumed by VMs with \"any reservation\"\ndefined. If enabled, then only VMs that target this reservation by name using\n`--reservation-affinity=specific` can consume from this reservation.\n\"\"\"\n return base.Argument(\n '--require-specific-reservation', action='store_true', help=help_text)\n\n\ndef GetVmCountFlag(required=True):\n return base.Argument(\n '--vm-count',\n required=required,\n type=int,\n help=\"\"\"\\\nThe number of VM instances that are allocated to this reservation.\nThe value of this field must be an int in the range [1, 1000].\n\"\"\")\n\n\ndef GetMinCpuPlatform():\n \"\"\"Gets the --min-cpu-platform flag.\"\"\"\n return base.Argument(\n '--min-cpu-platform',\n help='Optional minimum CPU platform of the reservation to create.')\n\n\ndef GetMachineType(required=True):\n \"\"\"Gets the --machine-type flag.\"\"\"\n help_text = \"\"\"\\\nThe type of machine (name only) which has a fixed number of vCPUs and a fixed amount\nof memory. This also includes specifying custom machine type following\n`custom-number_of_CPUs-amount_of_memory` pattern, e.g. `custom-32-29440`.\n\"\"\"\n return base.Argument('--machine-type', required=required, help=help_text)\n\n\ndef GetLocalSsdFlag():\n \"\"\"Gets the -local-ssd flag.\"\"\"\n help_text = \"\"\"\\\nManage the size and the interface of local SSD to use. See\nhttps://cloud.google.com/compute/docs/disks/local-ssd for more information.\n*interface*::: The kind of disk interface exposed to the VM for this SSD. Valid\nvalues are `scsi` and `nvme`. SCSI is the default and is supported by more\nguest operating systems. NVME may provide higher performance.\n*size*::: The size of the local SSD in base-2 GB.\n\"\"\"\n return base.Argument(\n '--local-ssd',\n type=arg_parsers.ArgDict(spec={\n 'interface': (lambda x: x.upper()),\n 'size': int,\n }),\n action='append',\n help=help_text)\n\n\ndef GetAcceleratorFlag():\n \"\"\"Gets the --accelerator flag.\"\"\"\n help_text = \"\"\"\\\nManage the configuration of the type and number of accelerator cards attached.\n*count*::: The number of accelerators to attach to each instance in the reservation.\n*type*::: The specific type (e.g. `nvidia-tesla-k80` for nVidia Tesla K80) of\naccelerator to attach to instances in the reservation. Use `gcloud compute accelerator-types list`\nto learn about all available accelerator types.\n\"\"\"\n return base.Argument(\n '--accelerator',\n type=arg_parsers.ArgDict(spec={\n 'count': int,\n 'type': str,\n }, required_keys=['count', 'type']),\n action='append',\n help=help_text)\n\n\ndef AddCreateFlags(parser):\n \"\"\"Adds all flags needed for the create command.\"\"\"\n GetDescriptionFlag().AddToParser(parser)\n\n group = base.ArgumentGroup(\n 'Manage the specific SKU reservation properties to create', required=True)\n\n group.AddArgument(GetRequireSpecificAllocation())\n group.AddArgument(GetVmCountFlag())\n group.AddArgument(GetMinCpuPlatform())\n group.AddArgument(GetMachineType())\n group.AddArgument(GetLocalSsdFlag())\n group.AddArgument(GetAcceleratorFlag())\n\n group.AddToParser(parser)\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/compute/reservations/flags.py","file_name":"flags.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"297686650","text":"import math\nimport random\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import init\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.optim import Optimizer\n\nbce_loss = nn.BCELoss().cuda()\nsoftmax = nn.Softmax(dim=1).cuda()\nclass_criterion = nn.CrossEntropyLoss().cuda()\ndef mixup_criterion(y_a, y_b, lam):\n return lambda criterion, pred: lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)\n\ndef get_optimizer(name, parameters, lr, weight_decay=0):\n if name == 'sgd':\n return torch.optim.SGD(parameters, lr=lr, weight_decay=weight_decay)\n elif name == 'rmsprop':\n return torch.optim.RMSprop(parameters, lr=lr, weight_decay=weight_decay)\n elif name == 'adagrad':\n return torch.optim.Adagrad(parameters, lr=lr, weight_decay=weight_decay)\n elif name == 'adam':\n return torch.optim.Adam(parameters, lr=lr, weight_decay=weight_decay)\n elif name == 'adamax':\n return torch.optim.Adamax(parameters, lr=lr, weight_decay=weight_decay)\n else:\n raise Exception(\"Unsupported optimizer: {}\".format(name))\n\ndef change_lr(optimizer, new_lr):\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_lr\n\n\n\nclass Trainer(object):\n def __init__(self, opt, model, partition_labels, ema= True):\n\n partition_num = partition_labels.max() + 1\n self.partition_labels = partition_labels.cuda()\n self.task_ratio = opt['task_ratio']\n self.loss_func = nn.CrossEntropyLoss()\n\n self.opt = opt\n self.ema = ema\n self.model = model\n self.criterion = nn.CrossEntropyLoss()\n self.parameters = [p for p in self.model.parameters() if p.requires_grad]\n\n self.ss_classifier = nn.Linear(opt['hidden_dim'], partition_num, bias=False)\n\n if opt['cuda']:\n self.criterion.cuda()\n self.ss_classifier.cuda()\n\n self.parameters.append(self.ss_classifier.weight)\n\n if self.ema == True:\n self.optimizer = get_optimizer(self.opt['optimizer'], self.parameters, self.opt['lr'], self.opt['decay'])\n\n def reset(self):\n self.model.reset()\n if self.ema == True:\n self.optimizer = get_optimizer(self.opt['optimizer'], self.parameters, self.opt['lr'], self.opt['decay'])\n\n def update(self, inputs, target, idx):\n if self.opt['cuda']:\n inputs = inputs.cuda()\n target = target.cuda()\n idx = idx.cuda()\n\n self.model.train()\n self.optimizer.zero_grad()\n\n logits = self.model(inputs)\n loss = self.criterion(logits[idx], target[idx])\n \n loss.backward()\n self.optimizer.step()\n return loss.item()\n\n def update_soft(self, inputs, target, idx, idx_u):\n if self.opt['cuda']:\n inputs = inputs.cuda()\n target = target.cuda()\n idx = idx.cuda()\n\n \n logits= self.model(inputs)\n logits = torch.log_softmax(logits, dim=-1)\n \n loss = -torch.mean(torch.sum(target[idx] * logits[idx], dim=-1))\n \n logits0 = self.model.forward_partition(inputs)\n logits0 = self.ss_classifier(logits0)\n loss0 = self.loss_func(logits0[idx_u], self.partition_labels[idx_u])\n \n return loss, loss0\n \n \n \n \n \n def update_soft_aux(self, inputs, target,target_discrete, idx, idx_unlabeled, adj, opt, mixup_layer, idx_u):\n \"\"\"uses the auxiliary loss as well, which does not use the adjacency information\"\"\"\n if self.opt['cuda']:\n inputs = inputs.cuda()\n target = target.cuda()\n idx = idx.cuda()\n idx_unlabeled = idx_unlabeled.cuda()\n\n self.model.train()\n self.optimizer.zero_grad()\n\n \n mixup = True\n if mixup == True:\n # get the supervised mixup loss #\n logits, target_a, target_b, lam = self.model.forward_aux(inputs, target=target, train_idx= idx, mixup_input=False, mixup_hidden = True, mixup_alpha = opt['mixup_alpha'],layer_mix=mixup_layer)\n\n logits0 = self.model.forward_partition(inputs)\n logits0 = self.ss_classifier(logits0)\n loss0 = self.loss_func(logits0[idx_u], self.partition_labels[idx_u])\n\n mixed_target = lam*target_a + (1-lam)*target_b\n loss = bce_loss(softmax(logits[idx]), mixed_target)\n\n # get the unsupervised mixup loss #\n logits, target_a, target_b, lam = self.model.forward_aux(inputs, target=target, train_idx= idx_unlabeled, mixup_input=False, mixup_hidden = True, mixup_alpha = opt['mixup_alpha'],layer_mix= mixup_layer)\n mixed_target = lam*target_a + (1-lam)*target_b\n loss_usup = bce_loss(softmax(logits[idx_unlabeled]), mixed_target)\n else:\n logits = self.model.forward_aux(inputs, target=None, train_idx= idx, mixup_input= False, mixup_hidden = False, mixup_alpha = 0.0,layer_mix=None)\n logits = torch.log_softmax(logits, dim=-1)\n loss = -torch.mean(torch.sum(target[idx] * logits[idx], dim=-1))\n\n '''\n logits0 = self.model.forward_partition(inputs)\n logits0 = self.ss_classifier(logits0)\n loss0 = self.loss_func(logits0, self.partition_labels) \n '''\n\n logits = self.model.forward_aux(inputs, target=None, train_idx= idx_unlabeled, mixup_input= False, mixup_hidden = False, mixup_alpha = 0.0,layer_mix=None)\n logits = torch.log_softmax(logits, dim=-1)\n loss_usup = -torch.mean(torch.sum(target[idx_unlabeled] * logits[idx_unlabeled], dim=-1))\n \n return loss, loss_usup, loss0\n\n \n \n def evaluate(self, inputs, target, idx):\n if self.opt['cuda']:\n inputs = inputs.cuda()\n target = target.cuda()\n idx = idx.cuda()\n\n self.model.eval()\n logits = self.model(inputs)\n loss = self.criterion(logits[idx], target[idx])\n preds = torch.max(logits[idx], dim=1)[1]\n correct = preds.eq(target[idx]).double()\n accuracy = correct.sum() / idx.size(0)\n\n return loss.item(), preds, accuracy.item()\n\n def predict(self, inputs, tau=1):\n if self.opt['cuda']:\n inputs = inputs.cuda()\n\n self.model.eval()\n\n logits = self.model(inputs) / tau\n\n logits = torch.softmax(logits, dim=-1).detach()\n\n return logits\n\n\n def predict_aux(self, inputs, tau=1):\n if self.opt['cuda']:\n inputs = inputs.cuda()\n\n self.model.eval()\n\n logits = self.model.forward_aux(inputs) / tau\n\n logits = torch.softmax(logits, dim=-1).detach()\n\n return logits\n\n def predict_noisy(self, inputs, tau=1):\n if self.opt['cuda']:\n inputs = inputs.cuda()\n\n #self.model.eval()\n\n logits = self.model(inputs) / tau\n\n logits = torch.softmax(logits, dim=-1).detach()\n\n return logits\n\n\n def predict_noisy_aux(self, inputs, tau=1):\n if self.opt['cuda']:\n inputs = inputs.cuda()\n\n #self.model.eval()\n\n logits = self.model.forward_aux(inputs) / tau\n\n logits = torch.softmax(logits, dim=-1).detach()\n\n return logits\n \n \n def save(self, filename):\n params = {\n 'model': self.model.state_dict(),\n 'optim': self.optimizer.state_dict()\n }\n try:\n torch.save(params, filename)\n except BaseException:\n print(\"[Warning: Saving failed... continuing anyway.]\")\n\n def load(self, filename):\n try:\n checkpoint = torch.load(filename)\n except BaseException:\n print(\"Cannot load model from {}\".format(filename))\n exit()\n self.model.load_state_dict(checkpoint['model'])\n self.optimizer.load_state_dict(checkpoint['optim'])\n","sub_path":"SS-GCNs/SS-GMNN-GraphMix/GraphMix-clu/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":7909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"618158035","text":"class Solution:\r\n def minSwaps(self, nums):\r\n temp = []\r\n for index, item in enumerate(nums):\r\n temp.append((item, index))\r\n sortedTemp = sorted(temp)\r\n\r\n newToOldIndexDict = {}\r\n for i in range(len(nums)):\r\n newToOldIndexDict[i] = sortedTemp[i][1]\r\n\r\n visited = {} # this is made a dictionary becacuse adding key value pair is more\r\n # efficient then appending to a list.\r\n\r\n ans = 0\r\n for j in range(len(nums)): # checking for all the indices in the array\r\n curr = j\r\n count = 0 # count is initilized inside the for loop because we need to count for each element and we dont need its old value\r\n if j in visited: # if the index is already involved in swapping ( or is in visited), we skip checking that index\r\n continue\r\n while curr != newToOldIndexDict[\r\n j]: # if the new and old index are not equal, it implies that it needs swapping!\r\n count += 1\r\n j = newToOldIndexDict[j]\r\n visited[curr] = True\r\n visited[j] = True # add this j to visited\r\n ans += count\r\n return ans\r\ns = Solution()\r\narr1 = [10,19,6,3,5]\r\nprint(s.minSwaps(arr1))","sub_path":"Graphs/minimum swaps to sort.py","file_name":"minimum swaps to sort.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"40967399","text":"#!/usr/local/bin/python3\nimport sys\nimport os\n\ndef add_50(filename):\n bed_file = open(filename,'r')\n for line in bed_file:\n line = line.split(\"\\t\")\n line[1] = int(line[1]) - 50\n line[2] = int(line[2]) + 50\n print (line)\n\ndef training_testing_sets_separation(filename, ratio, training_file, testing_file):\n bed50_file = open(filename,\"r\")\n training = open(training_file, 'w')\n testing = open(testing_file, 'w')\n count = 0\n for line in bed50_file:\n count += 1\n if count % ratio == 0:\n testing.write(line)\n else:\n training.write(line)\n\n\ndef background_signal_separation(filename):\n bed50_file = open(filename,\"r\")\n background = ()\n signal =()\n for line in bed50_file:\n line = line.strip().split(\"\\t\")\n background += (line[10][:50],)\n background += (line[10][-50:],)\n signal += (line[10][50:-50],)\n return (background, signal)\n\n\ndef generate_kmers(k,y=''):\n \"\"\"\n This function is a generator of kmers for DNA bases.\n It uses a recursive aproach.\n The only required argument is the order (k).\n it also accepts prefix defined as y='prefix'\n the default value for y is ''.\n example:\n get_kmers(3)\n \"\"\"\n if k==0:\n yield y\n else:\n for m in ['A','C','T','G']:\n kmer=y+m\n for item in generate_kmers(k-1,kmer):\n yield item\n\n\ndef dictionary_kmers(k):\n kmer_dict = {}\n for i in generate_kmers(k):\n kmer_dict[i]=0\n print (kmer_dict)\n\ndef main(k):\n (background,signal) = background_signal_separation(\"exemple.bed\")\n for element in signal:\n print (element)\n #if \n# for char in element:\n\n\nmain(2)\n\ndef get_kmers(sequence,k):\n \"\"\"jhsdj\"\"\"\n kmers_list=[]\n length=len(sequence)\n print(length)\n if k<1 or length < k:\n sys.exit()\n i=0\n while i= 0:\n torch.cuda.set_device(args.device)\n if torch.cuda.is_available():\n #if hvd: kwargs['num_workers'] = 1\n kwargs['pin_memory'] = True\n\ntestLoader = DataLoader(testDataset, batch_size=args.batch, shuffle=False, **kwargs)\n\nprint(\"Load model\", end='')\nif args.model == 'none':\n print(\"Load saved model from\", (args.input+'/model.pth'))\n model = torch.load(args.input+'/model.pth', map_location='cpu')\nelse:\n print(\"Load the model\", args.model)\n if args.model == 'original':\n from HEPCNN.torch_model_original import MyModel\n elif 'circpad' in args.model:\n from HEPCNN.torch_model_circpad import MyModel\n else:\n from HEPCNN.torch_model_default import MyModel\n model = MyModel(testDataset.width, testDataset.height, model=args.model)\n\ndevice = 'cpu'\nif args.device >= 0 and torch.cuda.is_available():\n model = model.cuda()\n device = 'cuda'\nprint('done')\n\nmodel.load_state_dict(torch.load(args.input+'/weight_0.pth', map_location='cpu'))\nmodel.to(device)\nprint('modify model', end='')\nmodel.fc.add_module('output', torch.nn.Sigmoid())\nmodel.eval()\nprint('done')\n\nfrom tqdm import tqdm\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import plot_confusion_matrix\nimport seaborn as sn\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nlabels, preds = [], []\nweights, scaledWeights = [], []\ntrue_label = torch.Tensor()\npred_label = torch.Tensor()\nprint(true_label)\nprint(true_label.shape)\nprint(pred_label)\nconfusion_matrix_ = torch.zeros(6,6)\nfor i, (data, label, weight, rescale, _) in enumerate(tqdm(testLoader)):\n data = data.float().to(device)\n weight = weight.float()\n pred = model(data).detach().to('cpu')\n\n value, index = torch.max(pred, dim = 1)\n true_label = torch.cat([true_label, label], dim=0)\n pred_label = torch.cat([pred_label, index], dim=0)\n # confusion_matrix_ = confusion_matrix_ + confusion_matrix(label,index,labels=[0,1,2,3,4,5])\nconfusion_matrix_ = confusion_matrix(true_label,pred_label,normalize=\"true\")\nprint(confusion_matrix_)\n\naxis_list = [r\"$\\tau^{\\mp}\\rightarrow\\pi^{\\mp}\\nu$\",r\"$\\tau^{\\mp}\\rightarrow\\pi^{\\mp}\\pi^{\\pm}\\pi^{\\mp}\\nu$\",r\"$\\tau^{\\mp}\\rightarrow\\pi^{\\mp}\\pi^{\\pm}\\pi^{\\mp}\\pi^{0}\\nu$\",r\"$\\tau^{\\mp}\\rightarrow\\pi^{\\mp}\\pi^{0}\\nu$\",r\"$\\tau^{\\mp}\\rightarrow\\pi^{\\mp}\\pi^{0}\\pi^{0}\\nu$\",r\"$Z\\rightarrow q \\bar{q}$\"]\n\ndf_cm = pd.DataFrame(confusion_matrix_, index = [i for i in axis_list], columns = [i for i in axis_list])\nplt.figure(figsize = (11,10))\nax = sn.heatmap(df_cm, annot=True, cmap=\"YlGnBu\")\nplt.savefig(\"conf.png\")\n","sub_path":"run/eval_torch_multi.py","file_name":"eval_torch_multi.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"345109067","text":"class LinkedList:\n def __init__(self):\n \"\"\"Create a new list with a Sentinel Node\"\"\"\n self.head = ListNode()\n\n def insert(self, x, p):\n \"\"\"Insert element x in the position after p\"\"\"\n temp = ListNode()\n temp.data = x\n temp.next = p.next\n p.next = temp\n\n def delete(self, p):\n \"\"\"Delete the node following node p in the linked list.\"\"\"\n if self.head is None:\n return\n temp = self.head\n if p == self.head:\n self.head = temp.next\n temp = None\n return\n while (p):\n temp = temp.next\n p = p.next\n if temp is None:\n return\n if temp is None:\n return\n if temp.next is None:\n return\n next = temp.next.next\n temp.next = next\n temp = None\n\n def printlist(self):\n \"\"\" Print all the elements of a list in a row.\"\"\"\n temp = self.head\n while temp.next is not None:\n print(temp.next.data)\n temp = temp.next\n\n def insertAtIndex(self, x, i):\n\n \"\"\"Insert value x at list position i. (The position of the first element is taken to be 0.)\"\"\"\n m = self.head\n if m.next is None:\n z = ListNode()\n z.data = x\n m.next = z\n else:\n n = ListNode()\n t = ListNode()\n n.data = x\n t.next = self.head\n for d in range(i + 1):\n t = t.next\n n.next = t.next\n t.next = n\n\n def search(self, x):\n \"\"\"Search for value x in the list. Return a reference to the first node with value x; return None if no such node is found.\"\"\"\n if self.head is None:\n return False\n temp = self.head\n while (temp):\n if (temp.data == x):\n return True\n else:\n temp = temp.next\n\n def len(self):\n \"\"\"Return the length (the number of elements) in the Linked List.\"\"\"\n count = 0\n temp = self.head\n while (temp is not None):\n count += 1\n temp = temp.next\n return count\n\n def isEmpty(self):\n \"\"\"Return True if the Linked List has no elements, False otherwise.\"\"\"\n temp = self.head\n if (temp is None):\n return True\n else:\n return False\n\n\nclass ListNode:\n def __init__(self, val=None, nxt=None):\n self.data = val\n self.next = nxt\n\n\n\nclass hashtable(object):\n def __init__(self):\n self.T = [None for i in range(30)]\n\n def keyvalue(self, key):\n t = 0\n for i in range(len(key) - 1, -1, -1):\n t = ord(key[i]) + (33 * t)\n return t % 30\n\n def insertintable(self, key):\n value = self.keyvalue(key)\n if self.T[value] is None:\n self.T[value] = LinkedList()\n self.T[value].insert(key, self.T[value].head)\n else:\n self.T[value].insert(key, self.T[value].head)\n\n def searchash(self, y):\n key = self.keyvalue(y)\n if self.T[key] is None:\n return None\n elif self.T[key].search(key) is False:\n return None\n else:\n return 1\n\n def printtable(self):\n for hr in range(30):\n if self.T[hr] is not None:\n if self.T[hr].isEmpty() is False:\n self.T[hr].printlist()\n\ndef main():\n h = hashtable()\n print(\"Enter the number of elements you want to enter in hashtable:\")\n n = int(raw_input())\n for kt in range(n):\n print(\"enter key:\")\n a1=raw_input()\n h.insertintable(a1)\n h.printtable()\n print(\"enter a string to search in hashtable:\")\n x = raw_input()\n if h.searchash(x) is None:\n print(\"Not Found\")\n else:\n print(\"found\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Data_Structure_Lab/hashtable/prog2.py","file_name":"prog2.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"479072689","text":"import random\n\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\n\nNUM_ACTIONS = 3\n\n\nclass BasalGanglia:\n \"\"\"\n Parameters:\n q_net: Network used to predict q-values.\n target_q_net: Used to avoid too much \"chasing a moving target\" - typically duplicate of above.\n optimizer: Optimizer.\n num_stripes: Number of independent selections to be made (one per stripe).\n gamma: Discounting reward factor in Bellman equation.\n batch_size Batch size.\n iter_before_train: Number of iterations used to expand memory buffer before training may begin.\n eps: Probability of making random choices instead of \n memory_buffer_size: Maximum size of memory replay buffer.\n replace_target_every_n: Frequency with which q_net's parameters are copied to target_q_net.\n log_every_n: Log after every n batches.\n tensorboard_path: Directory used for tensorboard logging.\n \n \"\"\"\n\n def __init__(self, q_net, target_q_net, optimizer, num_stripes=7, gamma=.3, batch_size=8,\n iter_before_train=50, eps=.1, memory_buffer_size=100, replace_target_every_n=100,\n log_every_n=100, tensorboard_path='logs'):\n self.q_net = q_net\n self.target_q_net = target_q_net\n self.optimizer = optimizer\n self.num_stripes = num_stripes\n self.gamma = gamma\n self.batch_size = batch_size\n self.iter_before_train = iter_before_train\n # TODO Consider each head *independently* being epsilon-greedy.\n self.eps = eps\n self.memory_buffer_size = memory_buffer_size\n self.replace_target_every_n = replace_target_every_n\n self.log_every_n = log_every_n\n self.writer = SummaryWriter(tensorboard_path)\n\n self.memory_buffer = []\n self.losses = []\n self.rewards = []\n self.loss_log_count = 0\n self.reward_log_count = 0\n self.iteration = 1\n\n def get_q_values(self, q_net_input, use_target=False):\n if use_target:\n return self.target_q_net(q_net_input)\n else:\n return self.q_net(q_net_input)\n\n def select_actions(self, state):\n if (len(self.memory_buffer) < self.iter_before_train or\n random.uniform(0, 1) < self.eps):\n return [random.randint(0, NUM_ACTIONS - 1)\n for _ in range(self.num_stripes)]\n else:\n q_vals = self.get_q_values(state.unsqueeze(0))\n q_vals = q_vals.reshape(self.num_stripes, NUM_ACTIONS)\n return torch.argmax(q_vals, dim=1).tolist()\n\n def train_iterate(self):\n samples = random.sample(self.memory_buffer, self.batch_size)\n loss = torch.tensor(0.)\n self.optimizer.zero_grad()\n\n for state, action, reward, new_state in samples:\n state = state.reshape(-1)\n current_q_values = self.get_q_values(state).squeeze(0).reshape(-1, 3)\n current_q_value = torch.tensor(0.)\n for q_values, subaction in zip(current_q_values, action):\n current_q_value += q_values[subaction]\n\n future_q_values = self.get_q_values(new_state, use_target=True).detach().squeeze(0).reshape(-1, 3)\n future_q_value = torch.sum(torch.max(future_q_values, dim=1).values)\n\n loss += (current_q_value - (reward + self.gamma * future_q_value)) ** 2\n\n loss.backward(retain_graph=True)\n self.optimizer.step()\n self.losses.append(loss.item())\n\n def learn_from_experience(self, prev_state, action, reward, curr_state):\n self.rewards.append(reward)\n\n # Update memory buffer and (if applicable) train.\n self.memory_buffer.append([prev_state, action, reward, curr_state])\n if len(self.memory_buffer) > self.memory_buffer_size:\n self.memory_buffer.pop(0)\n if len(self.memory_buffer) >= self.iter_before_train:\n self.train_iterate()\n\n if len(self.losses) == self.log_every_n:\n self.writer.add_scalar('BG Loss', sum(self.losses) / len(self.losses), self.loss_log_count)\n self.losses = []\n self.writer.flush()\n self.loss_log_count += 1\n\n if len(self.rewards) == self.log_every_n:\n self.writer.add_scalar('BG Reward', sum(self.rewards) / len(self.rewards), self.reward_log_count)\n self.rewards = []\n self.writer.flush()\n self.reward_log_count += 1\n\n if (self.iteration + 1) % self.replace_target_every_n == 0:\n self.target_q_net.load_state_dict(self.q_net.state_dict())\n self.iteration += 1\n","sub_path":"basal_ganglia.py","file_name":"basal_ganglia.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"516720907","text":"from gsrest.test.assertion import assertEqual\nfrom openapi_server.models.tx_summary import TxSummary\nfrom openapi_server.models.neighbors import Neighbors\nfrom openapi_server.models.neighbor import Neighbor\nfrom openapi_server.models.address import Address\nfrom openapi_server.models.entity_addresses import EntityAddresses\nfrom openapi_server.models.entity import Entity\nfrom openapi_server.models.values import Values\nfrom openapi_server.models.search_result_level1 import SearchResultLevel1\nfrom openapi_server.models.entity_tag import EntityTag\nfrom openapi_server.models.tags import Tags\nimport json\nimport gsrest.service.entities_service as service\nfrom gsrest.test.addresses_service import eth_address, \\\n eth_addressWithTagsOutNeighbors, atag1, atag2, eth_tag, eth_tag2\n\ntag = EntityTag(\n category=\"organization\",\n label=\"Internet, Archive\",\n abuse=None,\n lastmod=1560290400,\n source=\"https://archive.org/donate/cryptocurrency\",\n entity=17642138,\n tagpack_uri=\"http://tagpack_uri\",\n active=True,\n currency='btc'\n )\n\ntag2 = EntityTag(\n category=\"organization\",\n label=\"Internet Archive 2\",\n abuse=None,\n lastmod=1560290400,\n source=\"https://archive.org/donate/cryptocurrency\",\n entity=17642138,\n tagpack_uri=\"http://tagpack_uri\",\n active=True,\n currency='btc'\n )\n\nentityWithTags = Entity(\n no_outgoing_txs=280,\n last_tx=TxSummary(\n height=651545,\n tx_hash=\"5678\",\n timestamp=1602006938\n ),\n total_spent=Values(\n eur=2291256.5,\n value=138942266867,\n usd=2762256.25\n ),\n in_degree=4358,\n no_addresses=110,\n total_received=Values(\n usd=2583655.0,\n eur=2162085.5,\n value=139057689444\n ),\n no_incoming_txs=4859,\n entity=17642138,\n out_degree=176,\n first_tx=TxSummary(\n timestamp=1323298692,\n height=156529,\n tx_hash=\"4567\"\n ),\n balance=Values(\n value=115422577,\n usd=2.31,\n eur=1.15),\n tags=Tags(\n entity_tags=[tag2, tag],\n address_tags=[atag1, atag2],\n tag_coherence=0.5)\n)\n\neth_entity = Entity(\n no_outgoing_txs=eth_address.no_outgoing_txs,\n last_tx=eth_address.last_tx,\n total_spent=eth_address.total_spent,\n in_degree=eth_address.in_degree,\n no_addresses=1,\n total_received=eth_address.total_received,\n no_incoming_txs=eth_address.no_incoming_txs,\n entity=107925000,\n out_degree=eth_address.out_degree,\n first_tx=eth_address.first_tx,\n balance=eth_address.balance\n)\n\neth_entityWithTags = Entity(**eth_entity.to_dict())\neth_entityWithTags.tags = Tags(address_tags=[eth_tag, eth_tag2],\n entity_tags=[])\n\neth_neighbors = []\nfor n in eth_addressWithTagsOutNeighbors.neighbors:\n nn = Neighbor(**n.to_dict())\n nn.node_type = 'entity'\n eth_neighbors.append(nn)\n\neth_neighbors[0].id = '107925000'\neth_neighbors[1].id = '107925001'\n\neth_entityWithTagsOutNeighbors = Neighbors(\n next_page=None,\n neighbors=eth_neighbors)\n\nentityWithTagsOutNeighbors = Neighbors(\n next_page=None,\n neighbors=[\n Neighbor(\n received=Values(\n usd=3074.92,\n eur=2411.06,\n value=48610000000\n ),\n estimated_value=Values(\n eur=2411.06,\n usd=3074.92,\n value=48610000000\n ),\n id='2818641',\n node_type='entity',\n labels=['labelX', 'labelY'],\n no_txs=1,\n balance=Values(\n eur=0.0,\n usd=0.0,\n value=0\n )\n ),\n Neighbor(\n received=Values(\n usd=8517.93,\n eur=7064.18,\n value=7858798000\n ),\n estimated_value=Values(\n eur=1078.04,\n usd=1397.54,\n value=3375700000\n ),\n id='8361735',\n node_type='entity',\n labels=[],\n no_txs=3,\n balance=Values(\n eur=0.0,\n usd=0.0,\n value=0\n )\n )])\n\nentityWithTagsInNeighbors = Neighbors(\n next_page=None,\n neighbors=[\n Neighbor(\n received=Values(\n usd=43253.96,\n eur=33809.55,\n value=71089119639\n ),\n estimated_value=Values(\n usd=0.96,\n eur=0.72,\n value=190000\n ),\n id='67065',\n node_type='entity',\n labels=[],\n no_txs=10,\n balance=Values(\n eur=0.0,\n usd=0.0,\n value=606\n )\n ),\n Neighbor(\n received=Values(\n usd=13.41,\n eur=9.87,\n value=5000000000\n ),\n estimated_value=Values(\n eur=295.7,\n usd=404.02,\n value=50000000\n ),\n id='144534',\n node_type='entity',\n labels=[],\n no_txs=1,\n balance=Values(\n eur=0.0,\n usd=0.0,\n value=0\n )\n )])\n\n\nentityWithTagsAddresses = EntityAddresses(\n next_page=None,\n addresses=[\n Address(\n address=\"17gN64BPHtxi4mEM3qWrxdwhieUvRq8R2r\",\n last_tx=TxSummary(\n tx_hash=\"d325b684f4e6252d6bfdc83b75dc\"\n \"7ea650c9463ce286b023cf4ecaf305cf44a6\",\n height=572187,\n timestamp=1555605191\n ),\n no_outgoing_txs=35,\n balance=Values(\n value=0,\n eur=0.0,\n usd=0.0\n ),\n out_degree=27,\n first_tx=TxSummary(\n timestamp=1323298692,\n height=156529,\n tx_hash=\"dc035c562acc3230cec8c870293c1\"\n \"119d62e60b13932565231dbe5c407ff7508\"\n ),\n total_received=Values(\n value=95010277876,\n eur=16105.63,\n usd=21341.98\n ),\n total_spent=Values(\n value=95010277876,\n eur=70943.62,\n usd=95316.24\n ),\n no_incoming_txs=859,\n in_degree=1200\n ),\n Address(\n in_degree=1,\n first_tx=TxSummary(\n timestamp=1326139563,\n tx_hash=\"f73df637a912ac5f536d1e3b33695823a18a\"\n \"9e89ae7f3def89d9b06d6a475a52\",\n height=161451\n ),\n total_spent=Values(\n eur=0.2,\n value=763736,\n usd=0.26\n ),\n no_outgoing_txs=1,\n total_received=Values(\n usd=0.05,\n eur=0.04,\n value=763736\n ),\n balance=Values(\n usd=0.0,\n eur=0.0,\n value=0\n ),\n no_incoming_txs=1,\n out_degree=1,\n last_tx=TxSummary(\n timestamp=1362160247,\n tx_hash=\"c4f3c81d946d189265929212fdc76b18eabade\"\n \"7ab1fb0a86a2389c18b5851878\",\n height=223777\n ),\n address=\"1KeDrQdATuXaZFW4CL9tfe2zpQ5SrmBFWc\"\n )\n ]\n )\n\n\ndef get_entity(test_case):\n result = service.get_entity(currency='btc',\n entity=entityWithTags.entity,\n include_tags=True,\n tag_coherence=True)\n\n # tag_coherence tested by tests/util/test_tag_coherence.py so hardcode here\n test_case.assertIsNot(result.tags.tag_coherence, None)\n result.tags.tag_coherence = 0.5\n test_case.assertEqual(entityWithTags, result)\n\n result = service.get_entity(currency='eth',\n entity=eth_entity.entity,\n include_tags=True,\n tag_coherence=False)\n\n test_case.assertEqual(eth_entityWithTags, result)\n\n\ndef list_entities(test_case):\n result = service.list_entities(currency='btc')\n ids = [67065, 144534, 10102718, 10164852, 17642138, 2818641,\n 8361735, 123, 456, 789]\n test_case.assertEqual(ids.sort(),\n [row.entity for row in result.entities].sort())\n\n result = service.list_entities(currency='btc', ids=[67065, 456, 42])\n ids = [67065, 456]\n test_case.assertEqual(sorted(ids),\n sorted([row.entity for row in result.entities]))\n\n result = service.list_entities(currency='eth')\n test_case.assertEqual([107925000, 107925001, 107925002],\n sorted([row.entity for row in result.entities]))\n\n result = service.list_entities(currency='eth', ids=[107925000])\n test_case.assertEqual([eth_entity],\n result.entities)\n\n\ndef list_entities_csv(test_case):\n result = service.list_entities_csv(\n \"btc\", [456, 67065]).data.decode('utf-8')\n assertEqual(4, len(result.split(\"\\r\\n\")))\n result = service.list_entities_csv(\n \"eth\", [eth_entity.entity]).data.decode('utf-8')\n assertEqual(3, len(result.split(\"\\r\\n\")))\n\n\ndef list_tags_by_entity(test_case):\n result = service.list_tags_by_entity(currency='btc',\n entity=entityWithTags.entity,\n tag_coherence=False)\n result.tag_coherence = 0.5\n test_case.assertEqual(entityWithTags.tags, result)\n result = service.list_tags_by_entity(currency='eth',\n entity=eth_entityWithTags.entity,\n tag_coherence=False)\n test_case.assertEqual(eth_entityWithTags.tags, result)\n\n\ndef list_tags_by_entity_by_level_csv(test_case):\n csv = (\"abuse,active,category,currency,entity,label,lastmod,source,\"\n \"tagpack_uri\\r\\n\"\n \",True,organization,btc,17642138,\"\n \"Internet Archive 2,1560290400,https://archive.org/donate/crypto\"\n \"currency,http://tagpack_uri\\r\\n\"\n \",True,\"\n \"organization,btc,17642138,\\\"Internet, Archive\\\",1560290400,\"\n \"https://archive.org/donate/cryptocurrency,http://tagpack_uri\\r\\n\"\n )\n assertEqual(\n csv,\n service.list_tags_by_entity_by_level_csv(\n \"btc\", entityWithTags.entity, 'entity')\n .data.decode('utf-8'))\n\n\ndef list_entity_neighbors(test_case):\n result = service.list_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n include_labels=True,\n direction='out')\n test_case.assertEqual(entityWithTagsOutNeighbors, result)\n\n result = service.list_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n include_labels=True,\n direction='in')\n test_case.assertEqual(entityWithTagsInNeighbors, result)\n\n result = service.list_entity_neighbors(\n currency='eth',\n entity=eth_entityWithTags.entity,\n include_labels=True,\n direction='out')\n test_case.assertEqual(eth_entityWithTagsOutNeighbors, result)\n\n query_string = [('direction', 'in'), ('ids', '67065,144534')]\n headers = {\n 'Accept': 'application/json',\n }\n response = test_case.client.open(\n '/{currency}/entities/{entity}/neighbors'.format(\n currency=\"btc\",\n entity=\"17642138\"),\n method='GET',\n headers=headers,\n query_string=query_string)\n test_case.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n result = json.loads(response.data.decode('utf-8'))\n\n assertEqual(\n [n.id for n in entityWithTagsInNeighbors.neighbors],\n [n['id'] for n in result['neighbors']]\n )\n\n query_string = [('direction', 'in'), ('ids', '144534')]\n headers = {\n 'Accept': 'application/json',\n }\n response = test_case.client.open(\n '/{currency}/entities/{entity}/neighbors'.format(\n currency=\"btc\",\n entity=\"17642138\"),\n method='GET',\n headers=headers,\n query_string=query_string)\n test_case.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n result = json.loads(response.data.decode('utf-8'))\n\n test_case.assertEqual(\n [entityWithTagsInNeighbors.neighbors[1].id],\n [n['id'] for n in result['neighbors']]\n )\n\n query_string = [('direction', 'out'),\n ('ids',\n eth_entityWithTagsOutNeighbors.neighbors[0].id)]\n headers = {\n 'Accept': 'application/json',\n }\n response = test_case.client.open(\n '/{currency}/entities/{entity}/neighbors'.format(\n currency=\"eth\",\n entity=eth_entityWithTags.entity),\n method='GET',\n headers=headers,\n query_string=query_string)\n test_case.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n result = json.loads(response.data.decode('utf-8'))\n\n test_case.assertEqual(\n [eth_entityWithTagsOutNeighbors.neighbors[0].id],\n [n['id'] for n in result['neighbors']]\n )\n\n\ndef list_entity_neighbors_csv(test_case):\n csv = (\"balance_eur,balance_usd,balance_value,estimated_value_eur,\"\n \"estimated_value_usd,estimated_value_value,id,labels,no_txs,\"\n \"node_type,received_eur,received_usd,received_value\\r\\n0.0,0.0,0\"\n \",2411.06,3074.92,48610000000,2818641,\\\"['labelX', 'labelY']\\\",\"\n \"1,entity,2411.06,\"\n \"3074.92,48610000000\\r\\n0.0,0.0,0,1078.04,1397.54,3375700000,\"\n \"8361735,[],3,entity,7064.18,8517.93,7858798000\\r\\n\")\n result = service.list_entity_neighbors_csv(\n currency='btc',\n entity=entityWithTags.entity,\n direction='out',\n include_labels=True)\n assertEqual(csv, result.data.decode('utf-8'))\n\n\ndef list_entity_addresses(test_case):\n result = service.list_entity_addresses(\n currency='btc',\n entity=entityWithTags.entity)\n test_case.assertEqual(entityWithTagsAddresses, result)\n\n result = service.list_entity_addresses(\n currency='eth',\n entity=eth_entityWithTags.entity)\n expected = Address(\n address=eth_address.address,\n first_tx=eth_address.first_tx,\n last_tx=eth_address.last_tx,\n no_incoming_txs=eth_address.no_incoming_txs,\n no_outgoing_txs=eth_address.no_outgoing_txs,\n total_received=eth_address.total_received,\n total_spent=eth_address.total_spent,\n in_degree=eth_address.in_degree,\n out_degree=eth_address.out_degree,\n balance=eth_address.balance\n )\n\n assertEqual(EntityAddresses(\n next_page=None,\n addresses=[expected]), result)\n\n\ndef list_entity_addresses_csv(test_case):\n '''\n result = service.list_entity_addresses_csv(\n currency='btc',\n entity=entityWithTags.entity)\n assertEqual(\"\", result.data.decode('utf-8'))\n '''\n pass\n\n\ndef search_entity_neighbors(test_case):\n\n # Test category matching\n\n category = 'MyCategory'\n result = service.search_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n direction='out',\n depth=2,\n breadth=10,\n key='category',\n value=[category]\n )\n assertEqual(2818641, result.paths[0].node.entity)\n assertEqual(123, result.paths[0].paths[0].node.entity)\n assertEqual(category,\n result.paths[0].paths[0].node.tags.entity_tags[0].category)\n\n category = 'MyCategory'\n result = service.search_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n direction='in',\n depth=2,\n breadth=10,\n key='category',\n value=[category]\n )\n assertEqual(67065, result.paths[0].node.entity)\n assertEqual(123, result.paths[0].paths[0].node.entity)\n assertEqual(category,\n result.paths[0].paths[0].node.tags.entity_tags[0].category)\n\n # Test addresses matching\n\n addresses = ['abcdefg', 'xyz1234']\n result = service.search_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n direction='out',\n depth=2,\n breadth=10,\n key='addresses',\n value=addresses\n )\n assertEqual(2818641, result.paths[0].node.entity)\n assertEqual(456, result.paths[0].paths[0].node.entity)\n assertEqual(addresses, [a.address for a\n in result.paths[0].paths[0].matching_addresses])\n\n result = service.search_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n direction='out',\n depth=2,\n breadth=10,\n key='entities',\n value=['123']\n )\n assertEqual(2818641, result.paths[0].node.entity)\n assertEqual(123, result.paths[0].paths[0].node.entity)\n\n query_string = [('direction', 'out'),\n ('key', 'addresses'),\n ('value', ','.join(addresses)),\n ('depth', '7')]\n headers = {\n 'Accept': 'application/json',\n }\n response = test_case.client.open(\n '/{currency}/entities/{entity}/search'\n .format(currency=\"btc\", entity=entityWithTags.entity),\n method='GET',\n headers=headers,\n query_string=query_string)\n\n result = json.loads(response.data.decode('utf-8'))\n assertEqual(2818641, result['paths'][0]['node']['entity'])\n assertEqual(456, result['paths'][0]['paths'][0]['node']['entity'])\n assertEqual(addresses,\n [a['address'] for a\n in result['paths'][0]['paths'][0]['matching_addresses']])\n\n addresses = ['abcdefg']\n result = service.search_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n direction='out',\n depth=2,\n breadth=10,\n key='addresses',\n value=addresses\n )\n assertEqual(2818641, result.paths[0].node.entity)\n assertEqual(456, result.paths[0].paths[0].node.entity)\n assertEqual(addresses, [a.address for a\n in result.paths[0].paths[0].matching_addresses])\n\n addresses = ['0x234567']\n result = service.search_entity_neighbors(\n currency='eth',\n entity=eth_entityWithTags.entity,\n direction='out',\n depth=2,\n breadth=10,\n key='addresses',\n value=addresses\n )\n assertEqual(107925001, result.paths[0].node.entity)\n assertEqual(107925002, result.paths[0].paths[0].node.entity)\n assertEqual(addresses, [a.address for a\n in result.paths[0].paths[0].matching_addresses])\n\n # Test value matching\n\n result = service.search_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n direction='out',\n depth=2,\n breadth=10,\n key='total_received',\n value=['value', 5, 150]\n )\n assertEqual(2818641, result.paths[0].node.entity)\n assertEqual(789, result.paths[0].paths[0].node.entity)\n assertEqual(10, result.paths[0].paths[0].node.total_received.value)\n\n # Test value matching\n\n result = service.search_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n direction='out',\n depth=2,\n breadth=10,\n key='total_received',\n value=['value', 5, 8]\n )\n assertEqual(SearchResultLevel1(paths=[]), result)\n #\n # Test value matching\n\n result = service.search_entity_neighbors(\n currency='btc',\n entity=entityWithTags.entity,\n direction='out',\n depth=2,\n breadth=10,\n key='total_received',\n value=['eur', 50, 100]\n )\n assertEqual(2818641, result.paths[0].node.entity)\n assertEqual(789, result.paths[0].paths[0].node.entity)\n assertEqual(100.0, result.paths[0].paths[0].node.total_received.eur)\n","sub_path":"gsrest/test/entities_service.py","file_name":"entities_service.py","file_ext":"py","file_size_in_byte":21254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"344552668","text":"from display import *\nfrom matrix import *\nfrom draw import *\nimport time\n\ndef parse_file( fname, points, transform ):\n transform = ident(new_matrix())\n screen = new_screen()\n f=open(fname)\n lines = f.read().split('\\n')\n n = 0\n\n #******* IMPORTANT NOTE ***********#\n\n # I have note gotten image magic to work (there is a piazza question evidencing this)\n # As a result, I have created an alternative where i just create a new image, from 0 to n, each time a or v is entered. I will try and fix my problems (with image magic, not the ones stemming from divorce and an uninterested mother) \n\n \n for i in range(0,len(lines)):\n line= lines[i]\n line.strip()\n\n i = i + 1\n #print_matrix(transform)\n \n if line == \"l\":\n p = lines[i].split(' ')\n for x in range(0,len(p)):\n p[x]=int(p[x])\n add_edge(points,p[0],p[1],p[2],p[3],p[4],p[5])\n elif line == \"s\":\n args = lines[i].split(' ')\n r = make_scale(float(args[0]),float(args[1]),float(args[2]))\n transform = matrix_mult(r,transform)\n elif line == \"t\":\n args = lines[i].split(' ')\n r = make_translate(float(args[0]),float(args[1]),float(args[2]))\n transform = matrix_mult(r,transform)\n elif line == \"x\":\n arg = lines[i]\n r = make_rotX(int(arg))\n transform = matrix_mult(r,transform)\n elif line == \"y\":\n arg = lines[i]\n r = make_rotY(int(arg))\n transform = matrix_mult(r,transform)\n elif line == \"z\":\n arg = lines[i]\n r = make_rotZ(int(arg))\n transform = matrix_mult(r,transform)\n elif line == \"g\":\n #save_extension(screen,lines[i])\n display(screen, str(n))\n n = n+1\n else:\n i = i - 1\n if line == \"i\":\n transform = ident(transform)\n elif line == \"a\":\n points = matrix_mult(transform,points)\n elif line == \"v\":\n clear_screen(screen)\n draw_lines( points, screen, [255,0,0] )\n display(screen, str(n))\n n = n+1\n \n \n\npoints = []\ntransform = new_matrix()\n\nparse_file( 'script_c', points, transform )\n\n","sub_path":"graphics/transformations/8/adam_dehovitz/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"553870906","text":"from cs50 import get_int\n\n\ndef main():\n height = get_height()\n draw(height, height)\n\n\ndef get_height():\n while True:\n height = get_int(\"Height: \")\n if height>0 and height<9:\n break\n return height\n\n\ndef draw(height, h):\n if height == 0:\n return\n\n draw(height - 1, h)\n print(\" \" * (h - height), end='')\n print(\"#\" * height)\n\nmain()\n","sub_path":"Week6/pset6/mario/less/mario.py","file_name":"mario.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"588489296","text":"import xml.etree.ElementTree as ET\nfrom xml.sax.saxutils import escape\n\nfrom marketo.wrapper import campaign_record\n\ndef wrap(source='MKTOWS', name=None, exactName=False):\n \"\"\"\n Create request body for getCampaignsForSource.\n\n :type source: str\n :param source: the source requested. Possible values 'MKTOWS' or 'SALES'\n\n :type name: str\n :param name: the name filter to apply to the request. Optional.\n\n :type exactName: bool\n :param exactName: boolean flag indicating if the returned campaigns must be an exact match to name\n\n :returns: string of XML for the request body\n \"\"\"\n nameRestriction = ''\n if name:\n nameRestriction = '' + escape(name) + '' + \\\n '' + ('true' if exactName else 'false') + ''\n\n return (\n '' +\n '' + escape(source) + '' +\n nameRestriction +\n '')\n\n\ndef unwrap(response):\n \"\"\"\n Unwrap a getCampaignsForSource response.\n\n :type response: requests module HTTP response\n :param response: response from the SOAP request\n\n :returns; list of campaigns\n \"\"\"\n root = ET.fromstring(response.text)\n campaigns = []\n\n for child in root.find('.//campaignRecordList'):\n campaigns.append(campaign_record.unwrap(child))\n\n return campaigns","sub_path":"marketo/wrapper/get_campaigns_for_source.py","file_name":"get_campaigns_for_source.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"261925699","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.conf.urls.static import static\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'redpsi.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^accounts/', include('registration.backends.simple.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n\n# url(r'^media/(?P.*)$', 'django.views.static.serve',\n# {'document_root': settings.MEDIA_ROOT, } ),\n\n# url(r'^static/(?P.*)$', 'django.views.static.serve',\n# {'document_root': settings.MEDIA_ROOT, } ),\n # inicio\n url(r'^inicio/' , include('apps.inicio.urls')),\n # wisc\n url(r'^wisc3/' , include('apps.wisc3.urls')),\n # otros\n url(r'^' , include('apps.otros.urls')),\n # wais\n url(r'^wais/' , include('apps.wais.urls')),\n # wais4\n url(r'^wais4/' , include('apps.wais4.urls')),\n\n url(r'^paciente/' , include('apps.paciente.urls')),\n\n url(r'^pie/' , include('apps.pie.urls')),\n\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n\n\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n url(r'^media/(?P.*)$', 'django.views.static.serve', {\n 'document_root': settings.MEDIA_ROOT,\n }),\n url(r'^static/(?P.*)$', 'django.views.static.serve', {\n 'document_root': settings.STATIC_URL,\n }),\n )\nurlpatterns += staticfiles_urlpatterns()\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"redpsi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"395463741","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport urllib.request as urllib3\n\n\ndef parsing():\n page_link = 'http://old.ibda.ranepa.ru/students/mo/'\n html = urlopen(page_link)\n soup = BeautifulSoup(html, 'lxml')\n type(soup)\n schedule_table = soup.find('tr', {'class': 'bg2'})\n \"\"\"finding that table\"\"\"\n schedule_week = schedule_table.find('a').get('href')\n urllib3.urlretrieve('http://old.ibda.ranepa.ru'+schedule_week, 'raspisanie.xlsx')\n open('raspisanie.xlsx')\n \"\"\"opening the doc\"\"\"\n","sub_path":"scrapping.py","file_name":"scrapping.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"253551982","text":"from room import Room\nfrom player import Player\nfrom item import Item\n\n# Declare all the items\n\nitem_dic = {\n 'sword': Item('sword','Use this for battle'),\n 'axe': Item('axe','Use this for battle'),\n 'coin': Item('coin', 'It is shiny!'),\n 'potion': Item('potion', 'Restores 10 Health')\n}\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\",[item_dic['sword']]),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\",[item_dic['coin']]),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\",[item_dic['axe']]),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\",[item_dic['potion'], item_dic['coin']]),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\",[item_dic['coin']]),\n}\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n#\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\n\nstarting_room = room['outside']\nitems = []\n# Create Person object\nname = input(\"Enter your name: \")\np1 = Player(name, starting_room, items)\n\n# Error to print when user attempts to move in non existent room\nerror = \"~~~You cannot go that way!~~~\"\n\ngame_run = True\nwhile game_run == True:\n print(p1.room)\n print(\"\\n\\tEnter 'n', 's', 'e', or 'w' to move\\n\\tEnter 'get [item]' to pick up an item or 'drop [item]' to drop it.\\n\\t(q to quit)\")\n user_input = input(\"~~> \")\n print(\"________________________________________________________________________________________\")\n\n # Game Logic\n\n # End Game\n if user_input == 'q':\n print(\"\\nClosing Game...\")\n exit()\n\n # Get an item\n elif 'get' in user_input:\n item_input = user_input.split(' ')[1]\n if item_dic[item_input] in p1.room.items:\n p1.items.append(item_dic[item_input]) # add to inventory\n p1.room.items.remove(item_dic[item_input]) # remove item from room\n print(f\"{item_input} added!\")\n else:\n print(f\"~~~{item_input} not available~~~\")\n\n # Drop an item\n elif 'drop' in user_input:\n item_input = user_input.split(' ')[1]\n if item_dic[item_input] in p1.room.items:\n p1.items.remove(item_dic[item_input])\n p1.room.items.append(item_dic[item_input])\n else:\n print(f\"~~~{item_input} not available~~~\")\n\n # Move rooms \n elif user_input == 'n':\n if p1.room.n_to != None:\n p1.room = p1.room.n_to\n else:\n print(error)\n elif user_input == 's':\n if p1.room.s_to != None:\n p1.room = p1.room.s_to\n else:\n print(error)\n\n elif user_input == 'e':\n if p1.room.e_to != None:\n p1.room = p1.room.e_to\n else:\n print(error)\n\n elif user_input == 'w':\n if p1.room.w_to != None:\n p1.room = p1.room.w_to\n else:\n print(error)\n\n # Invalid input\n else:\n print(\"~~~input not valid~~~\")","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"210395180","text":"#Time Complexity : O(N) where N is number of elemeents\r\n#Space Complexity :O(1)\r\nclass Solution:\r\n def candy(self, ratings: List[int]) -> int:\r\n if (ratings == None or len(ratings) == 0):\r\n return 0\r\n candies = [1 for i in range(len(ratings))]\r\n for i in range(1, len(ratings)):\r\n if (ratings[i] > ratings[i - 1]):\r\n candies[i] = candies[i - 1] + 1\r\n\r\n total = candies[len(ratings) - 1]\r\n for i in range(len(ratings) - 2, -1, -1):\r\n if (ratings[i] > ratings[i + 1]):\r\n candies[i] = max(candies[i], candies[i + 1] + 1)\r\n total += candies[i] \r\n return total ","sub_path":"candy.py","file_name":"candy.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"273669036","text":"# Copyright (C) 2017 Daniel Watkins \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport inspect\nimport os\nimport socket\nimport subprocess\nfrom collections import namedtuple\nfrom glob import iglob\n\nimport pytest\nimport yaml\n\n\ndef get_available_port():\n sock = socket.socket()\n sock.bind(('', 0))\n port = sock.getsockname()[1]\n sock.close()\n return port\n\n\nJJB_CONFIG = '''\\\n[job_builder]\nignore_cache=True\n\n[jenkins]\nurl=http://0.0.0.0:{}/\nuser=XXX\npassword=XXX\n'''.format(get_available_port())\n\n\ndef _direct_runner(tmpdir, config):\n output_dir = os.path.join(tmpdir, 'output')\n subprocess.check_call([\n 'jenkins-jobs', 'test', os.path.join(tmpdir), '-o', output_dir])\n config_args = []\n if config is not None:\n conf_file = tmpdir.join('config.ini')\n conf_file.write(config)\n config_args = ['--conf', str(conf_file)]\n success = True\n try:\n output = subprocess.check_output(\n ['jenkins-job-linter', output_dir] + config_args,\n stderr=subprocess.STDOUT,\n )\n except subprocess.CalledProcessError as exc:\n output = exc.output\n success = False\n return success, output.decode('utf-8')\n\n\ndef _jjb_subcommand_runner(tmpdir, config):\n conf_file = tmpdir.join('config.ini')\n config = '\\n'.join([JJB_CONFIG, config or ''])\n conf_file.write(config)\n success = True\n try:\n output = subprocess.check_output([\n 'jenkins-jobs', '--conf', str(conf_file),\n 'lint', os.path.join(tmpdir)],\n stderr=subprocess.STDOUT,\n )\n except subprocess.CalledProcessError as exc:\n output = exc.output\n success = False\n return success, output.decode('utf-8')\n\n\n@pytest.fixture(params=['direct', 'jjb_subcommand'])\ndef runner(request):\n runner_funcs = {\n 'direct': _direct_runner,\n 'jjb_subcommand': _jjb_subcommand_runner,\n }\n return runner_funcs[request.param]\n\n\ndef test_integration(runner, tmpdir, integration_testcase):\n tmpdir.join('jobs.yaml').write(integration_testcase.jobs_yaml)\n success, output = runner(tmpdir, integration_testcase.config)\n assert integration_testcase.expected_output == output\n assert integration_testcase.expect_success == success\n\n\nIntegrationTestcase = namedtuple(\n 'IntegrationTestcase',\n ['test_name', 'jobs_yaml', 'expected_output', 'expect_success', 'config'])\n\n\ndef _get_case_item(key, case_dict, defaults, required=True):\n value = case_dict.get(key, None)\n if value is not None:\n return value\n if required:\n return defaults[key]\n return defaults.get(key, None)\n\n\ndef _parse_case(case_dict, defaults):\n if 'description' not in case_dict:\n raise Exception('Test {} has no description'.format(case_dict['name']))\n return IntegrationTestcase(\n case_dict['name'],\n _get_case_item('jobs.yaml', case_dict, defaults),\n _get_case_item('expected_output', case_dict, defaults),\n _get_case_item('expect_success', case_dict, defaults),\n _get_case_item('config', case_dict, defaults, required=False),\n )\n\n\ndef _parse_testcases(filenames):\n names = set()\n for filename in filenames:\n with open(filename) as f:\n data = yaml.safe_load(f)\n defaults = data.get('defaults', {})\n for case_dict in data['cases']:\n testcase = _parse_case(case_dict, defaults)\n if testcase.test_name in names:\n raise Exception(\n 'Duplicate test name: {}'.format(testcase.test_name))\n names.add(testcase.test_name)\n yield testcase\n\n\ndef pytest_generate_tests(metafunc):\n test_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))\n test_cases = _parse_testcases(iglob(os.path.join(test_dir, 'test_*.yaml')))\n if 'integration_testcase' in metafunc.fixturenames:\n metafunc.parametrize('integration_testcase', test_cases,\n ids=lambda testcase: testcase.test_name)\n","sub_path":"integration_tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"330310716","text":"# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom io import BytesIO\nfrom textwrap import dedent\nfrom typing import Tuple\nfrom zipfile import ZipFile\n\nimport pytest\n\nfrom pants.backend.awslambda.python.rules import PythonAwsLambdaFieldSet\nfrom pants.backend.awslambda.python.rules import rules as awslambda_python_rules\nfrom pants.backend.awslambda.python.target_types import PythonAWSLambda\nfrom pants.backend.awslambda.python.target_types import rules as target_rules\nfrom pants.backend.python.target_types import PythonLibrary\nfrom pants.core.goals.package import BuiltPackage\nfrom pants.core.target_types import Files, RelocatedFiles, Resources\nfrom pants.core.target_types import rules as core_target_types_rules\nfrom pants.engine.addresses import Address\nfrom pants.engine.fs import DigestContents\nfrom pants.testutil.rule_runner import QueryRule, RuleRunner\n\n\n@pytest.fixture\ndef rule_runner() -> RuleRunner:\n return RuleRunner(\n rules=[\n *awslambda_python_rules(),\n *target_rules(),\n *core_target_types_rules(),\n QueryRule(BuiltPackage, (PythonAwsLambdaFieldSet,)),\n ],\n target_types=[PythonAWSLambda, PythonLibrary, Files, RelocatedFiles, Resources],\n )\n\n\ndef create_python_awslambda(rule_runner: RuleRunner, addr: Address) -> Tuple[str, bytes]:\n rule_runner.set_options(\n [\n \"--backend-packages=pants.backend.awslambda.python\",\n \"--source-root-patterns=src/python\",\n ],\n env_inherit={\"PATH\", \"PYENV_ROOT\", \"HOME\"},\n )\n target = rule_runner.get_target(addr)\n built_asset = rule_runner.request(BuiltPackage, [PythonAwsLambdaFieldSet.create(target)])\n assert (\n \" Runtime: python3.7\",\n \" Handler: lambdex_handler.handler\",\n ) == built_asset.artifacts[0].extra_log_lines\n digest_contents = rule_runner.request(DigestContents, [built_asset.digest])\n assert len(digest_contents) == 1\n relpath = built_asset.artifacts[0].relpath\n assert relpath is not None\n return relpath, digest_contents[0].content\n\n\ndef test_create_hello_world_lambda(rule_runner: RuleRunner) -> None:\n rule_runner.write_files(\n {\n \"src/python/foo/bar/hello_world.py\": dedent(\n \"\"\"\n def handler(event, context):\n print('Hello, World!')\n \"\"\"\n ),\n \"src/python/foo/bar/BUILD\": dedent(\n \"\"\"\n python_library(name='lib')\n\n python_awslambda(\n name='lambda',\n dependencies=[':lib'],\n handler='foo.bar.hello_world:handler',\n runtime='python3.7',\n )\n \"\"\"\n ),\n }\n )\n zip_file_relpath, content = create_python_awslambda(\n rule_runner, Address(\"src/python/foo/bar\", target_name=\"lambda\")\n )\n assert \"src.python.foo.bar/lambda.zip\" == zip_file_relpath\n zipfile = ZipFile(BytesIO(content))\n names = set(zipfile.namelist())\n assert \"lambdex_handler.py\" in names\n assert \"foo/bar/hello_world.py\" in names\n\n\ndef test_warn_files_targets(rule_runner: RuleRunner, caplog) -> None:\n rule_runner.write_files(\n {\n \"assets/f.txt\": \"\",\n \"assets/BUILD\": dedent(\n \"\"\"\\\n files(name='files', sources=['f.txt'])\n relocated_files(\n name='relocated',\n files_targets=[':files'],\n src='assets',\n dest='new_assets',\n )\n\n # Resources are fine.\n resources(name='resources', sources=['f.txt'])\n \"\"\"\n ),\n \"src/py/project/__init__.py\": \"\",\n \"src/py/project/app.py\": dedent(\n \"\"\"\\\n def handler(event, context):\n print('Hello, World!')\n \"\"\"\n ),\n \"src/py/project/BUILD\": dedent(\n \"\"\"\\\n python_library(\n name='lib',\n dependencies=['assets:files', 'assets:relocated', 'assets:resources'],\n )\n\n python_awslambda(\n name='lambda',\n dependencies=[':lib'],\n handler='foo.bar.hello_world:handler',\n runtime='python3.7',\n )\n \"\"\"\n ),\n }\n )\n\n assert not caplog.records\n zip_file_relpath, _ = create_python_awslambda(\n rule_runner, Address(\"src/py/project\", target_name=\"lambda\")\n )\n assert caplog.records\n assert \"src.py.project/lambda.zip\" == zip_file_relpath\n assert (\n \"The python_awslambda target src/py/project:lambda transitively depends on\" in caplog.text\n )\n assert \"assets/f.txt:files\" in caplog.text\n assert \"assets:relocated\" in caplog.text\n assert \"assets:resources\" not in caplog.text\n","sub_path":"src/python/pants/backend/awslambda/python/rules_test.py","file_name":"rules_test.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"127593309","text":"r = 0.5\ntotal = 0\ngrenseverdi = 1/(1-r)\ntol = 0.001\ncounter = 0\nwhile(total <= grenseverdi - tol ):\n total = total + r**counter\n counter = counter+1 \n print(total)\nprint(\"Summen av rekka er\",total)\nprint(\"For å være innenfor toleransegrensen,\",tol, \",kjørte løkken,\",counter,\"ganger.\")\nprint(\"Differansen mellom sum og grenseverdi er\", abs(total-grenseverdi))","sub_path":"ITGK/Øving3/GeometriskRekkeB.py","file_name":"GeometriskRekkeB.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"48094572","text":"def vlan_list_to_bitmap(self, vlanlist):\n ' convert vlan list to vlan bitmap '\n vlan_bit = (['0'] * 1024)\n bit_int = ([0] * 1024)\n vlan_list_len = len(vlanlist)\n for num in range(vlan_list_len):\n tagged_vlans = int(vlanlist[num])\n if ((tagged_vlans <= 0) or (tagged_vlans > 4094)):\n self.module.fail_json(msg='Error: Vlan id is not in the range from 1 to 4094.')\n j = (tagged_vlans / 4)\n bit_int[j] |= (8 >> (tagged_vlans % 4))\n vlan_bit[j] = hex(bit_int[j])[2]\n vlan_xml = ''.join(vlan_bit)\n return vlan_xml","sub_path":"Data Set/bug-fixing-5/c8697a4864f95672c58598eff207548b0bcc63e5--bug.py","file_name":"c8697a4864f95672c58598eff207548b0bcc63e5--bug.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"609918193","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\n\nfrom employees.models import Employee,Supervision\nfrom overtime.models import OvertimeApplication\nfrom payroll.models import PayrollRecord, Payslip\nfrom leave.models import LeaveApplication, Leave_Types\nfrom leave.procedures import get_leave_balance, get_employee_leave, leave_balance\n# Create your views here.\nfrom role.models import Notification\n\n\ndef employee_role_page(request):\n user = request.user\n # If employee\n context = {\n \"employee\": user.solitonuser.employee,\n \"view_profile_page\": 'active'\n }\n return render(request, \"role/employee/employee.html\", context)\n\ndef leave_page(request, id):\n # Get the employee\n employee = Employee.objects.get(pk=id)\n\n leave_applications = LeaveApplication.objects.filter(employee=employee)\n context = {\n \"leave_applications\": leave_applications,\n \"l_types\": Leave_Types.objects.all(),\n \"l_balance\": employee.leave_balance,\n \"leave_page\": \"active\"\n }\n return render(request, 'role/employee/leave.html', context)\n\n\ndef employee_payslip_page(request, id):\n # Get the employee\n employee = Employee.objects.get(pk=id)\n # Get the latest payroll record\n payroll_record = PayrollRecord.objects.all().order_by('-id')[0]\n # Get the payroll\n payroll = Payslip.objects.get(employee=employee, payroll_record=payroll_record)\n context = {\n \"payroll\": payroll,\n \"month\": payroll.payroll_record.month,\n \"year\": payroll.payroll_record.year,\n \"name_of_employee\": \"{} {}\".format(payroll.employee.first_name, payroll.employee.last_name),\n \"payslip_page\": \"active\"\n }\n return render(request, 'role/employee/payslip.html', context)\n\ndef employee_overtime_page(request, id):\n\n # Get the employee\n employee = Employee.objects.get(pk=id)\n # Get the pending overtime applications\n pending_applications = OvertimeApplication.objects.filter(status=\"Pending\",supervisee=employee)\n context = {\n \"pending_applications\": pending_applications,\n \"overtime_page\": \"active\"\n }\n return render(request, 'role/employee/pending_overtime_applications.html', context)\n\ndef employee_approved_overtime_page(request, id):\n # Get the employee\n employee = Employee.objects.get(pk=id)\n # Get the approved overtime applications\n approved_applications = OvertimeApplication.objects.filter(status=\"Approved\",supervisee=employee)\n context = {\n \"overtime_page\": \"active\",\n \"approved_applications\": approved_applications\n }\n return render(request, 'role/employee/approved_overtime_applications.html', context)\n\ndef employee_rejected_overtime_page(request, id):\n # Get the employee\n employee = Employee.objects.get(pk=id)\n # Get the approved overtime applications\n approved_applications = OvertimeApplication.objects.filter(status=\"Rejected\",supervisee=employee)\n context = {\n \"overtime_page\": \"active\",\n \"approved_applications\": approved_applications\n }\n return render(request, 'role/employee/rejected_overtime_page.html', context)\n\ndef employee_supervisees_page(request,id):\n # Get the employee\n employee = Employee.objects.get(pk=id)\n context = {\n \"supervisees_page\": \"active\",\n \"supervisions\": Supervision.objects.filter(supervisor=employee)\n \n }\n return render(request,'role/employee/supervisees.html',context)\n\ndef employee_supervisee_page(request,id):\n # Get the supervisee\n supervisee = Employee.objects.get(pk=id)\n # Get the supervisee\n supervisee = Employee.objects.get(pk=id)\n # Get the approved overtime applications\n pending_applications = OvertimeApplication.objects.filter(status=\"Pending\",supervisee=supervisee)\n context = {\n \"supervisees_page\":\"active\",\n \"supervisee\": supervisee,\n \"pending_applications\": pending_applications\n }\n return render(request,'role/employee/supervisee.html',context)\n\n@login_required\ndef apply_overtime(request):\n overtime_application = create_overtime_application(request)\n supervisee_id = overtime_application.applicant.id\n return HttpResponseRedirect(reverse('employee_supervisee_page',args=[supervisee_id]))\n\n\ndef create_overtime_application(request):\n overtime_date = request.POST['date']\n start_time = request.POST['start_time']\n end_time = request.POST['end_time']\n description = request.POST['description']\n supervisee_id = request.POST['supervisee_id']\n supervisor_id = request.POST['supervisor_id']\n supervisor = Employee.objects.get(pk=supervisor_id)\n supervisee = Employee.objects.get(pk=supervisee_id)\n overtime_application = OvertimeApplication(date=overtime_date, start_time=start_time, end_time=end_time,\n supervisor=supervisor,\n description=description, supervisee=supervisee)\n overtime_application.save()\n return overtime_application","sub_path":"role/views/employee_views.py","file_name":"employee_views.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"408824200","text":"import datetime\nimport json\n\n\nclass Range:\n def __init__(self, time):\n self.startTime = time\n self.endTime = time\n self.count = 0\n\n def inc(self):\n self.count += 1\n\n def label(self):\n return self.startTime.strftime(\"%H:%M\") + \" - \" + self.endTime.strftime(\"%H:%M\")\n\n\nclass External:\n KEY_10KM = '10548 m'\n KEY_21KM = '21097 m'\n KEY_42KM = '42195 m'\n\n def __init__(self):\n self.ranges = []\n self.results = []\n\n def request(self, key, gender):\n file = open('data/2014.json')\n x = file.read()\n data = json.loads(x)\n\n if gender == 'ALL':\n self.results += data['data'][key]['M']\n self.results += data['data'][key]['F']\n elif gender == 'M' or gender == 'F':\n self.results = data['data'][key][gender]\n\n def calculate(self, step, number, hour, minute):\n step = step\n step_number = number * step\n\n base = datetime.datetime(1900, 1, 1, hour, minute)\n for i in range(0, step_number, step):\n r = Range(base + datetime.timedelta(minutes=i))\n self.ranges.append(r)\n\n for man in self.results:\n t = datetime.datetime.strptime(man[9], \"%H:%M:%S.%f\")\n for n in self.ranges:\n n.endTime = n.startTime + datetime.timedelta(minutes=step)\n if n.startTime < t < n.endTime:\n n.inc()\n break\n\n def print(self):\n for r in self.ranges:\n print(r.time)\n print(r.count)\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"381688438","text":"#!/usr/bin/python3\n\n# with open('nome.txt','r') as arquivo:\n# conteudo = arquivo.readlines()\n\ndef manipular_arquivo(nome,modo,conteudo = None):\n if modo == 'r':\n with open(nome,modo) as arquivo:\n cont = arquivo.readlines()\n print(cont)\n elif modo == 'a':\n with open(nome,modo) as arquivo:\n arquivo.write(conteudo+'\\n')\n return True\n\nmanipular_arquivo('frutas.txt','a','banana')\n","sub_path":"func10.py","file_name":"func10.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"72363492","text":"from flask import Flask, request, jsonify\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, Sequential\nimport numpy as np\nimport os\n\n\nprint(tf.__version__)\n\nprint(keras.__version__)\n\n#model = keras.models.load_model('./model.h5')\n#print(os.path.join(os.path.dirname(__file__),'model.h5'))\n\n\napp = Flask(__name__)\n\n@app.route('/previsao/', methods=['GET'])\n@app.route('/previsao/m4', methods=['GET'])\ndef pred_wheater():\n\n RainToday = float(request.args.get('RainToday'))\n Humidity3pm = float(request.args.get('Humidity3pm'))\n Rainfall = float(request.args.get('Rainfall'))\n Humidity9am = float(request.args.get('Humidity9am'))\n\n\n model = keras.models.load_model(os.path.join(os.path.dirname(__file__),'model_top4.h5'))\n\n x = np.array([[RainToday, Humidity3pm, Rainfall, Humidity9am]])\n\n y_pred = model.predict(x)\n\n if ( y_pred > 0.5 ):\n resp = {'prev':1}\n else:\n resp = {'prev':0}\n\n return jsonify(resp)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"Weather AUS/Flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"414326743","text":"TITLE = \"Big Iron\"\n# screen dims\nWIDTH = 900\nHEIGHT = 800\n# frames per second\nFPS = 60\n# colors\nWHITE = (255, 255, 255)\nBLACK = (0,0,0)\nBIG_GREY = (30, 30, 30)\nSKY_BLUE = (143, 185, 252)\nVAULT_BLUE = (63, 66, 226)\nWASTELAND_SKY = (178, 214, 111)\nSCRAP_GRAY = (177, 186, 201)\nFONT_NAME = 'comic sans'\nSPRITESHEET = \"spritesheet (2).png\"\nSPRITESHEET2 = \"spritesheet_jumper.png\"\n# data files\nHS_FILE = \"highscore.txt\"\n# player settings\nPLAYER_ACC = 0.5\nPLAYER_FRICTION = -0.12\nPLAYER_GRAV = 0.6\nPLAYER_JUMP = 100\n# game settings\nBOOST_POWER = 30\nPOW_SPAWN_PCT = 7\nMOB_FREQ = 300\n# layers - uses numerical value in layered sprites\nPLAYER_LAYER = 2\nPLATFORM_LAYER = 1\nPOW_LAYER = 1\nMOB_LAYER = 2\nCLOUD_LAYER = 0\n\n# platform settings\n''' old platforms from drawing rectangles'''\n'''\nPLATFORM_LIST = [(0, HEIGHT - 40, WIDTH, 40),\n (65, HEIGHT - 300, WIDTH-400, 40),\n (20, HEIGHT - 350, WIDTH-300, 40),\n (200, HEIGHT - 150, WIDTH-350, 40),\n (200, HEIGHT - 450, WIDTH-350, 40)]\n'''\nPLATFORM_LIST = [(0, HEIGHT - 40),\n (WIDTH/2, HEIGHT - 100),\n (105, HEIGHT - 200),\n (420, HEIGHT - 550),\n (670, HEIGHT - 750),\n (885, HEIGHT - 900),\n (998, HEIGHT - 1500),\n (1000, HEIGHT - 1750)]\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"614551716","text":"import torch as to\nfrom abc import ABC, abstractmethod\nfrom typing import Sequence\nfrom warnings import warn\n\nimport pyrado\nfrom pyrado.exploration.normal_noise import DiagNormalNoise, FullNormalNoise\nfrom pyrado.utils.properties import Delegate\nfrom pyrado.sampling.hyper_sphere import sample_from_hyper_sphere_surface\n\n\nclass StochasticParamExplStrat(ABC):\n \"\"\" Exploration strategy which samples policy parameters from a distribution. \"\"\"\n\n def __init__(self, param_dim: int):\n \"\"\"\n Constructor\n\n :param param_dim: number of policy parameters\n \"\"\"\n self.param_dim = param_dim\n\n @abstractmethod\n def sample_param_set(self, nominal_params: to.Tensor) -> to.Tensor:\n \"\"\"\n Sample one set of policy parameters from the current distribution.\n\n :param nominal_params: parameter set (1-dim tensor) to sample around\n :return: sampled parmeter set (1-dim tensor)\n \"\"\"\n raise NotImplementedError\n\n def sample_param_sets(self,\n nominal_params: to.Tensor,\n num_samples: int,\n include_nominal_params: bool = False) -> to.Tensor:\n \"\"\" \n Sample multiple sets of policy parameters from the current distribution.\n\n :param nominal_params: parameter set (1-dim tensor) to sample around\n :param num_samples: number of parameter sets\n :param include_nominal_params: `True` to include the nominal parameter values as first parameter set\n :return: policy parameter sets as NxP or (N+1)xP tensor where N is the number samples and P is the number of\n policy parameters\n \"\"\"\n ps = [self.sample_param_set(nominal_params) for _ in range(num_samples)]\n if include_nominal_params:\n ps.insert(0, nominal_params)\n return to.stack(ps)\n\n\nclass SymmParamExplStrat(StochasticParamExplStrat):\n \"\"\"\n Wrap a parameter exploration strategy to enforce symmetric sampling.\n The function `sample_param_sets` will always return an even number of parameters, and it's guaranteed that\n ps[:len(ps)//2] == -ps[len(ps)//2:]\n \"\"\"\n\n def __init__(self, wrapped: StochasticParamExplStrat):\n \"\"\"\n Constructor\n\n :param wrapped: exploration strategy to wrap around\n \"\"\"\n super().__init__(wrapped.param_dim)\n self.wrapped = wrapped\n\n def sample_param_set(self, nominal_params: to.Tensor) -> to.Tensor:\n # Should not be done, but fail gracefully\n warn('Called sample_param_set on SymmParamExplStrat, which will still return only one param set', stacklevel=2)\n return self.wrapped.sample_param_set(nominal_params)\n\n def sample_param_sets(self, nominal_params: to.Tensor,\n num_samples: int,\n include_nominal_params: bool = False) -> to.Tensor:\n # Adjust sample size to be even\n if num_samples % 2 != 0:\n num_samples += 1\n\n # Sample one half\n pos_half = self.wrapped.sample_param_sets(nominal_params, num_samples // 2)\n\n # Mirror around nominal params for the other half\n # hp = nom + eps => eps = hp - nom\n # hn = nom - eps = nom - (hp - nom) = 2*nom - hp\n neg_half = 2. * nominal_params - pos_half\n parts = [pos_half, neg_half]\n\n # Add nominal params if requested\n if include_nominal_params:\n parts.insert(0, nominal_params.view(1, -1))\n return to.cat(parts)\n\n def __getattr__(self, name: str):\n \"\"\"\n Forward unknown attributes to wrapped strategy.\n\n :param name: name of the attribute\n \"\"\"\n # getattr raises an AttributeError if not found, just as this method should.\n return getattr(self.wrapped, name)\n\n\nclass NormalParamNoise(StochasticParamExplStrat):\n \"\"\" Sample parameters from a normal distribution. \"\"\"\n\n def __init__(self,\n param_dim: int,\n full_cov: bool = False,\n std_init: float = 1.,\n std_min: [float, Sequence[float]] = 0.01,\n train_mean: bool = False):\n \"\"\"\n Constructor\n\n :param param_dim: number of policy parameters\n :param full_cov: use a full covariance matrix or a diagonal covariance matrix (independent random variables)\n :param std_init: initial standard deviation for the noise distribution\n :param std_min: minimal standard deviation for the exploration noise\n :param train_mean: set `True` if the noise should have an adaptive nonzero mean, `False` otherwise\n \"\"\"\n # Call the StochasticParamExplStrat's constructor\n super().__init__(param_dim)\n\n if full_cov:\n self._noise = FullNormalNoise(noise_dim=param_dim, std_init=std_init, std_min=std_min,\n train_mean=train_mean)\n else:\n self._noise = DiagNormalNoise(noise_dim=param_dim, std_init=std_init, std_min=std_min,\n train_mean=train_mean)\n\n @property\n def noise(self) -> [FullNormalNoise, DiagNormalNoise]:\n \"\"\" Get the exploation noise. \"\"\"\n return self._noise\n\n def sample_param_set(self, nominal_params: to.Tensor) -> to.Tensor:\n return self._noise(nominal_params).sample()\n\n def sample_param_sets(self,\n nominal_params: to.Tensor,\n num_samples: int,\n include_nominal_params: bool = False) -> to.Tensor:\n # Sample all exploring policy parameter at once\n ps = self._noise(nominal_params).sample((num_samples,))\n if include_nominal_params:\n ps = to.cat([nominal_params.view(1, -1), ps])\n return ps\n\n # Make NormalParamNoise appear as if it would have the following functions / properties\n reset_expl_params = Delegate('_noise')\n adapt = Delegate('_noise')\n std = Delegate('_noise')\n cov = Delegate('_noise')\n get_entropy = Delegate('_noise')\n\n\nclass HyperSphereParamNoise(StochasticParamExplStrat):\n \"\"\" Sample parameters from a normal distribution. \"\"\"\n\n def __init__(self,\n param_dim: int,\n expl_r_init: float = 1.0):\n \"\"\"\n Constructor\n\n :param param_dim: number of policy parameters\n :param expl_r_init: initial radius of the hyper-sphere\n \"\"\"\n # Call the base class constructor\n super().__init__(param_dim)\n\n self._r_init = expl_r_init\n self._r = expl_r_init\n\n @property\n def r(self) -> float:\n \"\"\" Get the radius of the hypersphere. \"\"\"\n return self._r\n\n def reset_expl_params(self):\n \"\"\" Reset all parameters of the exploration strategy. \"\"\"\n self._r = self._r_init\n\n def adapt(self, r: float):\n \"\"\" Set a new radius for the hyper sphere from which the policy parameters are sampled. \"\"\"\n if not r > 0.0:\n pyrado.ValueErr(given=r, g_constraint='0')\n self._r = r\n\n def sample_param_set(self, nominal_params: to.Tensor) -> to.Tensor:\n return nominal_params + self._r * sample_from_hyper_sphere_surface(self.param_dim, 'normal')\n","sub_path":"Pyrado/pyrado/exploration/stochastic_params.py","file_name":"stochastic_params.py","file_ext":"py","file_size_in_byte":7230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"166300480","text":"class Solution:\n def addToArrayForm(self, A: List[int], K: int) -> List[int]:\n X = 0\n pow10 = 1\n for digit in reversed(A):\n X += digit*pow10\n pow10 *= 10\n \n K += X\n length = len(str(K))\n res = [None for i in range(length)]\n \n pow10 = 10\n for i in reversed(range(length)):\n num = (K % pow10)\n res[i] = num\n K -= num\n K //= 10\n return res\n \n","sub_path":"leetcode_solutions/add_to_array_form_of_integer.py","file_name":"add_to_array_form_of_integer.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"197527393","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018, Jigar Tarpara and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nfrom frappe.custom.doctype.custom_field.custom_field import create_custom_fields\nclass BookServiceSetting(Document):\n\tdef validate(self):\n\t\tif self.enable == 1:\n\t\t\tsetup_custom_fields()\n\t\t\tsetup_custom_script()\n\ndef setup_custom_fields():\n\tcustom_fields = {\n\t\t\"Item\": [\n\t\t\tdict(fieldname='booking_item',\n\t\t\tlabel='Booking Item',\n\t\t\t\tfieldtype='Check',\n\t\t\t\tinsert_after='disabled',\n\t\t\t\tprint_hide=1),\n\t\t\tdict(fieldname='service_item',\n\t\t\tlabel= 'Service Item',\n\t\t\t\tfieldtype='Link',\n\t\t\t\tinsert_after='booking_item',\n\t\t\t\toptions='Item',\n\t\t\t\tdepends_on='eval:doc.booking_item',\n\t\t\t\tread_only=0, print_hide=1)\n\t\t]\n\t}\n\n\tcreate_custom_fields(custom_fields)\n\ndef setup_custom_script(ignore_validate = False):\n\tif not frappe.db.exists(\"Custom Script\", \"Item-Client\"):\n\t\tcustom_script = frappe.get_doc({\n\t\t\t\t\"doctype\":\"Custom Script\",\n\t\t\t\t\"dt\": \"Item\",\n\t\t\t\t\"script\": \"\"\"\n\t\t\t\t\tfrappe.ui.form.on('Item', {\n\t\t\t\t\t\tbooking_item: function(frm) {\n\t\t\t\t\t\t\tif(frm.doc.booking_item == 0){\n\t\t\t\t\t\t\t\tfrm.doc.service_item = \"\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\"\"\"\n\t\t\t})\n\t\tcustom_script.flags.ignore_validate = ignore_validate\n\t\tcustom_script.insert()","sub_path":"bookingapp/booking_service_app/doctype/book_service_setting/book_service_setting.py","file_name":"book_service_setting.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"282701765","text":"import pytest\nimport testcontainers.compose\nimport requests\nimport backoff\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nfrom fastapi.encoders import jsonable_encoder\nfrom registry.models import Subscriber\n\nCOMPOSE_PATH = \"./\"\n\n\n@pytest.fixture(scope=\"module\")\ndef compose(request):\n \"\"\"\n Test fixture to launch the docker containers as per the docker compose\n file. It has a retry loop to ensure the containers are up before\n releasing the tests.\n \"\"\"\n\n def fin():\n \"\"\"\n Tear down handler to bring down the containers once the tests have\n run to completion.\n \"\"\"\n print(\"Stopping containers\")\n compose.stop()\n request.addfinalizer(fin)\n\n @backoff.on_exception(backoff.expo,\n requests.exceptions.RequestException,\n max_time=30)\n def is_up(app_host: str, app_port: str):\n \"\"\"\n Continually polls the containers with back-off until we get a\n response back and we know the containers are up and running.\n The bond registry container depends on the dynamodb container\n (as per the docker-compose file) so we know that both containers\n are running if api returns a result.\n \"\"\"\n r = requests.get(f\"http://{app_host}:{app_port}/docs\")\n assert r.status_code == 200\n\n print(\"Starting containers\")\n compose = testcontainers.compose.DockerCompose(COMPOSE_PATH)\n compose.start()\n\n host = compose.get_service_host(\"bond-registry\", 8080)\n port = compose.get_service_port(\"bond-registry\", 8080)\n is_up(host, port)\n return compose\n\n\n@pytest.fixture(scope=\"module\")\ndef api_url(compose):\n \"\"\"\n Provide the URL to the API once the containers are up.\n \"\"\"\n host = compose.get_service_host(\"bond-registry\", 8080)\n port = compose.get_service_port(\"bond-registry\", 8080)\n return f\"{host}:{port}\"\n\n\n@pytest.fixture(scope=\"module\")\ndef db_url(compose):\n \"\"\"\n Provide the URL to dynamodb once the containers are up.\n \"\"\"\n host = compose.get_service_host(\"dynamodb-local\", 8000)\n port = compose.get_service_port(\"dynamodb-local\", 8000)\n return f\"{host}:{port}\"\n\n\n@pytest.fixture(scope='module')\ndef dynamodb(db_url):\n \"\"\"\n Connect to the local dynamodb container.\n \"\"\"\n try:\n resource = \\\n boto3.resource(\"dynamodb\",\n endpoint_url=f'http://{db_url}/',\n region_name='us-west-2',\n aws_access_key_id='AWS_ACCESS_KEY_ID',\n aws_secret_access_key='AWS_SECRET_ACCESS_KEY')\n except ClientError as err:\n print(err)\n raise err\n return resource\n\n\n@pytest.fixture(scope='module')\ndef table(dynamodb):\n \"\"\"Create the mock bond table.\"\"\"\n with open(\"./localdb/01-create-table.json\") as read_file:\n table_def = json.load(read_file)\n try:\n table = dynamodb.create_table(\n TableName=table_def['TableName'],\n BillingMode=table_def['BillingMode'],\n KeySchema=table_def['KeySchema'],\n AttributeDefinitions=table_def['AttributeDefinitions'],\n GlobalSecondaryIndexes=table_def['GlobalSecondaryIndexes'])\n\n \"\"\"Pre-loaded DynamoDB table for get tests.\"\"\"\n subs = {\n 'eniesc200': Subscriber(sid='eniesc200',\n name='Ed',\n email='ed@mail.com'),\n 'tfomoo100': Subscriber(sid='tfomoo100',\n name='Tom',\n email='tom@snail.com'),\n 'bfoere300': Subscriber(sid='bfoere300',\n name='Bill',\n email='bill@mojo.com')\n }\n items = [\n {'bond_id': '6cc333cd',\n 'host_account_id': 'KYOT95889719595091',\n 'sub_account_id': 'NSSV61341208978885',\n 'host_cost_center': 'yellow',\n 'sub_cost_center': 'silver',\n 'subscribers': {}\n }, {\n 'bond_id': 'bf66a510',\n 'host_account_id': 'HAEP29388232018739',\n 'sub_account_id': 'WZNH57184416064999',\n 'host_cost_center': 'yellow',\n 'sub_cost_center': 'white',\n 'subscribers': jsonable_encoder(subs)\n }, {\n 'bond_id': '3f4436a3',\n 'host_account_id': 'BULG01950964065116',\n 'sub_account_id': 'PFUP24464317335973',\n 'host_cost_center': 'maroon',\n 'sub_cost_center': 'navy',\n 'subscribers': jsonable_encoder(subs)\n }, {\n 'bond_id': '070840c5',\n 'host_account_id': 'LXJC36779030364939',\n 'sub_account_id': 'OYHE81882804630311',\n 'host_cost_center': 'maroon',\n 'sub_cost_center': 'olive',\n 'subscribers': jsonable_encoder(subs)\n }, {\n 'bond_id': 'e6d9c05f',\n 'host_account_id': 'YHRH31548177246824',\n 'sub_account_id': 'QZUL57771567168857',\n 'host_cost_center': 'navy',\n 'sub_cost_center': 'aqua',\n 'subscribers': jsonable_encoder(subs)\n }, {\n 'bond_id': 'deleteme',\n 'host_account_id': 'YHRH31548175555555',\n 'sub_account_id': 'QZUL57771567777777',\n 'host_cost_center': 'navy',\n 'sub_cost_center': 'aqua',\n 'subscribers': {}\n }, {\n 'bond_id': 'eb5e729a',\n 'host_account_id': 'YHRH31548177246824',\n 'sub_account_id': 'EVJS54814803488145',\n 'host_cost_center': 'navy',\n 'sub_cost_center': 'orange',\n 'subscribers': {}\n }, {\n 'bond_id': '2e545043',\n 'host_account_id': 'NAMD04758644119335',\n 'sub_account_id': 'BVOD03985622038101',\n 'host_cost_center': 'green',\n 'sub_cost_center': 'orange',\n 'subscribers': {}\n }, {\n 'bond_id': '402206d5',\n 'host_account_id': 'ZGDX86819087481638',\n 'sub_account_id': 'CNUE67550266655258',\n 'host_cost_center': 'black',\n 'sub_cost_center': 'orange',\n 'subscribers': {}\n }\n ]\n for r in items:\n table.put_item(Item=r)\n except ClientError as err:\n print(err)\n raise err\n yield table\n","sub_path":"tests/integration/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":6674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"104824296","text":"import numpy as np\r\n\r\n# For the gamma function, the considerations advised in Newman p. 205 were used\r\n# which includes a change of variable to integrate from 0 to \"infinity\"\r\n\r\n# the generic integrand is \"integrand\" while the simplified integrand when a = 1\r\n# is integrand_1\r\n\r\ndef integrand(a,z):\r\n return (a-1.0)/((1.0-z)*(1.0-z))*np.exp((a-1.0)*np.log((z*(a-1.0))/(1.0-z))-(z*(a-1.0))/(1.0-z))\r\n\r\n# integrand can be simplified when a = 1\r\ndef integrand_1(z):\r\n return 1.0/(1-z)**2*np.exp(-z/(1-z))\r\n\r\ndef gamma(a):\r\n \r\n # Considerations for gamma take were:\r\n # z = x/((a-1) + x)\r\n # gamma = integral of exp((a-1)*ln(x)-x)\r\n \r\n if a == 1.0:\r\n n = -1\r\n I_error = [100]\r\n points = [1]\r\n # doubling number of points used in calculation\r\n for i in range(10):\r\n points.append(2*points[i])\r\n \r\n # keep doubling points until error is < 1.0e-3\r\n for p in range(len(points)):\r\n n += 1\r\n I = 0\r\n \r\n # create z list from ~ 0 to infinity\r\n z = np.linspace(0+1e-16,1.0-1e-16,points[p]+1)\r\n h = 1.0/points[p]\r\n \r\n for i in range(points[p]):\r\n I += h*((integrand_1(z[i])+integrand_1(z[i+1]))/2.0)\r\n \r\n # append I to a list to estimate error\r\n I_error.append(I)\r\n if 1/3.0*abs(I_error[n+1]-I_error[n]) < 1e-3:\r\n break\r\n else: \r\n n = -1\r\n I_error = [100]\r\n points = [1]\r\n # doubling number of points used in calculation\r\n for i in range(10):\r\n points.append(2*points[i])\r\n \r\n # keep doubling points until error is < 1.0e-3\r\n for p in range(len(points)):\r\n n += 1\r\n I = 0\r\n \r\n # create z list from ~ 0 to infinity\r\n z = np.linspace(0+1e-16,1.0-1e-16,points[p]+1)\r\n h = 1.0/points[p]\r\n \r\n for i in range(points[p]):\r\n I += h*((integrand(a,z[i])+integrand(a,z[i+1]))/2.0)\r\n \r\n # append I to a list to estimate error\r\n I_error.append(I)\r\n if 1/3.0*abs(I_error[n+1]-I_error[n]) < 1e-3:\r\n break\r\n return I\r\n\r\n# creating file and inputing values of various gamma functions\r\nx = np.arange(1,10.2,0.1)\r\nfor i in range(len(x)):\r\n f = open('Gamma.dat','a')\r\n gamma_value = gamma(x[i])\r\n gamma_value = str(gamma_value)\r\n a_used = x[i]\r\n a_used = str(a_used)\r\n f.write(a_used)\r\n f.write(',')\r\n f.write(gamma_value)\r\n f.write('\\n')\r\n","sub_path":"Comp-Phys-1/Assignment #6 Gamma Function.py","file_name":"Assignment #6 Gamma Function.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"221011329","text":"a = list(map(int, input().split()))\n\ndef kangaroo(x1, v1, x2, v2):\n\n if x1>x2 and v1>v2:\n return'NO'\n\n elif x2>x1 and v2>v1:\n return 'NO'\n\n else:\n result = 'NO'\n for i in range(10000):\n if x1+i*v1==x2+i*v2:\n result = 'YES'\n break\n return result\n\nb=kangaroo(a[0], a[1], a[2], a[3])\nprint(b)\n","sub_path":"learn1/44.py","file_name":"44.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"145489243","text":"#!/usr/bin/env python\nfrom math import exp, log10 \nimport os\nimport numpy as np\nfrom matplotlib.pyplot import *\n\np = 10\npoints = np.linspace(10, 100000, p)\nrelative_error = []\nstep_lenght = []\n\nfor j in range(p):\n \n # Running Project_1 from terminal\n n = points[j]\n n = int(n)\n os.system(\"g++ project_1.cpp -o project_1_error\")\n os.system(\"./project_1_error %d\" % n)\n \n # Reading file data.dat\n infile = open('data.dat', 'r')\n infile.readline()\n values = []\n for line in infile:\n \n value = float(line)\n values.append(value)\n \n infile.close()\n \n # Inserting the boundary conditions v_0 and v_n+1 = 0\n values.insert(0, 0.0)\n values.append(0.0)\n\n # Makeing values an array\n v = np.array(values)\n \n # The analytic solution of u(x)\n h = 1./(n+1.)\n x = []\n u = []\n for i in range(n+2):\n\n x_i = i*h\n x.append(x_i)\n \n u_x = 1 - (1 - exp(-10))*x_i - exp(-10*x_i)\n u.append(u_x)\n\n # Makeing u an array\n U = np.array(u)\n\n # Calculating the relative error\n eps = np.zeros(n+1)\n eps = np.log10(np.abs((v[1:-1] - U[1:-1])/U[1:-1]))\n eps_max = max(eps)\n relative_error.append(eps_max)\n step_lenght.append(log10(h))\n \n\n\n#print relative_error\n#print step_lenght\n\n#figure(1)\nplot(step_lenght, relative_error)\n\ntitle(\"The relative error.\" )\n\nxlabel(\"Step lenght\")\nylabel(\"Relative error\")\n\nshow()\n","sub_path":"relativ_error.py","file_name":"relativ_error.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"132400281","text":"from NaiveBayesClassifier import NaiveBayesClassifier\nimport sys\n\n#===============================================\n# Script\n#===============================================\n\nTRAIN_FILE_NAME = sys.argv[1]\nTEST_FILE_NAME = sys.argv[2]\n\nNB = NaiveBayesClassifier()\nNB.train(TRAIN_FILE_NAME)\nNB.test(TEST_FILE_NAME)\n\n\n\n\n'''\nimport sys\nimport collections\n\nf = open(sys.argv[1],'r') #To open the file in order to read it\ns = f.read() #Reading the contents of the opened file\nf.close()\ns = s.lower() #Converting the read lines into lower case\n#s = s.rstrip(\"\\n\")\ns1 = s.split('\\n') #Splitting the read lines into a list of words (between each space\n#s1 = filter(None, s1)\n#print s1\ncounter = collections.Counter(s1)\nk, v = counter.keys(), counter.values()\nw = []\nfor k,v in counter.items():\n w.append((str('%03d' % v)+' :'+str(k)))\n\nw1 = sorted(w, reverse = True)\na = '\\n'.join(w1)\nprint a\n#sys.stdout.write(a)\n\n\nimport sys\nimport numpy as np\nimport collections\n\n\nf = open(sys.argv[1],'r')\ns = f.read() #Reading the contents of the opened file\nf.close()\ns = s.lower() #Converting the read lines into lower case\n\n\n\n\ns1 = s.split('\\n')\ns1 = filter(None, s1)\n\ns1 = list(set(s1))\ncounter = collections.Counter(s1)\nk, v = counter.keys(), counter.values()\nw = []\nfor k,v in counter.items():\n w.append((str(k)+':'+str(v)))\n\n#w1 = sorted(w, reverse = True)\n\na = ','.join(w)\nprint w\n\n\n#print \"hello world\"\n'''","sub_path":"9_Naive_Bayes/nb.py","file_name":"nb.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"632799263","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\n\nfrom .views import (HomePageView, OrganisationsView,\n AllQuestionsView, AllAnswersView)\n\nurlpatterns = patterns('',\n url(r'^$', TemplateView.as_view(template_name=\"home.html\"), name='home'),\n url(r'^organisations/', OrganisationsView.as_view(), name='organisations'),\n url(r'^questions/all/', AllQuestionsView.as_view(), name='all_questions'),\n url(r'^answers/all/', AllAnswersView.as_view(), name='all_answers'),\n)","sub_path":"q_and_a/apps/prototype/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"587504589","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('login', views.login),\n path('form', views.form),\n path('prediction_sp', views.prediction_sp),\n path('receive_csv', views.receive_csv),\n path('graph_sp', views.graph_sp),\n path('receive_csv_dj', views.receive_csv_dj),\n path('graph_dj', views.graph_dj),\n path('prediction_dj', views.prediction_dj),\n path('prediction_un', views.prediction_un),\n path('receive_csv_un', views.receive_csv_un),\n path('graph_un', views.graph_un),\n\n path('buttons', views.buttons),\n path('cards', views.cards),\n path('register', views.register),\n path('forgotpassword', views.forgotpassword),\n\n path('404page', views.fourpage),\n path('blankpage', views.blankpage),\n\n path('charts', views.charts),\n path('tables', views.tables),\n\n path('colors', views.colors),\n path('borders', views.borders),\n path('animations', views.animations),\n path('other', views.other),\n\n path('receive_input_sp', views.receive_input_sp),\n\n path('receive_input_dj', views.receive_input_dj),\n\n path('receive_input_un', views.receive_input_un)\n\n\n\n]","sub_path":"website_version_2/c19/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"327813279","text":"#/usr/bin/env python\n\nimport time\nimport sys\nimport gobject\nimport threading\n\nfrom pymachinetalk.dns_sd import ServiceDiscovery\nimport pymachinetalk.halremote as halremote\n\n\nclass BasicClass(threading.Thread):\n def __init__(self, loop):\n threading.Thread.__init__(self)\n self.daemon = True\n self.loop = loop\n\n def run(self):\n timeout = 2.0\n\n launcher_sd = ServiceDiscovery(service_type=\"_launcher._sub._machinekit._tcp\", debug=True)\n print('starting launcher service discovery')\n launcher_sd.start()\n assert launcher_sd.wait_discovered(timeout)\n data = launcher_sd.service_names.values()[0]\n print('launcher discovered %s %s' % (data.name, data.dsn))\n uuid = data.uuid\n print('uuid=%s' % uuid)\n\n halrcmd_sd = ServiceDiscovery(service_type=\"_halrcmd._sub._machinekit._tcp\", uuid=uuid, debug=True)\n print('starting halrcmd service discovery')\n halrcmd_sd.start()\n assert halrcmd_sd.wait_discovered(timeout)\n data = halrcmd_sd.service_names.values()[0]\n print('halrcmd discovered %s %s' % (data.name, data.dsn))\n halrcmd_dsn = data.dsn\n\n halrcomp_sd = ServiceDiscovery(service_type=\"_halrcomp._sub._machinekit._tcp\", uuid=uuid, debug=True)\n print('starting halrcomp service discovery')\n halrcomp_sd.start()\n assert halrcomp_sd.wait_discovered(timeout)\n data = halrcomp_sd.service_names.values()[0]\n print('halrcomp discovered %s %s' % (data.name, data.dsn))\n halrcomp_dsn = data.dsn\n\n halrcomp = halremote.RemoteComponent('anddemo')\n halrcomp.newpin('button0', halremote.HAL_BIT, halremote.HAL_OUT)\n halrcomp.newpin('button1', halremote.HAL_BIT, halremote.HAL_OUT)\n halrcomp.newpin('led', halremote.HAL_BIT, halremote.HAL_IN)\n #halrcomp.no_create = True\n halrcomp.halrcomp_uri = halrcomp_dsn\n halrcomp.halrcmd_uri = halrcmd_dsn\n\n halrcomp.ready()\n print('waiting for component connected')\n assert halrcomp.wait_connected()\n print('component connected')\n halrcomp.stop()\n\n self.loop.quit()\n\n\ndef main():\n gobject.threads_init() # important: initialize threads if gobject main loop is used\n loop = gobject.MainLoop()\n basic = BasicClass(loop=loop)\n basic.start()\n try:\n loop.run()\n except KeyboardInterrupt:\n loop.quit()\n\n #print(\"stopping threads\")\n #basic.stop()\n\n # wait for all threads to terminate\n while threading.active_count() > 1:\n time.sleep(0.1)\n\n print(\"threads stopped\")\n sys.exit(0)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/testing/halremote.py","file_name":"halremote.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"128032294","text":"import sys\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nimport ujson as json\n\ndata_path = sys.argv[1]\nflag = sys.argv[2]\n\n#plt.xkcd()\n\ndef plot_line(x, y, title, x_label, y_label, color):\n plt.figure(title)\n plt.title(title)\n plt.plot(x, y, ls='solid', lw=2.5, c=color)\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n\ndef plot_hist(x, y, title, x_label, y_label, color):\n #plt.figure(title)\n fig, ax = plt.subplots()\n xx = range(len(x))\n bars = ax.bar(xx, y, color=color)\n ax.set_title(title)\n ax.set_xlabel(x_label)\n ax.set_ylabel(y_label)\n ax.set_xticks(xx)\n ax.set_xticklabels(x)\n\nif flag == 'train':\n with open(data_path, 'r') as f:\n data = defaultdict(list)\n for line in f:\n epoch, loss, acc = line.strip().split()\n epoch = int(epoch)\n loss = float(loss)\n acc = float(acc)\n data['epochs'].append(epoch)\n data['losses'].append(loss)\n data['accs'].append(acc)\n plot_line(data['epochs'], data['losses'], 'Cross-entropy loss vs. epoch', 'Epoch', 'Cross-entropy loss', 'r')\n plot_line(data['epochs'], data['accs'], 'Accuracy vs. epoch', 'Epoch', 'Accuracy', 'b')\n \nelse:\n mode, k = flag.split('_')\n if k == '1':\n color = 'red'\n elif k == '3':\n color = 'orange'\n elif k == '6':\n color = 'yellow'\n title = '{}-note accuracy gain b/w consecutive contexts, on {} data'.format(k, mode)\n with open(data_path, 'r') as f:\n data = json.load(f).items()\n data.sort(key=lambda p: int(p[0]))\n data = data[:9]\n contexts = [int(datum[0]) for datum in data]\n accs = [datum[1] for datum in data]\n contexts = [' {} to {}'.format(contexts[i-1],contexts[i])for i in xrange(1, len(contexts))]\n accs = [accs[i]-accs[i-1] for i in xrange(1, len(accs))]\n plot_hist(contexts, accs, title, 'Context jump', 'Accuracy', color)\n \n\nplt.show()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"92676470","text":"# -*- coding: utf-8 -*-\n\n#%% IMPORTS\nfrom libraries.model.network import Encoder, EncoderTL, Decoder, Generator, Discriminator\nfrom libraries.model import network \nfrom libraries.model.options import Options\nfrom torchvision import models\nfrom libraries.torchsummary import summary\nimport torch.nn as nn\n\nfrom matplotlib import pyplot as plt\n#from dataset import generateDataloader\n#from dataset import getCifar10 as cifar\n#%% VARIABLE\n\nopt = Options(in_channels=3)\nopt.out_channels = 64\n\n#%%\ndataloader = cifar()\n\n#%%\nfor elem in dataloader['train']:\n print(elem[0].shape)\n item = elem[0]\n break\n\n#%% TEST ENCODER\n\nencoder = Encoder(opt) \nencoder\n\nopt.tl = 'resnet18'\n#opt.tl = 'vgg16'\nencoderTL = EncoderTL(opt)\nencoderTL\nsummary(encoderTL.cuda(), (3,224,224))\n#%% TEST DECODER\n\ndecoder = Decoder(opt) \n\n#%% TEST GENERATOR\n\nGenerator(opt)\n\n#%%\ndiscr = Discriminator(opt)\ndiscr\n\nclassifier, features = discr(item)\n\nprint(len(classifier))\nprint(len(features))\n#%%\nresnet = models.resnet18(pretrained=True)\nresnet.fc = nn.Linear(512, 100)\nsummary(resnet.cuda(), (3,224,224))\n\n\n#%%\nvgg = models.vgg16(pretrained=True)\n\n#%%\nopt = Options(out_channels=1)\nfilterNN = network.FilterNN(opt, 9)\n# 11 -> 5 \n# 5 -> 2\n# 7 -> 3\n# 9 -> 4\n# 3 -> 1\nsummary(filterNN.cuda(), (3,256,1600))\n#%%\nfilters = filterNN.conv.weight\na = filters[0].cpu().detach()\nout = np.transpose(a, (2,1,0))\n\nplt.imshow(a[2])\n","sub_path":"v2/libraries/tests/test_network.py","file_name":"test_network.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"638271822","text":"#!/usr/bin/python\n# written by: atholcomb\n# io_input.py\n# script reverses the given string object\n\ndef is_palindrome(string1):\n if string1 == string1[::-1]:\n print(\"Palindrome\")\n else:\n print(\"Not a Palindrome\")\n\n","sub_path":"input_output/io_input.py","file_name":"io_input.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"82536644","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of REANA.\n# Copyright (C) 2020 CERN.\n#\n# REANA is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Status module for REANA.\"\"\"\n\nimport subprocess\nfrom datetime import datetime, timedelta\n\nfrom invenio_accounts.models import SessionActivity\nfrom reana_commons.config import SHARED_VOLUME_PATH\nfrom reana_db.database import Session\nfrom reana_db.models import (\n Workflow,\n RunStatus,\n InteractiveSession,\n User,\n Resource,\n UserResource,\n ResourceType,\n ResourceUnit,\n)\nfrom reana_server.utils import get_usage_percentage\nfrom sqlalchemy import desc\n\n\nclass REANAStatus:\n \"\"\"REANA Status interface.\"\"\"\n\n def __init__(self, from_=None, until=None, user=None):\n \"\"\"Initialise REANAStatus class.\"\"\"\n self.from_ = from_ or (datetime.now() - timedelta(days=1))\n self.until = until or datetime.now()\n self.user = user\n\n def execute_cmd(self, cmd):\n \"\"\"Execute a command.\"\"\"\n return subprocess.check_output(cmd).decode().rstrip(\"\\r\\n\")\n\n def get_status(self):\n \"\"\"Get status summary for REANA.\"\"\"\n raise NotImplementedError()\n\n\nclass InteractiveSessionsStatus(REANAStatus):\n \"\"\"Class to retrieve statistics related to REANA interactive sessions.\"\"\"\n\n def __init__(self, from_=None, until=None, user=None):\n \"\"\"Initialise InteractiveSessionsStatus class.\n\n :param from_: From which moment in time to collect information. Not\n implemented yet.\n :param until: Until which moment in time to collect information. Not\n implemented yet.\n :param user: A REANA-DB user model.\n :type from_: datetime\n :type until: datetime\n :type user: reana_db.models.User\n \"\"\"\n super().__init__(from_=from_, until=until, user=user)\n\n def get_active(self):\n \"\"\"Get the number of active interactive sessions.\"\"\"\n non_active_statuses = [\n RunStatus.stopped,\n RunStatus.deleted,\n RunStatus.failed,\n ]\n active_interactive_sessions = (\n Session.query(InteractiveSession)\n .filter(InteractiveSession.status.notin_(non_active_statuses))\n .count()\n )\n return active_interactive_sessions\n\n def get_status(self):\n \"\"\"Get status summary for interactive sessions.\"\"\"\n return {\n \"active\": self.get_active(),\n }\n\n\nclass SystemStatus(REANAStatus):\n \"\"\"Class to retrieve statistics related to the current REANA component.\"\"\"\n\n def __init__(self, from_=None, until=None, user=None):\n \"\"\"Initialise SystemStatus class.\n\n :param from_: From which moment in time to collect information. Not\n implemented yet.\n :param until: Until which moment in time to collect information. Not\n implemented yet.\n :param user: A REANA-DB user model.\n :type from_: datetime\n :type until: datetime\n :type user: reana_db.models.User\n \"\"\"\n super().__init__(from_=from_, until=until, user=user)\n\n def uptime(self):\n \"\"\"Get component uptime.\"\"\"\n cmd = [\"uptime\", \"-p\"]\n return self.execute_cmd(cmd)\n\n def get_status(self):\n \"\"\"Get status summary for REANA system.\"\"\"\n return {\n \"uptime\": self.uptime(),\n }\n\n\nclass StorageStatus(REANAStatus):\n \"\"\"Class to retrieve statistics related to REANA storage.\"\"\"\n\n def __init__(self, from_=None, until=None, user=None):\n \"\"\"Initialise StorageStatus class.\n\n :param from_: From which moment in time to collect information. Not\n implemented yet.\n :param until: Until which moment in time to collect information. Not\n implemented yet.\n :param user: A REANA-DB user model.\n :type from_: datetime\n :type until: datetime\n :type user: reana_db.models.User\n \"\"\"\n super().__init__(from_=from_, until=until, user=user)\n\n def _get_path(self):\n \"\"\"Retrieve the path to calculate status from.\"\"\"\n path = None\n if self.user:\n path = self.user.workspace_path\n else:\n path = SHARED_VOLUME_PATH + \"/users\"\n\n return path\n\n def users_directory_size(self):\n \"\"\"Get disk usage for users directory.\"\"\"\n depth = 0\n cmd = [\"du\", \"-h\", f\"--max-depth={depth}\", self._get_path()]\n output = self.execute_cmd(cmd)\n size = output.split()[0]\n return size\n\n def shared_volume_health(self):\n \"\"\"REANA shared volume health.\"\"\"\n cmd = [\"df\", \"-h\", SHARED_VOLUME_PATH]\n output = self.execute_cmd(cmd).splitlines()\n headers = output[0].split()\n values = output[1].split()\n used_index = headers.index(\"Used\")\n available_index = headers.index(\"Avail\")\n use_percentage_index = headers.index(\"Use%\")\n\n return (\n f\"{values[used_index]}/{values[available_index]} \"\n f\"({values[use_percentage_index]})\"\n )\n\n def get_status(self):\n \"\"\"Get status summary for REANA storage.\"\"\"\n return {\n \"user_directory_size\": self.users_directory_size(),\n \"shared_volume_health\": self.shared_volume_health(),\n }\n\n\nclass UsersStatus(REANAStatus):\n \"\"\"Class to retrieve statistics related to REANA users.\"\"\"\n\n def __init__(self, from_=None, until=None, user=None):\n \"\"\"Initialise UsersStatus class.\n\n :param from_: From which moment in time to collect information. Not\n implemented yet.\n :param until: Until which moment in time to collect information. Not\n implemented yet.\n :param user: A REANA-DB user model.\n :type from_: datetime\n :type until: datetime\n :type user: reana_db.models.User\n \"\"\"\n super().__init__(from_=from_, until=until, user=user)\n\n def active_web_users(self):\n \"\"\"Get the number of active web users.\n\n Depends on how long does a session last.\n \"\"\"\n return Session.query(SessionActivity).count()\n\n def get_status(self):\n \"\"\"Get status summary for REANA users.\"\"\"\n return {\n \"active_web_users\": self.active_web_users(),\n }\n\n\nclass WorkflowsStatus(REANAStatus):\n \"\"\"Class to retrieve statistics related to REANA workflows.\"\"\"\n\n def __init__(self, from_=None, until=None, user=None):\n \"\"\"Initialise WorkflowsStatus class.\n\n :param from_: From which moment in time to collect information. Not\n implemented yet.\n :param until: Until which moment in time to collect information. Not\n implemented yet.\n :param user: A REANA-DB user model.\n :type from_: datetime\n :type until: datetime\n :type user: reana_db.models.User\n \"\"\"\n super().__init__(from_=from_, until=until, user=user)\n\n def get_workflows_by_status(self, status):\n \"\"\"Get the number of workflows in status ``status``.\"\"\"\n number = Session.query(Workflow).filter(Workflow.status == status).count()\n\n return number\n\n def restarted_workflows(self):\n \"\"\"Get the number of restarted workflows.\"\"\"\n number = Session.query(Workflow).filter(Workflow.restart).count()\n\n return number\n\n def stuck_in_running_workflows(self):\n \"\"\"Get the number of stuck running workflows.\"\"\"\n inactivity_threshold = datetime.now() - timedelta(hours=12)\n number = (\n Session.query(Workflow)\n .filter(Workflow.status == RunStatus.running)\n .filter(Workflow.run_started_at <= inactivity_threshold)\n .filter(Workflow.updated <= inactivity_threshold)\n .count()\n )\n\n return number\n\n def stuck_in_pending_workflows(self):\n \"\"\"Get the number of stuck pending workflows.\"\"\"\n inactivity_threshold = datetime.now() - timedelta(minutes=20)\n number = (\n Session.query(Workflow)\n .filter(Workflow.status == RunStatus.pending)\n .filter(Workflow.updated <= inactivity_threshold)\n .count()\n )\n\n return number\n\n def git_workflows(self):\n \"\"\"Get the number of Git based workflows.\"\"\"\n number = Session.query(Workflow).filter(Workflow.git_repo != \"\").count()\n\n return number\n\n def get_status(self):\n \"\"\"Get status summary for REANA workflows.\"\"\"\n return {\n \"running\": self.get_workflows_by_status(RunStatus.running),\n \"finished\": self.get_workflows_by_status(RunStatus.finished),\n \"stuck in running\": self.stuck_in_running_workflows(),\n \"stuck in pending\": self.stuck_in_pending_workflows(),\n \"queued\": self.get_workflows_by_status(RunStatus.queued),\n \"restarts\": self.restarted_workflows(),\n \"git_source\": self.git_workflows(),\n }\n\n\nclass QuotaUsageStatus(REANAStatus):\n \"\"\"Class to retrieve statistics related to the current REANA users quota usage.\"\"\"\n\n def __init__(self, from_=None, until=None, user=None):\n \"\"\"Initialise QuotaUsageStatus class.\n\n :param from_: From which moment in time to collect information. Not\n implemented yet.\n :param until: Until which moment in time to collect information. Not\n implemented yet.\n :param user: A REANA-DB user model.\n :type from_: datetime\n :type until: datetime\n :type user: reana_db.models.User\n \"\"\"\n super().__init__(from_=from_, until=until, user=user)\n\n def format_user_data(self, users):\n \"\"\"Format user data with human readable units.\"\"\"\n return [\n {\n \"email\": user.user.email,\n \"used\": ResourceUnit.human_readable_unit(\n user.resource.unit, user.quota_used\n ),\n \"limit\": ResourceUnit.human_readable_unit(\n user.resource.unit, user.quota_limit\n ),\n \"percentage\": get_usage_percentage(user.quota_used, user.quota_limit),\n }\n for user in users\n ]\n\n def get_top_five_percentage(self, resource_type):\n \"\"\"Get the top five users with highest quota usage percentage.\"\"\"\n users = (\n Session.query(UserResource)\n .join(UserResource.resource)\n .filter(Resource.type_ == resource_type)\n .filter(UserResource.quota_limit != 0)\n .order_by(desc(UserResource.quota_used * 100.0 / UserResource.quota_limit))\n .limit(5)\n )\n return self.format_user_data(users)\n\n def get_top_five(self, resource_type):\n \"\"\"Get the top five users according to quota usage.\"\"\"\n users = (\n Session.query(UserResource)\n .join(UserResource.resource)\n .filter(Resource.type_ == resource_type)\n .order_by(UserResource.quota_used.desc())\n .limit(5)\n )\n return self.format_user_data(users)\n\n def get_status(self):\n \"\"\"Get status summary for REANA system.\"\"\"\n return {\n \"top_five_disk\": self.get_top_five(ResourceType.disk),\n \"top_five_cpu\": self.get_top_five(ResourceType.cpu),\n \"top_five_disk_percentage\": self.get_top_five_percentage(ResourceType.disk),\n \"top_five_cpu_percentage\": self.get_top_five_percentage(ResourceType.cpu),\n }\n\n\nSTATUS_OBJECT_TYPES = {\n \"interactive-sessions\": InteractiveSessionsStatus,\n \"workflows\": WorkflowsStatus,\n \"users\": UsersStatus,\n \"system\": SystemStatus,\n \"storage\": StorageStatus,\n \"quota-usage\": QuotaUsageStatus,\n}\n\"\"\"High level REANA objects to extract information from.\"\"\"\n","sub_path":"reana_server/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":11842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"490618984","text":"import json\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\n\ndef index(request):\n context_dict = {'boldmessage': \"I am bold font from the context\"}\n\n return render(request, 'treePlotter/index.html', context_dict)\n\n\ndef getTree(request):\n nodes = {'children': [], 'title': 'Root', 'isFolder': True, 'hideCheckbox': True}\n nodes['children'].append({'title': 'Child 1', 'isFolder': False, 'children': []})\n nodes['children'].append({'title': 'Child 2', 'isFolder': False, 'children': []})\n\n res = json.dumps(nodes)\n\n return HttpResponse(res, content_type='application/json')\n\n\ndef getGraphData(request):\n finalResults = {'name': \"bernd\", \"position\": \"BA\"}\n\n arrayofdict = []\n for i in range(100):\n arrayofdict.append(finalResults)\n\n res = json.dumps(arrayofdict)\n\n return HttpResponse(res, content_type='application/json')\n\n\ndef getTableData(request):\n data = {\"data\": []}\n finalResults = {'name': \"bernd\", \"position\": \"BA\"}\n\n for i in range(10000):\n data[\"data\"].append(finalResults)\n\n res = json.dumps(data)\n\n return HttpResponse(res, content_type='application/json')","sub_path":"tutorialWebServer/treePlotter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"35209029","text":"#kullanıcıdan 3 sayı okuyup en büyüğünü çıktı veren algoritma\n\nsayi1 = int(input(\"sayi1 girin: \"))\nsayi2 = int(input(\"sayi2 girin: \"))\nsayi3 = int(input(\"sayi3 girin: \"))\n\nebs = sayi1\n\nif(sayi2>ebs):\n ebs = sayi2\nif(sayi3>ebs):\n ebs = sayi3\n\nprint(ebs)","sub_path":"PYTHON/DERS1-3.py","file_name":"DERS1-3.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"348621618","text":"import os.path\nimport argparse\nimport datetime\nimport requests\nimport whois\n\n\ndef load_urls4check(path):\n if not os.path.exists(path):\n return None\n with open(path) as file_handler:\n urls = []\n for line in file_handler.readlines():\n urls.append(line.rstrip())\n return urls\n\n\ndef is_server_respond_with_200(url):\n return requests.get(url).status_code == requests.codes.ok\n\n\ndef get_domain_expiration_date(domain_name):\n return whois.whois(domain_name).expiration_date\n\n\ndef get_file_name_with_urls():\n parser = argparse.ArgumentParser(description='Программа проверяет работоспособность сайта')\n parser.add_argument('file', default='urls.txt', type=str,\n help='файл, содержащий урлы сайтов для проверки')\n return parser.parse_args().file\n\n\ndef get_true_urls(urls):\n today = datetime.datetime.today()\n days_in_month = 30\n true_urls = []\n for url in urls:\n is_code_200 = is_server_respond_with_200(url)\n expiration_date = get_domain_expiration_date(url)\n days_to_expiration = (expiration_date - today).days\n if is_code_200 and days_to_expiration > days_in_month:\n true_urls.append(url)\n return true_urls\n\n\ndef print_true_urls(urls):\n for url in urls:\n print('%s в порядке!' % url)\n\n\nif __name__ == '__main__':\n path = get_file_name_with_urls()\n urls = load_urls4check(path)\n if not urls:\n print('файл %s не найден\\n' % path)\n else:\n urls = get_true_urls(urls)\n print_true_urls(urls)\n","sub_path":"check_sites_health.py","file_name":"check_sites_health.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"526235578","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files.\n\"\"\"\nimport csv\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\n\"\"\"\nTASK 1:\nHow many different telephone numbers are there in the records?\nPrint a message:\n\"There are different telephone numbers in the records.\"\n\"\"\"\ntotal_numbers = set()\n\nfor text in texts:\n total_numbers.add(text[0])\n total_numbers.add(text[1])\nfor call in calls:\n total_numbers.add(call[0])\n total_numbers.add(call[1])\n\nprint(\"There are {} different telephone numbers in the records.\".format(len(total_numbers)))\n\n# BIG O notation\n# O(n)\n","sub_path":"P0/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"366232176","text":"from base_iterator import Iterator\nimport numpy as np\nimport multiprocessing.pool\nimport matplotlib.image as mpimg\n\nclass ListItterator(Iterator):\n def __init__(self, list_, image_data_generator, target_size, batch_size=32, shuffle=True, seed=None, dtype='float32'):\n super(ListItterator, self).common_init(image_data_generator, target_size)\n self.data = list_\n \n self.dtype = dtype\n self.seed = seed\n self.shuffle = shuffle\n self.batch_size = batch_size\n self.target_size = target_size\n self.length_data = self.data[0].shape[0]\n super(ListItterator, self).__init__(self.length_data, self.batch_size, self.shuffle, self.seed)\n \n def _get_batches_of_transformed_samples(self, index_array) :\n batch_image_center = np.zeros((len(index_array),) + self.target_size,dtype=self.dtype)\n batch_speed = np.zeros((len(index_array),),dtype=self.dtype)\n batch_throttle = np.zeros((len(index_array),),dtype=self.dtype)\n batch_steering = np.zeros((len(index_array),),dtype=self.dtype)\n pool = multiprocessing.pool.ThreadPool(self.batch_size)\n all_images = [pool.apply_async(self.read_img, ('data_org/data/'+self.data[0][j],)) for i, j in enumerate(index_array)]\n for i,b in enumerate(all_images):\n batch_image_center[i] = b.get()\n for i, j in enumerate(index_array):\n batch_speed[i] = round(self.data[1][j],2)\n batch_throttle[i] = round(self.data[2][j],2)\n batch_steering[i] = round(self.data[3][j],2)\n pool.close()\n pool.join()\n return [batch_image_center, batch_speed], [batch_steering, batch_throttle]\n def read_img(self, image):\n #img = cv2.cvtColor(cv2.imread(image), cv2.COLOR_BGR2RGB)\n img =mpimg.imread(image)\n params = self.image_data_generator.get_random_transform(img.shape)\n img = self.image_data_generator.apply_transform(img, params)\n img = self.image_data_generator.standardize(img)\n return img\n \n def next(self):\n \"\"\"For python 2.x.\n\n # Returns\n The next batch.\n \"\"\"\n with self.lock:\n index_array = next(self.index_generator)\n # The transformation of images is not under thread lock\n # so it can be done in parallel\n return self._get_batches_of_transformed_samples(index_array)","sub_path":"list_iterator.py","file_name":"list_iterator.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"388216613","text":"from annsa.template_sampling import (rebin_spectrum,\n apply_LLD,\n construct_spectrum,)\nfrom numpy.testing import assert_almost_equal\nimport numpy as np\nimport pytest\n\n\n@pytest.fixture(scope=\"session\")\ndef spectrum():\n # define lamba = 1000\n # define size = 1x1024(the number of channels)\n dim = 1024\n lam = 1000\n spectrum = np.random.poisson(lam=lam, size=dim)\n return spectrum\n\n\n# rebinning unit test\ndef test_rebinning_size(spectrum):\n output_len = 512\n spectrum_rebinned = rebin_spectrum(spectrum,\n output_len=output_len)\n assert(len(spectrum_rebinned) == output_len)\n\n\n# LLD test\ndef test_lld(spectrum):\n lld = 10\n spectrum_lld = apply_LLD(spectrum, LLD=lld)\n assert(np.sum(spectrum_lld[0:lld]) == 0)\n\n\n# construct spectrum test\ndef test_construct_spectrum_test_rescale_case1(spectrum):\n \"\"\"case 1: Check if rescale returns correctly scaled template\"\"\"\n spectrum_counts = 10\n spectrum_rescaled = construct_spectrum(\n spectrum,\n spectrum_counts=spectrum_counts,)\n assert_almost_equal(np.sum(spectrum_rescaled), 10.0)\n\n\ndef test_construct_spectrum_test_rescale_case2(spectrum):\n \"\"\"case 2: Check if rescale returns values above zero\"\"\"\n spectrum_counts = 10\n spectrum_rescaled = construct_spectrum(\n spectrum,\n spectrum_counts=spectrum_counts,)\n assert(np.sum(spectrum_rescaled < 0) == 0)\n","sub_path":"annsa/tests/test_templatesampling.py","file_name":"test_templatesampling.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"363053751","text":"import time\nimport h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport VAE2\nimport keras\nfrom keras.models import Model, load_model # basic class for specifying and training a neural network\nfrom keras.layers import Input, Convolution2D, MaxPooling2D, Dense, Dropout, Flatten, TimeDistributed, LSTM\nfrom keras.utils import np_utils # utilities for one-hot encoding of ground truth values\nfrom keras.callbacks import ModelCheckpoint, CSVLogger, ReduceLROnPlateau, EarlyStopping\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2,l1\nfrom keras.optimizers import RMSprop\nfrom keras.models import Sequential, model_from_json, load_model\nfrom keras.layers.convolutional import Conv1D,MaxPooling1D,AveragePooling1D\nfrom keras.layers.normalization import BatchNormalization\n\n\nlatentDimensionVAE = 1024 # 128\nnoEpochsVAE = 1\nnoIter = 100\npModel = \"weights_noVAE.{epoch:02d}-{val_acc:.2f}-{val_loss:.2f}.hdf5.h5\"\npData = \"train_SEP.h5\"\nbatchSz = 10000\nlr = 0.0001\nnoEpochs = 1000\n\nnb_filter = 32\nfilter_length = 4\nwindow = 60\n\ndef buildModel():\n model = Sequential()\n model.add(Conv1D(nb_filter=nb_filter,\n filter_length=filter_length,\n border_mode=\"valid\",\n activation=\"relu\", \n input_shape=(latentDimensionVAE,1),))\n model.add(Conv1D(nb_filter=nb_filter,\n filter_length=4,\n border_mode=\"valid\",\n activation=\"relu\", ))\n model.add(MaxPooling1D(pool_size=8))\n model.add(BatchNormalization())\n model.add(Conv1D(nb_filter=nb_filter,\n filter_length=4,\n border_mode=\"valid\",\n activation=\"relu\", ))\n model.add(Conv1D(nb_filter=nb_filter,\n filter_length=4,\n border_mode=\"valid\",\n activation=\"relu\", ))\n model.add(MaxPooling1D(pool_size=8))\n model.add(BatchNormalization())\n# model.add(Conv1D(nb_filter=16,\n# filter_length=nb_filter,\n# border_mode=\"valid\",\n# activation=\"relu\", ))\n# model.add(MaxPooling1D(pool_size=2)) \n# model.add(LSTM(32, return_sequences=True,\n# activation='relu', recurrent_activation='hard_sigmoid',\n# dropout=0.2,recurrent_dropout=0.2)) # 100 num of LSTM units\n# model.add(LSTM(32, return_sequences=True,\n# activation='relu', recurrent_activation='hard_sigmoid',\n# dropout=0.2,recurrent_dropout=0.2))\n# model.add(LSTM(128, return_sequences=True,\n# activation='relu', recurrent_activation='hard_sigmoid',\n# dropout=0.2,recurrent_dropout=0.2))\n# model.add(LSTM(128, return_sequences=True,\n# activation='relu', recurrent_activation='hard_sigmoid',\n# dropout=0.2,recurrent_dropout=0.2))\n# model.add(LSTM(128, return_sequences=True,\n# activation='relu', recurrent_activation='hard_sigmoid',\n# dropout=0.2,recurrent_dropout=0.2))\n# model.add(Flatten())\n# model.add((Dense(100, activation='relu')))\n# model.add((Dense(100, activation='relu')))\n# model.add(Flatten())\n model.add(Conv1D(nb_filter=1,filter_length=1,activation=\"sigmoid\"))\n model.add(AveragePooling1D(pool_size=15)) \n# model.add(Dense(1)) \n model.add(Flatten())\n optimizer = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n \n model.compile(optimizer=optimizer, metrics=['accuracy'],\n loss='binary_crossentropy' )\n model.summary()\n return model \n\n#def train():\nif __name__ == '__main__':\n print('*** PROCESSING ' + pData)\n f = h5py.File(pData, \"r\")\n ## TRAINING\n # data\n train_pos = np.array(f[\"train_positive\"].value)\n train_neg = np.array(f[\"train_negative\"].value)\n train = np.hstack((train_pos, train_neg)).transpose() / 36\n noPosSamples = train_pos.shape[1]\n noNegSamples = train_neg.shape[1]\n # labels \n train_labels_pos = 0 * np.ones(noPosSamples)\n train_labels_neg = np.ones(noNegSamples)\n train_labels = np.hstack((train_labels_pos, train_labels_neg))\n # tau \n train_tau_pos = np.array(f[\"tau_positive\"].value)\n train_tau_neg = np.array(f[\"tau_negative\"].value)\n train_tau = np.max(np.hstack((train_tau_pos, train_tau_neg)), axis=0)\n \n ## TEST\n test_pos = np.array(f[\"test_positive\"].value)\n test_neg = np.array(f[\"test_negative\"].value)\n test = np.hstack((test_pos, test_neg)).transpose() / 36\n noPosTestSamples = test_pos.shape[1]\n noNegTestSamples = test_neg.shape[1]\n # labels \n test_labels_pos = 0 * np.ones(noPosTestSamples)\n test_labels_neg = np.ones(noNegTestSamples)\n test_labels = np.hstack((test_labels_pos, test_labels_neg))\n # tau \n test_tau_pos = np.array(f[\"tau_tst_positive\"].value)\n test_tau_neg = np.array(f[\"tau_tst_negative\"].value)\n test_tau = np.max(np.hstack((test_tau_pos, test_tau_neg)), axis=0) \n \n f.close()\n \n print(str(train.shape))\n train = train - np.mean(train)\n test = test - np.mean(test) \n #vae, encoder = VAE2.train(train, noEpochsVAE, latentDimensionVAE)\n #encoder.save(\"vae.h5\")\n #train = encoder.predict(train)\n #test = encoder.predict(test)\n \n train = train[..., np.newaxis]\n test = test[..., np.newaxis]\n train_labels = train_labels[..., np.newaxis]\n test_labels = test_labels[..., np.newaxis]\n print(\"Shape: \" + str(train_labels.shape)) \n model = buildModel()\n \n checkpoint = ModelCheckpoint(pModel, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n histLogger = CSVLogger(\"epochLog.csv\", separator=',', append=False)\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', patience=50, cooldown=0, verbose=1)\n earlyStop = EarlyStopping(monitor='val_loss', patience=20, verbose=0),\n callbacks_list = [checkpoint, reduce_lr, histLogger]\n model.fit(train, train_labels, batch_size=batchSz, epochs=noEpochs,\n validation_data=(test, test_labels), verbose=1, callbacks=callbacks_list)\n score = model.evaluate(test, test_labels, verbose=0)\n model.save(\"sep_binaryClassifier_1000_100.h5\")\n print('Test score:', score[0])\n print('Test accuracy:', score[1])\n","sub_path":"FunctionalImaging/TissueSegmentation.py","file_name":"TissueSegmentation.py","file_ext":"py","file_size_in_byte":6185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"215305519","text":"import scrabblerow as sr\r\nfrom random import Random\r\n\r\nversion = 'August 22, 2020'\r\n\r\n# Separator character denoting a blank space.\r\n\r\nsep = '-'\r\n\r\n# Seed for the random number generator that produces the patterns.\r\nseed = 4444\r\n\r\n# Length of the random patterns.\r\n\r\npatlen = 40\r\n\r\n# Minimum and maximum length of words accepted in solutions.\r\n\r\nminlen, maxlen = 4, 30\r\n\r\n# How many rounds to play this game.\r\n\r\nrounds = 10\r\n\r\n# Maximum possible consecutive run of blanks in the pattern.\r\n\r\nmb = 5\r\n\r\n# Percentage probability of the current run of blanks to continue.\r\n\r\nbp = 30\r\n\r\n# Scrabble letter values in the standard American English version.\r\n\r\nletter_values = {\r\n 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2,\r\n 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1,\r\n 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1,\r\n 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10\r\n }\r\n\r\n# Dictionary used to count the frequency of each letter.\r\n\r\nletter_counts = {c: 0 for c in letter_values}\r\n\r\n\r\n# Word scoring function for scrabble.\r\n\r\ndef scrabble_value(word):\r\n if minlen <= len(word) <= maxlen:\r\n return sum(letter_values.get(c, 0) for c in word)\r\n else:\r\n\r\n return 0\r\n\r\n\r\ndef length_squared(word):\r\n if minlen <= len(word) <= maxlen:\r\n return len(word) ** 2\r\n else:\r\n return 0\r\n\r\n\r\n# Create a random pattern of the given length.\r\n\r\ndef create_pattern(n, rng):\r\n prev, result, blanks = '', '', 0\r\n letters = \"\".join(sorted([c for c in letter_counts]))\r\n letter_freqs = [letter_counts[c] for c in letters]\r\n for i in range(n):\r\n if blanks < mb and (prev != sep or rng.randint(0, 99) < bp):\r\n prev = sep\r\n blanks += 1\r\n else:\r\n prev = rng.choices(letters, letter_freqs, k=1)[0]\r\n blanks = 0\r\n result += prev\r\n return result\r\n\r\n\r\ndef score_answer(result, pattern, scoring_f):\r\n curr, score = '', 0\r\n for (pos, (c1, c2)) in enumerate(zip(result + sep, pattern + sep)):\r\n if c2 != sep and c1 != c2:\r\n print(f\"\\nPATTERN MISMATCH AT POSITION {pos}!!!\")\r\n return 0\r\n if c1 == sep:\r\n if curr in wordset:\r\n score += scoring_f(curr)\r\n elif len(curr) > 1:\r\n print(f\"\\nUNKNOWN WORD {curr} AT POSITION {pos}!!!\")\r\n return 0\r\n curr = ''\r\n else:\r\n curr += c1\r\n return score\r\n\r\n\r\ndef play_one_round(pattern, scoring_f):\r\n score = 0\r\n print(f\"\\nPattern: {pattern}\")\r\n try:\r\n result = sr.fill_words(pattern, words, scoring_f, minlen, maxlen)\r\n except Exception as e:\r\n print(f\"CRASH!!! {e}\")\r\n return 0\r\n print(f\"Result : {result} \", end='')\r\n if len(result) == len(pattern):\r\n score += score_answer(result, pattern, scoring_f)\r\n else:\r\n print(f\"\\nRESULT AND PATTERN LENGTHS DIFFERENT!!!\")\r\n print(f\"({score})\")\r\n return score\r\n\r\n\r\ndef play():\r\n print(f\"Scrabblerun tester by Ilkka Kokkarinen, {version}.\")\r\n print(f\"Settings seed={seed}, patlen={patlen}, rounds={rounds}.\")\r\n\r\n def scoring_f(w):\r\n return length_squared(w) + scrabble_value(w)\r\n\r\n testcases = [] # Fill in your testcase strings inside this list.\r\n for pattern in testcases:\r\n play_one_round(pattern, scoring_f)\r\n\r\n total, rng = 0, Random(seed)\r\n for r in range(rounds):\r\n pattern = create_pattern(patlen, rng)\r\n total += play_one_round(pattern, scoring_f)\r\n print(f\"{total} {sr.author()} {sr.student_id()}\")\r\n\r\n\r\nwith open('words_sorted.txt', 'r', encoding='utf-8') as f:\r\n words = [x.strip() for x in f]\r\n words = [x for x in words if minlen <= len(x) <= maxlen]\r\n wordset = set(words)\r\n for word in words:\r\n for c in word:\r\n letter_counts[c] += 1\r\n\r\nif __name__ == '__main__':\r\n play()","sub_path":"scrabblerun.py","file_name":"scrabblerun.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"250610584","text":"import json, os, urllib, re, nltk, time, signal\nfrom bs4 import BeautifulSoup\nfrom urllib import parse\n\ndirectory = \"../data/en_es/\"\n\nresults = {}\nresults[\"dictionary\"] = {}\nresults[\"num_documents\"] = 0\nresults[\"completed\"] = []\ndictionary = results[\"dictionary\"]\nnum_documents = results[\"num_documents\"]\ncompleted = results[\"completed\"]\n\ndef handler(signum, frame):\n print('Signal handler called with signal', signum)\n raise OSError(\"Couldn't open device!\")\n\n\ndef urlEncodeNonAscii(b):\n return re.sub('[\\x80-\\xFF]', lambda c: '%%%02x' % ord(c.group(0)), b.decode('utf-8'))\n\ndef iriToUri(iri):\n parts= parse.urlparse(iri)\n return parse.urlunparse([urlEncodeNonAscii(part.encode('utf-8')) for part in parts])\n\ndef getArticleContents(title):\n url = u'http://es.wikipedia.org/wiki/' + title\n url = iriToUri(url)\n print(\" # Trying URL: \", url, \"#\")\n while True:\n try:\n signal.signal(signal.SIGALRM, handler)\n signal.alarm(10)\n html = urllib.request.urlopen(url).read().decode('utf8')\n signal.alarm(0)\n break\n except urllib.error.HTTPError:\n return\n except UnicodeEncodeError:\n return\n except urllib.error.URLError:\n print(\"Internet disconnected. Sleeping 60 seconds.\")\n time.sleep(60)\n pass\n soup = BeautifulSoup(html, \"html.parser\")\n content = soup.find(id='mw-content-text').find_all('p')\n result = \"\"\n for p in content:\n result += (p.getText())\n return result\n\ndef processText(text):\n tokens = nltk.word_tokenize(text)\n tokens = [w.lower() for w in tokens if w.lower() and w.isalpha()]\n fdist = nltk.FreqDist(tokens)\n for word in fdist:\n try:\n dictionary[word]['occurances'] += fdist[word]\n dictionary[word]['documents'] += 1\n except KeyError:\n dictionary[word] = {}\n dictionary[word]['occurances'] = fdist[word]\n dictionary[word]['documents'] = 1\n\nwith open('palabras.json', 'r') as f:\n try:\n results = json.load(f)\n dictionary = results[\"dictionary\"]\n num_documents = results[\"num_documents\"]\n completed = results[\"completed\"]\n print(\"Successfully loaded Palabras.json\")\n except:\n print(\"Failing to load palabras\")\n pass\n\nprint(\"Already completed: \", completed)\n\nfor filename in os.listdir(directory):\n if filename.endswith(\".json\") and filename not in completed:\n path = directory + filename\n with open(path) as article_file:\n articles = json.load(article_file) \n for en in articles:\n title = articles[en]\n title = title.replace(\"\\\\'\", \"'\")\n contents = getArticleContents(title)\n if contents:\n print(\" ## Contents found: \", title, \"##\")\n processText(contents)\n print(\" ## Text Processed: \", title, \"##\")\n num_documents += 1\n print(\" ### Article complete: \", title, \"###\")\n print(\" #### File complete: \", filename, \"####\")\n completed.append(filename)\n\n # Write our newest results to the file and continue.\n with open('palabras.json', 'w') as f:\n json.dump(results, f)\n print(\"##### Dumping to json #####\")\n\n","sub_path":"server/scripts/process_eswiki.py","file_name":"process_eswiki.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"118556970","text":"# from bot import *\nfrom controller.states.finish_state import FinishState\nimport requests\nfrom utils.config import *\nfrom utils.constants import GUESS_STATE, BAD_GUESS , GOOD_GUESS\nfrom model.bot_responses_model import return_user_message\n\nclass GuessState():\n\n def __init__(self, artist_name, item_number , channel_id ):\n\n self.artist_name = artist_name\n self.item_number = item_number\n self.channel_id = channel_id\n \n\n def handle_message(self, msg, bot):\n\n res = self.check_user_guess(msg.get_text())\n if res:\n message = return_user_message(GUESS_STATE, GOOD_GUESS)\n bot.handle_state(FinishState())\n else:\n message = return_user_message(GUESS_STATE, BAD_GUESS)\n \n return message\n\n def check_user_guess(self, user_guess):\n\n\n request_url = BASE_YOUTUBE_API_URL+'search?key={}&channelId={}&part=snippet,id&order=date&maxResults=20'.format(API_KEY,self.channel_id)\n\n result_data = requests.get(request_url).json()\n\n if user_guess == \"\":\n return False\n\n user_guess_arr = user_guess.lower().split(\" \")\n audio_title_arr = result_data['items'][self.item_number]['snippet']['title'].lower().split(\" \")\n artist_name_arr = self.artist_name.lower().split(\" \")\n\n\n for word in user_guess_arr:\n if word not in audio_title_arr:\n return False\n if word in artist_name_arr:\n return False\n\n return True\n\n\n","sub_path":"controller/states/guess_state.py","file_name":"guess_state.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"226231215","text":"import os, time, pickle, argparse, networks, utils\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nimport torchvision.transforms as transforms\nfrom PIL import Image\nimport torchvision.utils as vutils\nimport numpy as np\nfrom torchvision import transforms\nfrom utils import ToRGB, RatioedResize, Zero, RGBToBGR\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--name', required=False, default='project_name', help='')\nparser.add_argument('--src_data', required=False, default='src_data_path', help='sec data path')\nparser.add_argument('--tgt_data', required=False, default='tgt_data_path', help='tgt data path')\nparser.add_argument('--vgg_model', required=False, default='pre_trained_VGG19_model_path/vgg19.pth', help='pre-trained VGG19 model path')\nparser.add_argument('--in_ngc', type=int, default=3, help='input channel for generator')\nparser.add_argument('--out_ngc', type=int, default=3, help='output channel for generator')\nparser.add_argument('--in_ndc', type=int, default=3, help='input channel for discriminator')\nparser.add_argument('--out_ndc', type=int, default=1, help='output channel for discriminator')\nparser.add_argument('--batch_size', type=int, default=8, help='batch size')\nparser.add_argument('--ngf', type=int, default=64)\nparser.add_argument('--ndf', type=int, default=32)\nparser.add_argument('--nb', type=int, default=8, help='the number of resnet block layer for generator')\nparser.add_argument('--input_size', type=int, default=256, help='input size')\nparser.add_argument('--train_epoch', type=int, default=100)\nparser.add_argument('--pre_train_epoch', type=int, default=10)\nparser.add_argument('--lrD', type=float, default=0.0002, help='learning rate, default=0.0002')\nparser.add_argument('--lrG', type=float, default=0.0002, help='learning rate, default=0.0002')\nparser.add_argument('--con_lambda', type=float, default=10, help='lambda for content loss')\nparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for Adam optimizer')\nparser.add_argument('--beta2', type=float, default=0.999, help='beta2 for Adam optimizer')\nparser.add_argument('--pre_trained_model', required=True, default='pre_trained_model', help='pre_trained cartoongan model path')\nparser.add_argument('--image_dir', required=True, default='image_dir', help='test image path')\nparser.add_argument('--output_image_dir', required=True, default='output_image_dir', help='output test image path')\nargs = parser.parse_args()\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nif torch.backends.cudnn.enabled:\n torch.backends.cudnn.benchmark = True\n\nG = networks.Transformer()\nif torch.cuda.is_available():\n G.load_state_dict(torch.load(args.pre_trained_model))\nelse:\n # cpu mode\n G.load_state_dict(torch.load(args.pre_trained_model, map_location=lambda storage, loc: storage))\n\nG.to(device)\nG.eval()\n\n\nsrc_transform = transforms.Compose([\n ToRGB(),\n RatioedResize(args.input_size),\n transforms.ToTensor(),\n RGBToBGR(),\n Zero(),\n])\n# utils.data_load(os.path.join('data', args.src_data), 'test', src_transform, 1, shuffle=True, drop_last=True)\nimage_src = utils.data_load(os.path.join(args.image_dir), 'test', src_transform, 1, shuffle=True, drop_last=True)\n\nwith torch.no_grad():\n G.eval()\n for n, (x, _) in enumerate(image_src):\n x = x.to(device)\n G_recon = G(x)\n result = G_recon[0]\n path = os.path.join(args.output_image_dir, str(n + 1) + '.png')\n\t\t\t\t# BGR -> RGB\n result = result[[2, 1, 0], :, :]\n\t\t\t\t# deprocess, (0, 1)\n result = result.data.cpu().float() * 0.5 + 0.5\n vutils.save_image(result, path)\n\n'''\nvalid_ext = ['.jpg', '.png']\n\nfor files in os.listdir(args.image_dir):\n\text = os.path.splitext(files)[1]\n\tif ext not in valid_ext:\n\t\tcontinue\n\t# load image\n\tinput_image = Image.open(os.path.join(args.image_dir, files)).convert(\"RGB\")\n\t# resize image, keep aspect ratio\n\th = input_image.size[0]\n\tw = input_image.size[1]\n\tratio = h *1.0 / w\n\tif ratio > 1:\n\t\th = args.input_size\n\t\tw = int(h*1.0/ratio)\n\telse:\n\t\tw = args.input_size\n\t\th = int(w * ratio)\n\tinput_image = input_image.resize((h, w), Image.BICUBIC)\n\tinput_image = np.asarray(input_image)\n\t# RGB -> BGR\n\tinput_image = input_image[:, :, [2, 1, 0]]\n\tinput_image = transforms.ToTensor()(input_image).unsqueeze(0)\n\t# preprocess, (-1, 1)\n\tinput_image = -1 + 2 * input_image \n\tif torch.cuda.is_available():\n\t\tinput_image = Variable(input_image, volatile=True).cuda()\n\telse:\n\t\tinput_image = Variable(input_image, volatile=True).float()\n\t# forward\n\toutput_image = G(input_image)\n\toutput_image = output_image[0]\n\t# BGR -> RGB\n\toutput_image = output_image[[2, 1, 0], :, :]\n\t# deprocess, (0, 1)\n\toutput_image = output_image.data.cpu().float() * 0.5 + 0.5\n\t# save\n\tvutils.save_image(output_image, os.path.join(args.output_image_dir, files[:-4] + '.jpg'))\n\nprint('Done!')\n'''\n\n","sub_path":"baseline/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"615718568","text":"# CONSUMPTIE AUTOMAAT\n\nproducten = {'Mars': 1.20,\n 'Snickers': 1.25,\n 'Twix': 0.75,\n 'KitKat': 1.00}\ngeselecteerd_product = None\ngeselecteerd_product_prijs = None\ninvoer = 0\n\n\ndef vraag_product():\n # Selecteerd de producten en slaat het product en de prijs op in variabelen.\n product = input('Welk product wilt u? ').lower()\n for key, value in producten.items():\n if key.lower() == product:\n global geselecteerd_product, geselecteerd_product_prijs\n geselecteerd_product = key\n geselecteerd_product_prijs = value\n\n\ndef geef_wisselgeld(geld_input):\n # Returneerd het wisselgeld van de geselecteerde product prijs en het meegegeven bedrag.\n return geld_input - geselecteerd_product_prijs\n\n\ndef vraag_prijs():\n # Vraagt de gebruiker om geld in te werpen en checkt of het te weinig, teveel of precies goed is.\n print('Uw product kost:', geselecteerd_product_prijs)\n geld = float(input('Werp geld in alstublieft. '))\n if geld > geselecteerd_product_prijs:\n print('Uw wisselgeld is:', geef_wisselgeld(geld), 'Bedankt voor uw aankoop.')\n elif geld < geselecteerd_product_prijs:\n print('Te weinig geld ingeworpen, probeer opnieuw.')\n start_machine()\n else:\n print('Bedankt voor uw aankoop:', geselecteerd_product)\n\n\ndef print_producten():\n # Print de producten uit de producten dictionairy\n for key, value in producten.items():\n print(key)\n\n\ndef start_machine():\n # Start de machine en roept alle functies op.\n print('Welkom bij het NS Consumptie Automaat, Kies een product')\n print_producten()\n vraag_product()\n vraag_prijs()\n\n\nstart_machine()\n","sub_path":"week_3/weekopdracht/3.4.py","file_name":"3.4.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"19311265","text":"import os, sys, site\n\nsite.addsitedir('/home/coordt/.virtualenvs/djangopatterns/lib/python2.6/site-packages')\n\nPROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\nsys.path.insert(0, os.path.join(PROJECT_ROOT,\"apps\"))\nsys.path.insert(0, os.path.join(PROJECT_ROOT,\"lib\"))\nsys.path.insert(0, PROJECT_ROOT)\n\nsys.stdout = sys.stderr\n\nif PROJECT_ROOT not in sys.path:\n sys.path.append(PROJECT_ROOT)\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\n\nimport django.core.handlers.wsgi\n\napplication = django.core.handlers.wsgi.WSGIHandler()","sub_path":"conf/djangopatterns.wsgi","file_name":"djangopatterns.wsgi","file_ext":"wsgi","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"167063608","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.sparse.construct import rand, random\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom config import SEED\n\n\nclass DataLoader:\n \"\"\"A class used to load training data\n\n Args:\n filePath (str): A relative path from main to the data file.\n\n Attributes:\n X (pandas.DataFrame): A dataframe of features\n y (pandas.DataFrame): A dataframe of targets\n\n \"\"\"\n\n def __init__(self, filePath: str):\n print('[DataLoader] Loading data')\n df = pd.read_csv(filePath)\n\n # Set y as the target and select features\n y = df['TARGET']\n X = df[[\n 'MONTH',\n 'DAY_OF_MONTH',\n 'WEEKDAY',\n 'HOUR',\n 'WIND_SPEED',\n 'WIND_DIRECTION',\n 'AIR_TEMPERATURE',\n 'PRECIPITATION',\n 'VISIBILITY'\n ]]\n\n # Parse string features to numeric values\n # using a labelencoder and inject them as features\n le = LabelEncoder()\n le.fit(df['AIRLINE_IATA'].values)\n X.insert(2, 'AIRLINE_IATA', le.transform(\n df['AIRLINE_IATA'].values), True)\n\n le = LabelEncoder()\n le.fit(df['GATE_STAND'].astype(str).values)\n X.insert(2, 'GATE_STAND', le.transform(\n df['GATE_STAND'].astype(str).values), True)\n\n le = LabelEncoder()\n le.fit(df['INT_DOM_SCHENGEN'].values)\n X.insert(2, 'INT_DOM_SCHENGEN', le.transform(\n df['INT_DOM_SCHENGEN'].values), True)\n\n le = LabelEncoder()\n le.fit(df['DEP_ARR'].values)\n X.insert(2, 'DEP_ARR', le.transform(df['DEP_ARR'].values), True)\n\n le = LabelEncoder()\n le.fit(df['TO_FROM'].values)\n X.insert(2, 'TO_FROM', le.transform(df['TO_FROM'].values), True)\n\n le = LabelEncoder()\n le.fit(df['FLIGHT_ID'].values)\n X.insert(2, 'FLIGHT_ID', le.transform(df['FLIGHT_ID'].values), True)\n\n self.X = X\n self.y = y\n\n del df\n\n def extract(self, count: int = None):\n \"\"\"Extracts the data seperated as features and targets\n\n Args:\n count (int): The number of random samples to be returned. count=None returns all.\n\n Returns:\n bool: self.X and self.y as numpy arrays where X[i] belongs to y[i]\n\n Examples:\n To extract 20 random samples:\n >>> X, y = dataloader.extract(200)\n\n To extract all samples:\n >>> X, y = dataloader.extract()\n\n \"\"\"\n\n X, y = self.X, self.y\n\n if not count == None:\n X = X.sample(count, random_state=SEED)\n y = y.sample(count, random_state=SEED)\n\n return X.values, y.values\n\n def histogram(self):\n \"\"\"Shows a histogram plot of loaded features\"\"\"\n\n self.X.hist()\n plt.show()\n","sub_path":"src/pipeline/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"473600700","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sn\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport matplotlib as mpl\n\ndef plot2D(df, sample, sgn,x_axis_value, y_axis_value, range_x, range_y, pdf_key):\n \"\"\"\n\n Plots 2-D histogram.\n\n x_axis_value: e.g. 'mass'\n y_axis_value: e.g. 'distance'\n range_x: e.g. [1, 1.177]\n range_y: e.g [0, 100]\n folder: e.g. 'folder'\n\n \"\"\"\n\n fig, axs = plt.subplots(figsize=(15, 10))\n cax = plt.hist2d(df[x_axis_value],df[y_axis_value],range=[range_x, range_y], bins=100,\n norm=mpl.colors.LogNorm(), cmap=plt.cm.viridis)\n\n\n if x_axis_value=='mass':\n unit = r' $, \\frac{GeV}{c^2}$ '\n plt.vlines(x=1.115683,ymin=range_y[0],ymax=range_y[1], color='r', linestyle='-')\n\n if x_axis_value=='pT':\n unit = r' $, \\frac{GeV}{c}$'\n\n\n if sgn==1:\n plt.title('Signal candidates ' + sample, fontsize = 25)\n\n if sgn==0:\n plt.title('Background candidates' + sample, fontsize = 25)\n\n\n plt.xlabel(x_axis_value+unit, fontsize=25)\n plt.ylabel(y_axis_value, fontsize=25)\n\n\n\n mpl.pyplot.colorbar()\n\n plt.legend(shadow=True,title =str(len(df))+ \" samples\")\n\n fig.tight_layout()\n plt.savefig(pdf_key,format='pdf')\n","sub_path":"distributions/twoD_mass_pT.py","file_name":"twoD_mass_pT.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"187759236","text":"#!/usr/bin/env python3\n\"\"\"Number affiliations for each author, given an author list with affiliations\nfor each author.\"\"\"\n\nimport argparse\nfrom collections import OrderedDict\n\n__author__ = 'Hayden Metsky '\n\n\ndef read_authors(fn):\n \"\"\"Read list of authors and shortcuts of their affiliations.\n\n Args:\n fn: path to file with two columns in which each line corresponds\n to an author; column 1 gives the author's name and column\n 2 gives a comma-separated list of shorthand names of their\n affiliations\n\n Returns:\n ordered dict {author name: list of shorthands for affiliations},\n where the order of authors is the same as in the given file\n \"\"\"\n authors = OrderedDict()\n with open(fn) as f:\n for line in f:\n author, affiliations = line.strip().split('\\t')\n affiliations = affiliations.split(',')\n authors[author] = affiliations\n return authors\n\n\ndef read_affiliations(fn):\n \"\"\"Read list of full names of affiliations.\n\n Args:\n fn: path to file with two columns in which each line corresponds\n to an affiliation; column 1 gives a shorthand name for the\n affiliation (assigned to authors) and column 2 gives the\n full name of the affiliation\n\n Returns:\n dict {shorthand for affiliation: full name of affiliation}\n \"\"\"\n affiliations = {}\n with open(fn) as f:\n for line in f:\n shorthand, fullname = line.rstrip().split('\\t')\n affiliations[shorthand] = fullname\n return affiliations\n\n\ndef main(args):\n # Read input\n authors = read_authors(args.authors)\n affiliations = read_affiliations(args.affiliations)\n\n # Verify that each author's affiliation has a name\n for author in authors:\n for affiliation in authors[author]:\n if affiliation not in affiliations:\n raise Exception((\"Author %s has affiliation %s but the \"\n \"name of that affiliation was not given\") % (author,\n affiliation))\n\n # Order affiliations according to the author order\n affiliations_number = {}\n curr_num = 1\n for author in authors:\n for affiliation in authors[author]:\n if affiliation not in affiliations_number:\n affiliations_number[affiliation] = curr_num\n curr_num += 1\n affiliations_ordered = sorted(list(affiliations.keys()),\n key=lambda x: affiliations_number[x])\n\n # Generate HTML and LaTeX of authors with their affiliations numbered\n author_html = ''\n author_latex = ''\n for i, author in enumerate(authors):\n numbers = [affiliations_number[x] for x in authors[author]]\n numbers_str = ','.join([str(x) for x in sorted(numbers)])\n if i > 0:\n author_html += ', '\n author_latex += ',\\n'\n\n author_html += author + '' + numbers_str + ''\n\n # For LaTeX, put an mbox around the last name and another around\n # everything before the last name, so that neither of these two\n # pieces are split with a line break\n author_split = author.split(' ')\n author_mbox = ('\\mbox{' + ' '.join(author_split[:-1]) + '} ' +\n '\\mbox{' + author_split[-1] + '}')\n author_latex += author_mbox + '$^{' + numbers_str + '}$'\n author_latex += '\\n'\n\n # Generate HTML and LaTeX of affiliations with their full names\n affiliations_html = ''\n affiliations_latex = ''\n for i, affiliation in enumerate(affiliations_ordered):\n number = str(affiliations_number[affiliation])\n fullname = affiliations[affiliation]\n if i > 0:\n affiliations_html += ' '\n\n affiliations_html += '' + number + '' + fullname + '.'\n affiliations_latex += '$^{' + number + '}$' + fullname + '.\\n'\n\n # Write HTML\n with open(args.out_html, 'w') as f:\n f.write(author_html)\n f.write('

')\n f.write(affiliations_html)\n\n # Write LaTeX if desired\n if args.out_latex:\n with open(args.out_latex, 'w') as f:\n f.write('%%%%%%%%%%%%%%%%%%%%%\\n')\n f.write('%% LIST OF AUTHORS %%\\n')\n f.write('%%%%%%%%%%%%%%%%%%%%%\\n')\n f.write(author_latex)\n f.write('%%%%%%%%%%%%%%%%%%%%%\\n')\n f.write('\\n\\n')\n f.write('%%%%%%%%%%%%%%%%%%%%%%%%%%\\n')\n f.write('%% LIST OF AFFILIATIONS %%\\n')\n f.write('%%%%%%%%%%%%%%%%%%%%%%%%%%\\n')\n f.write(affiliations_latex)\n f.write('%%%%%%%%%%%%%%%%%%%%%%%%%%\\n')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('authors',\n help=(\"Path to file in which each line corresponds to an author \"\n \"(ordered as desired) and there are 2 columns: column 1 \"\n \"gives the full name of the author and column 2 gives a \"\n \"shorthand for the author's affiliation\"))\n parser.add_argument('affiliations',\n help=(\"Path to file in which each line corresponds to an affiliation \"\n \"and there are 2 columns: column 1 gives a shorthand for an \"\n \"affiliation and column 2 gives the full name of the \"\n \"affiliation\"))\n parser.add_argument('out_html',\n help=(\"Path to output HTML file that gives an author list with \"\n \"numbered affiliations\"))\n parser.add_argument('--out-latex',\n help=(\"Path to output tex file that gives an author list with \"\n \"numbered affiliations\"))\n\n args = parser.parse_args()\n main(args)\n","sub_path":"affiliate.py","file_name":"affiliate.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"267786729","text":"#@+leo-ver=4-thin\n#@+node:amd_yen.20130429141318.2175:@shadow c2/pyqt_4.py\n#@@language python\n\n#encoding: utf-8\nfrom PyQt4.QtGui import *\nimport sys\n\n應用程式 = QApplication(sys.argv)\n\n按鈕1 = QPushButton(\"&Quit\")\n按鈕2 = QPushButton(\"&Ok\")\n按鈕3 = QPushButton(\"&Quit1\")\n按鈕4 = QPushButton(\"&Ok1\")\n# QHBoxLayout 為 Horizontal (水平)配置方塊區\n方塊區 = QHBoxLayout()\n方塊區.addWidget(按鈕1)\n方塊區.addWidget(按鈕2)\n方塊區.addWidget(按鈕3)\n方塊區.addWidget(按鈕4)\n\n組件 = QWidget()\n組件.setLayout(方塊區)\n# 其中只有按鈕1按下有反應\n按鈕1.clicked.connect(組件.close)\n組件.resize(400, 300)\n組件.setWindowTitle(\"PyQt 視窗\")\n組件.show()\n# 在 PyQt 4.5 與 Python3 環境下可以直接使用 exec() 但是也可以使用舊版的 exec_()\n應用程式.exec_()\n#@nonl\n#@-node:amd_yen.20130429141318.2175:@shadow c2/pyqt_4.py\n#@-leo\n","sub_path":"2013spring/c2/.leo_shadow/xpyqt_4.py","file_name":"xpyqt_4.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"538727767","text":"import config\nimport keyboard\n\nbot = config.bot\nversion = config.version\nbot_username = config.bot_username\n\n\ndef start(msg):\n if msg.get('text'):\n if msg['text'] == '/start' or msg['text'] == '!start' or msg['text'].split()[\n 0] == '/start@' + bot_username:\n\n if msg['chat']['type'] == 'private':\n teclado = keyboard.start_pv\n smsg = 'Olá! eu sou o EduuRobot, para descobrir mais sobre minhas funções navegue pelo teclado abaixo:'\n else:\n teclado = keyboard.start\n smsg = 'Olá! eu sou o EduuRobot, para descobrir mais sobre mim inicie uma conversa comigo.'\n\n bot.sendMessage(msg['chat']['id'], smsg,\n reply_to_message_id=msg['message_id'], reply_markup=teclado)\n return True\n\n\n elif msg.get('data'):\n\n if msg['data'] == 'tools_cmds':\n bot.editMessageText(\n (msg['message']['chat']['id'], msg['message']['message_id']),\n text='''*Ferramentas:*\n\n/clima - Exibe informações de clima.\n/coub - Pesquisa de pequenas animações.\n/echo - Repete o texto informado.\n/gif - Pesquisa de GIFs.\n/git - Envia informações de um user do GitHub.\n/html - Repete o texto informado usando HTML.\n/ip - Exibe informações sobre um IP/domínio.\n/jsondump - Envia o json da mensagem.\n/mark - Repete o texto informado usando Markdown.\n/print - Envia uma print de um site.\n/pypi - Pesquisa de módulos no PyPI.\n/r - Pesquisa de tópicos no Reddit\n/request - Faz uma requisição a um site.\n/shorten - Encurta uma URL.\n/token - Exibe informações de um token de bot.\n/tr - Traduz um texto.\n/yt - Pesquisa vídeos no YouTube.\n/ytdl - Baixa o áudio de um vídeo no YouTube.''',\n parse_mode='Markdown',\n reply_markup=keyboard.cmds_back\n )\n\n\n elif msg['data'] == 'admin_cmds':\n bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']),\n '''*Comandos administrativos:*\n\n/ban - Bane um usuário.\n/config - Envia um menu de configurações.\n/defregras - Define as regras do grupo.\n/kick - Kicka um usuário.\n/mute - Restringe um usuário.\n/pin - Fixa uma mensagem no grupo.\n/title - Define o título do grupo.\n/unban - Desbane um usuário.\n/unmute - Desrestringe um usuário.\n/unpin - Desfixa a mensagem fixada no grupo.\n/unwarn - Remove as advertências do usuário.\n/warn - Adverte um usuário.\n/welcome - Define a mensagem de welcome.''',\n parse_mode='Markdown',\n reply_markup=keyboard.cmds_back)\n\n\n elif msg['data'] == 'user_cmds':\n bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']),\n '''*Comandos para usuários normais:*\n\n/add - Envia uma sugestão para a IA do bot.\n/admins - Mostra a lista de admins do chat.\n/dados - Envia um número aleatório de 1 a 6.\n/erro - Reporta um bug ao meu desenvolvedor.\n/id - Exibe suas informações ou de um usuário.\n/ping - Responde com uma mensagem de ping.\n/regras - Exibe as regras do grupo.\n/roleta - Para jogar a Roleta Russa.''',\n parse_mode='Markdown',\n reply_markup=keyboard.cmds_back)\n\n\n elif msg['data'] == 'start_back':\n if msg['message']['chat']['type'] == 'private':\n teclado = keyboard.start_pv\n else:\n teclado = keyboard.start\n bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']),\n \"Olá! eu sou o EduuRobot, para descobrir mais sobre minhas funções clique nos botões abaixo:\",\n reply_markup=teclado)\n\n\n elif msg['data'] == 'all_cmds':\n bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']),\n 'Selecione uma categoria de comando para visualizar.\\n\\nCaso precise de ajuda com o bot ou tem alguma sugestão entre no @AmanoChat',\n reply_markup=keyboard.all_cmds)\n\n\n elif msg['data'] == 'infos':\n bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']),\n '''• EduuRobot\n\nVersion: {}\nDevelopers: Amano Team\nOwner: Edu :3\n\nPartnerships:\n » HPXList - by usernein\n\n©2018 - AmanoTeam™'''.format(version),\n parse_mode='html',\n reply_markup=keyboard.start_back,\n disable_web_page_preview=True)\n","sub_path":"plugins/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"122104771","text":"import cv2\nimport os.path\nimport numpy as np\nfrom imutils import paths\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.layers.core import Flatten, Dense\n\nimagedir = \"data\" #訓練資料\nmodelname = \"carplate_model.hdf5\" #模型名稱\ndata = [] #資料串列\nlabels = [] #標籤串列\n\n#讀取資料\nfor image_file in paths.list_images(imagedir):\n image = cv2.imread(image_file)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #轉為灰階\n label = image_file.split(os.path.sep)[-2] #擷取文字資料夾名稱\n data.append(image) #加入圖形\n labels.append(label) #加入標籤\ndata = np.array(data) #轉換為numpy array\nlabels = np.array(labels)\n\n#訓練資料佔85%\n(X_train, X_test, Y_train, Y_test) = train_test_split(data, labels, test_size=0.15, random_state=0)\n#標準化資料\nX_train_normalize=X_train.reshape(X_train.shape[0],38,18,1).astype(\"float\") / 255.0\nX_test_normalize=X_test.reshape(X_test.shape[0],38,18,1).astype(\"float\") / 255.0\n#轉換標籤為one-hot\nlb = LabelBinarizer().fit(Y_train)\nY_train_OneHot = lb.transform(Y_train)\nY_test_OneHot = lb.transform(Y_test)\n\n#建立模型\nmodel = Sequential()\n#神經網路\nmodel.add(Conv2D(20, (5, 5), padding=\"same\", input_shape=(38, 18, 1), activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Conv2D(50, (5, 5), padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(500, activation=\"relu\"))\nmodel.add(Dense(34, activation=\"softmax\")) #34類\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n#開始訓練\nmodel.fit(X_train_normalize, Y_train_OneHot, validation_split=0.2, batch_size=32, epochs=10, verbose=1)\nmodel.save(modelname) #儲存模型\n\n#準確率\nscores = model.evaluate(X_train_normalize , Y_train_OneHot)\nprint(scores[1])\nscores2 = model.evaluate(X_test_normalize , Y_test_OneHot)\nprint(scores2[1])\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"339883359","text":"from socket import *\nimport select\nimport threading\n\n\nclass Server:\n def __init__(self):\n self.serverSocket = socket(AF_INET, SOCK_STREAM)\n self.serverSocket.bind((\"\", 8899))\n self.serverSocket.listen(5)\n self.fd_name = {} # nickname map\n self.inputs = [] # listen\n self.inputs.append(self.serverSocket)\n print(\"server is running\")\n\n def new_connect(self):\n clientSocket, clientInfo = self.serverSocket.accept()\n try:\n clientSocket.send(bytes(\"welcome to chatroom,pls set up your nick name!\", encoding='utf8'))\n client_name = clientSocket.recv(1024)\n self.fd_name[clientSocket] = client_name\n self.inputs.append(clientSocket)\n print(client_name, 'enter the room')\n self.forcast(self.fd_name[clientInfo] + bytes(\"join\",encoding='utf8'), clientSocket)\n except Exception as e:\n print(e)\n\n def run(self):\n while True:\n rlist, wlist, elist = select.select(self.inputs, [], [])\n if not rlist:\n print('out')\n self.serverSocket.close()\n break\n for r in rlist:\n if r is self.serverSocket:\n self.new_connect()\n else:\n try:\n data = r.recv(1024)\n data = self.fd_name[r] + bytes(\":\",encoding='utf8') + data\n except error:\n data = self.fd_name[r] + bytes(\"leaved the room\",encoding='utf8')\n print(self.fd_name[r], 'leave the room')\n self.inputs.remove(r)\n del self.fd_name[r]\n self.forcast(data, r)\n\n def forcast(self, mess, excepts):\n for socket in self.fd_name.keys():\n if socket != excepts and socket != self.serverSocket:\n socket.send(mess)\n\n def remove(self, r, data):\n self.inputs.remove(r)\n print(data)\n self.forcast(data, r)\n\n\ndef main():\n server = Server()\n server.run()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"computer_etwork/experiment1_py/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"514791392","text":"class Movie():\n def __init__(self, movie_title, poster_image, trailer_youtube):\n '''\n This class contains the movie-relate information.\n\n Atributes:\n title (str): Name of the Movie\n poster_image_url(str): URL of the image to be displayed with each movie\n trailer_youtube_url(str): URL of the video to be played\n '''\n self.title = movie_title\n self.poster_image_url = poster_image\n self.trailer_youtube_url = trailer_youtube\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"46655665","text":"# -*- coding:utf8 -*-\n# builtin packages\nimport csv\nimport json\nimport logging\nimport os\nimport sys\nimport time\nimport traceback\nfrom builtins import Exception\n\nfrom adopt.apps.competitive.models import DiscountRule\nfrom adopt.apps.competitive.reader import DiscountRuleReader\nfrom adopt.apps.core.models import Client\nfrom django.contrib.auth import get_user_model\nfrom django.core.management.base import BaseCommand, CommandError\n\nUser = get_user_model()\n\nclass Command(BaseCommand):\n help = 'load discount map'\n\n def add_arguments(self, parser):\n parser.add_argument('client', type=str)\n parser.add_argument('path', type=str)\n\n # 必须实现的方法\n def handle(self, *args, **options):\n if options['client'] is None:\n raise CommandError(\"Argument `client` must be specified.\")\n\n if options['path'] is None:\n raise CommandError(\"Argument `path` must be specified.\")\n\n client = options['client']\n filepath = options['path']\n try:\n client = Client.objects.get(name=client)\n except:\n print('client does not exists')\n sys.exit(-1)\n\n _st = time.time()\n index = 0\n try:\n args = []\n if os.path.isfile(filepath):\n read_discount_rule(client, filepath)\n return\n\n print(time.time() - _st)\n\n except Exception:\n traceback.print_exc()\n sys.exit(1)\n\n\ndef read_discount_rule(client, file_name):\n reader = DiscountRuleReader()\n\n objs = reader.read_excel(client, file_name)\n if len(objs)>0:\n queryset = DiscountRule.objects.filter(client=client)\n queryset._raw_delete(queryset.db)\n for each in objs:\n each.save()\n","sub_path":"adopt/apps/competitive/management/commands/load_discountrule.py","file_name":"load_discountrule.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"173364028","text":"import logging\nimport setup_GCToo_logger as setup_logger\nimport pandas as pd\nimport numpy as np\nimport os.path\n\n\n__author__ = \"Lev Litichevskiy\"\n__email__ = \"lev@broadinstitute.org\"\n\n\"\"\" Writes a GCToo object to a gct file.\n\nThe main method is write. write_version_and_dims writes the first two\nlines of the gct file, assemble_full_df assembles 3 component dfs\ninto a df of the correct form for a gct file, and write_full_df writes\nthe full_df into the gct file as lines 3 to the end.\nappend_dims_and_file_extension is a utility function that can be used to\nappend the matrix dimensions and .gct extension to the output filename.\n\nExample GCT:\n#1.3\n96 36 9 15\n\n96 = number of data rows\n36 = number of data columns\n9 = number of row metadata fields (+1 for the 'id' column -- first column)\n15 = number of col metadata fields (+1 for the 'id' row -- first row)\n---------------------------------------------------\n|id| rhd | cid |\n---------------------------------------------------\n| | | |\n|c | | |\n|h | (blank) | col_metadata |\n|d | | |\n| | | |\n---------------------------------------------------\n| | | |\n|r | | |\n|i | row_metadata | data |\n|d | | |\n| | | |\n---------------------------------------------------\n\"\"\"\n\nlogger = logging.getLogger(setup_logger.LOGGER_NAME)\n\n# Only writes GCT v1.3\nVERSION = \"1.3\"\n\n\ndef write(gctoo, out_fname, data_null=\"NaN\", metadata_null=\"-666\", filler_null=\"-666\", data_float_format=None):\n \"\"\"Write a gctoo object to a gct file.\n\n Args:\n gctoo (gctoo object)\n out_fname (string): filename for output gct file\n data_null (string): how to represent missing values in the data (default = \"NaN\")\n metadata_null (string): how to represent missing values in the metadata (default = \"-666\")\n filler_null (string): what value to fill the top-left filler block with (default = \"-666\")\n data_float_format (string): how many decimal points to keep in representing data (default = None will keep all digits)\n Returns:\n nothing\n \"\"\"\n # Create handle for output file\n if not out_fname.endswith(\".gct\"):\n out_fname = out_fname + \".gct\"\n f = open(out_fname, \"wb\")\n\n # Write first two lines\n dims_ints = [gctoo.data_df.shape[0], gctoo.data_df.shape[1],\n gctoo.row_metadata_df.shape[1], gctoo.col_metadata_df.shape[1]]\n dims = [str(dim) for dim in dims_ints]\n write_version_and_dims(VERSION, dims, f)\n\n # Convert 3 component dataframes into correct form\n full_df = assemble_full_df(\n gctoo.row_metadata_df, gctoo.col_metadata_df, gctoo.data_df,\n data_null, metadata_null, filler_null)\n\n # Write remainder of gct\n write_full_df(full_df, f, data_null, data_float_format)\n f.close()\n\n logger.info(\"GCT has been written to {}\".format(out_fname))\n\n\ndef write_version_and_dims(version, dims, f):\n \"\"\"Write first two lines of gct file.\n\n Args:\n version (string): 1.3 by default\n dims (list of strings): length = 4\n f (file handle): handle of output file\n Returns:\n nothing\n \"\"\"\n f.write((\"#\" + version + \"\\n\"))\n f.write((dims[0] + \"\\t\" + dims[1] + \"\\t\" + dims[2] + \"\\t\" + dims[3] + \"\\n\"))\n\n\ndef assemble_full_df(row_metadata_df, col_metadata_df, data_df, data_null, metadata_null, filler_null):\n \"\"\"Assemble 3 component dataframes into the correct form for gct files.\n\n Args:\n row_metadata_df (pandas df)\n col_metadata_df (pandas df)\n data_df (pandas df)\n data_null (string): how to represent missing values in the data\n metadata_null (string): how to represent missing values in the metadata\n filler_null (string): what value to fill the top-left filler block with\n\n Returns:\n full_df (pandas df): shape = (n_chd + n_rid, 1 + n_rhd + n_cid),\n header will become the 3rd line of the gct file\n \"\"\"\n # Convert metadata to strings\n row_metadata_df = row_metadata_df.astype(str)\n col_metadata_df = col_metadata_df.astype(str)\n\n # Replace missing values in metadata with metadata_null\n row_metadata_df.replace(\"nan\", value=metadata_null, inplace=True)\n col_metadata_df.replace(\"nan\", value=metadata_null, inplace=True)\n\n # TOP ROW: horz concatenate \"id\", rhd, and cid\n rhd_and_cid = np.hstack((row_metadata_df.columns.values, data_df.columns.values))\n top_row = np.hstack((\"id\", rhd_and_cid))\n\n # Check that it has correct length\n assert(len(top_row) == (1 + row_metadata_df.shape[1] + data_df.shape[1]))\n\n # Create nan array to fill the blank top-left quadrant\n filler = np.full((col_metadata_df.shape[1], row_metadata_df.shape[1]),\n filler_null, dtype=\"S8\")\n\n # TOP HALF: horz concatenate chd, filler, and col_metadata, which must be transposed\n filler_and_col_metadata = np.hstack((filler, col_metadata_df.T.values))\n top_half = np.column_stack((col_metadata_df.columns.values, filler_and_col_metadata))\n\n # BOTTOM HALF: horz concatenate rid, row_metadata, and data\n row_metadata_and_data = np.hstack((row_metadata_df.values, data_df.values))\n bottom_half = np.column_stack((data_df.index.values, row_metadata_and_data))\n\n # Vert concatenate the two halves\n full_df_values = np.vstack((top_half, bottom_half))\n\n # Stitch together full_df\n full_df = pd.DataFrame(full_df_values, columns=top_row)\n\n # Check that is has correct dims\n assert (full_df.shape == (\n (col_metadata_df.shape[1] + data_df.shape[0]),\n (1 + row_metadata_df.shape[1] + data_df.shape[1])))\n return full_df\n\n\ndef write_full_df(full_df, f, data_null, data_float_format):\n \"\"\"Write the full_df to the gct file.\n\n Args:\n full_df (pandas df): data and metadata arranged correctly\n f (file handle): handle for output file\n data_null (string): how to represent missing values in the data\n data_float_format (string): how many decimal points to keep in representing data\n Returns:\n nothing\n \"\"\"\n full_df.to_csv(f, header=True, index=False,\n sep=\"\\t\",\n na_rep=data_null,\n float_format=data_float_format)\n\n\ndef append_dims_and_file_extension(fname, data_df):\n \"\"\"Append dimensions and file extension to output filename.\n N.B. Dimensions are cols x rows.\n\n Args:\n fname (string): output filename\n data_df (pandas df)\n Returns:\n out_fname (string): output filename with matrix dims and .gct appended\n \"\"\"\n # If there's no .gct at the end of output file name, add the dims and .gct\n if not fname.endswith(\".gct\"):\n out_fname = '{0}_n{1}x{2}.gct'.format(fname, data_df.shape[1], data_df.shape[0])\n return out_fname\n\n # Otherwise, only add the dims\n else:\n basename = os.path.splitext(fname)[0]\n out_fname = '{0}_n{1}x{2}.gct'.format(basename, data_df.shape[1], data_df.shape[0])\n return out_fname\n","sub_path":"python/broadinstitute_cmap/io/pandasGEXpress/write_gct.py","file_name":"write_gct.py","file_ext":"py","file_size_in_byte":7343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"311430630","text":"import argparse\nimport sys\n\nfrom .. import __about__, crossref, tools\n\n\ndef _get_version_text():\n return \"\\n\".join(\n [\n \"betterbib {} [Python {}.{}.{}]\".format(\n __about__.__version__,\n sys.version_info.major,\n sys.version_info.minor,\n sys.version_info.micro,\n ),\n \"Copyright (c) 2013-2020, Nico Schlömer <{nico.schloemer@gmail.com}>\",\n ]\n )\n\n\ndef main(argv=None):\n parser = _get_parser()\n args = parser.parse_args(argv)\n source = crossref.Crossref()\n entry = source.get_by_doi(args.doi)\n\n bibtex_key = \"key\"\n string = tools.pybtex_to_bibtex_string(entry, bibtex_key)\n args.outfile.write(string)\n return\n\n\ndef _get_parser():\n parser = argparse.ArgumentParser(description=\"Turn a DOI into a BibTeX entry.\")\n parser.add_argument(\n \"-v\",\n \"--version\",\n help=\"display version information\",\n action=\"version\",\n version=_get_version_text(),\n )\n parser.add_argument(\"doi\", type=str, help=\"input DOI\")\n parser.add_argument(\n \"outfile\",\n nargs=\"?\",\n type=argparse.FileType(\"w\"),\n default=sys.stdout,\n help=\"output file (default: stdout)\",\n )\n return parser\n","sub_path":"betterbib/cli/doi2bibtex.py","file_name":"doi2bibtex.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"62650668","text":"'''\n Liliana Varela-Rodriguez\n \n SDEV 220 PYTHON\n \n M01 Programming Exercises 2.15\n \n 01/28/2018\n \n '''\n\n#2.15 Geometry: area of a hexagon\n\nlength = eval(input(\"Enter the one side's length\"))\n\nlength = length ** 2\narea = 3 * (3 ** 0.5) / 2 * length\n\nprint(\"The area of the hexagon = \", area)\n","sub_path":"Python/M01/M01_Assignment/Liliana_Varela/2.15.py","file_name":"2.15.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"37204342","text":"#!/usr/bin/env python\n# parallel usage :\n# ls *.hdf5 | parallel comp.py --timeout=100 --no-collect '--files={}'\n#\n# comp.py --max-problems=10 --no-compute --no-collect # output problems.txt\n# cat problems.txt | parallel comp.py --timeout=100 --no-collect '--files={}'\n#\n\n\nimport re\nfrom glob import glob\nfrom itertools import product\nfrom subprocess import check_call\nimport os\nimport h5py\nimport getopt\nimport sys\nimport hashlib\n\n#from io import StringIO\n\n\nimport numpy as np\n\n\n\nimport siconos.numerics as N\nnumerics_verbose=0\nN.numerics_set_verbose(numerics_verbose)\nimport siconos.fclib as FCL\n\n#print os.path.join(os.path.dirname(sys.argv[0]), 'external/build')\n\nsys.path.append(os.path.join(os.path.dirname(sys.argv[0]), 'external/build'))\n\ntry:\n import BogusInterface\nexcept:\n pass\n#logger = multiprocessing.log_to_stderr()\n#logger.setLevel(logging.INFO)\n\nfrom SiconosSolver import *\nfrom faf_tools import *\nfrom faf_timeout import *\nfrom faf_matrix_tools import *\nfrom faf_display_tools import *\nfrom faf_default_values import *\n\n#debugger\n#import pdb\n#pdb.set_trace()\n\n\ndef usage():\n print('Usage: '+sys.argv[0]+'[option]')\n\n options_doc = \"\"\"\n Options \n --help \n display this message\n --verbose \n enable verbose mode equal to 1 for Siconos Numerics\n --no-collect \n leave the result into separate file that are named according the solver and the name of the problem\n --just-collect\n collect all the result into comp.hdf5\n --timeout=n\n set the maximum time of computation for each problem to n seconds (default,utimeout,s)\n --maxiter=n\n set the maximum number of iterations for each problem to n (default\",maxiter,\")\n --maxiterls=n\n set the maximum number of iterations for each problem to n (default\",maxiterls,\")\n --domain='a:d:b'\n restrict the domain of the performance profile to the interval [a,b] with a step of d (default\",domain[0],\":\",domain[1]-domain[0],\":\",domain[-1]+domain[1]-domain[0],\")\n or a perfomance profile a should be greater or equal 1\n --measure=value\n select the value as the measure for the perfomance profile. Possible values are time, iter, flpops\n --display\n perform the computation of performance profile and display it in matplotlib\n --display-distrib='from-files' or \n perform the computation of distribution and display it in matplotlib\n --new\n remove comp.hdf5 file\n --solvers=string\n use keyworks in s separated by comma for filtering solvers\n --solvers-exact=string\n use exact names of solvers in s separated by comma for filtering solvers\n --with-mumps\n use mumps as linear system solver\n --max-problems=\n Randomly select problems in current directory.\n The problems list is written in problems.txt file\n --gnuplot-profile\n output gnuplot command file profile.gp for plotting profiles woth gnuplot\n --gnuplot-distrib\n output gnuplot command file distrib.gp for plotting distribution woth gnuplot\n --gnuplot-separate-keys\n output keys anf legend for gnuplot in a separate file.\n --display-distrib='from-files' \n --list-contents\n list contents of comp.hdf5 file\n --list-contents-solvers\n list solvers contents of comp.hdf5 file\n --compute-cond-rank\n compute the rank (vairous numerical methods) and condition number of W and store it in the problem file\n --compute-hardness\n compute the average performance of the best solver on a set of problem divided by the average number of contact\n --compute-cond-rank\n compute the conditioning number and the rank of the matrix in the problems\n\n Other options have to be documented\n \n Usage examples:\n\n 1) running comparison\n\n comp.py --measure=time --precision=1e-4 --timeout=100 --solvers-exact='NSN-JeanMoreau-NLS','NSN-AlartCurnier-NLS','NSN-NaturalMap-NLS' --no-collect \n\n 2) collecting results\n\n comp.py --measure=time --precision=1e-4 --timeout=100 --just-collect\n\n 3) displaying results\n\n comp.py --display --measure=time --domain='1:0.1:10' comp.hdf5\n\n comp.py --display --measure=time --solvers=Gauss,Tresca,SOCLCP,ACLM --domain=1:0.1:100\n\n 4) For openmp comparison:\n\n comp.py --thread-list=1,2,3,4,5 --solvers=NSGS-AC-OPENMP\n\n comp.py --display-speedup --measure=time\n\n \"\"\"\n print(options_doc)\n\n\ntry:\n opts, args = getopt.gnu_getopt(sys.argv[1:], '',\n ['help', 'verbose=','no-guess',\n 'clean', 'display', 'display-convergence','no-matplot',\n 'files=', 'solvers-exact=', 'solvers=',\n 'random-sample=', 'max-problems=',\n 'timeout=', 'maxiter=', 'maxiterls=', 'precision=',\n 'keep-files', 'new', 'errors',\n 'velocities', 'reactions', 'measure=',\n 'just-collect', 'cond-nc=', 'display-distrib=',\n 'no-collect', 'no-compute', 'domain=',\n 'replace-solvers-exact=','replace-solvers=',\n 'gnuplot-profile','gnuplot-distrib', 'logscale', 'gnuplot-separate-keys',\n 'output-dat', 'with-mumps', 'file-filter=', 'remove-files=',\n 'list-contents','list-contents-solver',\n 'add-precision-in-comp-file','add-timeout-in-comp-file',\n 'compute-cond-rank','compute-hardness','test-symmetry','forced','adhoc',\n 'display-speedup', 'thread-list=','estimate-optimal-timeout'])\n\n\nexcept getopt.GetoptError as err:\n sys.stderr.write('{0}\\n'.format(str(err)))\n usage()\n exit(2)\nfor o, a in opts:\n if o == '--verbose':\n numerics_verbose=int(a)\n N.numerics_set_verbose(numerics_verbose)\n if o == '--help':\n usage()\n exit(2)\n elif o == '--timeout':\n utimeout = float(a)\n elif o == '--maxiter':\n maxiter = int(a)\n elif o == '--maxiterls':\n maxiterls = int(a)\n elif o == '--precision':\n precision = float(a)\n elif o == '--clean':\n clean = True\n elif o == '--estimate-optimal-timeout':\n compute_rho=True\n estimate_optimal_timeout=True\n compute = False\n elif o == '--display':\n display = True\n compute_rho=True\n compute = False\n elif o == '--list-contents':\n list_contents = True\n compute = False\n elif o == '--list-contents-solver':\n list_contents_solver = True\n compute = False\n elif o == '--display-convergence':\n display_convergence = True\n compute = False\n elif o == '--display-speedup':\n display_speedup = True\n compute = False\n elif o == '--thread-list':\n print(a)\n thread_list = [int (x) for x in split(a,',')]\n elif o == '--measure':\n measure_name = a\n elif o == '--random-sample':\n if os.path.exists('problems.txt'):\n os.remove('problems.txt')\n random_sample_proba = float(a)\n elif o == '--max-problems':\n if os.path.exists('problems.txt'):\n os.remove('problems.txt')\n max_problems = int(a)\n elif o == '--keep-files':\n keep_files = True\n elif o == '--errors':\n output_errors = True\n elif o == '--velocities':\n output_velocities = True\n elif o == '--reactions':\n output_reactions = True\n elif o == '--just-collect':\n ask_compute = False\n elif o == '--no-collect':\n ask_collect = False\n elif o == '--no-compute':\n ask_compute = False\n elif o == '--cond-nc':\n cond_nc = [float (x) for x in split(a,':')]\n elif o == '--display-distrib':\n display_distrib = True\n compute = False\n display_distrib_var = a\n elif o == '--domain':\n urange = [float (x) for x in split(a,':')]\n domain = np.arange(urange[0], urange[2], urange[1])\n elif o == '--no-matplot':\n no_matplot=True\n elif o == '--solvers':\n user_solvers = split(a, ',')\n elif o == '--solvers-exact':\n user_solvers_exact = split(a, ',')\n elif o == '--replace-solvers-exact':\n replace_solvers = split(a, ',')\n try:\n with h5py.File('comp.hdf5','r+') as comp_file:\n solver_in_compfile = list(comp_file['data']['comp'])\n #print \"list(comp_file['data']['comp'])\", solver_in_compfile\n replace_solver_in_compfile = list(filter(lambda s: any(us == s for us in replace_solvers), solver_in_compfile))\n print(\"replace solver in comp file\", replace_solver_in_compfile)\n for s in replace_solver_in_compfile:\n del comp_file['data']['comp'][s]\n except Exception as e:\n print(e)\n elif o == '--replace-solvers':\n replace_solvers = split(a, ',')\n #print \"replace_solvers\", replace_solvers\n try:\n with h5py.File('comp.hdf5','r+') as comp_file:\n solver_in_compfile = list(comp_file['data']['comp'])\n #print \"list(comp_file['data']['comp'])\", solver_in_compfile\n replace_solver_in_compfile = list(filter(lambda s: any(us in s for us in replace_solvers), solver_in_compfile))\n print(\"replace solver in comp file\", replace_solver_in_compfile)\n for s in replace_solver_in_compfile:\n del comp_file['data']['comp'][s]\n except Exception as e:\n print(e)\n elif o == '--gnuplot-profile':\n gnuplot_profile=True\n elif o == '--logscale':\n logscale=True\n elif o == '--gnuplot-distrib':\n gnuplot_distrib=True\n elif o == '--gnuplot-separate-keys':\n gnuplot_separate_keys = True\n elif o == '--output-dat':\n output_dat=True\n elif o == '--with-mumps':\n with_mumps=1\n elif o == '--new':\n try:\n os.remove('comp.hdf5')\n except:\n pass\n\n elif o == '--files':\n\n files = split(a, ',')\n\n for f in files:\n\n if os.path.exists(f):\n user_filenames += [f]\n else:\n if os.path.exists('{0}.hdf5'.format(f)):\n user_filenames += ['{0}.hdf5'.format(f)]\n elif o == '--file-filter':\n file_filter=split(a, ',')\n\n elif o == '--remove-files':\n remove_file=split(a, ',')\n\n\n elif o == '--no-guess':\n with_guess = False\n elif o == '--add-precision-in-comp-file':\n with h5py.File('comp.hdf5','r+') as comp_file:\n create_attrs_precision_in_comp_file(comp_file,float(a))\n elif o == '--add-timeout-in-comp-file':\n with h5py.File('comp.hdf5','r+') as comp_file:\n create_attrs_timeout_in_comp_file(comp_file,float(a))\n elif o == '--compute-hardness':\n compute_hardness = True\n compute = False\n elif o == '--compute-cond-rank':\n compute_cond_rank = True\n compute = False\n elif o == '--test-symmetry':\n test_symmetry = True\n compute = False\n elif o == '--adhoc':\n adhoc = True\n compute = False\n elif o == '--forced':\n forced=True\n\nnumerics_has_openmp_solvers=False\ntry:\n dir(N).index('fc3d_nsgs_openmp')\n numerics_has_openmp_solvers=True\nexcept ValueError:\n print(\"warning : fc3d_nsgs_openmp is not in siconos numerics\")\n\n\n\nclass SolverCallback:\n def __init__(self, h5file, data):\n self._offset = 0\n self._data = data\n self._file = h5file\n\n def get_step(self, reaction, velocity, error):\n\n self._reactions = self._data['reactions']\n self._velocities = self._data['velocities']\n self._errors = self._data['errors']\n self._offset += 1\n if output_reactions:\n self._reactions.resize(self._offset, 0)\n self._reactions[self._offset - 1, :] = reaction\n\n if output_velocities:\n self._velocities.resize(self._offset, 0)\n self._velocities[self._offset - 1, :] = velocity\n\n if output_errors:\n self._errors.resize(self._offset, 0)\n self._errors[self._offset - 1, :] = error\n print(\"in get_step\")\n\nclass Caller():\n\n def __init__(self):\n pass\n\n def _solver_call(self, solver, *args):\n return solver(*args)\n\n def __call__(self, tpl):\n\n solver, filename = tpl\n if hasattr(solver, 'read_fclib_format'):\n sproblem = solver.read_fclib_format(filename)\n problem = read_fclib_format(filename)[1]\n else:\n problem = read_fclib_format(filename)[1]\n sproblem = problem\n\n if (output_dat) :\n # write a dat file to create a test for Siconos/Numerics\n #N.frictionContact_display(problem)\n datfilename = filename + '.dat'\n N.frictionContact_printInFilename(problem,datfilename )\n\n\n\n pfilename = os.path.basename(os.path.splitext(filename)[0])\n\n output_filename = '{0}-{1}.hdf5'.format(solver.name(),\n pfilename)\n # considered as tmp file\n try:\n os.remove(output_filename)\n except:\n pass\n\n try:\n\n self._internal_call(solver, sproblem, filename, pfilename,\n output_filename)\n \n except Exception as e:\n\n print('Exception in internal call', e)\n\n try:\n os.remove(output_filename)\n except:\n pass\n\n with h5py.File(output_filename, 'w') as output:\n\n digest = hashlib.sha256(open(filename, 'rb').read()).digest()\n \n create_attrs_in_comp_file(output,precision,utimeout,os.uname()[1],measure_name)\n\n comp_data=output['data']['comp']\n solver_data = comp_data.create_group(solver.name())\n solver_problem_data = solver_data.create_group(pfilename)\n attrs = solver_problem_data.attrs\n info = 1\n time_s = np.nan\n iter = np.nan\n err = np.nan\n real_time = np.nan\n proc_time = np.nan\n flpops = np.nan\n mflops = np.nan\n\n attrs.create('filename', np.string_(filename))\n attrs.create('nc', numberOfDegreeofFreedomContacts(filename))\n attrs.create('nds', numberOfDegreeofFreedom(filename))\n attrs.create('cond_nc', cond_problem(filename))\n attrs.create('digest', digest)\n attrs.create('info', info)\n attrs.create('iter', iter)\n attrs.create('err', err)\n attrs.create('time', time_s)\n attrs.create('real_time', real_time)\n attrs.create('proc_time', proc_time)\n attrs.create('flpops', flpops)\n attrs.create('mflops', mflops)\n attrs.create('precision', precision)\n attrs.create('timeout', utimeout)\n if numerics_has_openmp_solvers :\n try:\n attrs.create('n_threads', solver.SolverOptions().iparam[10] )\n except :\n attrs.create('n_threads',-1)\n\n list_keys= list(attrs.keys())\n if u'digest' in list_keys:\n list_keys.remove(u'digest') \n list_print=[solver.name()]\n list_print.extend([attrs[item] for item in list_keys])\n print(list_print)\n \n with open('report.txt', \"a\") as report_file:\n print (list_print, file=report_file)\n\n\n @timeout(utimeout)\n def _internal_call(self, solver, problem, filename, pfilename, output_filename):\n\n\n #print(\"_internal_call\")\n\n with h5py.File(output_filename, 'w') as output:\n\n create_attrs_in_comp_file(output,precision,utimeout,os.uname()[1],measure_name)\n comp_data=output['data']['comp']\n\n solver_data = comp_data.create_group(solver.name())\n\n solver_problem_data = solver_data.create_group(pfilename)\n attrs = solver_problem_data.attrs\n\n psize = numberOfDegreeofFreedomContacts(filename)\n\n info = None\n iter = None\n err = None\n time_s = None\n real_time = None\n proc_time = None\n flpops = None\n mflops = None\n\n digest = hashlib.sha256(open(filename, 'rb').read()).digest()\n\n if psize is not None:\n solver_problem_data.create_dataset(np.string_('reactions'),\n (0, psize),\n maxshape=(None, psize))\n\n solver_problem_data.create_dataset(np.string_('velocities'),\n (0, psize),\n maxshape=(None, psize))\n\n solver_problem_data.create_dataset(np.string_('errors'),\n (0, 1),\n maxshape=(None, 1))\n\n solver_problem_callback = \\\n SolverCallback(output, solver_problem_data)\n\n # need a function, not an instance method for PyObjectCall...\n def pffff(r, v, e):\n solver_problem_callback.get_step(r, v, e)\n\n# callback is broken\n# try:\n# if output_errors or output_velocities or output_reactions:\n# solver.SolverOptions().callback = pffff\n# except:\n# pass\n\n # get first guess or set guess to zero\n reactions, velocities = solver.guess(filename)\n\n normq = np.linalg.norm(problem.q)\n _, guess_err = N.fc3d_compute_error(read_fclib_format(filename)[1],\n reactions, velocities, precision, solver.SolverOptions(), normq)\n\n# print \"guess error:\", guess_err\n\n try:\n\n if numerics_verbose >1:\n N.solver_options_print(solver.SolverOptions())\n\n again = True\n info = 0\n iter = 0\n err = np.inf\n real_time = 0.\n proc_time = 0.\n flpops = 0.\n mflops = 0.\n\n # several call to solver if the precision is not reached\n while again:\n\n t0 = time.time()\n #t0 = time.process_time()\n\n stdout_result = ''\n\n with catch_stdout(really=output_errors) as get_stdout:\n\n result = solver(problem, reactions, velocities)\n\n current_stdout = get_stdout()\n\n try:\n\n cl = enumerate(filter(lambda s: '||F||' in s,\n current_stdout.split('\\n')))\n\n rdat = [re.split('=|,', l)[-3:] for i, l in cl]\n\n dat = [float(r) for r, z, f in rdat]\n\n for e in dat:\n pffff(None, None, e)\n\n except Exception as e:\n sys.stderr.write('||', type(e))\n \n stdout_result += current_stdout\n\n \n time_s = time.time() - t0 # on unix, t is CPU seconds elapsed (floating point)\n #time_s = time.process_time() -t0\n fclib_sol = FCL.fclib_solution()\n\n fclib_sol.v = None\n fclib_sol.r = reactions\n fclib_sol.u = velocities\n fclib_sol.l = None\n\n #nerr = FCL.fclib_merit_local(read_fclib_format(filename)[0],\n # FCL.MERIT_1, fclib_sol)\n\n# _, xerr = N.FrictionContact3D_compute_error(read_fclib_format(filename)[1],\n# reactions, velocities, precision, solver.SolverOptions())\n\n\n i_info, i_iter, i_err, i_real_time, i_proc_time, i_flpops, i_mflops = result\n\n info = i_info\n iter += i_iter\n err = i_err\n real_time += i_real_time\n proc_time += i_proc_time\n flpops += i_flpops\n mflops = (mflops + i_mflops)/2.\n\n# if info == 0 and xerr >= precision:\n# solver.SolverOptions().iparam[0]=1\n# solver.SolverOptions().dparam[0]=solver.SolverOptions().dparam[1]/10\n# print 'precision not reached : ', xerr, '>', precision\n# again = False\n# else:\n# again = False\n\n again = False\n\n if info != 0:\n time_s = np.nan\n iter = np.nan\n err = np.nan\n real_time = np.nan\n proc_time = np.nan\n flpops = np.nan\n mflops = np.nan\n\n except Exception as exception:\n print(exception)\n info = 1\n time_s = np.nan\n iter = np.nan\n err = np.nan\n real_time = np.nan\n proc_time = np.nan\n flpops = np.nan\n mflops = np.nan\n\n attrs.create('filename', np.string_(filename))\n attrs.create('nc', numberOfDegreeofFreedomContacts(filename))\n attrs.create('nds', numberOfDegreeofFreedom(filename))\n attrs.create('cond_nc', cond_problem(filename))\n attrs.create('digest', digest)\n attrs.create('info', info)\n attrs.create('iter', iter)\n attrs.create('err', err)\n attrs.create('time', time_s)\n attrs.create('real_time', real_time)\n attrs.create('proc_time', proc_time)\n attrs.create('flpops', flpops)\n attrs.create('mflops', mflops)\n attrs.create('precision', precision)\n attrs.create('timeout', utimeout)\n\n \n if numerics_has_openmp_solvers :\n attrs.create('n_threads', solver.SolverOptions().iparam[10] )\n\n\n list_keys= list(attrs.keys())\n if u'digest' in list_keys:\n list_keys.remove(u'digest') \n list_print=[solver.name()]\n list_print.extend([attrs[item] for item in list_keys])\n print(list_print)\n \n # if info == 1:\n # measure_v = np.inf\n # else:\n # if measure == 'flop':\n # measure_v = flpops\n # elif measure == 'iter':\n # measure_v = iter\n # elif measure == 'time':\n # measure_v = time_s\n\n # measure[solver][ip] = measure_v\n\n # min_measure[fileproblem] = min(measure_v,\n # min_measure[fileproblem])\n # ip += 1\n\n # comp_file.flush()\n with open('report.txt', \"a\") as report_file:\n print (list_print, file=report_file)\n\n\n\n\n\ndef create_attrs_precision_in_comp_file(comp_file,precision_val):\n data = comp_file.get('data')\n if data == None :\n data = comp_file.create_group('data')\n comp_data = data.get('comp')\n if comp_data == None:\n comp_data = data.create_group('comp')\n comp_data.attrs.create('precision',precision_val)\n\ndef create_attrs_timeout_in_comp_file(comp_file,utimeout_val):\n data = comp_file.get('data')\n if data == None :\n data = comp_file.create_group('data')\n comp_data = data.get('comp')\n if comp_data == None:\n comp_data = data.create_group('comp')\n comp_data.attrs.create('timeout',utimeout_val)\n \ndef create_attrs_hostname_in_comp_file(comp_file,hostname_val):\n data = comp_file.get('data')\n if data == None :\n data = comp_file.create_group('data')\n comp_data = data.get('comp')\n if comp_data == None:\n comp_data = data.create_group('comp')\n comp_data.attrs.create('hostname',np.string_(hostname_val))\n\ndef create_attrs_measure_name_in_comp_file(comp_file,measure_name_val):\n data = comp_file.get('data')\n if data == None :\n data = comp_file.create_group('data')\n comp_data = data.get('comp')\n if comp_data == None:\n comp_data = data.create_group('comp')\n comp_data.attrs.create('measure_name',np.string_(measure_name_val))\n\n\n\n\ndef create_attrs_in_comp_file(comp_file,precision_val,utimeout_val,hostname_val,measure_name_val):\n create_attrs_precision_in_comp_file(comp_file,precision_val)\n create_attrs_timeout_in_comp_file(comp_file,utimeout_val)\n create_attrs_hostname_in_comp_file(comp_file,hostname_val)\n create_attrs_measure_name_in_comp_file(comp_file,measure_name_val)\n\ndef collect(tpl):\n\n solver, filename = tpl\n\n pfilename = os.path.basename(os.path.splitext(filename)[0])\n results_filename = '{0}-{1}.hdf5'.format(solver.name(),pfilename)\n #print \"file=\", results_filename\n if os.path.exists('comp.hdf5'):\n with h5py.File('comp.hdf5', 'r') as comp_file:\n comp_precision=comp_file['data']['comp'].attrs.get('precision')\n comp_utimeout=comp_file['data']['comp'].attrs.get('timeout')\n comp_measure_name=comp_file['data']['comp'].attrs.get('measure_name')\n comp_hostname=comp_file['data']['comp'].attrs.get('hostname')\n #print \"comp_precision\",comp_precision\n if comp_precision == None :\n raise RuntimeError (\"Warning. precision information is missing in existing comp.hdf5 file (old version)\\n you must add it with --add-precision-in-comp-file= \")\n if comp_utimeout == None :\n raise RuntimeError (\"Warning. timeout information is missing in existing comp.hdf5 file (old version)\\n you must add it with --add-timeout-in-comp-file= \")\n if comp_hostname == None :\n raise RuntimeError (\"Warning. hostname information is missing in existing comp.hdf5 file (old version)\\n you must add it with --add-hostname-in-comp-file= \")\n else:\n with h5py.File('comp.hdf5', 'w') as comp_file:\n # if comp.hdf5 is not existing, we set the attributes precision, timeout, hostanme, measurename to the first file collected.\n with h5py.File( results_filename, 'r+') as result_file:\n result_precision=result_file['data']['comp'].attrs.get('precision')\n result_utimeout=result_file['data']['comp'].attrs.get('timeout')\n result_hostname=result_file['data']['comp'].attrs.get('hostname')\n result_measure_name=result_file['data']['comp'].attrs.get('measure_name')\n create_attrs_in_comp_file(comp_file,result_precision,result_utimeout,result_hostname,result_measure_name)\n comp_precision=comp_file['data']['comp'].attrs.get('precision')\n comp_utimeout=comp_file['data']['comp'].attrs.get('timeout')\n comp_measure_name=comp_file['data']['comp'].attrs.get('measure_name')\n comp_hostname=comp_file['data']['comp'].attrs.get('hostname')\n\n if os.path.exists(results_filename) and not os.stat(results_filename).st_size == 0:\n try:\n if os.path.exists('comp.hdf5'):\n with h5py.File( results_filename, 'r+') as result_file:\n result_precision=result_file['data']['comp'].attrs.get('precision')\n result_utimeout=result_file['data']['comp'].attrs.get('timeout')\n result_hostname=result_file['data']['comp'].attrs.get('hostname')\n result_measure_name=result_file['data']['comp'].attrs.get('measure_name')\n if comp_precision != result_precision:\n raise RuntimeError (\"Precision of the result in comp.hdf5 ({0}) are not consistent result with the new computed result ({1}) \\nWe dot not collect it\\nCreate a new comp.hdf5 file\".format(comp_precision,result_precision))\n if comp_utimeout != result_utimeout:\n raise RuntimeError (\"Timeout of the result in comp.hdf5 ({0}) are not consistent result with the new computed result ({1}) \\nWe dot not collect it\\nCreate a new comp.hdf5 file\".format(comp_utimeout,result_utimeout))\n if comp_hostname != result_hostname:\n raise RuntimeError (\"hostname of the result in comp.hdf5 ({0}) are not consistent result with the new computed result ({1}) \\nWe dot not collect it\\nCreate a new comp.hdf5 file\".format(comp_hostname,result_hostname))\n if comp_measure_name != result_measure_name:\n raise RuntimeError (\"Measure of the result in comp.hdf5 ({0}) are not consistent result with the new computed result ({1}) \\nWe dot not collect it\\nCreate a new comp.hdf5 file\".format(comp_measure_name,result_measure_name))\n\n check_call(['h5copy','-p','-i', results_filename,\n '-ocomp.hdf5','-s/data/comp/{0}/{1}'.format(solver.name(),pfilename),\n '-d/data/comp/{0}/{1}'.format(solver.name(),pfilename)])\n if not keep_files:\n os.remove('{0}-{1}.hdf5'.format(solver.name(),pfilename))\n except Exception as e:\n print(e)\n\n\nclass Results():\n def __init__(self, result_file):\n self._result_file = result_file\n\n def __call__(self, tpl):\n solver = tpl[0]\n problem_filename = os.path.splitext(tpl[1])[0]\n #print(\"Results: problem_filename:\", problem_filename, type(problem_filename) )\n try:\n r = self._result_file['data']['comp'][solver.name()][problem_filename]\n # if abs(r.attrs.get('precision') - precision) >= 1e-16 :\n # raise RuntimeError()\n # if abs(r.attrs.get('timeout') - utimeout) >= 1e-16 :\n # raise RuntimeError()\n\n # list_print =[r.attrs['filename'], cond_problem(r.attrs['filename']), solver.name(), r.attrs['info'],\n # r.attrs['iter'], r.attrs['err'], r.attrs['time'], r.attrs['real_time'], r.attrs['proc_time'],\n # r.attrs['flpops'], r.attrs['mflops'],r.attrs.get('precision'),r.attrs.get('timeout')]\n # if numerics_has_openmp_solvers :\n # list_print.append(r.attrs['n_threads'])\n # print(\"Already in comp file : \", list_print)\n\n\n list_keys= list(r.attrs.keys())\n if u'digest' in list_keys:\n list_keys.remove(u'digest')\n print(\"Already in comp file : \", [r.attrs[item] for item in list_keys])\n\n\n \n return False\n except:\n return True\n\n\n##################################\n## creation of solver list\n##################################\nprint(\"1 -- Creation of solver list\")\nfrom faf_solvers import *\nfs = faf_solvers(maxiter, precision, maxiterls, with_guess, with_mumps, numerics_has_openmp_solvers)\nall_solvers = fs.create_solvers()\n\n\nif (os.path.isfile(os.path.join( os.path.dirname(__file__),'adhoc_solverlist.py'))):\n execfile(os.path.join( os.path.dirname(__file__),'adhoc_solverlist.py'))\n #print \"execfile(\",os.path.join( os.path.dirname(__file__),'adhoc_solverlist.py'), \")\"\nif (os.path.isfile('adhoc_solverlist.py')):\n execfile('adhoc_solverlist.py')\n #print \"execfile(adhoc_solverlist.py)\"\n\nsolvers=[]\nif user_solvers != []:\n #print \"user_solvers\", user_solvers\n solvers.extend(list(filter(lambda s: any(us in s._name for us in user_solvers), all_solvers)))\n\n if solvers == []:\n raise RuntimeError (\"Cannot find any matching solver\")\nelif user_solvers_exact != []:\n #print \"user_solvers_exact\", user_solvers_exact\n solvers.extend(list(filter(lambda s: any(us == s._name for us in user_solvers_exact), all_solvers)))\n\n if solvers == []:\n raise RuntimeError(\"Cannot find any solvers in specified list\")\nelse:\n solvers= all_solvers\n\n##################################\n## creation of problems list\n##################################\nprint(\"2 -- Creation of problem list\")\n\nif not os.path.exists('problems.txt'):\n with open('problems.txt', 'w') as problems_txt:\n for f in filter(is_fclib_file, glob('*.hdf5')):\n problems_txt.write('{0}\\n'.format(f))\n\nif user_filenames == []:\n if file_filter == None:\n all_filenames = list_from_file('problems.txt')\n else:\n all_filenames = list(filter(lambda f: any(uf in f for uf in file_filter), list_from_file('problems.txt')))\n\nelse:\n all_filenames = user_filenames\n\n#all_filenames=['BoxesStack1-i9841-33.hdf5']\n#ask_collect = False\n#print(\"all_filenames\",all_filenames)\n_problem_filenames = list(filter(is_fclib_file,\n all_filenames))\n#print(\"_problems_filenames\", _problem_filenames)\n__problem_filenames = subsample_problems(_problem_filenames,\n random_sample_proba,\n max_problems, None, overwrite = (not display and not ask_compute and not ask_collect))\n\n\nproblem_filenames = subsample_problems(__problem_filenames,\n None,\n None, cond_nc)\n\nn_problems = len(problem_filenames)\n\n#problems = [read_fclib_format(f) for f in problem_filenames]\n\n\n\nmeasure = dict()\nsolver_r = dict()\nmin_measure = dict()\n\nfor fileproblem in problem_filenames:\n min_measure[fileproblem] = np.inf\n\nif clean:\n h5mode = 'w'\nelse:\n h5mode = 'a'\n\ncaller = Caller()\n\n\n#pool = MyPool(processes=8)\n\n\nif __name__ == '__main__':\n\n if compute:\n all_tasks = [t for t in product(solvers, problem_filenames)]\n if os.path.exists('comp.hdf5'):\n with h5py.File('comp.hdf5', 'r') as comp_file:\n tasks = list(filter(Results(comp_file), all_tasks))\n else:\n tasks = all_tasks\n \n \n print(\"3 -- Running computation and/or collecting tasks\")\n print(\" number of remaining tasks:\", len(tasks))\n print(\" for solvers :\", [ s._name for s in solvers])\n print(\" on files \",problem_filenames)\n #print(tasks)\n\n\n if ask_compute:\n print(\" with precision=\", precision, \" timeout=\", utimeout, \"and maxiter = \", maxiter)\n outputs = list(map(caller, tasks))\n if ask_collect:\n list(map(collect, tasks))\n\n if list_contents or list_contents_solver:\n with h5py.File('comp.hdf5', 'r') as comp_file:\n\n data = comp_file['data']\n comp_data = data['comp']\n for item in comp_data.attrs.keys():\n print(\"comp_data attrs: \", item + \":\", comp_data.attrs[item])\n print(\"Solvers :\")\n for solvername in comp_data:\n print(\" \",solvername)\n if (list_contents):\n for filename in comp_data[solvername]:\n list_keys= list(comp_data[solvername][filename].attrs.keys())\n if u'digest' in list_keys:\n list_keys.remove(u'digest')\n print(\" \",solvername, [comp_data[solvername][filename].attrs[item] for item in list_keys])\n\n if compute_rho:\n print(\"3 -- Compute rho for solvers :\", [ s._name for s in solvers])\n filename=None\n with h5py.File('comp.hdf5', 'r') as comp_file:\n\n data = comp_file['data']\n comp_data = data['comp']\n comp_precision=comp_file['data']['comp'].attrs.get('precision')\n comp_utimeout=comp_file['data']['comp'].attrs.get('timeout')\n # 1 n_problems\n n_problems = 0\n\n for solver in solvers:\n solver_name=solver.name()\n if solver_name in comp_data :\n if file_filter == None:\n all_filenames = comp_data[solver_name]\n else:\n all_filenames = list(filter(lambda f: any(uf in f for uf in file_filter), comp_data[solver_name]))\n\n if remove_file != None:\n remove_file_without_ext=[]\n for uf in remove_file:\n remove_file_without_ext.append(uf.split('.')[:-1][0])\n all_filenames = list(filter(lambda f: any(uf not in f for uf in remove_file_without_ext), all_filenames))\n\n filenames = subsample_problems(all_filenames,\n random_sample_proba,\n max_problems, cond_nc)\n\n n_problems = max(n_problems, len(filenames))\n\n # 2 measures & min_measure\n\n for solver in solvers:\n solver_name=solver.name()\n if solver_name in comp_data :\n if file_filter == None:\n all_filenames = comp_data[solver_name]\n else:\n all_filenames = list(filter(lambda f: any(uf in f for uf in file_filter), comp_data[solver_name]))\n\n if remove_file != None:\n remove_file_without_ext=[]\n for uf in remove_file:\n remove_file_without_ext.append(uf.split('.')[:-1][0])\n all_filenames = list(filter(lambda f: any(uf not in f for uf in remove_file_without_ext), all_filenames))\n\n\n filenames = subsample_problems(all_filenames,\n random_sample_proba,\n max_problems, cond_nc)\n\n\n assert len(filenames) <= n_problems\n\n measure[solver_name] = np.inf * np.ones(n_problems)\n solver_r[solver_name] = np.inf * np.ones(n_problems)\n\n ip = 0\n\n for filename in filenames:\n if filename not in min_measure:\n min_measure[filename] = np.inf\n try:\n pfilename = os.path.splitext(filename)[0]\n if comp_data[solver_name][pfilename].attrs['info'] == 0:\n measure[solver_name][ip] = comp_data[solver_name][pfilename].attrs[measure_name]\n min_measure[filename] = min(min_measure[filename], measure[solver_name][ip])\n else:\n measure[solver_name][ip] = np.inf\n except:\n measure[solver_name][ip] = np.nan\n ip += 1\n\n # 3 solver_r\n # for solver_name in comp_data:\n for solver in solvers:\n solver_name=solver.name()\n if solver_name in comp_data :\n if file_filter == None:\n all_filenames = comp_data[solver_name]\n else:\n all_filenames = list(filter(lambda f: any(uf in f for uf in file_filter), comp_data[solver_name]))\n if remove_file != None:\n remove_file_without_ext=[]\n for uf in remove_file:\n remove_file_without_ext.append(uf.split('.')[:-1][0])\n all_filenames = list(filter(lambda f: any(uf not in f for uf in remove_file_without_ext), all_filenames))\n\n\n\n filenames = subsample_problems(all_filenames,\n random_sample_proba,\n max_problems, cond_nc)\n\n ip = 0\n for filename in filenames:\n pfilename = os.path.splitext(filename)[0]\n try:\n if comp_data[solver_name][pfilename].attrs['info'] == 0:\n solver_r[solver_name][ip] = measure[solver_name][ip] / \\\n min_measure[filename]\n\n else:\n solver_r[solver_name][ip] = np.inf\n except:\n solver_r[solver_name][ip] = np.inf\n ip += 1\n\n # 4 rhos\n rhos = dict()\n #for solver_name in comp_data:\n for solver in solvers:\n solver_name=solver.name()\n if solver_name in comp_data :\n assert min(solver_r[solver_name]) >= 1\n rhos[solver_name] = np.empty(len(domain))\n for itau in range(0, len(domain)):\n rhos[solver_name][itau] = float(len(np.where( solver_r[solver_name] <= domain[itau] )[0])) / float(n_problems)\n\n if estimate_optimal_timeout:\n print(\"4 -- Estimate optimal timeout \")\n max_rhos=dict()\n with h5py.File('comp.hdf5', 'r') as comp_file:\n data = comp_file['data']\n comp_data = data['comp']\n for solver in solvers:\n #print(solver)\n solver_name=solver.name()\n #print(rhos[solver_name])\n #print(rhos[solver_name])\n if solver_name in comp_data :\n max_rhos[solver_name]= np.max(rhos[solver_name])\n #print(max_rhos)\n level_of_success=0.5\n nb_succeeded_solver= len(np.argwhere(np.array([max_rhos[solver_name] for solver_name in max_rhos.keys() ]) > level_of_success))\n #print(nb_succeeded_solver, \"solvers has rho_max over\", level_of_success)\n print(\"{0:2.0f} % solvers suceeded to reach rho max equal {1} \".format(nb_succeeded_solver/len(solvers)*100,level_of_success))\n level_of_success=0.9\n nb_succeeded_solver= len(np.argwhere(np.array([max_rhos[solver_name] for solver_name in max_rhos.keys() ]) > level_of_success))\n #print(nb_succeeded_solver, \"solvers has rho_max over\", level_of_success)\n print(\"{0:2.0f} % solvers suceeded to reach rho max equal {1} \".format(nb_succeeded_solver/len(solvers)*100,level_of_success))\n level_of_success=0.99\n nb_succeeded_solver= len(np.argwhere(np.array([max_rhos[solver_name] for solver_name in max_rhos.keys() ]) > level_of_success))\n #print(nb_succeeded_solver, \"solvers has rho_max over\", level_of_success)\n print(\"{0:2.0f} % solvers suceeded to reach rho max equal {1} \".format(nb_succeeded_solver/len(solvers)*100,level_of_success))\n pass\n\n if display:\n print(\"4 -- Running display tasks \")\n with h5py.File('comp.hdf5', 'r') as comp_file:\n data = comp_file['data']\n comp_data = data['comp']\n\n date_str = time.ctime(creation_date('comp.hdf5'))\n \n #print('###########', time.ctime(creation_date('comp.hdf5')))\n \n if (gnuplot_profile and (filename != None)) :\n def write_report(r, filename):\n with open(filename, \"w\") as input_file:\n for k, v in r.items():\n line = '{}, {}'.format(k, v)\n print(line, file=input_file)\n\n out_data=np.empty([len(domain),len(comp_data)+1])\n write_report(rhos,'rhos.txt')\n write_report(solver_r,'solver_r.txt')\n def long_substr(data):\n substr = ''\n #print(\"data=\",data)\n if len(data) > 0 and len(data[0]) > 0:\n for i in range(len(data[0])):\n for j in range(len(data[0])-i+1):\n if j > len(substr) and is_substr(data[0][i:i+j], data):\n substr = data[0][i:i+j]\n return substr\n\n def is_substr(find, data):\n if len(data) < 1 and len(find) < 1:\n return False\n for i in range(len(data)):\n if find not in data[i]:\n return False\n return True\n\n\n with open('profile.gp','w') as gp:\n # all_rhos = [ domain ] + [ rhos[solver_name] for solver_name in comp_data ]\n all_rhos = [ domain ] + [ rhos[solver.name()] for solver in filter(lambda s: s._name in comp_data, solvers) ]\n np.savetxt('profile.dat', np.matrix(all_rhos).transpose())\n gp.write('resultfile = \"profile.dat\"\\n')\n #print(\"filenames=\",filenames)\n #print(\"long_substr(filenames)=\", long_substr(filenames))\n test_name = long_substr(filenames).partition('-')[0]\n print(\"test_name=\",test_name)\n test_name_gnuplot = test_name.replace('_',' ')\n print(\"test_name_gnuplot=\",test_name_gnuplot)\n if test_name.endswith('_'):\n test_name = test_name[:-1]\n gp.write('basename=\"profile-{0}\"\\n'.format(test_name))\n #print filename.partition('-')[0]\n print(\"test_name=\",test_name)\n gp.write('\\n')\n gp.write('term_choice_tikz=1\\n')\n gp.write('if (term_choice_tikz == 1) \\\\\\n')\n if (gnuplot_with_color):\n gp.write('set term tikz standalone size 5in,3in font \\'\\\\small\\\\sf\\'; \\\\\\n')\n else:\n gp.write('set term tikz standalone monochrome size 5in,3in font \\'\\\\small\\\\sf\\'; \\\\\\n')\n gp.write('extension = \\'.tex\\'; \\\\\\n')\n gp.write('extension_legend = \\'_legend.tex\\'; \\\\\\n')\n gp.write('set output basename.extension; \\\\\\n')\n gp.write('print \"output = \", basename.extension; \\\\\\n')\n\n gp.write('else \\\\\\n')\n gp.write('set term aqua;\\\\\\n')\n gp.write('\\n')\n \n #gp.write('set title\\'{0} - precision: {1} - timeout: {2} - {3}\\';; \\n'.format(test_name_gnuplot,comp_precision,comp_utimeout, date_str))\n\n\n \n gp.write('set xrange [{0}:{1}]\\n'.format(domain[0]-0.01, domain[len(domain)-1]))\n gp.write('set yrange [-0.01:1.01]\\n')\n gp.write('set ylabel \\'$\\\\rho(\\\\tau)$ \\' \\n')\n maxrows=len(solvers)/2+1\n gp.write('set key below right vertical maxrows {0}\\n'.format(maxrows))\n\n\n x_label=False\n if x_label:\n if logscale:\n gp.write('set logscale x\\n')\n gp.write('set xlabel \\'$\\\\tau$ ({0}) (logscale)\\' \\n'.format(measure_name))\n else:\n gp.write('set xlabel \\'$\\\\tau$ ({0})\\' \\n'.format(measure_name))\n \n #gp.write('set title \\'{0}\\'\\n'.format(filename.partition('-')[0]));\n gp.write('plot ')\n if gnuplot_separate_keys:\n if (gnuplot_with_color):\n gp.write(\n ','.join(['resultfile using 1:{0} notitle w l dashtype {1} linecolor {2} lw 3'.format(index + 2,index+1,index%6+1)\n for index, solver in enumerate(filter(lambda s: s._name in comp_data, solvers)) ]))\n\n gp.write('\\n set output basename.extension_legend; \\n')\n gp.write('print \"output = \", basename.extension_legend; \\n \\n')\n gp.write('unset border; \\n \\n')\n gp.write('unset title; \\n \\n')\n gp.write('unset tics; \\n \\n')\n gp.write('unset xlabel; \\n \\n')\n gp.write('unset ylabel; \\n \\n')\n gp.write('set term tikz standalone size 5in,1.5in font \\'\\\\small\\\\sf\\'; \\\\\\n')\n gp.write('set key right inside vertical maxrows {0}\\n'.format(maxrows))\n gp.write('\\n plot [0:1] [0:1]')\n gp.write(\n ','.join([' NaN t \"{1}\" w l dashtype {2} linecolor {3} lw 3'.format(index + 2, solver.gnuplot_name(),index+1,index%6+1)\n for index, solver in enumerate(filter(lambda s: s._name in comp_data, solvers)) ]))\n\n\n\n else:\n gp.write(\n ','.join(['resultfile using 1:{0} notitle w l dashtype {1} linecolor {2} lw 3'.format(index + 2,index+1,8)\n for index, solver in enumerate(filter(lambda s: s._name in comp_data, solvers)) ]))\n\n gp.write('\\n set output basename.extension_legend; \\n')\n gp.write('print \"output = \", basename.extension_legend; \\n \\n')\n gp.write('unset border; \\n \\n')\n gp.write('unset title; \\n \\n')\n gp.write('unset tics; \\n \\n')\n gp.write('unset xlabel; \\n \\n')\n gp.write('unset ylabel; \\n \\n')\n gp.write('set term tikz standalone monochrome size 5in,1.5in font \\'\\\\small\\\\sf\\'; \\\\\\n')\n gp.write('set key right inside vertical maxrows {0}\\n'.format(maxrows))\n gp.write('\\n plot [0:1] [0:1]')\n gp.write(\n ','.join([' NaN t \"{1}\" w l dashtype {2} linecolor {3} lw 3'.format(index + 2, solver.gnuplot_name(),index+1,8)\n for index, solver in enumerate(filter(lambda s: s._name in comp_data, solvers)) ]))\n\n\n else:\n if (gnuplot_with_color):\n gp.write(\n ','.join(['resultfile using 1:{0} t \"{1}\" w l dashtype {2} linecolor {3} lw 3'.format(index + 2, solver.gnuplot_name(),index+1,index%6+1)\n for index, solver in enumerate(filter(lambda s: s._name in comp_data, solvers)) ]))\n else:\n gp.write(\n ','.join(['resultfile using 1:{0} t \"{1}\" w l dashtype {2} linecolor {3} lw 3'.format(index + 2, solver.gnuplot_name(),index+1,8)\n for index, solver in enumerate(filter(lambda s: s._name in comp_data, solvers)) ]))\n\n # all_rhos = [ rhos[solver_name] for solver_name in comp_data ]\n # g.plot(*all_rhos)\n\n if (gnuplot_profile and (filename == None)) :\n print(\"Warning: no problem corresponding to the required solver\")\n if (os.path.isfile('profile.gp')):\n os.remove('profile.gp')\n\n if not no_matplot:\n # 5 plot\n from matplotlib.pyplot import subplot, title, plot, grid, show, get_fignums, legend, figure, xlim, ylim, xscale\n\n #for solver_name in comp_data:\n for solver in solvers:\n solver_name=solver.name()\n if logscale:\n xscale('log')\n\n if solver_name in comp_data :\n plot(domain, rhos[solver_name], label=solver_name)\n ylim(0, 1.0001)\n xlim(domain[0], domain[-1])\n legend(loc=4)\n grid()\n\n\n if display_convergence:\n import matplotlib.pyplot as plt\n from matplotlib.pyplot import show\n with h5py.File('comp.hdf5', 'r') as comp_file:\n\n data = comp_file['data']\n comp_data = data['comp']\n\n if user_filenames == []:\n for solver_name in comp_data:\n\n filenames = subsample_problems(comp_data[solver_name],\n random_sample_proba,\n max_problems, cond_nc)\n else:\n filenames = user_filenames\n \n for filename in filenames:\n\n fig, axs = plt.subplots(1, 1)\n ax = axs\n\n ax.set_title('Convergence on {0}'.format(filename))\n ax.grid(True, which=\"both\")\n\n ax.set_yscale('symlog', linthreshy=0.001)\n \n for solver_name in comp_data:\n\n try:\n pfilename = os.path.splitext(filename)[0]\n solver_problem_data = comp_data[solver_name][pfilename]\n \n ax.plot(np.arange(len(solver_problem_data['errors'][:])),\n np.log(solver_problem_data['errors']),\n label='{0}'.format(solver_name))\n ax.legend(loc='lower left')\n \n except:\n pass\n\n\n\n if compute_cond_rank:\n print(\"Tasks will be run for\", problem_filenames)\n for problem_filename in problem_filenames:\n print(\"compute for\", problem_filename,\"....\")\n with h5py.File(problem_filename, 'r+') as fclib_file:\n no_rank_info=True\n if (not forced):\n if (fclib_file['fclib_local']['W'].attrs.get('rank') == None) :\n print(\"Rank info already not in\", problem_filename)\n else:\n print(\"Rank info already in\", problem_filename)\n print(\"fclib_file['fclib_local']['W'].attrs.get('rank')\", fclib_file['fclib_local']['W'].attrs.get('rank'))\n no_rank_info=False\n if no_rank_info:\n try:\n [norm_lsmr, cond_lsmr, max_nz_sv, min_nz_sv, cond, rank, rank_dense, rank_svd, rank_estimate] = norm_cond(problem_filename)\n print( problem_filename, norm_lsmr, cond_lsmr, max_nz_sv, min_nz_sv, cond, rank_dense, rank_svd, rank_estimate)\n with h5py.File(problem_filename, 'r+') as fclib_file:\n fclib_file['fclib_local']['W'].attrs.create('rank', rank)\n fclib_file['fclib_local']['W'].attrs.create('rank_dense', rank_dense)\n fclib_file['fclib_local']['W'].attrs.create('rank_svd', rank_svd)\n fclib_file['fclib_local']['W'].attrs.create('rank_estimate', rank_estimate)\n fclib_file['fclib_local']['W'].attrs.create('cond', cond)\n fclib_file['fclib_local']['W'].attrs.create('max_nz_sv', max_nz_sv)\n fclib_file['fclib_local']['W'].attrs.create('min_nz_sv', min_nz_sv)\n fclib_file['fclib_local']['W'].attrs.create('norm_lsmr', norm_lsmr)\n fclib_file['fclib_local']['W'].attrs.create('cond_lsmr', cond_lsmr)\n except Exception as e :\n print(\"-->\", e)\n \n if test_symmetry:\n print(\"Tasks will be run for\", problem_filenames)\n symmetry_test_list=[]\n dd_test_list=[]\n for problem_filename in problem_filenames:\n print(\"compute for\", problem_filename,\"....\")\n with h5py.File(problem_filename, 'r+') as fclib_file:\n no_rank_info=True\n \n try:\n is_symmetric, symmetry_test, is_dd, dd_test = test_symmetry_W(problem_filename)\n symmetry_test_list.append(symmetry_test)\n dd_test_list.append(dd_test)\n print(\"is_symmetric\", is_symmetric)\n print(\"is_dd\",is_dd)\n with h5py.File(problem_filename, 'r+') as fclib_file:\n fclib_file['fclib_local']['W'].attrs.create('symmetry', is_symmetric)\n except Exception as e :\n print(\"-->\", e)\n print(\"avg symmetry_test\",np.array(symmetry_test_list).mean() )\n print(\"avg dd_test\",np.array(dd_test_list).mean() )\n\n if adhoc:\n print(\"script adhoc (convenient moulinette)\")\n # for problem_filename in problem_filenames:\n # print \"treatment\", problem_filename\n # with h5py.File(problem_filename, 'r+') as fclib_file:\n # try:\n # import math\n # rank =fclib_file['fclib_local']['W'].attrs.get('rank')\n # if True : #if rank == None:\n # rank_dense=fclib_file['fclib_local']['W'].attrs.get('rank_dense')\n # if rank_dense != None and not math.isnan(rank_dense):\n # print \"rank := rank_dense\"\n # fclib_file['fclib_local']['W'].attrs.create('rank', rank_dense)\n # rank_svd=fclib_file['fclib_local']['W'].attrs.get('rank_svd')\n # if rank_svd != None and not math.isnan(rank_svd):\n # print \"rank := rank_svd\"\n # fclib_file['fclib_local']['W'].attrs.create('rank', rank_svd)\n\n # else:\n # print \"rank already present\"\n\n # r1 =fclib_file['fclib_local']['W'].attrs.get('r1')\n # r2 =fclib_file['fclib_local']['W'].attrs.get('r2')\n # if r1 != None:\n # print \"r1 --> norm_lsmr\"\n # fclib_file['fclib_local']['W'].attrs.create('norm_lsmr',r1)\n # fclib_file['fclib_local']['W'].attrs.__delitem__('r1')\n # if r2 != None:\n # print \"r2 --> cond_lsmr\"\n # fclib_file['fclib_local']['W'].attrs.create('cond_lsmr',r2)\n # fclib_file['fclib_local']['W'].attrs.__delitem__('r2')\n\n # except Exception as e :\n # print e\n # pass\n with h5py.File('comp.hdf5', 'r+') as comp_file:\n data = comp_file['data']\n comp_data = data['comp']\n for solver in comp_data:\n if ( 'NSGS-AC-' in solver):\n print(\"solver\", solver)\n if ('NSGS-AC-GP' not in solver):\n print(\"solver to be renamed\", solver)\n new_solver= solver.replace(\"AC-\",\"AC-GP-\")\n print(\"rename\", solver, \"in \",new_solver)\n data['comp'].move(solver,new_solver)\n\n if compute_hardness:\n nc = []\n nds = []\n cond_nc = []\n max_measure = dict()\n max_measure_by_contact = dict()\n min_measure_by_contact = dict()\n\n for fileproblem in problem_filenames:\n max_measure[fileproblem] = - np.inf\n max_measure_by_contact[fileproblem] = - np.inf\n min_measure_by_contact[fileproblem] = np.inf\n\n\n\n for problem_filename in problem_filenames:\n\n try:\n nc.append(numberOfDegreeofFreedomContacts(problem_filename)/3)\n except:\n pass\n try:\n nds.append(numberOfDegreeofFreedom(problem_filename))\n except:\n pass\n try:\n cond_nc.append(cond_problem(problem_filename))\n except:\n pass\n # compute other quantities\n #print(nc)\n nc_avg = sum(nc)/float(len(nc))\n print(\"nc_avg\", nc_avg)\n with h5py.File('comp.hdf5', 'r') as comp_file:\n data = comp_file['data']\n comp_data = data['comp']\n for solver in solvers:\n solver_name=solver.name()\n\n\n if solver_name in comp_data :\n filenames = subsample_problems(comp_data[solver_name],\n random_sample_proba,\n max_problems, None, overwrite=False)\n assert len(filenames) <= n_problems\n measure[solver_name] = np.inf * np.ones(n_problems)\n\n ip = 0\n\n for filename in filenames:\n if filename not in min_measure:\n min_measure[filename] = np.inf\n #try:\n pfilename = os.path.splitext(filename)[0]\n #print(' pfilename',pfilename)\n #print(solver_name,pfilename,comp_data[solver_name][pfilename].attrs['info'])\n if comp_data[solver_name][pfilename].attrs['info'] == 0:\n n_contact=numberOfDegreeofFreedomContacts(filename)/3\n #print(' filename n_contact',filename,n_contact)\n measure[solver_name][ip] = comp_data[solver_name][pfilename].attrs[measure_name]\n min_measure[filename] = min(min_measure[filename], measure[solver_name][ip])\n max_measure[filename] = max(max_measure[filename], measure[solver_name][ip])\n min_measure_by_contact[filename] = min(min_measure_by_contact[filename], measure[solver_name][ip]/n_contact)\n max_measure_by_contact[filename] = max(max_measure_by_contact[filename], measure[solver_name][ip]/n_contact)\n else:\n measure[solver_name][ip] = np.inf\n #except:\n # measure[solver_name][ip] = np.nan\n ip += 1\n\n print(\"min_measure\", min_measure)\n #print(\"max_measure\", max_measure)\n unsolved =0\n min_measure_list=[]\n min_measure_by_contact_list=[]\n for key in min_measure.keys():\n if min_measure[key] ==np.inf:\n unsolved += 1\n else:\n min_measure_list.append(min_measure[key])\n min_measure_by_contact_list.append(min_measure_by_contact[key])\n print('number of unsolved problems', unsolved)\n #min_measure_array=np.array([min_measure[key] for key in min_measure.keys()])\n #min_measure_by_contact_array=np.array([min_measure_by_contact[key] for key in min_measure_by_contact.keys()])\n \n avg_min_measure = np.array(min_measure_list).mean()\n std_min_measure = np.array(min_measure_list).std() \n avg_min_measure_by_contact = np.array(min_measure_by_contact_list).mean()\n std_min_measure_by_contact = np.array(min_measure_by_contact_list).std() \n print( \"Average min resolution measure (avg fastest solver measure) = {0:12.8e}\".format(avg_min_measure))\n print( \"Std min resolution measure (std fastest solver measure) = {0:12.8e}\".format(std_min_measure))\n print( \"Average min resolution measure by contact = {0:12.8e}\".format(avg_min_measure_by_contact))\n print( \"Std min resolution measure by contact = {0:12.8e}\".format(std_min_measure_by_contact))\n\n\n max_measure_list=[]\n max_measure_by_contact_list=[]\n for key in min_measure.keys():\n if max_measure[key] == -np.inf:\n unsolved += 1\n else:\n max_measure_list.append(max_measure[key])\n max_measure_by_contact_list.append(max_measure_by_contact[key])\n \n avg_max_measure = np.array(max_measure_list).mean()\n std_max_measure = np.array(max_measure_list).std() \n print( \"Average max resolution measure (avg slowest suceeded solver measure) = {0:12.8e}\".format(avg_max_measure))\n print( \"Std max resolution measure (std fastest solver measure) = {0:12.8e}\".format(std_max_measure))\n print( \"Average max resolution measure by contact = {0:12.8e}\".format(avg_max_measure/nc_avg))\n\n\n\n if display_distrib:\n from matplotlib.pyplot import title, subplot, grid, show, get_fignums, legend, figure, hist, xlim, ylim, xscale\n if display_distrib_var == 'from-files':\n\n nc = []\n nds = []\n cond_nc = []\n cond_W = []\n cond_W_lsmr = []\n rank_dense_W=[]\n rank_estimate_W=[]\n rank_ratio =[]\n rank_estimate_ratio =[]\n for problem_filename in problem_filenames:\n\n try:\n nc.append(numberOfDegreeofFreedomContacts(problem_filename)/3)\n except:\n pass\n try:\n nds.append(numberOfDegreeofFreedom(problem_filename))\n except:\n pass\n try:\n cond_nc.append(cond_problem(problem_filename))\n except:\n pass\n try:\n cond_W.append(cond(problem_filename))\n except:\n pass\n try:\n cond_W_lsmr.append(cond_lsmr(problem_filename))\n except:\n pass\n try:\n rank_dense_W.append(rank_dense(problem_filename))\n except:\n pass\n try:\n rank_estimate_W.append(rank_estimate(problem_filename))\n except:\n pass\n try:\n rank_ratio.append(numberOfDegreeofFreedomContacts(problem_filename)/float(rank_dense(problem_filename)))\n rank_estimate_ratio.append(numberOfDegreeofFreedomContacts(problem_filename)/float(rank_estimate(problem_filename)))\n except:\n pass\n print(\"number of problems\", len(nds))\n print(\"nds\", nds)\n print(\"max ndof\", max(nds))\n print(\"min ndof\", min(nds))\n print(\"max nc\", max(nc))\n print(\"min nc\", min(nc))\n\n \n print(\"rank_dense_W\", rank_dense_W)\n print(\"cond_nc\", cond_nc)\n\n print(\"cond_W\", cond_W)\n if (len(cond_W) >0):\n print(\"max cond_W\", max(cond_W))\n print(\"min cond_W\", min(cond_W))\n\n\n print(\"cond_W_lsmr\", cond_W_lsmr)\n print(\"max cond_W_lsmr\", max(cond_W_lsmr))\n print(\"min cond_W_lsmr\", min(cond_W_lsmr))\n print(\"max cond_nc\", max(cond_nc))\n print(\"min cond_nc\", min(cond_nc))\n\n print(\"max rank_dense_W\", max(rank_dense_W))\n print(\"min rank_dense_W\", min(rank_dense_W))\n \n print(\"max rank_estimate_W\", max(rank_estimate_W))\n print(\"min rank_estimate_W\", min(rank_estimate_W))\n\n print(\"max rank_ratio\", max(rank_ratio))\n print(\"min rank_ratio\", min(rank_ratio))\n\n print(\"max rank_estimate_ratio\", max(rank_estimate_ratio))\n print(\"min rank_estimate_ratio\", min(rank_estimate_ratio))\n\n \n if (len(cond_W) == 0):\n cond_W = cond_W_lsmr\n\n figure()\n subplot(311)\n hist(nc, 100, label='nc', histtype='stepfilled')\n grid()\n legend()\n subplot(312)\n import math\n if not math.isnan(min(nds)):\n hist(nds, 100, label='nds', histtype='stepfilled')\n grid()\n legend()\n subplot(313)\n\n if not math.isnan(min(cond_nc)):\n hist(cond_nc, 100, label='cond_nc', histtype='stepfilled')\n grid()\n legend()\n\n figure()\n subplot(311)\n if not math.isnan(min(cond_W)):\n hist(cond_W, 100, label='cond(W)', histtype='stepfilled')\n grid()\n legend()\n subplot(312)\n if not math.isnan(min(rank_dense_W)):\n hist(rank_dense_W, 100, label='rank(W)', histtype='stepfilled')\n grid()\n legend()\n subplot(313)\n\n if not math.isnan(min(rank_ratio)):\n hist(rank_ratio, 100, label='rank_ratio(W)', histtype='stepfilled')\n grid()\n legend()\n\n\n\n\n\n\n if gnuplot_distrib :\n\n with open('distrib.gp','w') as gp:\n # all_rhos = [ domain ] + [ rhos[solver_name] for solver_name in comp_data ]\n all_distrib = [ nc] + [nds] + [cond_nc]\n np.savetxt('distrib.dat', np.matrix(all_distrib).transpose())\n gp.write('resultfile = \"distrib.dat\"\\n')\n gp.write('basename=\"distrib-{0}\"\\n'.format(problem_filename.partition('-')[0]))\n gp.write('\\n')\n gp.write('ismin(x) = (xmax)?max=x:0\\n')\n gp.write('\\n')\n gp.write('max=-1e38;min=1e38;\\n')\n gp.write('plot resultfile u 1:(ismin($1)*ismax($1))\\n')\n gp.write('min_nc = min; max_nc = max\\n')\n gp.write('max=-1e38;min=1e38;\\n')\n gp.write('plot resultfile u 1:(ismin($2)*ismax($2))\\n')\n gp.write('min_ndof = min; max_ndof = max\\n')\n gp.write('max=-1e38;min=1e38;\\n')\n gp.write('plot resultfile u 1:(ismin($3)*ismax($3))\\n')\n gp.write('min_ncond = min; max_ncond = max\\n')\n gp.write('\\n')\n gp.write('\\n')\n\n gp.write('term_choice_tikz=1\\n')\n gp.write('if (term_choice_tikz == 1) \\\\\\n')\n gp.write('set term tikz standalone monochrome size 5in,3in font \\'\\\\small\\\\sf\\'; \\\\\\n')\n gp.write('extension = \\'.tex\\'; \\\\\\n')\n gp.write('set output basename.extension; \\\\\\n')\n gp.write('print \"output = \", basename.extension; \\\\\\n')\n gp.write('else \\\\\\n')\n gp.write('set term aqua;\\\\\\n')\n gp.write(' \\n')\n gp.write('set xtics offset 0,0.5 \\n')\n gp.write('set key left top\\n')\n\n gp.write('basheight = 0.36; heightoff = 0.0; winratio = 1.0; winheight = basheight*winratio ; trans = 0.9\\n')\n gp.write('set multiplot \\n')\n gp.write('set size winratio,winheight \\n')\n gp.write('\\n')\n # gp.write('set xrange [{0}:{1}]\\n'.format(domain[0]-0.01, domain[len(domain)-1]))\n # gp.write('set yrange [-0.01:1.01]\\n')\n gp.write('set ylabel \\'\\\\shortstack{Number of \\\\\\ problems} \\' \\n')\n gp.write('bin(x, width) = width*floor(x/width) + binwidth/2.0\\n')\n #gp.write('set title \\'{0}\\'\\n'.format(problem_filename.partition('-')[0]));\n gp.write('\\n')\n gp.write('set origin 0.0,winheight*2.0*trans+heightoff\\n')\n gp.write('numberofbox=50\\n')\n gp.write('print \\'max_nc =\\', max_nc,\\' min_nc =\\', min_nc \\n')\n gp.write('binwidth = (max_nc-min_nc)/numberofbox\\n')\n gp.write('set boxwidth binwidth\\n')\n\n gp.write('print \\'binwidth =\\', binwidth \\n')\n\n gp.write('set xlabel \\'number of contacts\\' offset 0,1.2 \\n')\n #gp.write('plot resultfile u (bin($1, binwidth)):(1.0) smooth freq w boxes title \\'number of contacts\\' \\n')\n gp.write('plot resultfile u (bin($1, binwidth)):(1.0) smooth freq w boxes notitle \\n')\n gp.write('\\n')\n gp.write('print \\'max_ndof =\\', max_ndof,\\' min_ndof =\\', min_ndof \\n')\n gp.write('if ( (max_ndof-min_ndof) < numberofbox) {binwidth =1 ;} else {binwidth = (max_ndof-min_ndof)/numberofbox}\\n');\n\n gp.write('set boxwidth binwidth\\n')\n gp.write('set origin 0.0,winheight*1.0*trans+heightoff\\n')\n\n gp.write('set xlabel \\'number of degrees of freedom \\' offset 0,1.2 \\n')\n\n #gp.write('plot resultfile u (bin($2, binwidth)):(1.0) smooth freq w boxes title \\'number of degrees of freedom \\' \\n')\n gp.write('plot resultfile u (bin($2, binwidth)):(1.0) smooth freq w boxes notitle \\n')\n gp.write('\\n')\n\n gp.write('set origin 0.0,winheight*0.0+heightoff\\n')\n gp.write('binwidth = (max_ncond-min_ncond)/numberofbox\\n')\n gp.write('print \\'binwidth =\\', binwidth \\n')\n\n gp.write('set boxwidth binwidth\\n')\n gp.write('set xlabel \\'ratio number of contacts unknowns/number of degrees of freedom\\' offset 0,1.2 \\n')\n #gp.write('plot resultfile u (bin($3, binwidth)):(1.0) smooth freq w boxes title \\'ratio number of contacts unknowns/number of degrees of freedom\\' \\n')\n gp.write('plot resultfile u (bin($3, binwidth)):(1.0) smooth freq w boxes notitle \\n')\n\n\n\n #gp.write(','.join(['resultfile using 1:{0} t \"{1}\" w l'.format(index + 2, solver.name())\n # for index, solver in enumerate(filter(lambda s: s._name in comp_data, solvers)) ]))\n # all_rhos = [ rhos[solver_name] for solver_name in comp_data ]\n # g.plot(*all_rhos)\n\n else:\n with h5py.File('comp.hdf5', 'r') as comp_file:\n\n data = comp_file['data']\n comp_data = data['comp']\n for solver_name in comp_data:\n\n if user_filenames == []:\n filenames = subsample_problems(comp_data[solver_name],\n random_sample_proba,\n max_problems, cond_nc)\n else:\n filenames = user_filenames\n\n x = dict()\n for filename in filenames:\n pfilename = os.path.splitext(filename)[0]\n if filename not in x:\n try:\n x[filename + solver_name] = comp_data[solver_name][pfilename].attrs[display_distrib_var]\n except:\n if display_distrib_var == 'cond-nc':\n print(filename)\n x[filename + solver_name] = cond_problem(filename)\n else:\n x[filename + solver_name] = np.nan\n figure()\n l = [x[k] for k in x]\n l.sort()\n values = array(l)\n hist(values, 100, range=(min(values), max(values)), histtype='stepfilled')\n grid()\n\n\n if display_speedup:\n from matplotlib.pyplot import subplot, title, plot, grid, show, get_fignums, legend, figure, hist, bar, xlabel, ylabel, boxplot\n print('\\n display speedup is starting ...')\n with h5py.File('comp.hdf5', 'r') as comp_file:\n\n data = comp_file['data']\n comp_data = data['comp']\n result_utimeout=comp_file['data']['comp'].attrs.get('timeout')\n print('solver in comp_data =',[s for s in comp_data] )\n solvers=[]\n if user_solvers != []:\n #print \"user_solvers\", user_solvers\n solvers.extend( list(filter(lambda s: any(us in s for us in user_solvers), comp_data)))\n\n if solvers == []:\n raise RuntimeError (\"Cannot find any matching solver\")\n\n elif user_solvers_exact != []:\n #print \"user_solvers_exact\", user_solvers_exact\n solvers.extend(list(filter(lambda s: any(us == s for us in user_solvers_exact), comp_data)))\n\n if solvers == []:\n raise RuntimeError(\"Cannot find any solvers in specified list\")\n\n else:\n solvers= comp_data\n\n print(' filtered solver in comp_data =',[s for s in solvers])\n\n solvers= list(filter(lambda s: ('OPENMP' in s), solvers))\n\n\n print(' solver for speedup-display =',[s for s in solvers])\n if solvers == []:\n raise RuntimeError(\"Cannot find any solvers in specified list\")\n #---#\n # collect results by filename\n #---#\n results_filename={}\n nthread_set= set()\n n_filename=[]\n\n for solver_name in solvers:\n if user_filenames == []:\n filenames = subsample_problems(comp_data[solver_name],\n random_sample_proba,\n max_problems, cond_nc)\n else:\n filenames = user_filenames\n n_filename.append(len(filenames))\n for filename in filenames:\n pfilename = os.path.splitext(filename)[0]\n nthread=int(solver_name.split('-')[-1])\n nthread_set.add(nthread)\n measure_data =comp_data[solver_name][pfilename].attrs[measure_name]\n nc =comp_data[solver_name][pfilename].attrs['nc']\n n_iter =comp_data[solver_name][pfilename].attrs['iter']\n if filename in results_filename.keys():\n results_filename[filename].append([solver_name,nthread,measure_data,nc,n_iter])\n else:\n results_filename[filename] = [[solver_name,nthread,measure_data,nc,n_iter]]\n\n\n #print(\"n_filename\", n_filename)\n\n results_filename_fails = {}\n for filename,solver in results_filename.items():\n for s in solver:\n if np.isnan(s[2]):\n if filename in results_filename.keys():\n results_filename_fails[filename]=results_filename[filename]\n print(\"\\nremove failed instance for filename:\",filename)\n print(results_filename.pop(filename))\n\n\n\n\n nthread_list=list(nthread_set)\n nthread_list.sort()\n\n # collect results by thread\n\n measure_by_nthread=[]\n measure_penalized_by_nthread=[]\n measure_mean_by_nthread=[]\n measure_mean_penalized_by_nthread=[]\n index_non_failed=[]\n index_failed=[]\n\n for n in nthread_list:\n measure_by_nthread.append([])\n measure_mean_by_nthread.append(0.0)\n\n speedup_list =[]\n speedup_size_list =[]\n\n for n in nthread_list:\n speedup_list.append([])\n speedup_size_list.append([])\n\n for filename,solver in results_filename.items():\n for s in solver:\n nthread= s[1]\n thread_index=nthread_list.index(nthread)\n measure_by_nthread[thread_index].append(s[2])\n measure_mean_by_nthread[thread_index] += s[2]\n\n\n for n in nthread_list:\n thread_index = nthread_list.index(n)\n measure_mean_by_nthread[thread_index] /= len(measure_by_nthread[thread_index])\n\n #raw_input()\n #print('measure_mean_by_nthread', measure_mean_penalized_by_nthread)\n\n speedup_list =[]\n speedup_size_list =[]\n iter_size_list=[]\n speedup_avg =[]\n\n for n in nthread_list:\n speedup_list.append([])\n speedup_size_list.append([])\n iter_size_list.append([])\n speedup_avg.append(0.0)\n thread_index=nthread_list.index(n)\n for i in range(len(measure_by_nthread[thread_index])):\n speedup_list[thread_index].append(0.0)\n\n for n in nthread_list:\n thread_index_ref= nthread_list.index(1)\n thread_index = nthread_list.index(n)\n for i in range(len(measure_by_nthread[thread_index])):\n speedup_list[thread_index][i] = measure_by_nthread[thread_index_ref][i]/measure_by_nthread[thread_index][i]\n speedup_avg[thread_index] += speedup_list[thread_index][i]\n speedup_avg[thread_index] /=len(measure_by_nthread[thread_index])\n\n print('speedup_avg', speedup_avg)\n #print('speedup_list', speedup_list)\n\n _cmp=0\n for filename,solver in results_filename.items():\n for s in solver:\n thread_index=nthread_list.index(s[1])\n #print _cmp, speedup_list[thread_index], speedup_list[thread_index][_cmp]\n speedup_size_list[thread_index].append([s[3] , speedup_list[thread_index][_cmp]])\n iter_size_list[thread_index].append([s[3] , s[4]])\n _cmp+=1\n\n count_failed=[]\n for n in nthread_list:\n count_failed.append(0)\n for filename,solver in results_filename_fails.items():\n for s in solver:\n nthread= s[1]\n thread_index=nthread_list.index(nthread)\n if np.isnan(s[2]):\n count_failed[thread_index] +=1\n\n # ---------------------------- #\n # figure #\n # ---------------------------- #\n\n\n\n figure(figsize=(8,14))\n\n subplot('211')\n xlabel('problem size')\n ylabel('speedup for each thread')\n for n in nthread_list:\n index=nthread_list.index(n)\n list_size_speedup= speedup_size_list[index]\n list_size_speedup= sorted(list_size_speedup, key=lambda data: data[0])\n plot(np.array([t[0] for t in list_size_speedup]), np.array([t[1] for t in list_size_speedup]), label='n='+str(n))\n legend()\n subplot('212')\n xlabel('problem size')\n ylabel('iter for each thread')\n for n in nthread_list:\n index=nthread_list.index(n)\n iter_size_speedup= iter_size_list[index]\n iter_size_speedup= sorted(iter_size_speedup, key=lambda data: data[0])\n plot(np.array([t[0] for t in iter_size_speedup]), np.array([t[1] for t in iter_size_speedup]), label='n='+str(n))\n legend()\n\n figure(figsize=(8,14))\n\n subplot('311')\n boxplot(speedup_list,positions=nthread_list)\n ylabel('speedup distribution')\n legend()\n\n\n subplot('312')\n plot(nthread_list,speedup_avg)\n ylabel('avg. speed up')\n legend()\n\n subplot('313')\n bar(nthread_list,count_failed)\n ylabel('# fails')\n xlabel('number of threads')\n legend()\n\n figure(figsize=(16,14))\n\n for filename,solver in results_filename.items():\n data_tuples = []\n for s in solver:\n data_tuples.append((s[1],s[2],s[3],s[4]))\n data_tuples=sorted(data_tuples, key=lambda data: data[0])\n try:\n subplot('211')\n #plot(np.array([data[0] for data in data_tuples])[:],np.array([data[1] for data in data_tuples])[:], label =filename)\n plot(np.array([data[0] for data in data_tuples])[:],np.array([data[1] for data in data_tuples])[:])\n ylabel('cpu time for each problems')\n xlabel('number of threads')\n legend()\n\n\n subplot('212')\n #plot(np.array([data[0] for data in data_tuples])[:],np.array([data[1] for data in data_tuples])[:], label =filename)\n plot(np.array([data[0] for data in data_tuples])[:],np.array([data_tuples[1][1]/data[1] for data in data_tuples])[:])\n ylabel('speedup for each problems')\n xlabel('number of threads')\n legend()\n except:\n pass\n\n\n\n\n display_bw=False\n if display or display_convergence or display_distrib or display_speedup:\n if not no_matplot:\n if (display_bw):\n figs = list(map(figure, get_fignums()))\n for fig in figs:\n setFigLinesBW(fig)\n\n show()\n","sub_path":"src/comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":86471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"652498678","text":"\n\ndef proteins(strand):\n \"\"\"Translate RNA sequences into proteins\"\"\"\n\n translate = {\n \"AUG\": \"Methionine\", \n \"UUU\": \"Phenylalanine\", \n \"UUC\": \"Phenylalanine\", \n \"UUA\": \"Leucine\", \n \"UUG\": \"Leucine\", \n \"UCU\": \"Serine\", \n \"UCC\": \"Serine\", \n \"UCA\": \"Serine\", \n \"UCG\": \"Serine\", \n \"UAU\": \"Tyrosine\", \n \"UAC\": \"Tyrosine\", \n \"UGU\": \"Cysteine\", \n \"UGC\": \"Cysteine\", \n \"UGG\": \"Tryptophan\", \n \"UAA\": \"\", \n \"UAG\": \"\", \n \"UGA\": \"\"\n }\n proteins = []\n for condon in (strand[i:i + 3] for i in range(0, len(strand), 3)):\n protein = translate[condon]\n if not protein:\n return proteins\n if not protein in proteins:\n proteins.append(protein)\n return proteins\n","sub_path":"protein-translation/protein_translation.py","file_name":"protein_translation.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"363179387","text":"from distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Distutils import build_ext\nfrom distutils import ccompiler\nfrom distutils import cmd\nfrom distutils import unixccompiler\nfrom Cython.Build import cythonize\nimport string\nimport platform\nimport sys\nimport os\n\n#holder for ext_modules variable\next_modules = None\n#execute following only if building extensions and started from makefile\nif(sys.argv[1] == \"build_ext\" and os.environ.has_key(\"CFLAGS\")):\n #determine arch of current os\n if(platform.system()=='Linux'):\n arch = 'linux'\n elif(platform.system()=='Darwin'):\n arch = 'macos'\n os.environ[\"CC\"] = \"g++\" \n else:\n arch = platform.system()\n\n #variable to hold all the libraries used in code\n libraries = [\"prim\"]#,\"boost_thread\",\"boost_system\"]\n\n #searches for boost_serialization or boost_serialization-mt libraries\n #if neither is found terminates compilation\n compiler = ccompiler.new_compiler() \n list_of_cflags = os.environ[\"CFLAGS\"].strip(string.whitespace).split(\" \")\n for flag in list_of_cflags:\n if(flag.startswith(\"-L\")):\n libdir = flag.lstrip(\"-L\")\n compiler.set_library_dirs([libdir])\n if(compiler.find_library_file(compiler.library_dirs, \"boost_serialization\")):\n libraries.append(\"boost_serialization\")\n break\n elif(compiler.find_library_file(compiler.library_dirs, \"boost_serialization-mt\")):\n libraries.append(\"boost_serialization-mt\")\n break\n else:\n print(\"BOOST serialization library not found\")\n print(\"Terminating...\")\n sys.exit(0)\n\n ext_modules=[\n Extension(\"interface\",\n [\"interface.pyx\",\"wrapper.cpp\"],\n # include_dirs=[\"kodiak/src/\", \"/\"],\n # extra_objects=[\"kodiak/lib/\"+arch+\"/libKodiak.a\",],\n include_dirs=[\"../src\", \"/\"],\n extra_objects=[\"../lib/\"+arch+\"/libKodiak.a\",],\n libraries=libraries,\n extra_link_args = [],\n extra_compile_args = [os.environ[\"CFLAGS\"]],\n language='c++',) # Unix-like specific\n ]\n\n\nsetup(\n name = \"python-interface-to-kodiak\",\n description = \"Userfriendly interface to Kodiak library\",\n cmdclass = {\"build_ext\": build_ext},\n ext_modules = ext_modules\n)\n","sub_path":"python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"282934429","text":"x, y, r1, r2 = (int(n) for n in input().split(' '))\nn = int(input())\nfor i in range(n):\n X, Y = (int(n) for n in input().split(' '))\n lower = r1 ** 2\n upper = r2 ** 2\n point = (X - x) ** 2 + (Y - y) ** 2\n if lower <= point <= upper:\n print('yes')\n else:\n print('no')\n\n'''\n\n\n入力例1\n 0 0 1 2\n 3\n 0 0\n 1 1\n 4 2\n\n出力例1\n no\n yes\n no\n\n入力例2\n 47 19 57 80\n 3\n 62 -52\n 35 -70\n -81 2\n\n出力例2\n yes\n no\n no\n '''\n","sub_path":"dcreekp/C/c021_ru_in_a_storm.py","file_name":"c021_ru_in_a_storm.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"354738821","text":"from openmesh import TriMesh\nimport projectconfig\nimport unittest\nfrom graphicfile import Graphic_File\nimport customstructures\nimport time\n\nclass AbstractTest(unittest.TestCase):\n def test_get_elements(self):\n start_time = time.time()\n elements = customstructures.get_elements(self.mesh)\n stop_time = time.time()\n print('time', stop_time - start_time)\n self.assertIsNotNone(elements)\n\n def test_get_elements_second_level(self):\n start_time = time.time()\n elements = customstructures.get_elements_second_level(self.mesh)\n stop_time = time.time()\n print('time', stop_time - start_time)\n self.assertIsNotNone(elements)\n \n def test_get_neighbors(self):\n start_time = time.time()\n neighbors = customstructures.get_neighbors(self.mesh)\n stop_time = time.time()\n print('time', stop_time - start_time)\n self.assertIsNotNone(neighbors)\n\n def test_flip_edges(self):\n start_time = time.time()\n customstructures.flip_edges(self.mesh)\n stop_time = time.time()\n print('time', stop_time - start_time)\n \n def test_border_check(self):\n start_time = time.time()\n customstructures.has_border(self.mesh)\n stop_time = time.time()\n print('time', stop_time - start_time)\n","sub_path":"test/abstract_test.py","file_name":"abstract_test.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"557475357","text":"from django.contrib import admin\nfrom django.urls import path, include\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('user/', include('users.urls')),\n path('Review/', include('Review.urls')),\n path('Like/', include('Like.urls')),\n]\n","sub_path":"toyproject/toyproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"250359267","text":"from coil_geom import TFcoil\r\nimport numpy as np\r\nimport pylab as pl\r\nfrom ANSYS import table\r\nfrom scipy.interpolate import griddata\r\nimport matplotlib.cm as cm\r\n\r\nTF = TFcoil(scale=0.1, Ndp=1, Nloop=7, cross_section='arc', Nsection=10, \r\n trim=0.01, insulation=0, named_selections=1) \r\n\r\nTF.conductor()\r\n#TF.case()\r\n#TF.pancakes()\r\nTF.end()\r\n\r\nNseg = 100 # theta segmentation\r\noffset_o = TF.po+5*TF.pn # pancake centre\r\nNcond,last = 0,0\r\n\r\ny_space = np.arange(-5*TF.pn,(TF.Nloop)*TF.pn-5*TF.pn,TF.pn)\r\ny_space = np.append(y_space-TF.r_cond*1.1,y_space+TF.r_cond*1.1)\r\ny_space = np.sort(y_space)\r\nz_space = np.append(TF.dp_pattern-TF.shift_o,TF.dp_pattern+TF.shift_o)\r\nz_space = np.append(z_space-TF.r_cond*1.1,z_space+TF.r_cond*1.1)\r\nz_space = np.sort(z_space)\r\nt_space = TF.sketch(Nseg=Nseg)[1]\r\nT,Y,Z = np.meshgrid(t_space,y_space,z_space,indexing='ij')\r\nLcond = np.zeros(np.shape(T))\r\n\r\npl.figure(figsize=(12,10))\r\n\r\nfor ishift,shift in enumerate(TF.dp_pattern[::-1]):\r\n for icshift,cshift in enumerate([TF.shift_o,-TF.shift_o]):\r\n if (shift == TF.dp_pattern[0] or shift == TF.dp_pattern[-1]) \\\r\n and len(TF.dp_pattern) > 1:\r\n if (cshift < 0 and shift < 0) or (cshift > 0 and shift > 0):\r\n pattern = TF.pattern[:3]\r\n else:\r\n pattern = TF.pattern[:9]\r\n else:\r\n pattern = TF.pattern\r\n ipattern = np.arange(0,len(pattern),1)\r\n if cshift > 0:\r\n pattern = pattern[::-1]\r\n ipattern = ipattern[::-1]\r\n for ioffset,offset in zip(ipattern,pattern):\r\n r,t = TF.sketch(Nseg=100, offset=offset)[:2]\r\n dr,dt = np.diff(r),np.diff(t)\r\n dl = ((r[:-1]+dr/2)**2+(dr/dt)**2)**0.5*dt\r\n l = np.cumsum(dl)\r\n l = np.append(0,l)\r\n l += last\r\n last = l[-1]\r\n \r\n y_index = 2*ioffset\r\n z_index = 4*TF.Ndp-(4*ishift+2*icshift)-2\r\n Lcond[:,y_index:y_index+2,z_index:z_index+2] = np.transpose([[l,l],[l,l]])\r\n \r\n pl.plot(shift+cshift,offset-offset_o,'ro')\r\n pl.text(shift+cshift,offset-offset_o,' {:1d}'.format(Ncond))\r\n \r\n Ncond += 1\r\n \r\nLcond /= last\r\n \r\npl.pcolormesh(Z[99,:,:],Y[99,:,:],Lcond[99,:,:], shading='gouraud') \r\npl.plot(Z[0,:,:],Y[0,:,:],'kx')\r\npl.xlabel('shift, z [m]')\r\npl.ylabel('offset, y [m]')\r\npl.colorbar(orientation='horizontal')\r\n\r\npl.axis('equal')\r\npl.savefig('../Figs/conductor_map_color.png', dpi=400)\r\n\r\nNseg = 200\r\nro,t_space = TF.sketch(Nseg=Nseg)[:2]\r\noversample = np.max(ro)/((TF.pattern[-1]+2*TF.r_cond)-\r\n (TF.pattern[0]-2*TF.r_cond))\r\nradius,theta,dy = np.array([]),np.array([]),np.array([])\r\nfor offset in np.linspace(TF.pattern[0]-2*TF.r_cond,\r\n TF.pattern[-1]+2*TF.r_cond,Nseg):\r\n r,t = TF.sketch(Nseg=Nseg,offset=offset)[:2]\r\n radius = np.append(radius,r)\r\n theta = np.append(theta,t)\r\n dy = np.append(dy,offset-offset_o*np.ones(np.shape(t)))\r\n\r\nr_space = np.linspace(np.min(ro)+TF.pattern[0]-2*TF.r_cond,\r\n np.max(ro)+TF.pattern[-1]+2*TF.r_cond,\r\n np.ceil(oversample)*Nseg)\r\nR,T = np.meshgrid(r_space,t_space,indexing='ij')\r\ndY = griddata((radius,theta),dy,(R,T),method='linear')\r\ndY[np.isnan(dY)] = 0\r\n \r\npl.figure(figsize=(12,8))\r\npl.plot(R*np.sin(T),R*np.cos(T),'.')\r\npl.plot(ro*np.sin(t_space),ro*np.cos(t_space),'k-')\r\npl.axis('equal')\r\n\r\npl.figure(figsize=(12,8))\r\npl.pcolor(R,T,dY,cmap=cm.prism)\r\n\r\n'''\r\n# conformal map\r\nres = 100\r\nro,t,alpha_o = TF.sketch(offset=offset_o)\r\ndr,theta,y = np.array([]),np.array([]),np.array([])\r\n\r\nfor offset in np.linspace(-8*TF.pn,8*TF.pn,4*res):\r\n r,t = TF.sketch(offset=offset_o+offset)[:2]\r\n dr = np.append(dr,(r-ro)*np.cos(alpha_o))\r\n theta = np.append(theta,t)\r\n y = np.append(y,offset*np.ones(len(t)))\r\n\r\ndr_grid = np.linspace(-7*TF.pn,7*TF.pn, 2*res)\r\ntheta_grid = np.linspace(-np.pi, np.pi, 8*res)\r\nTheta,dR = np.meshgrid(theta_grid,dr_grid,indexing='ij')\r\n\r\nY = griddata((theta,dr),y,(Theta,dR),method='linear')\r\n\r\nfig = pl.figure(figsize=(12,8))\r\npl.pcolor(Theta,dR,Y,cmap=cm.prism)\r\npl.xlabel(r'Azimuth, $\\theta$ [rad]')\r\npl.ylabel(r'$\\Delta$r [m]')\r\npl.savefig('../Figs/deltaR_conformal_map.png', dpi=400)\r\n'''\r\n\r\n\r\n\r\nfilename = 'APDL/Dmap'\r\nhtc = table(filename)\r\nhtc.f.write('xcut='+'{:1.4f}'.format(TF.coil.xcut)+'\\n')\r\nhtc.f.write('Ncond='+'{:1d}'.format(Ncond)+'\\n')\r\nhtc.f.write('\\n')\r\nhtc.nop()\r\n\r\n#htc.load('r_ref', ro, [t])\r\n#htc.write(['theta'])\r\n\r\n#htc.load('alpha_ref', alpha_o, [t])\r\n#htc.write(['theta'])\r\n\r\nhtc.load('dy', dY, [r_space,t_space*180/np.pi])\r\nhtc.write(['X','Y'])\r\n\r\nhtc.load('Lcond', Lcond, [y_space,t_space,z_space])\r\nhtc.write(['dy','X','Z'])\r\n\r\nhtc.go()\r\nhtc.close()\r\n\r\n\r\n'''\r\npl.figure(figsize=(14,10))\r\npl.plot(radius*np.cos(theta), radius*np.sin(theta))\r\nfor i in range(1):\r\n pl.plot(TF.coil.TF['origin'][i][0],TF.coil.TF['origin'][i][1], 'ro')\r\n o,po,p1=TF.coil.read(sector=i+1,offset=offset)\r\n pl.plot(o[0],o[1],'bx')\r\n pl.plot(po[0],po[1],'kd')\r\n pl.plot(p1[0],p1[1],'mo')\r\n \r\npl.axis('equal')\r\npl.grid('on')\r\n\r\npl.figure(figsize=(14,10))\r\npl.plot(theta,radius, 'r-')\r\n#index = (theta>psi[0]) & (theta<=psi[1])\r\n#pl.plot(theta[index],alpha[index], 'bx-')\r\npl.grid('on')\r\n'''","sub_path":"etna/TFC_outline_old.py","file_name":"TFC_outline_old.py","file_ext":"py","file_size_in_byte":5397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"149277753","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# make database.pickle from id-mxxxxxx.pickle\n###############################################################################\n\n### import modules\nimport os\nimport argparse\nimport pickle\nimport pandas as pd\n\n\n### Arg-parser\nparser = argparse.ArgumentParser(\n description=\"\")\nparser.add_argument(\"--pkltxt\", default=None, help=\"pkl file path text name\")\nparser.add_argument(\"--savetxt\", default=None, help=\"save file path\")\nargs = parser.parse_args()\n\n\n### main\nwith open(args.pkltxt, 'r') as f:\n all_data_dir_lst = f.readlines()\n\nnew_data_path_lst = []\nfor data_path in all_data_dir_lst:\n new_data_path_lst.append(data_path.replace('\\n', ''))\n\nwith open(new_data_path_lst[0], 'rb') as f:\n data_init = pickle.load(f)\ndb_df = pd.DataFrame(index=data_init.keys()).T\n\nfor data_path in new_data_path_lst:\n print(data_path)\n with open(data_path, 'rb') as f:\n data_df = pickle.load(f)\n db_df = pd.concat([db_df, data_df])\n\nwith open(args.savetxt, mode='wb') as f:\n pickle.dump(db_df, f)\n","sub_path":"module/mkdatabase.py","file_name":"mkdatabase.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"12785556","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Spell', '0004_auto_20150202_2011'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='spell',\n name='cast_time',\n field=models.CharField(max_length=30, default='1 standard action'),\n preserve_default=False,\n ),\n ]\n","sub_path":"Spell/migrations/0005_spell_cast_time.py","file_name":"0005_spell_cast_time.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"417705269","text":"from cImage import *\nimport math\n\nmyWin = ImageWin(\"Class image\", 300, 300)\nimg = EmptyImage(300,300)\n\n\nblackPixel = Pixel(0,0,0)\nredPixel = Pixel(255,0,0)\n\n# diagonal pixels are colored black\nfor i in range(300):\n img.setPixel(i,i,blackPixel)\n img.setPixel(100,100,redPixel)\n\n#square\nfor col in range(100, 201):\n img.setPixel(100,col, redPixel)\n img.setPixel(200,col, redPixel)\n for row in range(100, 200):\n img.setPixel(row,100,redPixel)\n \n\n\n# displays the image\nimg.draw(myWin)\n\nmyWin.exitOnClick()\nimg.save(\"classImg.gif\")\n\nmyWin.exitOnClick()\n","sub_path":"CH6/ch6Line.py","file_name":"ch6Line.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"60250447","text":"\"\"\"\nSimple graph implementation\n\"\"\"\nfrom util import Stack, Queue # These may come in handy\n\nclass Graph:\n\n \"\"\"Represent a graph as a dictionary of vertices mapping labels to edges.\"\"\"\n def __init__(self):\n self.vertices = {}\n\n def add_vertex(self, vertex_id):\n \"\"\"\n Add a vertex to the graph.\n \"\"\"\n self.vertices[vertex_id] = set()\n\n def add_edge(self, v1, v2):\n \"\"\"\n Add a directed edge to the graph.\n \"\"\"\n self.vertices[v1].add(v2)\n def get_neighbors(self, vertex_id):\n \"\"\"\n Get all neighbors (edges) of a vertex.\n \"\"\"\n return self.vertices[vertex_id]\n\n def bft(self, starting_vertex):\n \"\"\"\n Print each vertex in breadth-first order\n beginning from starting_vertex.\n \"\"\"\n # establish a queue\n q = Queue()\n # add starting vertex to queue\n q.enqueue([starting_vertex])\n # create a set of vertexes visited\n visited = set()\n # until queue is empty\n while q.size() > 0:\n # set current_vertex to the first item in the queue\n path = q.dequeue()\n current_vertex = path[-1] \n if current_vertex not in visited:\n # if the current_vertex hasn't been visited, print it and add it to visited\n print(current_vertex)\n visited.add(current_vertex)\n # enqueue all of the neighbors\n for vertex in self.get_neighbors(current_vertex):\n new_path = path + [vertex]\n q.enqueue(new_path)\n def dft(self, starting_vertex):\n \"\"\"\n Print each vertex in depth-first order\n beginning from starting_vertex.\n \"\"\"\n # establish a stack\n s = Stack()\n # add starting vertex to stack\n s.push(starting_vertex)\n # create a set of vertexes visited\n visited = set()\n # until stack is empty\n while s.size() > 0:\n # set current_vertex to the last item in the stack\n current_vertex = s.pop()\n if current_vertex not in visited:\n # if the current_vertex hasn't been visited, print it and add it to visited\n print(current_vertex)\n visited.add(current_vertex)\n # add all of the neighbors to the stack\n for vertex in self.get_neighbors(current_vertex):\n s.push(vertex) \n \n def dft_recursive_utils(self, v, visited):\n # add a the vertex to the visited set and print it\n visited[v[-1]] = True\n print(v[-1])\n # if it's been visited, don't do anything \n for vertex in self.get_neighbors(v[-1]):\n if visited[vertex] == False:\n # otherwise, plug neighbors into recursion\n self.dft_recursive_utils(v + [vertex], visited)\n def dft_recursive(self, starting_vertex):\n \"\"\"\n Print each vertex in depth-first order\n beginning from starting_vertex.\n\n This should be done using recursion.\n \"\"\"\n # created a False entry for all vertexes\n visited = {}\n for vertex in self.vertices:\n visited[vertex] = False\n # print(visited) \n self.dft_recursive_utils([starting_vertex], visited)\n def bfs(self, starting_vertex, destination_vertex):\n \"\"\"\n Return a list containing the shortest path from\n starting_vertex to destination_vertex in\n breath-first order.\n \"\"\"\n # establish a queue\n q = Queue()\n # add starting vertex to queue\n q.enqueue([starting_vertex])\n # create a set of vertexes visited\n visited = set()\n # until queue is empty\n while q.size() > 0:\n # set current_vertex to the first item in the queue\n path = q.dequeue()\n current_vertex = path[-1] \n if current_vertex not in visited:\n # if the current_vertex hasn't been visited, print it and add it to visited\n visited.add(current_vertex)\n # enqueue all of the neighbors\n for vertex in self.get_neighbors(current_vertex):\n new_path = path + [vertex]\n q.enqueue(new_path)\n if current_vertex == destination_vertex:\n return path\n \n def dfs(self, starting_vertex, destination_vertex):\n \"\"\"\n Return a list containing the shortest path from\n starting_vertex to destination_vertex in\n breath-first order.\n \"\"\"\n # establish a stack\n s = Stack()\n # add starting vertex to stack\n s.push([starting_vertex])\n # create a set of vertexes visited\n visited = set()\n # until stack is empty\n while s.size() > 0:\n # set current_vertex to the first item in the stack\n path = s.pop()\n current_vertex = path[-1] \n if current_vertex not in visited:\n # if the current_vertex hasn't been visited, print it and add it to visited\n visited.add(current_vertex)\n # enqueue all of the neighbors\n for vertex in self.get_neighbors(current_vertex):\n new_path = path + [vertex]\n s.push(new_path)\n if current_vertex == destination_vertex:\n return path \n \n def dfs_recursive_utils(self, v, visited, destination_vertex, finalanswer=False):\n \n # add a the vertex to the visited set and print it\n visited[v[-1]] = True\n # if it's been visited, don't do anything \n if v[-1] == destination_vertex:\n finalanswer = v\n return v\n elif v[-1] != destination_vertex:\n for vertex in self.get_neighbors(v[-1]):\n if visited[vertex] == False:\n # otherwise, plug neighbors into recursion\n result = self.dfs_recursive_utils(v + [vertex], visited, destination_vertex, )\n if result:\n return result\n def dfs_recursive(self, starting_vertex, destination_vertex):\n \"\"\"\n Print each vertex in depth-first order\n beginning from starting_vertex.\n\n This should be done using recursion.\n \"\"\"\n # created a False entry for all vertexes\n visited = {}\n for vertex in self.vertices:\n visited[vertex] = False\n # print(visited) \n return self.dfs_recursive_utils([starting_vertex], visited, destination_vertex)\n\nif __name__ == '__main__':\n graph = Graph() # Instantiate your graph\n # https://github.com/LambdaSchool/Graphs/blob/master/objectives/breadth-first-search/img/bfs-visit-order.png\n graph.add_vertex(1)\n graph.add_vertex(2)\n graph.add_vertex(3)\n graph.add_vertex(4)\n graph.add_vertex(5)\n graph.add_vertex(6)\n graph.add_vertex(7)\n graph.add_edge(5, 3)\n graph.add_edge(6, 3)\n graph.add_edge(7, 1)\n graph.add_edge(4, 7)\n graph.add_edge(1, 2)\n graph.add_edge(7, 6)\n graph.add_edge(2, 4)\n graph.add_edge(3, 5)\n graph.add_edge(2, 3)\n graph.add_edge(4, 6)\n\n '''\n Should print:\n {1: {2}, 2: {3, 4}, 3: {5}, 4: {6, 7}, 5: {3}, 6: {3}, 7: {1, 6}}\n '''\n # print(graph.vertices)\n\n '''\n Valid BFT paths:\n 1, 2, 3, 4, 5, 6, 7\n 1, 2, 3, 4, 5, 7, 6\n 1, 2, 3, 4, 6, 7, 5\n 1, 2, 3, 4, 6, 5, 7\n 1, 2, 3, 4, 7, 6, 5\n 1, 2, 3, 4, 7, 5, 6\n 1, 2, 4, 3, 5, 6, 7\n 1, 2, 4, 3, 5, 7, 6\n 1, 2, 4, 3, 6, 7, 5\n 1, 2, 4, 3, 6, 5, 7\n 1, 2, 4, 3, 7, 6, 5\n 1, 2, 4, 3, 7, 5, 6\n '''\n # graph.bft(1)\n\n '''\n Valid DFT paths:\n 1, 2, 3, 5, 4, 6, 7\n 1, 2, 3, 5, 4, 7, 6\n 1, 2, 4, 7, 6, 3, 5\n 1, 2, 4, 6, 3, 5, 7\n '''\n # graph.dft(1)\n # graph.dft_recursive(1)\n\n '''\n Valid BFS path:\n [1, 2, 4, 6]\n '''\n # print(graph.bfs(1, 6))\n\n '''\n Valid DFS paths:\n [1, 2, 4, 6]\n [1, 2, 4, 7, 6]\n '''\n # print(graph.dfs(1, 6))\n print(graph.dfs_recursive(1, 6))\n print(dir(Graph))","sub_path":"projects/graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"186241283","text":"\"\"\"\nDefinition of views.\n\"\"\"\n\nfrom django.shortcuts import render, render_to_response\nfrom django.http import HttpRequest, HttpResponse, HttpResponseRedirect\nfrom django.template import RequestContext\nfrom datetime import datetime, timedelta\nfrom django.db.models import *\nfrom app.models import *\n\ndef home(request):\n \"\"\"Renders the home page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/index.html',\n context_instance = RequestContext(request,\n {\n 'title':'Welcome',\n 'year':datetime.now().year\n })\n )\n\ndef managerhome(request):\n projectlist = Project.objects.all()\n return render_to_response('app/managerhome.html', {'projectlist': projectlist},\n context_instance = RequestContext(request,\n {\n 'title':'Home',\n 'year':datetime.now().year\n }))\n\ndef createproject(request):\n if request.method == 'GET':\n form = ProjectForm()\n return render(request, 'app/create.html', {'form': form})\n elif request.method == 'POST':\n form = ProjectForm(request.POST)\n form.save()\n return HttpResponseRedirect('/manager')\n\ndef createiteration(request):\n if request.method == 'GET':\n form = IterationForm()\n return render(request, 'app/create.html', {'form': form})\n elif request.method == 'POST':\n form = IterationForm(request.POST)\n form.save()\n return HttpResponseRedirect('/project/analysis/%s' %pid)\n\ndef itrdetail(request, iterid):\n itr = Iteration.objects.get(pk=iterid)\n if request.method == 'GET':\n form = SLOCForm()\n return render_to_response('app/iterationdetail.html',{'itr': itr, 'form': form},\n context_instance = RequestContext(request,\n {\n 'title':'Iteration Detail',\n 'year':datetime.now().year\n }))\n elif request.method == 'POST':\n form = SLOCForm(request.POST)\n if form.is_valid():\n itr.sloc = form.cleaned_data['sloc']\n itr.save()\n return HttpResponseRedirect('/project/analysis/%s' %itr.projectid)\n\n\ndef projectanalysis(request, pid):\n project = Project.objects.get(pk=pid)\n developers = project.developers.all()\n developerno = project.developers.count()\n slocsum = Iteration.objects.filter(projectid = pid).aggregate(Sum(\"sloc\"))\n\n inception = Iteration.objects.filter(projectid=pid,phrase='inception')\n elaboration = Iteration.objects.filter(projectid=pid,phrase='elaboration')\n construction = Iteration.objects.filter(projectid=pid,phrase='construction')\n translation = Iteration.objects.filter(projectid=pid,phrase='translation')\n return render_to_response('app/projectanalysis.html',{'project':project, 'slocsum':slocsum, 'developerno':developerno, 'developers':developers, 'inception':inception, 'elaboration':elaboration, 'construction':construction, 'translation':translation},\n context_instance = RequestContext(request,\n {\n 'title':'Analysis',\n 'year':datetime.now().year\n }))\n\ndef editproject(request, pid):\n project = Project.objects.get(pk=pid)\n developers = project.developers.all()\n if request.method == 'GET':\n return render_to_response('app/editproject.html',{'project':project, 'developers':developers},\n context_instance = RequestContext(request,\n {\n 'title':'Edit',\n 'year':datetime.now().year\n }))\n elif request.method == 'POST':\n form = EditProjectForm(request.POST)\n if form.is_valid():\n project = Project.objects.get(pk=pid)\n project.name = form.cleaned_data['name']\n project.phase = form.cleaned_data['phase']\n project.iterations = form.cleaned_data['iterations']\n project.expectedsloc = form.cleaned_data['expectedsloc']\n project.save()\n return HttpResponseRedirect('/manager')\n\ndef developers(request):\n developers = Developer.objects.all()\n return render_to_response('app/developerlist.html',{'developers':developers},\n context_instance = RequestContext(request,\n {\n 'title':'Login',\n 'year':datetime.now().year\n }))\n\ndef developerhome(request, workerid):\n projects = Project.objects.filter(developers__workerid=workerid)\n return render_to_response('app/developerhome.html',{'projects':projects},\n context_instance = RequestContext(request,\n {\n 'title':'Home',\n 'year':datetime.now().year\n }))\n\ndef projectdetail(request, pid):\n project = Project.objects.get(pk=pid)\n inception = Iteration.objects.filter(projectid=pid,phrase='inception')\n elaboration = Iteration.objects.filter(projectid=pid,phrase='elaboration')\n construction = Iteration.objects.filter(projectid=pid,phrase='construction')\n translation = Iteration.objects.filter(projectid=pid,phrase='translation')\n if request.method == 'GET':\n form = DefectForm()\n return render_to_response('app/projectdetail.html',{'form':form, 'project':project, 'inception':inception, 'elaboration':elaboration, 'construction':construction, 'translation':translation},\n context_instance = RequestContext(request,\n {\n 'title':'Phrases and Iterations',\n 'year':datetime.now().year\n }))\n elif request.method == 'POST':\n form = DefectForm(request.POST)\n if form.is_valid():\n defect = Defect(description = form.cleaned_data['description'], founditer = form.cleaned_data['founditer'], removediter = form.cleaned_data['removediter'])\n defect.save()\n print(defect)\n return HttpResponseRedirect('/project/%s' %pid)\n\n\ndef iterationpage(request, iterid):\n iteration = Iteration.objects.get(pk=iterid)\n project = Project.objects.get(pk=iteration.projectid)\n displayhour = int(iteration.timecost/3600)\n displaymin = int((iteration.timecost - displayhour*3600)/60)\n displaysec = int(iteration.timecost - displayhour*3600 - displaymin*60)\n return render_to_response('app/iteration.html', {'iteration':iteration, 'project':project,'displayhour':displayhour, 'displaymin':displaymin, 'displaysec':displaysec},\n context_instance = RequestContext(request,\n {\n 'title':'Iteration detail',\n 'year':datetime.now().year\n }))\n\ndef startitimer(request, iterid):\n iteration = Iteration.objects.get(pk=iterid)\n project = Project.objects.get(pk=iteration.projectid)\n start = datetime.now()\n iteration.laststart = start\n iteration.save()\n return HttpResponseRedirect('/project/iteration/%s/timer' % iterid)\n\ndef itertimer(request, iterid):\n iteration = Iteration.objects.get(pk=iterid)\n project = Project.objects.get(pk=iteration.projectid)\n return render_to_response('app/itertimer.html', {'iteration':iteration, 'project':project},\n context_instance = RequestContext(request,\n {\n 'title':'Timer',\n 'year':datetime.now().year\n }))\n\ndef enditimer(request, iterid):\n iteration = Iteration.objects.get(pk=iterid)\n project = Project.objects.get(pk=iteration.projectid)\n end = datetime.now()\n start = iteration.laststart\n hour = end.hour - start.hour\n min = end.minute - start.minute\n sec = end.second - start.second\n iteration.lastend = end\n iteration.timecost += hour*3600 + min*60 + sec\n project.totaltime += hour*3600 + min*60 + sec\n iteration.save()\n project.save()\n return HttpResponseRedirect('/project/iteration/%s' % iterid)\n","sub_path":"PDT/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"161779564","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright 2012 New Dream Network, LLC (DreamHost)\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n# @author Mark McClain (DreamHost)\n\nimport sys\n\nimport mock\nimport unittest2 as unittest\n\nfrom quantum.db import migration\nfrom quantum.db.migration import cli\n\n\nclass TestDbMigration(unittest.TestCase):\n def test_should_run_plugin_in_list(self):\n self.assertTrue(migration.should_run('foo', ['foo', 'bar']))\n self.assertFalse(migration.should_run('foo', ['bar']))\n\n def test_should_run_plugin_wildcard(self):\n self.assertTrue(migration.should_run('foo', ['*']))\n\n\nclass TestMain(unittest.TestCase):\n def setUp(self):\n self.process_argv_p = mock.patch.object(cli, 'process_argv')\n self.process_argv = self.process_argv_p.start()\n\n self.alembic_cmd_p = mock.patch.object(cli, 'alembic_command')\n self.alembic_cmd = self.alembic_cmd_p.start()\n\n def tearDown(self):\n self.alembic_cmd_p.stop()\n self.process_argv_p.stop()\n\n def test_main(self):\n self.process_argv.return_value = ('foo', ('bar', ), {'baz': 1})\n cli.main()\n\n self.process_argv.assert_called_once_with(sys.argv)\n self.alembic_cmd.foo.assert_called_once_with(mock.ANY, 'bar', baz=1)\n\n\nclass TestDatabaseSync(unittest.TestCase):\n def test_process_argv_stamp(self):\n self.assertEqual(\n ('stamp', ('foo',), {'sql': False}),\n cli.process_argv(['prog', 'stamp', 'foo']))\n\n self.assertEqual(\n ('stamp', ('foo',), {'sql': True}),\n cli.process_argv(['prog', 'stamp', '--sql', 'foo']))\n\n def test_process_argv_current(self):\n self.assertEqual(\n ('current', (), {}),\n cli.process_argv(['prog', 'current']))\n\n def test_process_argv_history(self):\n self.assertEqual(\n ('history', (), {}),\n cli.process_argv(['prog', 'history']))\n\n def test_process_argv_check_migration(self):\n self.assertEqual(\n ('branches', (), {}),\n cli.process_argv(['prog', 'check_migration']))\n\n def test_database_sync_revision(self):\n expected = (\n 'revision',\n (),\n {'message': 'message', 'sql': False, 'autogenerate': True}\n )\n\n self.assertEqual(\n cli.process_argv(\n ['prog', 'revision', '-m', 'message', '--autogenerate']\n ),\n expected\n )\n\n def test_database_sync_upgrade(self):\n self.assertEqual(\n cli.process_argv(['prog', 'upgrade', 'head']),\n ('upgrade', ('head', ), {'sql': False})\n )\n\n self.assertEqual(\n cli.process_argv(['prog', 'upgrade', '--delta', '3']),\n ('upgrade', ('+3', ), {'sql': False})\n )\n\n def test_database_sync_downgrade(self):\n self.assertEqual(\n cli.process_argv(['prog', 'downgrade', 'folsom']),\n ('downgrade', ('folsom', ), {'sql': False})\n )\n\n self.assertEqual(\n cli.process_argv(['prog', 'downgrade', '--delta', '2']),\n ('downgrade', ('-2', ), {'sql': False})\n )\n","sub_path":"quantum/tests/unit/test_db_migration.py","file_name":"test_db_migration.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"548225622","text":"# Copyright 2013 – present by the SalishSeaCast Project Contributors\n# and The University of British Columbia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# SPDX-License-Identifier: Apache-2.0\n\n\n\"\"\"SalishSeaCmd prepare sub-command plug-in unit tests\n\"\"\"\nfrom pathlib import Path\nfrom unittest.mock import call, Mock, patch\n\nimport cliff.app\nimport nemo_cmd.prepare\nimport pytest\n\nimport salishsea_cmd.prepare\n\n\n@pytest.fixture\ndef prepare_cmd():\n return salishsea_cmd.prepare.Prepare(Mock(spec=cliff.app.App), [])\n\n\nclass TestParser:\n \"\"\"Unit tests for `salishsea prepare` sub-command command-line parser.\"\"\"\n\n def test_get_parser(self, prepare_cmd):\n parser = prepare_cmd.get_parser(\"salishsea prepare\")\n assert parser.prog == \"salishsea prepare\"\n\n def test_parsed_args_defaults(self, prepare_cmd):\n parser = prepare_cmd.get_parser(\"salishsea prepare\")\n parsed_args = parser.parse_args([\"foo\"])\n assert parsed_args.desc_file == Path(\"foo\")\n assert not parsed_args.quiet\n\n @pytest.mark.parametrize(\"flag, attr\", [(\"-q\", \"quiet\"), (\"--quiet\", \"quiet\")])\n def test_parsed_args_flags(self, flag, attr, prepare_cmd):\n parser = prepare_cmd.get_parser(\"salishsea prepare\")\n parsed_args = parser.parse_args([\"foo\", flag])\n assert getattr(parsed_args, attr)\n\n\n@patch(\"nemo_cmd.prepare.load_run_desc\")\n@patch(\"nemo_cmd.prepare.check_nemo_exec\", return_value=\"nemo_bin_dir\")\n@patch(\"nemo_cmd.prepare.check_xios_exec\", return_value=\"xios_bin_dir\")\n@patch(\"nemo_cmd.api.find_rebuild_nemo_script\")\n@patch(\"nemo_cmd.resolved_path\")\n@patch(\"nemo_cmd.prepare.make_run_dir\")\n@patch(\"nemo_cmd.prepare.make_namelists\")\n@patch(\"nemo_cmd.prepare.copy_run_set_files\")\n@patch(\"nemo_cmd.prepare.make_executable_links\")\n@patch(\"nemo_cmd.prepare.make_grid_links\")\n@patch(\"nemo_cmd.prepare.make_forcing_links\")\n@patch(\"nemo_cmd.prepare.make_restart_links\")\n@patch(\"salishsea_cmd.prepare._record_vcs_revisions\")\n@patch(\"nemo_cmd.prepare.add_agrif_files\")\nclass TestPrepare:\n \"\"\"Unit tests for `salishsea prepare` prepare() function.\"\"\"\n\n def test_prepare(\n self,\n m_aaf,\n m_rvr,\n m_mrl,\n m_mfl,\n m_mgl,\n m_mel,\n m_crsf,\n m_mnl,\n m_mrd,\n m_resolved_path,\n m_frns,\n m_cxe,\n m_cne,\n m_lrd,\n ):\n run_dir = salishsea_cmd.prepare.prepare(\n Path(\"SalishSea.yaml\"), nocheck_init=False\n )\n m_lrd.assert_called_once_with(Path(\"SalishSea.yaml\"))\n m_cne.assert_called_once_with(m_lrd())\n m_cne.assert_called_once_with(m_lrd())\n m_frns.assert_called_once_with(m_lrd())\n m_resolved_path.assert_called_once_with(Path(\"SalishSea.yaml\"))\n m_mrd.assert_called_once_with(m_lrd())\n m_mnl.assert_called_once_with(m_resolved_path().parent, m_lrd(), m_mrd())\n m_crsf.assert_called_once_with(\n m_lrd(), Path(\"SalishSea.yaml\"), m_resolved_path().parent, m_mrd()\n )\n m_mel.assert_called_once_with(\"nemo_bin_dir\", m_mrd(), \"xios_bin_dir\")\n m_mgl.assert_called_once_with(m_lrd(), m_mrd())\n m_mfl.assert_called_once_with(m_lrd(), m_mrd())\n m_mrl.assert_called_once_with(m_lrd(), m_mrd(), False)\n m_aaf.assert_called_once_with(\n m_lrd(), Path(\"SalishSea.yaml\"), m_resolved_path().parent, m_mrd(), False\n )\n m_rvr.assert_called_once_with(m_lrd(), m_mrd())\n assert run_dir == m_mrd()\n\n\nclass TestRecordVCSRevisions:\n \"\"\"Unit tests for `salishsea prepare` _record_vcs_revisions() function.\"\"\"\n\n def test_no_paths_forcing_key(self):\n run_desc = {}\n with pytest.raises(SystemExit):\n salishsea_cmd.prepare._record_vcs_revisions(run_desc, Path(\"run_dir\"))\n\n @pytest.mark.parametrize(\n \"config_name_key, nemo_code_config_key\",\n [(\"config name\", \"NEMO code config\"), (\"config_name\", \"NEMO-code-config\")],\n )\n @patch(\"nemo_cmd.prepare.write_repo_rev_file\")\n def test_write_repo_rev_file_default_calls(\n self, m_write, config_name_key, nemo_code_config_key, tmpdir\n ):\n nemo_code_repo = tmpdir.ensure_dir(\"NEMO-3.6-code\")\n nemo_config = nemo_code_repo.ensure_dir(\"NEMOGCM\", \"CONFIG\")\n xios_code_repo = tmpdir.ensure_dir(\"XIOS\")\n run_desc = {\n config_name_key: \"SalishSea\",\n \"paths\": {\n nemo_code_config_key: str(nemo_config),\n \"XIOS\": str(xios_code_repo),\n },\n }\n salishsea_cmd.prepare._record_vcs_revisions(run_desc, Path(\"run_dir\"))\n assert m_write.call_args_list == [\n call(\n Path(str(nemo_code_repo)),\n Path(\"run_dir\"),\n nemo_cmd.prepare.get_git_revision,\n ),\n call(\n Path(str(xios_code_repo)),\n Path(\"run_dir\"),\n nemo_cmd.prepare.get_git_revision,\n ),\n ]\n\n @pytest.mark.parametrize(\n \"config_name_key, nemo_code_config_key\",\n [(\"config name\", \"NEMO code config\"), (\"config_name\", \"NEMO-code-config\")],\n )\n @patch(\"nemo_cmd.prepare.write_repo_rev_file\")\n def test_write_repo_rev_file_vcs_revisions_hg_call(\n self, m_write, config_name_key, nemo_code_config_key, tmpdir\n ):\n nemo_config = tmpdir.ensure_dir(\"NEMO-3.6-code\", \"NEMOGCM\", \"CONFIG\")\n xios_code_repo = tmpdir.ensure_dir(\"XIOS\")\n nemo_forcing = tmpdir.ensure_dir(\"NEMO-forcing\")\n ss_run_sets = tmpdir.ensure_dir(\"SS-run-sets\")\n run_desc = {\n config_name_key: \"SalishSea\",\n \"paths\": {\n nemo_code_config_key: str(nemo_config),\n \"XIOS\": str(xios_code_repo),\n \"forcing\": str(nemo_forcing),\n },\n \"vcs revisions\": {\"hg\": [str(ss_run_sets)]},\n }\n salishsea_cmd.prepare._record_vcs_revisions(run_desc, Path(\"run_dir\"))\n assert m_write.call_args_list[-1] == call(\n Path(str(ss_run_sets)), Path(\"run_dir\"), nemo_cmd.prepare.get_hg_revision\n )\n\n @pytest.mark.parametrize(\n \"config_name_key, nemo_code_config_key\",\n [(\"config name\", \"NEMO code config\"), (\"config_name\", \"NEMO-code-config\")],\n )\n @patch(\"nemo_cmd.prepare.write_repo_rev_file\")\n def test_write_repo_rev_file_vcs_revisions_git_call(\n self, m_write, config_name_key, nemo_code_config_key, tmpdir\n ):\n nemo_config = tmpdir.ensure_dir(\"NEMO-3.6-code\", \"NEMOGCM\", \"CONFIG\")\n xios_code_repo = tmpdir.ensure_dir(\"XIOS\")\n nemo_forcing = tmpdir.ensure_dir(\"NEMO-forcing\")\n ss_run_sets = tmpdir.ensure_dir(\"SS-run-sets\")\n run_desc = {\n config_name_key: \"SalishSea\",\n \"paths\": {\n nemo_code_config_key: str(nemo_config),\n \"XIOS\": str(xios_code_repo),\n \"forcing\": str(nemo_forcing),\n },\n \"vcs revisions\": {\"git\": [str(ss_run_sets)]},\n }\n salishsea_cmd.prepare._record_vcs_revisions(run_desc, Path(\"run_dir\"))\n assert m_write.call_args_list[-1] == call(\n Path(str(ss_run_sets)), Path(\"run_dir\"), nemo_cmd.prepare.get_git_revision\n )\n","sub_path":"tests/test_prepare.py","file_name":"test_prepare.py","file_ext":"py","file_size_in_byte":7760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"4083443","text":"#!/usr/bin/env python3\nfrom mpi4py import MPI\nimport requests\nfrom re import findall\nimport sys\ndef googleSearch(query, date):\n #company to search\n default = \"https://www.google.com/search?q=\" + query.replace(' ', '+')\n #site addition\n default += \"+site%3A\" + \"bloomberg.com\" #specify site\n default += \"&lr=lang_en\" #specify language\n default += \"&num=20\" #gets top 20\n default += \"&as_qdr=all&source=lnt\"\n\n date = date.split()\n\n\n default += \"&tbs=lr%3Alang_1en%2Ccdr%3A1%2Ccd_min\" \\\n + \"%3A\" + date[0] + \"%2F\" + date[1] + \"%2F\" + date[2] \\\n + \"%2Ccd_max\" \\\n + \"%3A\" + date[0] + \"%2F\" + date[1] + \"%2F\" + date[2] \\\n + \"&tbm=\"\n\n\n\n ua = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'}\n response = requests.get(default, headers=ua)\n\n return findall(r'href=\"(https://www.bloomberg.com/[^\"]+)\"',response.text)\n\ndef searchWith(date):\n for query in [\"google\", \"alphabet\"]:\n print('Searching for \\\"%s\\\" on %s'%(query, date))\n result = [date, [], [], []]\n for url in googleSearch(query, date):\n if '/videos/' in url: result[3].append(url)\n elif query.lower() not in url.lower(): result[2].append(url)\n else: result[1].append(url)\n return result\n\nfrom datetime import timedelta, date\ndef dateRange(start, end):\n for day in range(int((end - start).days)):\n yield start + timedelta(day)\n\n# generate dates in certain range\nsearchDates = [d.strftime('%m %d %Y') for d in dateRange(date(2011,1,1), date(2017,3,1))]\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nprocs = comm.Get_size()\n\nsegmentSize = float(len(searchDates))/procs\n\nbegin = int(segmentSize*rank)\nstop = int(segmentSize*(rank + 1))\nif rank + 1 == procs: stop = len(searchDates)\n\nresults = [searchWith(searchDates[x]) for x in range(begin,stop)]\n\n\nif rank:\n comm.send(results, dest=0, tag=1)\nelse:\n #This collects them in order\n for i in range(1, procs):\n results += comm.recv(source=i, tag=1)\n import csv\n with open('../articles/good.csv', 'w') as csvfile:\n writer = csv.writer(csvfile, quotechar='|')\n for row in results:\n writer.writerow([row[0]] + row[1])\n with open('../articles/bad.csv', 'w') as csvfile:\n writer = csv.writer(csvfile, quotechar='|')\n for row in results:\n writer.writerow([row[0]] + row[2])\n with open('../articles/ugly.csv', 'w') as csvfile:\n writer = csv.writer(csvfile, quotechar='|')\n for row in results:\n writer.writerow([row[0]] + row[3])\n","sub_path":"scripts/getArticles.py","file_name":"getArticles.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"250680780","text":"import numpy as np\nimport re, math\nfrom copy import deepcopy \nfrom functools import partial\nfrom kivy.uix.widget import Widget\nfrom kivy.properties import ListProperty\nfrom kivy.graphics import Color, Line, Rectangle, Ellipse, InstructionGroup\nfrom kivy.clock import Clock\nfrom bisect import bisect, insort\n# Librerias propias\nfrom pytikzgenerate.modulos.submodulos.base_pytikz import BasePytikz\nfrom pytikzgenerate.modulos.submodulos.validadores import Validadores\nfrom pytikzgenerate.modulos.submodulos.validador_pytikz.relleno import Relleno\nfrom pytikzgenerate.modulos.submodulos.validador_pytikz.relleno_lineas_libre import RellenoLineasLibre\nfrom pytikzgenerate.modulos.submodulos.validador_pytikz.guardar_dibujo_en_formato import GuardarDibujoEnImagen\nfrom pytikzgenerate.modulos.submodulos.evaluar import Evaluar\nfrom .transpilador import Transpilador\n\nclass ValidadorPytikz(BasePytikz):\n \n def __init__(self,area_de_dibujar):\n self.area_de_dibujar = area_de_dibujar\n self.guardar_dibujo_en_imagen = GuardarDibujoEnImagen(self.area_de_dibujar)\n self.comandos_pytikz_depurado = []\n self.mensajes_de_error = []\n self.estilo_global_local = {}\n self.comandos_global = {}\n #Utilizado para las animaciones\n self.index_animacion = 0\n #Utilizado para identificar que numero de comando segun orden tiene error.\n self.linea_de_comando = 1\n #Instanciar clases modulos.submodulos\n self.evaluar = Evaluar()\n\n def validar_pytikz(self):\n for comando_pytikz in self.comandos_pytikz_depurado:\n if(len(self.mensajes_de_error)>0):\n error = {\"error\":self.mensajes_de_error}\n return error\n nombre_comando = comando_pytikz[0]\n if nombre_comando in self.COMANDOS_DIBUJAR_PYTIKZ:\n parametros_comando = comando_pytikz[1]\n draw_posicion = comando_pytikz[2]\n figuras = comando_pytikz[3]\n funcion_de_figura = comando_pytikz[4]\n self.__validar_dibujar(nombre_comando,parametros_comando,draw_posicion,figuras,funcion_de_figura,self.area_de_dibujar)\n elif nombre_comando in self.COMANDOS_VARIABLES_PYTIKZ:\n funcion_de_comando = comando_pytikz[1]\n parametros_comando = comando_pytikz[2]\n self.__validar_variables_tikz(nombre_comando,funcion_de_comando,parametros_comando)\n else:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": El comando '\"+nombre_comando+\"' no esta registrado en el sistema o no existe.\")\n self.linea_de_comando+=1\n if(len(self.mensajes_de_error)>0):\n error = {\"error\":self.mensajes_de_error}\n return error\n\n def __validar_dibujar(self,nombre_comando,parametros_comando,draw_posicion,figuras,funcion_de_figura,area_de_dibujar,habilitado_generar_figura_en_formato={}):\n #Estilos predeterminados\n self.degradients = {}\n self.style = {}\n self.fill = (1,1,1) if nombre_comando == \"draw\" or nombre_comando == \"shade\" else (0,0,0) if nombre_comando == \"fill\" else (0,0,0)\n self.draw = (0,0,0) if nombre_comando == \"draw\" or nombre_comando == \"shade\" else (1,1,1) if nombre_comando == \"fill\" else (0,0,0)\n self.tipo_de_linea = \"\"\n self.line_width = 1.0\n #Estilos sujeto a cambio debido a parametros definidos en comando.\n estilos_predeterminados = {\n \"fill\":self.fill,\n \"draw\":self.draw,\n \"degradients\":self.degradients,\n \"tipo_de_linea\":self.tipo_de_linea,\n \"line_width\":self.line_width,\n \"style\":self.style\n }\n self.validadores = Validadores(estilos_predeterminados)\n indice = 0\n\n #VALIDA LOS ESTILOS DEL COMANDO, SI TIENE UNIDADES METRICAS VALIDOS LO CONVIERTE A FLOAT, LOS COLORES SON TRANSFORMADOS AL CODIGO DE COLOR QUE MANEJA KIVY.\n for parametro in parametros_comando:\n tupla_validada = False\n diccionario_validada = False\n #Explorar por []\n if indice == 0:\n for estilo in parametro:\n estilo = estilo.strip()\n #Si el estilo coincide con el nombre de una variable, utilizar los estilos de esa variable en la figura en cuestion...\n if estilo in list(self.estilo_global_local.keys()):\n parametros_estilo_global_local = self.estilo_global_local[estilo]\n indice_estilo_global_local = 0\n for parametro_estilo_global_local in parametros_estilo_global_local:\n #Explorar por []\n if indice_estilo_global_local == 0:\n array_estilos_validados = self.validadores.validar_estilos(\"tupla\",parametro_estilo_global_local)\n mensajes_de_error_generados = array_estilos_validados[len(array_estilos_validados)-1]\n if not len(mensajes_de_error_generados):\n self.degradients = array_estilos_validados[0]\n self.fill = array_estilos_validados[1]\n self.draw = array_estilos_validados[2]\n self.tipo_de_linea = array_estilos_validados[3]\n self.line_width = array_estilos_validados[4]\n self.style = array_estilos_validados[5]\n else:\n indice = 0\n for mensaje_de_error_generado in mensajes_de_error_generados:\n mensajes_de_error_generados[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n self.mensajes_de_error.extend(mensajes_de_error_generados)\n #Explorar por {}\n elif indice_estilo_global_local == 1:\n #Recorrer keys de {}\n keys_diccionario = list(parametro_estilo_global_local.keys())\n array_estilos_validados = self.validadores.validar_estilos(\"diccionario\",keys_diccionario,parametro_estilo_global_local)\n mensajes_de_error_generados = array_estilos_validados[len(array_estilos_validados)-1]\n if not len(mensajes_de_error_generados):\n self.degradients = array_estilos_validados[0]\n self.fill = array_estilos_validados[1]\n self.draw = array_estilos_validados[2]\n self.tipo_de_linea = array_estilos_validados[3]\n self.line_width = array_estilos_validados[4]\n self.style = array_estilos_validados[5]\n else:\n indice = 0\n for mensaje_de_error_generado in mensajes_de_error_generados:\n mensajes_de_error_generados[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n self.mensajes_de_error.extend(mensajes_de_error_generados)\n indice_estilo_global_local+=1\n #Si no es el caso\n elif not tupla_validada:\n array_estilos_validados = self.validadores.validar_estilos(\"tupla\",parametro)\n mensajes_de_error_generados = array_estilos_validados[len(array_estilos_validados)-1]\n if not len(mensajes_de_error_generados):\n self.degradients = array_estilos_validados[0]\n self.fill = array_estilos_validados[1]\n self.draw = array_estilos_validados[2]\n self.tipo_de_linea = array_estilos_validados[3]\n self.line_width = array_estilos_validados[4]\n self.style = array_estilos_validados[5]\n else:\n indice = 0\n for mensaje_de_error_generado in mensajes_de_error_generados:\n mensajes_de_error_generados[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n self.mensajes_de_error.extend(mensajes_de_error_generados)\n tupla_validada = True\n #Explorar por {}\n elif indice == 1:\n #Recorrer keys de {}\n keys_diccionario = list(parametro.keys())\n for key in keys_diccionario:\n key_original = key\n key = key.strip()\n #Si se quiere establecer los parametros a una variable global o local, para aplicar luego los estilos de la variable a la figura en cuestion.\n if key in list(self.estilo_global_local.keys()):\n # print(\"DETECTADO ESTILO GLOBAL O LOCAL CON PARAMETROS\")\n # print(\"key\")\n # print(key)\n #\\draw[estilo global = {red}{solid}] (0,0) rectangle (2.5, 2.5);\n #{'estilo global ': ' {red}{solid}'}\n variable_valores_definido = parametro[key_original].strip()\n variable_valores_definido = [valor for valor in variable_valores_definido.split(\"}\") if valor]\n variable_valores_definido_limpio = []\n for e in variable_valores_definido:\n if e.find(\"{\")!=-1:\n variable_valores_definido_limpio.append(e[e.find(\"{\")+1::])\n else:\n variable_valores_definido_limpio.append(e)\n variable_valores_definido = variable_valores_definido_limpio\n variable_valores_indefinidos = self.estilo_global_local[key]\n key_variable_indefinido = list(variable_valores_indefinidos.keys())[0]\n parametros_estilo_global_local = variable_valores_indefinidos[key_variable_indefinido]\n #[[['#2'], {'line width': '1.25pt', 'draw ': ' #1'}], [[], {'estilo global/.default ': '[cyan,dotted]'}]]\n indice_estilo_global_local = 0\n indice_estilo_global_local_parametro = 0\n for parametro_estilo_global_local in parametros_estilo_global_local:\n indice_estilo_global_local_parametro = 1 if indice_estilo_global_local > 1 else 0\n indice_estilo_global_local = indice_estilo_global_local if indice_estilo_global_local <2 else 0\n parametro_estilo_global_local = parametros_estilo_global_local[indice_estilo_global_local_parametro][indice_estilo_global_local]\n #Solo recorre por [['#2'], {'line width': '1.25pt', 'draw ': ' #1'}]\n if not indice_estilo_global_local_parametro:\n #Explorar por []\n if indice_estilo_global_local == 0:\n for key in parametro_estilo_global_local:\n key = key.strip()\n if key.find(\"#\") != -1:\n # print(\"variable_valores_definido\")\n # print(variable_valores_definido)\n indice = int(key[key.find(\"#\")+1::])-1 #EJ #2 -> \n # print(\"indice a utilizar en variable_valores_definido\")\n # print(indice)\n try:\n estilo = variable_valores_definido[indice] #Red, Solid etc...\n except:\n #{'estilo global/.default ': '[cyan,5pt]'}\n parametro_estilo_global_local_1 = parametros_estilo_global_local[1][1]\n str1 = list(parametro_estilo_global_local_1.values())[0]#'[cyan,5pt]'\n str2 = str1.replace(']','').replace('[','')\n valores_predeterminado = str2.replace('\"','').split(\",\")#['cyan', '5pt']\n estilo = valores_predeterminado[indice]\n # print(\"Estilo predeterminado seleccionado \"+estilo)\n array_estilos_validados = self.validadores.validar_estilos(\"tupla\",estilo)\n mensajes_de_error_generados = array_estilos_validados[len(array_estilos_validados)-1]\n if not len(mensajes_de_error_generados):\n self.degradients = array_estilos_validados[0]\n self.fill = array_estilos_validados[1]\n self.draw = array_estilos_validados[2]\n self.tipo_de_linea = array_estilos_validados[3]\n self.line_width = array_estilos_validados[4]\n self.style = array_estilos_validados[5]\n else:\n indice = 0\n for mensaje_de_error_generado in mensajes_de_error_generados:\n mensajes_de_error_generados[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n self.mensajes_de_error.extend(mensajes_de_error_generados)\n #Explorar por {}\n elif indice_estilo_global_local == 1:\n #Recorrer keys de {}\n values_diccionario = list(parametro_estilo_global_local.values())\n indice_key_seleccionado = 0\n for value in values_diccionario:\n if value.find(\"#\")!=-1:\n # print(\"variable_valores_definido\")\n # print(variable_valores_definido)\n indice = int(value[value.find(\"#\")+1::])-1 #EJ #2 -> 1\n # print(\"indice a utilizar en variable_valores_definido\")\n # print(indice)\n try:\n estilo = variable_valores_definido[indice] #Red, Solid etc...\n except:\n #{'estilo global/.default ': '[cyan,5pt]'}\n parametro_estilo_global_local_1 = parametros_estilo_global_local[1][1]\n str1 = list(parametro_estilo_global_local_1.values())[0]#'[cyan,5pt]'\n str2 = str1.replace(']','').replace('[','')\n valores_predeterminado = str1.replace('\"','').split(\",\")#['cyan', '5pt']\n estilo = valores_predeterminado[indice]\n # print(\"Estilo predeterminado seleccionado \"+estilo)\n indice_key = 0\n for key in list(parametro_estilo_global_local.keys()):\n if indice_key == indice_key_seleccionado:\n key = key.strip()\n array_estilos_validados = self.validadores.validar_estilos(\"diccionario\",key,estilo)\n mensajes_de_error_generados = array_estilos_validados[len(array_estilos_validados)-1]\n if not len(mensajes_de_error_generados):\n self.degradients = array_estilos_validados[0]\n self.fill = array_estilos_validados[1]\n self.draw = array_estilos_validados[2]\n self.tipo_de_linea = array_estilos_validados[3]\n self.line_width = array_estilos_validados[4]\n self.style = array_estilos_validados[5]\n else:\n indice = 0\n for mensaje_de_error_generado in mensajes_de_error_generados:\n mensajes_de_error_generados[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n self.mensajes_de_error.extend(mensajes_de_error_generados)\n indice_key+=1\n indice_key_seleccionado+=1\n else:\n break\n indice_estilo_global_local+=1\n #Si no es el caso...\n elif not diccionario_validada:\n #Codigos COLOR\n keys_color = [estilo_global for estilo_global in self.estilo_global_local.keys()]\n keys_color_invocados = list(parametro.values())\n # print(\"Colores globales existentes\")\n # print(keys_color)\n # print(\"Parametros establecidos\")\n # print(keys_color_invocados)\n #Si el comando tiene estilos con codigos RGB..\n if True in np.in1d(keys_color_invocados,keys_color):\n index_keys_color = []\n for index,value in enumerate(keys_color):\n if value in keys_color_invocados:\n index_keys_color.append(index)\n # print(\"Index donde el Color fue invocado...\")\n # print(index_keys_color)\n keys_color_invocados = []\n codigos_color_invocados = []\n for index,value in enumerate(self.estilo_global_local.values()):\n if index in index_keys_color:\n keys_color_invocados.append(keys_color[index])\n codigos_color_invocados.append(value)\n codigos_color = [codigo_color for codigo_color in codigos_color_invocados]\n #Si existe codigos rgb...\n codigos_rgb = [{index:list(color[1].values())[0]} for index,color in enumerate(codigos_color) if list(color[1].keys())[0].find(\"RGB\") != -1]\n # print(codigos_rgb)\n # print(\"Antes de actualizar\")\n # print(parametro)\n i = 0\n for key in parametro:\n if parametro[key] in keys_color:\n #Corresponde a un valor RGB?\n for codigo in codigos_rgb:\n if list(codigo.keys())[0] == i:\n for k in parametro:\n if parametro[k] == keys_color_invocados[i]:\n # print(\"La key...\")\n # print(parametro[k])\n # print(\"Corresponde a un codigo RGB, en el Index: \",i)\n # print(list(codigo.values())[0])\n parametro[k] = list(codigo.values())[0]\n i+=1\n array_estilos_validados = self.validadores.validar_estilos(\"diccionario\",keys_diccionario,parametro)\n mensajes_de_error_generados = array_estilos_validados[len(array_estilos_validados)-1]\n if not len(mensajes_de_error_generados):\n self.degradients = array_estilos_validados[0]\n self.fill = array_estilos_validados[1]\n self.draw = array_estilos_validados[2]\n self.tipo_de_linea = array_estilos_validados[3]\n self.line_width = array_estilos_validados[4]\n self.style = array_estilos_validados[5]\n else:\n indice = 0\n for mensaje_de_error_generado in mensajes_de_error_generados:\n mensajes_de_error_generados[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n self.mensajes_de_error.extend(mensajes_de_error_generados)\n diccionario_validada = True\n indice+=1\n\n #VALIDAR - FIGURA SIN PARAMETROS\n if(len(funcion_de_figura[0]) == 0 and len(list(funcion_de_figura[1].keys())) == 0):\n if not len(self.mensajes_de_error):\n for figura in figuras:\n #Dibujar rectangulo\n #\\draw[color=black] (10pt,10pt) rectangle (100pt,100pt); WORKS.\n #\\draw[color=black] (100pt,100pt) rectangle (10pt,10pt); WORKS. Y es lo mismo que lo anterior.\n #\\draw[color=black] (100pt,10pt) rectangle (100pt,100pt); WORKS.\n if(figura==\"rectangle\"):\n punto_inicial_x_y = self.validadores.validar_metrica(draw_posicion[0][0])\n punto_final_x_y = self.validadores.validar_metrica(draw_posicion[0][1])\n ancho = self.validadores.validar_metrica(draw_posicion[1][0])\n alto = self.validadores.validar_metrica(draw_posicion[1][1])\n #Si ocurre un error de validacion...\n if(isinstance(punto_inicial_x_y,list) or isinstance(punto_final_x_y,list) or isinstance(ancho,list) or isinstance(alto,list)):\n indice = 0\n for mensaje_de_error_generado in self.validadores.mensajes_de_error:\n self.validadores.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n indice += 1\n self.mensajes_de_error.extend(self.validadores.mensajes_de_error)\n #Si todo esta correcto...\n else:\n if punto_inicial_x_y >= ancho:\n punto_inicial_x_y_original = deepcopy(punto_inicial_x_y)\n punto_inicial_x_y = deepcopy(ancho)\n ancho = punto_inicial_x_y_original - ancho\n else:\n ancho = ancho - punto_inicial_x_y\n if punto_final_x_y >= alto:\n punto_final_x_y_original = deepcopy(punto_final_x_y)\n punto_final_x_y = deepcopy(alto)\n alto = punto_final_x_y_original - alto\n else:\n alto = alto - punto_final_x_y\n rectangulo_dibujado_lineas = [punto_inicial_x_y, punto_final_x_y, punto_inicial_x_y, punto_final_x_y+alto, punto_inicial_x_y+ancho, punto_final_x_y+alto, punto_inicial_x_y+ancho, punto_final_x_y, punto_inicial_x_y, punto_final_x_y]\n #Dibujar contenido rectangulo\n #DEGRADADO RECTANGULO\n if self.degradients:\n Relleno(area_de_dibujar,figura,self.degradients,(punto_inicial_x_y,punto_final_x_y),(ancho,alto),habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n #RELLENO RECTANGULO\n else:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.fill[0], self.fill[1], self.fill[2]))\n figura.add(Rectangle(pos=(punto_inicial_x_y,punto_final_x_y),size=(ancho,alto)))\n area_de_dibujar.canvas.add(figura)\n else:\n self.guardar_dibujo_en_imagen.figura_a_png(habilitado_generar_figura_en_formato[\"generar_dibujo_en_formato\"],\"rectangle\",(ancho,alto),(punto_inicial_x_y,punto_final_x_y),(self.fill[0], self.fill[1], self.fill[2]),self.tipo_de_linea,rectangulo_dibujado_lineas,(self.draw[0], self.draw[1], self.draw[2]),self.line_width)\n #Dibujar borde rectangulo\n #Si hay separacion de lineas...\n if self.tipo_de_linea:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(points=rectangulo_dibujado_lineas, dash_offset=10, dash_length=5))\n area_de_dibujar.canvas.add(figura)\n #Si no hay...\n else:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(points=rectangulo_dibujado_lineas,width=self.line_width))\n area_de_dibujar.canvas.add(figura)\n #DIBUJAR ARCO\n #\\draw[color=ColorA,line width=0.1cm,rounded corners=2ex] (100,100) arc (0:90:5cm);\n elif(figura==\"arc\"):\n \n posicion_x = None\n posicion_y = None\n indice_angulo_inicial_final_radio = None\n indice = 0\n\n for posicion in draw_posicion:\n if type(posicion) is list and len(posicion) == 2:\n #Si las posiciones de origen se rigen segun dos valores (X,Y)\n posicion_x = self.validadores.validar_metrica(draw_posicion[indice][0])\n posicion_y = self.validadores.validar_metrica(draw_posicion[indice][1])\n #Indice del angulo inicial, angulo final, y radio del Arc...\n elif type(posicion) is list and len(posicion)==3:\n if indice_angulo_inicial_final_radio == None:\n indice_angulo_inicial_final_radio = deepcopy(indice)\n radio = self.validadores.validar_metrica(draw_posicion[indice_angulo_inicial_final_radio][2])\n indice+=1\n\n #Si ocurre un error de validacion...\n if(isinstance(posicion_x,list) or isinstance(posicion_y,list) or isinstance(radio,list)):\n indice = 0\n for mensaje_de_error_generado in self.validadores.mensajes_de_error:\n self.validadores.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n indice += 1\n self.mensajes_de_error.extend(self.validadores.mensajes_de_error)\n else:\n #Si existe un posicion_x, posicion_y y radio\n if(posicion_x != None and posicion_y != None and indice_angulo_inicial_final_radio != None):\n angulo_inicial = float(450) if float(draw_posicion[indice_angulo_inicial_final_radio][0]) == 0.0 else float(450-(float(draw_posicion[indice_angulo_inicial_final_radio][0])))\n angulo_final = float(450) if float(draw_posicion[indice_angulo_inicial_final_radio][1]) == 0.0 else float(450-(float(draw_posicion[indice_angulo_inicial_final_radio][1])))\n #Eliminar parametro Arc utilizado\n self.angulo_final_arc = draw_posicion[indice_angulo_inicial_final_radio][1]\n self.longitud_arc = radio\n del draw_posicion[indice_angulo_inicial_final_radio:indice_angulo_inicial_final_radio+1]\n #DIBUJAR CONTENIDO ARC\n #Si aplica relleno o degradado...\n if self.fill != (1,1,1) or self.degradients:\n if self.degradients:\n #Aplicar degradado a la figura...\n Relleno(area_de_dibujar,figura,self.degradients,(posicion_x,posicion_y),(radio*2,radio*2),angulo_inicial, angulo_final,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n else:\n #Aplicar relleno a la figura...\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.fill[0],self.fill[1],self.fill[2]))\n figura.add(Ellipse(pos=(posicion_x,posicion_y),size=(radio*2,radio*2),angle_start=angulo_inicial, angle_end=angulo_final))\n area_de_dibujar.canvas.add(figura)\n else:\n self.guardar_dibujo_en_imagen.figura_a_png(habilitado_generar_figura_en_formato[\"generar_dibujo_en_formato\"],\"arc\",(radio*2,radio*2),(posicion_x,posicion_y),(self.fill[0], self.fill[1], self.fill[2]),self.tipo_de_linea,[posicion_x,posicion_y,radio,angulo_inicial,angulo_final],(self.draw[0], self.draw[1], self.draw[2]),self.line_width,angle_start=angulo_inicial, angle_end=angulo_final)\n posicion_x+=radio\n posicion_y+=radio\n #DIBUJAR ARC\n #ARCO CON LINEAS DISCONTINUADAS\n if self.tipo_de_linea:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(circle=[posicion_x,posicion_y,radio,angulo_inicial,angulo_final], dash_offset=10, dash_length=5))\n area_de_dibujar.canvas.add(figura)\n #Si no hay...\n #ARCO SIN LINEAS DISCONTINUADAS\n else:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(circle=[posicion_x,posicion_y,radio,angulo_inicial,angulo_final],width=self.line_width))\n area_de_dibujar.canvas.add(figura)\n else:\n if(posicion_x == None or posicion_y == None):\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Se esperaba posiciones de Origen y de Destino\")\n else:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Se esperaba Angulo de Inicio, Final y de Radio\")\n \n #DIBUJAR CIRCULO\n #\\draw[draw=red,fill=yellow] (0,0) circle (1cm);\n elif(figura==\"circle\"):\n posicion_x = self.validadores.validar_metrica(draw_posicion[0][0])\n posicion_y = self.validadores.validar_metrica(draw_posicion[0][1])\n posiciones_validas = True\n try:\n radio = self.validadores.validar_metrica(draw_posicion[1])\n except:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error cerca de \"+figura+\" se esperaba un valor de Radio o de posicion X y Y validos.\")\n posiciones_validas = False\n #Si ocurre un error de validacion...\n if(isinstance(posicion_x,list) or isinstance(posicion_y,list) or isinstance(radio,list)):\n indice = 0\n for mensaje_de_error_generado in self.validadores.mensajes_de_error:\n self.validadores.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n indice += 1\n self.mensajes_de_error.extend(self.validadores.mensajes_de_error)\n posiciones_validas = False\n #Line:\n # circle: (60,60,60,90,180)#CIRCULO CERRADO, 40 DE RADIO\n if posiciones_validas:\n #DIBUJAR CONTENIDO CIRCULO\n ancho = radio*2\n alto = radio*2\n if self.degradients:\n #APLICAR DEGRADADO AL CIRCULO\n Relleno(area_de_dibujar,figura,self.degradients,(posicion_x,posicion_y),(ancho,alto),habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n else:\n #RELLENO CIRCULO\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.fill[0], self.fill[1], self.fill[2]))\n figura.add(Ellipse(pos=(posicion_x,posicion_y),size=(ancho,alto)))\n area_de_dibujar.canvas.add(figura)\n else:\n self.guardar_dibujo_en_imagen.figura_a_png(habilitado_generar_figura_en_formato[\"generar_dibujo_en_formato\"],\"circle\",(ancho,alto),(posicion_x,posicion_y),(self.fill[0], self.fill[1], self.fill[2]),self.tipo_de_linea,[posicion_x,posicion_y,radio],(self.draw[0], self.draw[1], self.draw[2]),self.line_width)\n #DIBUJAR BORDE CIRCULO\n posicion_x+=radio\n posicion_y+=radio\n if self.tipo_de_linea:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(circle=[posicion_x,posicion_y,radio], dash_offset=10, dash_length=self.line_width))\n area_de_dibujar.canvas.add(figura)\n #Si no hay...\n else:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(circle=[posicion_x,posicion_y,radio], width=self.line_width))\n area_de_dibujar.canvas.add(figura)\n #DIBUJAR LINEAS BEZIER\n #\\draw[left color=yellow, bottom color=orange, right color=red,rounded] (0,100) .. controls (100,200) and (200,300) .. (300,400) .. (200,100) .. (300,200);\n elif(figura==\"controls\"):\n #Estas variables son necesarias para reunir coordenadas\n coordenadas = []\n #Extraer figura del array \"figuras\"\n indice = 0\n figuras_control = []\n for figura in figuras:\n if figura == \"controls\":\n figuras_control.append(figura)\n posiciones_controls = 0\n \n #Estas variables son necesarias cuando se trabaja con mas de 1 controls.\n cantidad_de_posiciones_valido = False\n conjunto_de_coordenadas = []\n\n for posicion in draw_posicion:\n coordenadas_x1y1_a_validar = None\n coordenadas_x2y2_a_validar = None\n if len(figuras_control)>1:\n #Maximo-Minimo 3 posiciones\n #Avanzando hacia el siguiente control (Termina en 4, luego inicia en 0 hasta 3, y pasa al proximo control en 4)...\n if (posiciones_controls == 4):\n conjunto_de_coordenadas.append(coordenadas)\n coordenadas = []\n posiciones_controls = 0\n cantidad_de_posiciones_valido = True\n if(posiciones_controls < 4):\n #Posiciones Control\n if(posiciones_controls == 0) and len(conjunto_de_coordenadas):\n ultimo_conjunto_de_coordenadas = conjunto_de_coordenadas[len(conjunto_de_coordenadas)-1]\n posicion_x_anterior = ultimo_conjunto_de_coordenadas[len(ultimo_conjunto_de_coordenadas)-2]\n posicion_y_anterior = ultimo_conjunto_de_coordenadas[len(ultimo_conjunto_de_coordenadas)-1]\n coordenadas.append(posicion_x_anterior)\n coordenadas.append(posicion_y_anterior)\n coordenadas_x1y1_a_validar = self.validadores.validar_metrica(posicion[0])\n coordenadas_x2y2_a_validar = self.validadores.validar_metrica(posicion[1])\n posiciones_controls+=1\n else:\n #Solo hay un control...\n #Posiciones Control\n coordenadas_x1y1_a_validar = self.validadores.validar_metrica(posicion[0])\n coordenadas_x2y2_a_validar = self.validadores.validar_metrica(posicion[1])\n if(coordenadas_x1y1_a_validar != None and coordenadas_x2y2_a_validar != None):\n #Si ocurre un error de validacion...\n if(isinstance(coordenadas_x1y1_a_validar,list) or isinstance(coordenadas_x2y2_a_validar,list)):\n coordenadas = []\n conjunto_de_coordenadas = []\n break\n else:\n coordenadas.append(coordenadas_x1y1_a_validar)\n coordenadas.append(coordenadas_x2y2_a_validar)\n indice += 1\n \n #Añadir las ultimas posiciones del ultimo control\n if(cantidad_de_posiciones_valido):\n if(posiciones_controls == 3):\n conjunto_de_coordenadas.append(coordenadas)\n else:\n cantidad_de_posiciones_valido = False\n coordenadas = []\n \n #Eliminar figuras Controls (Si hay mas de uno)\n if len(figuras_control)>1:\n while(True):\n try:\n index_control = figuras.index(\"controls\")\n except:\n break\n del figuras[index_control]\n \n if len(coordenadas)>=4 or len(conjunto_de_coordenadas) > 1:\n if not habilitado_generar_figura_en_formato:\n #Dibujar en el area de dibujado...\n indice = 0\n es_conjunto_de_coordenadas = True\n while(es_conjunto_de_coordenadas):\n if indice < len(conjunto_de_coordenadas):\n coordenadas = conjunto_de_coordenadas[indice]\n else:\n es_conjunto_de_coordenadas = False\n #Si hay separacion de lineas...\n if self.tipo_de_linea:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(bezier=coordenadas, dash_offset=10, dash_length=5))\n area_de_dibujar.canvas.add(figura)\n #Si no hay...\n else:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(bezier=coordenadas, width=self.line_width))\n area_de_dibujar.canvas.add(figura)\n indice+=1\n \n else:\n if(not cantidad_de_posiciones_valido):\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Se esperaba 3 posiciones por 'controls' (Sin contar posicion inicial).\")\n #Si ocurre un error de validacion...\n elif(isinstance(coordenadas_x1y1_a_validar,list) or isinstance(coordenadas_x2y2_a_validar,list)):\n indice = 0\n for mensaje_de_error_generado in self.validadores.mensajes_de_error:\n self.validadores.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n indice += 1\n self.mensajes_de_error.extend(self.validadores.mensajes_de_error)\n else: \n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error cerca de \"+str(coordenadas[len(coordenadas)-1])+\" se esperaba posiciones de Origen y de Destino\")\n #Si hay figura (--)...\n #\\draw[line width= 1.5pt, fill = yellow, draw = black](100,100) -- (200,0) -- (50,300) -- (40,200) -- cycle;\n elif(figura==\"--\"):\n coordenadas = []\n draw_posicion_valido = []\n \n for posicion in draw_posicion:\n if type(posicion) is list and len(posicion) == 2:\n draw_posicion_valido.append(posicion)\n \n indice = 0\n for posicion in draw_posicion_valido:\n coordenadas_x_a_validar = None\n coordenadas_y_a_validar = None\n if posicion != \"cycle\":\n coordenadas_x_a_validar = self.validadores.validar_metrica(posicion[0])\n coordenadas_y_a_validar = self.validadores.validar_metrica(posicion[1])\n #Si es Cycle...\n else:\n if posicion==\"cycle\":\n #HASTA COORDENADA ORIGEN X,Y\n coordenadas.append(coordenadas[0])\n coordenadas.append(coordenadas[1])\n if(coordenadas_x_a_validar != None and coordenadas_y_a_validar != None):\n #Si ocurre un error de validacion...\n if(isinstance(coordenadas_x_a_validar,list) or isinstance(coordenadas_y_a_validar,list)):\n indice = 0\n for mensaje_de_error_generado in self.validadores.mensajes_de_error:\n self.validadores.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n indice += 1\n self.mensajes_de_error.extend(self.validadores.mensajes_de_error)\n break\n else:\n coordenadas.append(coordenadas_x_a_validar)\n coordenadas.append(coordenadas_y_a_validar)\n indice+=1\n if not len(self.mensajes_de_error):\n if len(coordenadas)>=4:\n # print(\"coordenadas\")\n # print(coordenadas)\n #DIBUJAR LINEAS CON CONTENIDO\n #Si aplica relleno o degradado...\n if self.fill != (1,1,1) or self.degradients:\n if self.fill != (1,1,1):\n #Crear Imagen con relleno y aplicarlo en el Source de un Rectangle para luego dibujarlo en el Area_de_dibujar\n RellenoLineasLibre(area_de_dibujar,coordenadas,self.fill,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n else:\n RellenoLineasLibre(area_de_dibujar,coordenadas,self.degradients,False,True,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n #DIBUJAR LINEAS\n #Si hay separacion de lineas...\n if self.tipo_de_linea:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(points=coordenadas, dash_offset=10, dash_length=5))\n area_de_dibujar.canvas.add(figura)\n #Si no hay...\n else:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1],self.draw[2]))\n figura.add(Line(points=coordenadas, width=self.line_width))\n area_de_dibujar.canvas.add(figura)\n else:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error cerca de \"+str(coordenadas[len(coordenadas)-1])+\" se esperaba posiciones de Origen y de Destino\")\n #Si hay figura (grid)...\n #\\draw[style=help lines] (0,0) grid (21,29.7);\n elif(figura==\"grid\"):\n coordenadas = []\n draw_posicion_valido = []\n \n #Validar las posiciones, solo aceptan de esta manera: [21,29.7] (Valores varian), las posiciones se redondean a la unidad inferior.\n for conjunto_de_posiciones in draw_posicion:\n if type(conjunto_de_posiciones) is list and len(conjunto_de_posiciones) == 2:\n posiciones_validas = [self.validadores.validar_metrica(posicion) for posicion in conjunto_de_posiciones]\n posiciones_invalidas = [posicion for posicion in posiciones_validas if isinstance(posicion,list)]\n if not len(posiciones_invalidas):\n posiciones_con_cm = [posicion for posicion in conjunto_de_posiciones if posicion.find(\"pt\") == -1]\n posiciones_con_pt = [self.validadores.validar_metrica(posicion) for posicion in conjunto_de_posiciones if posicion.find(\"pt\") != -1]\n # print(\"posiciones_con_cm\")\n # print(posiciones_con_cm)\n # print(\"posiciones_con_pt\")\n # print(posiciones_con_pt)\n conjunto_de_posiciones = list(map(lambda x: x.replace(\"cm\",\"\"), posiciones_con_cm))+posiciones_con_pt\n conjunto_de_posiciones = [str(math.floor(float(posicion))) for posicion in conjunto_de_posiciones]\n draw_posicion_valido.append(conjunto_de_posiciones)\n else:\n for indice,mensaje_de_error_generado in enumerate(self.validadores.mensajes_de_error,0):\n self.validadores.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado \n self.mensajes_de_error.extend(self.validadores.mensajes_de_error)\n break\n \n #Añadir las posiciones al array de coordenadas, si su unidad metrica es valida y se guarda como float.\n if not len(self.mensajes_de_error):\n # print(\"draw_posicion_valido\")\n # print(draw_posicion_valido)\n for indice,posicion in enumerate(draw_posicion_valido,0):\n coordenadas_x_a_validar = None\n coordenadas_y_a_validar = None\n coordenadas_x_a_validar = self.validadores.validar_metrica(posicion[0])\n coordenadas_y_a_validar = self.validadores.validar_metrica(posicion[1])\n if(coordenadas_x_a_validar != None and coordenadas_y_a_validar != None):\n #Si ocurre un error de validacion...\n if(isinstance(coordenadas_x_a_validar,list) or isinstance(coordenadas_y_a_validar,list)):\n indice = 0\n for mensaje_de_error_generado in self.validadores.mensajes_de_error:\n self.validadores.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n indice += 1\n self.mensajes_de_error.extend(self.validadores.mensajes_de_error)\n break\n else:\n coordenadas.append(coordenadas_x_a_validar)\n coordenadas.append(coordenadas_y_a_validar)\n if(len(coordenadas) == 2):\n unidad_metrica_desde_x = posicion[0]\n unidad_metrica_desde_y = posicion[1]\n if(len(coordenadas) == 4):\n unidad_metrica_hasta_y = posicion[1]\n string_unidades_metricas = str(unidad_metrica_desde_y)+\",\"+str(unidad_metrica_hasta_y)\n numeros_ordenados = self.evaluar.resivar_metricas(string_unidades_metricas)\n unidades_metricas_desde_hasta_y_validas = False\n if(len(numeros_ordenados)<=1):\n unidades_metricas_desde_hasta_y_validas = True\n unidad_metrica_utilizado = list(filter(None,re.findall(r\"[A-z]*\",numeros_ordenados[0][0])))[0]\n \n if not len(self.mensajes_de_error):\n #Las coordenadas deben de ser si o si 4 en longitud (X1,X2)(Y1,Y2)\n if len(coordenadas)==4:\n if unidades_metricas_desde_hasta_y_validas:\n #Coordenadas (X1,Y1,X2,Y2) iniciales...\n desde_x,desde_y,hasta_x,hasta_y = coordenadas\n #1. Empezar dibujando los renglones horizontales...\n coordenadas = [desde_x,desde_y,hasta_x,desde_y]\n renglones_horizontales_verticales = [coordenadas]\n #1.1. Se actualizaran las coordendas, partiendo desde las coordenadas Y, se iran sumando de 1 en 1 hasta alcanzar las coordanadas hasta Y.\n desde_y_subir = self.evaluar.evaluar_metrica(unidad_metrica_desde_y,True)\n step = self.validadores.validar_metrica(\"1\"+unidad_metrica_utilizado)\n hasta_y_destino=hasta_y + step\n coordenadas = []\n for y_up in np.arange(desde_y_subir,hasta_y_destino,step):\n coordenadas_x1 = desde_x\n coordenadas_y1 = desde_y_subir+y_up\n coordenadas_x2 = hasta_x\n coordenadas_y2 = desde_y_subir+y_up\n coordenadas.append(coordenadas_x1)\n coordenadas.append(coordenadas_y1)\n coordenadas.append(coordenadas_x2)\n coordenadas.append(coordenadas_y2)\n #1.2. Añadir coordenadas a renglones_horizontales_verticales, despues limpiarlo para el siguiente renglon\n renglones_horizontales_verticales.append(coordenadas)\n coordenadas = []\n \n #2. Luego dibujar los renglones verticales...\n coordenadas = [desde_x,desde_y,desde_x,hasta_y]\n renglones_horizontales_verticales.append(coordenadas)\n #2.1. Se actualizaran las coordendas, partiendo desde las coordenadas X, se iran sumando de 1 en 1 hasta alcanzar las coordanadas hasta X.\n desde_x_derecha = self.evaluar.evaluar_metrica(unidad_metrica_desde_x,True)\n step = self.validadores.validar_metrica(\"1\"+unidad_metrica_utilizado)\n hasta_x_destino=hasta_x + step\n coordenadas = []\n for x_right in np.arange(desde_x_derecha,hasta_x_destino,step):\n coordenadas_x1 = desde_x_derecha+x_right\n coordenadas_y1 = desde_y\n coordenadas_x2 = desde_x_derecha+x_right\n coordenadas_y2 = hasta_y\n coordenadas.append(coordenadas_x1)\n coordenadas.append(coordenadas_y1)\n coordenadas.append(coordenadas_x2)\n coordenadas.append(coordenadas_y2)\n #2.2. Añadir coordenadas a renglones_horizontales_verticales, despues limpiarlo para el siguiente renglon\n renglones_horizontales_verticales.append(coordenadas)\n coordenadas = []\n\n #Antes de dibujar, actualizar valores de los estilos, si hay un estilo predeterminado definido.\n if self.style:\n for _, conjunto_de_estilos in self.style.items():\n nombres_estilos = list(conjunto_de_estilos.keys())\n for nombre_estilo in nombres_estilos:\n if nombre_estilo == \"degradients\":\n self.degradients = conjunto_de_estilos[nombre_estilo]\n if nombre_estilo == \"fill\":\n self.fill = conjunto_de_estilos[nombre_estilo]\n if nombre_estilo == \"draw\":\n self.draw = conjunto_de_estilos[nombre_estilo]\n if nombre_estilo == \"tipo_de_linea\":\n self.tipo_de_linea = conjunto_de_estilos[nombre_estilo]\n if nombre_estilo == \"line_width\":\n self.line_width = conjunto_de_estilos[nombre_estilo]\n for coordenadas in renglones_horizontales_verticales:\n #DIBUJAR LINEAS CON CONTENIDO\n #Si aplica relleno o degradado...\n if self.fill != (1,1,1) or self.degradients:\n if self.fill != (1,1,1):\n #Crear Imagen con relleno y aplicarlo en el Source de un Rectangle para luego dibujarlo en el Area_de_dibujar\n RellenoLineasLibre(area_de_dibujar,coordenadas,self.fill,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n else:\n RellenoLineasLibre(area_de_dibujar,coordenadas,self.degradients,False,True,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n #DIBUJAR LINEAS\n #Si hay separacion de lineas...\n if self.tipo_de_linea:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(points=coordenadas, dash_offset=10, dash_length=5))\n area_de_dibujar.canvas.add(figura)\n #Si no hay...\n else:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1],self.draw[2]))\n figura.add(Line(points=coordenadas, width=self.line_width))\n area_de_dibujar.canvas.add(figura)\n else:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error cerca de \"+str(coordenadas[len(coordenadas)-1])+\" se esperaba que las coordenadas Y1 y Y2 utilicen la misma unidad metrica.\")\n else:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error cerca de \"+str(coordenadas[len(coordenadas)-1])+\" se esperaba solo 4 coordenadas.\")\n #No tiene figura\n else:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error el comando PyTikZ '\"+nombre_comando+\"' no tiene una figura valida.\")\n \n #VALIDAR - FIGURA CON PARAMETROS\n else:\n if not len(self.mensajes_de_error):\n for figura in figuras:\n #DIBUJAR ARCO\n #\\draw[bottom color=cyan!60!black, top color=red, middle color = blue!20!white] (100,100) arc[start angle=0, end angle=90, radius=5cm];\n if(figura==\"arc\"):\n \n posicion_x = self.validadores.validar_metrica(draw_posicion[0][0])\n posicion_y = self.validadores.validar_metrica(draw_posicion[0][1])\n diccionario_funcion_figura = {}\n for key in list(funcion_de_figura[1].keys()):\n key_nueva = key.strip()\n diccionario_funcion_figura[key_nueva] = funcion_de_figura[1][key]\n radius = diccionario_funcion_figura[\"radius\"] if \"radius\" in list(diccionario_funcion_figura.keys()) else \"10.0\"\n radio = self.validadores.validar_metrica(radius)\n #Si ocurre un error de validacion...\n if(isinstance(posicion_x,list) or isinstance(posicion_y,list) or isinstance(radio,list)):\n indice = 0\n for mensaje_de_error_generado in self.validadores.mensajes_de_error:\n self.validadores.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n indice +=1\n self.mensajes_de_error.extend(self.validadores.mensajes_de_error)\n else:\n start_angle = diccionario_funcion_figura[\"start angle\"] if \"start angle\" in list(diccionario_funcion_figura.keys()) else \"0.0\"\n end_angle = diccionario_funcion_figura[\"end angle\"] if \"end angle\" in list(diccionario_funcion_figura.keys()) else \"360.0\"\n angulo_inicial = 450.0 if float(start_angle) == 0.0 else 450-float(start_angle)\n angulo_final = 450.0 if float(end_angle) == 0.0 else 450-float(end_angle)\n\n #DIBUJAR CONTENIDO ARC\n #Si aplica relleno o degradado...\n if self.fill != (1,1,1) or self.degradients:\n if self.degradients:\n #Aplicar degradado a la figura...\n Relleno(area_de_dibujar,figura,self.degradients,(posicion_x,posicion_y),(radio*2,radio*2),angulo_inicial,angulo_final,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n else:\n #Aplicar relleno a la figura...\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.fill[0],self.fill[1],self.fill[2]))\n figura.add(Ellipse(pos=(posicion_x,posicion_y),size=(radio*2,radio*2),angle_start=angulo_inicial, angle_end=angulo_final))\n area_de_dibujar.canvas.add(figura)\n else:\n self.guardar_dibujo_en_imagen.figura_a_png(habilitado_generar_figura_en_formato[\"generar_dibujo_en_formato\"],\"arc\",(radio*2,radio*2),(posicion_x,posicion_y),(self.fill[0],self.fill[1],self.fill[2]),self.tipo_de_linea,[posicion_x,posicion_y,radio,angulo_inicial,angulo_final],(self.draw[0], self.draw[1], self.draw[2]),self.line_width,angle_start=angulo_inicial, angle_end=angulo_final)\n #DIBUJAR ARC\n posicion_x+=radio\n posicion_y+=radio\n #BORDE CON LINEAS DISCONTINUADAS\n if self.tipo_de_linea:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(circle=[posicion_x,posicion_y,radio,angulo_inicial,angulo_final], dash_offset=10, dash_length=5))\n area_de_dibujar.canvas.add(figura)\n #Si no hay...\n else:\n if not habilitado_generar_figura_en_formato:\n figura = InstructionGroup()\n figura.add(Color(self.draw[0], self.draw[1], self.draw[2]))\n figura.add(Line(circle=[posicion_x,posicion_y,radio,angulo_inicial,angulo_final],width=self.line_width))\n area_de_dibujar.canvas.add(figura)\n #No tiene figura\n else:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error el comando PyTikZ '\"+nombre_comando+\"' no tiene una figura valida.\")\n\n def __validar_variables_tikz(self,nombre_comando,funcion_de_comando,parametros_comando,habilitado_generar_figura_en_formato={}):\n\n def animar(comandos_tikz_depurado_anidado,canvas_no_animar,schedule_animate,*args):\n try:\n codigo_a_dibujar = deepcopy(comandos_tikz_depurado_anidado[self.index_animacion])\n # print(\"ANIMAR\")\n # print(codigo_a_dibujar)\n animacion_valido = True\n except:\n # print(\"DETENER ANIMACIÓN\")\n Clock.unschedule(schedule_animate)\n animacion_valido = False\n if(animacion_valido):\n if(len(canvas_no_animar) == len(self.area_de_dibujar.canvas.children)):\n for canvas in canvas_no_animar:#Añadir Figuras no animadas...\n self.area_de_dibujar.canvas.add(canvas)\n else:\n #Elimina todos los canvas del widget \"area de dibujar\"\n canvas_no_animar_arr = []\n for canva in canvas_no_animar:\n canvas_no_animar_arr.append(canva)\n self.area_de_dibujar.canvas.children = canvas_no_animar_arr\n #Añade los canvas no animados...\n for canvas in canvas_no_animar:#Añadir Figuras no animadas...\n self.area_de_dibujar.canvas.add(canvas)\n #Dibujar la figura elegida de la lista\n if(isinstance(codigo_a_dibujar,tuple)):\n for codigo in codigo_a_dibujar:\n self.__validar_dibujar(codigo[0],codigo[1],codigo[2],\n codigo[3],codigo[4],self.area_de_dibujar)\n else:\n self.__validar_dibujar(codigo_a_dibujar[0],codigo_a_dibujar[1],codigo_a_dibujar[2],\n codigo_a_dibujar[3],codigo_a_dibujar[4],self.area_de_dibujar)\n #Continuar con la siguiente figura en la lista\n self.index_animacion+=1\n else:\n self.index_animacion = 0\n\n def validarSecuenciaNumerica(cantidad_parametros,array_secuencia_numerica):\n # print(\"Parametros_sin_definir_ordenado\")\n # print(parametros_sin_definir_ordenado)\n #Los parametros deben ser secuenciales #1,#2,#3. ETC\n parametros_sin_definir_ordenado = []\n indice = 0\n for e in array_secuencia_numerica:\n _ = bisect(parametros_sin_definir_ordenado, e)\n insort(parametros_sin_definir_ordenado, e)\n indice+=1\n indice = 0\n for _ in parametros_sin_definir_ordenado:\n if indice>0:\n if parametros_sin_definir_ordenado[indice-1]+1 != parametros_sin_definir_ordenado[indice]:\n parametros_sin_definir_ordenado = []\n break\n indice+=1\n if not len(parametros_sin_definir_ordenado):\n return[{\"error\":\"Error cerca de '#' se esperaba una secuencia numerica de parametros, ej: #1,#2,#3\"}]\n else:\n try:\n int(cantidad_parametros)\n except:\n return[{\"error\":\"Error cerca de la cantidad de parametros '#' se esperaba un numero INTEGER.\"}]\n if not len(self.mensajes_de_error):\n cantidad_parametros = int(cantidad_parametros)\n if len(array_secuencia_numerica) != cantidad_parametros:\n return[{\"error\":str(cantidad_parametros)+\" es diferente a la cantidad de parametros definidos (#) \"+str(len(array_secuencia_numerica))}]\n else:\n return True\n\n if nombre_comando == \"tikzset\":\n #\\tikzset{estilo global/.style = {line width=1.25pt, draw = cyan!75!gray,dashed}}\n nombre_variable_entorno = [nombre for nombre in list(funcion_de_comando[1].keys())[0].split(\" \") if nombre]\n key_original = list(funcion_de_comando[1].keys())[0]\n nombre_variable = nombre_variable_entorno[0]\n entorno = nombre_variable_entorno[1]\n if entorno == \"global/.style\":\n entorno = entorno.split(\"/\")[0]\n #NO TIENE PARAMETROS\n if isinstance(funcion_de_comando[1][key_original], list):\n self.estilo_global_local[nombre_variable+\" \"+entorno] = funcion_de_comando[1][key_original]\n #TIENE PARAMETROS -> EVALUAR VALIDES PARAMETROS\n else:\n cantidad_parametros = list(funcion_de_comando[1][key_original].keys())[0]\n parametros_estilo_global_local = funcion_de_comando[1][key_original][cantidad_parametros]\n parametros_sin_definir = []\n indice_estilo_global_local = 0\n indice_estilo_global_local_parametro = 0\n for parametro_estilo_global_local in parametros_estilo_global_local:\n indice_estilo_global_local_parametro = 1 if indice_estilo_global_local > 1 else 0\n indice_estilo_global_local = indice_estilo_global_local if indice_estilo_global_local <2 else 0\n parametro_estilo_global_local = parametros_estilo_global_local[indice_estilo_global_local_parametro][indice_estilo_global_local]\n #Explorar por []\n if indice_estilo_global_local == 0:\n for key in parametro_estilo_global_local:\n key = key.strip()\n #Aqui se espera Parametros #2\n if key.find(\"#\") != -1:\n try:\n int(key[key.find(\"#\")+1::])\n parametros_sin_definir.append(int(key[key.find(\"#\")+1::]))\n except:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error cerca de \"+key+\" se esperaba un parametro valido. '#'\")\n break\n else:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error cerca de \"+key+\" se esperaba un parametro valido. '#'\")\n #Explorar por {}\n elif indice_estilo_global_local == 1:\n #Recorrer keys de {}\n keys_diccionario = list(parametro_estilo_global_local.values())\n for key in keys_diccionario:\n if key.find(\"#\")!=-1:\n try:\n int(key[key.find(\"#\")+1::])\n parametros_sin_definir.append(int(key[key.find(\"#\")+1::]))\n except:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": Error cerca de \"+key+\" se esperaba un parametro valido. '#'\")\n break\n indice_estilo_global_local+=1\n if not len(self.mensajes_de_error): \n result_validacion_secuencia = validarSecuenciaNumerica(cantidad_parametros,parametros_sin_definir)\n if type(result_validacion_secuencia) is dict:\n self.mensajes_de_error.append(\"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+result_validacion_secuencia[\"error\"])\n else:\n #Si todas las validaciones son correctas...\n self.estilo_global_local[nombre_variable+\" \"+entorno] = funcion_de_comando[1][key_original]\n\n elif nombre_comando == \"definecolor\":\n nombre_variable_entorno = [nombre for nombre in list(funcion_de_comando[1].keys())[0].split(\" \") if nombre]\n nombre_variable = nombre_variable_entorno[0]\n key_original = list(funcion_de_comando[1].keys())[0]\n self.estilo_global_local[nombre_variable] = funcion_de_comando[1][key_original]\n\n elif nombre_comando == \"animarPytikz\":\n codigo_tikz_anidado = funcion_de_comando[1][\"ejecutar\"]\n conjunto_de_comandos = []\n\n #Si es para generar GIF, entonces se va a generar imagenes a partir de cada código dentro del comando animarPytikz que se utilizara para generar GIF, y luego se animara el mismo resultado pero en el aplicativo.\n if(\"save\" in parametros_comando[0]):\n habilitado_generar_figura_en_formato = {\"generar_dibujo_en_formato\":True, \"retornar_conjunto_de_codigos\":True}\n #Caso contrario, entonces se animara en la misma aplicación\n else:\n habilitado_generar_figura_en_formato = {\"generar_dibujo_en_formato\":False, \"retornar_conjunto_de_codigos\":True}\n for comando_tikz_anidado in codigo_tikz_anidado:\n if(len(self.mensajes_de_error)>0):\n break\n #Comandos preexistentes...\n if type(comando_tikz_anidado) is list:\n if comando_tikz_anidado[0] in self.COMANDOS_DIBUJAR_PYTIKZ:\n #Generar figuras en formato para la creacion de un GIF o JPG\n self.__validar_dibujar(comando_tikz_anidado[0],comando_tikz_anidado[1],comando_tikz_anidado[2],comando_tikz_anidado[3],comando_tikz_anidado[4],self.area_de_dibujar,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n elif comando_tikz_anidado[0] in self.COMANDOS_VARIABLES_PYTIKZ:\n #Generar figuras en formato para la creacion de un GIF o JPG\n frames_foraech = self.__validar_variables_tikz(comando_tikz_anidado[0],comando_tikz_anidado[1],comando_tikz_anidado[2],habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n if len(frames_foraech):\n conjunto_de_comandos.append(frames_foraech)\n #Comandos del usuario...\n elif type(comando_tikz_anidado) is dict:\n for comando_personalizado in comando_tikz_anidado.values():\n for comando in comando_personalizado:\n if comando[0] in self.COMANDOS_DIBUJAR_PYTIKZ:\n #Generar figuras en formato para la creacion de un GIF o JPG\n self.__validar_dibujar(comando[0],comando[1],comando[2],comando[3],comando[4],self.area_de_dibujar,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n elif comando[0] in self.COMANDOS_VARIABLES_PYTIKZ:\n #Generar figuras en formato para la creacion de un GIF o JPG\n frames_foraech = self.__validar_variables_tikz(comando[0],comando[1],comando[2],habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n if len(frames_foraech):\n conjunto_de_comandos.append(frames_foraech)\n #Cada conjunto de comando estara dentro de una TUPLA, cada indice de conjunto_de_comandos, pertenece a los comandos anidados en un comando.\n conjunto_de_comandos.append([tuple(comando_personalizado)])\n\n #Generar GIF\n if(habilitado_generar_figura_en_formato[\"generar_dibujo_en_formato\"]):\n self.guardar_dibujo_en_imagen.crear_imagen()\n\n #Generar animación en aplicativo...\n index_lista_de_comandos = 0\n for index,comando_tikz_anidado in enumerate(codigo_tikz_anidado):\n if type(comando_tikz_anidado) is list:\n if comando_tikz_anidado[0] == \"foreach\":\n del codigo_tikz_anidado[index]\n for frames in conjunto_de_comandos[index_lista_de_comandos]:\n codigo_tikz_anidado.insert(0,frames)\n index_lista_de_comandos+=1\n elif type(comando_tikz_anidado) is dict:\n #Eliminar el diccionario del comandos de usuario personalizado\n del codigo_tikz_anidado[index]\n #Añadir todos los comandos en conjunto del comando personalizado al array codigo_tikz_anidado\n for frames_comando_personalizado in conjunto_de_comandos[index_lista_de_comandos]:\n codigo_tikz_anidado.insert(0,frames_comando_personalizado)\n index_lista_de_comandos+=1\n \n class MyWidget(Widget):\n my_list = ListProperty([])\n\n print(\"__________________________________________________________\")\n print(\"CODIGO ANIDADO A ANIMAR\")\n print(codigo_tikz_anidado)\n print(\"__________________________________________________________\")\n\n canvas_no_animar = MyWidget()\n canvas_no_animar.my_list = self.area_de_dibujar.canvas.children\n schedule_animate = partial(animar,codigo_tikz_anidado,canvas_no_animar.my_list)\n schedule_animate(schedule_animate)\n Clock.schedule_interval(schedule_animate,1)\n \n elif nombre_comando == \"guardarPytikz\":\n print(\"__________________________________________________________\")\n print(\"CODIGO ANIDADO A EJECUTAR\")\n print(funcion_de_comando[1][\"ejecutar\"])\n print(\"__________________________________________________________\")\n codigo_tikz_anidado = funcion_de_comando[1][\"ejecutar\"]\n\n habilitado_generar_figura_en_formato = {\"generar_dibujo_en_formato\":True, \"retornar_conjunto_de_codigos\":False}\n \n for comando_tikz_anidado in codigo_tikz_anidado:\n if(len(self.mensajes_de_error)>0):\n break\n #Comandos preexistentes...\n if type(comando_tikz_anidado) is list:\n if comando_tikz_anidado[0] in self.COMANDOS_DIBUJAR_PYTIKZ:\n #Dibujar comandos\n self.__validar_dibujar(comando_tikz_anidado[0],comando_tikz_anidado[1],comando_tikz_anidado[2],comando_tikz_anidado[3],comando_tikz_anidado[4],self.area_de_dibujar)\n #Generar figuras en formato para la creacion de un GIF o JPG\n self.__validar_dibujar(comando_tikz_anidado[0],comando_tikz_anidado[1],comando_tikz_anidado[2],comando_tikz_anidado[3],comando_tikz_anidado[4],self.area_de_dibujar,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n elif comando_tikz_anidado[0] in self.COMANDOS_VARIABLES_PYTIKZ:\n #Dibujar comandos\n self.__validar_variables_tikz(comando_tikz_anidado[0],comando_tikz_anidado[1],comando_tikz_anidado[2])\n #Generar figuras en formato para la creacion de un GIF o JPG\n self.__validar_variables_tikz(comando_tikz_anidado[0],comando_tikz_anidado[1],comando_tikz_anidado[2],habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n #Comandos del usuario...\n elif type(comando_tikz_anidado) is dict:\n for comando_personalizado in comando_tikz_anidado.values():\n for comando in comando_personalizado:\n if comando[0] in self.COMANDOS_DIBUJAR_PYTIKZ:\n #Dibujar comandos\n self.__validar_dibujar(comando[0],comando[1],comando[2],comando[3],comando[4],self.area_de_dibujar)\n #Generar figuras en formato para la creacion de un GIF o JPG\n self.__validar_dibujar(comando[0],comando[1],comando[2],comando[3],comando[4],self.area_de_dibujar,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n elif comando[0] in self.COMANDOS_VARIABLES_PYTIKZ:\n #Dibujar comandos\n self.__validar_variables_tikz(comando[0],comando[1],comando[2])\n #Generar figuras en formato para la creacion de un GIF o JPG\n self.__validar_variables_tikz(comando[0],comando[1],comando[2],habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n\n #Generar ARCHIVO\n if(habilitado_generar_figura_en_formato[\"generar_dibujo_en_formato\"]):\n self.guardar_dibujo_en_imagen.crear_imagen()\n \n elif nombre_comando == \"foreach\":\n #Generar valores según Foreach\n \n #Variables Foreach\n each = parametros_comando[0]\n codigo_tikz_anidado = funcion_de_comando[1][\"ejecutar\"]\n variables = parametros_comando[1][\"variables\"]\n\n #Variables del generador_valores mediante Foreach\n index = 0\n index_tipo = 0\n index_interior = 0\n\n comandos_tikz_depurado_anidado = []\n index_nuevo_codigo_tikz = 0\n generado_comandos_tikz_depurado_anidado = False\n\n def reemplazar_valores(codigo_tikz_anidado,var,valor_original,valor_a_reemplazar,index,index_tipo=None,index_interior=None):\n if isinstance(var,dict):\n var = var[\"variable\"]\n\n if re.search(r\"\\\\\"+var,valor_original):#Si hay variables...\n #Cambiar valor correspondiente por el asignado en el Foreach\n variables_anidado = valor_original[\n re.search(r\"\\\\\"+var,valor_original).start():\n re.search(r\"\\\\\"+var,valor_original).end()\n ]\n if(index_tipo!=None):\n if(index_interior!=None):\n valor_original_str = codigo_tikz_anidado[index][index_tipo][index_interior]\n else:\n valor_original_str = codigo_tikz_anidado[index][index_tipo]\n #Comprobar si se trata de una ecuación\n #Donde valor_a_reemplazar: Es el valor de una variable, es decir \\y (variables_anidado) -> 6pt (valor_a_reemplazar) \n resultado = valor_original_str.replace(variables_anidado,valor_a_reemplazar)\n resultado = self.evaluar.evaluar_metrica(resultado)\n if(resultado==None):\n indice = 0\n for mensaje_de_error_generado in self.evaluar.mensajes_de_error:\n self.evaluar.mensajes_de_error[indice] = \"Error en la linea del comando \"+str(self.linea_de_comando)+\": \"+mensaje_de_error_generado\n indice += 1\n self.mensajes_de_error.extend(self.evaluar.mensajes_de_error)\n return resultado\n else:\n return valor_original\n \n def generar_valores(codigo_tikz_anidado,var,valor,index_nuevo_codigo_tikz,index,index_tipo=None,index_interior=None):\n for codigo in codigo_tikz_anidado:\n if(isinstance(codigo,list)): #[[], {}], [('\\\\i', '0'), '1cm'], ['circle'], [[], {}]]\n for object in codigo:#\n if(isinstance(object,list) or isinstance(object,tuple)):#Recorrer [] o ()\n for string in object:\n #Comprobar si se trata de una ecuación\n validar_ecuacion = reemplazar_valores(codigo_tikz_anidado,var,string,valor,index,index_tipo,index_interior)\n if(validar_ecuacion != None):\n comandos_tikz_depurado_anidado[index_nuevo_codigo_tikz][index][index_tipo][index_interior] = validar_ecuacion\n else:\n return False\n index_interior += 1\n index_interior = 0\n elif(isinstance(object,str)):\n validar_ecuacion = reemplazar_valores(codigo_tikz_anidado,var,object,valor,index,index_tipo)\n if(validar_ecuacion != None):\n comandos_tikz_depurado_anidado[index_nuevo_codigo_tikz][index][index_tipo] = validar_ecuacion\n else:\n return False\n index_tipo+=1\n index_tipo = 0\n index+=1\n return True\n\n #Extraer valor each (Si son 2 variables)\n valor_primario = []\n valor_secundario = []\n for valor in each[0]:\n if len(valor.split(\"/\"))>0:\n index_valor_primari = 0\n for valor_split in valor.split(\"/\"):\n if(index_valor_primari==0 or not index_valor_primari%2):\n valor_primario.append(valor_split)\n else:\n valor_secundario.append(valor_split)\n index_valor_primari+=1\n else:\n # self.message_error.append(\"ERROR: DEBE DE TENER VALORES EACH PARA DOS VARIABLES\")\n valor_primario.append(valor)\n if(len(valor_secundario)>0):\n variables[0] = {\"variable\":variables[0],\"each\":valor_primario}\n variables[1] = {\"variable\":variables[1],\"each\":valor_secundario}\n #Generar valores Foreach\n for var in variables:\n if(isinstance(var,dict)):\n valor_each = var[\"each\"]\n var = var[\"variable\"]\n for codigo_arr in codigo_tikz_anidado:\n for valor in valor_each:\n if not generado_comandos_tikz_depurado_anidado:\n comandos_tikz_depurado_anidado.append(deepcopy(codigo_arr))\n valores_validos = generar_valores(codigo_arr,var,valor,index_nuevo_codigo_tikz,index,index_tipo,index_interior)\n if(not valores_validos):\n return False\n else:\n valores_validos = generar_valores(comandos_tikz_depurado_anidado[index_nuevo_codigo_tikz],var,valor,index_nuevo_codigo_tikz,index,index_tipo,index_interior)\n if(not valores_validos):\n return False\n index_nuevo_codigo_tikz+=1\n index=0\n else:\n for codigo_arr in codigo_tikz_anidado:\n for valor in each[0]:\n if not generado_comandos_tikz_depurado_anidado:\n comandos_tikz_depurado_anidado.append(deepcopy(codigo_arr))\n valores_validos = generar_valores(codigo_arr,var,valor,index_nuevo_codigo_tikz,index,index_tipo,index_interior)\n if(not valores_validos):\n return False\n else:\n valores_validos = generar_valores(comandos_tikz_depurado_anidado[index_nuevo_codigo_tikz],var,valor,index_nuevo_codigo_tikz,index,index_tipo,index_interior)\n if(not valores_validos):\n return False\n index_nuevo_codigo_tikz+=1\n index=0\n index_nuevo_codigo_tikz=0\n generado_comandos_tikz_depurado_anidado=True\n\n #Transpilacion de TikZ a codigo PyTiZ\n transpilador = Transpilador()\n comandos_pytikz_depurado_anidado = transpilador.tikz_a_pytikz(comandos_tikz_depurado_anidado)\n\n print(\"_____________________________________________-\")\n print(\"CONTENIDO FOREACH A EJECUTAR\")\n print(comandos_pytikz_depurado_anidado)#Y estos son los que se pasarán a dibujar...\n print(\"_____________________________________________-\")\n\n #Retornar lista de comandos si es para animar, no para generar GIF\n dibujar_comandos = False if \"generar_dibujo_en_formato\" in habilitado_generar_figura_en_formato.keys() else True\n generar_archivo = habilitado_generar_figura_en_formato[\"generar_dibujo_en_formato\"] if not dibujar_comandos else False\n retornar_conjunto_de_codigos = habilitado_generar_figura_en_formato[\"retornar_conjunto_de_codigos\"] if not dibujar_comandos else False\n if(not dibujar_comandos):\n def retornar_codigos(each,comandos_pytikz_depurado_anidado):\n #Dividir valores del foreach según Each, para facilitar la animación\n codigo_pytikz_por_frame = []\n total_frames = len(each[0])\n for _ in range(total_frames):\n codigo_pytikz_por_frame.append([])\n index = 0\n for codigo in comandos_pytikz_depurado_anidado:\n codigo_pytikz_por_frame[index].append(codigo)\n if(index == total_frames-1):\n index = 0\n else:\n index+=1\n nuevo_codigo_pytikz_por_frame = []\n for frame in codigo_pytikz_por_frame:\n nuevo_codigo_pytikz_por_frame.append(tuple(frame))\n return nuevo_codigo_pytikz_por_frame\n if(generar_archivo and retornar_conjunto_de_codigos):\n #Generar imagenes mediante comandos generados por foreach, para luego convertirlos a GIF y retornar conjunto de codigo tikz para animarse.\n for comando_pytikz_anidado in comandos_pytikz_depurado_anidado:\n self.__validar_dibujar(comando_pytikz_anidado[0],comando_pytikz_anidado[1],comando_pytikz_anidado[2],comando_pytikz_anidado[3],comando_pytikz_anidado[4],self.area_de_dibujar,habilitado_generar_figura_en_formato=habilitado_generar_figura_en_formato)\n return retornar_codigos(each,comandos_pytikz_depurado_anidado)\n if(not generar_archivo and retornar_conjunto_de_codigos):\n return retornar_codigos(each,comandos_pytikz_depurado_anidado)\n #Dibujar según comandos de Foreach\n elif(dibujar_comandos):\n for comando_pytikz_anidado in comandos_pytikz_depurado_anidado:\n self.__validar_dibujar(comando_pytikz_anidado[0],comando_pytikz_anidado[1],comando_pytikz_anidado[2],comando_pytikz_anidado[3],comando_pytikz_anidado[4],self.area_de_dibujar)","sub_path":"pytikzgenerate/modulos/validador_pytikz.py","file_name":"validador_pytikz.py","file_ext":"py","file_size_in_byte":97482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"144814470","text":"min_value = 100500\nmatrix_value = []\n\n\ndef calc(value, worker, free: set):\n global min_value\n\n if min_value < value:\n return\n\n if len(free) == 0:\n if min_value > value:\n min_value = value\n\n for work in free:\n rest = set(free)\n rest.remove(work)\n\n new_value = value + matrix_value[worker][work]\n calc(new_value, worker + 1, rest)\n\n\nwith open(\"input.txt\") as f:\n n = int(f.readline())\n for i in range(n):\n line = f.readline()\n row = list(map(int, line.split()))\n matrix_value.append(row)\n\n min_value = 100500\n start_free = set(range(n))\n calc(0, 0, start_free)\n print(min_value)\n","sub_path":"labs/L10/task3/t9_3.py","file_name":"t9_3.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"188775234","text":"\r\nimport pymel.core as pm\r\nimport maya.cmds as cmds\r\n\r\nimport miiTools.utils as miiUtils\r\n\r\ndef getValidName(name):\r\n\tfor i in range(1,9999):\r\n\t\tnewname = \"{0}_{1}\".format(name, i)\r\n\t\tif cmds.objExists(newname):\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\treturn newname\r\n\r\ndef createBlendshape():\r\n\t#\r\n\t# This is before I found the special uses of '#' inside maya create commands...\r\n\t# no need to use getValidName() here...\r\n\t#\r\n\t# blendshape_nodename = getValidName('blendShape')\r\n\t# cmds.blendShape(n=blendshape_nodename)[0]\r\n\t# cmds.setAttr(blendshape_nodename + '.w[0]', 1.0)\r\n\t# return blendshape_nodename\r\n\r\n\tblendshape_nodename = cmds.blendShape(n='blendShape_#')[0]\r\n\tcmds.setAttr(blendshape_nodename + '.w[0]', 1.0)\r\n\treturn blendshape_nodename\r\n\r\ndef contextDelete():\r\n\tedge_list = cmds.filterExpand(expand=True, selectionMask=32) # 32 -> Polygon Edges\r\n\r\n\t# If edges are selected, use Delete Edge command\r\n\tif(edge_list and len(edge_list) >= 1):\r\n\t\tcmds.polyDelEdge(cv=1, ch=1)\r\n\t\treturn 1\r\n\r\n\t# else, just do a normal delete\r\n\tcmds.delete()\r\n\r\ndef MirrorX(makeInstance=False):\r\n\t'''\r\n\tMirror objects across X axis\r\n\t'''\r\n\tmirrored_objs = []\r\n\r\n\tfor obj in pm.selected():\r\n\t\t\r\n\t\t# Make a copy\r\n\t\tif makeInstance:\r\n\t\t\tmirror_obj = pm.instance(obj, name=miiUtils.mirrorName(obj.nodeName()))[0]\r\n\t\telse:\r\n\t\t\tmirror_obj = pm.duplicate(obj, name=miiUtils.mirrorName(obj.nodeName()))[0]\r\n\t\t\r\n\t\t# Unparent the copy from any parent, and group it to a world group\r\n\t\ttmp_grp = pm.group(mirror_obj, w=True)\r\n\t\tpm.xform(tmp_grp, os=True, piv=(0,0,0))\r\n\t\t# Mirror it by scaling the world group negative\r\n\t\ttmp_grp.scaleX.set(-1)\r\n\t\t# Unparent the copy from the world group\r\n\t\tpm.parent(mirror_obj, w=True)\r\n\t\t# Delete the world group\r\n\t\tpm.delete(tmp_grp)\r\n\r\n\t\tif not makeInstance:\r\n\t\t\tif pm.mel.getApplicationVersionAsFloat() >= 2014.0:\r\n\t\t\t\t# NOTE: The 'preserveNormals' flag is new in 2014\r\n\t\t\t\tpm.makeIdentity(mirror_obj, apply=True, t=True, r=True, s=True, preserveNormals=True)\r\n\t\t\telse:\r\n\t\t\t\t# Get all the mesh within the hierarchy and reverse their normal\r\n\t\t\t\tfor mesh in pm.listRelatives(mirror_obj, allDescendents=True, type='mesh', fullPath=True):\r\n\t\t\t\t\tpm.polyNormal(mesh, normalMode=0, userNormalMode=0, ch=True)\r\n\t\t\t\t\tpm.delete(mirror_obj, ch=True) # Delete mirror_obj's history\r\n\t\t\t\t\tmesh.opposite.set(0)\r\n\t\t\r\n\t\t# Mirror naming for the childs\r\n\t\tfor transform in pm.listRelatives(mirror_obj, allDescendents=True, type='transform', fullPath=True):\r\n\t\t\tpm.rename(transform, miiUtils.mirrorName(transform.nodeName()))\r\n\r\n\t\tmirrored_objs.append(mirror_obj)\r\n\r\n\tpm.select(cl=True)\r\n\tpm.select(mirrored_objs)\r\n","sub_path":"scripts/miitools/modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"568354381","text":"# -*- coding: utf-8 -*-\n# NoJoy_DI (c) 2016 by Andre Karlsson\n#\n# This file is part of NoJoy_DI.\n#\n# NoJoy_DI is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# NoJoy_DI is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with NoJoy_DI. If not, see .\n#\n# Filename: by: andrek\n# Timesamp: 5/1/16 :: 10:25 PM\n\n\nimport functools\nimport sys\n\nfrom src.utils.NoJoy_DI.service import Service\nfrom src.utils.NoJoy_DI.utils import *\nfrom src.utils.NoJoy_DI.patterns import *\nfrom src.utils.NoJoy_DI.exceptions import *\n\n#version hack\ntry:\n\tfrom inspect import signature, Parameter\n\tsignature_empty = Parameter.empty\nexcept ImportError:\n\tfrom src.utils.funcsigs import signature\n\tfrom src.utils.funcsigs import _empty as signature_empty\n\n\nclass DI(object):\n\t\"\"\"\n\tJoyiders Norse Dependency Injection Classifcation container!\n\t\"\"\"\n\n\tmy_patterns = []\n\tmy_patterns_cls = []\n\n\tdef __init__(self):\n\t\tsuper(DI, self).__init__()\n\t\tself.services = {}\n\t\tself.variables = {}\n\t\tself.my_service_name = object_name_standard(self.__class__)\n\t\tself.create_patterns(SingletonPattern, DefaultPattern, BorgPattern)\n\n\n\tdef create_patterns(self, *trees):\n\t\t\"\"\"\n\t\tLoad the design patterns from patterns.py\n\n\t\t:param trees: Args of patterns to load\n\t\t:return: Nothing\n\t\t\"\"\"\n\t\tthese_patterns = []\n\t\tthese_patterns_cls = []\n\n\t\tfor tree in trees:\n\t\t\tif isinstance(tree, BasePattern):\n\t\t\t\tthese_patterns.append(tree)\n\t\t\t\tthese_patterns_cls.append(tree.__class__)\n\t\t\telse:\n\t\t\t\tthese_patterns.append(tree())\n\t\t\t\tthese_patterns_cls.append(tree)\n\t\tself.my_patterns = tuple(these_patterns)\n\t\tself.my_patterns_cls = dict([(obj, inst) for inst, obj in enumerate(tuple(these_patterns_cls))])\n\n\tdef set(self, name):\n\t\tsvc = Service(name)\n\t\tself.services[svc.name] = svc\n\t\treturn svc\n\n\n\tdef attempt(self, name,shared=False):\n\t\t\"\"\"\n\t\tAdd a NON existing service to the DI container\n\n\t\t:param name: The service to be added\n\t\t:param shared: Shared service or not Default False(DefaultPattern)\n\t\t:return: Service if success, false if service already exists in Container\n\t\t\"\"\"\n\t\tif object_name_standard(name) not in self.services:\n\t\t\ts = Service(name)\n\t\t\tif isinstance(shared, bool) and shared:\n\t\t\t\ts.set_pattern(SingletonPattern)\n\t\t\tself.services[s.name] = s\n\t\t\treturn s\n\t\treturn False\n\n\tdef has_service(self, service):\n\t\t\"\"\"\n\t\tChecks whether the DI contains the Service\n\n\t\t:param service: The service to check if exists\n\t\t:return: True if the service exists else False\n\t\t\"\"\"\n\t\tname = object_name_standard(service)\n\t\tif name in self.services or name == self.my_service_name:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef has_variable(self, variabel):\n\t\t\"\"\"\n\t\tChecks whether the DI contains the variable\n\n\t\t:param variabel: The variable to check if exists\n\t\t:return: True if the variable exists otherwise False\n\t\t\"\"\"\n\t\tif object_name_standard(variabel) in self.variables:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef remove_variable(self, variabel):\n\t\t\"\"\"\n\t\tDelete the variable from the variable list\n\n\t\t:param variabel: The variable remove\n\t\t:return: True if the variable was deleted, otherwise KeyError\n\t\t\"\"\"\n\t\tif object_name_standard(variabel) in self.variables:\n\t\t\ttry:\n\t\t\t\tself.variables.pop(object_name_standard(variabel))\n\t\t\t\treturn True\n\t\t\texcept KeyError as ke:\n\t\t\t\treturn ke\n\t\telse:\n\t\t\traise KeyError(\"Key %s not found in injected variable list\" % variabel)\n\n\n\tdef get(self, service):\n\t\t\"\"\"\n\t\tWill instantiate and return the service as an instance\n\n\t\t>>> di.get(AClass)\n\t\t\n\t\t>>> isinstance(di.get(AClass), AClass)\n\t\tTrue\n\n\t\t:param service: Service to instantiate\n\t\t:return: The Instantiated class\n\t\t\"\"\"\n\t\tname = object_name_standard(service)\n\t\tif self.has_service(name):\n\t\t\treturn self._get_data(service)\n\t\traise Exception(\"Unknown Service or Service not available: \" + name)\n\n\tdef get_raw(self, service):\n\t\t\"\"\"\n\t\tWill return the `Raw` Service of the Class\n\n\t\t:param service: Service to get Raw data from\n\t\t:return: Class: Service for your service\n\t\t\"\"\"\n\t\tname = object_name_standard(service)\n\t\tif name not in self.services:\n\t\t\traise Exception(\"Raise Error unknown service: \" + name)\n\t\treturn self.services[name]\n\n\n\tdef add_variable(self, name, value):\n\t\t\"\"\"\n\t\tAdd a variable to the DI Container\n\n\t\t>>>di.add_variable(\"A_variable\", \"The variable value\")\n\n\t\t:param name: Name of the Variabel\n\t\t:param value: Value Of the Variable\n\t\t:return: True if success or Exception if fail\n\t\t\"\"\"\n\t\ttry:\n\t\t\tself.variables[name] = value\n\t\t\treturn True\n\t\texcept Exception as e:\n\t\t\treturn e\n\n\n\n\tdef get_variable(self, name):\n\t\t\"\"\"\n\t\tWill return the variable [name] from the DI Container\n\n\t\t>>> di.get_variable(\"A_variable\")\n\t\t'The variable value'\n\n\t\t:param name: Name of the Variable\n\t\t:return: Value of variable [name]\n\t\t\"\"\"\n\t\tif name in self.variables:\n\t\t\treturn self.variables[name]\n\t\telse:\n\t\t\traise Exception(\"Unknown variable name: \" + name)\n\n\n\tdef _get_data(self, myservice, req_tokens=None):\n\t\tname = object_name_standard(myservice)\n\n\t\tif name == self.my_service_name:\n\t\t\treturn self\n\n\t\tif not self.has_service(myservice):\n\t\t\traise Exception(\"Raise Error unknown service: \" + name)\n\n\t\tservice_definition = self.services.get(name)\n\t\tmy_tree = service_definition._mypattern\n\n\t\tif not my_tree in self.my_patterns_cls:\n\t\t\traise Exception(\"Unknown pattern state\")\n\n\t\ttree_idx = self.my_patterns_cls[my_tree]\n\n\t\tif not req_tokens:\n\t\t\treq_tokens = []\n\t\telse:\n\t\t\treq_tree = req_tokens[-1]._mypattern\n\t\t\tif req_tree and tree_idx > self.my_patterns_cls[req_tree]:\n\t\t\t\traise PatternizerException(service_definition, req_tokens)\n\n\t\tdef transformer(v):\n\t\t\tif isinstance(v, LazyMarker):\n\t\t\t\treturn v.transformer(lambda name: self._get_data(name, req_tokens + [service_definition]), self.get_variable)\n\t\t\telse:\n\t\t\t\treturn v\n\n\t\tdef service_maker():\n\t\t\treturn self._make(service_definition, transformer)\n\n\t\treturn self.my_patterns[tree_idx].get(service_maker, name)\n\n\tdef _update_input_from_signature(self, function, types_kwargs):\n\t\ttry:\n\t\t\tsig = signature(function)\n\t\texcept ValueError:\n\t\t\treturn\n\n\t\tfor name, parameter in tuple(sig.parameters.items()):\n\t\t\tif name == \"self\":\n\t\t\t\tcontinue\n\t\t\tif parameter.annotation is signature_empty:\n\t\t\t\tcontinue\n\t\t\tobject_name = object_name_standard(parameter.annotation)\n\n\t\t\tif object_name in self.services:\n\t\t\t\ttypes_kwargs.setdefault(name, LazyMarker(service=object_name))\n\n\n\tdef _make(self, svc_def, transformer):\n\t\tsvc_def._locked = True\n\n\t\tdef transform_input(types_kwargs):\n\t\t\treturn dict([(key, transformer(value)) for key, value in types_kwargs.items()])\n\n\t\tif svc_def._factory:\n\t\t\tcls = transformer(svc_def._factory)\n\t\telse:\n\t\t\tcls = svc_def._get_classification()\n\n\t\ttypes_kwargs = dict(svc_def._input)\n\t\tself._update_input_from_signature(cls.__init__, types_kwargs)\n\n\t\ttypes_kwargs = transform_input((types_kwargs))\n\n\t\tfor config in svc_def._arguments_injectors:\n\t\t\ttransformer(config)(types_kwargs)\n\n\t\tmyinstance = cls(**types_kwargs)\n\n\t\tfor config in svc_def._injectors:\n\t\t\ttransformer(config)(myinstance)\n\n\t\tfor key, value in transform_input(svc_def._sets).items():\n\t\t\tsetattr(myinstance, key, value)\n\n\t\tfor active_signature, caller_function, caller_input in svc_def._callers:\n\t\t\tcallable = getattr(myinstance, caller_function)\n\t\t\ttypes_kwargs = dict(caller_input)\n\t\t\tif active_signature:\n\t\t\t\tself._update_input_from_signature(callable, types_kwargs)\n\t\t\tcallable(**transform_input(types_kwargs))\n\n\t\treturn myinstance\n","sub_path":"src/utils/NoJoy_DI/di.py","file_name":"di.py","file_ext":"py","file_size_in_byte":7861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"602426240","text":"import csv\n\nimport requests\n\ncore_url = 'https://www.kulturarvsdata.se/ksamsok/api?method=statisticSearch&index=fromTime=*&query=(create_fromTime>=0%20OR%20produce_fromTime>=0%20OR%20use_fromTime>=0)%20OR%20(create_fromTime<=0%20OR%20produce_fromTime<=0%20OR%20use_fromTime<=0)'\n\nheaders = {\n 'Accept': 'json'\n}\n\nr = requests.get(core_url, headers=headers)\nraw = r.json()\n\nlist_of_values = set()\nfor item in raw['result']['term']:\n list_of_values.add(item['indexFields']['value'])\n\nlist_of_values = sorted(list_of_values, key=int)\n\ntime_fcts = []\nwith open('basis_data/time_fct.csv') as csvfile:\n time_fcts = list(csv.reader(csvfile))\n\nfor i, fct in enumerate(time_fcts):\n print('fct:' + fct[0])\n fct_filter = ''\n for value in list_of_values:\n try:\n if int(fct[0]) <= value <= int(time_fcts[i+1][0]) and value != int(time_fcts[i+1][0]):\n if len(fct_filter) > 0:\n fct_filter += '%20OR%20'\n fct_filter += '(create_fromTime>={0}%20OR%20produce_fromTime>={0}%20OR%20use_fromTime>={0})'.format(value)\n except:\n if int(fct[0]) <= value:\n if len(fct_filter) > 0:\n fct_filter += '%20OR%20'\n fct_filter += '(create_fromTime>={0}%20OR%20produce_fromTime>={0}%20OR%20use_fromTime>={0})'.format(value)\n fct.insert(0, fct_filter)\n fct.insert(0, i)\n\nwith open('time_fct.csv', 'w')as output:\n writer = csv.writer(output)\n for row in time_fcts:\n writer.writerow(row)\n\nprint('DONE')\n","sub_path":"scripts/time_fct.py","file_name":"time_fct.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362656936","text":"import os\nfrom fastapi import FastAPI, Request, Depends, HTTPException\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.security import OAuth2PasswordBearer\nfrom pydantic import BaseModel\nfrom sqlalchemy.orm import Session\nfrom enum import Enum\nfrom typing import List, Optional\nimport databases\nfrom ext import mako, SessionLocal, Base, db_engine, AioDataBase\nfrom models import model, schemas, var\nfrom views import crud, users, admin\nimport config\n\napp = FastAPI()\n\napp.__name__ = 'fast_blog'\n\nmako.init_app(app)\n\nmodel.Base.metadata.create_all(bind=db_engine)\n\naio_database = AioDataBase\n\n\nclass ModelName(str, Enum):\n alexnet = 'alexnet'\n resnet = 'resnet'\n lenet = 'lenet'\n\nclass UserAuth(BaseModel):\n username: str\n email: Optional[str] = None\n full_name: Optional[str] = None\n disabled: Optional[bool] = None\n\ndef fake_decode_token(token):\n return UserAuth(\n username=token + \"fakedecoded\",\n email='xsxsxs@com',\n full_name='Josnh',\n )\n# async def get_current_user(token: str=Depends(oauth2_scheme)):\n# user = fake_decode_token(token)\n# return user\n\ntest_item = {\n 'name': \"test\",\n \"price\": 11\n}\n\ndef get_db():\n try:\n db = SessionLocal()\n yield db\n finally:\n db.close()\n\n\nasync def common_params(skip: int=0, limit: int = 100):\n return {'skip': skip, 'limit': limit}\n\n\n@app.get('/items/{item_id}')\ndef read_item(item_id: int, q: str=None):\n return {\"item_id\": item_id, \"q\": q}\n\n@app.get('/items/')\ndef read_q(item_name: str):\n pass\n\n@app.put('/items/{item_id}')\ndef update_item(item_id: int, item: schemas.Item):\n return {\"item_name\": item.name, \"item_id\": item_id}\n\n\n@app.post('/api/users/', response_model=schemas.User)\ndef create_user(user: schemas.UserCreate, db: Session=Depends(get_db)):\n db_user = crud.get_user_by_email(db, email=user.email)\n if db_user:\n raise HTTPException(status_code=400, detail='Email already exists')\n return crud.create_user(db=db, user=user)\n\n@app.get('/api/users/{user_id}', response_model=schemas.User)\ndef read_user(user_id: int, db: Session=Depends(get_db)):\n db_user = crud.get_user(db=db, user_id=user_id)\n if db_user is None:\n raise HTTPException(status_code=404, detail='No such user')\n return db_user\n\n# @app.get('/api/users', response_model=List[schemas.User])\n# def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):\n# users = crud.get_users(db=db, skip=skip, limit=limit)\n# return users\n@app.get('/api/users', response_model=List[schemas.User], name='users')\ndef read_users(com_p: dict=Depends(common_params), db: Session = Depends(get_db)):\n users = crud.get_users(db=db, skip=com_p['skip'], limit=com_p['limit'])\n return users\n\n@app.post('/api/{user_id}/items/', response_model=schemas.Item)\ndef create_item_for_user(\n user_id: int, item: schemas.ItemCreate, db: Session=Depends(get_db)\n):\n return crud.create_user_item(db=db, item=item, user_id=user_id)\n\n@app.get('/api/items', response_model=List[schemas.Item]) \ndef read_items(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n items = crud.get_items(db=db, skip=skip, limit=limit)\n return items\n\n\n\n@app.get('/model/{model_name}')\nasync def get_model(model_name: ModelName):\n if model_name == ModelName.alexnet:\n return {\"model_name\": model_name}\n if model_name.value == 'lenet':\n return {\"model_name\": model_name}\n\n\n@app.get('/', response_class=HTMLResponse)\n@mako.template('index.html')\ndef index(request: Request):\n setattr(request, 'mako', 'test')\n return {'title': 'Yurs'}\n\n@app.get('/async_index', response_class=HTMLResponse)\n@mako.template('index.html')\nasync def async_index(request: Request):\n setattr(request, 'mako', 'test')\n return {'title': 'Yurs'}\n\n\n@app.on_event(\"startup\")\nasync def startup():\n global aio_database\n await aio_database.connect()\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown():\n global aio_database\n await aio_database.disconnect()\n\n@app.middleware('http')\nasync def set_context(req: Request, call_next):\n global aio_database\n if aio_database is None:\n print('aio database is NOne...')\n else:\n var.aio_databases.set(aio_database)\n response = await call_next(req)\n return response\n\nasync def custome_middware(req: Request, call_next):\n print('In custome middleware...')\n response = await call_next(req)\n return response\n\n# @app.get('/api/users/me')\n# async def read_users_me(current_user: UserAuth=Depends(get_current_user)):\n# return current_user\n\napp.include_router(\n users.router,\n prefix='/api/async_users'\n)\n\nprint(app.url_path_for('users'))\n# app['some_key'] = 'ax'\nsetattr(app, 'some_key', 'aa')\n\n\n\napp.user_middleware.append(custome_middware)\nprint(app.user_middleware)\napp.__name__ = 'fast_blog'\nprint(app.__name__)\nsetattr(app, 'config', config)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"238819691","text":"#!/usr/bin/env python3\n# bot.py\nimport os\nimport discord\nimport re\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\nTOKEN = os.getenv('DISCORD_TOKEN')\nGUILD = os.getenv('DISCORD_GUILD')\nTARGET_USER = os.getenv('TARGET_USER')\nCURRENT_USER = os.getenv('CURRENT_USER')\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n for guild in client.guilds:\n if guild.name == GUILD:\n break\n\n print(\n f'{client.user} is connected to the following guild:\\n'\n f'{guild.name}(id: {guild.id})\\n'\n )\n\ndef get_user(username):\n return discord.utils.get(client.get_all_members(), name=username.split('#')[0], discriminator=username.split('#')[1])\n\ndef is_balance_message(message):\n if not message.embeds:\n return False\n\n username = CURRENT_USER.split('#')[0] \n balance_title = f'{username}\\'s balance'\n return balance_title in message.embeds[0].title \n\ndef get_wallet_total(balance_message):\n embed_msg = balance_message.embeds[0].description\n result = re.search('\\*\\*Wallet\\*\\*: (.*)\\n', embed_msg).group(1)\n return int(result.replace(',',''))\n\ndef is_police_message(message):\n id = get_user(CURRENT_USER).id\n return '<@' + str(id) + '> The police are here, and they\\'re after you! Type' in message.content\n\ndef get_police_secret(message):\n return re.search('`.*`', message.content).group(1)\n\n@client.event\nasync def on_message(message):\n if is_police_message(message):\n print(\"We found a police message\")\n print(get_police_secret(message))\n elif is_balance_message(message):\n print(\"We found a balance message\")\n print(f'current user has {get_wallet_total(message)} coins')\n# if str(message.author) == TARGET_USER:\n# embed_list = message.embeds\n# for embed in embed_list:\n# print(embed.title)\n# print(embed.description)\nclient.run(TOKEN)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"196362094","text":"# -*- coding: utf-8 -*-\nfrom datetime import date\n\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.sites.models import Site\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom model_utils.models import TimeStampedModel\n\nfrom .utils import get_quarter_number\nfrom .querysets import MetricItemQuerySet, DayMetricQuerySet, WeekMetricQuerySet, MonthMetricQuerySet, QuarterMetricQuerySet, YearMetricQuerySet\n\n\nclass Metric(TimeStampedModel):\n name = models.CharField(max_length=90)\n description = models.TextField(blank=True, null=True)\n slug = models.SlugField(unique=True, max_length=100, db_index=True)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = _('metric')\n verbose_name_plural = _('metrics')\n\n\nclass AbstractMetric(models.Model):\n metric = models.ForeignKey(Metric)\n count = models.IntegerField(default=0)\n date_up = models.DateField(default=date.today)\n\n site = models.ForeignKey(Site)\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n object_id = models.PositiveIntegerField()\n content_object = GenericForeignKey('content_type', 'object_id')\n\n def __str__(self):\n values = dict(\n name=self.metric,\n count=self.count,\n date_up=self.date_up.strftime(\"%b. %d %Y\")\n )\n if self.content_object:\n string = u\"%(count)s '%(name)s' for '%(content_object)s' on %(date_up)s\"\n values[\"content_object\"] = self.content_object\n elif self.content_type and self.object_id:\n string = u\"%(count)s '%(name)s' for ('%(content_type)s', '%(object_id)s') on %(date_up)s\"\n values[\"content_type\"] = self.content_type\n values[\"object_id\"] = self.object_id\n else:\n string = u\"%(count)s '%(name)s' for %(date_up)s\"\n return string % values\n\n class Meta:\n abstract = True\n verbose_name = _('abstract metric item')\n verbose_name_plural = _('abstract metric items')\n\n\nclass MetricItem(AbstractMetric):\n objects = MetricItemQuerySet.as_manager()\n\n def save(self, *args, **kwargs):\n if self.count == 0:\n self.count = 1\n return super(MetricItem, self).save(*args, **kwargs)\n\n class Meta:\n verbose_name = _('metric item')\n verbose_name_plural = _('metric items')\n\n\nclass DayMetric(AbstractMetric):\n objects = DayMetricQuerySet.as_manager()\n\n def __str__(self):\n values = dict(\n name=self.metric.name,\n date_up=self.date_up.strftime(\"%b. %d %Y\")\n )\n if self.content_object:\n string = u\"'%(name)s' for '%(content_object)s' on %(date_up)s\"\n values[\"content_object\"] = self.content_object\n elif self.content_type and self.object_id:\n string = u\"'%(name)s' for ('%(content_type)s', '%(object_id)s') on %(date_up)s\"\n values[\"content_type\"] = self.content_type\n values[\"object_id\"] = self.object_id\n else:\n string = \"'%(name)s' for '%(date_up)s'\"\n return string % values\n\n class Meta:\n verbose_name = _('day metric')\n verbose_name_plural = _('day metrics')\n\n\nclass WeekMetric(AbstractMetric):\n objects = WeekMetricQuerySet.as_manager()\n\n def __str__(self):\n values = dict(\n name=self.metric.name,\n week=self.date_up.strftime(\"%U\"),\n year=self.date_up.strftime(\"%Y\")\n )\n if self.content_object:\n string = u\"'%(name)s' for '%(content_object)s' on week %(week)s of year %(year)s\"\n values[\"content_object\"] = self.content_object\n elif self.content_type and self.object_id:\n string = u\"'%(name)s' for ('%(content_type)s', '%(object_id)s') on week %(week)s of year %(year)s\"\n values[\"content_type\"] = self.content_type\n values[\"object_id\"] = self.object_id\n else:\n string = \"'%(name)s' for week %(week)s of year %(year)s\"\n return string % values\n\n class Meta:\n verbose_name = _('week metric')\n verbose_name_plural = _('week metrics')\n\n\nclass MonthMetric(AbstractMetric):\n objects = MonthMetricQuerySet.as_manager()\n\n def __str__(self):\n values = dict(\n name=self.metric.name,\n month=self.date_up.strftime(\"%B\"),\n year=self.date_up.strftime(\"%Y\")\n )\n if self.content_object:\n string = u\"'%(name)s' for '%(content_object)s' on %(month)s %(year)s\"\n values[\"content_object\"] = self.content_object\n elif self.content_type and self.object_id:\n string = u\"'%(name)s' for ('%(content_type)s', '%(object_id)s') on %(month)s %(year)s\"\n values[\"content_type\"] = self.content_type\n values[\"object_id\"] = self.object_id\n else:\n string = \"'%(name)s' for %(month)s %(year)s\"\n return string % values\n\n class Meta:\n verbose_name = _('month metric')\n verbose_name_plural = _('month metrics')\n\n\nclass QuarterMetric(AbstractMetric):\n objects = QuarterMetricQuerySet.as_manager()\n\n def __str__(self):\n values = dict(\n name=self.metric.name,\n quarter=get_quarter_number(self.date_up, True),\n year=self.date_up.strftime(\"%Y\")\n )\n if self.content_object:\n string = u\"'%(name)s' for '%(content_object)s' on quarter %(quarter)s of year %(year)s\"\n values[\"content_object\"] = self.content_object\n elif self.content_type and self.object_id:\n string = u\"'%(name)s' for ('%(content_type)s', '%(object_id)s') on quarter %(quarter)s of year %(year)s\"\n values[\"content_type\"] = self.content_type\n values[\"object_id\"] = self.object_id\n else:\n string = \"'%(name)s' for %(year)s\"\n return string % values\n\n class Meta:\n verbose_name = _('querter metric')\n verbose_name_plural = _('quarter metrics')\n\n\nclass YearMetric(AbstractMetric):\n objects = YearMetricQuerySet.as_manager()\n\n def __str__(self):\n values = dict(\n name=self.metric.name,\n year=self.date_up.strftime(\"%Y\")\n )\n if self.content_object:\n string = u\"'%(name)s' for '%(content_object)s' on %(year)s\"\n values[\"content_object\"] = self.content_object\n elif self.content_type and self.object_id:\n string = u\"'%(name)s' for ('%(content_type)s', '%(object_id)s') on %(year)s\"\n values[\"content_type\"] = self.content_type\n values[\"object_id\"] = self.object_id\n else:\n string = \"'%(name)s' for %(year)s\"\n return string % values\n\n class Meta:\n verbose_name = _('year metric')\n verbose_name_plural = _('year metrics')\n\n\n\n","sub_path":"time_metrics/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"428766596","text":"MAIN_SETTINGS = {\n # Теги подлежащие к обязательному удалению.\n 'trash_tags': ['script', 'noscript', 'style', 'meta', 'footer', 'code', 'link', 'aside', 'iframe', 'svg'],\n # Награды/Штрафы за теги\n 'good_tags': [\n {\n 'tags': ['p'],\n 'min_len': 10,\n 'award': 150,\n 'once': True\n },\n {\n 'tags': ['h1', 'h2'],\n 'min_len': 10,\n 'award': 150,\n 'once': True\n },\n {\n 'tags': ['time'],\n 'min_len': 1,\n 'award': 150,\n 'once': True\n }\n ],\n # Удаление `не значимых` тегов\n 'minimal_remove': [\n {\n 'tag': 'td',\n 'max_len': 10,\n 'max_childrens': 2\n },\n {\n 'tag': 'tr',\n 'max_len': 10,\n 'max_childrens': 2\n },\n {\n 'tag': 'table',\n 'max_len': 10,\n 'max_childrens': 2\n }\n \n ],\n # Награды за присутствие определенных слов в атрибуте\n 'meaningful_words': [\n {\n 'attr': 'class',\n 'words': ['post', 'entry', 'content', 'text', 'body', 'news', 'article'],\n 'term': 25\n },\n {\n 'attr': 'id',\n 'words': ['post', 'entry', 'content', 'text', 'body', 'news'],\n 'term': 25\n },\n {\n 'attr': 'class',\n 'words': ['comment', 'foot', 'footer', 'navbar', 'header', 'Ad'],\n 'term': -25\n },\n {\n 'attr': 'id',\n 'words': ['comment', 'foot', 'footer', 'navbar', 'header', 'Ad'],\n 'term': -25\n },\n ]\n}","sub_path":"Settings/main_settings.py","file_name":"main_settings.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"471842203","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^register/$',views.register,name='register'),\n url(r'^register_handle/$',views.register_handle,name='register_handle'),\n url(r'^register_exit/$',views.register_exit,name='register_exit'),\n url(r'^login/$',views.login,name='login'),\n url(r'^login_handle/$',views.login_handle,name='login_handle'),\n url(r'^logout/$',views.login_handle,name='logout'),\n # url(r'^login_handle/$',views.login_handle1),\n # url(r'^user_exit/$',views.user_exit),\n # url(r'^upwd_exit/$',views.upwd_exit),\n url(r'^info/$',views.info,name='info'),\n url(r'^order/(\\d+)$',views.order,name='order'),\n url(r'^site/$',views.site,name='site'),\n]\n","sub_path":"dailyfresh/df_user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"492870986","text":"#!/usr/bin/env python\n\"\"\"Run a Gene Ontology Enrichment Analysis (GOEA), plots, etc.\n\n Nature 2014_0126;\n\t\t\tComputational analysis of cell-to-cell heterogeneity\n in single-cell RNA-sequencing data reveals hidden\n subpopulations of cells\n http://www.nature.com/nbt/journal/v33/n2/full/nbt.3102.html#methods\n\"\"\"\n\nfrom goatools.test_data.genes_NCBI_10090_ProteinCoding import GENEID2NT as GeneID2nt_mus\nfrom goatools.test_data.nature3102_goea import get_geneid2symbol, get_goeaobj\n\n__copyright__ = \"Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved.\"\n__author__ = \"DV Klopfenstein\"\n\ndef test_example():\n \"\"\"Run Gene Ontology Enrichment Analysis (GOEA) on Nature data.\"\"\"\n # --------------------------------------------------------------------\n # --------------------------------------------------------------------\n # Gene Ontology Enrichment Analysis (GOEA)\n # --------------------------------------------------------------------\n # --------------------------------------------------------------------\n taxid = 10090 # Mouse study\n # Load ontologies, associations, and population ids\n geneids_pop = GeneID2nt_mus.keys()\n geneids2symbol_study = get_geneid2symbol(\"nbt.3102-S4_GeneIDs.xlsx\")\n geneids_study = geneids2symbol_study.keys()\n goeaobj = get_goeaobj(\"fdr_bh\", geneids_pop, taxid)\n # Run GOEA on study\n goea_results_all = goeaobj.run_study(geneids_study)\n goea_results_sig = [r for r in goea_results_all if r.p_fdr_bh < 0.05]\n # Print GOEA results to files: With study genes printed as geneids or symbols\n goeaobj.wr_xlsx(\"nbt3102_sig_symbols.xlsx\", goea_results_sig, itemid2name=geneids2symbol_study)\n goeaobj.wr_xlsx(\"nbt3102_sig_geneids.xlsx\", goea_results_sig)\n goeaobj.wr_xlsx(\"nbt3102_all_symbols.xlsx\", goea_results_all, itemid2name=geneids2symbol_study)\n goeaobj.wr_xlsx(\"nbt3102_all_geneids.xlsx\", goea_results_all)\n\nif __name__ == '__main__':\n test_example()\n\n# Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved.\n","sub_path":"tests/test_nbt3102_goea.py","file_name":"test_nbt3102_goea.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"508463200","text":"import numpy as np\r\n\r\nclass Classifier():\r\n def __init__(self, w_star):\r\n \"\"\"\r\n Member Variables\r\n - w (np.array) := Parameter of size (dim, 1).\r\n - w_star (np.array) := Actual parameters of size (dim, 1)\r\n \"\"\"\r\n self.w = None\r\n self.w_star = w_star\r\n \r\n def obj(self, X, y, reg):\r\n \"\"\"\r\n Compute the value of the loss function.\r\n Inputs:\r\n - X (np.array) := The data to calculate the loss on of\r\n size (N, dim).\r\n - y (np.array) := The corresponding labels of the data of size\r\n (N, 1).\r\n - reg (float) := The regularization parameter.\r\n Outputs: \r\n - obj (float) := Value of the objective function.\r\n \"\"\"\r\n pass\r\n \r\n def grad(self, X_batch, y_batch, reg):\r\n \"\"\"\r\n Compute the gradient.\r\n Inputs:\r\n - X_batch (np.array) := The data to calculate the gradient on of\r\n size (N, dim).\r\n - y (np.array) := The corresponding labels of the data of size\r\n (N, 1).\r\n - reg (float) := The regularization parameter.\r\n Outputs:\r\n - grad (np.array) := Gradient with respect to self.w of size (dim, 1).\r\n \"\"\"\r\n pass\r\n\r\n def SGD(self, X, y, step_size=0.1, reg=1e-4, epochs=100, batch_size=50, \r\n experiments=1, w_next=None, decay=False):\r\n \"\"\"\r\n Perform SGD.\r\n Input:\r\n - X (np.array) := The data of size (N x dim).\r\n - y (np.array) := The labels of the data of size (N x 1).\r\n - step_size (float) := Step size.\r\n - reg (float) := The regularization parameter.\r\n - epochs (int) := The number of passes through the data.\r\n - batch_size (int) := The amount of data to sample at each sub-iteration.\r\n - w_next (np.array) := If this is passed, we initialize w as w_next. It is of\r\n size (dim x 1).\r\n - decay (boolean) := False if no decay rate. True if use decaying rate.\r\n Output:\r\n - obj_SGD (np.array) := Array of objective values at each epoch. Has size (Epoch x 1)\r\n - obj_SGD_iters (np.array) := Array of objective values at each iteration. Has size (Epoch x 1)\r\n - MSE (np.array) := Array of the MSE at each iteration. (Iterations x 1)\r\n \"\"\"\r\n N, dim = X.shape\r\n \r\n obj_SGD = np.zeros((epochs, 1))\r\n max_iters = int(N/batch_size)\r\n obj_SGD_iters = np.zeros((int(epochs*max_iters), 1))\r\n MSE = np.zeros((int(epochs*max_iters), 1))\r\n\r\n for k in range(experiments):\r\n self.w = 0.001 * np.random.randn(dim, 1)\r\n if w_next is not None:\r\n self.w = w_next\r\n for i in range(epochs):\r\n obj_SGD[i] += self.obj(X, y, reg).item()\r\n if i % 10 == 0:\r\n print(f\"Experiment: {k}/{experiments}, Epoch: {i}/{epochs}, Loss: {obj_SGD[i]/(k+1)}\")\r\n for j in range(max_iters):\r\n rand_idx = np.random.randint(0, N-1, batch_size)\r\n X_batch = X[rand_idx, :]\r\n y_batch = y[rand_idx]\r\n obj_SGD_iters[i*max_iters + j] += self.obj(X, y, reg).item()\r\n MSE[i*max_iters + j] += np.linalg.norm(self.w - self.w_star, 2)\r\n if decay == False:\r\n self.w = self.w - step_size * self.grad(X_batch, y_batch, reg)\r\n else:\r\n self.w = self.w - .1/(reg*(j+1000)) * self.grad(X_batch, y_batch, reg)\r\n obj_SGD /= experiments\r\n obj_SGD_iters /= experiments\r\n MSE /= experiments\r\n return obj_SGD, obj_SGD_iters, MSE\r\n\r\n def FedAVG(self, X, y, comm, step_size=0.1, reg=1e-4, epochs=100, batch_size=50, \r\n experiments=25, w_next=None, decay=False, communications=100):\r\n \"\"\"\r\n Perform FedAVG.\r\n Input:\r\n - X (np.array) := The data of size (N x dim).\r\n - y (np.array) := The labels of the data of size (N x 1).\r\n - comm (MPI.COMM_WORLD) := Variable derived from MPI4PY to handle parallelization. \r\n - step_size (float) := Step size.\r\n - reg (float) := The regularization parameter.\r\n - epochs (int) := The number of passes through the data.\r\n - batch_size (int) := The amount of data to sample at each sub-iteration.\r\n - experiments (int) := Number of experiments to average over.\r\n - w_next (np.array) := If this is passed, we initialize w as w_next. It is of\r\n size (dim x 1).\r\n - decay (boolean) := False if no decay rate. True if use decaying rate.\r\n - communications (int) := Number of communication steps performed.\r\n Output:\r\n - obj_SGD (np.array) := Array of objective values at each communication. Has size (communications x 1)\r\n - MSE (np.array) := Array of the MSE at each communication. (communications x 1)\r\n \"\"\"\r\n my_rank = comm.Get_rank()\r\n p = comm.Get_size()\r\n N, dim = X.shape\r\n num_split = int(N//(p-1))\r\n\r\n if my_rank == 0:\r\n # Initialize arrays to hold the results from each experiment.\r\n obj_SGD = np.zeros((communications, 1))\r\n MSE_SGD = np.zeros((communications, 1))\r\n\r\n for i in range(experiments):\r\n for j in range(communications):\r\n # At every communication step receive all the parameters from the workers and average. \r\n w_aggregate_SGD = np.zeros_like(self.w_star) \r\n for k in range(1, p):\r\n w_aggregate_SGD += comm.recv(source=k)\r\n w_aggregate_SGD /= p-1\r\n for k in range(1, p):\r\n comm.send(w_aggregate_SGD, dest=k)\r\n self.w = w_aggregate_SGD\r\n obj_SGD[j] += self.obj(X, y, reg).item()\r\n MSE_SGD[j] += np.linalg.norm(self.w - self.w_star, 2)\r\n print(f\"SGD, Experiment: {i} Communications: {j} Loss: {obj_SGD[j]/(i+1)}\") \r\n obj_SGD /= experiments\r\n MSE_SGD = 10 * np.log(MSE_SGD/experiments)\r\n return obj_SGD, MSE_SGD \r\n else:\r\n\r\n X_split = X[(my_rank-1)*num_split:(my_rank)*num_split, :]\r\n y_split = y[(my_rank-1)*num_split:(my_rank)*num_split]\r\n for i in range(experiments):\r\n if w_next == None:\r\n w_global_SGD = 0.001 * np.random.randn(dim, 1)\r\n else:\r\n w_global_SGD = w_next\r\n for j in range(communications):\r\n self.SGD(X_split, y_split, step_size=step_size, reg=reg, epochs=epochs, batch_size=batch_size, w_next=w_global_SGD, decay=decay)\r\n comm.send(self.w, dest=0)\r\n w_global_SGD = comm.recv(source=0)\r\n pass\r\n\r\nclass LogReg(Classifier):\r\n def __init__(self, w_star):\r\n super(LogReg, self).__init__(w_star)\r\n\r\n def sigmoid(self, x):\r\n return 1 / (1 + np.exp(-x))\r\n\r\n def obj(self, X, y, reg):\r\n N, _ = X.shape\r\n return 1/N * np.sum(np.log(1 + np.exp(-y * X @ self.w))) + 1/2 * reg * self.w.T @ self.w \r\n \r\n def grad(self, X_batch, y_batch, reg):\r\n N_batch, _ = X_batch.shape\r\n return 1/N_batch * X_batch.T @ (y_batch * (self.sigmoid(y_batch * X_batch @ self.w) - 1)) + reg * self.w \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":"legacy/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":7487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"94857093","text":"import numpy as np\nimport pandas as pd\n\ndef quadrants384_to_96(data):\n quad1 = []\n for row in np.arange(0, 16, 2):\n for col in np.arange(0, 23, 2):\n quad1.append(data.values[row, col])\n\n\n QUAD1_96 = pd.DataFrame(np.array(quad1).reshape([8, 12])) # 96\n QUAD1_96.columns = np.linspace(1, 12, 12, dtype = np.int)\n QUAD1_96['Row'] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n QUAD1_96.set_index(['Row'], inplace = True)\n\n quad2 = []\n for row in np.arange(0, 16, 2):\n for col in np.arange(1, 24, 2):\n quad2.append(data.values[row, col])\n\n\n QUAD2_96 = pd.DataFrame(np.array(quad2).reshape([8, 12])) # 96\n QUAD2_96.columns = np.linspace(1, 12, 12, dtype = np.int)\n QUAD2_96['Row'] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n QUAD2_96.set_index(['Row'], inplace = True)\n\n quad3 = []\n for row in np.arange(1, 17, 2):\n for col in np.arange(0, 23, 2):\n quad3.append(data.values[row, col])\n\n\n QUAD3_96 = pd.DataFrame(np.array(quad3).reshape([8, 12])) # 96\n QUAD3_96.columns = np.linspace(1, 12, 12, dtype = np.int)\n QUAD3_96['Row'] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n QUAD3_96.set_index(['Row'], inplace = True)\n\n quad4 = []\n for row in np.arange(1, 17, 2):\n for col in np.arange(1, 24, 2):\n quad4.append(data.values[row, col])\n\n\n QUAD4_96 = pd.DataFrame(np.array(quad4).reshape([8, 12])) # 96\n QUAD4_96.columns = np.linspace(1, 12, 12, dtype = np.int)\n QUAD4_96['Row'] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n QUAD4_96.set_index(['Row'], inplace = True)\n\n return QUAD1_96, QUAD2_96, QUAD3_96, QUAD4_96\n","sub_path":"quadrants384_to_96.py","file_name":"quadrants384_to_96.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"160439906","text":"from bottle import request, response\nfrom bottle import post, get, route\nfrom connexion.connexion import ConnexionHandler, authenticate\nfrom user.infoManager import infoManager\nimport json\n\n@post('/addPayedLogin')\n@authenticate\ndef add_pay_login(user=None):\n try:\n if user.is_admin():\n try:\n data = json.loads(request.body.read())\n if data is None:\n raise ValueError\n finally:\n return infoManager.set_has_payed(data.get(\"login\"))\n else:\n return json.dumps({\"error\": \"you are not an skiutc admin\"})\n except ValueError:\n response.status = 400\n response.status = '400 Bad Request'\n return json.dumps({\"error\": \"Bad Request\"})\n\n@get('/getRecapUsers')\n@authenticate\ndef get_recap_users(user=None):\n try:\n if user.is_admin():\n return infoManager.get_has_payed()\n else:\n return json.dumps({\"error\": \"you are not an skiutc admin\"})\n except ValueError:\n response.status = 400\n response.status = '400 Bad Request'\n return json.dumps({\"error\": \"Bad Request\"})\n","sub_path":"python/lib/webapis/adminmanager.py","file_name":"adminmanager.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"26187239","text":"#!/bin/python2\r\n\r\n'''\r\nFile: client.py\r\nDate: March 30, 2018\r\nDesigners: Huu Khang Tran, Anderson Phan\r\nDescription: This scripts covers the general client that will spawn a bunch of\r\n other clients to connect to either the multi-threaded, select, or\r\n epoll servers.\r\n'''\r\n\r\nimport threading\r\nimport socket\r\nimport sys\r\nimport time\r\nimport os\r\nimport random\r\nfrom signal import signal, SIGPIPE, SIG_DFL\r\n\r\nglobal output_file\r\nglobal clients\r\nglobal echoedNUM\r\nglobal RTT\r\nglobal totalRTT\r\nglobal avgRTT\r\nglobal totalMessages\r\nglobal totalRequests\r\n# totalRequests - How many requests meaning connections and echoes included towards the server\r\nglobal totalRequests\r\n\r\n# THis function invokes multi-threading to create multiple clients\r\ndef spawn_clients(machineAddr, clients, portForwarderAddr, portForwarderPort, echoedMsg, echoedNUM, totalRequests, output_file):\r\n threadQueue = []\r\n clientID = 1\r\n totalMessages = \"\"\r\n totalRTT = 0\r\n for i in range(clients):\r\n # threading.Thread() starts a new thread and passes in args\r\n thread = threading.Thread(target=start_engine, args=(i, machineAddr, clients, portForwarderAddr, portForwarderPort, echoedMsg, echoedNUM, totalRequests, output_file, totalMessages, totalRTT))\r\n # now we want to load up the array \"threadQueue\"\r\n threadQueue.append(thread)\r\n print (\"Starting Client #\" + str(clientID))\r\n thread.start()\r\n clientID += 1\r\n\r\n # We iterate through all the threads and join() waits for each thread to finish execution\r\n for thread in threadQueue:\r\n thread.join()\r\n\r\n\r\ndef start_engine(clientID, machineAddr, clients, portForwarderAddr, portForwarderPort, echoedMsg, echoedNUM, totalRequests, output_file, totalMessages, totalRTT):\r\n\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s.connect((portForwarderAddr, portForwarderPort))\r\n done = \"\"\r\n\r\n # this iterates through the user-specified number of echoes that will be sent out\r\n for i in range(echoedNUM + 1):\r\n # start the time once msg is sent to server\r\n startTime = time.time()\r\n echoData = str(echoedMsg)\r\n totalLenData = len(echoData)\r\n # this condition is meant for select/epoll server: once the list of messages have been iterated and sent\r\n # this specific client has to send a quit so that the server can move on to another client session\r\n if i == echoedNUM:\r\n print (\"We're done with the server now. Time to terminate this session eh!\")\r\n print (\"Client: \" + str(clientID) + \" --> has iterated through total number of messages to echo out. Server will be notified.\")\r\n done = \"done\"\r\n s.send(done.encode('utf-8'))\r\n else:\r\n s.send(echoData.encode('utf-8'))\r\n print (\"Message was sent: \" + str(totalLenData) + \" Bytes\")\r\n # This value will continuously increment in value after every msg sent --> will output the total bytes sent to client\r\n totalMessages += echoData\r\n\r\n recvMsg = s.recv(2048)\r\n totalLenRecv = len(recvMsg)\r\n # once we receive the echo back from server, we end the timer\r\n endTime = time.time()\r\n # Now we gather the round trip time of the msg being sent from client to server and then from back from server to client.\r\n RTT = endTime - startTime\r\n totalRTT += RTT\r\n avgRTT = RTT / totalRTT\r\n clientSleep = random.randint(0,9)\r\n time.sleep(clientSleep)\r\n i += 1\r\n\r\n # now we want to output the results of this echo stats to the log file\r\n output_file.write(\"\\n Client #\" + str(clientID) + \" sent out a total of \" + str(echoedNUM) + \" messages with a total roundtrip time of \" + str(RTT) + \" seconds.\")\r\n output_file.write(\"\\n\")\r\n result_to_file(clients, totalRTT, avgRTT, totalMessages, totalRequests, output_file)\r\n\r\ndef result_to_file(clients, totalRTT, avgRTT, totalMessages, totalRequests, output_file):\r\n totalLenMsgs = len(totalMessages)\r\n output_file.write(\"\\n\")\r\n output_file.write(\"\\n -------------------RESULTS-------------------\")\r\n output_file.write(\"\\n Total Number of Clients: \" + str(clients))\r\n output_file.write(\"\\n Total Number of Requests: \" + str(totalRequests))\r\n output_file.write(\"\\n Total Data Sent to server: \" + str(totalLenMsgs) + \" Bytes\")\r\n output_file.write(\"\\n Total Roundtrip Time for each echo: \" + str(totalRTT) + \" seconds\")\r\n output_file.write(\"\\n Average Roundtrip Time for each echo: \" + str(avgRTT) + \" seconds\")\r\n output_file.write(\"\\n\")\r\n\r\n\r\ndef main():\r\n\r\n #portForwarderAddr = raw_input(\"Enter the server ip address: \")\r\n\r\n portForwarderAddr = '192.168.0.11'\r\n portForwarderPort = 7007\r\n\r\n #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n #s.connect((serverIP, port))\r\n output_file = open('Client-Output.txt','w')\r\n signal(SIGPIPE, SIG_DFL)\r\n\r\n #machineAddr = raw_input(\"What is your IP Address? (i.e. 192.168.0.X) \")\r\n machineAddr = '192.168.0.11'\r\n #clients = raw_input(\"How many clients would you like to spawn? (Enter an Integer value) \")\r\n clients = '800'\r\n #echoedMsg = raw_input(\"What do you want to echo to the server? (Enter a string) \")\r\n\t# the data we will be sending is 2000 Bytes in size\r\n echoedMsg = \"\"\"Hey there server. It's me, your friendly neighbour Spiderman. Wait is that even right? Spiderman is the\r\n most insane character in the MCU and come on.... Peter Parker is awesome especially his relationship with Mary Jane! I am\r\n so getting out of context here. I am getting too hyped with MCU eversince we all went to go see Black Panther. T'Challa was\r\n such a crazy character and don't even get me started with Erik Killmonger. His character is soo complex. It's like peeling an\r\n oniong meaning it's just layers and layers of mystery. Everything about that movie is amazing! Empahsizes so much on unity and\r\n how you use that empowerment to overcome any other obstacles. The point I wanted to get out was just a simple hello! I must\r\n say that the MCU have really outdone themself with the expansion of the team. Like come on! Who isn't excited for the new\r\n Infinity War against the almighty Thanos, the destroyer and true ruler of the universe. Once he has all the infinity stones\r\n that dude would be unstoppable no matter how big the team is. Disney is just a monster house buying every company there is.\r\n Good job to them and bad job with Star Wars: The Last Jedi LIKE COME ON!!!!!\r\n the destroyer and true ruler of the universe.\"\"\"\r\n #echoedNUM = raw_input(\"How many times do you want this message echoed from each client to the server? (Enter an integer value) \")\r\n echoedNUM = '15'\r\n option = raw_input(\"Would you like to commence the echo program? (type 'begin') \")\r\n\r\n totalRequests = ((int(clients) * int(echoedNUM)) + int(clients))\r\n\r\n if option == \"begin\":\r\n # we want to makes sure we're not passing a null msg to the server\r\n if echoedMsg == \"\":\r\n print (\"The message cannot be null! You must send something\")\r\n echoedMsg = raw_input(\"What do you want to echo to the server? (Enter a string)\")\r\n else:\r\n spawn_clients(machineAddr, int(clients), portForwarderAddr, portForwarderPort, echoedMsg, int(echoedNUM), totalRequests, output_file)\r\n\r\n\r\nif __name__ == \"__main__\": main()\r\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"41257851","text":"from __future__ import print_function\n\nimport numpy as np\nimport cv2\n\nfrom multiprocessing.pool import ThreadPool\nfrom collections import deque\n\nfrom common import clock, draw_str, StatValue\nimport video\nfrom video import create_capture\n\n\nclass DummyTask:\n def __init__(self, data):\n self.data = data\n def ready(self):\n return True\n def get(self):\n return self.data\n\nif __name__ == '__main__':\n import sys, getopt\n\n print(__doc__)\n\n args, fn = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])\n try:\n fn = sys.argv[1]\n except:\n fn = 0\n\n args = dict(args)\n cascade_fn = args.get('--cascade', \"data/haarcascades/haarcascade_frontalface_alt.xml\")\n nested_fn = args.get('--nested-cascade', \"data/haarcascades/haarcascade_eye.xml\")\n\n cascade = cv2.CascadeClassifier(cascade_fn)\n nested = cv2.CascadeClassifier(nested_fn)\n # cap = video.create_capture(fn)\n cap = create_capture(fn, fallback='synth:bg=../data/lena.jpg:noise=0.05')\n\n def detect(img, cascade):\n rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE)\n if len(rects) == 0:\n return []\n rects[:,2:] += rects[:,:2]\n return rects\n\n def draw_rects(img, rects, color):\n for x1, y1, x2, y2 in rects:\n cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)\n\n def process_frame(frame, t0):\n # some intensive computation...\n # frame = cv2.medianBlur(frame, 19)\n # frame = cv2.medianBlur(frame, 19)\n # frame = cv2.bilateralFilter(frame,9,75,75)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.equalizeHist(gray)\n\n t = clock()\n rects = detect(gray, cascade)\n vis = frame.copy()\n draw_rects(vis, rects, (0, 255, 0))\n if not nested.empty():\n for x1, y1, x2, y2 in rects:\n roi = gray[y1:y2, x1:x2]\n vis_roi = vis[y1:y2, x1:x2]\n subrects = detect(roi.copy(), nested)\n draw_rects(vis_roi, subrects, (255, 0, 0))\n dt = clock() - t\n\n draw_str(vis, (20, 80), 'time: %.1f ms' % (dt*1000))\n # cv2.imshow('facedetect', vis)\n return vis_roi, t0\n\n threadn = cv2.getNumberOfCPUs()\n pool = ThreadPool(processes = threadn)\n pending = deque()\n\n threaded_mode = True\n\n latency = StatValue()\n frame_interval = StatValue()\n last_frame_time = clock()\n while True:\n while len(pending) > 0 and pending[0].ready():\n res, t0 = pending.popleft().get()\n latency.update(clock() - t0)\n draw_str(res, (20, 20), \"threaded : \" + str(threaded_mode))\n draw_str(res, (20, 40), \"latency : %.1f ms\" % (latency.value*1000))\n draw_str(res, (20, 60), \"frame interval : %.1f ms\" % (frame_interval.value*1000))\n cv2.imshow('threaded video', res)\n if len(pending) < threadn:\n ret, frame = cap.read()\n t = clock()\n frame_interval.update(t - last_frame_time)\n last_frame_time = t\n if threaded_mode:\n task = pool.apply_async(process_frame, (frame.copy(), t))\n else:\n task = DummyTask(process_frame(frame, t))\n pending.append(task)\n ch = cv2.waitKey(1)\n if ch == ord(' '):\n threaded_mode = not threaded_mode\n if ch == 27:\n break\ncv2.destroyAllWindows()\n","sub_path":"PoolCamAI/haardetect.py","file_name":"haardetect.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"382828331","text":"from django.contrib import messages\nfrom django.shortcuts import render,get_object_or_404,redirect\nfrom .models import Item,Order,OrderItem\nfrom django.views.generic import ListView,DetailView\nfrom django.utils import timezone\n\n#home class bassed views\nclass HomeView(ListView):\n model = Item\n template_name = \"home.html\"\n paginate_by = 1\n\n#home function bassed views\n\"\"\"\ndef home(request):\n context = {\n 'items':Item.objects.all()\n }\n return render(request,'home.html',context)\n\"\"\"\nclass OrderSummaryView(DetailView):\n model = Order\n template_name = 'order_summary.html'\n\n\nclass ItemDetailView(DetailView):\n model = Item \n template_name = \"product.html\"\n \n\n\ndef checkout(request):\n return render(request,'checkout.html',context)\n\ndef add_to_cart(request, slug):\n item = get_object_or_404(Item,slug=slug)\n order_item, created= OrderItem.objects.get_or_create(\n item=item,\n user=request.user,\n ordered=False\n )\n order_qs = Order.objects.filter(user=request.user,ordered=False)\n if order_qs.exists():\n order = order_qs[0]\n #check if the order item is in the order\n if order.items.filter(item__slug=item.slug).exists():\n order_item.quantity += 1\n order_item.save()\n messages.info(request,\"This item quantity was updated.\")\n else:\n order.items.add(order_item) \n messages.info(request,\"This item was added to your cart.\")\n return redirect(\"product\",slug=slug) \n else:\n ordered_date = timezone.now()\n order = Order.objects.create(user=request.user, ordered_date=ordered_date)\n order.items.add(order_item)\n messages.info(request,\"This item was added to your cart.\")\n return redirect(\"product\",slug=slug) \n\ndef remove_from_cart(request, slug):\n item = get_object_or_404(Item,slug=slug)\n order_qs = Order.objects.filter(\n user=request.user,\n ordered=False)\n if order_qs.exists():\n order = order_qs[0]\n #check if the order item is in the order\n if order.items.filter(item__slug=item.slug).exists():\n order_item = OrderItem.objects.filter(\n item=item,\n user=request.user,\n ordered=False\n )[0]\n order.items.remove(order_item)\n messages.info(request,\"This item was removed from your cart.\")\n return redirect('product', slug=slug) \n else: \n #add a message saying the user doesnt have an order\n messages.info(request,\"This item was not in your cart.\")\n return redirect('product', slug=slug) \n \n else:\n #add a message saying the user doesnt have an order\n messages.info(request,\"You do not have an active order.\")\n return redirect('product', slug=slug) \n ","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"422609996","text":"import dataclasses\nimport itertools\nimport json\nimport os\nimport subprocess\nfrom dataclasses import dataclass\nfrom os import path\nfrom typing import Optional\n\nimport torch\nfrom torch.optim import Adam\n\nfrom train import TrainSettings, train_model, TrainState\nfrom util import DATA_WIDTH, GameData, load_data, DEVICE\n\n\n@dataclass\nclass SelfplaySettings:\n game: str\n game_count: int\n\n temperature: float\n zero_temp_move_count: int\n\n keep_tree: bool\n dirichlet_alpha: float\n dirichlet_eps: float\n\n max_game_length: int\n\n full_search_prob: float\n full_iterations: int\n part_iterations: int\n\n exploration_weight: float\n random_symmetries: bool\n\n batch_size: int\n threads_per_device: int\n\n def to_dict(self):\n return dataclasses.asdict(self)\n\n\n@dataclass\nclass LoopSettings:\n root_path: str\n initial_network: str\n\n generations: int\n buffer_gen_count: int\n test_fraction: float\n\n selfplay_settings: SelfplaySettings\n train_settings: TrainSettings\n train_weight_decay: float\n\n def new_buffer(self):\n return Buffer(self.buffer_gen_count, self.test_fraction, self.train_settings.batch_size)\n\n\n@dataclass\nclass Generation:\n settings: LoopSettings\n\n gi: int\n prev_gen_folder: str\n gen_folder: str\n games_path: str\n prev_network_path: str\n next_network_path: str\n\n @classmethod\n def from_gi(cls, gi: int, settings: LoopSettings):\n gen_folder = path.join(settings.root_path, f\"gen_{gi}\")\n prev_gen_folder = path.join(settings.root_path, f\"gen_{gi - 1}\") \\\n if gi != 0 else None\n\n return Generation(\n settings=settings,\n gi=gi,\n prev_gen_folder=prev_gen_folder,\n gen_folder=gen_folder,\n games_path=path.join(gen_folder, \"games_from_prev.bin\"),\n prev_network_path=path.join(prev_gen_folder, f\"model_{settings.train_settings.epochs}_epochs.pt\")\n if gi != 0 else settings.initial_network,\n next_network_path=path.join(gen_folder, f\"model_{settings.train_settings.epochs}_epochs.pt\"),\n )\n\n\n# TODO buffer may not fit in memory, load files in sequence instead\n# extra advantage: the last gen will always be trained on last\nclass Buffer:\n def __init__(self, max_gen_count: int, test_fraction: float, min_test_size: int):\n self.max_gen_count = max_gen_count\n self.test_fraction = test_fraction\n self.min_test_size = min_test_size\n\n self.buffer = torch.zeros(0, DATA_WIDTH)\n self.gen_lengths = []\n\n self.train_data: Optional[GameData] = None\n self.test_data: Optional[GameData] = None\n\n def push_load_path(self, games_path: str):\n train_data, test_data = load_data(games_path, self.test_fraction, limit=None)\n\n if len(self.gen_lengths) == self.max_gen_count:\n start = self.gen_lengths[0]\n del self.gen_lengths[0]\n else:\n start = 0\n\n self.gen_lengths.append(len(train_data))\n self.buffer = torch.cat([self.buffer[start:], train_data.full], dim=0)\n\n self.train_data = GameData(self.buffer).to(DEVICE)\n self.test_data = test_data.to(DEVICE)\n\n def __len__(self):\n return len(self.buffer)\n\n\ndef generate_selfplay_games(gen: Generation):\n \"\"\"Run the selfplay program, which will generate games and save them to gen.games.path\"\"\"\n\n arg_dict = gen.settings.selfplay_settings.to_dict()\n arg_dict[\"output_path\"] = gen.games_path\n arg_dict[\"network_path\"] = gen.prev_network_path\n\n # TODO go back to release\n command = \"cargo run --manifest-path rust/Cargo.toml --bin selfplay_cmd\".split(\" \") + [\n json.dumps(arg_dict)]\n print(f\"Running command {command}\")\n\n env = os.environ.copy()\n env[\"RUSTFLAGS\"]=\"-C target-cpu=native\"\n p = subprocess.Popen(command, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, universal_newlines=True)\n for line in p.stdout:\n print(line, end=\"\")\n p.wait()\n if p.returncode != 0:\n print(f\"Process exited with error code {p.returncode}\")\n print(p.stderr)\n raise subprocess.CalledProcessError(p.returncode, command)\n\n\ndef train_new_network(buffer: Buffer, gen: Generation):\n model = torch.jit.load(gen.prev_network_path, map_location=DEVICE)\n state = TrainState(\n settings=gen.settings.train_settings,\n output_path=gen.gen_folder,\n train_data=buffer.train_data,\n test_data=buffer.test_data,\n optimizer=Adam(model.parameters(), weight_decay=gen.settings.train_weight_decay),\n scheduler=None\n )\n\n train_model(model, state)\n\n\ndef find_last_finished_gen(settings: LoopSettings) -> Optional[int]:\n for gi in itertools.count():\n gen = Generation.from_gi(gi, settings)\n\n if not os.path.exists(gen.next_network_path):\n if gi >= 1:\n return gi - 1\n return None\n\n\ndef load_resume_buffer(settings: LoopSettings, last_finished_gi: int) -> Buffer:\n buffer = settings.new_buffer()\n for gi in range(last_finished_gi + 1):\n gen = Generation.from_gi(gi, settings)\n buffer.push_load_path(gen.games_path)\n return buffer\n\n\ndef run_loop(settings: LoopSettings):\n print(f\"Starting loop in directory {os.getcwd()}\")\n assert os.path.exists(\"./rust\") and os.path.exists(\"./python\"), \"should be run in root STTTZero folder\"\n\n # check if we're resuming a run and restore the buffer if so\n last_finished_gi = find_last_finished_gen(settings)\n if last_finished_gi is not None:\n start_gi = last_finished_gi + 1\n print(f\"Resuming {settings.root_path}, restarting with gen {start_gi}\")\n buffer = load_resume_buffer(settings, last_finished_gi)\n else:\n print(\"Starting new run from gen 0\")\n start_gi = 0\n buffer = settings.new_buffer()\n\n for gi in range(start_gi, settings.generations):\n print(f\"Starting generation {gi}\")\n\n gen = Generation.from_gi(gi, settings)\n os.makedirs(gen.gen_folder, exist_ok=True)\n\n generate_selfplay_games(gen)\n buffer.push_load_path(gen.games_path)\n\n print(f\"Buffer size: {len(buffer)}\")\n\n train_new_network(buffer, gen)\n","sub_path":"python/loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":6234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"61471006","text":"from threading import Thread\nfrom socket import *\nfrom signal import *\n\n# 网络地址\nHOST = '0.0.0.0'\nPORT = 8888\nADDR = (HOST, PORT)\n\n\ndef handle(connfd):\n while True:\n data = connfd.recv(1024)\n if not data:\n break\n print(data.decode())\n connfd.send(b\"ok\")\n connfd.close()\n\n\nsignal(SIGCHLD, SIG_IGN)\n\n\n# 搭建并发网络\ndef main():\n # 创建tcp套接字\n sock = socket()\n sock.bind(ADDR)\n sock.listen(5)\n print('listen the port %d' % PORT)\n signal(SIGCHLD, SIG_IGN)\n # 循环等待客户端连接\n while True:\n try:\n connfd, addr = sock.accept()\n print(\"Connect from\", addr)\n except KeyboardInterrupt:\n sys.exit(\"服务结束\")\n p = Thread(target=handle, args=(connfd,))\n p.start()\n","sub_path":"mydir/thread_server.py","file_name":"thread_server.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"134457489","text":"from typing import Any, Dict, List, Callable\nfrom data_stack.dataset.iterator import DatasetIteratorIF, CombinedDatasetIterator\nfrom ml_gym.data_handling.postprocessors.postprocessor import LabelMapperPostProcessor, FeatureEncoderPostProcessor, OneHotEncodedTargetPostProcessor\nfrom ml_gym.data_handling.iterators import PostProcessedDatasetIterator\nfrom data_stack.dataset.meta import MetaFactory\nfrom data_stack.dataset.factory import InformedDatasetFactory\nfrom data_stack.dataset.iterator import InformedDatasetIteratorIF\nfrom data_stack.dataset.splitter import SplitterFactory\n\n\nclass ModelGymInformedIteratorFactory(InformedDatasetFactory):\n\n @staticmethod\n def get_mapped_labels_iterator(identifier: str, iterator: DatasetIteratorIF, mappings: Dict) -> InformedDatasetIteratorIF:\n label_mapper_post_processor = LabelMapperPostProcessor(mappings=mappings,\n target_position=iterator.dataset_meta.target_pos,\n tag_position=iterator.dataset_meta.tag_pos)\n meta = MetaFactory.get_dataset_meta_from_existing(iterator.dataset_meta, identifier=identifier)\n return InformedDatasetFactory.get_dataset_iterator(PostProcessedDatasetIterator(iterator, label_mapper_post_processor), meta)\n\n @staticmethod\n def get_filtered_labels_iterator(identifier: str, iterator: InformedDatasetIteratorIF,\n filtered_labels: List[Any]) -> InformedDatasetIteratorIF:\n valid_indices = [i for i in range(len(iterator)) if iterator[i][iterator.dataset_meta.target_pos] in filtered_labels]\n meta = MetaFactory.get_dataset_meta_from_existing(iterator.dataset_meta, identifier=identifier)\n return InformedDatasetFactory.get_dataset_iterator_view(iterator, meta, valid_indices)\n\n @staticmethod\n def get_iterator_view(identifier: str, iterator: InformedDatasetIteratorIF, selection_fun: Callable[[DatasetIteratorIF], List[int]],\n view_tags: Dict[str, Any]) -> InformedDatasetIteratorIF:\n valid_indices = selection_fun(iterator)\n # valid_indices = list(np.argwhere(valid_mask).flatten())\n meta = MetaFactory.get_dataset_meta_from_existing(iterator.dataset_meta, identifier=identifier)\n return InformedDatasetFactory.get_dataset_iterator_view(iterator, meta, valid_indices, view_tags)\n\n @staticmethod\n def get_feature_encoded_iterators(identifier: str, iterators: Dict[str, InformedDatasetIteratorIF],\n feature_encoding_configs: Dict[str, List[Any]]) -> Dict[str, DatasetIteratorIF]:\n sample_position = list(iterators.items())[0][1].dataset_meta.sample_pos\n feature_encoder_post_processor = FeatureEncoderPostProcessor(\n sample_position=sample_position, feature_encoding_configs=feature_encoding_configs)\n feature_encoder_post_processor.fit(iterators)\n return {name: InformedDatasetFactory.get_dataset_iterator(PostProcessedDatasetIterator(iterator, feature_encoder_post_processor),\n MetaFactory.get_dataset_meta_from_existing(iterator.dataset_meta,\n identifier=identifier))\n for name, iterator in iterators.items()}\n\n @staticmethod\n def get_one_hot_encoded_target_iterators(identifier: str, iterators: Dict[str, InformedDatasetIteratorIF],\n target_vector_size: int) -> Dict[str, DatasetIteratorIF]:\n target_position = list(iterators.items())[0][1].dataset_meta.target_pos\n postprocessor = OneHotEncodedTargetPostProcessor(target_vector_size=target_vector_size, target_position=target_position)\n return {name: InformedDatasetFactory.get_dataset_iterator(PostProcessedDatasetIterator(iterator, postprocessor), MetaFactory.get_dataset_meta_from_existing(iterator.dataset_meta, identifier=identifier))\n for name, iterator in iterators.items()}\n\n @staticmethod\n def get_combined_iterators(identifier: str, iterators: Dict[str, Dict[str, InformedDatasetIteratorIF]], combine_configs: Dict) -> Dict[str, InformedDatasetIteratorIF]:\n \"\"\"Combines iterators.\n\n Args:\n identifier (str):\n iterators (Dict[str, Dict[str, InformedDatasetIteratorIF]]): Dictionary mapping from iterator_name -> split_name -> iterator\n combine_configs (Dict):\n\n Returns:\n Dict[str, InformedDatasetIteratorIF]:\n \"\"\"\n\n def get_iterators_to_be_combined(iterators: Dict[str, Dict[str, InformedDatasetIteratorIF]], split_config: List):\n return [iterators[element[\"iterators_name\"]][split_name] for element in split_config for split_name in element[\"splits\"]]\n\n combined_iterators = {}\n for split_config in combine_configs:\n iterator_list = get_iterators_to_be_combined(iterators, split_config[\"old_splits\"])\n meta = MetaFactory.get_dataset_meta_from_existing(dataset_meta=iterator_list[0].dataset_meta, identifier=identifier,\n dataset_name=\"combined_dataset\", dataset_tag=None)\n combined_iterators[split_config[\"new_split\"]] = InformedDatasetFactory.get_dataset_iterator(\n CombinedDatasetIterator(iterator_list), meta)\n return combined_iterators\n\n @staticmethod\n def get_splitted_iterators(identifier: str, iterators: Dict[str, InformedDatasetIteratorIF], seed: int,\n stratified: bool, split_config: Dict) -> Dict[str, InformedDatasetIteratorIF]:\n def _split(iterator: InformedDatasetIteratorIF, seed: int, split_config: Dict) -> Dict[str, InformedDatasetIteratorIF]:\n names = list(split_config.keys())\n ratios = list(split_config.values())\n if stratified:\n splitter = SplitterFactory.get_stratified_splitter(ratios=ratios, seed=seed)\n else:\n splitter = SplitterFactory.get_random_splitter(ratios=ratios, seed=seed)\n splitted_iterators = splitter.split(iterator)\n dataset_metas = [MetaFactory.get_dataset_meta_from_existing(\n iterator.dataset_meta, identifier=identifier, dataset_tag=name) for name in names]\n return {name: InformedDatasetFactory.get_dataset_iterator(splitted_iterators[i], dataset_metas[i]) for i, name in enumerate(names)}\n\n split_list = []\n for name, iterator in iterators.items():\n if name in split_config.keys():\n split_list.append(_split(iterator, seed, split_config[name]))\n else:\n split_list.append({name: iterator})\n\n splitted_iterator_dict = {}\n for d in split_list:\n splitted_iterator_dict = {**splitted_iterator_dict, **d}\n return splitted_iterator_dict\n\n @staticmethod\n def get_in_memory_iterator(identifier: str, iterator: InformedDatasetIteratorIF) -> InformedDatasetIteratorIF:\n meta = MetaFactory.get_dataset_meta_from_existing(iterator.dataset_meta, identifier=identifier)\n return InformedDatasetFactory.get_in_memory_dataset_iterator(iterator, meta)\n\n @staticmethod\n def get_shuffled_iterator(identifier: str, iterator: InformedDatasetIteratorIF, seed: int) -> InformedDatasetIteratorIF:\n meta = MetaFactory.get_dataset_meta_from_existing(iterator.dataset_meta, identifier=identifier)\n return InformedDatasetFactory.get_shuffled_dataset_iterator(iterator, meta, seed)","sub_path":"src/ml_gym/data_handling/postprocessors/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":7692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"524222899","text":"import json\n\nfrom server.models import database, PatientModel, LoginModel\nfrom server.hmsexceptions import UserNotExistException\nfrom server.utils import logger\n\n\ndef register_patient(post_data):\n \"\"\"\n Register a patient in the system. The post data is in json format.\n :param post_data: dict\n :returns: a status, a str( patient's info on success, err info on failure)\n \"\"\"\n # print(post_data)\n patient = ''\n try:\n logger.debug('in register_patient')\n\n with database.atomic():\n patient = PatientModel.create_by_dict(post_data)\n logger.debug(patient)\n logger.debug('in database.atomic')\n # except peewee.IntegrityError:\n # logger.warning('in patient model create except')\n\n # # `username` is a unique column, so this username already exists,\n # # making it safe to call .get().\n # old_user = AccountModel.get(AccountModel.username == username)\n # logger.warning('user exists...')\n # resp_dict['info'] = 'user exists, did not create user:%s' % username\n # resp.status = falcon.HTTP_409\n # try:\n # change_user = AccountModel.get(AccountModel.username==username,\n # AccountModel.password==password)\n # except:\n # logger.debug('change user data failed...')\n except Exception as ex:\n logger.error('Exception: ', ex)\n q = PatientModel.delete().where(PatientModel.email==patient)\n q.execute()\n try:\n with database.atomic():\n user = LoginModel.create_by_dict('patient', post_data)\n logger.debug(patient)\n logger.debug('in database.atomic')\n # except peewee.IntegrityError:\n # logger.warning('in doctor model create except')\n\n # # `username` is a unique column, so this username already exists,\n # # making it safe to call .get().\n # old_user = AccountModel.get(AccountModel.username == username)\n # logger.warning('user exists...')\n # resp_dict['info'] = 'user exists, did not create user:%s' % username\n # resp.status = falcon.HTTP_409\n # try:\n # change_user = AccountModel.get(AccountModel.username==username,\n # AccountModel.password==password)\n # except:\n # logger.debug('change user data failed...')\n except Exception as ex:\n logger.error('Exception: ', ex)\n q = LoginModel.delete().where(LoginModel.username==patient)\n q.execute()\n return 0, 'create patient failed, did not create patient', ''\n else:\n return 1, str(patient), str(user.password)\n\n\ndef edit_patient(patientid, post_data):\n \"\"\"\n Edit a patient in the system. The post data is a dict.\n\n :param post_data: dict\n :returns: a status, a str( patient's info on success, err info on failure)\n \"\"\"\n # print(post_data)\n try:\n logger.debug('in edit_patient')\n PatientModel.update_by_dict(patientid, post_data)\n logger.debug('executed')\n # except peewee.IntegrityError:\n # logger.warning('in doctor model create except')\n\n # # `username` is a unique column, so this username already exists,\n # # making it safe to call .get().\n # old_user = AccountModel.get(AccountModel.username == username)\n # logger.warning('user exists...')\n # resp_dict['info'] = 'user exists, did not create user:%s' % username\n # resp.status = falcon.HTTP_409\n # try:\n # change_user = AccountModel.get(AccountModel.username==username,\n # AccountModel.password==password)\n # except:\n # logger.debug('change user data failed...')\n except Exception as ex:\n logger.error('Exception: ', ex)\n return 0, 'edit_patient failed, did not edit_patient'\n else:\n return 1, str(patientid)\n\n\ndef get_patient(patientid):\n \"\"\"\n Get info of a patient in the system.\n :param patientid: patient's uid\n :returns: a status, a str ( patient's info on success, err info on failure)\n \"\"\"\n # print(patientid)\n info = {}\n try:\n logger.debug('in get_patient')\n patient_dict = PatientModel.get_dict(patientid)\n logger.debug(patient_dict)\n except UserNotExistException:\n logger.debug('in UserNotExistException')\n return 0, 'get patient failed, the required patient Did Not Exist'\n except Exception as ex:\n logger.error('Exception: ', ex)\n return 0, 'get patient failed'\n else:\n patient_json = json.dumps(patient_dict)\n logger.debug(patient_json)\n return 1, patient_json\n","sub_path":"server/patient.py","file_name":"patient.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"511915446","text":"import tkinter as tk \n\nclass Calculator(tk.Frame):\n def __init__(self, master=None):\n tk.Frame.__init__(self, master)\n self.pack()\n\n self.entry = tk.StringVar()\n self.entry.set(\"0\")\n\n self.reset = True\n\n self.createWidgets()\n \n def createWidgets(self):\n tk.Label(self, textvariable=self.entry).pack(side=tk.TOP, padx=10, pady=10)\n\n frame = tk.Frame(self)\n tk.Button(frame, text=\"7\", command=lambda: self.enter(7)).grid(row=0, column=0)\n tk.Button(frame, text=\"8\", command=lambda: self.enter(8)).grid(row=0, column=1)\n tk.Button(frame, text=\"9\", command=lambda: self.enter(9)).grid(row=0, column=2)\n tk.Button(frame, text=\"4\", command=lambda: self.enter(4)).grid(row=1, column=0)\n tk.Button(frame, text=\"5\", command=lambda: self.enter(5)).grid(row=1, column=1)\n tk.Button(frame, text=\"6\", command=lambda: self.enter(6)).grid(row=1, column=2)\n tk.Button(frame, text=\"1\", command=lambda: self.enter(1)).grid(row=2, column=0)\n tk.Button(frame, text=\"2\", command=lambda: self.enter(2)).grid(row=2, column=1)\n tk.Button(frame, text=\"3\", command=lambda: self.enter(3)).grid(row=2, column=2)\n tk.Button(frame, text=\"0\", command=lambda: self.enter(0)).grid(row=3, column=0)\n tk.Button(frame, text=\".\", command=lambda: self.enter(\".\")).grid(row=3, column=1)\n tk.Button(frame, text=\"=\", command=self.calculate).grid(row=3, column=2)\n frame.pack(side=tk.LEFT)\n\n frame = tk.Frame(self)\n tk.Button(frame, text='+', command=lambda: self.enter(\"+\")).pack()\n tk.Button(frame, text='-', command=lambda: self.enter(\"-\")).pack()\n tk.Button(frame, text='*', command=lambda: self.enter(\"*\")).pack()\n tk.Button(frame, text='/', command=lambda: self.enter(\"/\")).pack()\n frame.pack(side=tk.RIGHT)\n\n def enter(self, value):\n if self.reset:\n self.entry.set( str(value) )\n self.reset = False\n else:\n entry = self.entry.get()\n entry += str(value)\n self.entry.set(entry)\n\n self.update_idletasks()\n\n def calculate(self):\n entry = self.entry.get() # calculator entry string\n cursor = 0 # keeps current location in string\n reader = '' # reads in characters\n\n operator = ''\n operand = 0\n result = 0\n\n try:\n # read in the first number\n while cursor < len(entry) and entry[cursor] not in '+-*/':\n reader += entry[cursor]\n cursor += 1\n result = int(reader)\n\n while cursor < len(entry):\n # read in operator \n operator = entry[cursor]\n cursor += 1\n\n # read in operand\n reader = '' \n while cursor < len(entry) and entry[cursor] not in '+-*/':\n reader += entry[cursor]\n cursor += 1\n operand = int(reader)\n\n # calculte new result\n if operator == '+':\n result += int(operand)\n elif operator == '-':\n result -= int(operand)\n elif operator == '*':\n result *= int(operand)\n else:\n result /= int(operand)\n \n except:\n result = \"Syntax Error\"\n\n self.reset = True\n self.entry.set(result)\n self.update_idletasks()","sub_path":"calculator/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"45214649","text":"import logging\r\nimport time\r\n\r\nimport serial\r\nfrom telegram.ext import Updater, CommandHandler, CallbackQueryHandler\r\n\r\n\r\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\r\n level=logging.INFO)\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\ndef start(update, context):\r\n update.message.reply_text('Benvenuto in T_IoT_botGruppo9')\r\n update.message.reply_text('Comando \"/temp\" per richiedere la temperatura registrata\\nComando \"/plus\" per aumentare la velocità della ventola\\n'\r\n 'Comando \"/minus\" per ridurre la velocità della ventola')\r\n\r\n\r\ndef temp(update, context):\r\n ser = serial.Serial('COM5', 9600)\r\n time.sleep(2)\r\n\r\n data = []\r\n for i in range(50):\r\n b = ser.readline() \r\n string_n = b.decode() \r\n string = string_n.rstrip() \r\n flt = float(string) \r\n print(flt)\r\n data.append(flt) \r\n time.sleep(0.1) \r\n\r\n ser.close()\r\n\r\n for line in data:\r\n temp = line\r\n temp = str(temp)\r\n\r\n update.message.reply_text(\"L'ultima temperatura registrata è \" + temp + \"°C\")\r\n \r\n\r\ndef plus(update,context):\r\n ser = serial.Serial('COM5', 9600)\r\n val = \"+\"\r\n ser.write(\"+\".encode())\r\n\r\ndef minus(update,context):\r\n ser = serial.Serial('COM5', 9600)\r\n val = \"-\"\r\n ser.write(\"-\".encode())\r\n\r\n\r\ndef help_command(update, context):\r\n update.message.reply_text(\"Use /start to test this bot.\")\r\n\r\n\r\ndef main():\r\n updater = Updater(\"1178065054:AAF_zEYdJKJX28V0_7FGROgfR6AXHWDUf20\", use_context=True)\r\n\r\n updater.dispatcher.add_handler(CommandHandler('start', start))\r\n updater.dispatcher.add_handler(CommandHandler('temp', temp))\r\n updater.dispatcher.add_handler(CommandHandler('plus', plus))\r\n updater.dispatcher.add_handler(CommandHandler('minus', minus))\r\n updater.dispatcher.add_handler(CommandHandler('help', help_command))\r\n\r\n # Start the Bot\r\n updater.start_polling()\r\n\r\n updater.idle()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"LabSW4/LabSW4.py","file_name":"LabSW4.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"181663358","text":"import os\nimport shutil\nimport re\ndef delete():\n dir = \"/home/cyg/cygSpider/.scrapy/httpcache/roleinfo\"\n for root, dirs, files in os.walk(dir):\n #print(root)\n for file in files:\n if file == \"meta\":\n f = open(root+\"/\"+file)\n text = f.read()\n if 'page_num=' in text:\n page_num = int(re.findall(r'page_num=(\\d+)',text)[0])\n if page_num<=20:\n root_delete = root\n f.close()\n shutil.rmtree(root_delete)\n\n\nif __name__ == \"__main__\":\n delete()\n","sub_path":"cygSpider/delete_catch2.py","file_name":"delete_catch2.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"141242274","text":"#!/usr/bin/python3\nfrom sys import *\nimport re\n\n\n#OK\ndef extract_dict (filename) :\n result= []\n fic = open(filename, \"r\");\n listeAttributs = []\n for numLine,line in enumerate(fic):\n if numLine == 0:\n listeAttributs=line.rstrip(\"\\n\").split(\";\");\n else:\n dic = {}\n for numAtt,att in enumerate(listeAttributs):\n dic[att] = line.rstrip(\"\\n\").split(\";\")[numAtt]\n result.append(dic)\n return result\n\n#TEST\n#print\n(extract_dict(\"./Paris/commercesparis.csv\"))\n \nclass csvdata:\n \n def __init__(self, nomFichier, attLieu, attAdresse, attCoord):\n self.nomFichier = nomFichier\n self.attLieu = attLieu\n self.attAdresse = attAdresse\n self.attCoord = attCoord \n self.listDic = extract_dict(nomFichier)\n\n def __getitem__(self, key):\n return self.listDic[key]\n\n def __len__(self):\n return len(self.listDic)\n\n def liste_lieux(self, critere=\":\"):\n result = [()]\n crit = critere.split(\":\")\n nomColonne = crit[0]\n valColonne = crit [1]\n print (nomColonne) \n for dic in self.listDic :\n if nomColonne == \"\" or valColonne == \"\" :\n print (\"coucou\")\n t = (dic[self.attCoord].split(\", \")[0],dic[self.attCoord].split(\", \")[1],dic[self.attLieu],dic[self.attAdresse])\n result.append(t)\n else :\n if dic[nomColonne] == valColonne :\n t = (dic[self.attCoord].split(\", \")[0],dic[self.attCoord].split(\", \")[1],dic[self.attLieu],dic[self.attAdresse])\n result.append(t)\n \n return result\n\n\n \n \n","sub_path":"csvdata.py","file_name":"csvdata.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"494388548","text":"import requests\nfrom requests.cookies import RequestsCookieJar\n\n\ndef get_cookies() -> RequestsCookieJar:\n headers = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n \"Origin\": \"https://xueqiu.com\",\n \"Accept-Encoding\": \"br, gzip, deflate\",\n \"Host\": \"xueqiu.com\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15\",\n \"Accept-Language\": \"en-us\",\n \"Referer\": \"https://xueqiu.com/\",\n \"Connection\": \"keep-alive\"\n }\n\n return requests.get(url=\"https://xueqiu.com\", headers=headers, timeout=30).cookies\n","sub_path":"data_crawler/xueqiu/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"281235828","text":"import torch\n\n\"\"\"\nNot neccessary\nIn convenience of tracking tensor's scale for adjust bits, especially for fx_quantize.\n\"\"\"\nclass QTensor(torch.Tensor):\n @classmethod\n def __torch_function__(cls, func, types, args=(), kwargs=None):\n if kwargs is None:\n kwargs = {}\n scale = args[0].scale if hasattr(args[0], 'scale') else None\n zero_point = args[0].zero_point if hasattr(args[0], 'zero_point') else None\n out = super().__torch_function__(func, types, args, kwargs)\n if isinstance(out, torch.Tensor):\n out.scale = scale\n out.zero_point = zero_point\n return out\n \n def __repr__(self):\n s = super().__repr__()\n scale = self.scale if hasattr(self, 'scale') else None\n zero_point = self.zero_point if hasattr(self, 'zero_point') else None\n s += f' scale={scale}, zero_point={zero_point}'\n return s\n\n\nif __name__ == '__main__':\n x = QTensor([1,2,3,4])\n x.scale = 1.0\n y = QTensor([1,2,3,4])\n print(y)\n z = x * y\n print(z)\n print(x)","sub_path":"qqquantize/qtensor.py","file_name":"qtensor.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"631779405","text":"from functools import partial\nfrom multiprocessing import Pool\nimport socket\n\nmulticount = 10\nfastPort = [21,22,23,80,8080,443,3389,1443,3306]\nallPort = range(1, 65536)\n\ndef ping(host, port):\n try:\n socket.socket().connect((host, port))\n print(str(port) + \" Open\")\n return port\n except:\n pass\n\ndef scan_ports(host, scanMode):\n if scanMode == \"fast\":\n portype=fastPort\n elif scanMode == \"all\":\n portype=fastPort\n else:\n exit()\n\n p = Pool(multicount)\n ping_host = partial(ping, host)\n return filter(bool, p.map(ping_host, fastPort))\n\ndef main():\n hostAddress = raw_input(\"Scan Target IP: \")\n scanMode = raw_input(\"Scan Mode Select (all or fast): \")\n hostIP = socket.gethostbyname(hostAddress)\n\n if hostIP is None:\n exit()\n\n print(\"\\nScanning start \" + hostIP + \" ...\")\n ports = list(scan_ports(hostIP, scanMode))\n print(\"\\nDone.\")\n\n print(str(len(ports)) + \" ports openned\")\n print(ports)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"portscan.py","file_name":"portscan.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"27035248","text":"#!/usr/bin/env python\n\n# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"Setup tool for artman.\"\"\"\n\nimport setuptools\n\nfrom pip.req import parse_requirements\n\nrequirements = [\n 'gcloud>=0.10.0',\n 'kazoo>=2.2.1',\n 'oslo.utils>=3.4.0',\n 'pyyaml>=3.11',\n 'taskflow>=1.25.0',\n 'yapf>=0.6.2'\n]\n\nsetuptools.setup(\n name='googleapis-artman',\n version='0.1.0',\n description='Google API artifact manager',\n author='Google Inc',\n author_email='googleapis-packages@google.com',\n url='https://github.com/googleapis/artman',\n license='Apache-2.0',\n install_requires=requirements,\n packages=setuptools.find_packages(),\n scripts=['execute_pipeline.py', 'start_conductor.py'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"455248574","text":"#!/usr/bin/env python\n\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Distutils import build_ext\n\nimport numpy\n\next_module = Extension(\n \"f_apply\",\n [\"f_apply.pyx\", \"mp_func.c\"],\n include_dirs=[numpy.get_include()], \n extra_compile_args=['-fopenmp'],\n extra_link_args=['-fopenmp'],\n)\n\nsetup(\n name = 'f_apply',\n cmdclass = {'build_ext': build_ext},\n ext_modules = [ext_module],\n)\n","sub_path":"develop/_Cython_func/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"385904441","text":"\nfrom nanohttp import Controller, html, settings, context\n\n\nclass Root(Controller):\n\n @html\n def index(self): # pragma: no cover\n yield 'nanohttp demo'\n yield '

nanohttp demo page

'\n yield '

debug flag is: %s

' % settings.debug\n yield ''\n yield '
    '\n yield from ('
  • %s: %s
  • ' % i for i in context.environ.items())\n yield '
'\n yield ''\n","sub_path":"nanohttp/tests/stuff/package_for_test_bootstrapping/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"617474031","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def GetFirstOfK(self, data, k,start,end):\n if start>end:\n return -1\n mid = (end+start)//2\n if data[mid]==k:\n if (mid>0 and data[mid-1] !=k) or mid == 0:\n return mid\n else:\n end = mid-1\n elif data[mid]end:\n return -1\n mid = (end+start)//2\n if data[mid]==k:\n if ( mid-1 and last>-1:\n count = last - first +1\n return count\n\n\nif __name__ == '__main__':\n l = [1,2,3,3,3,3]\n k = 3\n # print(len(l))\n solution1 = Solution()\n a = solution1.GetNumberOfK(l,k)\n print(a)","sub_path":"py-project/Solution53-1 2.py","file_name":"Solution53-1 2.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"360768535","text":"def solution(cacheSize, cities):\n runTime = 0\n cache = []\n \n for city in cities:\n runTime += LRU(cacheSize, cache, city)\n \n return runTime\n\ndef LRU(cacheSize, cache, city): \n # cache hit\n if city in cache:\n cache.pop(cache.index(city))\n cache.append(city)\n \n return 1\n \n # cache miss\n else:\n if len(cache) < cacheSize:\n cache.append(city)\n else:\n if cacheSize != 0:\n cache.pop(0)\n cache.append(city)\n \n return 5\n\nsolution(3, [\"Jeju\", \"Pangyo\", \"Seoul\", \"NewYork\", \"LA\", \"Jeju\", \"Pangyo\", \"Seoul\", \"NewYork\", \"LA\"])","sub_path":"prev/programmers/20주차/캐시_sj.py","file_name":"캐시_sj.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"378469035","text":"# Question:\n# Given two strings representing two complex numbers.\n\n# You need to return a string representing their multiplication. Note i2 = -1 according to the definition.\n\n# Example 1:\n# Input: \"1+1i\", \"1+1i\"\n# Output: \"0+2i\"\n# Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\n# Example 2:\n# Input: \"1+-1i\", \"1+-1i\"\n# Output: \"0+-2i\"\n# Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n# Note:\n\n# The input strings will not have extra blank.\n# The input strings will be given in the form of a+bi, where the integer a and b will both belong to \n# the range of [-100, 100]. And the output should be also in this form.\n\nclass Solution(object):\n def complexNumberMultiply(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n index1 = [a.index('+'), b.index('+')]\n realp = int(a[:index1[0]]) * int(b[:index1[1]]) - int(a[index1[0] + 1: -1]) * int(b[index1[1] + 1: -1])\n imagp = int(a[:index1[0]]) * int(b[index1[1] + 1: -1]) + int(b[:index1[1]]) * int(a[index1[0] + 1: -1])\n return str(realp) + '+' + str(imagp) + 'i'\n# runtime 45 ms, above 25.43%\n\nclass Solution(object):\n\tdef complexNumberMultiply(self, a, b):\n\t\t\"\"\"\n\t\t:type a: str\n\t\t:type b: str\n\t\t:rtype: str\n\t\t\"\"\"\n\t\t[m, n] = a[:-1].split('+')\n\t\t[p, q] = b[:-1].split('+')\n\t\tm = int(m)\n\t\tn = int(n)\n\t\tp = int(p)\n\t\tq = int(q)\n\t\trealp = m * n - p * q\n\t\timagp = m * q + n * p\n\t\treturn str(realp) + '+' + str(imagp) + 'i'\n# runtime 42ms, above 31.53%\n","sub_path":"Leetcode/537. Complex Number Multiplication.py","file_name":"537. Complex Number Multiplication.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"386994115","text":"from mpl_toolkits.basemap import Basemap, cm, shiftgrid,interp,maskoceans\nfrom netCDF4 import Dataset as NetCDFFile\nimport numpy as N\nimport matplotlib.pyplot as plt\nimport glob\nimport numpy.ma as ma\nfrom scipy.interpolate import griddata\nimport matplotlib.colors as colors\n\n\niizumi=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/iizumi/iizumi.2013JAN29.maize.1982-2006.30min.nc4','r')\n#print iizumi\niyield = iizumi.variables['yield50'][18,:,:]\niarea =iizumi.variables['area'][18,:,:]\nla=iizumi.variables['lat'][:]\nlo=iizumi.variables['lon'][:]\niyield=N.flipud(iyield)\niarea=N.flipud(iarea)\n\nregion1=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/HistoricalGLM_crop_150901.nc','r')\nmaitrop = region1.variables['maize_trop'][99,:,:]\nmaitemp = region1.variables['maize_temp'][99,:,:]\nmaitropi=region1.variables['maize_trop_irrig'][99,:,:]\nmaitempi=region1.variables['maize_temp_irrig'][99,:,:]\ngridarea = region1.variables['area'][:,:]\nmaitrop=ma.masked_where(maitrop<=0,maitrop)\nmaitrop=ma.filled(maitrop, fill_value=0.)\nmaitemp=ma.masked_where(maitemp<=0,maitemp)\nmaitemp=ma.filled(maitemp, fill_value=0.)\n\nmaitropi=ma.masked_where(maitropi<=0,maitropi)\nmaitropi=ma.filled(maitropi, fill_value=0.)\nmaitempi=ma.masked_where(maitempi<=0,maitempi)\nmaitempi=ma.filled(maitempi, fill_value=0.)\n\nmaizetor=maitrop+maitemp\nmaizetoi=maitropi+maitempi\nmaizeto = maitrop+maitemp+maitropi+maitempi\n\n\n\nclm=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetrop_historical_co2_rf_fert_0.5x0.5.nc','r')\nclmtropf = clm.variables['yield'][99,:,:]\n#clmtropf=N.average(clmtrop,axis=0)\n\nclm1=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetemp_historical_co2_rf_fert_0.5x0.5.nc','r')\nclmtempf = clm1.variables['yield'][99,:,:]\n\nclm2=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetrop_historical_co2_irrig_fert_0.5x0.5.nc','r')\nclmtropfi = clm2.variables['yield'][99,:,:]\n\nclm3=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/maizetemp_historical_co2_irrig_fert_0.5x0.5.nc','r')\nclmtempfi = clm3.variables['yield'][99,:,:]\n\nclmtropf=N.flipud(clmtropf)\nclmtempf=N.flipud(clmtempf)\nclmtropfi=N.flipud(clmtropfi)\nclmtempfi=N.flipud(clmtempfi)\n\nclmtropf= ma.masked_where(maitrop<=0,clmtropf)\nclmtempf= ma.masked_where(maitemp<=0,clmtempf)\nclmtropf=ma.filled(clmtropf, fill_value=0.)\nclmtempf=ma.filled(clmtempf, fill_value=0.)\n\nclmtropfi= ma.masked_where(maitropi<=0,clmtropfi)\nclmtempfi= ma.masked_where(maitempi<=0,clmtempfi)\nclmtropfi=ma.filled(clmtropfi, fill_value=0.)\nclmtempfi=ma.filled(clmtempfi, fill_value=0.)\n\nyield_clmtf=clmtropf+clmtempf\nyield_clmtf = ma.masked_where(yield_clmtf<=0,yield_clmtf)\n#yield_clmtf = ma.masked_where(maizetor<=0,yield_clmtf )\nyield_clmtf=ma.filled(yield_clmtf, fill_value=0.)\n\nyield_clmtfi=clmtropfi+clmtempfi\nyield_clmtfi = ma.masked_where(yield_clmtfi<=0,yield_clmtfi)\n#yield_clmtfi = ma.masked_where(maizetoi<=0,yield_clmtfi)\nyield_clmtfi=ma.filled(yield_clmtfi, fill_value=0.)\n\n\narea=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf.nc','r')\ngridarea = area.variables['cell_area'][:,:]\ngridlon = area.variables['lon'][:]\n\ngridarea,gridlon = shiftgrid(180.5,gridarea,gridlon,start=False)\n\nnclu=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/maize_AreaYieldProduction.nc','r')\nncvar_maize = nclu.variables['maizeData'][:]\nlatnc = nclu.variables['latitude'][:]\nznc = nclu.variables['level'][:]\nlonnc = nclu.variables['longitude'][:]\ntimenc = nclu.variables['time'][:]\n\n\n\nyieldfi= N.zeros((1, 360, 720))\nyieldf2i= N.zeros((1, 360, 720))\n\nyieldf= N.zeros((1, 360, 720))\nyieldf2= N.zeros((1, 360, 720))\nyears = range(2000, 2001)\nfor i, year in enumerate(years):\n base = NetCDFFile (\"/scratch2/scratchdirs/tslin2/isam/model/global/isam_his/cruhis/output/cruhis.bgp-yearly_crop_{0}.nc\".format(year), mode='r')\n lona1 = base.variables[\"lon\"][:]\n lata1 = base.variables[\"lat\"][:]\n \n yield1 = base.variables[\"yield\"][0,:,:]\n yieldf[i, :, :] = yield1\n\n basei = NetCDFFile (\"/scratch2/scratchdirs/tslin2/isam/model/global/isam_his/cruhis_irr/output/cruhisirr.bgp-yearly_crop_{0}.nc\".format(year), mode='r')\n yield2 = basei.variables[\"yield\"][0,:,:]\n yieldf2[i, :, :] = yield2\n\nyielda=N.average(yieldf,axis=0)\nyielda2=N.average(yieldf2,axis=0)\n\nyield_new,lona11 = shiftgrid(180.5,yielda,lona1,start=False)\nyield_new2,lona11 = shiftgrid(180.5,yielda2,lona1,start=False)\n\nlon2,lat2 = N.meshgrid(lona11,lata1)\n\n\n\nfig, ax = plt.subplots(figsize=(8,6))\n\nax.set_title(\"Iizumi Maize Yield (t/ha)\",fontsize=20)\n\nmap = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')\nx,y = map(lon2,lat2)\niyield = ma.masked_where(iyield<=0,iyield)\niarea = ma.masked_where(iarea<=0,iarea)\n#iyield = ma.masked_where(iarea<=0,iyield)\niyield = ma.masked_where(maizeto<=0,iyield)\n\nmap.drawcoastlines()\nmap.drawcountries()\nmap.drawmapboundary()\niizumy=iyield\ncs = map.pcolormesh(x,y,iizumy,cmap=plt.cm.YlGn,vmin=0,vmax=16)\n\ncbar = map.colorbar(cs,location='bottom',size=\"5%\",pad=\"2%\")\ncbar.ax.tick_params(labelsize=15)\nplt.axis('off')\nplt.savefig('maiiizirr.jpg',dpi=300,bbox_inches='tight')\n\nfig = plt.figure(figsize=(20,15))\n\n\nax2 = fig.add_subplot(321)\nax2.set_title(\"ISAM-NCEP Maize Yield (t/ha)\",fontsize=20)\nmap = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')\nx,y = map(lon2,lat2)\niyield = ma.masked_where(iyield<=0,iyield)\niarea = ma.masked_where(iarea<=0,iarea)\n#iyield = ma.masked_where(iarea<=0,iyield)\n\nmap.drawcoastlines()\nmap.drawcountries()\nmap.drawmapboundary()\n#yield_new = ma.masked_where(yield_new<=0,yield_new)\nyield_new=maskoceans(x,y,yield_new)\nyield_new=ma.filled(yield_new, fill_value=0.)\nyield_new = ma.masked_where(yield_new<=0,yield_new)\nyield_new = ma.masked_where(maizeto<=0,yield_new)\n\nyield_new2=maskoceans(x,y,yield_new2)\nyield_new2=ma.filled(yield_new2, fill_value=0.)\nyield_new2 = ma.masked_where(yield_new2<=0,yield_new2)\nyield_new2 = ma.masked_where(maizeto<=0,yield_new2)\n\nisamy=((yield_new*maizetor*gridarea)+(yield_new2*maizetoi*gridarea))/((maizetoi*gridarea)+(maizetor*gridarea))\nisamy = ma.masked_where(iizumy<=0,isamy)\n\ncs1 = map.pcolormesh(x,y,isamy,cmap=plt.cm.YlGn,vmin=0,vmax=16)\ncbar = map.colorbar(cs1,location='bottom',size=\"5%\",pad=\"2%\")\ncbar.ax.tick_params(labelsize=15) \nplt.axis('off')\n\n\nax2 = fig.add_subplot(322)\nax2.set_title(\"CLM Maize Yield (t/ha)\",fontsize=20)\nmap = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')\n#map = Basemap(projection='robin',lon_0=0,resolution='c')\nmap.drawcoastlines()\nmap.drawcountries()\nmap.drawmapboundary()\n\n#yield_clmtf = ma.masked_where(yield_clmtf<=0,yield_clmtf)\n\n#yield_clmtfi = ma.masked_where(yield_clmtfi<=0,yield_clmtfi)\n\nyield_clmtf=maskoceans(x,y,yield_clmtf)\n#yield_clmtf=ma.filled(yield_clmtf, fill_value=0.)\n#yield_clmtf = ma.masked_where(yield_clmtf<=0,yield_clmtf)\nyield_clmtf = ma.masked_where(maizeto<=0,yield_clmtf)\n\nyield_clmtfi=maskoceans(x,y,yield_clmtfi)\n#yield_clmtfi=ma.filled(yield_clmtfi, fill_value=0.)\n#yield_clmtfi = ma.masked_where(yield_clmtfi<=0,yield_clmtfi)\nyield_clmtfi = ma.masked_where(maizeto<=0,yield_clmtfi)\n\nclmy=((yield_clmtf*maizetor*gridarea)+(yield_clmtfi*maizetoi*gridarea))/((maizetoi*gridarea)+(maizetor*gridarea))\nclmy = ma.masked_where(iizumy<=0,clmy)\n\ncs1 = map.pcolormesh(x,y,clmy,cmap=plt.cm.YlGn,vmin=0,vmax=16)\n\ncbar = map.colorbar(cs1,location='bottom',size=\"5%\",pad=\"2%\")\ncbar.ax.tick_params(labelsize=15) \nplt.axis('off')\n#print N.max(yield_fine*ncvar_maize1*1000/gridarea)\n\n\n\nax2 = fig.add_subplot(323)\nax2.set_title(\"ISAM-Iizumi Maize Yield (t/ha)\",fontsize=20)\nmap = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')\n#map = Basemap(projection='robin',lon_0=0,resolution='c')\nmap.drawcoastlines()\nmap.drawcountries()\nmap.drawmapboundary()\ncd=isamy-iizumy\ncd = ma.masked_where(cd==0,cd)\n\ncs1 = map.pcolormesh(x,y,cd,cmap=plt.cm.bwr,vmin=-5,vmax=5)\n\ncbar = map.colorbar(cs1,location='bottom',size=\"5%\",pad=\"2%\")\ncbar.ax.tick_params(labelsize=15) \nplt.axis('off')\n\n\nax2 = fig.add_subplot(324)\nax2.set_title(\"CLM-Iizumi Maize Yield (t/ha)\",fontsize=20)\nmap = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')\n#map = Basemap(projection='robin',lon_0=0,resolution='c')\nmap.drawcoastlines()\nmap.drawcountries()\nmap.drawmapboundary()\ncs1 = map.pcolormesh(x,y,clmy-iizumy,cmap=plt.cm.bwr,vmin=-5,vmax=5)\n\ncbar = map.colorbar(cs1,location='bottom',size=\"5%\",pad=\"2%\")\ncbar.ax.tick_params(labelsize=15) \nplt.axis('off')\n\n\n\nax2 = fig.add_subplot(325)\nax2.set_title(\"ISAM-Iizumi Maize Yield gridcell (%)\",fontsize=20)\nmap = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')\n#map = Basemap(projection='robin',lon_0=0,resolution='c')\nmap.drawcoastlines()\nmap.drawcountries()\nmap.drawmapboundary()\ncs1 = map.pcolormesh(x,y,(isamy-iizumy)/iizumy*100,cmap=plt.cm.bwr,vmin=-100,vmax=100)\n\ncbar = map.colorbar(cs1,location='bottom',size=\"5%\",pad=\"2%\")\ncbar.ax.tick_params(labelsize=15)\nplt.axis('off')\n\n\nax2 = fig.add_subplot(326)\nax2.set_title(\"CLM-Iizumi Maize Yield gridcell (%)\",fontsize=20)\nmap = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')\n#map = Basemap(projection='robin',lon_0=0,resolution='c')\nmap.drawcoastlines()\nmap.drawcountries()\nmap.drawmapboundary()\n#diff=(yield_clmtf*iarea/100/10*1000)-(iyield*iarea/100/10*1000)\ncs1 = map.pcolormesh(x,y,(clmy-iizumy)/iizumy*100,cmap=plt.cm.bwr,vmin=-100,vmax=100)\n\ncbar = map.colorbar(cs1,location='bottom',size=\"5%\",pad=\"2%\")\ncbar.ax.tick_params(labelsize=15)\nplt.axis('off')\n\n\n\nplt.savefig('maiiizirr1_ncep.jpg',dpi=300,bbox_inches='tight')\nplt.show()\n\n\n#fig, ax = plt.subplots(figsize=(6,6))\ncolors = (0,0,1)\ncolorsr = (1,0,0)\nfig = plt.figure(figsize=(8,12))\nax = fig.add_subplot(211)\n\n#ax.plot([0,1000],[0,1000], 'k--',label='1:1')\n\n#ax.scatter(iizumy, isamy, c=colors,alpha=1,label='ISAM')\nax.scatter(iizumy, clmy, c=colorsr,alpha=0.5,label='CLM')\nplt.xlim(0, 16)\nplt.ylim(0, 16)\nax.plot([0,16],[0,16], 'k--',label='1:1')\n\n#ax.set_title('Maize yield over gridcell',fontsize=18)\n#ax.legend()\n\nplt.tick_params(axis='both',labelsize=15)\nplt.xlabel('Iizumi-Crops (t/ha)',fontsize=18)\nplt.ylabel('Model (t/ha)',fontsize=18)\n\n\nax = fig.add_subplot(212)\n\n#ax.plot([0,1000],[0,1000], 'k--',label='1:1')\n\nax.scatter(iizumy, isamy, c=colors,alpha=0.5,label='ISAM')\n#ax.scatter(iizumy, clmy, c=colorsr,alpha=0.5,label='CLM')\nax.plot([0,16],[0,16], 'k--',label='1:1')\n\nplt.xlim(0, 16)\nplt.ylim(0, 16)\n#ax.set_title('Maize yield over gridcell',fontsize=18)\n#ax.legend()\nplt.xticks([])\nplt.tick_params(axis='both',labelsize=15)\n#plt.xlabel('Iizumi-Crops (g/$\\mathregular{m^2}$)',fontsize=18)\nplt.ylabel('Model (t/ha)',fontsize=18)\n\nplt.savefig('scatter_maiiizirr1_ncep.png',bbox_inches='tight')\n#plt.show()\n\n\n","sub_path":"scripts/plotcrop-master/spatial/maiiiz1_irrnew.py","file_name":"maiiiz1_irrnew.py","file_ext":"py","file_size_in_byte":11089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"220494644","text":"# -*- coding: utf-8 -*-\n\nimport h5py\nimport numpy as np\nimport scipy as sp\nfrom scipy import signal\n\ndef insertAttrs():\n dsets = h5py.File('D:/workspace/eeg/minlab/ppres.hdf5','r')\n dsetsnew = h5py.File('D:/workspace/eeg/minlab/ppres3.hdf5','w')\n dsetsattr = h5py.File('D:/workspace/eeg/minlab/test2.hdf5','r')\n\n oriDsets = []\n for i in dsetsattr.items():\n dset = dsetsattr[i[0]]\n if dset.attrs['convdiv'] == b'Conv' and dset.attrs['expunexp'] == b'ExpectedTarget':\n oriDsets.append(i[0])\n\n cnt = 0\n for i in dsets.items():\n if i[0] == 'rout': continue\n dsetattr = dsetsattr[oriDsets[cnt]]\n dset = dsetsnew.create_dataset(i[0],data=dsets[i[0]],dtype=np.float16)\n for j in dsetattr.attrs.items():\n dset.attrs[j[0]] = j[1]\n cnt = cnt + 1\n\n dsets.close()\n dsetsattr.close()\n dsetsnew.flush()\n dsetsnew.close()\n return dsetsnew\n\ndef showattrs(dsets):\n #dsets = h5py.File('D:/workspace/eeg/minlab/res.hdf5','r')\n cnt = 0\n for i in dsets.items():\n dset = dsets[i[0]]\n #print(i[0]); continue\n for j in dset.attrs.items():\n print(j)\n #if cnt == 10: break\n cnt = cnt + 1\n\ndef meanbyexpr(dsets):\n resdata = []\n resisi = []\n resstuno = []\n for i in dsets.items():\n dset = dsets[i[0]]\n stuno = dset.attrs['studentno']\n isi = dset.attrs['isi']\n resdata.append(np.apply_along_axis(np.mean,1, np.array(dset)))\n resisi.append(isi)\n resstuno.append(stuno)\n return resdata,resisi, resstuno\n\ndef findpeaks(resdata):\n respeaks = []\n for i in resdata:\n peaks = []\n for j in range(i.shape[0]):\n peaks.append(np.mean(i[j,signal.find_peaks_cwt(list(i[j,:]),np.arange(1,50))]))\n respeaks.append(peaks)\n return respeaks\n\ndef exec():\n dsets = h5py.File('D:/workspace/eeg/minlab/ppres3.hdf5','r')\n resdata,resisi,resstuno = meanbyexpr(dsets)\n respeaks = findpeaks(resdata)\n\n return resdata,resisi,resstuno,respeaks\n\n\n\n\n\nexec()\n","sub_path":"experiment/expr_03.py","file_name":"expr_03.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"578731774","text":"#!/usr/bin/python\r\n# Copyright 2019, 2020 Jack Consoli. All rights reserved.\r\n#\r\n# NOT BROADCOM SUPPORTED\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may also obtain a copy of the License at\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"\r\n:mod:`maps_clear.py` - Clear the MAPS dashboard\r\n\r\nVersion Control::\r\n\r\n +-----------+---------------+-----------------------------------------------------------------------------------+\r\n | Version | Last Edit | Description |\r\n +===========+===============+===================================================================================+\r\n | 1.0.0 | 01 Dec 2019 | Initial |\r\n +-----------+---------------+-----------------------------------------------------------------------------------+\r\n | 1.0.1 | 28 Dec 2019 | Updated comments only |\r\n +-----------+---------------+-----------------------------------------------------------------------------------+\r\n | 1.0.2 | 28 Mar 2020 | Missed a regression when the brcdapi.brcdapi_rest library was updated |\r\n +----------+----------------+-----------------------------------------------------------------------------------+\r\n | 1.0.3 | 26 Apr 2020 | Added ability to enable driver level debug. |\r\n +-----------+---------------+-----------------------------------------------------------------------------------+\r\n\"\"\"\r\n__author__ = 'Jack Consoli'\r\n__copyright__ = 'Copyright 2019, 2020 Jack Consoli'\r\n__date__ = '26 Apr 2020'\r\n__license__ = 'Apache License, Version 2.0'\r\n__email__ = 'jack.consoli@broadcom.com'\r\n__maintainer__ = 'Jack Consoli'\r\n__status__ = 'Released'\r\n__version__ = '1.0.3'\r\n\r\nimport argparse\r\nimport brcdapi.brcdapi_rest as brcdapi_rest\r\nimport brcdapi.pyfos_auth as pyfos_auth\r\nimport brcdapi.log as brcdapi_log\r\n\r\n_DOC_STRING = False # Should always be False. Prohibits any actual I/O. Only useful for building documentation\r\n_DEBUG = False # When True, use _DEBUG_* below instead of passed arguments.\r\n_DEBUG_IP = '10.8.105.10'\r\n_DEBUG_ID = 'admin'\r\n_DEBUG_PW = 'password'\r\n_DEBUG_SEC = 'none'\r\n_DEBUG_FID = 20\r\n_DEBUG_VERBOSE = False # When True, all content and responses are formatted and printed.\r\n\r\ndef version():\r\n \"\"\"Returns the module version number\r\n\r\n :return: Version\r\n :rtype: str\r\n \"\"\"\r\n return __version__\r\n\r\n\r\ndef parse_args():\r\n \"\"\"Parses the module load command line\r\n\r\n :return ip: IP address\r\n :rtype ip: str\r\n :return id: User ID\r\n :rtype id: str\r\n :return pw: Password\r\n :rtype pw: str\r\n :return s: Type of HTTP security. None if not specified\r\n :rtype s: str, None\r\n :return fid: Fabric ID\r\n :rtype fid: int\r\n :return d: True - enable log debug\r\n :rtype d: bool\r\n \"\"\"\r\n if _DEBUG:\r\n return _DEBUG_IP, _DEBUG_ID, _DEBUG_PW, _DEBUG_SEC, _DEBUG_FID, _DEBUG_VERBOSE\r\n else:\r\n buf = 'Creates new MAPS rules for SFPs, copies the policy specified with the -m parameter, removes all SFP '\r\n buf += 'rules from the copied policy, adds the new SFP rules to the copied policy, then, if -a is specified, '\r\n buf += 'enables the copied policy.'\r\n parser = argparse.ArgumentParser(description=buf)\r\n parser.add_argument('-ip', help='IP address', required=True)\r\n parser.add_argument('-id', help='User ID', required=True)\r\n parser.add_argument('-pw', help='Password', required=True)\r\n parser.add_argument('-s', help='\\'CA\\' or \\'self\\' for HTTPS mode.', required=False,)\r\n parser.add_argument('-fid', help='FID number', required=True,)\r\n parser.add_argument('-d', help='Enable debug logging.', action='store_true', required=False)\r\n args = parser.parse_args()\r\n return args.ip, args.id, args.pw, args.s, args.fid, args.d\r\n\r\n\r\ndef _clear_dashboard(session, fid):\r\n \"\"\"Clears the MAPS dashboard\r\n\r\n :return fid: Fabric ID\r\n :rtype fid: int\r\n \"\"\"\r\n content = {'clear-data': True}\r\n obj = brcdapi_rest.send_request(session, 'brocade-maps/dashboard-misc', 'PUT', content, fid)\r\n if pyfos_auth.is_error(obj):\r\n print('Failed to clear MAPS dashboard')\r\n brcdapi_log.log(pyfos_auth.formatted_error_msg(obj), True)\r\n return -1\r\n return 0\r\n\r\n\r\ndef pseudo_main():\r\n \"\"\"Basically the main().\r\n\r\n :return: Exit code\r\n :rtype: int\r\n \"\"\"\r\n if _DEBUG:\r\n brcdapi_log.log('WARNING!!! Debug is enabled')\r\n ip, user_id, pw, sec, fid, vd = parse_args()\r\n if vd:\r\n brcdapi_rest.verbose_debug = True\r\n fid = int(fid)\r\n if sec is None:\r\n sec = 'none'\r\n\r\n # Login\r\n brcdapi_log.log('Attempting login')\r\n session = brcdapi_rest.login(user_id, pw, ip, sec)\r\n if pyfos_auth.is_error(session):\r\n brcdapi_log.log('Login failed')\r\n brcdapi_log.log(pyfos_auth.formatted_error_msg(session))\r\n return -1\r\n brcdapi_log.log('Login succeeded')\r\n\r\n # try/except used during development to ensure logout due to programming errors.\r\n try:\r\n ec = _clear_dashboard(session, fid)\r\n except:\r\n brcdapi_log.exception('Encountered a programming error')\r\n ec = -1\r\n\r\n obj = brcdapi_rest.logout(session)\r\n if pyfos_auth.is_error(obj):\r\n brcdapi_log.log('Logout failed:\\n' + pyfos_auth.formatted_error_msg(obj), True)\r\n return ec\r\n\r\n###################################################################\r\n#\r\n# Main Entry Point\r\n#\r\n###################################################################\r\n\r\n\r\nif not _DOC_STRING:\r\n brcdapi_log.close_log(str(pseudo_main()), True)\r\n","sub_path":"maps_clear.py","file_name":"maps_clear.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"542018458","text":"from datetime import datetime\n\nfrom day18.utils.trans.tools import gen_trans_id\nfrom day18.utils.trans import tools as trans_tools\nfrom day18.utils.work import tools as work_tools\n\ndef test_trans_tool():\n \"\"\"测试trans包下的tools模块\"\"\"\n id1 = trans_tools.gen_trans_id()\n print(id1)\n date = datetime(2015,12,2,16,45,20)\n id2 = trans_tools.gen_trans_id(date)\n print(id2)\n\ndef test_work_tool():\n \"\"\"测试work模块\"\"\"\n file_name = \"D:\\\\python学习文件夹\\\\test.jpg\"\n rest = work_tools.get_file_type(file_name)\n print(rest)\n\nif __name__ == '__main__':\n test_trans_tool()\n test_work_tool()\n\n\n\n\n","sub_path":"步骤二:python函数与模块/day18/utils/trans/test_module.py","file_name":"test_module.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"322427775","text":"import scrapy\n\n\nclass QuotesSpider(scrapy.Spider):\n name = \"willhabenCrawlerXpath\"\n start_urls = [\n 'https://www.willhaben.at/iad/kaufen-und-verkaufen/marktplatz/tische-5751/',\n ]\n\n def parse(self, response):\n \n\n for quote in response.xpath('//article[@class=\"search-result-entry \"]'):\n yield {\n \n \n #TITLE\n 'title' : quote.xpath('.//div[@class=\"header w-brk\"]/a/span/text()').extract(),\n \n #price\n #note: propapy doesnt work cause script\n #'price' : quote.xpath('.//div[@class=\"info\"]').extract(),\n\n \n #description\n 'description' : quote.xpath('.//div[@class=\"description\"]/text()').extract_first(),\n \n #adress\n 'adress' : quote.xpath('.//div[@class=\"address-lg w-brk-ln-1 \"]/text()').extract(),\n 'date' : quote.xpath('.//div[@class=\"bottom-2\"]/text()').extract(),\n\n \n \n #image\n 'image' : quote.xpath('.//section[@class=\"image-section\"]/a/img/@src').extract(),\n }\n \n\n\n\n #next_page = response.css('li.next a::attr(\"href\")').extract_first()\n #if next_page is not None:\n # yield response.follow(next_page, self.parse)\n ","sub_path":"Crawler1/crawler1/crawler1/spiders/willhabenCrawlerXpath.py","file_name":"willhabenCrawlerXpath.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"79677115","text":"from .models import Session\nfrom datetime import datetime\nfrom django.contrib.auth.models import AnonymousUser\n\n\nclass CheckSession:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n session_id = request.COOKIES.get('session_id')\n\n try:\n session = Session.objects.get(key=session_id, date__gt=datetime.now())\n request.my_app_session = session\n request.my_app_user = session.user\n except Session.DoesNotExist:\n request.my_app_session = None\n request.my_app_user = None\n\n response = self.get_response(request)\n return response\n","sub_path":"app/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"602780383","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport socket,time,os\nauthenticated = False #用户登陆状态\n\ndef put(file_name,client):\n '''\n 上传文件\n :param file_name: 文件名\n :return:\n '''\n try:\n f = open(file_name,'rb')\n client.sendall(f.read())\n f.close()\n time.sleep(1)\n client.send(b'EOF')\n print('上传完成')\n except FileNotFoundError:\n client.send(b'file does not exist')\n print('请检查文件名的正确性')\n\ndef get(file_name,client):\n f = open(file_name,'wb')\n while True:\n put_data = client.recv(10240000)\n if put_data == b'file does not exist':#如果要下载的文件不存在\n print('文件不存在,请输入正确的文件名')\n f.close()\n os.remove(file_name)\n return\n if put_data == b'EOF':\n break\n f.write(put_data)\n f.flush()\n print('下载完成')\n f.close()\n\ndef operate(client):\n while True:\n command = input('command:').strip()\n if command == 'q':\n client.sendall(command.encode())\n break\n elif command.startswith('dir'):\n client.send(command.encode())\n data = client.recv(1024000)\n print(data.decode('gbk'))\n elif command.startswith('put'):\n command_list = command.split()\n client.sendall(bytes(command,encoding='utf--8'))\n put(command_list[1],client)\n elif command.startswith('get'):\n command_list = command.split()\n client.sendall(bytes(command,encoding='utf--8'))\n get(command_list[1],client)\n else:\n print('Input error')\n client.close() #关闭这个连接\n\ndef main():\n global authenticated\n client = socket.socket() #声明socket连接类型,默认为TCP/IP IPV4,同时生成一个socket连接对象\n client.connect(('localhost',30301))#连接到一个地址的端口,参数类型为一个元组(hostname,port)\n while not authenticated:\n user = input('user:').strip()\n passwd = input('password:').strip()\n user_passwd = user+' '+passwd #组合用户名和密码\n client.sendall(bytes(user_passwd,encoding='utf-8')) #发送数据,数据必须是bytes类型\n data = client.recv(1024000) #接收的数据量,默认大小单位为字节\n if data.decode() == 'Welcome':\n authenticated = True\n print('欢迎登陆')\n operate(client)\n else:\n print(data.decode())\n\nif __name__ == '__main__':\n main()","sub_path":"Modular_three/FTP/ftp_client.py","file_name":"ftp_client.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"652702857","text":"import tensorflow as tf\nimport numpy as np\nimport unittest\n\n\ndef readfile():\n with open('train.txt', 'r') as f:\n train_data = np.array([int(x) for x in f.read()]).reshape((6000, 2))\n with open('label.txt', 'r') as f:\n train_label = np.array([int(x) for x in f.read()])\n\n with open('train_test.txt', 'r') as f:\n train_data_test = np.array([int(x) for x in f.read()]).reshape((1000, 2))\n with open('label_test.txt', 'r') as f:\n train_label_test = np.array([int(x) for x in f.read()])\n return train_data, train_label, train_data_test, train_label_test\n\n\ndef main():\n x = tf.placeholder(tf.float32, [None, 2])\n w = tf.Variable(tf.zeros([2, 3]))\n b = tf.Variable(tf.zeros([3]))\n y = tf.matmul(x, w) + b\n y_ = tf.placeholder(tf.int64, [None]) # 一维的,就是它的真实值\n # tf.losses.sparse_softmax_cross_entropy 这种方法的label是真实值\n # tf.nn.softmax_cross_entropy_with_logits 两个方法可以定义损失函数,这种方法的label是由one-hot编码\n\n # The raw formulation of cross-entropy,\n #\n # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n # reduction_indices=[1]))\n #\n # can be numerically unstable.\n #\n # So here we use tf.losses.sparse_softmax_cross_entropy on the raw\n # logit outputs of 'y', and then average across the batch.\n cross_entropy = tf.losses.sparse_softmax_cross_entropy(logits=y, labels=y_)\n train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n train_data, train_label, train_data_test, train_label_test = readfile()\n sess = tf.InteractiveSession()\n sess.run(tf.global_variables_initializer())\n for _ in range(1000):\n sess.run(train_step, feed_dict={x: train_data, y_: train_label})\n\n correct_prediction = tf.equal(tf.argmax(y, 1), y_)\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n print(sess.run(accuracy, feed_dict={x: train_data_test,\n y_: train_label_test}))\n print(sess.run(w))\n print(sess.run(b))\n\n\nif __name__ == '__main__':\n main()\n\n\nclass TestDict(unittest.TestCase):\n\n def test_init(self):\n w = np.array([[-1.00487339, - 1.15891397, 2.16378975],\n [-0.44634497, 4.75635386, -4.31000757]])\n b = np.array([-0.44633889, 4.75634384, -4.31001806])\n y = np.matmul([6, 1], w) + b\n print(y)\n","sub_path":"trials/validateSoftmax.py","file_name":"validateSoftmax.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"393002519","text":"from os.path import join\n\nfrom flask import Flask\nfrom flask_assets import Environment as FlaskAssets, Bundle\nfrom flask_sqlalchemy import SQLAlchemy\n\n\napp = Flask(__name__)\n\napp.config.from_object('config.Config')\napp.secret_key = app.config['SECRET_KEY']\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\nassets = FlaskAssets(app)\n\nassets.register('js_base', Bundle(\n join('js', 'jquery-1.12.4.js'),\n join('js', 'bootstrap-3.3.7.js'),\n filters='jsmin',\n output=join('gen', 'js.%(version)s.min.js'))\n)\nassets.register('js_activity', Bundle(\n join('js', 'activity.js'),\n filters='jsmin',\n output=join('gen', 'activity.%(version)s.min.js'))\n)\nassets.register('css_base', Bundle(\n join('css', 'bootstrap.css'),\n join('css', 'font-awesome.css'),\n join('css', 'app.css'),\n filters='cssmin',\n output=join('gen', 'css.%(version)s.min.css'))\n)\n\n\ndb = SQLAlchemy(app)\n\nfrom DataQualityTester import routes, models, views, lib\n","sub_path":"DataQualityTester/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"247256175","text":"\"\"\"sampler for configuring the transport layer security\"\"\"\nimport configparser\nimport os\nfrom os.path import dirname\nfrom solace.messaging.config.transport_security_strategy import TLS\nfrom solace.messaging.messaging_service import MessagingService\nfrom sampler_boot import SamplerUtil\n\nCONFIG_INI_FILE_NAME = \"config.ini\"\n\n\ndef config_parser():\n \"\"\"method used to parse the config properties from the config.ini\"\"\"\n config = configparser.ConfigParser()\n config.read(os.path.join(dirname(dirname(__file__)), CONFIG_INI_FILE_NAME))\n config_parser_dict = {s: dict(config.items(s)) for s in config.sections()}\n if 'solace_properties_template' not in config_parser_dict:\n raise Exception('Unable to locate \"solace_properties_template\" broker properties in config.ini')\n return config_parser_dict['solace_properties_template']\n\n\nbroker_properties_value = config_parser()\n\n\nclass HowToConnectWithTls:\n \"\"\"sampler class for validating transport layer security configuration\"\"\"\n\n @staticmethod\n def tls_with_certificate_validation_and_trusted_store_settings(props, ignore_expiration: bool,\n trust_store_path: str):\n \"\"\"method for validating tls certificate along with trusted store by providing the file path\n Args:\n props: broker properties\n trust_store_path (str): trust store file path\n ignore_expiration (bool): holds a boolean flag whether to ignore expiration or not\n\n Returns:\n a new connection to messaging service\n \"\"\"\n try:\n transport_security = TLS.create() \\\n .with_certificate_validation(ignore_expiration=ignore_expiration,\n trust_store_file_path=trust_store_path)\n messaging_service = MessagingService.builder().from_properties(props)\\\n .with_transport_security_strategy(transport_security).build()\n messaging_service.connect()\n\n finally:\n messaging_service.disconnect()\n\n @staticmethod\n def tls_downgradable_to_plain_text(props):\n \"\"\"method for validating the tls downgradable to plain text\n Args:\n props: broker properties\n\n Returns:\n a new connection to messaging service\n \"\"\"\n try:\n transport_security = TLS.create().downgradable()\n messaging_service = MessagingService.builder().from_properties(props) \\\n .with_transport_security_strategy(transport_security).build()\n messaging_service.connect()\n finally:\n messaging_service.disconnect()\n\n @staticmethod\n def tls_with_excluded_protocols(props, excluded_protocol: TLS.SecureProtocols):\n \"\"\"method for validating excluding tls protocols\n Args:\n props: broker properties\n excluded_protocol (SecuredProtocols): contains a value or a list of values of protocols to be excluded\n\n Returns:\n a new connection to messaging service\n \"\"\"\n try:\n transport_security = TLS.create().with_excluded_protocols(excluded_protocol)\n\n messaging_service = MessagingService.builder().from_properties(props) \\\n .with_transport_security_strategy(transport_security).build()\n messaging_service.connect()\n finally:\n messaging_service.disconnect()\n\n @staticmethod\n def tls_with_cipher_suites(props, cipher_suite: str):\n \"\"\"method for validating the cipher suited with tls\n Args:\n props: broker properties\n cipher_suite (str): cipher suite list\n\n Returns:\n a new connection to messaging service\n \"\"\"\n try:\n transport_security = TLS.create().with_cipher_suites(cipher_suite)\n\n messaging_service = MessagingService.builder().from_properties(props) \\\n .with_transport_security_strategy(transport_security).build()\n messaging_service.connect()\n finally:\n messaging_service.disconnect()\n\n @staticmethod\n def run():\n \"\"\"method to run all the methods related to tls configuration \"\"\"\n props = broker_properties_value\n trust_store_path_name = SamplerUtil.get_trusted_store_dir()\n cipher_suite = \"ECDHE-RSA-AES256-GCM-SHA384\"\n\n HowToConnectWithTls.\\\n tls_with_certificate_validation_and_trusted_store_settings(props, ignore_expiration=True,\n trust_store_path=trust_store_path_name)\n\n HowToConnectWithTls.tls_downgradable_to_plain_text(props)\n\n HowToConnectWithTls.tls_with_excluded_protocols(props,\n excluded_protocol=TLS.SecureProtocols.SSLv3)\n\n HowToConnectWithTls.tls_with_cipher_suites(props, cipher_suite=cipher_suite)\n\n\nif __name__ == '__main__':\n HowToConnectWithTls.run()\n","sub_path":"howtos/extras/how_to_configure_transport_layer_security.py","file_name":"how_to_configure_transport_layer_security.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"323152175","text":"from datetime import timedelta\n\nclass Equipo:\n def __init__(self, nombre, iniciales, img_logo = None):\n self.nombre = nombre\n self.iniciales = iniciales\n self.img_logo = img_logo\n\n def __str__(self):\n return self.nombre + '(' + self.iniciales + ')'\n\nclass Partido:\n def __init__(self, equipos = [], ganador = None):\n self.equipos = equipos\n self.ganador = ganador\n \n def __str__(self):\n if self.ganador == None:\n return str(self.equipos[0]) + ' vs ' + str(self.equipos[1])\n else:\n return str(self.equipos[0]) + ' vs ' + str(self.equipos[1]) + '\\tGanador: ' + str(self.ganador)\n\nclass Eliminatoria:\n def __init__(self, equipos = [], partidos = [], ganador = None):\n self.partidos = partidos\n self.equipos = equipos\n self.ganador = ganador\n\n def __str__(self):\n if self.ganador == None:\n return 'Eliminatoria: ' + str(self.equipos[0]) + ' vs ' + str(self.equipos[1])\n else:\n return 'Eliminatoria: ' + str(self.equipos[0]) + ' vs ' + str(self.equipos[1]) + '\\tGanador: ' + str(self.ganador)\n\n def nuevo_partido(self, equipo1, equipo2, fecha):\n Partido(fecha, [equipo1, equipo2])\n\n# Comprobar\n def nuevo_ganador(self):\n contador_equipo1 = 0\n contador_equipo2 = 0\n for equipo in self.partidos:\n if equipo == self.equipos[0]:\n contador_equipo1 += 1\n elif equipo == self.equipos[1]:\n contador_equipo2 += 1\n \n if contador_equipo1 == 4:\n return self.equipos[0]\n elif contador_equipo2 == 4:\n return self.equipos[1]\n\nclass Temporada:\n def __init__(self, nombre, equipos = [], eliminatorias = []):\n self.nombre = nombre\n self.equipos = equipos\n self.eliminatorias = eliminatorias\n\n def __str__(self):\n string = 'Temporada: ' + self.nombre + '\\n'\n for equipo in self.equipos:\n string += '\\t' + str(equipo) + '\\n'\n return string\n \n #comprobar\n def nueva_eliminatoria(self, equipo1, equipo2, fecha):\n lista_partidos = []\n for i in range(7):\n lista_partidos.append(Partido(fecha, [equipo1, equipo2]))\n fecha += timedelta(days=2)\n self.eliminatorias.append(Eliminatoria([equipo1, equipo2], lista_partidos))\n\n def busca_eliminatoria(self, equipo1, equipo2):\n for eliminatoria in self.eliminatorias:\n if [equipo1, equipo2] == eliminatoria.equipos:\n return eliminatoria\n \n def introduce_resultado(self, eliminatoria, ganador):\n for partido in eliminatoria.partidos:\n if fecha == partido.fecha:\n partido.ganador = ganador\n","sub_path":"playoff_clases.py","file_name":"playoff_clases.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"416731636","text":"import sys\nimport os\nimport glob\nimport errno\nimport numpy as np\n\nimport parse_intent\nimport dataset_io as dio\nimport parameter_io as pio\n\nclass Universe(object):\n \"\"\"\n Create the universe of the simulation.\n \"\"\"\n\n def __init__(self,\n world_fn=None,\n organisms_fn=None,\n world_param_fn=None,\n species_param_fns=None,\n custom_methods_fns=None,\n current_time=0,\n end_time=10,\n dataset_dir='datasets/',\n pad_zeroes=4,\n file_extension='.txt'):\n \"\"\"\n Initialize universe based on either parameter files or saved datasets.\n\n Parameters\n ----------\n world_fn : str\n Filename of saved world dataset.\n organisms_fn : str\n Filename of saved organism dataset.\n world_param_fn : str\n Filename of world parameter file.\n species_param_fns : list of str\n List of filenames of species parameter files.\n custom_methods_fns : list of str\n List of filenames of external python scripts containing custom\n behaviors.\n current_time : int\n Current time of simulation.\n end_time : int\n End time of simulation.\n dataset_dir : str\n Directory path for saving all world and organism datasets.\n pad_zeroes : int\n Number of zeroes to pad in dataset filenames.\n file_extension : str\n File extension for saving dataset files. Should generally be '.txt'\n or '.json'.\n\n \"\"\"\n self.world_fn = world_fn\n self.organisms_fn = organisms_fn\n self.world_param_fn = world_param_fn\n self.species_param_fns = species_param_fns\n self.custom_methods_fns = custom_methods_fns\n\n self.current_time = current_time\n self.end_time = end_time\n\n self.dataset_dir = dataset_dir\n if dataset_dir[-1] != '/':\n self.dataset_dir += '/'\n try:\n os.makedirs(dataset_dir)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n self.pad_zeroes = pad_zeroes\n while (self.end_time - self.current_time) >= 10 ** self.pad_zeroes:\n self.pad_zeroes += 1\n self.file_extension = file_extension\n\n # world is a World object\n self.world = self.initialize_world()\n # organisms is a list of Organism objects\n self.organism_list = self.initialize_organisms()\n self.intent_list = []\n\n def initialize_world(self):\n \"\"\"\n Initialize the world of the universe from either a saved dataset\n or from a parameter file (and subsequently writing the\n initial time step to file).\n\n Returns\n -------\n world : World\n World at the beginning of the simulation.\n \"\"\"\n if self.world_fn is not None:\n # Set up entire world based on world records\n world = dio.load_world_dataset(self.world_fn)\n elif self.world_param_fn is not None:\n # Set up entire world based on parameter file\n world = pio.load_world_parameters(self.world_param_fn)\n dio.write_world_dataset(world, self.dataset_dir + 'world_ds' + str(self.current_time).zfill(self.pad_zeroes) + self.file_extension)\n else:\n sys.exit('No files specified for initialization!')\n return world\n\n def initialize_organisms(self):\n \"\"\"\n Initialize all organisms in the universe from either a saved dataset\n or from parameter files (and subsequently writing the\n initial time step to file).\n\n Returns\n -------\n organism_list : list of Organisms\n List of organisms at the beginning of the simulation.\n \"\"\"\n if self.organisms_fn is not None:\n # Set up all organisms based on organism records\n organism_list = dio.load_organism_dataset(self.organisms_fn)\n elif self.species_param_fns is not None:\n # Set up all organisms based on species specifications\n organism_list = pio.load_species_parameters(self.species_param_fns, self.world, self.custom_methods_fns)\n dio.write_organism_dataset(organism_list, self.dataset_dir + 'organisms_ds' + str(self.current_time).zfill(self.pad_zeroes) + self.file_extension)\n else:\n sys.exit('No files specified for initialization!')\n return organism_list\n\n def step(self):\n \"\"\"\n Steps through one time step, iterating over all organisms and\n computing new organism states. Saves all organisms and the world\n to file at the end of each step.\n \"\"\"\n self.intent_list = []\n for organism in self.organism_list:\n for new_organism in organism.step(self.organism_list, self.world):\n self.intent_list.append(new_organism)\n\n self.current_time += 1\n # Parse intent list and ensure it is valid\n self.organism_list = parse_intent.parse(self.intent_list, self.organism_list)\n\n dio.write_organism_dataset(self.organism_list, self.dataset_dir + 'organisms_ds' + str(self.current_time).zfill(self.pad_zeroes) + self.file_extension)\n\n # Potential changes to the world would go here\n dio.write_world_dataset(self.world, self.dataset_dir + 'world_ds' + str(self.current_time).zfill(self.pad_zeroes) + self.file_extension)\n\n\n# At its simplest, the entire executable could just be written like this\nif __name__ == '__main__':\n universe = Universe()\n while universe.current_time < universe.end_time:\n universe.step()\n","sub_path":"blossom/universe.py","file_name":"universe.py","file_ext":"py","file_size_in_byte":5734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"369719332","text":"### CONWAY'S GAME OF LIFE ###\n### Implemented in Python ###\n### by Howard Melnyczuk ###\n\n\n# import graphics.py for display purposes\nfrom graphics import GraphWin, Rectangle, Point\n# import numpy to contain Game of Life state information\nimport numpy as np\n\n\nclass GOL:\n \"\"\"\n This class contains everything needed to calculate a game of life.\n\n Designed to work regardless of output method\n \"\"\"\n\n def __init__(self, _w, _h):\n self.w = _w\n self.h = _h\n # Create new numpy array to store Game of Life grid\n self.grid = np.zeros((self.w, self.h), dtype=\"int32\")\n\n def initRandomGrid(self):\n \"\"\" Initialise a random seed grid \"\"\"\n return np.random.randint(2, size=(self.w, self.h), dtype=\"int32\")\n\n def update(self):\n \"\"\" \n Update the game for the next iteration\n\n Return a grid for the next iteration\n \"\"\"\n self.grid = self.progress()\n return self.grid\n\n def progress(self):\n \"\"\"\n Create a temporary numpy array to store next iteration\n \"\"\"\n nextGen = np.zeros((self.w, self.h), dtype=\"int32\")\n for x in range(self.w):\n for y in range(self.h):\n nextGen[x][y] = self.getState(x, y)\n return nextGen\n\n def getState(self, x, y):\n \"\"\"\n Return next iteration state for any cell (x,y)\n\n Check state against rules of life\n \"\"\"\n n = self.kernel(x, y)\n state = 0\n # Kill cell if kernel is overcrowded or underpopulated\n if n > 3 or n < 2:\n state = 0\n # Living cell survives if kernel population is equal to 2\n # Cell is revived if kernel population is equal to 3\n if (n == 2 and self.grid[x][y] == 1) or n == 3:\n state = 1\n return state\n\n def kernel(self, x, y):\n \"\"\"\n 3x3 kernel to deduce new state for point (x,y)\n\n Return sum of kernel\n \"\"\"\n k = np.zeros((3, 3), dtype=\"int32\")\n # 2D nested for loop iterates kernel it relation to point (x,y)\n for b in range(-1, 2):\n for a in range(-1, 2):\n # This if statement prevents grid wrapping by preventing negative/out-of-range indices\n if x + a >= 0 and x + a < self.w and y + b >= 0 and y + b < self.h:\n k[1 + a][1 + b] = self.grid[x + a][y + b]\n # Return sum of kernel after subtracting state of cell itself\n return np.sum(k) - self.grid[x][y]\n\n\nclass Window:\n \"\"\"\n This class contains everything needed to display the Game Of Life.\n\n Uses graphics.py\n \"\"\"\n\n def __init__(self, w, h, scale=5):\n self.w = w\n self.h = h\n self.scale = scale\n # Creates new graphic.py window with title \"Game of Life\"\n self.win = GraphWin(\"Game of Life\", self.w *\n self.scale, self.h * self.scale)\n # Set window background colour to black\n self.win.setBackground('black')\n\n def display(self, grid):\n \"\"\"\n Displays the Game of Life board\n \"\"\"\n self.clear() # Clear previous board\n for (x, y), state in np.ndenumerate(grid):\n # Check state at point (x,y)\n if state == 1:\n # If point (x,y) is alive, draw rectangle to scale\n r = Rectangle(Point(0, 0), Point(self.scale, self.scale))\n # Move each rectangle to correct position\n r.move(x * self.scale, y * self.scale)\n # Set stroke-weight and fill\n r.setWidth(1)\n r.setFill(\"white\")\n # Draw rectangle\n r.draw(self.win)\n\n def clear(self):\n \"\"\"\n Clear previous board of iterations\n \"\"\"\n # loops over all rectangles drawn in window\n for item in self.win.items[:]:\n # deletes each old rectangle\n item.undraw()\n self.win.update()\n\n\nif __name__ == \"__main__\":\n # Specify size of board (w,h) and scale of window (s)\n w, h, s = 50, 50, 10\n # Initialise new Game of Life object of size (w,h)\n gol = GOL(w, h)\n # Initialise Window object of size(w,h)\n win = Window(w, h, scale=s)\n # Populate grid with random seed\n gol.grid = gol.initRandomGrid()\n while True:\n # main while loop\n # Show Game of Life grid\n win.display(gol.grid)\n # Update Game of Life object for next iteration\n gol.update()\n","sub_path":"gol.py","file_name":"gol.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"242794690","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 1 01:34:06 2001\n\n@author: santavasquez\n\"\"\"\nfrom Weighted_Graph import *\n\ndef Prims(T):\n VG = G.vertex_set() \n i=0 \n while T[0]!= VG: \n i+=1 \n T = update_tree(G, T)\n total_cost = 0\n for e in T[1]:\n total_cost += cost(G, e)\n return(T, ' Total Cost = ', total_cost)\n \nprint(Prims(T))\n\n#def tot_c(T):\n# VG = G.vertex_set() \n# i=0 \n# while T[0]!= VG: \n# i+=1 \n# T = update_tree(G, T)\n# ttotal_cost = 0\n# for e in T[1]:\n# ttotal_cost += cost(G, e)\n# return(ttotal_cost)\n#print(tot_c(T))\n","sub_path":"Prims.py","file_name":"Prims.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"425195824","text":"\"\"\"\npghoard - compressor threads\n\nCopyright (c) 2016 Ohmu Ltd\nSee LICENSE for details\n\"\"\"\nfrom io import BytesIO\nfrom pghoard import config, wal\nfrom pghoard.common import write_json_file\nfrom pghoard.rohmu import rohmufile\nfrom queue import Empty\nfrom tempfile import NamedTemporaryFile\nfrom threading import Thread\nimport logging\nimport os\n\n\nclass CompressorThread(Thread):\n def __init__(self, config_dict, compression_queue, transfer_queue, stats):\n super().__init__()\n self.log = logging.getLogger(\"Compressor\")\n self.config = config_dict\n self.stats = stats\n self.state = {}\n self.compression_queue = compression_queue\n self.transfer_queue = transfer_queue\n self.running = True\n self.log.debug(\"Compressor initialized\")\n\n def get_compressed_file_path(self, site, filetype, original_path):\n if filetype == \"basebackup\":\n rest, _ = os.path.split(original_path)\n rest, backupname = os.path.split(rest)\n folder_for_type = \"basebackup\"\n else:\n backupname = os.path.basename(original_path)\n folder_for_type = \"xlog\"\n\n cfp = os.path.join(self.config[\"backup_location\"], self.config[\"path_prefix\"],\n site, folder_for_type, backupname)\n self.log.debug(\"compressed_file_path for %r is %r\", original_path, cfp)\n return cfp\n\n def find_site_for_file(self, filepath):\n # Formats like:\n # /home/foo/t/default/xlog/000000010000000000000014\n # /home/foo/t/default/basebackup/2015-02-06_3/base.tar\n if os.path.basename(filepath) == \"base.tar\":\n return filepath.split(\"/\")[-4]\n return filepath.split(\"/\")[-3]\n\n def compression_algorithm(self):\n return self.config[\"compression\"][\"algorithm\"]\n\n def run(self):\n while self.running:\n try:\n event = self.compression_queue.get(timeout=1.0)\n except Empty:\n continue\n\n try:\n if event[\"type\"] == \"QUIT\":\n break\n if event[\"type\"] == \"DECOMPRESSION\":\n self.handle_decompression_event(event)\n else:\n filetype = self.get_event_filetype(event)\n if not filetype:\n if \"callback_queue\" in event and event[\"callback_queue\"]:\n self.log.debug(\"Returning success for unrecognized and ignored event: %r\", event)\n event[\"callback_queue\"].put({\"success\": True, \"opaque\": event.get(\"opaque\")})\n continue\n\n self.handle_event(event, filetype)\n except Exception as ex: # pylint: disable=broad-except\n if \"blob\" in event:\n log_event = dict(event, blob=\"<{} bytes>\".format(len(event[\"blob\"])))\n else:\n log_event = event\n self.log.exception(\"Problem handling: %r: %s: %s\",\n log_event, ex.__class__.__name__, ex)\n self.stats.unexpected_exception(ex, where=\"compressor_run\")\n if \"callback_queue\" in event and event[\"callback_queue\"]:\n event[\"callback_queue\"].put({\"success\": False, \"exception\": ex, \"opaque\": event.get(\"opaque\")})\n\n self.log.debug(\"Quitting Compressor\")\n\n def get_event_filetype(self, event):\n if event[\"type\"] == \"CLOSE_WRITE\" and os.path.basename(event[\"full_path\"]) == \"base.tar\":\n return \"basebackup\"\n\n if event[\"type\"] == \"CLOSE_WRITE\" or (event[\"type\"] == \"MOVE\" and event[\"src_path\"].endswith(\".partial\")):\n if wal.XLOG_RE.match(os.path.basename(event[\"full_path\"])):\n return \"xlog\"\n if wal.TIMELINE_RE.match(os.path.basename(event[\"full_path\"])):\n return \"timeline\"\n\n return None\n\n def handle_decompression_event(self, event):\n with open(event[\"local_path\"], \"wb\") as output_obj:\n rohmufile.read_file(\n input_obj=BytesIO(event[\"blob\"]),\n output_obj=output_obj,\n metadata=event.get(\"metadata\"),\n key_lookup=config.key_lookup_for_site(self.config, event[\"site\"]),\n log_func=self.log.debug,\n )\n\n if \"callback_queue\" in event:\n event[\"callback_queue\"].put({\"success\": True, \"opaque\": event.get(\"opaque\")})\n\n def handle_event(self, event, filetype):\n # pylint: disable=redefined-variable-type\n rsa_public_key = None\n site = event.get(\"site\")\n if not site:\n site = self.find_site_for_file(event[\"full_path\"])\n\n encryption_key_id = self.config[\"backup_sites\"][site][\"encryption_key_id\"]\n if encryption_key_id:\n rsa_public_key = self.config[\"backup_sites\"][site][\"encryption_keys\"][encryption_key_id][\"public\"]\n\n compressed_blob = None\n if event.get(\"compress_to_memory\"):\n output_obj = BytesIO()\n compressed_filepath = None\n else:\n compressed_filepath = self.get_compressed_file_path(site, filetype, event[\"full_path\"])\n output_obj = NamedTemporaryFile(prefix=compressed_filepath, suffix=\".tmp-compress\")\n\n input_obj = event.get(\"input_data\")\n if not input_obj:\n input_obj = open(event[\"full_path\"], \"rb\")\n with output_obj, input_obj:\n if filetype == \"xlog\":\n wal.verify_wal(wal_name=os.path.basename(event[\"full_path\"]), fileobj=input_obj)\n\n original_file_size, compressed_file_size = rohmufile.write_file(\n input_obj=input_obj,\n output_obj=output_obj,\n compression_algorithm=self.config[\"compression\"][\"algorithm\"],\n compression_level=self.config[\"compression\"][\"level\"],\n rsa_public_key=rsa_public_key,\n log_func=self.log.info,\n )\n\n if compressed_filepath:\n os.link(output_obj.name, compressed_filepath)\n else:\n compressed_blob = output_obj.getvalue()\n\n if event.get(\"delete_file_after_compression\", True):\n os.unlink(event[\"full_path\"])\n\n metadata = event.get(\"metadata\", {})\n metadata.update({\n \"pg-version\": self.config[\"backup_sites\"][site].get(\"pg_version\"),\n \"compression-algorithm\": self.config[\"compression\"][\"algorithm\"],\n \"compression-level\": self.config[\"compression\"][\"level\"],\n \"original-file-size\": original_file_size,\n })\n if encryption_key_id:\n metadata.update({\"encryption-key-id\": encryption_key_id})\n if compressed_filepath:\n metadata_path = compressed_filepath + \".metadata\"\n write_json_file(metadata_path, metadata)\n\n self.set_state_defaults_for_site(site)\n self.state[site][filetype][\"original_data\"] += original_file_size\n self.state[site][filetype][\"compressed_data\"] += compressed_file_size\n self.state[site][filetype][\"count\"] += 1\n if original_file_size:\n size_ratio = compressed_file_size / original_file_size\n self.stats.gauge(\n \"pghoard.compressed_size_ratio\", size_ratio,\n tags={\n \"algorithm\": self.config[\"compression\"][\"algorithm\"],\n \"site\": site,\n \"type\": filetype,\n })\n transfer_object = {\n \"callback_queue\": event.get(\"callback_queue\"),\n \"file_size\": compressed_file_size,\n \"filetype\": filetype,\n \"metadata\": metadata,\n \"opaque\": event.get(\"opaque\"),\n \"site\": site,\n \"type\": \"UPLOAD\",\n }\n if compressed_filepath:\n transfer_object[\"local_path\"] = compressed_filepath\n else:\n transfer_object[\"blob\"] = compressed_blob\n transfer_object[\"local_path\"] = event[\"full_path\"]\n\n self.transfer_queue.put(transfer_object)\n return True\n\n def set_state_defaults_for_site(self, site):\n if site not in self.state:\n self.state[site] = {\n \"basebackup\": {\"original_data\": 0, \"compressed_data\": 0, \"count\": 0},\n \"xlog\": {\"original_data\": 0, \"compressed_data\": 0, \"count\": 0},\n \"timeline\": {\"original_data\": 0, \"compressed_data\": 0, \"count\": 0},\n }\n","sub_path":"pghoard/compressor.py","file_name":"compressor.py","file_ext":"py","file_size_in_byte":8516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"498759597","text":"import ply.lex as lex\nimport re\n\nWHITESPACE = re.compile(r\"\\s+\")\n\ntokens = [ 'START','EQUALS','KEY','PARAMETER','COMMA','END',\n 'VALUE','NUMBER']\n\nt_PARAMETER = r'[a-zA-Z]\\w*'\nt_EQUALS = r'='\n\ndef t_KEY(t):\n r'\\{[a-zA-Z][^,\\s]*'\n t.value = t.value[1:]\n return t\n\ndef t_NUMBER(t):\n r'=\\s*\\d+'\n t.value = int(t.value[1:].lstrip())\n return t\n\ndef t_VALUE(t):\n r'=\\s*\"[^=\"]+\"'\n t.value = WHITESPACE.sub(\" \", t.value[1:].lstrip()[1:-1].strip())\n return t\n\nt_ignore_START = r'@[a-zA-Z]+\\s*'\n\nt_ignore_COMMA = r','\n\nt_ignore_END = r'\\}'\n\nt_ignore = ' \\t\\n'\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\ndef t_error(t):\n line = t.value.lstrip()\n i = line.find(\"\\n\")\n line = line if i == -1 else line[:i]\n print(\"failed to parse line {0}: {1}\".format(t.lineno + 1, line))\n\nlex.lex()\n\nlex.input(''' @BOOK {cpp , \n author = \"Daisuke\",\n title = \"How to program in C\",\n publisher = \"Deitel\",\n year = \"2010\"}\n''')\n\nwhile True:\n tok = lex.token()\n if not tok: break\n print(tok)","sub_path":"compiler/lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"266781023","text":"_hextochr = dict()\nfor i in range(256):\n _hextochr['%02x' % i] = chr(i)\n _hextochr['%02X' % i] = chr(i)\n\ndef unquote(s):\n \"\"\"unquote('abc%20def') -> 'abc def'.\"\"\"\n res = s.split('%')\n for i in xrange(1, len(res)):\n item = res[i]\n try:\n res[i] = _hextochr[item[:2]] + item[2:]\n except KeyError:\n res[i] = '%' + item\n except UnicodeDecodeError:\n res[i] = unichr(int(item[:2], 16)) + item[2:]\n return \"\".join(res)\n","sub_path":"Twidder/venv/lib/python2.7/site-packages/pywsgi/util/unquote.py","file_name":"unquote.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"111891921","text":"\nimport pandas as pd\nimport datetime\nimport csv\nfrom fpdf import FPDF\n# def timmer():\n# my_time = 0\n# for i in range(24):\n# my_time += 1\n# print(my_time,'time')\n \n# print(my_time)\n# all_users = [{'id': 6, 'user_id': 30, 'Name': 'Shashank Kumar', 'UserName': 'zombiebaloon@gmail.com', 'status': 'pending', 'userRole': 'Active'}, {'id': 7, 'user_id': 37, 'Name': None, 'UserName': 'zombiebaloon000@gmail.com', 'status': 'Pending', 'userRole': 'Active'}, {'id': 8, 'user_id': 38, 'Name': None, 'UserName': 'zombiebaloon007@gmail.com', 'status': 'Pending', 'userRole': 'Active'}, {'id': 9, 'user_id': 39, 'Name': None, 'UserName': 'user@gmail.com', 'status': 'Pending', 'userRole': 'Active'}, {'id': 10, 'user_id': 40, 'Name': None, 'UserName': 'user2@gmail.com', 'status': 'Pending', 'userRole': 'Active'}, {'id': 11, 'user_id': 41, 'Name': None, 'UserName': 'user3@gmail.com', 'status': 'Pending', 'userRole': 'Not_Active'}]\n# if my_time >=8 and my_time <= 20:\n# for i in all_users:\n# i['userRole'] = 'Active'\n# print(i['userRole'],'working hours')\n# elif my_time > 20 or my_time < 8:\n# for i in all_users:\n# i['userRole'] = 'Not_Active'\n# print(i['userRole'],'working hours over')\n# while True:\n# time.sleep\n# timmer()\nclass PDF(FPDF):\n def header(self):\n# self.image()\n page_width = self.w - 2 * self.l_margin\n self.set_font('Times','B',14)\n self.cell(page_width,0.0,'Daily Report',align = 'C')\n self.ln(10)\n def footer(self):\n self.set_y(-15)\n self.set_font('helvetica','I',10)\n #page number\n self.cell(0,10,f'Page {self.page_no()}/{{nb}}',align= 'C')\n def body_title(self,page_title):\n self.set_font('helvetica','',12)\n p_title = f'{page_title}'\n self.cell(0,5,p_title,ln=True)\n self.ln()\n def body(self, name):\n #reading\n self.set_font('Courier','',12)\n page_width = self.w - 2 * self.l_margin\n col_width = page_width/6\n self.ln(1)\n th= self.font_size\n with open(name, newline='') as f:\n reader = csv.reader(f)\n for row in reader:\n self.cell(10,th,str(row[0]),border=1)\n self.cell(30,th,row[1],border=1)\n self.cell(28,th,row[2],border=1)\n self.cell(25,th,row[3],border=1)\n self.cell(23,th,row[4],border=1)\n self.cell(17,th,row[5],border=1)\n self.cell(30,th,row[6],border=1)\n self.cell(35,th,row[7],border=1)\n self.ln(th)\n\n self.ln(10)\n self.set_font('Times','',10.0) \n self.cell(page_width, 0.0, '- end of report -', align='C')\n \n def print_page(self,page_title,name):\n self.add_page()\n self.body_title(page_title)\n self.body(name)\n\n\n\nclass Fetch_Data:\n def raw_material(rm_data):\n RM_Data = rm_data\n id_list = []\n register_id = []\n Date =[]\n RM_thickness=[]\n RM_Size = []\n RM_Grade = []\n RM_coilweight = []\n RM_Scrapweight = []\n for i in RM_Data.values():\n id_list.append(i['id'])\n register_id.append(i['register_id'])\n Date.append(i['RM_Date'])\n RM_thickness.append(i['RM_Thickness'])\n RM_Grade.append(i['RM_Grade'])\n RM_Size.append(i['RM_Size'])\n RM_coilweight.append(i['RM_coilWeight'])\n RM_Scrapweight.append(i['RM_scrapWeight'])\n Raw_dic = {\n 'id': id_list,\n 'register id': register_id,\n 'Date':Date,\n 'Thickness': RM_thickness,\n 'Grade': RM_Grade,\n 'Size': RM_Size,\n 'Weight': RM_coilweight,\n 'ScrapeWeight': RM_Scrapweight\n }\n return Raw_dic\n def EssentialitemUserperDay(es_data):\n Date = []\n ES_Data = es_data\n # FM_dic = FM_Data.values()\n es_id = []\n Register_id = []\n Type = []\n Size = []\n EPD_uid = []\n Quantity = []\n\n for i in ES_Data.values():\n es_id.append(i['id'])\n Type.append(i['EPD_Type'])\n Date.append(i['EPD_Date'])\n Register_id.append(i['register_id'])\n EPD_uid.append(i['EPD_UID_id'])\n Size.append(i['EPD_Size'])\n Quantity.append(i['EPD_Quantity'])\n ES_dic = {\n 'extra': 0,\n 'id': es_id,\n 'Item Stock id': EPD_uid,\n 'Date': Date,\n 'Register':Register_id,\n 'Type': Type,\n 'Size':Size,\n 'Quantity': Quantity,\n }\n return ES_dic\n\n\n # def fm_stock(fm_data):\n # Date = []\n # FM_Data = fm_data\n # # FM_dic = FM_Data.values()\n # FM_id = []\n # Register_id = []\n # CoilUID = []\n # Size = []\n # Grade = []\n # CoilWeight = []\n # MaterialType = []\n # FM_Thickness = []\n # FM_Size = []\n # FM_Weight = []\n # FM_Quantity = []\n # FM_scrapWeight = []\n # UF_Thickness = []\n # UF_Size = [] \n # UF_Weight = []\n # UF_Quantity = []\n\n # for i in FM_Data.values():\n # FM_id.append(i['id'])\n # Date.append(i['FM_Date'])\n # Register_id.append(i['register_id'])\n # CoilUID.append(i['coilUID_id'])\n # Size.append(i['Size'])\n # Grade.append(i['Grade'])\n # CoilWeight.append(i['coilWeight'])\n # MaterialType.append(i['materialType'])\n # FM_Thickness.append(i['FM_Thickness'])\n # FM_Size.append(i['FM_Size'])\n # FM_Weight.append(i['FM_Weight'])\n # FM_Quantity.append(i['FM_Quantity'])\n # FM_scrapWeight.append(i['FM_scrapWeight'])\n # UF_Thickness.append(i['UF_Thickness'])\n # UF_Size.append(i['UF_Size'])\n # UF_Weight.append(i['UF_Weight'])\n # UF_Quantity.append(i['UF_Quantity'])\n # FM_dic = {\n # 'id': FM_id,\n # 'Date': Date,\n # 'Register':Register_id,\n # 'Coil': CoilUID,\n # 'Size':Size,\n # 'Grade':Grade,\n # 'Weight': CoilWeight,\n # 'Material Type': MaterialType,\n # 'FM Thickness': FM_Thickness,\n # 'FM Size': FM_Size,\n # 'FM Quant': FM_Quantity,\n # 'FM ScrapW': FM_scrapWeight,\n # 'UF Thickness': UF_Thickness,\n # 'UF Size': UF_Size,\n # 'UF Weight':UF_Weight,\n # 'UF Quan': UF_Quantity\n # }\n # return FM_dic\n","sub_path":"apex/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"63610073","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 5 23:15:03 2019\n\n@author: ASUS\n\"\"\"\n\nimport pandas as pd\nimport tushare as tu\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport datetime\n\n#买卖函数\ndef buy(code,money,day):\n global total\n global handle\n global cost\n global df\n global handles\n \n str(code)\n str(day)\n data=tu.get_hist_data(code,day,day)\n buy_price=float(data['open'])\n cost = money/buy_price\n handles = handles+cost\n handle = {code:handles*buy_price}\n total = total - money\n print('buy',buy_price)\n print('handle',handle[code])\n print('total',total)\n print('final',total+handle[code])\n return buy_price \n \ndef sell(code,percent,day):\n global total\n global handle\n global cost\n global df\n global handles\n \n str(code)\n str(day)\n data=tu.get_hist_data(code,day,day)\n sell_price=float(data['close'])\n handle = {code:handles*(1-percent)*sell_price}\n total = total + sell_price*handles*percent\n handles = handles*(1-percent)\n print('sell',sell_price)\n print('handle',handle[code])\n print('total',total)\n print('final',total+handle[code])\n return sell_price\n \n \ntotal = 100\nbuy_money = total*0.1\nsell_percent = 1\n\ncode = '000001'\n\n#draw = pd.DataFrame()\nbuydata = pd.DataFrame()\nselldata = pd.DataFrame()\nflag = 0\nbuyp = []\nsellp = []\nbuyt = []\nsellt = []\nhandle = pd.DataFrame() \n\ni = 0\nflag = 'out'\nhandles = 0\nfil = []\nkey=1\n\n\nscore_input = pd.DataFrame()\nscort_hs300s = pd.DataFrame()\n\nyear = 2017\nseason = 4\n\nprofit = tu.get_profit_data(year,season)\ngrowth = tu.get_growth_data(year,season)\ntoday = tu.get_today_all()\ncodelist = tu.get_hs300s()\n\n\nprofit = profit.sort_values('code')\ngrowth = growth.sort_values('code')\ntoday = today.sort_values('code')\n\nprofit = profit.set_index('code')\ngrowth = growth.set_index('code')\ntoday = today.set_index('code')\ngrowth = growth.drop(['name'],axis=1)\ntoday = today.drop(['name'],axis=1)\n\nprofit = profit.join(growth,how='inner')\nprofit = profit.join(today,how='inner')\nprofit = profit.reset_index()\n\nscore_input['code']= profit['code']\nscore_input['pb']= profit['pb']\nscore_input['roe'] = profit['roe']\nscore_input['gross_profit_rate'] = profit['gross_profit_rate']\nscore_input['mbrg'] = profit['mbrg']\nscore_input['nprg'] = profit['nprg']\nscore_input['nav'] = profit['nav']\nscore_input['targ'] = profit['targ']\n\nscore_input['hs300'] = score_input['code'].isin(codelist['code'])\nscore_input = score_input[score_input['hs300']>0]\nscore_input = score_input[score_input['pb']>0]\n\nm = score_input.iloc[:,2:9] > 0\nn = score_input.iloc[:,2:9] <= 0 \nscore_input.iloc[:,2:9] = score_input.iloc[:,2:9].where(m,1)\nscore_input.iloc[:,2:9] = score_input.iloc[:,2:9].where(n,0) \nscore_input['score'] = score_input.iloc[:,2:9].sum(axis=1)\nscore_input = score_input.sort_values(by=['score', 'pb'])\nscore_input.drop(score_input[score_input['pb']<1].index,inplace=True)\ncodes = score_input['code']\n\n\n#交易逻辑\nk = 0\nday_start = '2018-12-01'\nday_end = '2019-10-26'\nhandle = {code:0}\nbias = 0\n\ndef get_datas(code,day_start,day_end):\n data=tu.get_hist_data(code,day_start,day_end)\n data = data.sort_index()\n truerange = []\n maxdata = []\n mindata = []\n high=data['high']\n low=data['low']\n close=data['close']\n index = 0\n \n for item in data.index:\n tr = max(high[index-1]-low[index-1],high[index]-close[index],close[index]-low[index])\n truerange.append(tr)\n trueranges = pd.DataFrame(data=truerange)\n peranges = trueranges.rolling(window=5,center=False).mean()\n if index<21:\n maxd = max(close[0:index+1])\n mind = min(close[0:index+1])\n else: \n maxd = max(close[index-20:index])\n mind = min(close[index-20:index])\n maxdata.append(maxd)\n mindata.append(mind)\n index = index+1\n #print(perange)\n return peranges,data,maxdata,mindata\n\nperanges,data,maxdata,mindata = get_datas(codes.iloc[k+bias],day_start,day_end)\nfor item in data.index:\n final = total+handle[code]\n uint = float(abs(final*0.01/peranges.loc[i]))\n if data.loc[item,'close'] > maxdata[i] and flag == 'out':\n buy_money = total*0.7\n bp = buy(codes.iloc[k+bias],buy_money,item) \n buyp.append(bp)\n buyt.append(item)\n flag = 1\n flag = 'in0'\n if data.loc[item,'close'] < mindata[i] and flag != 'out':\n sell_percent = 1\n sp=sell(codes.iloc[k+bias],sell_percent,item)\n sellp.append(sp)\n sellt.append(item)\n flag = 'out'\n key = 1\n\n \n \n if data.loc[item,'p_change'] > float(peranges.loc[i]) and flag == 'in0' :\n buy_money = uint\n bp = buy(codes.iloc[k+bias],buy_money,item) \n key = key+1\n if key >5:\n flag = 'in1'\n print('d')\n buyp.append(bp)\n buyt.append(item)\n \n if data.loc[item,'p_change'] < float(-peranges.loc[i]) and flag != 'out':\n sell_percent = 1\n sp=sell(codes.iloc[k+bias],sell_percent,item)\n sellp.append(sp)\n sellt.append(item)\n flag = 'out'\n key = 1\n if flag == 'out':\n k =0\n while 1:\n print('while',k)\n k=k+1\n try:\n peranges,data,maxdata,mindata = get_datas(codes.iloc[k+bias],day_start,day_end)\n if data.loc[item,'close'] > maxdata[i] or k>10:\n print('break',item)\n break\n except TypeError:\n print('TypeError')\n continue\n except KeyError:\n print('KeyError')\n continue\n \n handle = {code:handles*data.loc[item,'close']} \n final = total+handle[code]\n i = i+1\n fil.append(total+handle[code]-100)\n \n#数据整理与绘图\ndata_test = {'buy_price':buyp,'sellprice':sellp}\ndraw = data['close']\nbuydata['data'] = buyt\nbuydata['price'] = buyp\nselldata['data'] = sellt\nselldata['price'] = sellp\n\ndatab_list = []\nfor i in buydata['data']: \n dateb_time = datetime.datetime.strptime(i,'%Y-%m-%d')\n t = matplotlib.dates.date2num(dateb_time)\n datab_list.append(t)\nbuydata['data'] = datab_list\n\ndatas_list = []\nfor i in selldata['data']: \n dates_time = datetime.datetime.strptime(i,'%Y-%m-%d')\n t = matplotlib.dates.date2num(dates_time)\n datas_list.append(t)\nselldata['data'] = datas_list\n\ndraw = draw.reset_index()\ndraw_list = []\nfor i in draw['date']: \n dates_time = datetime.datetime.strptime(i,'%Y-%m-%d')\n t = matplotlib.dates.date2num(dates_time)\n draw_list.append(t)\ndraw['date'] = draw_list\nopr = plt.subplot2grid((2,1), (0,0))\nres = plt.subplot2grid((2,1), (1,0))\n\n\nopr.plot(buydata['data'],buydata['price'],'bo')\nopr.plot(selldata['data'],selldata['price'],'bo',color='red')\nopr.plot(draw['date'],draw['close'])\nres.plot(fil)\n\n\n","sub_path":"turtle.py","file_name":"turtle.py","file_ext":"py","file_size_in_byte":6858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"574460003","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n超音波距離センサモジュール HC-SR04(SparkFun販売品)\nhttps://www.switch-science.com/catalog/2860/\n\n- 仕様\n - 電源電圧: 5 V\n - 待機電流: 2 mA未満\n - 信号出力: 0~5 V\n - センサ角度: 15 度以下\n - 測定可能距離: 2~400 cm\n 分解能: 0.3 cm\n 端子間隔: 2.54 mm\n\n- 使い方\n - トリガ端子を10 us以上Highにしてください。\n - このセンサモジュールが40 kHzのパルスを8回送信して受信します。\n - 受信すると、出力端子がHighになります。\n - 出力端子がHighになっている時間がパルスを送信してから受信するまでの時間です。\n - 出力端子がHighになっている時間の半分を音速で割った数値が距離です。\n\n\"\"\"\nimport time\n\nimport pigpio\n\nLONGEST_TIME = 20000\n\nclass Driver:\n \"\"\"\n このクラスは一種の音響距離計測器をカプセル化します。\n 特に別々のトリガーとエコーピンを持つ距離計測のタイプをさします。\n\n トリガーのパルスがソナーのpingを開始し、\n その直後にソナーのパルスが送信され、\n エコーピンがハイになります。\n エコーピンは、ソナーエコーが受信されるまで\n (または応答がタイムアウトするまで)ハイのままです。\n ハイエッジとローエッジの間の時間は、ソナーの往復時間を示します。\n \"\"\"\n\n def __init__(self, pi, trigger, echo):\n \"\"\"\n 使用するPiオブジェクト、トリガGPIO番号およびエコーGPIO番号を受け取ります。\n 引数\n pi gpio.piオブジェクト\n trigger Trigピンが接続されているGPIO番号\n echo Echoピンが接続されているGPIO番号\n 戻り値\n なし\n \"\"\"\n # インスタンス変数初期化\n self.pi = pi\n self._trig = trigger\n self._echo = echo\n\n # ソナーがping中であるかどうか\n self._ping = False\n # Echoピンがハイになった時刻(マイクロ秒)\n self._high = None\n # Echoピンがハイになっていた時刻\n self._time = None\n\n # トリガされているかどうか\n self._triggered = False\n\n # 開始前の各GPIOの状態を保管\n self._trig_mode = pi.get_mode(self._trig)\n self._echo_mode = pi.get_mode(self._echo)\n\n # GPIO初期化\n pi.set_mode(self._trig, pigpio.OUTPUT)\n pi.set_mode(self._echo, pigpio.INPUT)\n\n # Trigピンにコールバ��ク関数をセット\n self._cb = pi.callback(self._trig, pigpio.EITHER_EDGE, self._cbf)\n # Echoピンにコールバック関数をセット\n self._cb = pi.callback(self._echo, pigpio.EITHER_EDGE, self._cbf)\n\n # 初期化したかどうか\n self._inited = True\n\n def _cbf(self, gpio, level, tick):\n \"\"\"\n コールバック関数\n 引数\n gpio 0〜31 状態が変化したGPIO番号\n level 0〜2 0 =ローに変化(立ち下がりエッジ)\n 1 =ハイに変化(立ち上がりエッジ)\n 2 =レベル変更なし(ウォッチドッグタイムアウト)\n tick 32bit 起動後のマイクロ秒数\n                   警告:これはおよそ72分ごとに4294967295から0に折り返される\n \"\"\"\n # Trigピンの場合\n if gpio == self._trig:\n # トリガPinがハイ=トリガ送信済みの場合\n if level == 0:\n # 送信済み状態にする\n self._triggered = True\n # Echoピンがハイになった現在時刻を削除\n self._high = None\n # Echo ピンの場合\n else:\n # トリガ送信済みの場合\n if self._triggered:\n # Echoピンがハイになった場合\n if level == 1:\n # Echoピンがハイになった現在時刻(マイクロ秒)を保管\n self._high = tick\n # Echoピン変化なしもしくはローになったとき\n else:\n # 現在時刻が保管されている場合\n if self._high is not None:\n # Echoピンがハイになっていた時間(マイクロ秒)を計算\n self._time = tick - self._high\n # Echoピンがハイになった現在時刻を削除\n self._high = None\n # Echoピンによる時間計測した状態にする\n self._ping = True\n\n def read(self):\n \"\"\"\n 読み取りを開始する。 \n 返される読み取り値は、ソナーの往復のマイクロ秒数となる。\n 往復cms =往復時間/ 1000000.0 * 34030\n 引数\n なし\n 戻り値\n distance cm 距離\n Noneの場合はタイムアウトもしくは計測不能\n \"\"\"\n # 初期化済みの場合\n if self._inited:\n # Echoピンによる時間計測していない状態にする\n self._ping = False\n # Trigピンにトリガ信号を送信\n self.pi.gpio_trigger(self._trig, 11, pigpio.HIGH)\n # Trigピンにトリガ信号を送信した時刻を保管\n start = time.time()\n # Echoピンによる時間計測が終わるまでループ\n while not self._ping:\n # 5秒以上待機した場合\n if (time.time()-start) > 5.0:\n return duration_to_distance(LONGEST_TIME)\n # 1ミリ秒待機\n time.sleep(0.001)\n # Echoピンがハイになっていた時間を返却\n return duration_to_distance(self._time)\n else:\n return None\n\n def cancel(self):\n \"\"\"\n 距離計測をキャンセルしてgpiosを元のモードに戻す。\n 引数\n なし\n 戻り値\n なし\n \"\"\"\n if self._inited:\n # 初期化前の状態にする\n self._inited = False\n # コールバック関数の解除\n self._cb.cancel()\n # 初期化前に保管していた状態に戻す\n self.pi.set_mode(self._trig, self._trig_mode)\n self.pi.set_mode(self._echo, self._echo_mode)\n\ndef duration_to_distance(duration):\n \"\"\"\n Echoピンがハイになっていた時間を距離に変換する。\n 引数\n duration Echoピンがハイになっていた時間 (マイクロ秒)\n 戻り値\n distance 距離 (cm)\n Noneの場合はタイムアウトもしくは計測不能\n \"\"\"\n if duration is None or duration < 0 or duration == LONGEST_TIME:\n return None\n else:\n # 往復距離なので2で割り、音速で割って距離化(cm)\n return (duration / 2.0) * 340.0 * 100.0 / 1000000.0\n\nif __name__ == \"__main__\":\n import time\n import pigpio\n RANGE_TRIG_GPIO = 5\n RANGE_ECHO_GPIO = 6\n RANGE_GPIOS = [\n RANGE_TRIG_GPIO,\n RANGE_ECHO_GPIO\n ]\n pi = pigpio.pi()\n sonar = Driver(pi, RANGE_GPIOS[0], RANGE_GPIOS[1])\n\n end = time.time() + 600.0\n\n r = 1\n while time.time() < end:\n\n print(\"{} {}\".format(r, sonar.read()))\n r += 1\n time.sleep(0.03)\n\n sonar.cancel()\n\n pi.stop()\n","sub_path":"donkeypart_sonicrangesensor/hc_sr04.py","file_name":"hc_sr04.py","file_ext":"py","file_size_in_byte":7759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"146410284","text":"# Copyright 2009-2023 NTESS. Under the terms\n# of Contract DE-NA0003525 with NTESS, the U.S.\n# Government retains certain rights in this software.\n#\n# Copyright (c) 2009-2023, NTESS\n# All rights reserved.\n#\n# This file is part of the SST software package. For license\n# information, see the LICENSE file in the top level directory of the\n# distribution.\nimport sst\nimport inspect, os, sys\n\n\nparams = dict({\n # Set filename to the name of this file\n \"filename\" : inspect.getfile(inspect.currentframe())\n })\n\nfor i in range(10):\n comp = sst.Component(\"Table Comp %d\"%i, \"coreTestElement.simpleLookupTableComponent\")\n comp.addParams(params)\n\n","sub_path":"tests/test_LookupTable.py","file_name":"test_LookupTable.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"20061500","text":"class Solution(object):\n def isValidSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: bool\n \"\"\"\n for j in range(9):#horize\n for i in range(1,10):\n if board[j].count(str(i))>=2:\n return False\n num_list=[]\n for j in range(9):#vertical\n for i in range(9):\n print(i,j)\n if (board[i][j] not in num_list) and board[i][j]!='.':\n num_list.append(board[i][j])\n else:\n return False\n print(\"x\") \n for block in range(9):\n x_block=block%3#0,1,2\n y_block=block//3#0,1,2\n num_list=[]\n for i in range(y_block*3,(y_block+1)*3):\n for j in range(x_block*3,(x_block+1)*3):\n if board[i][j] not in num_list:\n num_list.append(board[i][j])\n elif board[i][j]=='.':\n continue\n else:\n return False\n \n return True \n \ns=Solution()\nprint(s.isValidSudoku([\".87654321\",\"2........\",\"3........\",\"4........\",\"5........\",\"6........\",\"7........\",\"8........\",\"9........\"])) \n \n ","sub_path":"exercise/leetcode/python_src/by2017_Sep/Leet036.py","file_name":"Leet036.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"331851576","text":"from pcraster import *\r\ndem = readmap(\"dem.map\")\r\nGradx = gradx(dem);\r\nreport(Gradx, \"gradx.map\")\r\nGrady = grady(dem);\r\nreport(Grady, \"grady.map\")\r\nLax = lax(dem, 0.5);\r\nreport(Lax, \"lax.map\")\r\nLaplacian = laplacian(dem);\r\nreport(Laplacian, \"laplacian.map\")\r\nDivergence = divergence(Gradx, Grady);\r\nreport(Divergence, \"divergence.map\")\r\nDiver = diver(Gradx, Grady, spatial(scalar(1)), spatial(scalar(1)));\r\nreport(Diver, \"diver.map\")\r\n","sub_path":"pcraster_demo_data-20131204/example/vector/AllFunctions.py","file_name":"AllFunctions.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"338315139","text":"import numpy as np \nimport scipy, h5py\nimport tables\nimport sys\nfrom scipy.optimize import minimize\nfrom numpy.polynomial import legendre as LG\nimport matplotlib.pyplot as plt\n\ndef Calib(theta, *args):\n ChannelID, flight_time, PMT_pos, cut, LegendreCoeff = args\n y = flight_time\n T_i = np.dot(LegendreCoeff, theta)\n # quantile regression\n # quantile = 0.01\n L0 = Likelihood_quantile(y, T_i, 0.01, 0.3)\n # L = L0\n L = L0 + np.sum(np.abs(theta))\n return L\n\ndef Likelihood_quantile(y, T_i, tau, ts):\n less = T_i[y=T_i] - T_i[y>=T_i]\n R = (1-tau)*np.sum(less) + tau*np.sum(more)\n #log_Likelihood = exp\n return R\n\ndef Legendre_coeff(PMT_pos, vertex, cut):\n size = np.size(PMT_pos[:,0])\n if(np.sum(vertex**2) > 1e-6):\n cos_theta = np.sum(vertex*PMT_pos,axis=1) \\\n /np.sqrt(np.sum(vertex**2)*np.sum(PMT_pos**2,axis=1))\n else:\n cos_theta = np.ones(size)\n x = np.zeros((size, cut))\n # legendre coeff\n for i in np.arange(0, cut):\n c = np.zeros(cut)\n c[i] = 1\n x[:,i] = LG.legval(cos_theta,c)\n return x \n\ndef hessian(x, *args):\n ChannelID, PETime, PMT_pos, cut, LegendreCoeff = args\n H = np.zeros((len(x),len(x)))\n h = 1e-3\n k = 1e-3\n for i in np.arange(len(x)):\n for j in np.arange(len(x)):\n if (i != j):\n delta1 = np.zeros(len(x))\n delta1[i] = h\n delta1[j] = k\n delta2 = np.zeros(len(x))\n delta2[i] = -h\n delta2[j] = k\n\n\n L1 = - Calib(x + delta1, *(total_pe, PMT_pos, cut, LegendreCoeff))\n L2 = - Calib(x - delta1, *(total_pe, PMT_pos, cut, LegendreCoeff))\n L3 = - Calib(x + delta2, *(total_pe, PMT_pos, cut, LegendreCoeff))\n L4 = - Calib(x - delta2, *(total_pe, PMT_pos, cut, LegendreCoeff))\n H[i,j] = (L1+L2-L3-L4)/(4*h*k)\n else:\n delta = np.zeros(len(x))\n delta[i] = h\n L1 = - Calib(x + delta, *(total_pe, PMT_pos, cut, LegendreCoeff))\n L2 = - Calib(x - delta, *(total_pe, PMT_pos, cut, LegendreCoeff))\n L3 = - Calib(x, *(total_pe, PMT_pos, cut, LegendreCoeff))\n H[i,j] = (L1+L2-2*L3)/h**2 \n return H\n\ndef readfile(filename):\n# read files by table\n h1 = tables.open_file(filename,'r')\n print(filename)\n truthtable = h1.root.GroundTruth\n EventID = truthtable[:]['EventID']\n ChannelID = truthtable[:]['ChannelID']\n PETime = truthtable[:]['PETime']\n photonTime = truthtable[:]['photonTime']\n PulseTime = truthtable[:]['PulseTime']\n dETime = truthtable[:]['dETime']\n \n x = h1.root.TruthData[:]['x']\n y = h1.root.TruthData[:]['y']\n z = h1.root.TruthData[:]['z']\n \n h1.close()\n \n dn = np.where((x==0) & (y==0) & (z==0))\n dn_index = (x==0) & (y==0) & (z==0)\n pin = dn[0] + np.min(EventID)\n if(np.sum(x**2+y**2+z**2>0.1)>0):\n cnt = 0 \n for ID in np.arange(np.min(EventID), np.max(EventID)+1):\n if ID in pin:\n cnt = cnt+1\n #print('Trigger No:', EventID[EventID==ID])\n #print('Fired PMT', ChannelID[EventID==ID])\n \n ChannelID = ChannelID[~(EventID == ID)]\n PETime = PETime[~(EventID == ID)]\n photonTime = photonTime[~(EventID == ID)]\n PulseTime = PulseTime[~(EventID == ID)]\n dETime = dETime[~(EventID == ID)]\n EventID = EventID[~(EventID == ID)]\n \n x = x[~dn_index]\n y = y[~dn_index]\n z = z[~dn_index]\n \n return (EventID, ChannelID, PETime, photonTime, PulseTime, dETime, x, y, z)\n\ndef readchain(radius, path, axis):\n for i in np.arange(0,5):\n if(i == 0):\n #filename = path + '1t_' + radius + '.h5'\n filename = '%s1t_%s_%s.h5' % (path, radius, axis)\n EventID, ChannelID, PETime, photonTime, PulseTime, dETime, x, y, z = readfile(filename)\n else:\n try:\n filename = '%s1t_%s_%s_%d.h5' % (path, radius, axis, i)\n EventID1, ChannelID1, PETime1, photonTime1, PulseTime1, dETime1, x1, y1, z1 = readfile(filename)\n EventID = np.hstack((EventID, EventID1))\n ChannelID = np.hstack((ChannelID, ChannelID1))\n PETime = np.hstack((PETime,PETime1))\n photonTime = np.hstack((photonTime, photonTime1))\n PulseTime = np.hstack((PulseTime, PulseTime1))\n dETime = np.hstack((dETime, dETime1))\n x = np.hstack((x, x1))\n y = np.hstack((y, y1))\n z = np.hstack((z, z1))\n except:\n pass\n return EventID, ChannelID, PETime, photonTime, PulseTime, dETime, x, y, z\n\ndef main_Calib(radius, path, fout, cut_max):\n #filename = '/mnt/stage/douwei/Simulation/1t_root/1.5MeV_015/1t_' + radius + '.h5' \n with h5py.File(fout,'w') as out:\n # read files by table\n if(eval(radius) != 0.00):\n EventIDx, ChannelIDx1, PETimex, photonTimex, PulseTimex, dETimex, xx, yx, zx = readchain('+' + radius, path, 'x')\n EventIDy, ChannelIDy1, PETimey, photonTimey, PulseTimey, dETimey, xy, yy, zy = readchain('+' + radius, path, 'y')\n EventIDz, ChannelIDz1, PETimez, photonTimez, PulseTimez, dETimez, xz, yz, zz = readchain('+' + radius, path, 'z')\n\n EventIDy = EventIDy + np.max(EventIDx)\n EventIDz = EventIDz + np.max(EventIDy)\n\n x1 = np.array((xx[0], yx[0], xz[0]))\n y1 = np.array((xy[0], yy[0], zy[0]))\n z1 = np.array((xz[0], yz[0], zz[0])) \n\n # dark noise (np.unique EventID should not change since the pure trigger by dark noise has been filtered!)\n flight_timex = PulseTimex - dETimex \n EventIDx = EventIDx[~(flight_timex==0)]\n ChannelIDx1 = ChannelIDx1[~(flight_timex==0)]\n flight_timex = flight_timex[~(flight_timex==0)]\n\n flight_timey = PulseTimey - dETimey \n EventIDy = EventIDy[~(flight_timey==0)]\n ChannelIDy1 = ChannelIDy1[~(flight_timey==0)]\n flight_timey = flight_timey[~(flight_timey==0)]\n\n flight_timez = PulseTimez - dETimez \n EventIDz = EventIDz[~(flight_timez==0)]\n ChannelIDz1 = ChannelIDz1[~(flight_timez==0)]\n flight_timez = flight_timez[~(flight_timez==0)]\n\n EventID1 = np.hstack((EventIDx, EventIDy, EventIDz))\n ChannelID1 = np.hstack((ChannelIDx1, ChannelIDy1, ChannelIDz1))\n PETime1 = np.hstack((PETimex, PETimey, PETimez))\n photonTime1 = np.hstack((photonTimex, photonTimey, photonTimez))\n PulseTime1 = np.hstack((PulseTimex, PulseTimey, PulseTimez))\n dETime1 = np.hstack((dETimex, dETimey, dETimez))\n flight_time1 = np.hstack((flight_timex, flight_timey, flight_timez))\n\n # read files by table\n EventIDx, ChannelIDx2, PETimex, photonTimex, PulseTimex, dETimex, xx, yx, zx = readchain('-' + radius, path, 'x')\n EventIDy, ChannelIDy2, PETimey, photonTimey, PulseTimey, dETimey, xy, yy, zy = readchain('-' + radius, path, 'y')\n EventIDz, ChannelIDz2, PETimez, photonTimez, PulseTimez, dETimez, xz, yz, zz = readchain('-' + radius, path, 'z')\n\n EventIDy = EventIDy + np.max(EventIDx)\n EventIDz = EventIDz + np.max(EventIDy)\n\n x2 = np.array((xx[0], yx[0], xz[0]))\n y2 = np.array((xy[0], yy[0], zy[0]))\n z2 = np.array((xz[0], yz[0], zz[0])) \n\n # dark noise (np.unique EventID should not change since the pure trigger by dark noise has been filtered!)\n flight_timex = PulseTimex - dETimex \n EventIDx = EventIDx[~(flight_timex==0)]\n ChannelIDx2 = ChannelIDx2[~(flight_timex==0)]\n flight_timex = flight_timex[~(flight_timex==0)]\n\n flight_timey = PulseTimey - dETimey \n EventIDy = EventIDy[~(flight_timey==0)]\n ChannelIDy2 = ChannelIDy2[~(flight_timey==0)]\n flight_timey = flight_timey[~(flight_timey==0)]\n\n flight_timez = PulseTimez - dETimez \n EventIDz = EventIDz[~(flight_timez==0)]\n ChannelIDz2 = ChannelIDz2[~(flight_timez==0)]\n flight_timez = flight_timez[~(flight_timez==0)]\n\n EventID2 = np.hstack((EventIDx, EventIDy, EventIDz))\n ChannelID2 = np.hstack((ChannelIDx2, ChannelIDy2, ChannelIDz2))\n PETime2 = np.hstack((PETimex, PETimey, PETimez))\n photonTime2 = np.hstack((photonTimex, photonTimey, photonTimez))\n PulseTime2 = np.hstack((PulseTimex, PulseTimey, PulseTimez))\n dETime2 = np.hstack((dETimex, dETimey, dETimez))\n flight_time2 = np.hstack((flight_timex, flight_timey, flight_timez))\n\n x = np.hstack((xx, xy, xz))\n y = np.hstack((yx, yy, yz))\n z = np.hstack((xz, yz, zz))\n \n EventID = np.hstack((EventID1, EventID2))\n ChannelID = np.hstack((ChannelID1, ChannelID2))\n PETime = np.hstack((PETime1, PETime2))\n photonTime = np.hstack((photonTime1, photonTime2))\n PulseTime = np.hstack((PulseTime1, PulseTime2))\n dETime = np.hstack((dETime1, dETime2))\n flight_time = np.hstack((flight_time1, flight_time2))\n \n print('begin processing legendre coeff')\n # this part for the same vertex\n tmp_x_p = Legendre_coeff(PMT_pos,x1/1e3, cut_max)\n tmp_x_p = tmp_x_p[ChannelIDx1]\n tmp_y_p = Legendre_coeff(PMT_pos,y1/1e3, cut_max)\n tmp_y_p = tmp_y_p[ChannelIDy1]\n tmp_z_p = Legendre_coeff(PMT_pos,z1/1e3, cut_max)\n tmp_z_p = tmp_z_p[ChannelIDz1] \n tmp_x_n = Legendre_coeff(PMT_pos,x2/1e3, cut_max)\n tmp_x_n = tmp_x_n[ChannelIDx2]\n tmp_y_n = Legendre_coeff(PMT_pos,y2/1e3, cut_max)\n tmp_y_n = tmp_y_n[ChannelIDy2]\n tmp_z_n = Legendre_coeff(PMT_pos,z2/1e3, cut_max)\n tmp_z_n = tmp_z_n[ChannelIDz2]\n LegendreCoeff = np.vstack((tmp_x_p, tmp_y_p, tmp_z_p,tmp_x_n, tmp_y_n, tmp_z_n))\n else:\n EventIDx, ChannelIDx1, PETimex, photonTimex, PulseTimex, dETimex, xx, yx, zx = readchain('-' + radius, path, 'x')\n EventIDy, ChannelIDy1, PETimey, photonTimey, PulseTimey, dETimey, xy, yy, zy = readchain('-' + radius, path, 'y')\n EventIDz, ChannelIDz1, PETimez, photonTimez, PulseTimez, dETimez, xz, yz, zz = readchain('-' + radius, path, 'z')\n\n EventIDy = EventIDy + np.max(EventIDx)\n EventIDz = EventIDz + np.max(EventIDy)\n\n x1 = np.array((xx[0], yx[0], xz[0]))\n y1 = np.array((xy[0], yy[0], zy[0]))\n z1 = np.array((xz[0], yz[0], zz[0])) \n\n # dark noise (np.unique EventID should not change since the pure trigger by dark noise has been filtered!)\n flight_timex = PulseTimex - dETimex \n EventIDx = EventIDx[~(flight_timex==0)]\n ChannelIDx1 = ChannelIDx1[~(flight_timex==0)]\n flight_timex = flight_timex[~(flight_timex==0)]\n\n flight_timey = PulseTimey - dETimey \n EventIDy = EventIDy[~(flight_timey==0)]\n ChannelIDy1 = ChannelIDy1[~(flight_timey==0)]\n flight_timey = flight_timey[~(flight_timey==0)]\n\n flight_timez = PulseTimez - dETimez \n EventIDz = EventIDz[~(flight_timez==0)]\n ChannelIDz1 = ChannelIDz1[~(flight_timez==0)]\n flight_timez = flight_timez[~(flight_timez==0)]\n\n EventID1 = np.hstack((EventIDx, EventIDy, EventIDz))\n ChannelID1 = np.hstack((ChannelIDx1, ChannelIDy1, ChannelIDz1))\n PETime1 = np.hstack((PETimex, PETimey, PETimez))\n photonTime1 = np.hstack((photonTimex, photonTimey, photonTimez))\n PulseTime1 = np.hstack((PulseTimex, PulseTimey, PulseTimez))\n dETime1 = np.hstack((dETimex, dETimey, dETimez))\n flight_time1 = np.hstack((flight_timex, flight_timey, flight_timez))\n \n EventID = EventID1\n ChannelID = ChannelID1\n PETime = PETime1\n photonTime = photonTime1\n PulseTime = PulseTime1\n dETime = dETime1\n flight_time = flight_time1\n\n print('begin processing legendre coeff')\n # this part for the same vertex\n tmp_x_p = Legendre_coeff(PMT_pos,x1/1e3, cut_max)\n tmp_x_p = tmp_x_p[ChannelIDx1]\n tmp_y_p = Legendre_coeff(PMT_pos,y1/1e3, cut_max)\n tmp_y_p = tmp_y_p[ChannelIDy1]\n tmp_z_p = Legendre_coeff(PMT_pos,z1/1e3, cut_max)\n tmp_z_p = tmp_z_p[ChannelIDz1]\n LegendreCoeff = np.vstack((tmp_x_p, tmp_y_p, tmp_z_p))\n \n print(ChannelID.shape, LegendreCoeff.shape)\n # this part for EM\n '''\n LegendreCoeff = np.zeros((0,cut_max))\n for k_index, k in enumerate(np.unique(EventID)):\n tmp = Legendre_coeff(PMT_pos,np.array((x[k_index], y[k_index], z[k_index]))/1e3, cut_max)\n single_index = ChannelID[EventID==k]\n LegendreCoeff = np.vstack((LegendreCoeff,tmp[single_index]))\n '''\n print('finish calc coeff')\n \n for cut in np.arange(5,cut_max + 5,5):\n\n theta0 = np.zeros(cut) # initial value\n theta0[0] = np.mean(flight_time) - 26\n result = minimize(Calib,theta0, method='SLSQP',args = (ChannelID, flight_time, PMT_pos, cut, LegendreCoeff[:,0:cut])) \n record = np.array(result.x, dtype=float)\n print(result.x)\n \n out.create_dataset('coeff' + str(cut), data = record)\n\n\nf = open(r'./PMT_1t.txt')\nline = f.readline()\ndata_list = []\nwhile line:\n num = list(map(float,line.split()))\n data_list.append(num)\n line = f.readline()\nf.close()\nPMT_pos = np.array(data_list)\n\n# sys.argv[1]: '%s' radius\n# sys.argv[2]: '%s' path\n# sys.argv[3]: '%s' output\n# sys.argv[4]: '%d' cut\nmain_Calib(sys.argv[1],sys.argv[2], sys.argv[3], eval(sys.argv[4]))\n","sub_path":"calib/Time_calib/main_calib.py","file_name":"main_calib.py","file_ext":"py","file_size_in_byte":14377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"232376492","text":"\"\"\"\nFile Path: app.py\nDescription: Application Init\nCopyright (c) 2019. This Application has been developed by OR73.\n\"\"\"\n# from application.setup import create_app\nfrom application import create_app\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"554769491","text":"v_dir = \"k:\\\\Python\\\\codejam\\\\2016_problem_a\\\\\"\r\nv_file_input = v_dir + \"input_1.txt\"\r\n# filename = v_dir + \"A-small-practice.in\"\r\n# filename = v_dir + \"A-large-practice.in\"\r\n\r\nv_txt_in = open(v_file_input)\r\nv_file_output = \"output_1.txt\"\r\nv_txt_out = open(v_file_output, 'w')\r\n\r\nv_number_of_tests = int(v_txt_in.readline())\r\n\r\nv_test_number = 1\r\n\r\nwhile v_test_number <= v_number_of_tests:\r\n v_first_number = int(v_txt_in.readline())\r\n v_number = 0\r\n c = []\r\n\r\n while (len(c) < 10 and v_first_number != 0):\r\n v_number += v_first_number\r\n c.extend(list(str(v_number))) # add digits from new number\r\n c = list(set(c)) # delete dublicates\r\n# c.sort()\r\n# print(v_number)\r\n# print(c)\r\n\r\n# print('==========')\r\n if v_first_number != 0:\r\n v_txt_out.write(\"Case #\" + str(v_test_number) + \": \" + str(v_number) + \"\\n\")\r\n else:\r\n v_txt_out.write(\"Case #\" + str(v_test_number) + \": \" + 'INSOMNIA' + \"\\n\")\r\n v_test_number += 1\r\n\r\n\"\"\"\r\n v_diners = v_txt_in.readline()\r\n info = v_txt_in.readline().split()\r\n arr = info\r\n print(arr)\r\n arr_feat = []\r\n for i in arr\r\n\r\n v_test_number += 1\r\n\"\"\"\r\n\r\n\"\"\"\r\nfor line in v_txt_in:\r\n # print(line)\r\n answer = 0\r\n position = 0\r\n sum = 0\r\n info = line.split()\r\n # print(info)\r\n # print(info[1])\r\n # for i in info[1] :\r\n # print(i)\r\n # print(int(info[0]),position)\r\n while position <= int(info[0]):\r\n if position > sum:\r\n answer += 1\r\n sum += 1\r\n sum += int(info[1][position])\r\n # print(int(info[1][position]), answer, sum)\r\n position += 1\r\n # print(\"case #\",index_of_line,\": \",answer, sep='')\r\n v_txt_out.write(\"case #\"+str(index_of_line)+\": \"+str(answer)+\"\\n\")\r\n v_index_of_line += 1\r\n\"\"\"","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_gravilet_2016_problem_a.py","file_name":"16_0_1_gravilet_2016_problem_a.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"631124420","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 30 21:39:38 2017\n\n@author: zhouyi\n\"\"\"\n\ngold = open(\"gold.txt\")\npred = open(\"pred.txt\")\n\ncorr = 0\n\nwhile True:\n gold_line = gold.readline()\n pred_line = pred.readline()\n if gold_line == '':\n break\n if int(gold_line) == int(pred_line):\n corr += 1\n \nprint(\"accuracy {}\".format((float) (corr/10)))","sub_path":"test_sample/checker/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"232180447","text":"from scipy.stats import t\r\nfrom scipy.special import ndtri\r\n\r\ndef f1(x, n, alpha, disp):\r\n sr = sum(x) / n\r\n kv = disp ** 0.5\r\n tk = ndtri(alpha / 2 + 0.5)\r\n otkl = tk * kv / n ** 0.5\r\n\r\n return (sr - otkl, sr + otkl)\r\n\r\ndef f2(x, n, alpha):\r\n sr = sum(x) / n\r\n disp = sum([(i - sr) ** 2 for i in x]) / (n - 1)\r\n kv = disp ** 0.5\r\n tk = t.ppf((1 + alpha) / 2, n - 1)\r\n otkl = tk * kv / (n - 1) ** 0.5\r\n\r\n return (sr - otkl, sr + otkl)\r\n\r\nwith open('input.txt', 'r') as fin:\r\n n, alpha, disp = map(float, fin.readline().split())\r\n x = list(map(float, fin.readline().split()))\r\n\r\nif disp > 0:\r\n a, b = f1(x, n, alpha, disp) # -1.32 0.433\r\nelse:\r\n a, b = f2(x, n, alpha) # -1.814 0.928\r\n\r\nwith open('output.txt', 'w') as fout:\r\n print(str(a) + \" \" + str(b), file=fout)","sub_path":"ШЦЭ 2019. Матметоды анализа данных/Оценка матожидания.py","file_name":"Оценка матожидания.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"487725274","text":"from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.mail import send_mail\n\nfrom scoops.taskapp.celery import app\n\nUser = get_user_model()\n\n\n@app.task()\ndef send_mail_to_user(user_id, subject, message, html):\n user = User.objects.get(pk=user_id)\n\n # Add a greeting to the message\n greeting = \"Hi {},\\n\\n\".format(user.username)\n message = greeting + message\n\n # Add a greeting to the HTML message\n html_greeting = \"

Hi {},

\".format(user.username)\n html = html_greeting + html\n\n send_mail(\n subject=subject,\n message=message,\n from_email=settings.DEFAULT_FROM_EMAIL,\n recipient_list=[user.email],\n html_message=html\n )\n\n@app.task()\ndef send_mail_to_users(user_ids, subject, message, html):\n for user_id in user_ids:\n send_mail_to_user.delay(user_id, subject, message, html)\n","sub_path":"scoops/users/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"208366246","text":"'''\nFile: app.py\nFile Created: 2020-07-25\nAuthor: Parijat Khan (khanparijat@gmail.com)\n-----\nCopyright 2020 Parijat Khan\n'''\n\nimport streamlit as st\nimport numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\n\nfrom floorplan import makeplan\n\nst.title('Mall-monitor by ')\n\nfig = go.Figure()\n\nmakeplan(fig)\n\nsize = [20, 40, 60, 80, 100, 80, 60, 40, 20, 40, 60, 20, 10, 5]\n\nfig.add_trace(go.Scatter(\n x=[10, 10, 10, 40, 70, 97, 97, 90, 63, 30, 40, 40, 70, 70],\n y=[10, 25, 40, 45, 45, 40, 20, 5, 5, 5, 20, 30, 20, 30],\n mode='markers',\n marker=dict(\n size=size,\n sizemode='area',\n sizeref=2.*max(size)/(40.**2),\n sizemin=4\n )\n))\n\nfig.update_shapes(dict(xref='x', yref='y'))\n\nfig.update_layout(\n autosize=False,\n width=735,\n height=350,\n margin=dict(\n l=0,\n r=0,\n b=0,\n t=0,\n pad=0\n ),\n showlegend=False\n)\n\nst.plotly_chart(fig)\n\n# DATE_COLUMN = 'date/time'\n# DATA_URL = ('https://s3-us-west-2.amazonaws.com/'\n# 'streamlit-demo-data/uber-raw-data-sep14.csv.gz')\n\n# DATE_COLUMN = 'date/time'\n# DATA_URL = ('https://s3-us-west-2.amazonaws.com/'\n# 'streamlit-demo-data/uber-raw-data-sep14.csv.gz')\n\n# @st.cache\n# def load_data(nrows):\n# data = pd.read_csv(DATA_URL, nrows=nrows)\n# lowercase = lambda x: str(x).lower()\n# data.rename(lowercase, axis='columns', inplace=True)\n# data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN])\n# return data\n\n# data_load_state = st.text('Loading data...')\n# data = load_data(10000)\n# data_load_state.text(\"Done! (using st.cache)\")\n\n# if st.checkbox('Show raw data'):\n# st.subheader('Raw data')\n# st.write(data)\n\n# st.subheader('Number of pickups by hour')\n# hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0]\n# st.bar_chart(hist_values)\n\n# # Some number in the range 0-23\n# hour_to_filter = st.slider('hour', 0, 23, 17)\n# filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter]\n\n# st.subheader('Map of all pickups at %s:00' % hour_to_filter)\n# st.map(filtered_data)\n\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"106128023","text":"from macaroons.macaroon import Macaroon\n\n\ndef test():\n m = Macaroon(\n location='http://mybank/',\n identifier='we used our secret key',\n key='this is our super secret key; only we should know it'\n )\n m.signature\n\n\nif __name__ == '__main__':\n import timeit\n print(timeit.timeit(\n \"test()\",\n setup=\"from __main__ import test\",\n number=1000000\n ))\n","sub_path":"profiling/benchmark_basic_macaroon_creation.py","file_name":"benchmark_basic_macaroon_creation.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"561406018","text":"from src.data_provider import milan\n\ndef data_provider(dataset_name,\n\t\t\t\ttrain_data_paths,\n\t\t\t\tvalid_data_paths,\n\t\t\t\tbatch_size,\n\t\t\t\timg_width,\n\t\t\t\tin_seq_length,\n\t\t\t\tout_seq_length,\n\t\t\t\tdims_3D,\n\t\t\t\tis_training):\n\n\t'''Returns a Dataset.\n\n Args:\n dataset_name: String, the name of the dataset.\n train_data_paths: List, [train_data_path1, train_data_path2...]\n valid_data_paths: List, [val_data_path1, val_data_path2...]\n batch_size: Int, the batch size.\n img_width: Int, the width of input images.\n in_seq_length, number of input snapshots.\n out_seq_length, number of output snapshots.\n dims_3D, dimension of depth channel of 3D encoder\n is_training: Bool, training or testing.\n\n Returns:\n if is_training is True, it returns two dataset instances for both\n training and evaluation. Otherwise only one dataset instance for\n evaluation.\n Raises:\n ValueError: When `dataset_name` is unknown.\n\t'''\n\n\tif dataset_name != 'milan':\n\t\traise ValueError('Name of dataset unknown %s' % dataset_name)\n \n\ttest_input_param = {\n\t\t'tra_set': False,\n\t\t'paths': valid_data_paths,\n\t\t'minibatch_size': batch_size,\n\t\t'input_data_type': 'float32',\n\t\t'input_seq_length': in_seq_length,\n\t\t'output_seq_length': out_seq_length,\n\t\t'3D_dims': dims_3D,\n\t\t'name': dataset_name + 'test iterator'\n\t\t}\n \n\ttest_input_handle = milan.InputHandle(test_input_param)\n\ttest_input_handle.begin(do_shuffle=False)\n \n\tif is_training:\n\t\ttrain_input_param = {\n\t\t\t'tra_set': True,\n\t\t\t'paths': train_data_paths,\n\t\t\t'minibatch_size': batch_size,\n\t\t\t'input_data_type': 'float32',\n\t\t\t'input_seq_length': in_seq_length,\n\t\t\t'output_seq_length': out_seq_length,\n\t\t\t'3D_dims': dims_3D,\n\t\t\t'name': dataset_name + ' train iterator'\n\t\t}\n \n\t\ttrain_input_handle = milan.InputHandle(train_input_param)\n\t\ttrain_input_handle.begin(do_shuffle=True)\n\t\treturn train_input_handle, test_input_handle\n\telse:\n\t\treturn test_input_handle\n","sub_path":"src/data_provider/datasets_factory.py","file_name":"datasets_factory.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"414979811","text":"\"\"\"\r\nWrite a function to sum up a given set of numbers other than itself\r\nInput: An array if n integers nums,\r\nOutput: An array output such that output[i] is equal to the sum of all the elements of nums except nums[i].\r\nFor example, given [1,2,3,4], return [9,8,7,6]\r\n\"\"\"\r\nimport sys\r\nimport ast\r\n\r\ndef sum_up(nums):\r\n\toutput = []\r\n\tfor num in nums:\r\n\t\toutput.append(sum(nums) - num)\r\n\treturn output\r\n\r\na = ast.literal_eval(sys.argv[1])\r\nb = sum_up(a)\r\n\r\nprint(b) ","sub_path":"q1/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"650181289","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^new/?', 'workshop.views.workshop_new', name='workshop_new'),\n url(r'^(?P\\d+)/?$', 'workshop.views.workshop_detail',\n name='workshop_detail'),\n url(r'^(?P\\d+)/delete/?$', 'workshop.views.workshop_delete',\n name='workshop_delete'),\n url(r'^(?P\\d+)/edit/?$', 'workshop.views.workshop_edit',\n name='workshop_edit'),\n url(r'^(?P\\d+)/subscribe/?$', 'workshop.views.workshop_subscribe',\n name='workshop_subscribe'),\n url(r'^(?P\\d+)/unsubscribe/?$', 'workshop.views.workshop_unsubscribe',\n name='workshop_unsubscribe'),\n url(r'^(?P\\d+)/questions/new/?$', 'workshop.views.question_new',\n name='question_new'),\n url(r'^(?P\\d+)/questions/(?P\\d+)/?$', 'workshop.views.question_detail',\n name='question_detail'),\n url(r'^/?$', 'workshop.views.workshops', name='workshop_list'),\n url(r'^admin/', include(admin.site.urls)),\n)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"workshop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"474654451","text":"# https://us-central1-bloodbankasaservice.cloudfunctions.net/get_user_by_request\n\nfrom google.api_core import retry\nfrom google.cloud import pubsub_v1\nimport os, json, math, redis, datetime\nfrom firebase_admin import credentials, firestore, initialize_app\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = (\n os.path.abspath(os.getcwd()) + \"/key.json\"\n)\n\ntimeout = 300\nproject_id = \"bloodbankasaservice\"\ncred = credentials.Certificate(\"./key.json\")\ndefault_app = initialize_app(cred)\ndb = firestore.client()\nuser = db.collection(\"User\")\nrequest = db.collection(\"Request\")\nredis_host = \"10.0.0.3\"\nredis_port = 6379\nredis_client = redis.Redis(host=redis_host, port=redis_port)\n\n\nclass Blood_Request:\n def __init__(self, victim_id, blood_group, timestamp, latitude, longitude):\n self.victim_id = victim_id\n self.blood_group = blood_group\n self.timestamp = timestamp\n self.latitude = latitude\n self.longitude = longitude\n\n\ndef listen_topic(blood_group, user_id):\n topic = f\"{ blood_group.lower() }blood_group\"\n topic_path = f\"projects/{project_id}/topics/{topic}\"\n subscriber = pubsub_v1.SubscriberClient()\n subscription_path = subscriber.subscription_path(\n project_id, f\"{blood_group}~{user_id}~temp\"\n )\n subscriber.create_subscription(\n request={\"name\": subscription_path, \"topic\": topic_path}\n )\n final_response = None\n with subscriber:\n response = subscriber.pull(\n request={\"subscription\": subscription_path, \"max_messages\": 1},\n retry=retry.Retry(deadline=10),\n )\n ack_ids = []\n if response.received_messages:\n received_message = response.received_messages[0]\n ack_ids.append(received_message.ack_id)\n subscriber.acknowledge(\n request={\"subscription\": subscription_path, \"ack_ids\": ack_ids}\n )\n final_response = received_message.message.data.decode(\"utf-8\")\n subscriber.delete_subscription(request={\"subscription\": subscription_path})\n return final_response\n\n\ndef response(message):\n headers = {\n \"Access-Control-Allow-Origin\": \"*\",\n }\n return (message, 200, headers)\n\n\ndef polling_requests(request):\n \"\"\"Responds to any HTTP request.\n Args:\n request (flask.Request): HTTP request object.\n Returns:\n The response text or any set of values that can be turned into a\n Response object using\n `make_response `.\n \"\"\"\n\n if request.method == \"OPTIONS\":\n # Allows GET requests from any origin with the Content-Type\n # header and caches preflight response for an 3600s\n headers = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Max-Age\": \"3600\",\n }\n return (\"\", 204, headers)\n\n print(request)\n request_json = request.get_json()\n print(request_json)\n\n blood_group = request_json[\"blood_group\"]\n user_id = request_json[\"user_id\"]\n return response(listen_topic(blood_group, user_id))\n","sub_path":"cloud_functions/polling_requests.py","file_name":"polling_requests.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"155670191","text":"import pygame\nfrom main.image_init import image\n\nclass screen():\n screen_width = 1920\n screen_height = 1080\n win = pygame.display.set_mode([screen_width, screen_height],pygame.FULLSCREEN)\n\nclass player(object):\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.speed = 10\n self.jumpCount = 10\n self.left = False\n self.right = False\n self.lastposition = 1\n self.animCount = 0\n self.up = False\n self.down = True\n\n def draw(self, win):\n if self.animCount + 1 >= 30:\n self.animCount = 0\n if self.left:\n win.blit(image.walkLeft, (self.x, self.y))\n self.animCount += 1\n elif self.right:\n win.blit(image.walkRight, (self.x, self.y))\n self.animCount += 1\n else:\n if self.lastposition == 1:\n win.blit(image.idleLeft, (self.x, self.y))\n if self.lastposition == 2:\n win.blit(image.idleRight, (self.x, self.y))\n\nplayer = player(0, 0, 196, 118)\n\n\ndef drawWindow():\n screen.win.blit(image.background, (0, 0))\n player.draw(screen.win)\n pygame.display.update()\n\ndef playerGoing():\n keys = pygame.key.get_pressed()\n if keys[pygame.K_LEFT] and player.x >= 0:\n player.x -= player.speed\n player.left = True\n player.right = False\n player.lastposition = 1\n if keys[pygame.K_RIGHT] and player.x <= screen.screen_width - player.width:\n player.x += player.speed\n player.left = False\n player.right = True\n player.lastposition = 2\n else:\n player.left = False\n player.right = False\n if keys[pygame.K_UP] and y >= 0:\n y -= speed\n if keys[pygame.K_DOWN] and y <= screen.screen_height - player.height:\n y += speed\n","sub_path":"main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"218140710","text":"import logging\nfrom logging.handlers import RotatingFileHandler\nfrom watson import Watson\nimport requests\nimport os\nimport datetime\nimport subprocess\n\n#parameters for authorization and audio format\nURL = 'WATSON_URL'\nPASSWORD = 'WATSON_PASSWORD'\nUSERNAME = 'WATSON_USERNAME'\nCHUNK_SIZE = 1024\n#Information for logger\nMEGABYTE = 1000000 #number of bytes in a megabyte\nnow = datetime.datetime.now() #current time\n\n\n#method for making a rotating log\n#REQUIRES: Path is valid\n#MODIFIES: Log based on byte size and period of time\n#EFFECTS: Creates multiple logs, as well as deleting them after 30 days\ndef createRotatingLog(path):\n #initiates logging session\n Logger = logging.getLogger(\"TTS\")\n Logger.setLevel(logging.DEBUG)\n #defines handler for byte size\n #will roll over after 100 mb, will max out at 10 backup files\n sizeHandler = RotatingFileHandler(path, maxBytes=(MEGABYTE * 100),\n backupCount=10)\n fmtr = logging.Formatter('%(asctime)s %(levelname)s %(message)s',\n datefmt='%H:%M:%S')\n\n sizeHandler.setFormatter(fmtr)\n sizeHandler.setLevel(logging.DEBUG)\n\n Logger.addHandler(sizeHandler)\n\n return Logger\n\n\n#Bool method to assert whether the string is intended to return\n#True or False\ndef yesOrNo(string):\n if string == '1':\n return True\n if string == '0':\n return False\n\n\n#Bool method that shows the input is valid (a 1 or a 0)\ndef validBool(string):\n if string == '1' or string == '0':\n return True\n else:\n return False\n\n\n#Bool method that shows the filename does not contain bad characters\ndef validFilename(string):\n for c in string:\n if c == ':' or c == '.':\n return False\n\n return True\n\n#method to request a text phrase to synthesize voice\ndef requestPhrase(Logger):\n userInput = input(\"Enter a phrase: \")\n #checks for empty input\n if userInput == '':\n Logger.warning(\"No text input\")\n\n if len(userInput) < 2:\n Logger.warning(\"Not enough text to synthesize\")\n\n return userInput\n\n#method to request a voiceID yes or no answer\ndef requestVoiceID(Logger):\n voiceIDBool = input(\"Enter 1 to hear male voice, 0 to hear female voice: \")\n if not validBool(voiceIDBool):\n Logger.warning(\"Invalid input for VoiceID: %s\" % voiceIDBool)\n\n if yesOrNo(voiceIDBool):\n voiceID = 'en-US_MichaelVoice'\n else:\n voiceID = 'en-US_AllisonVoice'\n\n return voiceID\n\n#method to check if user wants to stream or download\n#returns true or false\ndef isStream(Logger):\n #stream input (determines whether code runs stream() or download())\n streamBool = input(\"Enter 1 to stream, enter 0 to download: \")\n if not validBool(streamBool):\n Logger.warning(\"Invalid input for streamBool: %s\" % streamBool)\n\n if yesOrNo(streamBool):\n\n return True\n else:\n return False\n\n#method to receive format of audio from user\n#also recieves if the file is to be converted into vox\n#returns a dictionary, in the format of (accept, voxBool)\ndef requestFormat(Logger):\n formatBool = input(\"Enter 1 for .wav, enter 2 for .ogg, enter 3 for .vox: \")\n fInt = int(formatBool)\n if fInt != 1 or fInt != 2 or fInt != 3:\n Logger.warning(\"Invalid input for formatBool: %s\" % formatBool)\n\n #adjusts the accept variable based on response\n if fInt == 1:\n accept = \"audio/wav\"\n Logger.info(\"File type: .wav\")\n voxBool = False\n elif fInt == 2:\n accept = \"audio/ogg;codecs=opus\"\n Logger.info(\"File type: .ogg\")\n voxBool = False\n elif fInt == 3:\n accept = \"audio/wav\"\n Logger.info(\"File type: .vox\")\n voxBool = True\n\n return {'accept':accept, 'voxBool':voxBool}\n\n#method to receive filename from user\ndef requestFilename(Logger):\n #filename and location input\n filename = input(\"Enter a name for the file: \")\n if not validFilename(filename):\n Logger.warning(\"Invalid input for filename: %s\" % filename)\n\n #logs filename\n Logger.info(\"Filename: %s\" % filename)\n\n return filename\n\n#method to receive filepath from user\ndef requestPath(Logger):\n location = input(\"Enter a location for the file: \")\n #asserts that the path exists\n if not os.path.isdir(location):\n Logger.warning(\"Directory in path does not exist: %s\" % location)\n\n return location\n\n#method to initially convert ogg file to wav\ndef convertToWav(filename):\n #strips ogg extension and attaches .wav\n wavName = filename[:-4] + '2.wav'\n #creates command line for ffmpeg\n command = [\"ffmpeg\", \"-i\", filename, wavName]\n #ffmpeg is a service for command line conversion\n #used specifically because it ignores bad header information (Watson wav files)\n #called through subprocess to return converted file\n subprocess.call(command, shell=True)\n\n #removes ogg file\n os.remove(filename)\n\n #returns string name reference to the wavfile\n return wavName\n\n#method to convert a wav file to a vox file, provided full path\ndef convertToVox(filename, voxName):\n voxName = voxName[:-5] + \".vox\"\n #creates command for vcecopy, another command line executable\n #vcecopy handles wav -> vox conversion\n command = [r\"copyfiles\\vcecopy\", \"-m\", \",1\", \"-c4\", filename, voxName]\n subprocess.call(command, shell=True)\n\n #removes wav file\n os.remove(filename)\n\n#method to convert ogg file to vox\n#ties together methods above to create a single command conversion\ndef fullConvert(stringList):\n #with only one element in the list, conversion is simple\n #extract filename, end with vox, convert\n if len(stringList) == 1:\n #takes first and only element from the list\n for string in stringList:\n filepath = string[0]\n filename = string[1]\n fullPath = filepath + '\\\\' + filename + '.wav'\n #wavPath is the filepath to the newly converted file, ogg->wav\n wavPath = convertToWav(fullPath)\n #voxName is the new file for conversion, removes '.wav'\n #and replaces it with '.vox', so the file will still have the user's\n #desired name choice\n voxPath = wavPath[:-4] + '.vox'\n\n #end conversion of wav->vox\n convertToVox(wavPath, voxPath)\n\n #else clause for the event of merging multiple files\n else:\n\n for string in stringList:\n filepath = string[0]\n filename = string[1]\n\n fullPath = filepath + '\\\\' + filename + '.ogg'\n wavPath = convertToWav(fullPath)\n\n #removes the .ogg extension as well as the numeric identifier\n #that organizes the ogg/wav files.\n #each file will be subsequently converted to the same vox name\n #merging the files in the process\n voxPath = fullPath[:-5] + '.vox'\n convertToVox(wavPath, voxPath)\n\n\ndef main():\n\n #creates the log session\n Logger = createRotatingLog(\"TTS.log\")\n Logger.info(\"* File session started *\")\n\n\n #disable warnings for requests library\n requests.packages.urllib3.disable_warnings()\n\n #empty variables to be used as parameters for download()\n userInput = ''\n filename = ''\n location = ''\n accept = 'audio/wav'\n voiceID = ''\n\n #main function, loops until user types quit\n while userInput != 'quit':\n #phrase input\n userInput = requestPhrase(Logger)\n #breaks loop\n if userInput != 'quit':\n #voiceID input (bool conversion to string)\n voiceID = requestVoiceID(Logger)\n\n if isStream(Logger):\n Logger.info(\"Output: Stream.\")\n #creates watson object, wav is default for stream\n watson = Watson(USERNAME, PASSWORD, voiceID,\n URL, CHUNK_SIZE, 'audio/wav')\n watson.playFiles(userInput)\n\n #Request ID placeholder\n Logger.info(\"Request ID: 375832948 (placeholder)\")\n Logger.info(\"Stream successful.\")\n else:\n #audio format input\n #returns a short dictionary\n audioFormat = requestFormat(Logger)\n #filename and location input\n filename = requestFilename(Logger)\n location = requestPath(Logger)\n\n #creates watson object\n watson = Watson(USERNAME, PASSWORD, voiceID,\n URL, CHUNK_SIZE, audioFormat['accept'])\n #writes files\n fileList = watson.writeFiles(userInput, filename, location)\n if audioFormat['voxBool']:\n fullConvert(fileList)\n Logger.info(\"Vox filed created.\")\n Logger.info(\"Request ID: 375832948 (placeholder)\")\n\n print(\"Audio file saved.\")\n\n Logger.info(\"Download successful.\")\n\n #Indicates end of logging session, adds space between sessions\n Logger.info(\"* File session ended *\\n\\n\")\n\n#runs main function\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"448927591","text":"#!/usr/bin/env python\n\n# Copyright 2018 The GraphicsFuzz Project 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport argparse\nimport glob\nimport json\nimport os\nimport random\nimport shutil\nimport subprocess\nimport sys\nimport threading\nimport io\nimport platform\n\nsys.path.append(os.path.split(os.path.abspath(__file__))[0] + os.path.sep + \"..\")\nfrom cmd_helpers import validate_frag\nfrom cmd_helpers import execute\n\nthis_path = os.path.split(os.path.abspath(__file__))[0] + os.path.sep\nmax_int = pow(2, 16)\n\n\n### Helper functions\n\ndef abs_path_with_extension(prefix, extension):\n return os.path.abspath(prefix + extension)\n\ndef uniforms_file(prefix):\n return abs_path_with_extension(prefix, \".json\")\n\ndef primitives_file(prefix):\n return abs_path_with_extension(prefix, \".primitives\")\n\ndef license_file(prefix):\n return abs_path_with_extension(prefix, \".license\")\n\ndef uniforms_present(prefix):\n return os.path.isfile(uniforms_file(prefix))\n\ndef kill_generator(generator_proc):\n if args.verbose:\n print(\"Timeout\")\n generator_proc.kill()\n\ndef generate_variant(reference_prefix, inner_seed, output_prefix):\n cmd = [\"java\", \"-ea\",\n \"com.graphicsfuzz.generator.tool.Generate\",\n reference_prefix + \".json\",\n args.donors,\n args.glsl_version,\n output_prefix + \".json\",\n \"--seed\",\n str(inner_seed) ]\n if args.webgl:\n cmd += [ \"--webgl\" ]\n if args.small:\n cmd += [ \"--small\" ]\n if args.avoid_long_loops:\n cmd += [ \"--avoid_long_loops\" ]\n if args.replace_float_literals:\n cmd += [ \"--replace_float_literals\" ]\n if args.aggressively_complicate_control_flow:\n cmd += [ \"--aggressively_complicate_control_flow\" ]\n if args.multi_pass:\n cmd += [ \"--multi_pass\" ]\n if args.generate_uniform_bindings:\n cmd += [ \"--generate_uniform_bindings\" ]\n if args.max_uniforms is not None:\n cmd += [ \"--max_uniforms\", str(args.max_uniforms) ]\n if args.verbose:\n print(\"Transform command: %s\" % (\" \".join(cmd)))\n generator_proc = subprocess.Popen(cmd,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n kill_timer = threading.Timer(args.timeout, lambda: kill_generator(generator_proc))\n try:\n kill_timer.start()\n generator_stdout, generator_stderr = generator_proc.communicate()\n assert (generator_proc.returncode is not None)\n finally:\n kill_timer.cancel()\n return {\"returncode\": generator_proc.returncode,\n \"stdout\": generator_stdout,\n \"stderr\": generator_stderr,\n \"cmd\": \" \".join(cmd)}\n\ndef prepare_reference_shaders(reference_prefix, output_file_prefix, glsl_version):\n cmd = [\"java\",\n \"-ea\",\n \"com.graphicsfuzz.generator.tool.PrepareReference\",\n reference_prefix + \".json\",\n output_file_prefix + \".json\",\n glsl_version ]\n if args.replace_float_literals:\n cmd += [ \"--replace_float_literals\" ]\n if args.webgl:\n cmd += [ \"--webgl\" ]\n if args.generate_uniform_bindings:\n cmd += [ \"--generate_uniform_bindings\" ]\n if args.max_uniforms is not None:\n cmd += [ \"--max_uniforms\", str(args.max_uniforms - 1) ] # We subtract 1 because we need to be able to add injectionSwitch\n if args.verbose:\n print(\"Reference preparation command: %s\" % (\" \".join(cmd)))\n prepare_reference_proc = subprocess.Popen(cmd,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n prepare_reference_stdout, prepare_reference_stderr = prepare_reference_proc.communicate()\n if prepare_reference_proc.returncode != 0:\n print(\"Reference preparation resulted in errors: \" + prepare_reference_stderr)\n sys.exit(1)\n\ndef get_git_revision_hash():\n git_hash = open(args.hash_file, 'r')\n ret_val = git_hash.read()\n git_hash.close()\n return ret_val\n\n\ndef shader_is_valid(shader_file):\n if args.verbose:\n print(\"Validating...\")\n validator_results = validate_frag(shader_file, args.validator_path, args.verbose)\n if validator_results[\"returncode\"] == 0 and args.webgl:\n validator_results = execute([args.translator_path, \"-s=w\", shader_file], args.verbose)\n elif validator_results[\"returncode\"] == 0 and args.glsl_version == \"100\":\n validator_results = execute([args.translator_path, shader_file], args.verbose)\n if validator_results[\"returncode\"] != 0:\n if args.verbose:\n print(\"Failed validating shader:\")\n print(validator_results[\"stdout\"].decode(\"utf-8\"))\n print(validator_results[\"stderr\"].decode(\"utf-8\"))\n return False\n return True\n\ndef generated_shaders_too_large(args, variant_file_prefix):\n for ext in [ \".frag\", \".vert\" ]:\n variant_shader_file = variant_file_prefix + ext\n if not os.path.isfile(variant_shader_file):\n continue\n num_bytes_variant = os.path.getsize(variant_shader_file)\n num_bytes_reference = os.path.getsize(args.reference_prefix + ext)\n\n if args.max_factor is not None and float(num_bytes_variant) > args.max_factor * float(num_bytes_reference):\n if args.verbose:\n print(\"Discarding \" + ext + \" shader of size \" + str(num_bytes_variant) + \" bytes; more than \" + str(args.max_factor) + \" times larger than reference of size \" + str(num_bytes_reference))\n return True\n\n if args.max_bytes is not None and num_bytes_variant > args.max_bytes:\n if args.verbose:\n print(\"Discarding \" + ext + \" shader of size \" + str(num_bytes_variant) + \" bytes; exceeds limit of \" + str(args.max_bytes) + \" bytes\")\n return True\n\n return False\n\ndef remove_if_exists(filename):\n if os.path.isfile(filename):\n os.remove(filename)\n\ndef move_if_exists(src, dst):\n print(src)\n print(dst)\n if os.path.isfile(src):\n shutil.move(src, dst)\n\ndef skip_due_to_invalid_shader(args, variant_file_prefix):\n variant_file_frag = variant_file_prefix + \".frag\"\n variant_file_vert = variant_file_prefix + \".vert\"\n variant_file_json = variant_file_prefix + \".json\"\n variant_file_probabilities = variant_file_prefix + \".prob\"\n\n if args.disable_validator:\n return False\n for ext in [ \".frag\", \".vert\" ]:\n variant_shader_file = variant_file_prefix + ext\n if not os.path.isfile(variant_shader_file):\n continue\n if shader_is_valid(variant_shader_file):\n continue\n if not args.keep_bad_variants:\n remove_if_exists(variant_file_frag)\n remove_if_exists(variant_file_vert)\n os.remove(variant_file_json)\n os.remove(variant_file_probabilities)\n return True\n else:\n move_if_exists(variant_file_frag, \"bad_\" + os.path.basename(variant_file_frag))\n move_if_exists(variant_file_vert, \"bad_\" + os.path.basename(variant_file_vert))\n shutil.move(variant_file_json, \"bad_\" + os.path.basename(variant_file_json))\n shutil.move(variant_file_probabilities, \"bad_\" + os.path.basename(variant_file_probabilities))\n if args.stop_on_fail:\n if args.verbose:\n print(\"Generated an invalid variant, stopping.\")\n exit(1)\n return False\n\n### Argument parser\nparser = argparse.ArgumentParser(description=\"Variant generator\")\n\n# Required arguments\nparser.add_argument(\"reference_prefix\", type=str, action=\"store\",\n help=\"Prefix of shader files and associated metadata files.\")\nparser.add_argument(\"donors\", type=str, action=\"store\",\n help=\"Path to a folder containing donor shaders.\")\nparser.add_argument(\"glsl_version\", type=str, action=\"store\",\n help=\"Version of GLSL to be used.\")\nparser.add_argument(\"output_folder\", type=str, action=\"store\",\n help=\"Folder to hold output shaders.\")\n\n# Optional arguments\nparser.add_argument(\"--java_tool_path\", type=str, action=\"store\",\n default=os.sep.join(\n [os.path.dirname(os.path.abspath(__file__)), \"..\", \"..\", \"jar\", \"tool-1.0.jar\"]),\n help=\"Path to tool-1.0.jar, or root directory of compiled class files.\")\nparser.add_argument(\"--num_variants\", type=int, action=\"store\", default=10,\n help=\"Number of variants to produce.\")\nparser.add_argument(\"--seed\", type=int, action=\"store\",\n default=random.randint(0, max_int),\n help=\"Seed to initialize random number generator with.\")\nparser.add_argument(\"--timeout\", type=int, action=\"store\",\n default=30,\n help=\"Time in seconds after which execution of generation is terminated.\")\nparser.add_argument(\"--hash_file\", type=str, action=\"store\",\n default=this_path + \"..\" + os.path.sep + \"..\" + os.path.sep + \"HASH\",\n help=\"Path to file containing git hash.\")\nparser.add_argument(\"--disable_validator\", action=\"store_true\",\n help=\"Disable calling glslangValidator for generated variants.\")\nparser.add_argument(\"--validator_path\", type=str, action=\"store\",\n default=os.sep.join(\n [os.path.dirname(os.path.abspath(__file__)), \"..\", \"..\", \"bin\", platform.system(), \"glslangValidator\"]),\n help=\"Path to binary to use to validate produced variants (usually glslangvalidator).\")\nparser.add_argument(\"--translator_path\", type=str, action=\"store\",\n default=os.sep.join(\n [os.path.dirname(os.path.abspath(__file__)), \"..\", \"..\", \"bin\", platform.system(), \"shader_translator\"]),\n help=\"Path to binary to use to validate WebGL variants (usually shader_translator).\")\nparser.add_argument(\"--keep_bad_variants\", action=\"store_true\",\n help=\"Do not remove invalid variants upon generation.\")\nparser.add_argument(\"--stop_on_fail\", action=\"store_true\",\n help=\"Quit if an invalid variant is generated.\")\nparser.add_argument(\"--verbose\", action=\"store_true\",\n help=\"Emit detailed information regarding the progress of the generation.\")\nparser.add_argument(\"--small\", action=\"store_true\",\n help=\"Restrict generation to small shader families.\")\nparser.add_argument(\"--chunk_size\", type=int, action=\"store\", default=4,\n help=\"Number of non-verbose progress messages (<=0 = none).\")\nparser.add_argument(\"--webgl\", action=\"store_true\",\n help=\"Restrict transformations to be WebGL-compatible.\")\nparser.add_argument(\"--max_bytes\", type=int, action=\"store\",\n help=\"Maximum allowed size, in bytes, for variant shader (default: no limit).\")\nparser.add_argument(\"--max_factor\", type=float, action=\"store\",\n help=\"Maximum blowup allowed, compared with size of reference shader (default: no limit).\")\nparser.add_argument(\"--avoid_long_loops\", action=\"store_true\",\n help=\"Avoid long-running loops during live code injection.\")\nparser.add_argument(\"--aggressively_complicate_control_flow\", action=\"store_true\",\n help=\"Generate very complex control flow.\")\nparser.add_argument(\"--multi_pass\", action=\"store_true\",\n help=\"Apply shader transformations multiple times.\")\nparser.add_argument(\"--replace_float_literals\", action=\"store_true\",\n help=\"Replace floating-point literals with uniforms.\")\nparser.add_argument(\"--require_license\", action=\"store_true\",\n help=\"Require a license file to be provided alongside the reference and pass details through to generated shaders.\")\nparser.add_argument(\"--generate_uniform_bindings\", action=\"store_true\",\n help=\"Put all uniforms in uniform blocks and generate associated bindings. Necessary for Vulkan compatibility.\")\nparser.add_argument(\"--max_uniforms\", type=int, action=\"store\",\n help=\"Ensure that no more than the given number of uniforms are included in generated shaders. Necessary for Vulkan compatibility.\")\n\nargs = parser.parse_args()\n\n### Initial setup\nif args.verbose:\n print(\"Using seed %d.\" % (args.seed))\nrandom.seed(args.seed)\n\nargs.validator_path = os.path.abspath(args.validator_path)\nargs.translator_path = os.path.abspath(args.translator_path)\n\nos.environ[\"CLASSPATH\"] = args.java_tool_path + (os.pathsep + os.environ[\"CLASSPATH\"] if \"CLASSPATH\" in os.environ else \"\")\n\nif args.verbose:\n print(\"Setting CLASSPATH to: %s.\" % (os.environ[\"CLASSPATH\"]))\n\nargs.output_folder = os.path.normpath(args.output_folder) + os.path.sep\n\nargs.donors = os.path.abspath(args.donors)\n\nargs.reference_prefix = os.path.splitext(os.path.abspath(args.reference_prefix + \".frag\"))[0]\n\nif args.verbose:\n print(\"Using donor folder %s.\" % (args.donors))\n\n# Make output directory\nif os.path.isdir(args.output_folder):\n print(\"Overwriting previous output folder (%s).\" % (args.output_folder))\n shutil.rmtree(args.output_folder)\nos.mkdir(args.output_folder)\n\nif not uniforms_present(args.reference_prefix):\n print(\"No uniforms file present for reference '\" + args.reference_prefix + \"'\")\n exit(1)\n\n# Prepare reference shaders\nprepare_reference_shaders(args.reference_prefix, args.output_folder + \"reference\", args.glsl_version)\n\n# Validate reference shaders\nif not args.disable_validator:\n if not shader_is_valid(args.output_folder + \"reference.frag\"):\n print(\"The reference fragment shader is not valid, stopping.\")\n exit(1)\n vertex_shader = args.output_folder + \"reference.vert\"\n if os.path.isfile(vertex_shader) and not shader_is_valid(vertex_shader):\n print(\"The reference vertex shader is not valid, stopping.\")\n exit(1)\n\n# Copy primitives for reference shaders, if they exist\nif os.path.isfile(primitives_file(args.reference_prefix)):\n shutil.copyfile(primitives_file(args.reference_prefix),\n args.output_folder + \"reference.primitives\")\n\n# Copy texture if referenced by primitives\nif os.path.isfile(primitives_file(args.reference_prefix)):\n primitives_data = json.load(open(primitives_file(args.reference_prefix)))\n if \"texture\" in primitives_data:\n texture_filename = primitives_data[\"texture\"]\n shutil.copyfile(texture_filename, args.output_folder + texture_filename)\n\nos.chdir(args.output_folder)\n\ndonor_list = glob.glob(args.donors + os.path.sep + \"*.frag\")\nif not donor_list:\n print(\"Given donor folder contains no .frag files!\")\n exit(1)\n\n# Initialise json log file with version information\nlog_json = {\n \"git_hash\": get_git_revision_hash(),\n \"glsl_version\": args.glsl_version,\n \"webgl\": args.webgl,\n \"seed\": args.seed,\n \"reference_basename\": os.path.basename(args.reference_prefix)\n }\n\ngen_variants = 0\ntried_variants = 0\nchunk_count = 0\n\n# Main variant generation loop\nwhile gen_variants < args.num_variants:\n\n if args.verbose:\n print(\"Trying variant %d (produced %d of %d)...\" % (tried_variants, gen_variants, args.num_variants))\n # Generation\n inner_seed = random.randint(0, max_int)\n if args.verbose:\n print(\"Generating variant with inner seed %d...\" % inner_seed)\n variant_file_prefix = \"variant_\" + \"{0:0=3d}\".format(gen_variants)\n generator_results = generate_variant(args.reference_prefix, inner_seed, variant_file_prefix)\n tried_variants += 1\n if generator_results[\"returncode\"] != 0:\n if args.verbose:\n print(\"Failed generating variant:\")\n print(generator_results[\"stderr\"].decode(\"utf-8\"))\n if args.stop_on_fail:\n if args.verbose:\n print(\"Failed generating a variant, stopping.\")\n exit(1)\n continue\n\n # Check code size\n if generated_shaders_too_large(args, variant_file_prefix):\n # A generated shader is too large - discard it (but don't log it as bad)\n continue\n\n # Validation\n if skip_due_to_invalid_shader(args, variant_file_prefix):\n continue\n\n if os.path.isfile(\"reference.primitives\"):\n shutil.copyfile(\"reference.primitives\", primitives_file(variant_file_prefix))\n\n gen_variants += 1\n\n### Final steps\n# Output json log\ndict = {}\ndict['dict'] = log_json\nlog_json_file = open(\"infolog.json\", 'w')\nlog_json_file.write(json.dumps(dict, sort_keys=True, indent=4))\nlog_json_file.close()\n\nprint(\"Generation complete -- generated %d variants in %d tries.\" % (gen_variants, tried_variants))\n","sub_path":"python/src/main/python/drivers/generate-shader-family.py","file_name":"generate-shader-family.py","file_ext":"py","file_size_in_byte":17208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"364389946","text":"from bs4 import BeautifulSoup\r\nfrom langdetect import detect, lang_detect_exception\r\nfrom datetime import date, timedelta\r\nimport time\r\nimport requests\r\nimport praw\r\nimport credentials\r\n\r\nbreak_words = ['pictures', 'photos', 'gifs', 'images',\r\n 'twitter', 'must see', 'tweets', 'memes',\r\n 'instagram', 'tumblr', 'gifts', 'products']\r\n\r\n\r\ndef connect_to_reddit():\r\n\r\n reddit = praw.Reddit(client_id=credentials.CLIENT_ID,\r\n client_secret=credentials.CLIENT_SECRET,\r\n user_agent=credentials.USER_AGENT,\r\n username=credentials.USERNAME,\r\n password=credentials.PASSWORD)\r\n return reddit\r\n\r\n\r\ndef soup_session(link):\r\n \"\"\"BeautifulSoup session\"\"\"\r\n session = requests.Session()\r\n daily_archive = session.get(link)\r\n soup = BeautifulSoup(daily_archive.content, 'html.parser')\r\n return soup\r\n\r\n\r\ndef reddit_bot(headline, main_text, link, my_subreddit, website_name):\r\n \"\"\"Module that takes the title, main text and link to article and posts directly to reddit\"\"\"\r\n\r\n reddit = connect_to_reddit()\r\n\r\n reddit.subreddit(my_subreddit).submit(title=headline, selftext=main_text+'\\n' + '[Link to article](' + link + ')').mod.flair(text=website_name)\r\n\r\n\r\ndef total_articles_today(article_completed_count=0, modify=False):\r\n \"\"\" Saves the progress of amount of links already searched through in an external file if modify = true\r\n Returns the current progress of the amount of links/articles already searched if modify = false\"\"\"\r\n\r\n filepath = r'C:\\Users\\Riccardo\\Desktop\\Python Scripts\\BuzzFeed Reddit Bot\\Posts_Made_Today.txt'\r\n\r\n if not modify:\r\n with open(filepath, 'r') as file:\r\n articles_searched = file.read()\r\n return int(articles_searched)\r\n\r\n else:\r\n with open(filepath, 'w') as file:\r\n file.write(str(article_completed_count))\r\n return 0\r\n\r\n\r\ndef chronological_list_maker(full_list_text, list_count):\r\n\r\n count_list = []\r\n\r\n for x, y in zip(range(1, list_count), reversed(range(1, list_count))):\r\n count_list.append([x, y])\r\n\r\n for i, (x, y) in enumerate(count_list):\r\n count_list[i] = [str(x) + '.', str(y) + '.']\r\n\r\n for i, (start, end) in enumerate(count_list):\r\n if i <= len(count_list) / 2:\r\n full_list_text = full_list_text.replace(end, start)\r\n else:\r\n full_list_text = start.join(full_list_text.rsplit(end, 1))\r\n\r\n return full_list_text\r\n\r\n\r\ndef post_reset():\r\n \"\"\"Resets total articles searched file if post is run at the beginning of the day\"\"\"\r\n import datetime\r\n current_time = datetime.datetime.now().time()\r\n min_time = datetime.time(2, 55)\r\n max_time = datetime.time(3, 5)\r\n if min_time <= current_time <= max_time:\r\n total_articles_today(0, True)\r\n print('reset done')\r\n\r\n\r\ndef post_made_check(post_title, subpoints, my_subreddit):\r\n \"\"\"Checks if the post has already been submitted.\r\nReturns True if post was submitted already and returns False otherwise\"\"\"\r\n\r\n post_made = False\r\n reddit = connect_to_reddit()\r\n subreddit = reddit.subreddit(my_subreddit)\r\n submissions = subreddit.new(limit=40)\r\n for submission in submissions:\r\n if submission.title.lower() == post_title:\r\n post_made = True\r\n break\r\n try:\r\n subpoints_to_check = [int(s) for s in submission.title.split() if s.isdigit()][0]\r\n except IndexError:\r\n continue\r\n if subpoints_to_check == subpoints:\r\n same_words = set.intersection(set(post_title.split()), set(submission.title.lower().split()))\r\n number_of_words = len(same_words)\r\n if number_of_words >=4:\r\n post_made = True\r\n break\r\n return post_made\r\n\r\n\r\ndef article_info(article_date, start_iter):\r\n \"\"\"Gets the link to the article that will be posted on the sub.\r\nThe three if-statements below check if (1) the article starts with a number, (2) the post hasn't been made already,\r\n(3) the articles language is in english,(4) if the articles main points actually have text and not images and\r\n(5) If the article title doesn't contain any keywords listed below\r\nIf all these conditions are met, this module will get the articles text using the article_text() module\r\nand then posts the corresponding text to reddit using the reddit_bot() module\"\"\"\r\n\r\n current_iter = 0\r\n\r\n soup = soup_session(archive_link + article_date)\r\n\r\n for link in list(soup.find_all('a', attrs={'class': 'link-gray'}, href=True))[start_iter:]:\r\n current_iter += 1\r\n for article_to_open in link.find_all('h2', attrs={'class': 'xs-mb05 xs-pt05 sm-pt0 xs-text-4 sm-text-2 bold'}):\r\n\r\n try:\r\n if not detect(article_to_open.text) == 'en':\r\n break\r\n except lang_detect_exception.LangDetectException:\r\n break\r\n\r\n no_of_points = [int(s) for s in article_to_open.text.split() if s.isdigit()] #Records number of points in the article\r\n if not no_of_points:\r\n break\r\n\r\n article_title_lowercase = article_to_open.text.lower()\r\n if any(words in article_title_lowercase for words in break_words):\r\n break\r\n try:\r\n post_made = post_made_check(article_title_lowercase, no_of_points[0], my_subreddit)\r\n except IndexError:\r\n post_made = post_made_check(article_title_lowercase, 0, my_subreddit)\r\n\r\n if post_made:\r\n break\r\n\r\n top_x_link = 'https://www.buzzfeed.com' + link['href']\r\n\r\n try: #Avoids rare case of when there is an index error (occurs when article starts with number immediately followed by a symbol)\r\n article_text_to_use = article_text(top_x_link, no_of_points[0])\r\n if article_text_to_use == '':\r\n article_text_to_use = paragraph_article_text(top_x_link, no_of_points[0])\r\n\r\n if article_text_to_use != '':\r\n reddit_bot(article_to_open.text, article_text_to_use, top_x_link, my_subreddit, website_name)\r\n print(article_to_open.text)\r\n start_iter += current_iter\r\n total_articles_today(start_iter, modify=True)\r\n return\r\n break\r\n except IndexError:\r\n break\r\n\r\n total_articles_today(start_iter + current_iter, modify=True)\r\n\r\n\r\ndef paragraph_article_text(link_to_check, total_points):\r\n \"\"\"Parses list articles that are in paragraph form (have the 'p' HTML tag)\"\"\"\r\n\r\n i = 1\r\n top_x_final = ''\r\n\r\n soup = soup_session(link_to_check)\r\n\r\n for subpoint in soup.find_all('p'):\r\n try:\r\n if subpoint.text[0].isdigit():\r\n top_x_final += subpoint.text.replace(')', '. ', 1) + '\\n'\r\n i += 1\r\n except IndexError:\r\n continue\r\n\r\n if total_points != i-1:\r\n top_x_final = ''\r\n return top_x_final\r\n\r\n\r\ndef article_text(link_to_check, total_points):\r\n \"\"\"Concatenates the main points of the article into a single string and also makes sure the string isn't empty.\r\nAlso checks to make sure the number of sub-points in the article is equal to the number the article title starts with\"\"\"\r\n\r\n i = 1\r\n this_when_counter = 0\r\n top_x_final = ''\r\n\r\n soup = soup_session(link_to_check)\r\n\r\n for title in soup.find_all('h3'):\r\n\r\n subpoint_check = False\r\n\r\n for subpoint in title.find_all('span', attrs={'class': 'subbuzz__number'}):\r\n if subpoint:\r\n subpoint_check = True\r\n break\r\n\r\n if not subpoint_check:\r\n continue\r\n\r\n for article in title.find_all('span', attrs={'class': 'js-subbuzz__title-text'}):\r\n if len(article.text)<4 or article.text.endswith(':'):\r\n return ''\r\n else:\r\n top_x_final_temp = top_x_final\r\n if this_when_counter == 3:\r\n return ''\r\n\r\n if article.text.startswith(('When ', 'This ', 'And this ')):\r\n this_when_counter += 1\r\n else:\r\n this_when_counter = 0\r\n try:\r\n for link in article.find_all('a', href=True):\r\n if 'amazon' in link['href']:\r\n link_to_use = link['href'].split('?', 1)[0]\r\n else:\r\n link_to_use = link['href']\r\n\r\n if link_to_use.startswith('http:') and (r'/https:' in link_to_use or r'/http:' in link_to_use): #removes redirect link if there is any\r\n link_to_use = 'http' + link_to_use.split(r'/http', 1)[1]\r\n\r\n link_to_use = link_to_use.replace(')', r'\\)')\r\n\r\n if article.text.startswith((str(i)+'.' , str(i)+')')):\r\n top_x_final += '[' + article.text + '](' + link_to_use + ')' + '\\n'\r\n else:\r\n top_x_final += str(i) + '. ' + '[' + article.text + '](' + link_to_use + ')' + '\\n'\r\n break\r\n except KeyError:\r\n pass\r\n if top_x_final_temp == top_x_final:\r\n if article.text.startswith(str(i)+')'):\r\n article.text.replace(str(i)+')', str(i)+'. ')\r\n if article.text.startswith(str(i)+'.'):\r\n top_x_final += article.text + '\\n'\r\n else:\r\n top_x_final += str(i) + '. '+ article.text + '\\n'\r\n i += 1\r\n\r\n if total_points != i-1:\r\n top_x_final = ''\r\n return top_x_final\r\n\r\n\r\ndef url_to_search():\r\n\r\n yesterday = date.today() - timedelta(1)\r\n date_format = yesterday.strftime(\"%Y/%m/%d\")\r\n\r\n article_count = total_articles_today()\r\n\r\n article_info(date_format, article_count)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n my_subreddit = 'buzzfeedbot'\r\n website_name = 'BuzzFeed'\r\n archive_link = 'https://www.buzzfeed.com/archive/'\r\n\r\n start_time = round(time.time(), 2)\r\n\r\n post_reset()\r\n\r\n print('Searching Yesterdays Archive')\r\n url_to_search()\r\n\r\n print('Script ran for ' + str(round(((time.time()-start_time)),2)) + ' seconds')\r\n\r\n","sub_path":"Archive Parser Scripts/buzzfeedbot.py","file_name":"buzzfeedbot.py","file_ext":"py","file_size_in_byte":10487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"225969425","text":"# coding=utf8\n\"\"\"\nmcstatus.py - Check minecraft server status / services related things -- Uses Dinnerbone's python server status lib\nCopyright 2014 Max Gurela\n\nLicensed under the Eiffel Forum License 2.\n\"\"\"\n\nfrom mcstatus import MinecraftServer\nfrom willie.module import commands\nfrom willie import web\nfrom willie.formatting import color,bold\nimport json\nimport re\n\n@commands('status','ping')\ndef status(bot, trigger):\n \"\"\"\n .status - Grabs information about a minecraft server!\n \"\"\"\n try:\n server = MinecraftServer.lookup(trigger.group(3).strip())\n except Exception:\n bot.say(u'[MCS] Unable to find a Minecraft server running at \\'{}\\''.format(trigger.group(3).strip()))\n\n try:\n status = server.status()\n desc = ' '.join(re.sub(u'\\u00A7.', '', status.description).split())\n bot.say(u'[MCS] {0} | {1} players | {2} ms | {3}'.format(trigger.group(3).strip(), status.players.online, status.latency, desc))\n except Exception as e:\n bot.say(u'[MCS] Unable to fetch info from \\'{}\\' ({})'.format(trigger.group(3).strip(), e))\n\n@commands('mcstatus','mcs')\ndef mcstats(bot, trigger):\n \"\"\"\n .mcstatus - Check the status of Mojang's servers\n \"\"\"\n try:\n raw = web.get('https://status.mojang.com/check')\n\n response = json.loads(raw.replace(\"}\", \"\").replace(\"{\", \"\").replace(\"]\", \"}\").replace(\"[\", \"{\"))\n \n out = []\n # use a loop so we don't have to update it if they add more servers\n for server, status in response.items():\n out.append(u'{} {} '.format(server, format_status(status)))\n bot.say(''.join(out))\n except Exception as e:\n bot.say('[MCS] Mojang server status check is currently offline. ({})'.format(e))\n\n@commands('mcpaid','haspaid')\ndef mcpaid(bot, trigger):\n \"\"\"\n .mcpaid - Checks if has a premium Minecraft account.\n \"\"\" \n users = trigger.group(2).strip()\n for user in users.split():\n has_paid(bot, user)\n\ndef has_paid(bot, user):\n status = web.get('https://www.minecraft.net/haspaid.jsp?user={}'.format(user))\n if 'true' in status:\n bot.say('The account \\'{}\\' is a premium Minecraft account!'.format(user))\n else:\n bot.say('The account \\'{}\\' is not a premium Minecraft account!'.format(user))\n\n\ndef format_status(status):\n return status.replace('red', color(u'\\u2718', 'red')).replace('green', color(u'\\u2713', 'green')).replace('yellow', color(u'~', 'yellow'))\n","sub_path":"mcs.py","file_name":"mcs.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"87686097","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[47]:\n\n\nimport random\n\nclass Player:\n \n def __init__(self, health = 100):\n self.health = health\n \n def take_damage(self, damage):\n self.health -= damage\n\nai = Player()\nhuman = Player()\n\nplaying = True\n\nhuman_player_active = True\n\ndef ask_action():\n pass\n\ndef weak_punch():\n \n hit_strength = random.randint(18, 25)\n \n if human_player_active:\n \n if hit_strength >= ai.health:\n player_win()\n \n else:\n ai.take_damage(hit_strength)\n print(f'\\nYou used the Cautious Punch, hitting the enemy for {hit_strength}. They have {ai.health} health left.')\n \n else:\n \n if hit_strength >= human.health:\n ai_win()\n \n else: \n human.health -= hit_strength\n print(f'\\nThe enemy used the Cautious Punch, hitting you for {hit_strength}. You got {human.health} health left.')\n \n\ndef strong_punch():\n hit_strength = random.randint(10, 35)\n \n if human_player_active:\n \n if hit_strength >= ai.health:\n player_win()\n \n else:\n ai.take_damage(hit_strength)\n print(f'\\nYou used the Reckless Punch, hitting the enemy for {hit_strength}. They have {ai.health} health left.')\n \n else:\n \n if hit_strength >= human.health:\n ai_win()\n \n else: \n human.health -= hit_strength\n print(f'\\nThe enemy used the Reckless Punch, hitting you for {hit_strength}. You got {human.health} health left.')\n \ndef heal():\n if human_player_active:\n human.take_damage(-10)\n if human.health > 100:\n human.health = 100\n print(f'\\nYou healed 10 and now have {human.health} left.')\n \n else:\n ai.take_damage(-10)\n if ai.health > 100:\n ai.health = 100\n print(f'\\nThe enemy healed 10 and now has {ai.health} left.')\ndef ai_action():\n # while health >90 do not heal\n # while health low more likely to heal\n pass\n\n# def check_death():\n# pass\n\n\n# In[39]:\n\n\ndef player_win():\n print(f'You got him for {hit_strength}, bringing his health down to 0. You won!\\n')\n # decision = lower(input('Play again? y/n '))\n # if decision[0] == 'y':\n # pass\n # else:\n # playing = False\n # break\n playing = False\n\ndef ai_win():\n pass\n\n\n# In[48]:\n\n\nweak_punch()\n\n\n# In[49]:\n\n\nhuman.take_damage(30)\n\n\n# In[51]:\n\n\nhuman.health\n\n\n# In[55]:\n\n\nheal()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"battle game.py","file_name":"battle game.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"585409296","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\n# Convolutional network\nclass ConvNet(nn.Module):\n def __init__(self):\n super(ConvNet, self).__init__()\n # Convolutional layers for left image\n self.conv1_l = nn.Conv2d(1, 16, kernel_size=3)\n self.conv2_l = nn.Conv2d(16, 32, kernel_size=3)\n\n # Convolutional layers for right image\n self.conv1_r = nn.Conv2d(1, 16, kernel_size=3)\n self.conv2_r = nn.Conv2d(16, 32, kernel_size=3)\n\n # Fully connected layers for left image class prediction\n self.fc1_class_l = nn.Linear(128, 64)\n self.fc2_class_l = nn.Linear(64, 10)\n\n # Fully connected layers for right image class prediction\n self.fc1_class_r = nn.Linear(128, 64)\n self.fc2_class_r = nn.Linear(64, 10)\n\n # Fully connected layers for binary target prediction\n self.fc1_target = nn.Linear(256, 64)\n self.fc2_target = nn.Linear(64, 32)\n self.fc3_target = nn.Linear(32 + 2 * 10, 32)\n self.fc4_target = nn.Linear(32, 2)\n\n def forward(self, x, weight_sharing):\n # We split the pair into the left and right images\n x1 = x[:, 0, :, :].view(-1, 1, 14, 14)\n x2 = x[:, 1, :, :].view(-1, 1, 14, 14)\n\n x1 = F.leaky_relu(F.max_pool2d(self.conv1_l(x1), 2))\n x1 = F.leaky_relu(F.max_pool2d(self.conv2_l(x1), 2))\n if weight_sharing:\n # Use the same layers for both images\n x2 = F.leaky_relu(F.max_pool2d(self.conv1_l(x2), 2))\n x2 = F.leaky_relu(F.max_pool2d(self.conv2_l(x2), 2))\n else:\n # Use different layers\n x2 = F.leaky_relu(F.max_pool2d(self.conv1_r(x2), 2))\n x2 = F.leaky_relu(F.max_pool2d(self.conv2_r(x2), 2))\n\n # We merge the features gathered for both images\n x = torch.cat((x1, x2), 1)\n\n # We flatten everything to start the classification part\n x = x.view(x.size(0), -1)\n x1 = x1.view(x1.size(0), -1)\n x2 = x2.view(x2.size(0), -1)\n\n x1 = F.leaky_relu(self.fc1_class_l(x1))\n x1 = self.fc2_class_l(x1)\n if weight_sharing:\n # Use the same layers for both images\n x2 = F.leaky_relu(self.fc1_class_l(x2))\n x2 = self.fc2_class_l(x2)\n else:\n # Use different layers\n x2 = F.leaky_relu(self.fc1_class_r(x2))\n x2 = self.fc2_class_r(x2)\n\n x = F.leaky_relu(self.fc1_target(x))\n x = F.leaky_relu(self.fc2_target(x))\n\n # We add the classes predictions as features to predict the target\n x = torch.cat((x, x1, x2), 1)\n\n x = F.leaky_relu(self.fc3_target(x))\n x = self.fc4_target(x)\n\n # We return the predictions for the binary target, the left class and the right class\n return x, x1, x2\n","sub_path":"Proj1/convnet.py","file_name":"convnet.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"573305184","text":"from typing import Deque, List\n\nfrom picotui.defs import (C_B_WHITE, C_BLACK, C_GRAY, C_GREEN, C_WHITE,\n KEY_ENTER)\nfrom picotui.editorext import Viewer\nfrom picotui.screen import Screen\nfrom picotui.widgets import WListBox\n\nfrom yatrc.model import Post\n\n\n# pylint: disable=too-many-ancestors\nclass VerboseWidget(Viewer):\n def __init__(self, actions: Deque):\n width, height = Screen.screen_size()\n super().__init__(0, 0, width, height)\n self.actions = actions\n self.w = width # pylint: disable=invalid-name\n self.h = height # pylint: disable=invalid-name\n self.focus = False\n\n def redraw(self):\n if self.focus:\n super().redraw()\n\n def handle_key(self, key):\n if key == KEY_ENTER:\n self.actions.append('list')\n return None\n return super().handle_key(key)\n\n def set_post(self, post: Post):\n text = post.verbose_view(self.width)\n self.set_lines(text)\n self.top_line = 0\n self.cur_line = 0\n self.row = 0\n self.adjust_cursor_eol()\n self.redraw()\n\n\nclass PostsWidget(WListBox):\n def __init__(self, items: List[str], actions: Deque):\n width, height = Screen.screen_size()\n super().__init__(width, height, items)\n default_style = (C_B_WHITE, C_GRAY)\n self.styles = [default_style] * len(items)\n self.actions = actions\n\n def redraw(self):\n if self.focus:\n super().redraw()\n\n def show_line(self, line, i):\n hlite = self.cur_line == i\n if hlite:\n if self.focus:\n self.attr_color(C_WHITE, C_GREEN)\n else:\n self.attr_color(C_BLACK, C_GREEN)\n if i != -1:\n if not hlite:\n self.attr_color(*self.styles[i])\n line = self.render_line(line)[:self.width]\n self.wr(line)\n self.clear_num_pos(self.width - len(line))\n self.attr_reset()\n\n def handle_key(self, key):\n if key == KEY_ENTER:\n self.styles[self.cur_line] = (C_BLACK, C_GRAY)\n self.actions.append('verbose')\n return super().handle_key(key)\n","sub_path":"yatrc/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"396778583","text":"# Copyright 2019-2020 SURF.\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 types import new_class\nfrom typing import Any, ClassVar, Dict, Generator, List, Optional, Sequence, Type, TypeVar, get_args\nfrom uuid import UUID\n\nimport structlog\nfrom pydantic import BaseModel, ConstrainedList, EmailStr\nfrom pydantic.errors import EnumMemberError\nfrom pydantic.fields import ModelField\nfrom pydantic.utils import update_not_none\nfrom pydantic.validators import str_validator, uuid_validator\n\nfrom orchestrator.forms import DisplayOnlyFieldType\nfrom orchestrator.services import products\nfrom orchestrator.types import AcceptData, SummaryData, strEnum\n\nlogger = structlog.get_logger(__name__)\n\n\nT = TypeVar(\"T\") # pragma: no mutate\n\n\nclass UniqueConstrainedList(ConstrainedList, List[T]):\n unique_items: Optional[bool] = None\n\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n super().__modify_schema__(field_schema)\n update_not_none(field_schema, uniqueItems=cls.unique_items)\n\n @classmethod\n def __get_validators__(cls) -> Generator: # noqa: B902\n yield from super().__get_validators__()\n if cls.unique_items is not None:\n yield cls.check_unique\n\n @classmethod\n def check_unique(cls, v: List[T]) -> List[T]:\n if len(set(v)) != len(v):\n raise ValueError(\"Items must be unique\")\n\n return v\n\n def __init_subclass__(cls, **kwargs: Any) -> None:\n super().__init_subclass__(**kwargs) # type:ignore\n\n # Copy generic argument (T) if not set explicitly\n # This makes a lot of assuptions about the internals of `typing`\n if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]:\n generic_base_cls = cls.__dict__[\"__orig_bases__\"][0]\n if (not hasattr(cls, \"item_type\") or isinstance(cls.item_type, TypeVar)) and get_args(generic_base_cls):\n cls.item_type = get_args(generic_base_cls)[0]\n\n # Make sure __args__ is set\n assert hasattr(cls, \"item_type\"), \"Missing a concrete value for generic type argument\" # noqa: S101\n\n cls.__args__ = (cls.item_type,)\n\n def __class_getitem__(cls, key: Any) -> Any:\n # Some magic to make sure that subclasses of this class still work as expected\n class Inst(cls): # type: ignore\n item_type = key\n __args__ = (key,)\n\n return Inst\n\n\ndef unique_conlist(\n item_type: Type[T],\n *,\n min_items: Optional[int] = None,\n max_items: Optional[int] = None,\n unique_items: Optional[bool] = None,\n) -> Type[List[T]]:\n namespace = {\n \"min_items\": min_items,\n \"max_items\": max_items,\n \"unique_items\": unique_items,\n \"__origin__\": list, # Needed for pydantic to detect that this is a list\n \"__args__\": (item_type,), # Needed for pydantic to detect the item type\n }\n # We use new_class to be able to deal with Generic types\n return new_class(\n \"ConstrainedListValue\", (UniqueConstrainedList[item_type],), {}, lambda ns: ns.update(namespace) # type:ignore\n )\n\n\ndef remove_empty_items(v: list) -> list:\n \"\"\"Remove Falsy values from list.\n\n Sees dicts with all Falsy values as Falsy.\n This is used to allow people to submit list fields which are \"empty\" but are not really empty like:\n `[{}, None, {name:\"\", email:\"\"}]`\n\n Example:\n >>> remove_empty_items([{}, None, [], {\"a\":\"\"}])\n []\n \"\"\"\n if v:\n return list(filter(lambda i: bool(i) and (not isinstance(i, dict) or any(i.values())), v))\n return v\n\n\nclass Accept(str):\n data: ClassVar[Optional[AcceptData]] = None\n\n class Values(strEnum):\n ACCEPTED = \"ACCEPTED\"\n INCOMPLETE = \"INCOMPLETE\"\n\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n field_schema.update(\n format=\"accept\",\n type=\"string\",\n enum=[v.value for v in cls.Values],\n **({\"data\": cls.data} if cls.data else {}),\n )\n\n @classmethod\n def __get_validators__(cls) -> Generator:\n yield cls.enum_validator\n yield cls.must_be_complete\n\n @classmethod\n def enum_validator(cls, v: Any, field: \"ModelField\") -> str:\n try:\n enum_v = cls.Values(v)\n except ValueError:\n # cls.Values should be an enum, so will be iterable\n raise EnumMemberError(enum_values=list(cls.Values))\n return enum_v.value\n\n @classmethod\n def must_be_complete(cls, v: str) -> bool:\n if v == \"INCOMPLETE\":\n raise ValueError(\"Not all tasks are done\")\n\n return v == \"ACCEPTED\"\n\n\nclass Choice(strEnum):\n label: ClassVar[str]\n\n def __new__(cls, value: str, label: Optional[str] = None) -> \"Choice\":\n obj = str.__new__(cls, value)\n obj._value_ = value\n obj.label = label or value # type:ignore\n return obj\n\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n\n kwargs = {}\n\n options = dict(map(lambda i: (i.value, i.label), cls.__members__.values()))\n\n if not all(map(lambda o: o[0] == o[1], options.items())):\n kwargs[\"options\"] = options\n\n field_schema.update(type=\"string\", **kwargs)\n\n\nclass ChoiceList(UniqueConstrainedList[T]):\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n super().__modify_schema__(field_schema)\n\n data: dict = {}\n cls.item_type.__modify_schema__(data) # type: ignore\n field_schema.update(**{k: v for k, v in data.items() if k == \"options\"})\n\n\ndef choice_list(\n item_type: Type[Choice],\n *,\n min_items: Optional[int] = None,\n max_items: Optional[int] = None,\n unique_items: Optional[bool] = None,\n) -> Type[List[T]]:\n namespace = {\n \"min_items\": min_items,\n \"max_items\": max_items,\n \"unique_items\": unique_items,\n \"__origin__\": list, # Needed for pydantic to detect that this is a list\n \"item_type\": item_type, # Needed for pydantic to detect the item type\n \"__args__\": (item_type,), # Needed for pydantic to detect the item type\n }\n # We use new_class to be able to deal with Generic types\n return new_class(\n \"ChoiceListValue\", (ChoiceList[item_type],), {}, lambda ns: ns.update(namespace) # type:ignore\n )\n\n\nclass ContactPersonName(str):\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n field_schema.update(format=\"contactPersonName\")\n\n\nclass ContactPerson(BaseModel):\n name: ContactPersonName\n email: EmailStr\n phone: str = \"\"\n\n\nclass ContactPersonList(ConstrainedList):\n item_type = ContactPerson\n __args__ = (ContactPerson,)\n\n organisation: ClassVar[Optional[UUID]] = None\n organisation_key: ClassVar[Optional[str]] = \"organisation\"\n\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n super().__modify_schema__(field_schema)\n data = {}\n\n if cls.organisation:\n data[\"organisationId\"] = str(cls.organisation)\n if cls.organisation_key:\n data[\"organisationKey\"] = cls.organisation_key\n\n field_schema.update(**data)\n\n @classmethod\n def __get_validators__(cls) -> Generator:\n yield from super().__get_validators__()\n yield remove_empty_items\n\n # TODO: Validatie organisation?\n\n\ndef contact_person_list(\n organisation: Optional[UUID] = None, organisation_key: Optional[str] = \"organisation\"\n) -> Type[List[T]]:\n namespace = {\"organisation\": organisation, \"organisation_key\": organisation_key}\n # We use new_class to be able to deal with Generic types\n return new_class(\"ContactPersonListValue\", (ContactPersonList,), {}, lambda ns: ns.update(namespace))\n\n\nclass LongText(str):\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n field_schema.update(format=\"long\", type=\"string\")\n\n @classmethod\n def __get_validators__(cls) -> Generator:\n yield str_validator\n\n\nclass DisplaySubscription(DisplayOnlyFieldType):\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n field_schema.update(format=\"subscription\", type=\"string\")\n\n\nclass Label(DisplayOnlyFieldType):\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n field_schema.update(format=\"label\", type=\"string\")\n\n\nclass OrganisationId(UUID):\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n field_schema.update(format=\"organisationId\")\n\n @classmethod\n def __get_validators__(cls) -> Generator:\n yield uuid_validator\n\n # TODO: Check if org exists?\n\n\nclass ProductIdError(EnumMemberError):\n code = \"product_id\"\n enum_values: Sequence[Any] # Required kwarg\n\n def __str__(self) -> str:\n permitted = \", \".join(repr(v) for v in self.enum_values)\n return f\"value is not a valid enumeration member; permitted: {permitted}\"\n\n\nclass ProductId(UUID):\n products: Optional[List[UUID]] = None\n\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n kwargs = {\"uniforms\": {\"productIds\": cls.products}} if cls.products else {}\n field_schema.update(format=\"productId\", **kwargs)\n\n @classmethod\n def __get_validators__(cls) -> Generator:\n yield uuid_validator\n yield cls.is_product\n if cls.products:\n yield cls.in_products\n\n @classmethod\n def is_product(cls, v: UUID) -> UUID:\n product = products.get_product_by_id(v)\n if product is None:\n raise ValueError(\"Product not found\")\n\n return v\n\n @classmethod\n def in_products(cls, v: UUID) -> UUID:\n if cls.products and v not in cls.products:\n raise ProductIdError(enum_values=list(map(str, cls.products)))\n\n return v\n\n\ndef product_id(products: Optional[List[UUID]] = None) -> Type[ProductId]:\n namespace = {\"products\": products}\n return new_class(\"ProductIdSpecific\", (ProductId,), {}, lambda ns: ns.update(namespace))\n\n\nclass MigrationSummary(DisplayOnlyFieldType):\n data: ClassVar[Optional[SummaryData]] = None\n\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n field_schema.update(format=\"summary\", type=\"string\", uniforms={\"data\": cls.data})\n\n\ndef migration_summary(data: Optional[SummaryData] = None) -> Type[MigrationSummary]:\n namespace = {\"data\": data}\n return new_class(\"MigrationSummaryValue\", (MigrationSummary,), {}, lambda ns: ns.update(namespace))\n\n\nclass ListOfOne(UniqueConstrainedList[T]):\n min_items = 1\n max_items = 1\n\n\nclass ListOfTwo(UniqueConstrainedList[T]):\n min_items = 2\n max_items = 2\n","sub_path":"orchestrator/forms/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":11312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"270818607","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib import messages\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth import authenticate, login, logout\nfrom blogapp.views import *\nfrom blogapp.models import *\nfrom albums.models import *\nfrom albums.forms import *\nfrom blogapp.forms import *\nfrom django.utils import timezone\nfrom django.http import HttpResponseRedirect, HttpResponse, HttpResponseServerError, JsonResponse\nimport json\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n# Create your views here.\n\n@login_required\ndef album_create(request):\n form = AlbumForm()\n if request.POST:\n form = AlbumForm(request.POST)\n if form.is_valid():\n f = form.save(commit=False)\n f.author = request.user\n f.save()\n return redirect('album_view', f.id)\n else:\n messages.error(request, 'Error while creating album.')\n context = {'form': form}\n return render(request, 'album_add.html', context)\n\n\ndef album_view(request, album_id):\n try:\n album = PhotoAlbum.objects.get(id=album_id)\n # this is a shitode i am really sorry you had to see this\n if album.privacy is not PhotoAlbum.private or album.privacy is not PhotoAlbum.unlisted or request.user is not album.author:\n photos_list = album.images.all().order_by('-uploaded_at')\n page = request.GET.get('page', 1)\n if photos_list:\n paginator = Paginator(photos_list, 20)\n try:\n photos = paginator.page(page)\n except PageNotAnInteger:\n photos = paginator.page(1)\n except EmptyPage:\n photos = paginator.page(paginator.num_pages)\n else:\n photos = None\n context = {'album': album, 'photos': photos}\n return render(request, 'album_view.html', context)\n else:\n messages.error(request, 'Album is private')\n except ObjectDoesNotExist:\n messages.error('Album with such id does not exist.')\n\n\ndef image_add(request, album_id):\n try:\n album = PhotoAlbum.objects.get(id=album_id)\n if request.user == album.author and not album.automatic:\n form = ImageForm()\n if request.POST:\n form = ImageForm(request.POST, request.FILES)\n if form.is_valid():\n f = form.save(commit=False)\n f.author = request.user\n f.album = album\n f.save()\n f.album.images.add(f)\n messages.info(request, 'Image has been added.')\n return redirect('image_view', album.id, f.id)\n else:\n messages.error(request, 'An error has occured.')\n context= {'album': album, 'form': form}\n return render(request, 'image_add.html', context)\n else:\n messages.error(request, 'You are not the album owner')\n except ObjectDoesNotExist:\n messages.error('Album with such id does not exist.')\n\n\ndef image_view(request, album_id, image_id):\n try:\n album = PhotoAlbum.objects.get(id=album_id)\n img = Image.objects.filter(album=album).get(id=image_id)\n if album.privacy is not PhotoAlbum.private or request.user is not album.author:\n form = PhotoCommentForm()\n if 'profilepic' in request.POST:\n img = Image.objects.get(id=request.POST['image_id'])\n request.user.extuser.avatar.name = img.document.name\n request.user.extuser.save()\n messages.info(request, 'Profile picture has been changed.')\n if 'add' in request.POST:\n form = PhotoCommentForm(request.POST)\n if form.is_valid():\n f = form.save(commit=False)\n if request.user.is_authenticated():\n f.author = request.user\n f.image = img\n f.save()\n form = PhotoCommentForm()\n messages.info(request, 'Comment has been added.')\n else:\n messages.error(request, 'Fill in the comment data correctly.')\n comments_list = PhotoComment.objects.filter(image=img).order_by('-date') or None\n page = request.GET.get('page', 1)\n if comments_list:\n paginator = Paginator(comments_list, 10)\n try:\n comments = paginator.page(page)\n except PageNotAnInteger:\n comments = paginator.page(1)\n except EmptyPage:\n comments = paginator.page(paginator.num_pages)\n else:\n comments = None\n context = {'img': img, 'form': form, 'comments': comments}\n return render(request, 'image_view.html', context)\n except ObjectDoesNotExist:\n messages.error(request, 'Image does not exist.')\n\n\ndef profile_albums(request, username):\n try:\n user = User.objects.get(username=username)\n if request.user != user:\n albums_list = PhotoAlbum.objects.filter(author=user).filter(privacy=PhotoAlbum.public) or None\n else:\n albums_list = PhotoAlbum.objects.filter(author=user) or None\n page = request.GET.get('page', 1)\n if albums_list:\n paginator = Paginator(albums_list, 10)\n try:\n albums = paginator.page(page)\n except PageNotAnInteger:\n albums = paginator.page(1)\n except EmptyPage:\n albums = paginator.page(paginator.num_pages)\n else:\n albums = None\n context = {'albums': albums}\n return render(request, 'profile_albums.html', context)\n except ObjectDoesNotExist:\n messages.error(request, 'User does not exist')\n\n\ndef avatars_album(user, files=None):\n avatar_album, created = PhotoAlbum.objects.get_or_create(author=user, name='ProfilePictures', automatic=True, privacy=PhotoAlbum.private)\n avatar_album.save()\n try:\n avatar_image = Image.objects.create(author=user, album=avatar_album, document=user.extuser.avatar)\n avatar_image.save()\n avatar_album.images.add(avatar_image)\n except Exception as e:\n print(e)\n\n","sub_path":"albums/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"326794057","text":"import uuid\nimport json\nimport logging\nfrom hashlib import sha256\nfrom datetime import datetime\nfrom pydantic import BaseModel\nfrom ..util import HelperEncoder\n\n\nclass Block:\n def __init__(self, id, data, block_type, timestamp: datetime, previous_hash,\n data_collection_name, data_key_field_name, data_key_value):\n self.id = id\n self.block_type = block_type\n self.timestamp = timestamp\n self.previous_hash = previous_hash\n self.data = json.dumps(data, cls=HelperEncoder)\n\n logging.debug(json.dumps(self.__dict__, sort_keys=True, cls=HelperEncoder))\n\n self.hash = sha256(json.dumps(self.__dict__, sort_keys=True, cls=HelperEncoder).encode()) \\\n .hexdigest()\n self.data_collection_name = data_collection_name\n self.data_key_field_name = data_key_field_name\n self.data_key_value = data_key_value\n self.superceded = False\n\n def get_naked_block(self):\n return NakedBlock(self.id, self.timestamp, self.block_type, self.hash, self.previous_hash)\n\n def get_data_block(self):\n return DataBlock(self.timestamp, self.data_collection_name,\n self.data, self.hash, self.block_type, self.superceded)\n\n\nclass NakedBlock:\n def __init__(self, id, timestamp, block_type, hash, previous_hash):\n self.id = id\n self.block_type = block_type\n self.timestamp = timestamp\n self.previous_hash = previous_hash\n self.hash = hash\n\n\nclass DataBlock:\n def __init__(self, timestamp, data_collection_name, data, hash, block_type, superceded):\n self.timestamp = timestamp\n self.collection = data_collection_name\n self.block_type = block_type\n self.data = data\n self.superceded = superceded\n self.hash = hash\n\n def set_superceded(self):\n self.superceded = True\n\n def get_document(self):\n document = json.loads(self.data)\n document['hash_id'] = self.hash\n document['block_type'] = self.block_type\n document['superceded'] = self.superceded\n return document\n\n\ndef block_types_lookup(block_type):\n block_types = {\"CREATE\": 0, \"GRANT\": 1, \"EDIT\": 2}\n return block_types[block_type]\n\n\ndef block_types_reverse_lookup(block_type):\n print(block_type)\n block_types = {0: \"CREATE\", 1: \"GRANT\", 2: \"EDIT\"}\n return block_types[block_type]\n\n\nclass ProposedBlock(BaseModel):\n id: str\n block_type: str\n timestamp: str\n data: str\n data_collection_name: str\n data_key_field_name: str\n data_key_value: str\n\n\ndef generate_block(data, block_type, timestamp: datetime, previous_hash,\n data_collection_name, data_key_field_name, data_key_value):\n return Block(uuid.uuid4().hex, data, block_type, timestamp, previous_hash,\n data_collection_name, data_key_field_name, data_key_value)\n\ndef generate_audit_block(id, data, block_type, timestamp: datetime, previous_hash):\n del data[\"hash_id\"]\n return Block(id, data, block_type, timestamp, previous_hash, '', '', '')\n\n\ndef generate_from_proposed_block(proposed_block: ProposedBlock, previous_hash):\n return Block(proposed_block.id, json.loads(proposed_block.data),\n proposed_block.block_type, proposed_block.timestamp, previous_hash,\n proposed_block.data_collection_name, proposed_block.data_key_field_name,\n proposed_block.data_key_value)\n","sub_path":"example/app/api/blockchain/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"242590356","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 24 14:18:23 2020\n\n@author: Student 201386558\nUniveristy of Leeds\n\nCreates an empty list, populates it with ten agents at random positions.\nMoves each agent in turn randomly 100 times\nUses a function to calculate distance between agents passed to it\nLoops to pass two agents at a time to dstance function\nPlots final postitions on a scatter plot \n\"\"\"\n\nimport random, matplotlib.pyplot\n\n# Function to calculates distance between 2 agents passed into function\ndef distance_between(agents_row_a, agents_row_b):\n distance = (((agents_row_a[0] - agents_row_b[0])**2) + ((agents_row_a[1] - agents_row_b[1])**2))**0.5\n return distance\n\n# Create an empty agent list and \nnum_of_agents = 10\nnum_of_iterations = 100\nagents = []\n\n# Create agents \nfor i in range(num_of_agents):\n agents.append([random.randint(0,99), random.randint(0,99)])\n\n# Move each agent in turn by one position 100 times \nfor j in range(num_of_iterations):\n for i in range(num_of_agents):\n #print(j, i)\n if random.random() < 0.5:\n agents[i][0] = (agents[i][0] + 1) % 100\n else:\n agents[i][0] = (agents[i][0] - 1) % 100\n\n if random.random() < 0.5:\n agents[i][1] = (agents[i][1] + 1) % 100\n else:\n agents[i][1] = (agents[i][1] - 1) % 100\n\n# Calculate distance between agents \nfor i in range(num_of_agents):\n for j in range(i, num_of_agents):\n if i != j:\n distance = distance_between(agents[i], agents[j])\n print(agents[i], agents[j], \" are \", distance, \"apart\")\n else:\n pass\n'''\nprint(max(agents, key=operator.itemgetter(1)))\npythag = (((agents[0][0] - agents[1][0])**2) + ((agents[0][1] - agents[1][1])**2))**0.5\nprint(agents[1][1], agents[1][0], agents[0][1], agents[0][0], pythag)\n'''\n\n# Plot the agents positions \nmatplotlib.pyplot.ylim(0, 99)\nmatplotlib.pyplot.xlim(0, 99)\nfor i in range(num_of_agents):\n matplotlib.pyplot.scatter(agents[i][1],agents[i][0], color='green')\nmatplotlib.pyplot.show()","sub_path":"src/unpackaged/abm/BuildingTools/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"83057451","text":"# imports\nif __name__ == \"__main__\":\n from configs import config\n from configs.detection import detect_people\nelse:\n from .configs import config\n from .configs.detection import detect_people\n\nfrom scipy.spatial import distance as dist \nimport numpy as np\nfrom argparse import ArgumentParser\nfrom imutils import resize\nimport cv2\nimport os\nfrom dataclasses import dataclass\n\n__net = None\n__LABELS = None\n__ln = None\n\n@dataclass(frozen=True)\nclass Args:\n input : str\n output : str\n target : str\n display : bool\n\n@dataclass(frozen=True)\nclass FrameArgs:\n input : str\n path : str\n target : str\n\ndef getArgs() -> Args:\n \"\"\"\n Construct the argument parser and parse the arguments\n \"\"\"\n ap = ArgumentParser(description=\n \"\"\"\n Program that gets a video file from disk and uses the YOLO-Coco network \n \"\"\")\n ap.add_argument(\"input\" , type=str , help=\"path to input video file\")\n ap.add_argument(\"-o\", \"--output\" , type=str , default=\"\", help=\"path to output video file\")\n ap.add_argument(\"-t\", \"--target\" , type=str , nargs=\"?\", default=\"person\", help=\"target tag to look for in the video stream DEFAULTS TO 'person'\")\n ap.add_argument(\"-d\", \"--display\" , type=bool , nargs=\"?\", default=False, const=True, help=\"whether or not output frame should be displayed\")\n\n temp = ap.parse_args()\n return Args(temp.input, temp.output, temp.target, temp.display)\n\ndef setUpNN():\n global __net, __LABELS, __ln\n # load the COCO class labels the YOLO model was trained on\n labelsPath = os.path.sep.join([config.MODEL_PATH, \"coco.names\"])\n __LABELS = open(labelsPath).read().strip().split(\"\\n\")\n\n # derive the paths to the YOLO weights and model configuration\n weightsPath = os.path.sep.join([config.MODEL_PATH, \"yolov3.weights\"])\n configPath = os.path.sep.join([config.MODEL_PATH, \"yolov3.cfg\"])\n\n # load the YOLO object detector trained on COCO dataset (80 classes)\n print(\"[INFO] loading YOLO from disk...\")\n __net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)\n \n\n # check if GPU is to be used or not\n if config.USE_GPU:\n # set CUDA s the preferable backend and target\n print(\"[INFO] setting preferable backend and target to CUDA...\")\n __net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n # print(f\"cv2.dnn.DNN_BACKEND_CUDA {cv2.dnn.DNN_BACKEND_CUDA}\")\n __net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n # print(f\"cv2.dnn.DNN_TARGET_CUDA {cv2.dnn.DNN_TARGET_CUDA}\")\n\n # determine only the \"output\" layer names that we need from YOLO\n ln = __net.getLayerNames()\n __ln = [ln[i[0] - 1] for i in __net.getUnconnectedOutLayers()]\n\ndef video_stream_parser(vs, target: str, display=False):\n global __net, __ln, __LABELS\n # loop over the frames from the video stream\n while True:\n # read the next frame from the input video\n (grabbed, frame) = vs.read()\n\n # if the frame was not grabbed, then that's the end fo the stream \n if not grabbed:\n print(\"[INFO] Video Stream has ended\")\n yield False, None\n break\n\n # resize the frame and then detect people (only people) in it\n frame = resize(frame, width=700)\n results = detect_people(frame, __net, __ln, personIdx=__LABELS.index(target))\n\n # initialize the set of indexes that violate the minimum social distance\n violate = set()\n\n # ensure there are at least two people detections (required in order to compute the\n # the pairwise distance maps)\n if len(results) >= 2:\n # extract all centroids from the results and compute the Euclidean distances\n # between all pairs of the centroids\n centroids = np.array([r[2] for r in results])\n D = dist.cdist(centroids, centroids, metric=\"euclidean\")\n\n # loop over the upper triangular of the distance matrix\n for i in range(0, D.shape[0]):\n for j in range(i+1, D.shape[1]):\n # check to see if the distance between any two centroid pairs is less\n # than the configured number of pixels\n if D[i, j] < config.MIN_DISTANCE:\n # update the violation set with the indexes of the centroid pairs\n violate.add(i)\n violate.add(j)\n \n # loop over the results\n for (i, (prob, bbox, centroid)) in enumerate(results):\n # extract the bounding box and centroid coordinates, then initialize the color of the annotation\n (startX, startY, endX, endY) = bbox\n (cX, cY) = centroid\n color = (0, 255, 0)\n #result_text -> 'Low risk'\n\n # if the index pair exists within the violation set, then update the color\n if i in violate:\n color = (0, 0, 255)\n #result_text -> 'High Risk'\n\n # draw (1) a bounding box around the person \n cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)\n cv2.circle(frame, (cX, cY), 5, color, 1)\n\n # draw the total number of social distancing violations on the output frame\n text = \"Social Distancing Violations: {}\".format(len(violate))\n cv2.putText(frame, text, (10, frame.shape[0] - 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)\n\n # check to see if the output frame should be displayed to the screen\n if display:\n # show the output frame\n cv2.imshow(\"Output\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # if the 'q' key is pressed, break from the loop\n if key == ord(\"q\"):\n yield False, None\n break\n \n yield True, frame\n\ndef main(args : Args):\n # initialize the video stream and pointer to output video file\n print(\"[INFO] accessing video stream...\")\n # open input video if available else webcam stream\n vs = cv2.VideoCapture(args.input)\n writer = None\n\n streamer = video_stream_parser(vs, args.target, args.display)\n\n while True:\n\n cont, frame = next(streamer)\n\n if not cont:\n break\n\n # if an output video file path has been supplied and the video writer has not been \n # initialized, do so now\n if args.output != \"\" and writer is None:\n # initialize the video writer\n fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n writer = cv2.VideoWriter(args.output, fourcc, 25, (frame.shape[1], frame.shape[0]), True)\n\n # if the video writer is not None, write the frame to the output video file\n if writer is not None:\n writer.write(frame)\n\ndef predictFrames(args : FrameArgs):\n # initialize the video stream and pointer to output video file\n print(\"[INFO] accessing video stream...\")\n # open input video if available else webcam stream\n vs = cv2.VideoCapture(args.input)\n\n streamer = video_stream_parser(vs, args.target)\n\n count = 0\n\n # loop over the frames from the video stream\n while True:\n \n cont, frame = next(streamer)\n\n if not cont:\n break\n\n cv2.imwrite(f\"{args.path}frame{count}.jpg\",frame)\n count += 1\n\n# Regardless of the case we setup the NN for further use.\nsetUpNN()\n\nif __name__ == \"__main__\":\n # main(getArgs())\n predictFrames(FrameArgs(\"pedestrians.mp4\", \"frames/\", \"person\"))","sub_path":"social_distancing_detector.py","file_name":"social_distancing_detector.py","file_ext":"py","file_size_in_byte":7519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"212758036","text":"filename = \"/home/antonio/Progetto Grafica/lines/backwallB.lines\"\nlines = lines2lines(filename)\nrobiewall = STRUCT(AA(POLYLINE)(lines)) \nV,FV,EV,polygons = larFromLines(lines)\nFV.remove(FV[0])\nVV = AA(LIST)(range(len(V)))\nsubmodel = STRUCT(MKPOLS((V,EV)))\n#VIEW(larModelNumbering(1,1,1)(V,[VV,EV,FV],submodel,0.01))\n\nW = (((mat(V) - V[3]) * 438.31) + [.5,-.05]).tolist()\n\ntemp = [214.83359,119.97648900000002]\nW[4]=temp\nW[6]=[temp[0],W[6][1]]\ntemp = [212.64204,119.97648900000002]\nW[5]=temp\nW[7]=[temp[0],W[7][1]]\n\nbwBM = (W,FV)\nbwBP = [-5,alzo2]\nbwB = larModelProduct([bwBM,larQuote1D(bwBP)])\n\naltoAdx = [6]\naltoAsx = [7]\nbassoAsx = [5]\nbassoAdx = [4]\n\nW[6]=SUM([W[6],[0,larghezzaB]])\n\nfor k in altoAsx:\n\tW[k] = SUM([W[k],[-larghezzaB,larghezzaB]])\n\nW[5]=SUM([W[5],[-larghezzaB,0]])\n\nbwBGAPM = (W,FV)\nbwBGAPP = [-5,-alzo1,bordino]\n\nbwBGAP = larModelProduct([bwBGAPM,larQuote1D(bwBGAPP)])\n","sub_path":"266319/models/backwallB.py","file_name":"backwallB.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"241432147","text":"import os\nimport re\nfrom typing import Any, Dict, Iterator, List, Optional, Type\n\nimport pytest\n\nfrom determined.common import schemas, yaml\nfrom determined.common.schemas import expconf\nfrom determined.common.schemas.expconf import _v0\n\n\ndef strip_runtime_defaultable(obj: Any, defaulted: Any) -> Any:\n \"\"\"\n Recursively find strings of \"*\" in defaulted and set corresponding non-None values in obj to\n also be \"*\", so that equality tests will pass.\n \"\"\"\n if defaulted is None or obj is None:\n return obj\n\n if isinstance(defaulted, str):\n if defaulted == \"*\":\n return \"*\"\n\n # Recurse through dicts.\n if isinstance(defaulted, dict):\n if not isinstance(obj, dict):\n return obj\n return {k: strip_runtime_defaultable(obj.get(k), defaulted.get(k)) for k in obj}\n\n if isinstance(defaulted, tuple):\n defaulted = list(defaulted)\n\n # Recurse through lists.\n if isinstance(defaulted, list):\n if not isinstance(obj, (list, tuple)):\n return obj\n\n # Truncate defaulted (if it's long) then pad with Nones (if it's short).\n defaulted = defaulted[: len(obj)]\n defaulted = defaulted + [None] * (len(obj) - len(defaulted))\n\n return [strip_runtime_defaultable(o, d) for o, d in zip(obj, defaulted)]\n\n return obj\n\n\ndef class_from_url(url: str) -> Type[schemas.SchemaBase]:\n schema = expconf.get_schema(url)\n title = schema[\"title\"]\n\n cls = getattr(_v0, title + \"V0\")\n assert issubclass(cls, schemas.SchemaBase)\n return cls # type: ignore\n\n\nclass Case:\n def __init__(\n self,\n name: str,\n case: Any,\n sane_as: Optional[List[str]] = None,\n complete_as: Optional[List[str]] = None,\n sanity_errors: Optional[Dict[str, str]] = None,\n completeness_errors: Optional[Dict[str, str]] = None,\n defaulted: Any = None,\n default_as: Optional[str] = None,\n merge_as: Optional[str] = None,\n merge_src: Any = None,\n merged: Any = None,\n ) -> None:\n self.name = name\n self.case = case\n self.sane_as = sane_as\n self.complete_as = complete_as\n self.sanity_errors = sanity_errors\n self.completeness_errors = completeness_errors\n self.defaulted = defaulted\n self.default_as = default_as\n self.merge_as = merge_as\n self.merge_src = merge_src\n self.merged = merged\n\n def run(self) -> None:\n self.run_sanity()\n self.run_completeness()\n self.run_sanity_errors()\n self.run_completeness_errors()\n self.run_defaulted()\n self.run_round_trip()\n self.run_merged()\n\n def run_sanity(self) -> None:\n if not self.sane_as:\n return\n for url in self.sane_as:\n errors = expconf.sanity_validation_errors(self.case, url)\n if not errors:\n continue\n raise ValueError(f\"'{self.name}' failed against {url}:\\n - \" + \"\\n - \".join(errors))\n\n def run_completeness(self) -> None:\n if not self.complete_as:\n return\n for url in self.complete_as:\n errors = expconf.completeness_validation_errors(self.case, url)\n if not errors:\n continue\n raise ValueError(\n (\"'{}' failed completeness validation against {}:\\n - \" \"\\n - \")\n .format(self.name, url)\n .join(errors)\n )\n\n def run_sanity_errors(self) -> None:\n if not self.sanity_errors:\n return\n self._run_errors(self.sanity_errors, test_type=\"sanity\")\n\n def run_completeness_errors(self) -> None:\n if not self.completeness_errors:\n return\n self._run_errors(self.completeness_errors, test_type=\"completeness\")\n\n def _run_errors(self, error_cases: Any, test_type: str) -> None:\n for url, expected in error_cases.items():\n assert isinstance(expected, list), \"malformed test case\"\n if test_type == \"sanity\":\n errors = expconf.sanity_validation_errors(self.case, url)\n else:\n errors = expconf.completeness_validation_errors(self.case, url)\n assert errors, (\n f\"'{self.name}' {test_type} validated against {url} unexpectedly, \"\n f\"expected {expected}\"\n )\n for exp in expected:\n for err in errors:\n if re.search(exp, err):\n break\n else:\n msg = f\"while testing '{self.name}' for {test_type}, expected to match the\"\n msg += f\" pattern\\n {exp}\\n\"\n msg += \"but it was not found in any of\\n \"\n msg += \"\\n \".join(errors)\n raise ValueError(msg)\n\n def run_defaulted(self) -> None:\n if not self.defaulted and not self.default_as:\n return\n assert (\n self.defaulted and self.default_as\n ), \"`default_as` and `defaulted` must both be present to run a defaulted test\"\n cls = class_from_url(self.default_as)\n\n obj = cls.from_dict(self.case)\n obj.fill_defaults()\n\n out = obj.to_dict(explicit_nones=True)\n out = strip_runtime_defaultable(out, self.defaulted)\n assert out == self.defaulted, f\"failed while testing {self.name}\"\n\n def run_round_trip(self) -> None:\n if not self.defaulted:\n return\n\n assert self.default_as, \"need a `default_as` entry to run a run_round_trip test\"\n cls = class_from_url(self.default_as)\n\n obj0 = cls.from_dict(self.case)\n\n obj1 = cls.from_dict(obj0.to_dict())\n assert obj1 == obj0, \"round trip to_dict/from_dict failed\"\n\n # Round-trip again with defaults.\n obj1.fill_defaults()\n obj2 = cls.from_dict(obj1.to_dict())\n assert obj2 == obj1, \"round trip failed with defaults\"\n\n def run_merged(self) -> None:\n if not self.merge_as and not self.merge_src and not self.merged:\n return\n assert (\n self.merge_as and self.merge_src and self.merged\n ), \"merge_as, merge_src, and merged must all be present in a test case if any are present\"\n\n # Python expconf doesn't yet support custom merge behavior on list objects, nor does it\n # support the partial checkpoint storage configs. It probably will never support the\n # partial checkpoint storage (only the master needs it, and hopefully only for the V0\n # schema).\n pytest.skip(\"python expconf doesn't support merge tests yet\")\n\n cls = class_from_url(self.merge_as)\n\n obj = cls.from_dict(self.case)\n src = cls.from_dict(self.merge_src)\n\n merged = schemas.SchemaBase.merge(obj, src)\n assert merged == self.merged, f\"failed while testing {self.name}\"\n\n\nCASES_ROOT = os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"..\", \"schemas\", \"test_cases\")\n\n\n# Get a list of all test cases. They are parameterized this way because it makes it extremely\n# easy to identify which test failed from the log output. Otherwise, we would just yield the full\n# test case here.\ndef all_cases() -> Iterator[\"str\"]:\n for root, _, files in os.walk(CASES_ROOT):\n for file in files:\n if file.endswith(\".yaml\"):\n path = os.path.join(root, file)\n with open(path) as f:\n cases = yaml.safe_load(f)\n for case in cases:\n display_path = os.path.relpath(path, CASES_ROOT)\n yield display_path + \"::\" + case[\"name\"]\n\n\n@pytest.mark.parametrize(\"test_case\", all_cases())\ndef test_schemas(test_case: str) -> None:\n cases_file, case_name = test_case.split(\"::\", 1)\n with open(os.path.join(CASES_ROOT, cases_file)) as f:\n cases = yaml.safe_load(f)\n # Find the right test from the file of test cases.\n case = [c for c in cases if c[\"name\"] == case_name][0]\n Case(**case).run()\n\n\ndef lint_schema_subclasses(cls: type) -> None:\n \"\"\"Recursively check all SchemaBase subclasses\"\"\"\n for sub in cls.__subclasses__():\n lint_schema_subclasses(sub)\n\n # Ignore certain classes.\n if cls in [schemas.SchemaBase]:\n return\n\n # class annotations should match __init__ arg annotations.\n cls_annos = {\n (name, anno) for name, anno in cls.__annotations__.items() if not name.startswith(\"_\")\n }\n init_annos = {\n (name, anno)\n for name, anno in cls.__init__.__annotations__.items() # type: ignore\n if name != \"return\"\n }\n assert (\n cls_annos == init_annos\n ), f\"{cls.__name__}: class annotions and __init__ args do not match\"\n\n defaults = [name for name, _ in cls_annos if hasattr(cls, name)]\n\n # All default values should be None.\n for name in defaults:\n assert getattr(cls, name) is None, (\n f\"{cls.__name__}.{name} must default to None; schema objects are like typed \"\n \"dictionaries and None is the value to represent that no other value was specified. \"\n \"Defaults from the json-schema definitions are applied via .fill_defaults()\"\n )\n\n # class values should match __init__ arg defaults.\n cls_defaults = {(name, getattr(cls, name)) for name in defaults}\n init_defaults = {\n (name, (cls.__init__.__defaults__ or {}).get(name)) for name in defaults # type: ignore\n }\n assert (\n cls_defaults == init_defaults\n ), f\"{cls.__name__}: class defaults and __init__ defaults do not match\"\n\n\ndef test_schema_class_definitons() -> None:\n lint_schema_subclasses(schemas.SchemaBase)\n","sub_path":"harness/tests/common/test_schemas.py","file_name":"test_schemas.py","file_ext":"py","file_size_in_byte":9694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"68908188","text":"'''\r\n高度,容积,颜色,材质\r\n能存放液体\r\n'''\r\n\r\nclass Glass:\r\n __h = \"\"\r\n __v = \"\"\r\n __color = \"\"\r\n __textrue = \"\"\r\n\r\n def setH(self,h):\r\n if h >12 or h < 0:\r\n print(\"您的输入存在异常!\")\r\n else:\r\n self.__h = h\r\n def getH(self):\r\n return self.__h\r\n\r\n def setV(self,v):\r\n if v > 12 or v < 0:\r\n print(\"容积不能超过高度!\")\r\n else:\r\n self.__v = v\r\n def getV(self):\r\n return self.__v\r\n\r\n def color(self,name):\r\n print(name,\"的杯子在桌子上,里面有\",self.__v,\"ml水\")\r\n\r\n def textrue(self,name):\r\n print(name,\"材质的杯子在桌子上,它的高度为\",self.__h,\"cm\")\r\n\r\na = Glass()\r\n\r\na.setV(10)\r\na.setH(12)\r\na.color(\"蓝色\")\r\na.textrue(\"玻璃\")\r\n\r\n\r\n'''\r\n有笔记本电脑(屏幕大小,价格,cpu型号,内存大小,待机时长),行为(打字,打游戏,看视频)\r\n'''\r\n\r\nclass Computer:\r\n __size = \"\"\r\n __price = \"\"\r\n __cpu = \"\"\r\n __memory = \"\"\r\n __time = \"\"\r\n\r\n def __init__(self,size,price,cpu,memory,time):\r\n self.__size = size\r\n self.__price = price\r\n self.__cpu = cpu\r\n self.__memory = memory\r\n self.__time = time\r\n\r\n def playGames(self,name):\r\n print(\"您的CPU为:\",self.__cpu,\"您的内存大小为:\",self.__memory,\"您可以玩\",name)\r\n def watchingTV(self):\r\n print(\"您的内存为:\",self.__memory,\"您正在看电视!\")\r\n def typing(self):\r\n print(\"CPU为:\",self.__cpu,\"您的内存大小为:\",self.__memory,\"正在打字!\")\r\n\r\n\r\n\r\na = Computer(15.6,5000,\"64G\",\"500G\",\"24h\")\r\na.playGames(\"绝地求生\")\r\na.watchingTV()\r\na.typing()","sub_path":"water.cumputer.py","file_name":"water.cumputer.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"94592619","text":"from Task import Task\nfrom Helper import Level\n\n\nclass AddMilestone(Task):\n def __init__(self, logMethod, parent, params):\n super().__init__(\"Add Milestone\", parent, params, logMethod, None)\n\n def Run(self):\n try:\n milestone = self.params['Milestone']\n self.Log(Level.INFO, f\"Adding milestone '{milestone}' to experiment.\")\n self.parent.AddMilestone(milestone)\n except KeyError:\n self.Log(Level.ERROR, \"'Milestone' value not set\")\n","sub_path":"Executor/Tasks/Run/add_milestone.py","file_name":"add_milestone.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"400877674","text":"# u, v로 분리\ndef UVreturn(w):\n left = 0\n right = 0\n for i in range(len(w)):\n if w[i] == '(':\n left += 1\n if w[i] == ')':\n right += 1\n if left == right:\n return w[0:i+1], w[i+1:]\n\n# u의 올바른 문자열 판단\ndef proper(u):\n left = 0\n right = 0\n for i in range(len(u)):\n if u[i] == '(':\n left += 1\n if u[i] == ')':\n right += 1\n if left < right:\n return False\n return True\n\n\ndef solution(p):\n answer = ''\n # 1\n if p == '':\n return ''\n\n # 2\n u, v = UVreturn(p)\n\n # 3\n if proper(u):\n # 3-1\n return u + solution(v)\n # 4\n else:\n # 4-1\n answer = '('\n # 4-2\n answer += solution(v)\n # 4-3\n answer += ')'\n # 4-4\n for i in u[1:-1]:\n if i == ')':\n answer += '('\n else:\n answer += ')'\n return answer\n\n\np = \")()()()(\"\nprint(solution(p))","sub_path":"week5/괄호변환.py","file_name":"괄호변환.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"627847531","text":"'''\nInclude Sphinx json files into a static website\n'''\nimport os\n\nfrom pulsar import ImproperlyConfigured\n\nfrom ..routers import JsonContent, JsonFile, HtmlContent, HtmlFile, normpath\nfrom ..contents import Content\ntry:\n from .builder import LuxSphinx\nexcept ImportError:\n LuxSphinx = None\n\n\nclass SphinxContent(Content):\n\n def __init__(self, app, meta, ctx):\n meta.update(ctx.get('meta', ()))\n meta['content_type'] = 'text/html'\n content = ctx.get('body', '')\n super().__init__(app, content, meta, ctx.get('src'), ctx['pagename'])\n\n\nclass SphinxMixin(object):\n\n def get_content(self, request):\n content = request.cache.content\n if not content:\n raise NotImplementedError('Not implemented yet')\n return content\n\n def build(self, app, location=None):\n '''Build the files for this Builder\n '''\n if self.built is not None:\n return self.built\n if location is None:\n location = os.path.abspath(app.config['STATIC_LOCATION'])\n data = getattr(self.html_router, '_doc_build', None)\n if data is None:\n data = self.build_sphinx(app, location)\n self.html_router._doc_build = data\n self.built = []\n for ctx in data:\n self.build_file(app, location, ctx)\n return self.built\n\n def build_file(self, app, location, ctx):\n urlparams = {self.route.ordered_variables[0]: ctx['pagename']}\n path = self.path(**urlparams)\n url = app.site_url(normpath(path))\n content = SphinxContent(app, self.meta.copy(), ctx)\n request = app.wsgi_request(path=url, extra={'HTTP_ACCEPT': '*/*'})\n request.cache.building_static = True\n request.cache.content = content\n response = self.response(request.environ, urlparams)\n self.write(app, request, location, response)\n\n def build_sphinx(self, app, location):\n if not LuxSphinx:\n raise ImproperlyConfigured('Sphinx not installed')\n path = self.html_router.path()[1:]\n if path:\n location = os.path.join(location, path)\n if not os.path.isdir(location):\n os.makedirs(location)\n srcdir = os.path.abspath(self.dir)\n doctreedir = os.path.join(location, '_doctrees')\n app = LuxSphinx(app, srcdir, srcdir, location, doctreedir, 'lux')\n force_all = False\n app.build(force_all)\n return app.data\n\n\nclass SphinxFiles(SphinxMixin, HtmlFile):\n pass\n\n\nclass SphinxJsonFiles(SphinxMixin, JsonFile):\n pass\n\n\nclass SphinxJsonDocs(JsonContent):\n JsonFileRouter = SphinxJsonFiles\n\n\nclass SphinxDocs(HtmlContent):\n JsonApiRouter = SphinxJsonDocs\n HtmlFileRouter = SphinxFiles\n drafts = None\n","sub_path":"lux/extensions/static/rst/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"607949778","text":"\"\"\"\nTF2 Currency data\n\"\"\"\nimport logging\nfrom os.path import exists\nfrom json import loads, dumps\nfrom time import time\n\nfrom telegram import Bot, Update\nfrom telegram.ext import Updater\nimport requests\n\nimport constants # pylint: disable=E0401\nimport settings\nCURRENCY = \"http://backpack.tf/api/IGetCurrencies/v1?key=%s\" % settings.BPTFTOKEN\nLOGGER = logging.getLogger(\"TF2 Currency\")\ndef void(*_):\n \"\"\"\n Simple function that can accept anything...\n ...and do nothing\n \"\"\"\n return\n\ndef IGetCurrencies():\n \"\"\"\n Gets currency data from Backpack.TF API\n \"\"\"\n curr = requests.get(CURRENCY).json()\n curr[\"updated\"] = time()\n with open(\"plugins/IGetCurrencies.json\", 'w') as f:\n f.write(dumps(curr))\n return curr\n\ndef IGetCurrencies_strg():\n \"\"\"\n Gets IGetCurrencies data from storage, and updates it if\n needed\n \"\"\"\n if exists(\"plugins/IGetCurrencies.json\"):\n with open(\"plugins/IGetCurrencies.json\") as f:\n data = loads(f.read())\n now = time()\n if now - data[\"updated\"] > 120:\n return IGetCurrencies()\n else:\n return data\n else:\n return IGetCurrencies()\n\ndef preload(updater: Updater, level):\n \"\"\"\n This loads whenever plugin starts\n Even if you dont need it, you SHOULD put at least\n return None, otherwise your plugin wont load\n \"\"\"\n return\n\ndef tfcurr(bot: Bot, update: Update, user, args): # pylint: disable=W0613\n \"\"\"\n /tfcash command\n \"\"\"\n data = IGetCurrencies_strg()[\"response\"][\"currencies\"]\n message = \"\"\n if len(args) < 2:\n message += \"TF2 currency data:\\n\"\n for currency in data:\n cdata = data[currency][\"price\"]\n message += \"%s=%s %s\\n\" % (currency.capitalize(), cdata[\"value\"], cdata[\"currency\"])\n else:\n if not args[1].lower() in data:\n return \"I dont know %s\" % args[1], constants.TEXT\n cdata = data[args[1]][\"price\"]\n message += \"%s %s=%s %s\\n\" % (args[0], args[1], float(args[0]) * cdata[\"value\"],\n cdata[\"currency\"])\n message += \"\\nData from backpack.tf\"\n return message, constants.TEXT\n\nCOMMANDS = [\n {\n \"command\":\"/tfcash\",\n \"function\":tfcurr,\n \"description\":\"Sends TF2 currency data if no arguments were supplied, or sends value in other currency. Example:/tfcash 2 keys\",\n \"inline_support\":True\n }\n]\n","sub_path":"plugins/tf_currency.py","file_name":"tf_currency.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"310777293","text":"class utworyMuzyczne():\n def __init__(self,wykonawca, tytul, album, rok):\n self.wykonawca = wykonawca\n self.tytul = tytul\n self.album = album\n self.rok = rok\n \n def __str__(self):\n return f'''\nWykonawca: {self.wykonawca}\nUtwor: {self.tytul}\nAlbum: {self.album}\nRok: {self.rok}'''\n \nutw = utworyMuzyczne('Dawid Podsiadlo', 'Nie ma fal', 'Mialomiasteczkowy', 2018)\nprint(utw)","sub_path":"07-ObjectOrientedProgramming/during class/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"324054240","text":"from odoo import api, fields, models\n\nclass PurchaseOrder(models.Model):\n _inherit = \"purchase.order\"\n\n @api.depends('order_line.price_subtotal', 'discount_type', 'discount_rate','additional_amount')\n def _calculate_amount_all(self):\n\n \"\"\"\n Compute the total amounts of the po.\n \"\"\"\n discount_rate_value = 0\n\n for order in self:\n amount_untaxed = amount_tax = amount_discount = 0.0\n\n for line in order.order_line:\n # unit_price = unit_price + (line.price_unit * line.product_qty)\n # total_netto = total_netto + (line.price_unit * line.product_qty) - line.price_subtotal\n amount_untaxed += (line.product_qty * line.price_unit)\n\n if line.discount_type == 'percent':\n amount_discount += (line.product_qty * line.price_unit * line.discount_rate) / 100\n if order.discount_type == 'percent':\n calculate_discount = 0\n if order.discount_rate:\n for line in order.order_line:\n calculate_discount += (line.product_qty * line.price_unit * line.discount_rate) / 100\n order.amount_discount = calculate_discount + ((amount_untaxed * order.discount_rate) / 100)\n discount_rate_value = order.amount_discount\n\n else:\n calculate_discount = 0\n if order.discount_rate:\n for line in order.order_line:\n calculate_discount += (line.product_qty * line.price_unit * line.discount_rate) / 100\n order.amount_discount = (calculate_discount + order.discount_rate)\n discount_rate_value = order.amount_discount\n\n else:\n amount_discount += line.discount_rate\n if order.discount_type == 'percent':\n calculate_discount = 0\n if order.discount_rate:\n for line in order.order_line:\n calculate_discount += line.discount_rate\n # calculate_discount += (line.product_qty * line.price_unit * line.discount_rate) / 100\n order.amount_discount = calculate_discount + ((amount_untaxed * order.discount_rate) / 100)\n discount_rate_value = order.amount_discount\n\n else:\n calculate_discount = 0\n if order.discount_rate:\n for line in order.order_line:\n calculate_discount += line.discount_rate\n #calculate_discount += (line.product_qty * line.price_unit * line.discount_rate) / 100\n order.amount_discount = (calculate_discount + order.discount_rate)\n discount_rate_value = order.amount_discount\n\n amount_tax += line.price_tax\n\n untaxed_amount = order.currency_id.round(amount_untaxed)\n\n if order.discount_type and order.discount_rate:\n order.update({\n 'cal_add_price': order.additional_amount,\n 'amount_untaxed': untaxed_amount ,\n 'amount_tax': order.currency_id.round(amount_tax),\n 'amount_discount': order.currency_id.round(discount_rate_value),\n 'amount_total': untaxed_amount - discount_rate_value + amount_tax + order.additional_amount,\n })\n else:\n order.update({\n 'cal_add_price': order.additional_amount,\n 'amount_untaxed': untaxed_amount,\n 'amount_tax': order.currency_id.round(amount_tax),\n 'amount_discount': order.currency_id.round(amount_discount),\n 'amount_total': untaxed_amount - amount_discount + amount_tax + order.additional_amount,\n })\n\n additional_amount = fields.Float('Additional Fee')\n cal_add_price = fields.Monetary(string='Additional Fee', store=True, readonly=True, compute='_calculate_amount_all',)\n\n","sub_path":"beta-dev1/pdp_modifer_purchase_fields/models/purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"457411979","text":"#!/usr/bin/python3\n\"\"\"\nThe file contains a Adversarial Autoencoder in tensorflow.\n\nCopyright (c) 2018\nLicensed under the MIT License (see LICENSE for details)\nWritten by Arash Tehrani\n\"\"\"\n# ---------------------------------------------------\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tflearn\nimport os\nimport datetime\nfrom progressbar import ProgressBar, ETA, Bar, Percentage, Timer\n# ----------------------------------------------\nclass AAE(object):\n\n def __init__(self,\n input_shape=[28, 28],\n reduced_dim=10, \n batch_size=128, channel_size=128,\n activation=tf.nn.relu,\n lr=1e-3, beta1=0.5,\n weight_init=tflearn.initializations.xavier(uniform=False),\n bias_init=tflearn.initializations.xavier(uniform=False),\n tensorboar_dir='./AdversarialAE/tf_logs'):\n \"\"\"\n initialization\n Arguments:\n input_shape: ist of 2 ints, shape of the input image\n reduced_dim: int, dimension of the latent feature space, i.e., z\n batch_size: int, batch size\n channel_size: int, channel size\n activation: tf function, activation of the layers\n lr: float, learning rate\n beta1: float, adam optimizer beta1 parameter\n weight_init: tf function, initialization of the weights\n bias_init: tf function, initialization of the biases\n tensorboard_dir: string, path in where the tf logs will be saved\n \"\"\"\n tf.reset_default_graph()\n self.graph = tf.get_default_graph()\n self.input_shape = input_shape\n self.reduced_dim = reduced_dim\n self.activation=activation\n self.lr = lr\n self.beta1 = beta1\n self.small_size_img = int(input_shape[0]*input_shape[1]/16)\n self.batch_size = batch_size\n self.channel_size = channel_size\n dummy_dim = int(np.sqrt(self.small_size_img))\n self.reshaped_dim = [-1, dummy_dim, dummy_dim, self.channel_size] #[-1, 7, 7, .self.channel_size]\n self.weight_init = weight_init\n self.bias_init = bias_init\n self.tensorboar_dir = tensorboar_dir\n self._setup()\n self._build_model()\n\n\n def _setup(self):\n \"\"\"\n setup the placeholders and dimensions\n \"\"\"\n self.X = tf.placeholder(dtype=tf.float32, shape=[None, self.input_shape[0], \n self.input_shape[1]], name='X')\n self.Y = tf.placeholder(dtype=tf.float32, shape=[None, self.input_shape[0], \n self.input_shape[1]], name='Y')\n self.Y_flat = tf.reshape(self.Y, shape=[-1, self.input_shape[0] * self.input_shape[1]])\n #self.Z = tf.placeholder(dtype=tf.float32, shape=[None, self.reduced_dim], name='Z')\n self.Z_prior = tf.placeholder(dtype=tf.float32, shape=[None, self.reduced_dim], \n name='Z_prior')\n\n\n def encoder(self, x, reuse=None):\n \"\"\"\n Encoder network\n \"\"\"\n with tf.variable_scope('encoder', reuse=None):\n x = tf.reshape(x, shape=[-1, self.input_shape[0], self.input_shape[1], 1])\n x = tf.layers.conv2d(x, filters=64, kernel_size=4, strides=2, \n padding='same', \n activation=self.activation, \n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='enc_L1_conv')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.layers.conv2d(x, filters=128, kernel_size=4, strides=2, \n padding='same', \n activation=None, \n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='enc_L2_conv')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.layers.batch_normalization(x, name='enc_L3_bn')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = self.activation(x)\n x = tf.contrib.layers.flatten(x)\n x = tf.layers.dense(x, units=1024, \n activation=None, \n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init,\n name ='enc_L4_fc')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.layers.batch_normalization(x, name='enc_L5_bn')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = self.activation(x)\n x = tf.layers.dense(x, units=self.reduced_dim, \n activation=None, \n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init,\n name ='enc_L6_fc')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n \n return x\n\n\n def decoder(self, z, reuse=False):\n \"\"\"\n Decoder network\n \"\"\"\n dim = int(self.input_shape[0]*self.input_shape[1]*self.channel_size/16)\n if reuse:\n tf.get_variable_scope().reuse_variables()\n with tf.variable_scope('decoder', reuse=reuse):\n x = tf.layers.dense(z, units=1024, \n activation= None,\n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='dec_L1_fc')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.layers.batch_normalization(x, name='dec_L2_bn')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = self.activation(x)\n x = tf.layers.dense(x, units=dim, \n activation= None,\n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='dec_L3_fc')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.reshape(x, shape=self.reshaped_dim)\n x = tf.layers.batch_normalization(x, name='dec_L4_bn')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = self.activation(x)\n x = tf.layers.conv2d_transpose(x, filters=64, kernel_size=4, strides=2, \n padding='same',\n activation= None,\n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='dec_L5_convt')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.layers.batch_normalization(x, name='dec_L6_bn')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = self.activation(x)\n x = tf.layers.conv2d_transpose(x, filters=1, kernel_size=4, strides=2, \n padding='same',\n activation= tf.nn.sigmoid,\n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='dec_L7_convt')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.reshape(x, shape=[-1, self.input_shape[0], self.input_shape[1]])\n\n return x \n\n\n def discriminator(self, z, reuse=False):\n \"\"\"\n Discriminator network\n Note: if uncomment the monitor of activations, then two discriminator in the \n tensorboard will be created one for each real or fake distribution.\n \"\"\"\n if reuse:\n tf.get_variable_scope().reuse_variables()\n with tf.variable_scope('discriminator', reuse=reuse):\n x = tf.layers.dense(z, units=1000, \n activation= self.activation,\n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='dis_L1_fc')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.layers.dense(x, units=1000, \n activation= None,\n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='dis_L2_fc')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = tf.layers.batch_normalization(x, name='dis_L3_bn')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n x = self.activation(x)\n x = tf.layers.dense(x, units=1, \n activation= tf.nn.sigmoid,\n kernel_initializer=self.weight_init,\n bias_initializer=self.bias_init, \n name ='dis_L4_fc')\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, x)\n return x\n \n\n def _build_model(self):\n \"\"\"\n Building the model and loss function\n \"\"\"\n with tf.variable_scope(tf.get_variable_scope()):\n self.z = self.encoder(self.X)\n self.y = self.decoder(self.z)\n y_flat = tf.reshape(self.y, [-1, self.input_shape[0] * self.input_shape[1]])\n\n with tf.variable_scope(tf.get_variable_scope()):\n d_real = self.discriminator(self.Z_prior)\n d_fake = self.discriminator(self.z, reuse=True)\n\n with tf.variable_scope(tf.get_variable_scope()):\n self.gen = self.decoder(self.Z_prior, reuse=True)\n \n\n # loss\n self.rec_loss = tf.reduce_mean(tf.square(self.Y_flat - y_flat))\n\n self.gen_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.ones_like(d_fake), logits=d_fake))\n \n self.dis_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.ones_like(d_real), logits=d_real)) \\\n + tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.zeros_like(d_fake), logits=d_fake))\n\n # collecting trainable variables\n all_variables = tf.trainable_variables()\n enc_vars = [var for var in all_variables if 'encoder' in var.name]\n dec_vars = [var for var in all_variables if 'decoder' in var.name]\n dis_vars = [var for var in all_variables if 'discriminator' in var.name]\n rec_vars = enc_vars + dec_vars\n \n # building the optimizers\n opt = tf.train.AdamOptimizer(learning_rate=self.lr, beta1=self.beta1)\n self.rec_opt = opt.minimize(self.rec_loss, var_list=rec_vars)\n self.dis_opt = opt.minimize(self.dis_loss, var_list=dis_vars)\n self.gen_opt = opt.minimize(self.gen_loss, var_list=enc_vars)\n\n # getting the gradients (I could also tf.gradients)\n rec_grads = opt.compute_gradients(self.rec_loss, rec_vars)\n rec_grads = list(zip(rec_grads, rec_vars))\n \n dis_grads = opt.compute_gradients(self.dis_loss, dis_vars)\n dis_grads = list(zip(dis_grads, dis_vars))\n \n gen_grads = opt.compute_gradients(self.gen_loss, enc_vars)\n gen_grads = list(zip(gen_grads, enc_vars))\n\n self.saver = tf.train.Saver()\n \n self._summary_setup(enc_vars, dec_vars, dis_vars,\n rec_grads, dis_grads, gen_grads)\n\n self.saver = tf.train.Saver()\n\n self.sess = tf.Session(graph=self.graph) \n\n\n def _trainer(self, dataset, n_epoch=100, z_std=5, checkpoint_interval=50, report_flag=True):\n \"\"\"\n train the adversarial autoencoder\n Arguments:\n dataset: tensorflow dataset object\n n_epoch: int, number of epochs\n z_std: float, standard deviation of z_prior\n checkpoint_interval: int, interval in number of batches to store the network parameters\n report_flag: bool, a flag to print the log values\n \"\"\"\n step = 0\n self.n_epoch = n_epoch\n self.sess.run(tf.global_variables_initializer())\n path = os.path.join(self.tensorboar_dir, self.run_id)\n if not os.path.exists(path):\n os.mkdir(path)\n writer = tf.summary.FileWriter(logdir=path, graph=self.graph)\n self._log_setup(path)\n \n with self.sess.as_default() as sess:\n for epoch_num in range(self.n_epoch):\n\n n_batches = int(dataset.train.num_examples / self.batch_size)\n widgets = ['epoch {}|'.format(epoch_num), Percentage(), Bar(), ETA(), Timer()]\n pbar = ProgressBar(maxval=n_batches, widgets=widgets)\n pbar.start()\n \n for batch_num in range(1, n_batches + 1):\n pbar.update(batch_num)\n # getting the batch data\n z_prior = np.random.randn(self.batch_size, self.reduced_dim) * z_std\n batch_x, _ = dataset.train.next_batch(self.batch_size)\n batch_x = batch_x.reshape((-1, 28,28))\n\n sess.run(self.rec_opt, feed_dict={self.X: batch_x, self.Y: batch_x})\n sess.run(self.dis_opt,\n feed_dict={self.X: batch_x, self.Y: batch_x, self.Z_prior: z_prior})\n sess.run(self.gen_opt, feed_dict={self.X: batch_x, self.Y: batch_x})\n \n if batch_num % checkpoint_interval == 0:\n a_loss, d_loss, g_loss, summary = sess.run(\n [self.rec_loss, self.dis_loss, self.gen_loss, self.summary_op],\n feed_dict={self.X: batch_x, self.Y: batch_x, self.Z_prior: z_prior})\n writer.add_summary(summary, global_step=step)\n if report_flag:\n print('Epoch: {}, iteration: {}'.format(epoch_num, batch_num))\n print('Autoencoder Loss: {}'.format(a_loss))\n print('Discriminator Loss: {}'.format(d_loss))\n print('Generator Loss: {}'.format(g_loss))\n with open(path+'/log.txt', 'a') as log:\n log.write('Epoch: {}, batch number: {}\\n'.format(epoch_num, batch_num))\n log.write('Autoencoder Loss: {}\\n'.format(a_loss))\n log.write('Discriminator Loss: {}\\n'.format(d_loss))\n log.write('Generator Loss: {}\\n'.format(g_loss))\n \n step += 1\n writer.flush()\n writer.close()\n\n\n def train(self, dataset, n_epoch=100, z_std=5, checkpoint_interval=50, report_flag=True, run_id=None): \n \"\"\"\n train the neural net\n Arguments:\n dataset: tensorflow binary object, dataset\n n_epoch: int, number of epochs\n z_std: float, standard deviation of z-prior\n checkpoint_interval: int, interval in number of batches to write the log file or print the output\n report_flag: bool, a flag to print the log values\n \"\"\"\n if run_id is None:\n run_id = 'Adversarial_AE_{}'.format(datetime.datetime.now())\n \n self.run_id = run_id\n self._trainer(dataset, n_epoch=n_epoch, z_std=z_std, checkpoint_interval=checkpoint_interval, report_flag=report_flag)\n \n \n def _summary_setup(self, enc_vars, dec_vars, dis_vars,\n rec_grads, dis_grads, gen_grads\n ):\n \"\"\"\n Build the sumary of trainable variables, activations, and gradiesnts as suggested by \n the name of the arguments\n \"\"\"\n # Summarize all activations\n for actv in tf.get_collection(tf.GraphKeys.ACTIVATIONS):\n tf.summary.histogram(actv.name, actv)\n \n # Summarize the weights and biases\n for var in enc_vars:\n tf.summary.histogram(var.name, var)\n \n for var in dec_vars:\n tf.summary.histogram(var.name, var)\n \n for var in dis_vars:\n tf.summary.histogram(var.name, var)\n \n # Summarize all gradients\n for grad, var in rec_grads:\n tf.summary.histogram(var.name + '/rec_gradient', grad)\n \n for grad, var in dis_grads:\n tf.summary.histogram(var.name + '/dis_gradient', grad)\n \n for grad, var in gen_grads:\n tf.summary.histogram(var.name + '/gen_gradient', grad)\n\n # summarize the losses\n tf.summary.scalar(name='Reconstruction Loss', tensor=self.rec_loss)\n tf.summary.scalar(name='Discriminator Loss', tensor=self.dis_loss)\n tf.summary.scalar(name='Generator Loss', tensor=self.gen_loss)\n tf.summary.histogram(name='Latent Distribution', values=self.z)\n tf.summary.histogram(name='Real Distribution', values=self.Z_prior)\n tf.summary.image(name='Input Images', \n tensor=tf.reshape(self.X, shape=[-1, self.input_shape[0], self.input_shape[1], 1]), \n max_outputs=10) \n tf.summary.image(name='Reconstructed Images', \n tensor=tf.reshape(self.y, shape=[-1, self.input_shape[0], self.input_shape[1], 1]), \n max_outputs=10)\n tf.summary.image(name='Generated Images', \n tensor=tf.reshape(self.gen, shape=[-1, self.input_shape[0], self.input_shape[1], 1]), \n max_outputs=10)\n\n self.summary_op = tf.summary.merge_all()\n\n\n def save(self, model_file):\n \"\"\"\n save model weights\n Arguments:\n model_file: string, address of the saved file\n \"\"\"\n self.saver.save(self.sess, save_path=model_file)\n\n\n def load(self, model_file):\n \"\"\"\n Restore model weights.\n Arguments:\n model_file: string, address of the saved file.\n trainable_variable_only: boolean, set to True if you only want to load the weights\n \"\"\"\n self.saver.restore(self.sess, model_file)\n\n\n def _log_setup(self, path):\n \"\"\"\n Store the network parameters in the log file\n Arguments:\n path: str, path to the corresponding folder\n \"\"\"\n with open(path+'/log.txt', 'w') as log:\n log.write('Adversarial AutoEncoder\\n')\n log.write('-------------------------------------------\\n')\n log.write('trained on: {}\\n'.format(datetime.datetime.now()))\n log.write('Parameters:\\n')\n log.write('dimension of z: {}\\n'.format(self.reduced_dim))\n log.write('learning rate: {}\\n'.format(self.lr))\n log.write('batch size: {}\\n'.format(self.batch_size))\n log.write('number of epochs: {}\\n'.format(self.n_epoch))\n log.write('beta1: {}\\n'.format(self.beta1))\n log.write('channel size: {}\\n'.format(self.channel_size)) \n log.write('-------------------------------------------\\n')\n\n\n def reconstruct(self, x):\n \"\"\"\n Produce the reconstruction for input images x\n Arguments:\n x: 3d array [num_images,h,w], input images\n \"\"\"\n return self.sess.run(self.y, feed_dict={self.X: x.reshape((-1,self.input_shape[0], self.input_shape[1]))})\n\n\n def reconstructor_viewer(self, x):\n \"\"\"\n produce an image to view reconstructed data together with the original data\n Arguments:\n x: 3d array [num_images,h,w], input images\n \"\"\" \n reconstructed = self.reconstruct(x)\n \n num_images = x.shape[0]\n h, w = x.shape[1], x.shape[2]\n\n n = np.sqrt(num_images).astype(np.int32)\n img = np.ones((h*n, 2*w*n+2*n))\n for j in range(n):\n for i in range(n):\n img[i*h:(i+1)*h, j*2*w+2*j:(j+1)*2*w+2*j] = \\\n np.hstack((\n x[n*j+i, :, :].reshape(h,w),\n reconstructed[n*j+i, :, :].reshape(h,w), \n )) \n\n return img\n\n\n def reduce_dimension(self, x):\n \"\"\"\n Produce the z vectors for the given inputs\n Arguments:\n x: 3d array [num_images,h,w], input images\n \"\"\"\n return self.sess.run(self.z, feed_dict={self.X: x.reshape((-1,self.input_shape[0], self.input_shape[1]))})\n\n \n def visualization_2d(self, x, y):\n \"\"\"\n 2d visualization for the case reduced_dim =2\n Arguments:\n x: 3d array [num_images,h,w], input images\n y: 2d array [num_images, label], labels of the classes\n \"\"\"\n z = self.sess.run(self.z, feed_dict={self.X: x.reshape((-1, self.input_shape[0], self.input_shape[1]))})\n assert z.shape[1] == 2, 'reduced_dim, i.e., dimension of z, must be 2 for this display to work'\n plt.figure(figsize=(10, 8)) \n plt.scatter(z[:, 0], z[:, 1], c=np.argmax(y, axis=1))\n plt.colorbar()\n plt.grid()\n\n\n def generate(self, num_images=None, z=None, z_std=5):\n \"\"\"\n generate data from noise input\n Arguments:\n num_images: int, number of images to be generated.\n z: numpy 2d array, noise input\n Note: it will use either the num_images or the given z\n \"\"\"\n if num_images is None:\n num_images = self.batch_size\n\n if z is None:\n z = np.random.randn(num_images, self.reduced_dim) * z_std\n else:\n num_images = z.shape[0]\n \n return self.sess.run(self.decoder(self.Z_prior, reuse=True), feed_dict={self.Z_prior: z})\n \n\n def generator_viewer(self, num_images):\n \"\"\"\n produce an image to view generated data\n Arguments:\n num_images: int, number of images to be generated.\n \"\"\" \n generated = self.generate(num_images)\n\n n = np.sqrt(num_images/2).astype(np.int32)\n h = self.input_shape[0]\n w = self.input_shape[1]\n img = np.zeros((h*(n+1), 2*w*n))\n for i in range(n+1):\n for j in range(2*n):\n if 2*n*i+j < num_images:\n img[i*h:(i+1)*h, j*w:(j+1)*w] = \\\n generated[2*n*i+j, :, :].reshape(w,h)\n\n return img\n\n\n def spectum_2d(self, num_imgs_row):\n \"\"\"\n spectrum of the changes of generator\n Arguments:\n num_imgs_row: int, number of images in each row\n \"\"\"\n assert self.reduced_dim == 2, 'reduced_dim must be 2 for this visualization'\n h, w = self.input_shape[0], self.input_shape[1]\n \n x = np.linspace(-5, 5, num_imgs_row)\n img = np.empty((h*num_imgs_row, w*num_imgs_row))\n for i, xi in enumerate(x):\n z = np.vstack(([xi]*num_imgs_row, x)).transpose()\n generated = self.generate(z=z)\n dummy = np.empty((h, 0), dtype=float)\n for j in range(num_imgs_row):#generated.shape[0]):\n dummy = np.hstack((\n dummy, generated[j,:,:].reshape(w,h)\n ))\n\n img[i*h:(i+1)*h, :] = dummy \n\n plt.figure(figsize=(8, 8)) \n plt.imshow(img, cmap=\"gray\")\n \n\n# ----------------------------------------------\nif __name__ == '__main__':\n\n # get the data\n from tensorflow.examples.tutorials.mnist import input_data\n mnist = input_data.read_data_sets('./mnist/', one_hot=True)\n\n # ----------------------------------------\n # build the model\n aae = AAE()\n\n # train and save the model\n aae.train(dataset=mnist, n_epoch=20, report_flag=False)\n #aae.save('./AdversarialAE/saved_models/model.ckpt')\n\n # load the model\n aae.load('./AdversarialAE/saved_models/model.ckpt')\n \n # test the generator\n plt.imshow(aae.generator_viewer(60), cmap='gray')\n \n # get the images\n images, labels = mnist.test.next_batch(128)\n images = images.reshape((-1,28,28))\n image = images[0,:,:]\n \n # test the dimensionality reduction\n z = aae.reduce_dimension(images)\n\n # test the reconstruction\n plt.figure()\n plt.imshow(np.hstack((image.reshape(28,28), \n aae.reconstruct(image).reshape(28,28)\n )), cmap='gray')\n plt.figure()\n plt.imshow(aae.reconstructor_viewer(images), cmap='gray')\n \n plt.show()\n # ----------------------------------------\n # build the 2 dimensional model\n aae2d = AAE(reduced_dim=2) \n\n # train and save the model\n #aae2d.train(dataset=mnist, n_epoch=20, report_flag=False)\n #aae2d.save('./AdversarialAE/saved_models/model2d.ckpt')\n\n # load the model\n aae2d.load('./AdversarialAE/saved_models/model2d.ckpt')\n \n # get the images\n images, labels = mnist.train.next_batch(1000)\n images = images.reshape((-1,28,28))\n \n # the scatter plot of 2d latent features\n aae2d.visualization_2d(images, labels)\n\n # the spectrum of the generated images\n aae2d.spectum_2d(40)\n\n plt.show()","sub_path":"AdversarialAE/AdversarialAE.py","file_name":"AdversarialAE.py","file_ext":"py","file_size_in_byte":25497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"166421955","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport os\nimport sys\nimport logging\nimport time\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\nfrom conf import settings\n\n\ndef recode_msg(card_num, message):\n struct_time = time.localtime()\n if struct_time.tm_mday < 23:\n file_name = \"%s_%s_%d\" % (struct_time.tm_year, struct_time.tm_mon, 22)\n else:\n file_name = \"%s_%s_%d\" % (struct_time.tm_year, struct_time.tm_mon + 1, 22)\n\n file_handler = logging.FileHandler(\n os.path.join(settings.USER_USER_INFO_DIR, card_num, 'record', file_name),\n encoding='utf-8'\n )\n fmt = logging.Formatter(fmt=\"%(asctime)s : %(message)s\")\n file_handler.setFormatter(fmt)\n\n logger = logging.Logger('user_logger', level=logging.INFO)\n logger.addHandler(file_handler)\n logger.info(message)\n","sub_path":"server/atm_server/models/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"230672799","text":"\"\"\"\n불량 사용자\nhttps://programmers.co.kr/learn/courses/30/lessons/64064\n\"\"\"\nfrom itertools import product\n\n\ndef solution(user_id, banned_id):\n blen = len(banned_id)\n data = [[] for _ in range(blen)]\n for user in user_id:\n ulen = len(user)\n for bix, ban in enumerate(banned_id):\n if ulen == len(ban):\n for i in range(ulen):\n if ban[i] != \"*\" and ban[i] != user[i]:\n break\n else:\n data[bix].append(user)\n\n answer = set()\n for case in product(*data):\n if len(set(case)) == blen:\n answer.add(tuple(sorted(list(case))))\n return len(answer)\n\n\nprint(solution([\"frodo\", \"fradi\", \"crodo\", \"abc123\", \"frodoc\"], [\"fr*d*\", \"abc1**\"]), 2)\nprint(solution([\"frodo\", \"fradi\", \"crodo\", \"abc123\", \"frodoc\"], [\"*rodo\", \"*rodo\", \"******\"]), 2)\nprint(solution([\"frodo\", \"fradi\", \"crodo\", \"abc123\", \"frodoc\"], [\"fr*d*\", \"*rodo\", \"******\", \"******\"]), 3)\n","sub_path":"2021/21주차/불량 사용자/하현준.py","file_name":"하현준.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"279632344","text":"# -*- coding: iso-8859-15 -*-\n'''\nVISUM add-in Import Google Transit Feed\n\nDate: 22.05.2014\nAuthor: Dimitri Krutik\nContact: Dimitri.Krutik@ptvgroup.com\nCompany: PTV AG'''\n\nfrom VisumPy.helpers import HHMMSS2secs\nfrom GoogleTransitImport import Operations as op\nfrom GoogleTransitImport import GoogleTransitExceptions as ex\nfrom GoogleTransitImport.TransitDataImporter.DataBuilder.BuilderBase import BuilderBase\nfrom GoogleTransitImport.TransitDataImporter.DataBuilder.BuilderHelpers.RecordCollectorGroupedByTrip import RecordCollectorGroupedByTrip\n\nclass StopTimesBuilder(BuilderBase):\n \"\"\"\n StopTimesBuilder parse the stop times and group it on the trip.\n \"\"\"\n\n __bordAlightAllowed = 1\n __bordAlightNotAllowed = 0\n\n def __init__(self, worker):\n super(StopTimesBuilder, self).__init__(worker)\n self.__tripStopTimeRecords = dict()\n\n def Pop(self, tripId):\n stopTimeRecords = self.__tripStopTimeRecords.pop(tripId, None)\n return self.__prepareTripStopTimes(stopTimeRecords)\n\n def Get(self, tripId):\n '''\n Return stop times of the trip, or None, if trip doesn't have stop times.\n '''\n stopTimeRecords = self.__tripStopTimeRecords.get(tripId, None)\n return self.__prepareTripStopTimes(stopTimeRecords)\n\n @classmethod\n def _checkRequiredFiles(cls, worker):\n if worker.Files.stoptimesfile == None:\n raise ex.RequiredFileMissed(_(\"Required file '%s' is missing.\").decode('iso-8859-15') % worker.Files.StoptimesFileName)\n\n def __clear(self):\n self.__tripStopTimeRecords.clear()\n\n def LoadData(self):\n self.__clear()\n\n with self._worker.OpenCSVFile(self._worker.Files.stoptimesfile) as csvReader:\n try:\n self._setReadFileProgressDlg(csvReader, 3500)\n self._progressDlg.Message = _(\"Reading stop times\")\n\n self.__importStopTimeRecords(csvReader)\n\n except ex.ExecutionCanceled:\n raise\n\n except Exception as e:\n mess = self._createDefaultReadFileExceptionMessage(self._worker.Files.StoptimesFileName)\n raise ex.GoogleTransitException(mess, e)\n\n finally:\n self._resetReadFileProgressDlg()\n\n\n def __importStopTimeRecords(self, csvReader):\n recordCollector = RecordCollectorGroupedByTrip(self.__tripStopTimeRecords)\n\n for stopTimeRecord in csvReader:\n self._progressDlg.UpdateProgressDialog()\n self._progressDlg.LineCount += 1\n\n stopTime = self.__parseStopTimeRecord(stopTimeRecord)\n recordCollector.StoreRecordToTrip(stopTime.tripId, stopTime)\n\n # --------------------------------------------------------------------------\n # ------------------------------------------------------ Parse StopTimes\n\n def __parseStopTimeRecord(self, record):\n stopTime = StopTime()\n\n stopTime.tripId = op.MakeSafeString(self._readRequiredAttribute(record, \"trip_id\"))\n stopTime.stopId = op.MakeSafeString(self._readRequiredAttribute(record, \"stop_id\"))\n\n stopTime.stopSequence = self._readRequiredIntAttribute(record, \"stop_sequence\")\n\n stopTime.arrivAndDepart = self.__parseArrivalAndDepartureFromRecord(record)\n\n stopTime.board = self.__parseBordAlightTypes(self._readAttribute(record, \"pickup_type\"))\n stopTime.alight = self.__parseBordAlightTypes(self._readAttribute(record, \"drop_off_type\"))\n\n distTraveled = op.MakeSafeString(self._readAttribute(record, \"shape_dist_traveled\"))\n stopTime.shapeDistTraveled = self.__parseDistTraveled(distTraveled, stopTime)\n\n return stopTime\n\n def __parseDistTraveled(self, distTraveled, stopTime):\n if distTraveled == \"\":\n return 0\n\n try:\n val = float(distTraveled)\n if val >= 0:\n return val\n except Exception:\n pass\n\n self.__writeIncorrectDistTraveledWarning(stopTime, distTraveled)\n return 0\n\n\n def __parseArrivalAndDepartureFromRecord(self, record):\n try:\n arrivAndDepart = StopArrivalAndDeparture()\n arrivAndDepart.SetArrival(self._readAttribute(record, \"arrival_time\"))\n arrivAndDepart.SetDeparture(self._readAttribute(record, \"departure_time\"))\n arrivAndDepart.MatchTimes()\n\n return arrivAndDepart\n except:\n raise ex.ValueTypeException(_(\"Incorrect value of the arrival or departure time attribute.\").decode('iso-8859-15'))\n\n def __parseBordAlightTypes(self, bordingAlightType):\n if bordingAlightType == u\"1\":\n return self.__bordAlightNotAllowed\n else:\n return self.__bordAlightAllowed\n\n\n # --------------------------------------------------------------------------\n # -------------------------------------------- Prepare StopTimes of the trip\n\n def __prepareTripStopTimes(self, stopTimes):\n if stopTimes == None:\n return None\n\n sortedStopTimes = self.__sortStopTimes(stopTimes)\n validStopTimes = self.__validateStopTimes(sortedStopTimes)\n self.__setPostLengths(validStopTimes)\n return validStopTimes\n\n @classmethod\n def __sortStopTimes(cls, stopTimes):\n return sorted(stopTimes, key=lambda stopTime: stopTime.stopSequence)\n\n def __validateStopTimes(self, sortedStopTimes):\n \"\"\"\n - the first and the last stops should be a routing points\n => remove none routing points on the begin and the end of the list\n - combine successive repeated stops\n => from two of the repeated stops remove the none route point an keep the route point\n if both stop entries are the route points, keep the first one and\n set the earliest arrival and the latest departure times\n\n Return valid stop time list or None\n \"\"\"\n validationAssistant = StopTimesValidationAssistant()\n\n # -------------------------------------------------------------------\n # Remove NOT route points on the begin of the stop time list\n # Combine stop times defines the same stop in the line\n for currentStopTime in sortedStopTimes:\n\n if not validationAssistant.hasFirstRoutePoint:\n if currentStopTime.isRoutePoint:\n validationAssistant.hasFirstRoutePoint = True\n else:\n self.__writeFirstStopTimeIsNotRoutePointWarning(currentStopTime)\n continue\n\n if validationAssistant.IsRepeatedStop(currentStopTime.stopId):\n self.__writeCombineRepeatedStopsWarning(validationAssistant.lastHandledStopTime,\n currentStopTime)\n validationAssistant.CombineRepeatedStopDefinition(currentStopTime)\n continue\n\n validationAssistant.AddHandledStopTime(currentStopTime)\n\n # -------------------------------------------------------------------\n # Remove NOT route points on the end of the stop time list\n endWithNotRoutePoint = True\n while endWithNotRoutePoint:\n currentStopTime = validationAssistant.GetLastStopTime()\n if currentStopTime != None and not currentStopTime.isRoutePoint:\n self.__writeLastStopTimeIsNotRoutePointWarning(currentStopTime)\n validationAssistant.RemoveLastStopTime()\n else:\n endWithNotRoutePoint = False\n\n # -------------------------------------------------------------------\n # return the valid stop time list or None\n if validationAssistant.hasFinalStopTimes:\n return validationAssistant.finalStopTimes\n else:\n return None\n\n\n def __setPostLengths(self, stopTimes):\n if stopTimes == None or len(stopTimes) == 0:\n return\n\n firstSP = None\n secondSP = None\n isFirstSegment = True\n\n for i in range(0, len(stopTimes)):\n if not stopTimes[i].isRoutePoint:\n stopTimes[i].postLength = 0\n continue\n\n if firstSP == None:\n firstSP = stopTimes[i]\n continue\n\n secondSP = stopTimes[i]\n\n postLength = 0\n if (isFirstSegment and secondSP.shapeDistTraveled != 0) or \\\n (firstSP.shapeDistTraveled != 0 and secondSP.shapeDistTraveled != 0):\n\n postLength = secondSP.shapeDistTraveled - firstSP.shapeDistTraveled\n\n if postLength < 0:\n self.__writeNegativePostLengthWarning(firstSP, secondSP)\n postLength = 0\n\n firstSP.postLength = postLength\n isFirstSegment = False\n\n firstSP = secondSP\n secondSP = None\n\n if firstSP:\n # the postLength of the last stop point is 0\n firstSP.postLength = 0\n\n\n def __writeIncorrectDistTraveledWarning(self, stopTime, distTraveled):\n mess0 = _(\"Attribute value '%s' is incorrect.\").decode('iso-8859-15') % 'shape_dist_traveled'\n mess1 = _(\"Value '%s', trip id '%s', stop time sequence number %s.\").decode('iso-8859-15') % (distTraveled, stopTime.tripId, stopTime.stopSequence)\n mess2 = _(\"The value is set to the default value '0'.\").decode('iso-8859-15')\n mess = \"%s %s %s %s\" % (mess0, mess1, mess2, self.__getFileNameMessage())\n self._worker.WriteWarning(mess)\n\n def __writeNegativePostLengthWarning(self, firstStopTime, secondStopTime):\n mess0 = _(\"The calculated value for the attribute 'postLength' is negative.\").decode('iso-8859-15')\n mess1 = _(\"Trip id '%s', 'postLength' between stop times with sequence numbers %s and %s.\").decode('iso-8859-15') % (firstStopTime.tripId, firstStopTime.stopSequence, secondStopTime.stopSequence)\n mess2 = _(\"The 'postLength' value of the resulting line route item is set to '0'.\").decode('iso-8859-15')\n mess = \"%s %s %s %s\" % (mess0, mess1, mess2, self.__getFileNameMessage())\n self._worker.WriteWarning(mess)\n\n def __writeFirstStopTimeIsNotRoutePointWarning(self, stopTime):\n mess0 = _(\"The first stop time of the trip has no arrival/departure times, thus is not a route point.\").decode('iso-8859-15')\n mess1 = _(\"This stop time can not be used as a first item of the line route.\").decode('iso-8859-15')\n mess2 = _(\"The stop time is skipped.\").decode('iso-8859-15')\n mess3 = _(\"Trip id '%s', stop time sequence number %s.\").decode('iso-8859-15') % (stopTime.tripId, stopTime.stopSequence)\n mess = \"%s %s %s %s %s\" % (mess0, mess1, mess2, mess3, self.__getFileNameMessage())\n self._worker.WriteWarning(mess)\n\n def __writeLastStopTimeIsNotRoutePointWarning(self, stopTime):\n mess0 = _(\"The last stop time of the trip has no arrival/departure times, thus is not a route point.\").decode('iso-8859-15')\n mess1 = _(\"This stop time can not be used as a last item of the line route.\").decode('iso-8859-15')\n mess2 = _(\"The stop time is skipped.\").decode('iso-8859-15')\n mess3 = _(\"Trip id '%s', stop time sequence number %s.\").decode('iso-8859-15') % (stopTime.tripId, stopTime.stopSequence)\n mess = \"%s %s %s %s %s\" % (mess0, mess1, mess2, mess3, self.__getFileNameMessage())\n self._worker.WriteWarning(mess)\n\n def __writeCombineRepeatedStopsWarning(self, stopTimeFirst, stopTimeSecond):\n mess0 = _(\"The stop referenced multiple times in successive stop times. This stop times are combined.\").decode('iso-8859-15')\n mess1 = _(\"Trip id '%s', stop id '%s', stop time sequence numbers %s and %s.\").decode('iso-8859-15')\n mess1 = mess1 % (stopTimeFirst.tripId,\n stopTimeFirst.stopId,\n stopTimeFirst.stopSequence,\n stopTimeSecond.stopSequence)\n mess = \"%s %s %s\" % (mess0, mess1, self.__getFileNameMessage())\n self._worker.WriteWarning(mess)\n\n def __getFileNameMessage(self):\n return _(\"See file '%s'.\").decode('iso-8859-15') % self._worker.Files.StoptimesFileName\n\n# -----------------------------------------------------------------------------------------------\n# ------------------------------------------------------------------------------ Help classes\n\nclass StopTimesValidationAssistant(object):\n __slots__ = (\"lastHandledStopTime\", \"hasFirstRoutePoint\", \"finalStopTimes\")\n\n def __init__(self):\n self.lastHandledStopTime = None\n self.hasFirstRoutePoint = False\n self.finalStopTimes = []\n\n @property\n def finalStopTimesCount(self):\n return len(self.finalStopTimes)\n\n @property\n def hasFinalStopTimes(self):\n return len(self.finalStopTimes) > 0\n\n def GetLastStopTime(self):\n lastIndex = self.finalStopTimesCount - 1\n if lastIndex >= 0:\n return self.finalStopTimes[lastIndex]\n else:\n return None\n\n def RemoveLastStopTime(self):\n if self.finalStopTimesCount > 0:\n self.finalStopTimes.pop()\n\n def AddHandledStopTime(self, stopTime):\n self.lastHandledStopTime = stopTime\n self.finalStopTimes.append(stopTime)\n\n def IsRepeatedStop(self, stopId):\n return self.lastHandledStopTime and \\\n self.lastHandledStopTime.stopId == stopId\n\n def CombineRepeatedStopDefinition(self, repeatedStopTime):\n \"\"\"\n Combine two successive stop times, that reference the same stop.\n \"\"\"\n self.lastHandledStopTime.CombineStopTimes(repeatedStopTime)\n\n\n\nclass StopTime(object):\n __slots__ = (\"tripId\", \"stopId\", \"stopSequence\", \"board\",\n \"alight\", \"arrivAndDepart\", \"shapeDistTraveled\", \"postLength\")\n\n def __init__(self):\n self.tripId = \"\"\n self.stopId = \"\"\n self.stopSequence = \"\"\n self.board = \"\"\n self.alight = \"\"\n self.shapeDistTraveled = 0\n self.postLength = 0\n self.arrivAndDepart = StopArrivalAndDeparture()\n\n @property\n def isRoutePoint(self):\n # it is enough to test only one of the times\n # -> always: no times or both time are set\n return self.arrivAndDepart.HasDeparture()\n\n @property\n def arrivalSec(self):\n return self.arrivAndDepart.arrivalSec\n\n @property\n def arrivalStr(self):\n return self.arrivAndDepart.arrivalStr\n\n @property\n def departureSec(self):\n return self.arrivAndDepart.departureSec\n\n @property\n def departureStr(self):\n return self.arrivAndDepart.departureStr\n\n def CombineStopTimes(self, other):\n \"\"\"\n Combine two stop times. Use for successive stop times,\n that reference the same stop.\n\n Precondition:\n Function do not check if trip id and referenced stops are the same.\n Assumed that it is so!\n\n - set the earliest arrival and the latest departure.\n - set the farthest shape distance and related 'postLength'\n\n - do not change: stopSequence, board, alight\n \"\"\"\n self.arrivAndDepart.UpdateEarliestAndLatestTimes(other.arrivAndDepart)\n\n if self.shapeDistTraveled < other.shapeDistTraveled:\n self.shapeDistTraveled = other.shapeDistTraveled\n self.postLength = other.postLength\n\n\n\n\nclass StopArrivalAndDeparture(object):\n \"\"\"\n Class handles arrival and departure times as string and count of seconds.\n If one of the times is missing, the MatchTimes() method sets both times\n to the same (existing) value.\n So, after setting of time the state is:\n - both times are set (different values or the same)\n - both times are empty\n \"\"\"\n __slots__ = (\"arrivalStr\", \"arrivalSec\", \"departureStr\", \"departureSec\")\n\n def __init__(self):\n self.arrivalStr = None\n self.arrivalSec = None\n self.departureStr = None\n self.departureSec = None\n self.__resetArrival()\n self.__resetDeparture()\n\n def SetArrival(self, arrivalTime):\n if op.IsNoneOrEmpty(arrivalTime):\n self.__resetArrival()\n else:\n self.__setArrival(arrivalTime, HHMMSS2secs(arrivalTime))\n\n def SetDeparture(self, departureTime):\n if op.IsNoneOrEmpty(departureTime):\n self.__resetDeparture()\n else:\n self.__setDeparture(departureTime, HHMMSS2secs(departureTime))\n\n def UpdateEarliestAndLatestTimes(self, newArrivAndDepartureTimes):\n \"\"\"\n Update arrival and departure from current and the new objects.\n Set the arrival of the current object to the Earliest of both arrival times\n and the departure to the latest of both departures times.\n For each of arrival and departure:\n - keep own value, if new object has no value\n - if new object has a value:\n - if one value is not set, take the value from new object\n - if one value is set, take the min/max value of both objects\n \"\"\"\n self.__updateToEarliestArrival(newArrivAndDepartureTimes)\n self.__updateToLatestDeparture(newArrivAndDepartureTimes)\n\n def __updateToLatestDeparture(self, otherArrivAndDeparture):\n if otherArrivAndDeparture.HasDeparture():\n if not self.HasDeparture():\n # own time entry is not available => take the value from \"other\"\n self.__setDeparture(otherArrivAndDeparture.departureStr,\n otherArrivAndDeparture.departureSec)\n else:\n # both time entries available => choose the latest time\n if self.departureSec < otherArrivAndDeparture.departureSec:\n self.__setDeparture(otherArrivAndDeparture.departureStr,\n otherArrivAndDeparture.departureSec)\n\n def __updateToEarliestArrival(self, otherArriveAndDeparture):\n if otherArriveAndDeparture.HasArrival():\n if not self.HasArrival():\n # own time entry is not available => take the value from \"other\"\n self.__setArrival(otherArriveAndDeparture.arrivalStr,\n otherArriveAndDeparture.arrivalSec)\n else:\n # both time entries available => choose the earliest time\n if otherArriveAndDeparture.arrivalSec < self.arrivalSec:\n self.__setArrival(otherArriveAndDeparture.arrivalStr,\n otherArriveAndDeparture.arrivalSec)\n\n def HasDeparture(self):\n return self.departureStr != u\"\"\n\n def HasArrival(self):\n return self.arrivalStr != u\"\"\n\n def MatchTimes(self):\n if self.HasArrival():\n if not self.HasDeparture():\n # has arrival and not departure -> copy arrival to departure\n self.__setDeparture(self.arrivalStr, self.arrivalSec)\n else:\n if self.HasDeparture():\n # has departure and no arrival -> copy departure to arrival\n self.__setArrival(self.departureStr, self.departureSec)\n\n def __setArrival(self, arrivalStr, arrivalSec):\n self.arrivalStr = arrivalStr\n self.arrivalSec = arrivalSec\n\n def __setDeparture(self, departureStr, departureSec):\n self.departureStr = departureStr\n self.departureSec = departureSec\n\n def __resetDeparture(self):\n self.__setDeparture(u\"\", 0)\n\n def __resetArrival(self):\n self.__setArrival(u\"\", 0)\n","sub_path":"GoogleTransitImport/TransitDataImporter/DataBuilder/StopTimesBuilder.py","file_name":"StopTimesBuilder.py","file_ext":"py","file_size_in_byte":19558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"461384640","text":"import argparse\nimport logging\nimport os\n\nfrom source.core.personal_assistant import PersonalAssistant\n\n\ndef main(config_dir, app_data_dir, launch):\n logging.info(\"Starting PersonalAssistant/__main__.py\")\n pa = PersonalAssistant(config_dir=config_dir, app_data_dir=app_data_dir)\n if launch:\n logging.info(\"Launching PA from PersonalAssistant/__main__.py\")\n pa.run()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n from secrets import lib_root\n\n default_config_dir = os.path.join(lib_root, 'config')\n default_app_data_dir = os.path.join(lib_root, 'app_data')\n parser.add_argument(\"--config-dir\", \"-c\", default=default_config_dir)\n parser.add_argument(\"--app-data-dir\", \"-a\", default=default_app_data_dir)\n parser.add_argument(\"--launch\", \"--run\", action=\"store_true\")\n parser.add_argument(\"--debug\", action=\"store_true\")\n\n args = parser.parse_args()\n if args.debug:\n logging.basicConfig(level=logging.DEBUG)\n main(config_dir=args.config_dir, app_data_dir=args.app_data_dir, launch=args.launch)\n\n# read plugins data\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"125071635","text":"__all__ = ['TmexSession']\n\nimport sys\nfrom logger import logger\n\nclass TmexSession(object):\n IS_SUPPORT = False\n\nif not sys.platform.startswith('win'):\n logger.error('TMEX only for Windows systems')\nelse:\n import tmex\n from database import session\n from tmex.devices.base import BaseDevice\n from database.models.tmex import TmexDevice\n\n class TmexSession(object):\n IS_SUPPORT = True\n tmex_devices = {}\n _tmex = None\n\n def __init__(self, port=0):\n self._re_init(port)\n\n def _re_init(self, port):\n self.tmex_devices = {}\n self._tmex = tmex.Session(port=port)\n logger.info('TMEX port={}'.format(port))\n\n obj = None\n for idx_dev, dev in enumerate(self._tmex.enumrate(ignore=None), 1):\n args = dict(\n model=dev.model,\n description=dev.description,\n device_type=dev.type,\n )\n\n logger.info('Device #{0:03d}: {1.device_id} - {1.model} - {1.description}'.format(idx_dev, dev))\n\n dev_rom = None\n if isinstance(dev, BaseDevice):\n dev_rom = dev.device_id\n args.update(dict(rom=dev_rom, family=0))\n else:\n args.update(dict(rom='{:02X}'.format(dev.kind),\n family=dev.kind))\n if dev_rom:\n self.tmex_devices[dev_rom] = dev\n\n obj = TmexDevice(**args)\n obj.save()\n\n if isinstance(obj, TmexDevice):\n obj.save(commit=True)\n\n @staticmethod\n def get_all(black_list=None, return_list=False):\n \"\"\" Возвращает список всех зарегистрированных устройств.\n\n :param black_list: (list) список игнорируемых семейства устройств.\n :param return_list: (bool) возвращает список если true.\n :return (list)\n \"\"\"\n\n q = session.query(TmexDevice)\n\n if isinstance(black_list, (tuple, list, set)):\n black_list = set(black_list)\n\n if len(black_list) > 0:\n q = q.filter(TmexDevice.family.notin_(black_list))\n\n return q.all() if return_list else q\n\n","sub_path":"att/tmexSession.py","file_name":"tmexSession.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"412290158","text":"\"\"\"mergef\n\nThe motivation for this tool is mainly to merge all the exported csv files\nfrom my bank accounts into one generalized file.\nAfter that i can easily do whatever i want with the data.\n\"\"\"\n\nimport click\nimport csv\nimport datetime\nimport os.path\n\nfrom itertools import islice\nfrom models.dkbTransaction import DKBTransaction\nfrom models.ingTransaction import INGTransaction\nfrom models.amexTransaction import AmexTransaction\n\n\n@click.command()\n@click.option('--dkb',\n type=click.File(encoding='iso-8859-1'),\n required=True,\n help='The DKB csv file')\n@click.option('--ing',\n type=click.File(encoding='iso-8859-1'),\n required=True,\n help='The ING-DiBa csv file')\n@click.option('--amex',\n type=click.File(encoding='us-ascii'),\n required=True,\n help='The AmericanExpress csv file')\n@click.option('--out',\n type=click.Path(exists=True, file_okay=False, resolve_path=True),\n required=True,\n help='The output path where the merged csv file gets written to')\ndef cli(dkb, ing, amex, out):\n \"\"\"\n In general it parses all the csv files, merges and sorts them\n and after that it writes it to the given output path.\n \"\"\"\n parsed_dkb = list(\n map(lambda line: DKBTransaction(line), _parse_csv(dkb, ';', 7)))\n parsed_ing = list(\n map(lambda line: INGTransaction(line), _parse_csv(ing, ';', 15)))\n parsed_amex = list(\n map(lambda line: AmexTransaction(line), _parse_csv(amex, ',', 0)))\n\n merged_transactions = parsed_dkb + parsed_ing + parsed_amex\n sorted_merged_transactions = sorted(merged_transactions,\n key=lambda t: t.date)\n\n _write_transactions(out, sorted_merged_transactions)\n\n\ndef _parse_csv(csv_file, delimiter, start_at):\n \"\"\"Parses the given csv file.\n\n Parameters\n ----------\n csv_file : click.File\n The csv which needs to be parsed\n delimiter : str\n The delimiter used in the csv file\n start_at : int\n The number of row where the content starts\n\n Returns\n -------\n list\n List of all lines\n \"\"\"\n\n return islice(csv.reader(csv_file, delimiter=delimiter), start_at, None)\n\n\ndef _get_header():\n \"\"\"Returns a list of all column names\"\"\"\n return ['Date', 'Type', 'Amount', 'Description', 'Bank', 'Tag']\n\n\ndef _write_transactions(output_path, merged_transactions):\n \"\"\"Writes the merged transaction list to the given output path.\n\n It also generated the filename according to: merged_MONTH-YEAR.csv\n\n Parameters\n ----------\n output_path : click.Path\n The output path where the merged csv file gets written to\n merged_transactions : list\n A merged list of all parsed transactions\n \"\"\"\n now = datetime.datetime.now().strftime('%m-%Y')\n output_file_path = os.path.join(output_path, f'transactions_{now}.csv')\n\n with open(output_file_path, 'w', newline='') as merged_file:\n csv_writer = csv.writer(merged_file, delimiter=';')\n csv_writer.writerow(_get_header())\n for transaction in merged_transactions:\n csv_writer.writerow(transaction.to_row())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"582793045","text":"# Monkey patch the safety module\nimport os.path\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nparent = os.path.dirname(dir_path)\nsafety_path = os.path.join(parent, \"safety\")\nif os.path.isdir(safety_path):\n from safety import safety\n\n orig_check = safety.check\n\n def derp(*args, packages=None, **kwargs):\n print(\"Running my modified safety.check\")\n filtered = []\n for package in packages:\n if \"insecure-package\" in package.key:\n continue\n filtered.append(package)\n return orig_check(*args, packages=filtered, **kwargs)\n\n safety.check = derp\n","sub_path":"malicious/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"20237262","text":"from django.urls import path\nfrom bookstore.views import document_views as views\n\nurlpatterns = [ \n path('about/', views.about, name='about'), \n path('t&c/', views.terms_and_conditions, name='terms-and-conditions'), \n path('privacy/', views.privacy, name='privacy'), \n path('contact/', views.contact, name='contact'), \n path('faq/', views.faq, name='faq'), \n]\n","sub_path":"backend/bookstore/urls/document_urls.py","file_name":"document_urls.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"536953287","text":"\"\"\"\nCreate a Python3_Homework03 project and assign it to your Python3_Homework working set. In the Python3_Homework03/src folder, create a file named decoder.py, which contains an iterator named alphabator. When passed a list, simply return objects as-is unless they are integers between 1 and 26, in which case it should convert that number to the corresponding letter. The integer-to-letter correspondence is 1=A, 2=B, 3=C, 4=D, and so on.\n\nYou may use any technique you've learned in lesson 3 to execute this project.\n\"\"\"\n\n\n\ndef alphabator(list):\n for l in list:\n if l in range(1,27):\n char_num = l+64\n item = chr(char_num)\n else:\n item =l\n yield item\n \n \n ","sub_path":"Python 3/Python3_03(Iteration in Python)/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"189245398","text":"# -*- coding: utf-8 -*-\n\nfrom django.db.models.loading import get_model\n\n\ndef create_user(id, save=True, is_superuser=False):\n model = get_model(\"users\", \"User\")\n domain_member_model = get_model(\"domains\", \"DomainMember\")\n domain_model = get_model(\"domains\", \"Domain\")\n\n instance = model(\n username=\"user{0}\".format(id),\n email=\"user{0}@taiga.io\".format(id),\n first_name=\"Foo{0}\".format(id),\n last_name=\"Bar{0}\".format(id)\n )\n\n instance.set_password(instance.username)\n if is_superuser:\n instance.is_staff = True\n instance.is_superuser = True\n\n instance.save()\n\n domain = domain_model.objects.get(pk=1)\n dm = domain_member_model.objects.create(user=instance,\n email=instance.email,\n domain=domain)\n if id == 1:\n dm.is_owner = True\n dm.is_staff = True\n dm.save()\n\n return instance\n\n\ndef create_domain(name, public_register=False):\n domain_model = get_model(\"domains\", \"Domain\")\n\n instance = domain_model(name=name,\n domain=name,\n public_register=public_register)\n\n instance.save()\n return instance\n","sub_path":"taiga/base/users/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"300268961","text":"import numpy as np\nimport math\n\nwith open('../datasets/naive_bayes_dataset.txt', 'r') as f:\n l = [[string.strip('\\n') for string in line.split(',')] for line in f]\n\n\n# for testing default label=\"outlook\" (sunny,rainy or overcast)\n\n\nx_label = np.array([l[i][0] for i in range(len(l))])\ny_class = np.array([l[i][-1] for i in range(len(l))])\n\n# merging the two to get a matrix\n\nM = np.array([[l[i][0], l[i][-1]] for i in range(len(l))])\n\n# an array for unique values\n\nY = np.unique(y_class)\nX = np.unique(x_label)\n\n\ndef make_frequency_table(X, Y):\n \"\"\"\n This function prepares a frequency table for every label in respective column.\n \"\"\"\n freq = dict()\n\n for i in range(len(X)):\n freq[X[i]] = [0, 0]\n\n for i in range(len(M)):\n if M[i][1] == Y[0]:\n freq[M[i][0]][0] += 1\n else:\n freq[M[i][0]][1] += 1\n\n return freq\n\n\ndef make_likelihood_table(X, Y, x, y):\n\n # for each item divide by column sum\n\n likelihood = [[0 for i in range(len(Y))] for j in range(len(X))]\n\n freq = make_frequency_table(X, Y)\n\n for j in range(len(Y)):\n Sum = (y == Y[j]).sum()\n for i in range(len(X)):\n likelihood[i][j] = freq[X[i]][j] / Sum\n\n return likelihood\n\n\ndef naive_bayes(X, Y):\n \"\"\"\n pyx: P(y/X) is proportional to p(x1/y)*p(x2/y)...*p(y)\n using log and adding as multiplying for smaller numbers can make them very small\n As denominator P(X)=P(x1)*P(x2).. is common we can ignore it\n \"\"\"\n\n pyx = []\n\n likelihood = make_likelihood_table(X, Y, x_label, y_class)\n\n for j in range(len(Y)):\n Sum = 0\n for i in range(len(X)):\n if(likelihood[i][j] == 0):\n continue\n\n Sum += math.log(likelihood[i][j])\n\n y_sum = (y_class == Y[j]).sum()\n\n if y_sum:\n Sum += math.log(y_sum / len(y_class))\n pyx.append([Sum, X[i], Y[j]])\n\n return pyx\n\n\ndef most_likely():\n \"\"\"\n predicts the most likely label,class\n \"\"\"\n prediction = max(naive_bayes(X, Y))\n return [prediction[1], prediction[2]]\n","sub_path":"MLlib/utils/naive_bayes_utils.py","file_name":"naive_bayes_utils.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"264403345","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('brands/nike', views.brand_list_nike, name='brand_list_nike'),\n path('brands/adidas', views.brand_list_adidas, name='brand_list_adidas'),\n path('products/', views.product_list, name='products'),\n path('products/outlet', views.product_list_outlet, name='product_list_outlet'),\n path('products/men', views.product_list_men, name='product_list_men'),\n path('products/women', views.product_list_women,\n name='product_list_women'),\n path('products/kids', views.product_list_kids, name='product_list_kids'),\n path('product/', views.product_details, name='product_details'),\n path('import', views.import_data, name='import_data'),\n]\n","sub_path":"www/webshop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"547741180","text":"import numpy as np\nimport matplotlib.pyplot as mpl\nimport sys\n\npoints = np.loadtxt(sys.argv[1])\nhull = np.loadtxt(sys.argv[2])\nhull = list(hull)\nhull.append(hull[0])\nhull = np.array(hull)\n\nmpl.plot(points[:,0], points[:,1], 'o')\nmpl.plot(hull[:,0], hull[:,1], 'r-')\n\nmpl.savefig(\"convex-hull.pdf\")\n","sub_path":"04uebung/convex-hull-plot (2).py","file_name":"convex-hull-plot (2).py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"513723042","text":"import matplotlib.pyplot as plt\nimport json\nimport os\nimport numpy as np\n\nfor subdir, dirs, files in os.walk('./'):\n for file in files:\n with open(file, 'r') as f:\n try:\n motif = json.load(f)\n print(motif['motif'])\n ratios= [ x['ratio'] for x in motif['proteins'] if x['ratio']>1]\n\n plt.hist(ratios, bins = 50)\n plt.xlabel('Ratio')\n plt.ylabel('Number of proteins')\n locs, labels = plt.yticks() \n plt.yticks(np.arange(0, 5001, step=250)) \n # locs, labels = plt.xticks() \n # plt.xticks(np.arange(0, 25, step=1)) \n plt.title('{}'.format(motif['motif']))\n figure = plt.gcf() # get current figure\n figure.set_size_inches(15, 10)\n plt.savefig('./plots/{}.png'.format(motif['motif'][0]),dpi = 100)\n plt.clf()\n f.close()\n except:\n print('{} error'.format(motif['motif']))\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"483115611","text":"# Copyright 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Manages subcommands in a script.\n\nEach subcommand should look like this:\n @usage('[pet name]')\n def CMDpet(parser, args):\n '''Prints a pet.\n\n Many people likes pet. This command prints a pet for your pleasure.\n '''\n parser.add_option('--color', help='color of your pet')\n options, args = parser.parse_args(args)\n if len(args) != 1:\n parser.error('A pet name is required')\n pet = args[0]\n if options.color:\n print('Nice %s %d' % (options.color, pet))\n else:\n print('Nice %s' % pet)\n return 0\n\nExplanation:\n - usage decorator alters the 'usage: %prog' line in the command's help.\n - docstring is used to both short help line and long help line.\n - parser can be augmented with arguments.\n - return the exit code.\n - Every function in the specified module with a name starting with 'CMD' will\n be a subcommand.\n - The module's docstring will be used in the default 'help' page.\n - If a command has no docstring, it will not be listed in the 'help' page.\n Useful to keep compatibility commands around or aliases.\n - If a command is an alias to another one, it won't be documented. E.g.:\n CMDoldname = CMDnewcmd\n will result in oldname not being documented but supported and redirecting to\n newcmd. Make it a real function that calls the old function if you want it\n to be documented.\n - CMDfoo_bar will be command 'foo-bar'.\n\"\"\"\n\nimport difflib\nimport sys\nimport textwrap\n\n\ndef usage(more):\n \"\"\"Adds a 'usage_more' property to a CMD function.\"\"\"\n def hook(fn):\n fn.usage_more = more\n return fn\n return hook\n\n\ndef epilog(text):\n \"\"\"Adds an 'epilog' property to a CMD function.\n\n It will be shown in the epilog. Usually useful for examples.\n \"\"\"\n def hook(fn):\n fn.epilog = text\n return fn\n return hook\n\n\ndef CMDhelp(parser, args):\n \"\"\"Prints list of commands or help for a specific command.\"\"\"\n # This is the default help implementation. It can be disabled or overridden if\n # wanted.\n if not any(i in ('-h', '--help') for i in args):\n args = args + ['--help']\n parser.parse_args(args)\n # Never gets there.\n assert False\n\n\ndef _get_color_module():\n \"\"\"Returns the colorama module if available.\n\n If so, assumes colors are supported and return the module handle.\n \"\"\"\n return sys.modules.get('colorama') or sys.modules.get('third_party.colorama')\n\n\ndef _function_to_name(name):\n \"\"\"Returns the name of a CMD function.\"\"\"\n return name[3:].replace('_', '-')\n\n\nclass CommandDispatcher(object):\n def __init__(self, module):\n \"\"\"module is the name of the main python module where to look for commands.\n\n The python builtin variable __name__ MUST be used for |module|. If the\n script is executed in the form 'python script.py', __name__ == '__main__'\n and sys.modules['script'] doesn't exist. On the other hand if it is unit\n tested, __main__ will be the unit test's module so it has to reference to\n itself with 'script'. __name__ always match the right value.\n \"\"\"\n self.module = sys.modules[module]\n\n def enumerate_commands(self):\n \"\"\"Returns a dict of command and their handling function.\n\n The commands must be in the '__main__' modules. To import a command from a\n submodule, use:\n from mysubcommand import CMDfoo\n\n Automatically adds 'help' if not already defined.\n\n Normalizes '_' in the commands to '-'.\n\n A command can be effectively disabled by defining a global variable to None,\n e.g.:\n CMDhelp = None\n \"\"\"\n cmds = dict(\n (_function_to_name(name), getattr(self.module, name))\n for name in dir(self.module) if name.startswith('CMD'))\n cmds.setdefault('help', CMDhelp)\n return cmds\n\n def find_nearest_command(self, name_asked):\n \"\"\"Retrieves the function to handle a command as supplied by the user.\n\n It automatically tries to guess the _intended command_ by handling typos\n and/or incomplete names.\n \"\"\"\n commands = self.enumerate_commands()\n name_to_dash = name_asked.replace('_', '-')\n if name_to_dash in commands:\n return commands[name_to_dash]\n\n # An exact match was not found. Try to be smart and look if there's\n # something similar.\n commands_with_prefix = [c for c in commands if c.startswith(name_asked)]\n if len(commands_with_prefix) == 1:\n return commands[commands_with_prefix[0]]\n\n # A #closeenough approximation of levenshtein distance.\n def close_enough(a, b):\n return difflib.SequenceMatcher(a=a, b=b).ratio()\n\n hamming_commands = sorted(\n ((close_enough(c, name_asked), c) for c in commands),\n reverse=True)\n if (hamming_commands[0][0] - hamming_commands[1][0]) < 0.3:\n # Too ambiguous.\n return None\n\n if hamming_commands[0][0] < 0.8:\n # Not similar enough. Don't be a fool and run a random command.\n return None\n\n return commands[hamming_commands[0][1]]\n\n def _gen_commands_list(self):\n \"\"\"Generates the short list of supported commands.\"\"\"\n commands = self.enumerate_commands()\n docs = sorted(\n (cmd_name, self._create_command_summary(cmd_name, handler))\n for cmd_name, handler in commands.items())\n # Skip commands without a docstring.\n docs = [i for i in docs if i[1]]\n # Then calculate maximum length for alignment:\n length = max(len(c) for c in commands)\n\n # Look if color is supported.\n colors = _get_color_module()\n green = reset = ''\n if colors:\n green = colors.Fore.GREEN\n reset = colors.Fore.RESET\n return (\n 'Commands are:\\n' +\n ''.join(\n ' %s%-*s%s %s\\n' % (green, length, cmd_name, reset, doc)\n for cmd_name, doc in docs))\n\n def _add_command_usage(self, parser, command):\n \"\"\"Modifies an OptionParser object with the function's documentation.\"\"\"\n cmd_name = _function_to_name(command.__name__)\n if cmd_name == 'help':\n cmd_name = ''\n # Use the module's docstring as the description for the 'help' command if\n # available.\n parser.description = (self.module.__doc__ or '').rstrip()\n if parser.description:\n parser.description += '\\n\\n'\n parser.description += self._gen_commands_list()\n # Do not touch epilog.\n else:\n # Use the command's docstring if available. For commands, unlike module\n # docstring, realign.\n lines = (command.__doc__ or '').rstrip().splitlines()\n if lines[:1]:\n rest = textwrap.dedent('\\n'.join(lines[1:]))\n parser.description = '\\n'.join((lines[0], rest))\n else:\n parser.description = lines[0] if lines else ''\n if parser.description:\n parser.description += '\\n'\n parser.epilog = getattr(command, 'epilog', None)\n if parser.epilog:\n parser.epilog = '\\n' + parser.epilog.strip() + '\\n'\n\n more = getattr(command, 'usage_more', '')\n extra = '' if not more else ' ' + more\n parser.set_usage('usage: %%prog %s [options]%s' % (cmd_name, extra))\n\n @staticmethod\n def _create_command_summary(cmd_name, command):\n \"\"\"Creates a oneliner summary from the command's docstring.\"\"\"\n if cmd_name != _function_to_name(command.__name__):\n # Skip aliases. For example using at module level:\n # CMDfoo = CMDbar\n return ''\n doc = command.__doc__ or ''\n line = doc.split('\\n', 1)[0].rstrip('.')\n if not line:\n return line\n return (line[0].lower() + line[1:]).strip()\n\n def execute(self, parser, args):\n \"\"\"Dispatches execution to the right command.\n\n Fallbacks to 'help' if not disabled.\n \"\"\"\n # Unconditionally disable format_description() and format_epilog().\n # Technically, a formatter should be used but it's not worth (yet) the\n # trouble.\n parser.format_description = lambda _: parser.description or ''\n parser.format_epilog = lambda _: parser.epilog or ''\n\n if args:\n if args[0] in ('-h', '--help') and len(args) > 1:\n # Reverse the argument order so 'tool --help cmd' is rewritten to\n # 'tool cmd --help'.\n args = [args[1], args[0]] + args[2:]\n command = self.find_nearest_command(args[0])\n if command:\n if command.__name__ == 'CMDhelp' and len(args) > 1:\n # Reverse the argument order so 'tool help cmd' is rewritten to\n # 'tool cmd --help'. Do it here since we want 'tool help cmd' to work\n # too.\n args = [args[1], '--help'] + args[2:]\n command = self.find_nearest_command(args[0]) or command\n\n # \"fix\" the usage and the description now that we know the subcommand.\n self._add_command_usage(parser, command)\n return command(parser, args[1:])\n\n cmdhelp = self.enumerate_commands().get('help')\n if cmdhelp:\n # Not a known command. Default to help.\n self._add_command_usage(parser, cmdhelp)\n # Don't pass list of arguments as those may not be supported by cmdhelp.\n # See: https://crbug.com/1352093\n return cmdhelp(parser, [])\n\n # Nothing can be done.\n return 2\n","sub_path":"third_party/depot_tools/subcommand.py","file_name":"subcommand.py","file_ext":"py","file_size_in_byte":9124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"535963550","text":"#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nimport shutil\nimport tempfile\n\nfrom edb.server import _testbase as tb\nfrom edb.server import ctl\nfrom edb.server import cluster as edgedb_cluster\n\n\nclass TestCtl(tb.TestCase):\n def test_ctl_init_1(self):\n data_dir = tempfile.mkdtemp(prefix='edgedbtest-')\n conn = cluster = None\n\n try:\n env = {'EDGEDB_LOG_LEVEL': 'silent'}\n\n ctl.main(['-D', data_dir, 'init'], env=env)\n\n cluster = edgedb_cluster.Cluster(\n data_dir, port='dynamic', env=env)\n cluster_status = cluster.get_status()\n\n self.assertEqual(cluster_status, 'stopped')\n\n cluster.start()\n\n cluster_status = cluster.get_status()\n\n self.assertEqual(cluster_status, 'running')\n\n finally:\n if conn is not None:\n conn.close()\n\n if cluster is not None:\n cluster.stop()\n cluster.destroy()\n\n shutil.rmtree(data_dir, ignore_errors=True)\n","sub_path":"tests/test_ctl.py","file_name":"test_ctl.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"624389432","text":"from odoo import models, fields, api\n\nclass TaxWork(models.Model):\n\t_name = 'taxes.work'\n\n\tdate_from = fields.Date(string=\"Date From\")\n\tdate_to = fields.Date(string=\"Date To\")\n\tsum_id = fields.One2many('tax.tree','tax_id')\n\t\n\t@api.multi\n\tdef generate_suppliers(self):\n\t\tall_suppliers \t= self.env['res.partner'].search([('supplier','=',True)])\n\t\tjournal_ent \t= self.env['account.move'].search([])\n\t\tline \t\t\t= self.env['tax.tree'].search([])\n\t\tcredit_amount = 0 \n\t\tdebit_amount = 0\n\t\ttotal_payment = 0\n\t\ttotal_tax = 0\n\t\tif self.date_from and self.date_to:\n\t\t\tfor x in all_suppliers:\n\t\t\t\tcredit_amount = 0 \n\t\t\t\tdebit_amount = 0\n\t\t\t\ttotal_payment = 0\n\t\t\t\ttotal_tax = 0\n\t\t\t\tfor y in journal_ent:\n\t\t\t\t\tfor z in y.line_ids:\n\t\t\t\t\t\tif x.name == z.partner_id.name:\n\t\t\t\t\t\t\tif z.date >= self.date_from and z.date <= self.date_to:\n\t\t\t\t\t\t\t\tif z.debit > 0:\n\t\t\t\t\t\t\t\t\tdebit_amount = debit_amount + z.debit\n\t\t\t\t\t\t\t\telif z.credit > 0:\n\t\t\t\t\t\t\t\t\tcredit_amount = credit_amount +z.credit\n\t\t\t\tif credit_amount > 0 or debit_amount > 0 or total_payment >0:\t\n\t\t\t\t\tcustomer_payments = self.env['customer.payment.bcube'].search([('partner_id','=',x.id)])\n\t\t\t\t\tfor a in customer_payments:\n\t\t\t\t\t\ttotal_payment = total_payment + a.amount\n\t\t\t\t\t\ttotal_tax = total_tax + a.t_total\n\t\t\t\t\tcreate_line = line.create({\n\t\t\t\t\t\t'suppliers' : x.name,\n\t\t\t\t\t\t'open_bal' : debit_amount + credit_amount,\n\t\t\t\t\t\t'sales' : debit_amount,\n\t\t\t\t\t\t'payment' : total_payment,\n\t\t\t\t\t\t'tax_appl' : total_tax,\n\t\t\t\t\t\t'tax_dedt' : total_tax,\n\t\t\t\t\t\t'tax_paid' : total_tax,\n\t\t\t\t\t\t'close_bal' : debit_amount + credit_amount + debit_amount - total_payment,\n\t\t\t\t\t\t'tax_id' : self.id,\n\t\t\t\t\t\t})\n\t\t\t\t\n\t\t\t\t# print \"Vendor Name\"\n\t\t\t\t# print x.name\n\t\t\t\t# print \"Debit Amount\"\n\t\t\t\t# print debit_amount\n\t\t\t\t# print \"Credit Amount\"\n\t\t\t\t# print credit_amount\n\t\t\t\t# print \"Total Payment Made\"\n\t\t\t\t# print total_payment\n\t\t\n\n\nclass TaxTree(models.Model):\n\t_name = \"tax.tree\"\n\n\tsuppliers = fields.Char(string=\"Supplier\")\n\topen_bal = fields.Char(string=\"Opening Balance\")\n\tsales = fields.Char(string=\"Sales\")\n\tpayment = fields.Char(string=\"Payment\")\n\ttax_appl = fields.Char(string=\"Tax Applicable\")\n\ttax_dedt = fields.Char(string=\"Tax Deducted\")\n\ttax_paid = fields.Char(string=\"Tax Paid\")\n\tclose_bal = fields.Char(string=\"Closing Balance\")\n\ttax_id = fields.Many2one('taxes.work')\n\n\n","sub_path":"custom-addons/working_161_champion/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"183815433","text":"from configuration import *\n\n@api.route('/show')# show the intraday_limit_one for the currency in the watch list\nclass show_all_watch_list(Resource):\n @api.response(200,'intraday data')\n @api.response(404,'empty watchlist')\n @api.response(403,'over source limit,take a break and try again')\n @api.doc(description='show the intraday_limit_one for the currency in the watch list')\n @api.expect(currency_model,validate=True)\n @jwt_required()\n def post(self):\n payload=request.json\n item=payload['currency_id'].upper()## need to check whether the item is valid,if not valid raise 404 error\n conn=sqlite3.connect('test.db')\n c=conn.cursor()\n query=\"SELECT currency FROM Watchlist WHERE owner= ?\"\n a=current_identity\n # print(type(str(a)))\n c.execute(query,(str(a),))\n\n info=c.fetchall()\n # conn.commit()\n\n\n info=[i[0] for i in info]\n\n if 'initial' in info or len(info)==0:## check whether user added watchlis\n\n\n return {\"message\":\"empty watchlist\"},404\n else:\n # result=[]\n data=requests.get(\"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency={}&apikey=OEDO5I2RF8SKBBJ8\".format(item))\n data=data.json()\n data=data[\"Realtime Currency Exchange Rate\"]\n data=data['5. Exchange Rate']\n\n last_day_price_query=\"SELECT last_day_price FROM Currency_list WHERE currency_code=?\"\n c.execute(last_day_price_query,(item,))\n data2=c.fetchall()\n conn.commit()\n data2=data2[0][0]\n\n\n sName=item\n svalue=float(data)\n data2=float(data2)\n # print(type(svalue))\n # print(type(data2))\n schangeValue=svalue-data2\n\n schangePercent=float(schangeValue/data2)\n schangeValue=round(schangeValue,4)\n if schangeValue==0.0 or schangeValue==0:\n colorFlag=3\n show_schangeValue=0\n show_schangePercent=\"{:.2%}\".format(schangePercent)\n\n # show_schangePercent=\"{:.2%}\".format(schangePercent)\n\n if schangeValue>0.0:\n colorFlag=\"#093\"\n show_schangeValue=f'%.4f'%(schangeValue)\n show_schangePercent=\"+\"\"{:.2%}\".format(schangePercent)\n\n if schangeValue<0.0:\n colorFlag=\"#ff333a\"\n show_schangeValue=f'%.4f'%(schangeValue)\n show_schangePercent= \"{:.2%}\".format(schangePercent)\n\n tmp={\"sName\":sName,\n \"sValue\":\"{}\".format('%.4f' % svalue),\n \"sChangeValue\":\"{}\".format(show_schangeValue),\n \"sChangePercent\":\"{}\".format(show_schangePercent),\n \"colorFlag\":\"{}\".format(str(colorFlag))\n }\n print(tmp)\n # result.append(tmp)\n conn.close()\n return tmp,200\n\n @api.response(200,'ok')\n @api.response(404,'empty watchlist')\n @jwt_required()\n def get(self):\n conn=sqlite3.connect('test.db')\n c=conn.cursor()\n query=\"SELECT currency FROM Watchlist WHERE owner= ?\"\n a=current_identity\n # print(type(str(a)))\n c.execute(query,(str(a),))\n\n info=c.fetchall()\n # conn.commit()\n info=[i[0] for i in info]\n if 'initial' in info or len(info)==0:## check whether user added watchlis\n return {\"message\":\"empty watchlist\"},404\n else:\n return info,200\n","sub_path":"backend/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"465895437","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 13 16:03:27 2015\r\n\r\n@author: thinkpad\r\n\"\"\"\r\nfrom numpy import *\r\n#读出数据\r\ndef loadDataSet():\r\n dataMat = []\r\n labelMat = []\r\n fr = open('testSet.txt')\r\n for line in fr.readlines():\r\n lineArr = line.strip().split()\r\n #print lineArr\r\n dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])\r\n labelMat.append(int(lineArr[2]))\r\n return dataMat,labelMat\r\n#公式\r\ndef sigmoid(inX):\r\n return 1.0/(1+exp(-inX))\r\n#求值\r\ndef gradAscent(dataMatIn, classLabels):\r\n dataMatrix = mat(dataMatIn) #转换为numpy矩阵数据类型 \r\n labelMat = mat(classLabels).transpose() #转置\r\n m,n = shape(dataMatrix)#行列\r\n alpha = 0.001\r\n maxCycles = 500\r\n weights = ones((n,1))\r\n for k in range(maxCycles): \r\n h = sigmoid(dataMatrix*weights) #矩阵相乘 \r\n error = (labelMat - h) \r\n weights = weights + alpha * dataMatrix.transpose()* error \r\n return weights\r\n#画图\r\ndef plotBestFit(wei):\r\n\timport matplotlib.pyplot as plt\r\n\tweights = wei\r\n\t#dataMat,labelMat = loadDataSet()\r\n\tdataArr = array(dataMat)\r\n\tn = shape(dataArr)[0]#行数\r\n\txcord1 = []\r\n\tycord1 = []\t\r\n\txcord2 = []\r\n\tycord2 = []\r\n\tfor i in range(n):\r\n\t\tif int(labelMat[i]) == 1:\r\n\t\t\txcord1.append(dataArr[i,1])\r\n\t\t\tycord1.append(dataArr[i,2])\r\n\t\telse:\r\n\t\t\txcord2.append(dataArr[i,1])\r\n\t\t\tycord2.append(dataArr[i,2])\t\t\t\r\n\tfig = plt.figure()\r\n\tax = fig.add_subplot(1,1,1)\r\n\tax.scatter(xcord1,ycord1,s=30,c='red',marker='s')\r\n\tax.scatter(xcord2,ycord2,s=30,c='green')\r\n\tx = arange(-4.0,4.0,0.1)\r\n\ty = (-weights[0]-weights[1]*x)/weights[2]#最佳拟合直线\r\n\tax.plot(x,y)\r\n\tplt.xlabel('X1')\r\n\tplt.ylabel('X2')\r\n\tplt.show()\r\n#随机梯度上升算法\r\ndef stocGradAscent0(dataMatrix,classLabels):\r\n\tm,n = shape(dataMatrix)\r\n\talpha = 0.01\r\n\tweights = ones(n)\r\n\tfor i in range(m):\r\n\t\th = sigmoid(sum(dataMatrix[i]*weights))\r\n\t\terror = classLabels[i] - h\r\n\t\tweights = weights + alpha * error * dataMatrix[i]\r\n\treturn weights\r\n#改进的随机梯度上升算法\r\ndef stocGradAscent1(dataMatrix,classLabels,numIter=150):\r\n\tm,n = shape(dataMatrix)\r\n\tweights = ones(n)\r\n\tfor j in range(numIter):\r\n\t\tdataIndex = range(m)\r\n\t\tfor i in range(m):\r\n\t\t\talpha = 4/(1.0+j+i)+0.01\r\n\t\t\trandIndex = int(random.uniform(0,len(dataIndex)))\r\n\t\t\th = sigmoid(sum(dataMatrix[randIndex]*weights))\r\n\t\t\terror = classLabels[randIndex] - h\r\n\t\t\tweights = weights + alpha * error * dataMatrix[randIndex]\r\n\t\t\tdel(dataIndex[randIndex])\r\n\treturn weights\r\n#以回归系数和特征向量作为输入来计算对应的Sigmoid值\r\ndef classifyVector(inX,weights):\r\n\tprob = sigmoid(sum(inX*weights))\r\n\tif prob>0.5:\r\n\t\treturn 1.0\r\n\telse:\r\n\t\treturn 0.0\r\n\r\ndef colicTest():\r\n\tfrTrain = open('horseColicTraining.txt')#训练集\r\n\tfrTest = open('horseColicTest.txt')#测试集\r\n\ttrainingSet = []\r\n\ttrainingLabels = []\r\n\tfor line in frTrain.readlines():\r\n\t\tcurrLine = line.strip().split('\\t')\r\n\t\tlineArr = []\r\n\t\tfor i in range(21):#每行21个数据\r\n\t\t\tlineArr.append(float(currLine[i]))\r\n\t\ttrainingSet.append(lineArr)\r\n\t\ttrainingLabels.append(float(currLine[21]))\r\n\ttrainWeights = stocGradAscent1(array(trainingSet),trainingLabels)\r\n\t#前边是训练\r\n\t#后边是测试\r\n\terrorCount = 0\r\n\tnumTestVec = 0.0\r\n\tfor line in frTest.readlines():\r\n\t\tnumTestVec += 1.0\r\n\t\tcurrLine = line.strip().split('\\t')\r\n\t\tlineArr = []\r\n\t\tfor i in range(21):\r\n\t\t\tlineArr.append(float(currLine[i]))\r\n\t\tif int(classifyVector(array(lineArr),trainWeights))!=int(currLine[21]):\r\n\t\t\terrorCount += 1\r\n\terrorRate = (float(errorCount)/numTestVec)\r\n\tprint (\"the error rate of this test is: %f\" %(errorRate))\r\n\treturn errorRate\r\n\r\ndef multiTest():\r\n\tnumTests = 10\r\n\terrorSum = 0.0\r\n\tfor k in range(numTests):\r\n\t\terrorSum +=colicTest()\r\n\tprint (\"after %d iterations the average error rate is: %f\" %(numTests,errorSum/float(numTests)))\r\nmultiTest()\r\n\t\r\n","sub_path":"logRegres/logRegres.py","file_name":"logRegres.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"568464692","text":"import numpy as np\nimport math\n\n\nclass Node:\n signal_type = -1\n signal_time = -1\n fid = -1\n x = 0\n y = 0\n\n def __init__(self, stype, stime, fid, x, y):\n self.signal_time = stime\n self.signal_type = stype\n self.fid = fid\n self.x = x\n self.y = y\n\n\nclass FingerprintSequence:\n category = 0\n signal_type = None\n fids = None\n uploader = None\n nodes_time = None\n nodes_location = None\n nodes_rssi = None\n feature_location = None\n feature_avg = None\n feature_std = None\n feature_max = None\n confidence = None\n\n def __init__(self, fid, x, y, signal_time, signal_type, uploader):\n self.signal_type = signal_type\n self.uploader = uploader\n self.fids = [fid]\n self.nodes_location = [[x, y]]\n self.nodes_time = [signal_time]\n # self.feature_location = np.array([0, 0])\n # self.feature_avg = np.array([])\n # self.feature_std = np.array([])\n # self.feature_max = np.array([])\n return\n\n def add_node(self, fid, x, y, signal_time):\n self.fids.append(fid)\n self.nodes_time.append(signal_time)\n self.nodes_location.append([x, y])\n return\n\n def feature_extraction(self):\n self.feature_location = np.mean(self.nodes_location, 0)\n self.feature_max = np.max(self.nodes_rssi, 0)\n self.feature_avg = np.array([None] * len(self.feature_max))\n self.feature_std = np.array([None] * len(self.feature_max))\n for i in range(len(self.nodes_rssi[0])):\n rssi_list = []\n for j in range(len(self.nodes_rssi)):\n if self.nodes_rssi[j][i] > -100:\n rssi_list.append(self.nodes_rssi[j][i])\n if len(rssi_list) > 0:\n self.feature_avg[i] = np.mean(rssi_list)\n self.feature_std[i] = np.std(rssi_list)\n else:\n self.feature_avg[i] = -100\n self.feature_std[i] = 0\n\n def __len__(self):\n return len(self.fids)\n\n @staticmethod\n def distance_loc(f1, f2):\n return np.sqrt(np.sum(np.square(f1.feature_location-f2.feature_location)))\n\n @staticmethod\n def distance_rssi(f1, f2):\n avg_d = np.sqrt(np.sum(np.square(f1.feature_avg - f2.feature_avg)))\n std_d = np.sqrt(np.sum(np.square(f1.feature_std - f2.feature_std)))\n max_d = np.sqrt(np.sum(np.square(f1.feature_max - f2.feature_max)))\n return avg_d + std_d + max_d\n\n\nclass Category:\n type = None\n data = None\n grids = None\n\n def __init__(self, data):\n self.data = data\n self.grids = {}\n for i in range(len(data)):\n current_seq = data[i]\n x = current_seq.feature_location[0]\n y = current_seq.feature_location[1]\n ceil_x = math.ceil(x)\n ceil_y = math.ceil(y)\n floor_x = math.floor(x)\n floor_y = math.floor(y)\n self.grids[str(ceil_x) + ' '+ str(ceil_y)] = 1\n self.grids[str(ceil_x) + ' ' + str(floor_y)] = 1\n self.grids[str(floor_x) + ' ' + str(ceil_y)] = 1\n self.grids[str(floor_x) + ' ' + str(floor_y)] = 1\n\n def __len__(self):\n return len(self.data)\n\n def matched(self, fingerprint_sequence):\n x = fingerprint_sequence.feature_location[0]\n y = fingerprint_sequence.feature_location[1]\n ceil_x = math.ceil(x)\n ceil_y = math.ceil(y)\n floor_x = math.floor(x)\n floor_y = math.floor(y)\n loc = 0\n if str(ceil_x) + ' ' + str(ceil_y) in self.grids:\n loc = 1\n elif str(floor_x) + ' ' + str(ceil_y) in self.grids:\n loc = 1\n elif str(ceil_x) + ' ' + str(floor_y) in self.grids:\n loc = 1\n elif str(floor_x) + ' ' + str(floor_y) in self.grids:\n loc = 1\n if loc > 0:\n return self.rssi_match(fingerprint_sequence)\n else:\n return False\n\n def rssi_match(self, seq):\n dist = []\n nei_count = 0\n for i in range(len(self.data)):\n d = FingerprintSequence.distance_rssi(self.data[i], seq)\n if d < np.sqrt(len(seq.feature_avg)) * 3:\n nei_count += 1\n dist.append(d)\n dist.sort()\n if(len(dist)) >= 3:\n return np.mean([1/(1+dist[i]/np.sqrt(len(seq.feature_avg))) for i in range(3)])\n return False\n\n\n\n\n\n\n\n\n","sub_path":"python/fingerprint-update/server_new/fingerprint_sequence.py","file_name":"fingerprint_sequence.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"155787853","text":"#!/usr/bin/python\nfrom bs4 import BeautifulSoup\nimport pymysql\nimport requests\nimport json\nimport threading\nimport re\n\n\ndef getDBcon():\n db = pymysql.connect(\n \"localhost\",\n \"root\",\n \"zqt1997\",\n \"21cnjy\",\n use_unicode=True,\n charset=\"utf8\")\n cursor = db.cursor()\n return db, cursor\n\n\ndef getData():\n db, cursor = getDBcon()\n cursor.execute(\n 'select * from knowledge_msg')\n data = cursor.fetchall()\n db.close()\n return data\n\n\ndef getJson(xd, chid, upid):\n url = 'https://www.21cnjy.com/soft.php?mod=zyindex_ajax&knowledges=1&xd=%s&chid=%s&upid=%s' % (\n xd, chid, upid)\n text = requests.get(url).text\n return text\n\n\ndef getKnowledge(pids, xd, chid, subjectId, depth=1):\n db, cursor = getDBcon()\n for i in range(len(pids)):\n pid = pids[i]\n print(pid)\n cdata = getJson(xd, chid, pid)\n try:\n js = json.loads(cdata)\n except:\n print(pid)\n chid_pid = []\n sort = 0\n for chapter in js:\n sort += 1\n rcode = chapter['id']\n cname = chapter['name']\n child = int(chapter['child'])\n level = depth+1\n chid_pid.append(rcode)\n if child == 0:\n is_last = 1\n else:\n is_last = 0\n sql = 'insert into dict_prepare_lesson_knowledge(knowleage_name,subject_id,parent_id,level,is_last,sort,knowledge_id) values (%s,%s,%s,%s,%s,%s,%s)'\n cursor.execute(sql, (cname, subjectId, pid,\n level, is_last, sort, rcode))\n \n print(subjectId, cname, pid, level, is_last, sort, rcode)\n db.commit()\n if len(chid_pid) > 0:\n getKnowledge(chid_pid, xd, chid, subjectId, depth=depth+1)\n db.close()\n\n\ndef work1():\n db, cursor = getDBcon()\n data = getData()\n for line in data:\n chid = line[0]\n subjectName = line[1]\n kid = line[2]\n subjectId = line[3]\n xd = line[4]\n url = 'https://www.21cnjy.com/knowledge.php?chid={}&kid={}'.format(\n chid, kid)\n text = requests.get(url).text\n # with open('x.html','w+') as f:\n # f.write(text)\n p = r'knowledges = (\\[.*?\\])'\n res = re.findall(p, text)[0]\n js = json.loads(res, encoding='utf8')\n for x in js:\n kid = x['id']\n kname = x['name']\n child = x['child']\n if int(child) > 0:\n is_last = 1\n else:\n is_last = 0\n sql = 'insert into dict_prepare_lesson_knowledge(knowleage_name,subject_id,parent_id,level,is_last,sort,knowledge_id) values (%s,%s,%s,%s,%s,%s,%s)'\n cursor.execute(sql, (kname, subjectId, 0, 1, is_last, 1, kid))\n print(kname, subjectId, 0, 1, is_last, 1, kid)\n db.commit()\n db.close()\n\n\ndef work2():\n db, cursor = getDBcon()\n sql = 'select k.id,k.knowledge_id,s.id,s.chid,s.xd from dict_prepare_lesson_knowledge as k inner join subject as s on s.id=k.subject_id and k.id>3'\n cursor.execute(sql)\n data = cursor.fetchall()\n for line in data:\n kid = line[0]\n spId = line[1]\n subjectId = line[2]\n chid = line[3]\n xd = line[4]\n print([spId], xd, chid, subjectId)\n getKnowledge([spId], xd, chid, subjectId)\n db.close()\n\n\nif __name__ == '__main__':\n work2()\n","sub_path":"教育网站/21cnjy/getKnowledge.py","file_name":"getKnowledge.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"384426104","text":"#======================================#\n# deeper systems neural networks test\n# @ claudio\n#=====================================#\n\n# import packages\nimport pandas as pd\nfrom PIL import Image\n\n# import data with predictions\npredata = pd.read_csv('results/test.preds.csv')\n\n# function to define rotation\ndef rotation(image, prediction):\n if prediction == 'upside_down':\n transposed = image.transpose(Image.ROTATE_180)\n elif prediction == 'rotated_right':\n transposed = image.transpose(Image.ROTATE_90)\n elif prediction == 'rotated_left':\n transposed = image.transpose(Image.ROTATE_270)\n else:\n return image\n return transposed\n\n# loop to rotate\nfor i in range(len(predata)):\n image = Image.open(('data/test/' + predata['fn'][i]))\n rotated = rotation(image, predata['label'][i])\n rotated.save('results/rotated/'+predata['fn'][i])\n","sub_path":"codes/rotate_images.py","file_name":"rotate_images.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"538729005","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nfrom unittest import mock\n\n\ndef test_mock_patch_object():\n with mock.patch.object(os, 'sys', mock.Mock(return_value=100)):\n assert os.sys() == 100\n\n with mock.patch.object(os, 'sys', return_value=101):\n assert os.sys() == 101\n\n\ndef test_mock_assert_has_calls():\n m = mock.Mock()\n m(1)\n m(2)\n m.assert_has_calls([mock.call(1), mock.call(2)])\n\n\ndef test_mock_call_args_list():\n m = mock.Mock()\n m(1)\n m(2)\n assert [mock.call(1), mock.call(2)] == m.call_args_list\n","sub_path":"test_mock.py","file_name":"test_mock.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"226477531","text":"\"\"\"\nPython wrapper for getting weather data from AccueWeather for Limited Trial package.\n\"\"\"\nimport json\nimport logging\nfrom typing import Any, Dict, List, Optional, Tuple, Union, cast\n\nfrom aiohttp import ClientSession\n\nfrom .const import (\n ATTR_CURRENT_CONDITIONS,\n ATTR_FORECAST,\n ATTR_GEOPOSITION,\n ENDPOINT,\n HTTP_HEADERS,\n HTTP_OK,\n HTTP_UNAUTHORIZED,\n REMOVE_FROM_CURRENT_CONDITION,\n REMOVE_FROM_FORECAST,\n REQUESTS_EXCEEDED,\n TEMPERATURES,\n URLS,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass AccuWeather:\n \"\"\"Main class to perform AccuWeather API requests\"\"\"\n\n def __init__( # pylint:disable=too-many-arguments\n self,\n api_key: str,\n session: ClientSession,\n latitude: Optional[float] = None,\n longitude: Optional[float] = None,\n location_key: Optional[str] = None,\n ):\n \"\"\"Initialize.\"\"\"\n if not self._valid_api_key(api_key):\n raise InvalidApiKeyError(\n \"Your API Key must be a 32-character hexadecimal string\"\n )\n\n if not location_key:\n if not self._valid_coordinates(latitude, longitude):\n raise InvalidCoordinatesError(\"Your coordinates are invalid\")\n\n self.latitude = latitude\n self.longitude = longitude\n self._api_key = api_key\n self._session = session\n self._location_key: Optional[str] = location_key\n self._location_name: Optional[str] = None\n self._requests_remaining: Optional[int] = None\n\n @staticmethod\n def _valid_coordinates(\n latitude: Union[float, int, None], longitude: Union[float, int, None]\n ) -> bool:\n \"\"\"Return True if coordinates are valid.\"\"\"\n try:\n assert isinstance(latitude, (int, float)) and isinstance(\n longitude, (int, float)\n )\n assert abs(latitude) <= 90 and abs(longitude) <= 180\n except (AssertionError, TypeError):\n return False\n return True\n\n @staticmethod\n def _valid_api_key(api_key: str) -> bool:\n \"\"\"Return True if API key is valid.\"\"\"\n try:\n assert isinstance(api_key, str)\n assert len(api_key) == 32\n except AssertionError:\n return False\n return True\n\n @staticmethod\n def _construct_url(arg: str, **kwargs: str) -> str:\n \"\"\"Construct AccuWeather API URL.\"\"\"\n url = ENDPOINT + URLS[arg].format(**kwargs)\n return url\n\n @staticmethod\n def _clean_current_condition(\n data: Dict[str, Any], to_remove: Tuple[str, ...]\n ) -> Dict[str, Any]:\n \"\"\"Clean current condition API response.\"\"\"\n return {key: data[key] for key in data if key not in to_remove}\n\n @staticmethod\n def _parse_forecast(data: dict, to_remove: tuple) -> list:\n \"\"\"Parse and clean forecast API response.\"\"\"\n parsed_data = [\n {key: value for key, value in item.items() if key not in to_remove}\n for item in data[\"DailyForecasts\"]\n ]\n\n for day in parsed_data:\n # For some forecast days, the AccuWeather API does not provide an Ozone value.\n day.setdefault(\"Ozone\", {})\n day[\"Ozone\"].setdefault(\"Value\")\n day[\"Ozone\"].setdefault(\"Category\")\n\n for item in day[\"AirAndPollen\"]:\n if item[\"Name\"] == \"AirQuality\":\n day[item[\"Type\"]] = item\n day[item[\"Type\"]].pop(\"Name\")\n day[item[\"Type\"]].pop(\"Type\")\n else:\n day[item[\"Name\"]] = item\n day[item[\"Name\"]].pop(\"Name\")\n day.pop(\"AirAndPollen\")\n\n for temp in TEMPERATURES:\n day[f\"{temp}Min\"] = day[temp][\"Minimum\"]\n day[f\"{temp}Max\"] = day[temp][\"Maximum\"]\n day.pop(temp)\n\n for key, value in day[\"Day\"].items():\n day[f\"{key}Day\"] = value\n day.pop(\"Day\")\n\n for key, value in day[\"Night\"].items():\n day[f\"{key}Night\"] = value\n day.pop(\"Night\")\n\n return parsed_data\n\n async def _async_get_data(self, url: str) -> Dict[str, Any]:\n \"\"\"Retreive data from AccuWeather API.\"\"\"\n async with self._session.get(url, headers=HTTP_HEADERS) as resp:\n if resp.status == HTTP_UNAUTHORIZED:\n raise InvalidApiKeyError(\"Invalid API key\")\n if resp.status != HTTP_OK:\n error_text = json.loads(await resp.text())\n if error_text[\"Message\"] == REQUESTS_EXCEEDED:\n raise RequestsExceededError(\n \"The allowed number of requests has been exceeded\"\n )\n raise ApiError(f\"Invalid response from AccuWeather API: {resp.status}\")\n _LOGGER.debug(\"Data retrieved from %s, status: %s\", url, resp.status)\n data = await resp.json()\n if resp.headers[\"RateLimit-Remaining\"].isdigit():\n self._requests_remaining = int(resp.headers[\"RateLimit-Remaining\"])\n return cast(Dict[str, Any], data if isinstance(data, dict) else data[0])\n\n async def async_get_location(self) -> None:\n \"\"\"Retreive location data from AccuWeather.\"\"\"\n url = self._construct_url(\n ATTR_GEOPOSITION,\n api_key=self._api_key,\n lat=str(self.latitude),\n lon=str(self.longitude),\n )\n data = await self._async_get_data(url)\n self._location_key = data[\"Key\"]\n self._location_name = data[\"LocalizedName\"]\n\n async def async_get_current_conditions(self) -> Dict[str, Any]:\n \"\"\"Retreive current conditions data from AccuWeather.\"\"\"\n if not self._location_key:\n await self.async_get_location()\n assert self._location_key is not None\n url = self._construct_url(\n ATTR_CURRENT_CONDITIONS,\n api_key=self._api_key,\n location_key=self._location_key,\n )\n data = await self._async_get_data(url)\n return self._clean_current_condition(data, REMOVE_FROM_CURRENT_CONDITION)\n\n async def async_get_forecast(self, metric: bool = True) -> List[Dict[str, Any]]:\n \"\"\"Retreive forecast data from AccuWeather.\"\"\"\n if not self._location_key:\n await self.async_get_location()\n assert self._location_key is not None\n url = self._construct_url(\n ATTR_FORECAST,\n api_key=self._api_key,\n location_key=self._location_key,\n metric=str(metric),\n )\n data = await self._async_get_data(url)\n return self._parse_forecast(data, REMOVE_FROM_FORECAST)\n\n @property\n def location_name(self) -> Optional[str]:\n \"\"\"Return location name.\"\"\"\n return self._location_name\n\n @property\n def location_key(self) -> Optional[str]:\n \"\"\"Return location key.\"\"\"\n return self._location_key\n\n @property\n def requests_remaining(self) -> Optional[int]:\n \"\"\"Return number of remaining allowed requests.\"\"\"\n return self._requests_remaining\n\n\nclass ApiError(Exception):\n \"\"\"Raised when AccuWeather API request ended in error.\"\"\"\n\n def __init__(self, status: str):\n \"\"\"Initialize.\"\"\"\n super().__init__(status)\n self.status = status\n\n\nclass InvalidApiKeyError(Exception):\n \"\"\"Raised when API Key format is invalid.\"\"\"\n\n def __init__(self, status: str):\n \"\"\"Initialize.\"\"\"\n super().__init__(status)\n self.status = status\n\n\nclass InvalidCoordinatesError(Exception):\n \"\"\"Raised when coordinates are invalid.\"\"\"\n\n def __init__(self, status: str):\n \"\"\"Initialize.\"\"\"\n super().__init__(status)\n self.status = status\n\n\nclass RequestsExceededError(Exception):\n \"\"\"Raised when allowed number of requests has been exceeded.\"\"\"\n\n def __init__(self, status: str):\n \"\"\"Initialize.\"\"\"\n super().__init__(status)\n self.status = status\n","sub_path":"accuweather/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"507715359","text":"import os, sys, subprocess, re, time, threading, sqlite3, sys\n\nFNULL = open(os.devnull, 'w')\nbenchmark_runner = os.path.join('build', 'release', 'benchmark', 'benchmark_runner')\nout_file = 'out.csv'\nlog_file = 'out.log'\ndefault_start_commit = '0109d4301b8ed005ca5396c177cf5ef36bef5274'\nduckdb_base = os.path.join(os.getcwd(), '..', 'duckdb')\nduckdb_web_base = os.getcwd()\nsqlite_db_file = os.path.join(duckdb_web_base, 'benchmarks.db')\n# 5 minute timeout per benchmark\ntotal_timeout = 300\n# slow benchmarks are skipped for all commits except the most recent commit to speed up benchmarking\n# e.g. if a merge of 20+ commits is done, we don't want to run the slow benchmarks for all commits\nslow_benchmarks = ['imdb']\nignored_benchmarks = ['expression_reordering']\n# the specific commit to run (if any)\nspecific_commit = None\n\nif len(sys.argv) > 1:\n specific_commit = sys.argv[1]\n print(\"Running specific commit \" + specific_commit)\n\ndef log(msg):\n print(msg)\n\ndef initdb():\n con = sqlite3.connect(sqlite_db_file)\n c = con.cursor()\n c.execute(\"\"\"\nCREATE TABLE benchmarks(\n id INTEGER PRIMARY KEY,\n name VARCHAR,\n groupname VARCHAR,\n subgroup VARCHAR,\n description VARCHAR);\"\"\")\n c.execute(\"\"\"\nCREATE TABLE groups(\n name VARCHAR,\n subgroup VARCHAR,\n display_name VARCHAR,\n description VARCHAR);\"\"\")\n c.execute(\"\"\"\nCREATE TABLE commits(\n hash VARCHAR PRIMARY KEY,\n date VARCHAR,\n message VARCHAR);\"\"\")\n c.execute(\"\"\"\nCREATE TABLE timings(\n hash VARCHAR,\n benchmark_id INTEGER,\n success BOOLEAN,\n median DOUBLE,\n timings VARCHAR,\n error VARCHAR,\n profile VARCHAR,\n meta_info VARCHAR,\n graph_json VARCHAR,\n stdout VARCHAR,\n stderr VARCHAR);\"\"\")\n con.commit()\n con.close()\n\nrun_with_timeout_returncode = 0\ndef run_with_timeout(command, timeout):\n global run_with_timeout_returncode\n def run_with_timeout_internal(command):\n global run_with_timeout_returncode\n run_with_timeout_returncode = os.system(' '.join(command) + \" > out.log 2>err.log\")\n\n try:\n os.remove('out.log')\n except:\n pass\n try:\n os.remove('err.log')\n except:\n pass\n thread = threading.Thread(target=run_with_timeout_internal, args=(command,))\n thread.start()\n\n thread.join(timeout)\n\n stdout = \"\"\n stderr = \"\"\n try:\n with open('out.log', 'r') as f:\n stdout = f.read()\n with open('err.log', 'r') as f:\n stderr = f.read()\n except:\n pass\n\n if thread.is_alive():\n log(\"Force terminating process...\")\n os.system('killall -9 benchmark_runner')\n error_msg = \"TIMEOUT\"\n thread.join()\n return (1, stdout, stderr, error_msg)\n return (run_with_timeout_returncode, stdout, stderr, \"\")\n\n\ndef pull_new_changes():\n # pull from duckdb-web\n os.chdir(duckdb_web_base)\n proc = subprocess.Popen(['git', 'pull'], stdout=FNULL)\n proc.wait()\n # pull from duckdb\n os.chdir(duckdb_base)\n proc = subprocess.Popen(['git', 'pull', 'origin', 'master'], stdout=FNULL)\n proc.wait()\n\ndef build_optimized():\n log(\"Starting optimized build\")\n # always rebuild\n os.system('rm -rf build')\n os.environ['BUILD_BENCHMARK'] = '1'\n os.environ['BUILD_TPCH'] = '1'\n os.environ['BUILD_PYTHON'] = '1'\n os.environ['USER_SPACE'] = '1'\n (return_code, stdout, stderr, error_msg) = run_with_timeout(['make', 'opt', '-j'], 1200)\n\n if return_code != 0:\n print(\"Failed to compile, moving on to next commit\")\n print(stdout)\n print(stderr)\n print(error_msg)\n return False\n else:\n log(\"Finished optimized build\")\n return True\n\ndef get_list_of_commits(until_commit=None):\n proc = subprocess.Popen(['git', 'checkout', 'master'], stdout=subprocess.PIPE)\n proc.wait()\n commit_list = []\n commit_regex = re.compile('commit ([a-z0-9]{40})')\n proc = subprocess.Popen(['git', 'log'], stdout=subprocess.PIPE)\n while True:\n line = proc.stdout.readline().decode('utf8')\n if line == '':\n break\n match = commit_regex.search(line)\n if match != None:\n commit_number = match.groups()[0]\n if commit_number == until_commit:\n break\n commit_list.append(commit_number)\n commit_list.reverse()\n return commit_list\n\ndef switch_to_commit(commit_number):\n proc = subprocess.Popen(['git', 'checkout', commit_number])\n proc.wait()\n return proc.returncode == 0\n\ndef get_benchmark_list():\n benchmark_list = []\n proc = subprocess.Popen([benchmark_runner, '--list'], stdout=subprocess.PIPE)\n for line in proc.stdout.read().decode('utf8').split('\\n'):\n bname = line.rstrip()\n if len(bname) > 0:\n benchmark_list.append(bname)\n return benchmark_list\n\n\nclass RunBenchmark(object):\n def __init__(self, benchmark, log_file, stdout_name, stderr_name, out_file):\n self.benchmark = benchmark\n self.log_file = log_file\n self.stdout_name = stdout_name\n self.stderr_name = stderr_name\n self.out_file = out_file\n self.proc = None\n self.error_msg = \"\"\n\n def run(self, timeout):\n command = [benchmark_runner, '--out=' + self.out_file, '--log=' + self.log_file, self.benchmark]\n\n (returncode, self.stdout, self.stderr, self.error_msg) = run_with_timeout(command, timeout)\n return returncode\n\ndef benchmark_already_ran(benchmark_id, commit_hash):\n # first check if this benchmark has already been run\n c.execute(\"SELECT * FROM timings WHERE benchmark_id=? AND hash=?\", (benchmark_id, commit_hash))\n results = c.fetchall()\n if len(results) > 0:\n return True\n return False\n\ndef run_benchmark(benchmark, benchmark_id, commit_hash):\n if benchmark_already_ran(benchmark_id, commit_hash):\n return\n\n log(\"Starting benchmark \" + benchmark)\n base_path = '/tmp/benchmark'\n\n log_file = base_path + \".log\"\n stdout_name = base_path + \".stdout.log\"\n stderr_name = base_path + \".stderr.log\"\n runner = RunBenchmark(benchmark, log_file, stdout_name, stderr_name, out_file)\n\n return_code = runner.run(total_timeout)\n\n error_msg = \"\"\n if len(runner.error_msg) > 0:\n error_msg = runner.error_msg\n elif return_code != 0:\n log(\"Failed to run benchmark \" + benchmark)\n error_msg = \"CRASH\"\n else:\n log(\"Succeeded in running benchmark \" + benchmark)\n try:\n # succeeded, gather data\n stdout = runner.stdout\n stderr = runner.stderr\n timings = []\n with open(runner.out_file, 'r') as f:\n for line in f.read().split('\\n'):\n line = line.strip()\n if len(line) == 0:\n continue\n try:\n timings.append(float(line))\n except:\n error_msg = line\n raise\n timing_info = ','.join([str(x) for x in timings])\n timings.sort()\n median = timings[int(len(timings) / 2)]\n with open(runner.log_file, 'r') as f:\n profile_info = f.read()\n except:\n if len(error_msg) == 0:\n # no error message specified\n raise\n\n if len(error_msg) > 0:\n # insert error into database\n print(\"Error: \" + error_msg)\n c.execute(\"INSERT INTO timings (benchmark_id, hash, success, error) VALUES (?, ?, ?, ?)\", (benchmark_id, commit_hash, False, error_msg))\n else:\n # insert data about benchmark into database\n print(\"Median timing: \" + str(median))\n c.execute(\"INSERT INTO timings (benchmark_id, hash, success, median, timings, profile, stdout, stderr, meta_info) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'none')\", (benchmark_id, commit_hash, True, median, timing_info, profile_info, stdout, stderr))\n con.commit()\n\ndef get_benchmark_info(benchmark):\n display_name = None\n groupname = None\n subgroup = None\n proc = subprocess.Popen([benchmark_runner, '--info', benchmark], stdout=subprocess.PIPE)\n lines = proc.stdout.read().decode('utf8').strip().split('\\n')\n for line in lines:\n line = line.strip()\n if len(line) == 0:\n continue\n splits = line.split(':')\n if splits[0] == 'display_name':\n display_name = splits[1].strip()\n elif splits[0] == 'group':\n groupname = splits[1].strip()\n elif splits[0] == 'subgroup':\n subgroup = splits[1].strip()\n if len(subgroup) == 0:\n subgroup = None\n return (display_name, groupname, subgroup)\n\ndef insert_benchmark_info(display_name,groupname,subgroup):\n # first figure out if the benchmark is already in the database\n c.execute(\"SELECT id, groupname FROM benchmarks WHERE name=?\", (display_name,))\n results = c.fetchall()\n if len(results) > 0:\n # benchmark already exists, return the id\n return (results[0][0], results[0][1])\n # benchmark does not exist, write it to the database\n # get info and group\n # write to db\n c.execute(\"INSERT INTO benchmarks (name, groupname, subgroup) VALUES (?, ?, ?)\", (display_name, groupname, subgroup))\n c.execute(\"SELECT id, groupname FROM benchmarks WHERE name=?\", (display_name,))\n results = c.fetchall()\n if len(results) > 0:\n # benchmark already exists, return the id\n return (results[0][0], results[0][1])\n\n\ndef write_benchmark_info(benchmark):\n (display_name, groupname, subgroup) = get_benchmark_info(benchmark)\n if display_name is None:\n log(\"Failed to fetch display name for benchmark \" + benchmark)\n return (None, None)\n return insert_benchmark_info(display_name,groupname,subgroup)\n\ndef run_arrow(commit_hash,column_name,experiment_name,duck_con):\n import statistics,duckdb,pyarrow\n duck_to_arrow = []\n arrow_to_duck = []\n for i in range(6):\n duck_con.execute(\"select \" + column_name + \" from t;\")\n\n start_time = time.time()\n result = duck_con.fetch_arrow_table()\n time_duck_to_arrow = time.time() - start_time\n\n start_time = time.time()\n result = duckdb.from_arrow_table(result)\n time_arrow_to_duck = time.time() - start_time\n\n if i!= 0:\n duck_to_arrow.append(time_duck_to_arrow)\n arrow_to_duck.append(time_arrow_to_duck)\n\n (benchmark_id, groupname) = insert_benchmark_info('duckdb -> arrow ' + experiment_name,'arrow_integration','')\n c.execute(\"INSERT INTO timings (benchmark_id, hash, success, median) VALUES (?, ?, ?, ?)\", (benchmark_id, commit_hash, True, statistics.median(duck_to_arrow)))\n (benchmark_id, groupname) = insert_benchmark_info('arrow -> duckdb ' + experiment_name,'arrow_integration','')\n c.execute(\"INSERT INTO timings (benchmark_id, hash, success, median) VALUES (?, ?, ?, ?)\", (benchmark_id, commit_hash, True, statistics.median(arrow_to_duck)))\n con.commit()\n\ndef run_arrow_tpch(commit_hash,duck_con):\n #Only run Queries 1 and 6\n import statistics,duckdb,pyarrow\n query_times = []\n tpch_queries = [1,6]\n duck_con.execute(\"CALL dbgen(sf=1);\")\n tpch_tables = ['lineitem']\n arrow_tables = []\n for tpch_table in tpch_tables:\n duck_tbl = duck_con.table(tpch_table)\n arrow_tables.append(duck_tbl.arrow())\n duck_arrow_table = duck_con.from_arrow_table(arrow_tables[-1])\n duck_con.execute(\"DROP TABLE \"+tpch_table)\n duck_arrow_table.create(tpch_table)\n\n for tpch_query in tpch_queries:\n query = duck_con.execute(\"select query from tpch_queries() where query_nr=\"+str(tpch_query)).fetchone()[0]\n for i in range(6):\n start_time = time.time()\n result = duck_con.execute(query)\n q_time = time.time() - start_time\n if i!= 0:\n query_times.append(q_time)\n\n (benchmark_id, groupname) = insert_benchmark_info('arrow tpch Q'+str(tpch_query),'arrow_integration','')\n c.execute(\"INSERT INTO timings (benchmark_id, hash, success, median) VALUES (?, ?, ?, ?)\", (benchmark_id, commit_hash, True, statistics.median(query_times)))\n con.commit()\n\ndef run_arrow_parallel(commit_hash,duck_con):\n import statistics,duckdb,pyarrow, numpy\n batch_sizes = [1024, 100000, 1000000]\n num_threads = [1,2,4,8]\n data = (pyarrow.array(numpy.random.randint(800, size=100000000), type=pyarrow.int32()))\n duckdb_conn = duckdb.connect()\n for batch in batch_sizes:\n for thread in num_threads:\n tbl = pyarrow.Table.from_batches(pyarrow.Table.from_arrays([data],['a']).to_batches(batch))\n rel = duckdb_conn.from_arrow_table(tbl)\n duckdb_conn.execute(\"PRAGMA threads=\"+str(thread))\n duckdb_conn.execute(\"PRAGMA force_parallelism\")\n total_times=[]\n for i in range(6):\n start_time = time.time()\n result = rel.aggregate(\"(count(a))::INT\").execute()\n total_time = time.time() - start_time\n if i!= 0:\n total_times.append(total_time)\n\n (benchmark_id, groupname) = insert_benchmark_info('threads:' +str(thread) + ' batch_size:' +str(batch) ,'arrow_integration','')\n c.execute(\"INSERT INTO timings (benchmark_id, hash, success, median) VALUES (?, ?, ?, ?)\", (benchmark_id, commit_hash, True, statistics.median(total_times)))\n con.commit()\n\ndef run_arrow_benchmarks(commit_hash):\n import duckdb\n duck_con = duckdb.connect()\n duck_con.execute (\"\"\"create temporary table t as \n select (RANDOM()*(100000)+10000000)::INTEGER int_val,\n CASE\n WHEN range%10=0 THEN NULL\n ELSE (RANDOM()*(100000)+10000000)::INTEGER\n END int_n_val,\n\n (RANDOM()*(100000)+10000000)::INTEGER::VARCHAR str_val,\n CASE\n WHEN range%10=0 THEN NULL\n ELSE (RANDOM()*(100000)+10000000)::INTEGER::VARCHAR\n END str_n_val\n\n from range(100000000);\"\"\")\n\n run_arrow(commit_hash,'int_val','int',duck_con)\n run_arrow(commit_hash,'int_n_val','int (null)',duck_con)\n run_arrow(commit_hash,'str_val','str',duck_con)\n run_arrow(commit_hash,'str_n_val','str (null)',duck_con)\n run_arrow_parallel(commit_hash,duck_con)\n run_arrow_tpch(commit_hash,duck_con)\n\n\ndef run_benchmark_for_commit(commit, run_slow_benchmarks):\n log(\"Benchmarking commit \" + commit)\n # switch to this commit in the source tree\n if not switch_to_commit(commit):\n log(\"Failed to switch to commit!\")\n return\n\n # get the commit hash, date and commit msg from the commit\n proc = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE)\n commit = proc.stdout.read().decode('utf8').strip()\n proc = subprocess.Popen(['git', 'show', '-s', '--format=%ci', commit], stdout=subprocess.PIPE)\n date = proc.stdout.read().decode('utf8').strip()\n proc = subprocess.Popen(['git', 'show', '-s', '--format=%B', commit], stdout=subprocess.PIPE)\n commit_msg = proc.stdout.read().decode('utf8').strip()\n if 'Merge pull request' not in commit_msg:\n log(\"Skipping commit \" + commit + \", not a pull request merge (\" + commit_msg + \")\")\n return\n\n # now try to compile it\n if not build_optimized():\n log(\"Failed to build!\")\n return\n\n # now run the benchmarks\n benchmarks_to_run = get_benchmark_list()\n for benchmark in benchmarks_to_run:\n (benchmark_id, groupname) = write_benchmark_info(benchmark)\n if benchmark_id is None:\n log(\"Failed to fetch benchmark id for benchmark \" + benchmark)\n return\n if groupname in ignored_benchmarks or (groupname in slow_benchmarks and not run_slow_benchmarks):\n continue\n run_benchmark(benchmark, benchmark_id, commit)\n run_arrow_benchmarks(commit)\n # finished running this commit: insert it into the list of completed commits\n c.execute(\"SELECT * FROM commits WHERE hash=?\", (commit,))\n if len(c.fetchall()) == 0:\n c.execute('INSERT INTO commits (hash, date, message) VALUES (?, ?, ?)', (commit, date, commit_msg))\n con.commit()\n\n# initialize the sqlite database, if it does not exist yet\nif not os.path.isfile(sqlite_db_file):\n initdb()\n\ncon = sqlite3.connect(sqlite_db_file)\nc = con.cursor()\n\npull_new_changes()\n\nif specific_commit != None:\n run_benchmark_for_commit(specific_commit, False)\n exit(0)\n\n# figure out the highest commit hash we already ran by looking into the db\nc.execute(\"\"\"\nSELECT hash\nFROM commits\nORDER BY date DESC\nLIMIT 1\n\"\"\")\n\nprev_hash = default_start_commit\nresults = c.fetchall()\nif len(results) > 0:\n prev_hash = results[0][0]\n\nprint(\"Running benchmarks since commit \" + prev_hash)\n\n# get a list of all commits we need to run\ncommit_list = get_list_of_commits(prev_hash)\nif len(commit_list) == 0:\n exit(1)\n\nprint(\"List of commits: \" + str(commit_list))\n\nfor commit in commit_list:\n is_final_commit = commit == commit_list[-1]\n run_benchmark_for_commit(commit, is_final_commit)\n\n\n\n","sub_path":"scripts/run_benchmarks.py","file_name":"run_benchmarks.py","file_ext":"py","file_size_in_byte":17278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"438824485","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nfrom setuptools.command.test import test as TestCommand\n\ntry:\n from setuptools import setup, find_packages\nexcept ImportError:\n from distutils.core import setup, find_packages\n\n# To prevent importing about and thereby breaking the coverage info we use this\n# exec hack\nabout = {}\nwith open('mt940/__about__.py') as fp:\n exec(fp.read(), about)\n\n\nclass PyTest(TestCommand):\n user_options = [('pytest-args=', 'a', 'Arguments to pass to pytest')]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n self.pytest_args = ''\n\n def run_tests(self):\n import shlex\n # import here, cause outside the eggs aren't loaded\n import pytest\n errno = pytest.main(shlex.split(self.pytest_args))\n sys.exit(errno)\n\n\ntests_require = [\n 'pyyaml',\n 'pytest',\n 'pytest-cache',\n 'pytest-cover',\n 'pytest-flake8',\n 'flake8',\n]\n\n\nif sys.argv[-1] == 'info':\n for k, v in about.items():\n print('%s: %s' % (k, v))\n sys.exit()\n\nif __name__ == '__main__':\n with open('README.rst') as fh:\n try:\n import sphinx2rst\n readme = sphinx2rst.sphinx_to_rst(fh)\n except ImportError:\n readme = fh.read()\n\n try:\n import git\n try:\n repo = git.Repo('.')\n except git.exc.InvalidGitRepositoryError:\n raise ImportError()\n\n if repo.bare:\n raise ImportError()\n\n tags = [tag.tag for tag in repo.tags if tag.tag]\n tags = sorted(tags, key=lambda tag: tag.tagged_date, reverse=True)\n changes = [\n '',\n '',\n 'Changelog',\n '---------',\n ]\n\n for tag in tags:\n version = tag.tag\n if version[0] != 'v':\n version = 'v' + version\n\n message = tag.message.split('\\n')[0]\n changes.append(' * **%s** %s' % (version, message))\n\n changes = '\\n'.join(changes)\n except ImportError:\n changes = ''\n\n setup(\n name=about['__package_name__'],\n version=about['__version__'],\n author=about['__author__'],\n author_email=about['__email__'],\n description=about['__description__'],\n url=about['__url__'],\n license=about['__license__'],\n keywords=about['__title__'],\n packages=find_packages(exclude=['docs']),\n long_description=readme + changes,\n include_package_data=True,\n tests_require=tests_require,\n setup_requires=[\n 'setuptools>=39.1.0',\n ],\n zip_safe=False,\n cmdclass={'test': PyTest},\n extras_require={\n 'docs': [\n 'sphinx>=1.7.2',\n 'GitPython>=2.1.9',\n 'sphinx2rst',\n ],\n 'tests': tests_require,\n },\n classifiers=[\n 'Development Status :: 6 - Mature',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Programming Language :: Python :: Implementation :: PyPy',\n ],\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"116343416","text":"import config\r\nimport praw\r\nimport json\r\nimport argparse\r\nimport datetime\r\n\r\n\r\nreddit = praw.Reddit(client_id= config.client_id,\r\n client_secret= config.client_secret,\r\n user_agent= config.user_agent)\r\n\r\ndef get_parser():\r\n parser = argparse.ArgumentParser(description=\"Reddit Downloader\")\r\n parser.add_argument(\"-s\",\r\n \"--subreddit\",\r\n dest=\"subreddit\",\r\n help=\"Subreddit to PRAW\",\r\n default='all')\r\n\r\n parser.add_argument(\"-l\",\r\n \"--limit\",\r\n dest=\"limit\",\r\n help=\"Pull N number of submissions\",\r\n default=None)\r\n\r\n return parser\r\n\r\ndef prawSubreddit(subName, lm):\r\n print(\"Collecting from /r/{}...\".format(subName))\r\n submissionCount = 0\r\n commentCount = 0\r\n fileCount = 0\r\n redditData = {}\r\n\r\n subreddit = reddit.subreddit(subName)\r\n submissions = subreddit.new(limit=lm)\r\n redditData[str(subreddit)] = [{}]\r\n\r\n # Iterate through each submissions and following comments\r\n for submission in submissions:\r\n submissionCount += 1\r\n submission.comments.replace_more(limit=None)\r\n redditData[str(subreddit)][0][submission.fullname] = [{}]\r\n redditData[str(subreddit)][0][submission.fullname][0]['0_title'] = submission.title\r\n redditData[str(subreddit)][0][submission.fullname][0]['1_text'] = submission.selftext\r\n redditData[str(subreddit)][0][submission.fullname][0]['3_author'] = str(submission.author)\r\n redditData[str(subreddit)][0][submission.fullname][0]['2_timestamp'] = str(datetime.datetime.fromtimestamp(submission.created))\r\n redditData[str(subreddit)][0][submission.fullname][0]['comments'] = [{}]\r\n\r\n for comment in submission.comments.list():\r\n commentCount += 1\r\n if(not userExistInComments(redditData[str(subreddit)][0][submission.fullname][0]['comments'][0], str(comment.author))):\r\n redditData[str(subreddit)][0][submission.fullname][0]['comments'][0][str(comment.author)] = [{}] # Only run is it does not exist\r\n\r\n redditData[str(subreddit)][0][submission.fullname][0]['comments'][0][str(comment.author)][0][str(comment)] = [{}]\r\n redditData[str(subreddit)][0][submission.fullname][0]['comments'][0][str(comment.author)][0][str(comment)][0][\"0_timestamp\"] = str(datetime.datetime.fromtimestamp(comment.created_utc))\r\n redditData[str(subreddit)][0][submission.fullname][0]['comments'][0][str(comment.author)][0][str(comment)][0][\"1_text\"] = comment.body\r\n\r\n updateTerminal(submissionCount, commentCount, )\r\n\r\n if(submissionCount % 300 == 0):\r\n writeOutput(\"{}_{}.txt\".format(subName,fileCount),redditData)\r\n fileCount += 1\r\n redditData = {}\r\n subreddit = reddit.subreddit(subName)\r\n redditData[str(subreddit)] = [{}]\r\n\r\n print(\"Finished Collecting.\")\r\n writeOutput(\"{}_{}.txt\".format(subName,fileCount),redditData)\r\n\r\ndef userExistInComments(commentList, user):\r\n if user in commentList:\r\n return True\r\n return False\r\n\r\ndef writeOutput(fileName, data):\r\n outputFile = open(fileName, \"w\")\r\n outputFile.write(json.dumps(data, sort_keys=True))\r\n\r\n# After X amount of seconds, update progress to terminal\r\ndef updateTerminal( subCount, comCount):\r\n #if ((subCount % 350) == 0):\r\n print(\"Downloaded: {} Submissions\".format(subCount))\r\n print(\"Downloaded: {} Comments\".format(comCount))\r\n\r\n@classmethod\r\ndef parse(cls, api, raw):\r\n status = cls.first_parse(api, raw)\r\n setattr(status, 'json', json.dumps(raw))\r\n return status\r\n\r\nif __name__ == '__main__':\r\n\r\n parser = get_parser()\r\n args = parser.parse_args()\r\n\r\n limit = args.limit\r\n if (limit != None):\r\n limit = int(limit)\r\n\r\n prawSubreddit(args.subreddit, limit)","sub_path":"subreddit_collection.py","file_name":"subreddit_collection.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"484011210","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pickle\nd = dict(name = 'Bob', age = 20, score=88)\nprint(pickle.dumps(d))\n\nf = open(r'.\\11.IO\\dump.txt','wb')\npickle.dump(d, f)\nf.close()\n\nf = open(r'.\\11.IO\\dump.txt', 'rb')\nd = pickle.load(f)\nprint(d)\nf.close()","sub_path":"12.IO/7.pickle.py","file_name":"7.pickle.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"75427110","text":"# -*- coding:utf-8 -*-\nimport datetime\nimport http\nimport os\nimport socket\nimport sys\nimport threading\nimport time\nimport traceback\nimport hashlib\nfrom logging import getLogger, INFO, Formatter\nfrom tqdm import tqdm\n\nimport requests\nimport threadpool\nfrom cloghandler import ConcurrentRotatingFileHandler\n\nimport model.db as dbm\n# 自有模块\nimport model.model as model\n\nfinish_num = 0\ntqdm_list = {}\n\n\ndef download(key, lock, log, progress, thread_num):\n \"\"\"\n 多线程,线程指定函数\n :param progress: 进度条对象\n :param thread_num: 进程编号\n :param key: 多个任务中的第key个,用于展示或日志\n :param lock: 锁,用于数据库的排他\n :param log: 日志对象,用于全局的日志记录\n :return:\n \"\"\"\n start = time.time()\n log.info('开始下载 key:%s' % key)\n lock.acquire()\n try:\n db = dbm.DbManager()\n session = db.get_session()\n one_data = session.query(model.Item).filter(model.Item.status == 0).first()\n # print(one_data)\n # exit()\n if one_data:\n data_id = one_data.id\n data_url = one_data.url\n data_type = one_data.type\n data_name = one_data.blog_name\n data_time = one_data.post_time\n one_data.status = 1\n db.add_data(one_data)\n log.info('获取数据完成 key: %s id: %s' % (key, str(data_id)))\n else:\n log.info('获取数据失败 key: %s' % key)\n return False\n except Exception as e:\n # raise e\n # print(e)\n log.error('id: %s key: %s 发生错误: %s' % (str(one_data.id), str(key), str(e)))\n return False\n finally:\n lock.release()\n\n download_data = {'id': data_id, 'url': data_url, 'blog_name': data_name, 'type': data_type, 'time': data_time}\n md5_val = download_img(download_data, 1, log, thread_num, key, lock)\n if not md5_val:\n db = dbm.DbManager()\n one_data = db.session.query(model.Item).filter(model.Item.id == data_id).first()\n one_data.status = 2\n db.add_data(one_data)\n log.info('下载失败 key:%s id: %s' % (key, data_id))\n return False\n else:\n db = dbm.DbManager()\n one_data = db.session.query(model.Item).filter(model.Item.id == data_id).first()\n one_data.status = 3\n one_data.md5 = md5_val\n db.add_data(one_data)\n end = time.time()\n log.info('下载完毕 key:%s 用时: %s秒' % (key, int(end - start)))\n # print('下载完毕 key:%s 用时: %s秒' % (key, int(end - start)))\n global finish_num\n finish_num = finish_num + 1\n # print(finish_num)\n progress.update(1)\n return True\n\n\ndef download_img(one_data, try_times=1, log=None, thread_num=0, key=0, lock=None):\n \"\"\"\n 实际下载方法,递归实现多次尝试\n :param key: 多个任务中的第key个,用于展示或日志\n :param thread_num:进程编号\n :param one_data: 需要下载的数据 字典类型\n :param try_times: 尝试次数,默认为1\n :param log: 日志对象\n :return:\n \"\"\"\n # 绝对路径\n target_path = '/Volumes/hhd/python_download/tum/'\n target_path = os.path.join(target_path, 'download_' + time.strftime(\"%Y-%m-%d\", time.localtime()))\n if not os.path.exists(target_path):\n os.mkdir(target_path)\n try:\n\n video_dir = os.path.join(target_path, 'video')\n pic_dir = os.path.join(target_path, 'pic')\n\n # this_dir = os.path.join(target_path, 'download_' + time.strftime(\"%Y-%m-%d\", time.localtime()))\n\n if one_data['type'] == 1:\n # 根据不同类型设置过期时间\n time_limit = 30\n # 视频写死扩展\n ext = '.mp4'\n this_dir = os.path.join(video_dir, one_data['blog_name'])\n new_dir = os.path.join(this_dir, 'post_' + time.strftime(\"%Y-%m-%d\", time.localtime(one_data['time'])))\n else:\n # 根据不同类型设置过期时间\n time_limit = 10\n # 动态获取扩展\n ext = os.path.splitext(one_data['url'])[1]\n this_dir = os.path.join(pic_dir, one_data['blog_name'])\n new_dir = os.path.join(this_dir, 'post_' + time.strftime(\"%Y-%m-%d\", time.localtime(one_data['time'])))\n\n if not os.path.exists(new_dir):\n # 目录自动创建\n os.makedirs(new_dir)\n # 组装文件名称\n new_filename = os.path.join(new_dir, str(one_data['id']) + ext)\n # 获取开始下载时间\n\n url = one_data['url']\n except Exception as e:\n log.info('发生错误:%s url:%s' % (str(e), one_data['url']))\n return False\n try:\n proxies = {\"http\": \"http://127.0.0.1:1087\", \"https\": \"https://127.0.0.1:1087\", }\n r = requests.get(url, proxies=proxies, stream=True, timeout=time_limit)\n size = int(r.headers['Content-Length']) // 1024\n position = get_position(lock, log) + 1\n log.info('key:%s thread_num:%s postion:%s' % (str(key), str(thread_num), str(position)))\n except Exception as e:\n # traceback.print_exc()\n log.info('发生错误:%s url:%s' % (str(e), one_data['url']))\n return False\n try:\n m = hashlib.md5()\n t = tqdm(iterable=r.iter_content(1024), total=size, unit='k', desc='%d' % (key % thread_num),\n position=position)\n with open(new_filename, 'wb') as f:\n for data in t:\n m.update(data)\n f.write(data)\n t.clear()\n t.close()\n except (http.client.IncompleteRead, socket.timeout) as ie:\n # 下载超时或不完整则重试\n if try_times > 3:\n log.error('id: %s 尝试次数过多 url:%s' % (one_data['id'], one_data['url']))\n return False\n else:\n log.info('id: %s 获取不为完整,重试: %s' % (one_data['id'], str(ie)))\n return download_img(one_data, try_times + 1, log, thread_num, key)\n except Exception as e:\n log.info('发生错误:%s url:%s' % (str(e), one_data['url']))\n return False\n unset_position(position - 1, lock)\n # print(m.hexdigest())\n md5_val = m.hexdigest()\n # 查询是否存在相同文件\n db = dbm.DbManager()\n exist_md5 = db.session.query(model.Item).filter(model.Item.md5 == md5_val, model.Item.id != one_data['id']).first()\n if exist_md5:\n # print(exist_md5)\n log.info('%s md5重复:%s,删除文件:%s' % (one_data['id'],exist_md5.id, new_filename))\n os.remove(new_filename)\n return md5_val\n\n\ndef main():\n \"\"\"\n 多线程博文下载:采用多线程下载博文,博文根据博客名分文件夹.再根据发布日期分文件夹\n python3 download.py 1000 10 启动10个线程下载1000个博文\n \"\"\"\n args = sys.argv\n if len(args) == 2:\n limit = int(args[1])\n thread_num = 8\n elif len(args) == 3:\n limit = int(args[1])\n thread_num = int(args[2])\n else:\n limit = 1\n thread_num = 1\n begin = time.time()\n\n # 日志相关初始化\n if not os.path.isdir('log'):\n os.mkdir('log')\n log_file_name = '%s-%s.log' % (os.path.basename(__file__).replace('.py', ''), datetime.date.today())\n log_full_file_name = os.path.join('log', log_file_name)\n log = getLogger()\n rotateHandler = ConcurrentRotatingFileHandler(log_full_file_name, \"a\", 512 * 1024, 0, 'utf-8')\n datefmt_str = '%Y-%m-%d %H:%M:%S'\n format_str = \"[%(asctime)s - %(levelname)s - %(filename)s - LINE:%(lineno)d] %(message)s\"\n formatter = Formatter(format_str, datefmt_str)\n rotateHandler.setFormatter(formatter)\n log.addHandler(rotateHandler)\n log.setLevel(INFO)\n\n log.info('开始执行: 启动%s个线程下载%s个博文' % (thread_num, limit))\n # 实例化线程锁\n lock = threading.Lock()\n # 创建线程池\n pool = threadpool.ThreadPool(thread_num)\n global tqdm_list\n for x in range(thread_num):\n tqdm_list[x] = 0\n # print(tqdm_list)\n # print(get_position())\n # return False\n requests_list = []\n progress = tqdm(total=limit, desc='total')\n for x in range(limit):\n requests_list.append(([x, lock, log, progress, thread_num], None))\n requests_res = threadpool.makeRequests(download, requests_list)\n [pool.putRequest(req) for req in requests_res]\n pool.wait()\n\n\ndef fmt_time(sec):\n if 60 <= sec <= 3600:\n return '%d分%d秒' % (sec / 60, sec % 60)\n elif sec < 60:\n return '%d秒' % sec\n elif sec > 3600:\n return '%d小时%d分%d秒' % (sec / 3600, sec % 3600 / 60, sec % 3600 % 60)\n\n\ndef get_position(lock=None, log=None):\n lock.acquire()\n try:\n global tqdm_list\n for x in range(len(tqdm_list)):\n if tqdm_list[x] == 0:\n tqdm_list[x] = 1\n return x\n finally:\n lock.release()\n log.info('position error' + str(tqdm_list))\n for x in range(len(tqdm_list)):\n tqdm_list[x] = 0\n\n\ndef unset_position(position, lock=None):\n lock.acquire()\n try:\n global tqdm_list\n tqdm_list[position] = 0\n finally:\n lock.release()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"download_md5.py","file_name":"download_md5.py","file_ext":"py","file_size_in_byte":9220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"249589090","text":"# -*- coding: utf-8 -*-\n\"\"\" AAA \"\"\"\nimport logging\nfrom pyramid.view import view_config\nfrom arttest.logic.returnhelper import response\nfrom arttest.facades.types import TypesFacade\nfrom arttest.facades.accounts import AccountsFacade\nfrom arttest.logic.helpers import dtnow\nfrom datetime import datetime\n\nLOG = logging.getLogger(__name__)\n\nclass ArticleViews(object):\n \"\"\" docstring for ArticleViews \"\"\"\n def __init__(self, request):\n super(ArticleViews, self).__init__()\n self.request = request\n self.facade = TypesFacade(request)\n self.accounts = AccountsFacade(request)\n self.userinfo = self.accounts.logged()\n self.uid = request.authenticated_userid\n\n @view_config(route_name='types', request_method=\"GET\",\n renderer='arttest:templates/types.html', xhr=False, http_cache=60)\n def main(self):\n \"\"\" Index \"\"\"\n LOG.debug(\"Articles: w/o xhr for: %s\", self.uid)\n return dict(userinfo=self.userinfo, dt=dtnow())\n\n @response\n @view_config(route_name='types_details', request_method=\"GET\",\n renderer='json', xhr=True, permission='view')\n def getall(self):\n \"\"\" Returns all types \"\"\"\n LOG.info(\"Get all xhr for %s\", self.uid)\n return self.facade.all()\n \n @response\n @view_config(route_name='types_manage', request_method='GET', renderer='json',\n xhr=True, permission='view')\n def getsingle(self):\n \"\"\"Gets article type from system by code \"\"\"\n LOG.debug(\"Type ADD req POST xhr for %s\", self.uid)\n code = self.request.matchdict.get(\"code\")\n return self.facade.get(code)\n\n @response\n @view_config(route_name='types', request_method='PUT', renderer='json',\n xhr=True, permission='edit')\n def addtype(self):\n \"\"\" Adds new article type \"\"\"\n LOG.debug(\"Type ADD req POST xhr for %s\", self.uid)\n article_type = self.request.json_body.get(\"type\")\n return self.facade.add(article_type)\n\n @response\n @view_config(route_name='types_manage', request_method='POST', renderer='json',\n xhr=True, permission='edit')\n def edittype(self):\n \"\"\" Updates article type \"\"\"\n LOG.debug(\"Type EDIT req POST xhr for %s\", self.uid)\n article_type = self.request.json_body.get(\"type\")\n return self.facade.update(article_type)\n\n @response\n @view_config(route_name='types_manage', request_method='DELETE', renderer='json',\n xhr=True, permission='delete')\n def deletetype(self):\n \"\"\" Deletes article type by code \"\"\"\n LOG.debug(\"Type DELETE req POST xhr for %s\", self.uid)\n code = self.request.matchdict.get(\"code\")\n return self.facade.delete(code)","sub_path":"arttest/views/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"477057307","text":"import random\ndado1 = random.randint(1,6)\ndado2 = random.randint(1,6)\ndado3 = random.randint(1,6)\ndados = dado1 + dado2 + dado3\ndin = 10\ndicas = True\nchutes = True\nwhile dicas:\n print(din)\n if din == 0:\n print('Você perdeu!')\n dicas = False\n chutes = False\n else:\n dica = input('Quer uma dica por 1 dinheiro? (sim/não)')\n if dica == 'sim':\n n1 = int(input('Palpite 1: '))\n n2 = int(input('Palpite 2: '))\n n3 = int(input('Palpite 3: '))\n if n1 == dados or n2 == dados or n3 == dados:\n print('Está entre os 3')\n else:\n print('Não está entre os 3')\n else:\n dicas = False\nwhile chutes:\n print(din)\n if din == 0:\n print('Você perdeu!')\n chutes = False\n else:\n c = int(input('Chute: '))\n if c == dados:\n din = 6 * din\n print('Você ganhou o jogo com {0} dinnheiros!'.format(din))\n chutes = False\n else:\n din -= 1","sub_path":"backup/user_070/ch136_2020_04_01_11_38_59_846413.py","file_name":"ch136_2020_04_01_11_38_59_846413.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"251711469","text":"import os\nimport shutil\nentries=os.listdir('./')\ni=0\n# for entry in entries:\n # if entry[0]!='B':\n # continue\n # k=int(entry[-7:-4])%90\n # l=int(entry[-7:-4])/90\n # os.rename(entry,str(l)+\" \"+str(k)+'.jpg') \nr=entries[0][:-7]\nprint(r)\n\nfor i in range(180):\n os.mkdir(\"./\"+str(2*i))\n if((2*i)<10):\n s='00'+str(2*i)\n elif ((2*i)<100):\n s='0'+str(2*i)\n else:\n s=str(2*i)\n j=(2*i+90)%360\n if(j<10):\n u='00'+str(j)\n elif (j<100):\n u='0'+str(j)\n else:\n u=str(j)\n f1=r+s+'.jpg'\n f2=r+u+'.jpg'\n shutil.copyfile(\"./\"+f1,\"./\"+str(2*i)+\"/\"+f1)\n shutil.copyfile(\"./\"+f2,\"./\"+str(2*i)+\"/\"+f2)\n print(f1+\" \"+f2)\n","sub_path":"makepair.py","file_name":"makepair.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"118554105","text":"# -*- coding: utf-8 -*-\nfrom django.urls import path, include\nfrom rest_framework import routers\n\nfrom . import api\nfrom . import views\n\n\napp_name = 'pyfb_did'\n\nrouter = routers.DefaultRouter()\nrouter.register(r'did', api.DidViewSet)\nrouter.register(r'routesdid', api.RoutesDidViewSet)\n\n\nurlpatterns = (\n # urls for Django Rest Framework API\n path('api/v1/', include(router.urls)),\n)\n\nurlpatterns += (\n # urls for Did\n path('pyfb_did/did/', views.DidListView.as_view(), name='pyfb_did_did_list'),\n path('pyfb_did/did/create/', views.DidCreateView.as_view(), name='pyfb_did_did_create'),\n path('pyfb_did/did/detail//', views.DidDetailView.as_view(), name='pyfb_did_did_detail'),\n path('pyfb_did/did/update//', views.DidUpdateView.as_view(), name='pyfb_did_did_update'),\n)\n\nurlpatterns += (\n # urls for RoutesDid\n path('pyfb_did/routesdid/', views.RoutesDidListView.as_view(), name='pyfb_did_routesdid_list'),\n path('pyfb_did/routesdid/create/', views.RoutesDidCreateView.as_view(), name='pyfb_did_routesdid_create'),\n path('pyfb_did/routesdid/detail//', views.RoutesDidDetailView.as_view(), name='pyfb_did_routesdid_detail'),\n path('pyfb_did/routesdid/update//', views.RoutesDidUpdateView.as_view(), name='pyfb_did_routesdid_update'),\n)\n","sub_path":"pyfb_did/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"24422565","text":"from pyrevit import revit, DB, UI\nfrom pyrevit import script\nfrom pyrevit import forms\n\nlogger = script.get_logger()\n\n# ensure active document is a family document\nforms.check_familydoc(revit.doc, exitscript=True)\n\napp = revit.doc.Application\n\n# make sure user has saved open models in case the tool crashes\nif not forms.alert(\n \"Make sure your models are saved and synced. \" \"Hit OK to continue...\", cancel=True\n):\n script.exit()\n\n# filepath = forms.pick_file(file_ext='txt')\n# if filepath:\n# app.SharedParametersFilename = filepath\n# sharedParametersFile = app.OpenSharedParameterFile()\n# sharedGroups = sharedParametersFile.Groups\n# else:\n# forms.alert('You must select a file', exitscript=True)\nsharedParametersFile = app.OpenSharedParameterFile()\nsharedGroups = sharedParametersFile.Groups\n\nfamily_params = revit.doc.FamilyManager.GetParameters()\n\nreplace_list = []\nshared_list = []\n\nfor group in sharedGroups:\n for sparam in group.Definitions:\n for fparam in family_params:\n if not fparam.IsShared:\n if fparam.Definition.Name == sparam.Name:\n if fparam.Definition.ParameterType == sparam.ParameterType:\n replace_list.append(fparam)\n shared_list.append(sparam)\n\n# define a transaction variable and describe the transaction\nwith revit.Transaction(\"Replace parameters\"):\n for r, s in zip(replace_list, shared_list):\n try:\n print(\n 'Replacing \"{}\" with Shared Parameter ({})'.format(\n r.Definition.Name, s.Name\n )\n )\n # Revit doesn't like it if the old parameter has the same name as the new one so we much change it first\n revit.doc.FamilyManager.RenameParameter(r, r.Definition.Name + \"_Old\")\n new_param = revit.doc.FamilyManager.ReplaceParameter(\n r, s, r.Definition.ParameterGroup, r.IsInstance\n )\n except:\n logger.error('Failed to Replace \"{}\"'.format(r.Definition.Name))\n # logger.error('Failed to Replace Parameter')\n\n print(\"Done\")\n","sub_path":"pySSG.tab/Family Parameters.Panel/Shared Parameters.stack/Replace.pushbutton/script)old.py","file_name":"script)old.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"323252586","text":"from multiprocessing import Value\nfrom typing import Type\nfrom pulse2percept.models.granley2021 import DefaultBrightModel, \\\n DefaultSizeModel, DefaultStreakModel\nfrom pulse2percept.utils.base import FreezeError\nimport numpy as np\nimport pytest\nimport numpy.testing as npt\n\nfrom pulse2percept.implants import ArgusI, ArgusII\nfrom pulse2percept.percepts import Percept\nfrom pulse2percept.stimuli import Stimulus, BiphasicPulseTrain\nfrom pulse2percept.models import BiphasicAxonMapModel, BiphasicAxonMapSpatial, \\\n AxonMapSpatial\nfrom pulse2percept.utils.testing import assert_warns_msg\n\n\ndef test_effects_models():\n # Test thresholding on bright model\n model = DefaultBrightModel(do_thresholding=True)\n # Technically this could fail, but the probability is negliglible\n npt.assert_almost_equal(model(20, 0.01, 0.45), 0)\n\n # Test rho scaling on size model\n model = DefaultSizeModel(200)\n npt.assert_almost_equal(np.sqrt(model(0.01, 0.01, 0.45) * 200 * 200), model.min_rho)\n\n # Test lambda scaling on streak model\n model = DefaultStreakModel(200)\n npt.assert_almost_equal(np.sqrt(model(10, 1, 10000) * 200 * 200), model.min_lambda)\n\n coeffs = {'a' + str(i) : i for i in range(9)}\n # Models can take correct coeffs\n model_coeffs = {k:v for k,v in coeffs if hasattr(DefaultBrightModel(), k)}\n model = DefaultBrightModel(**model_coeffs)\n npt.assert_equal(hasattr(model, 'a0'), True)\n npt.assert_equal(hasattr(model, 'a9'), False)\n model_coeffs = {k:v for k,v in coeffs if hasattr(DefaultSizeModel(200), k)}\n model = DefaultSizeModel(200, **model_coeffs)\n npt.assert_equal(hasattr(model, 'a0'), True)\n npt.assert_equal(hasattr(model, 'a9'), False)\n model_coeffs = {k:v for k,v in coeffs if hasattr(DefaultStreakModel(200), k)}\n model = DefaultStreakModel(200, **model_coeffs)\n npt.assert_equal(hasattr(model, 'a0'), False)\n npt.assert_equal(hasattr(model, 'a9'), True) \n\n\n@pytest.mark.parametrize('engine', ('serial', 'cython', 'jax'))\ndef test_biphasicAxonMapSpatial(engine):\n # Lambda cannot be too small:\n with pytest.raises(ValueError):\n BiphasicAxonMapSpatial(axlambda=9).build()\n\n model = BiphasicAxonMapModel(engine=engine, xystep=2).build()\n # Jax not implemented yet\n if engine == 'jax':\n with pytest.raises(NotImplementedError):\n implant = ArgusII()\n implant.stim = Stimulus({'A5' : BiphasicPulseTrain(20, 1, 0.45)})\n percept = model.predict_percept(implant)\n return\n\n # Only accepts biphasic pulse trains with no delay dur\n implant = ArgusI(stim=np.ones(16))\n with pytest.raises(TypeError):\n model.predict_percept(implant)\n\n # Nothing in, None out:\n npt.assert_equal(model.predict_percept(ArgusI()), None)\n\n # Zero in = zero out:\n implant = ArgusI(stim=np.zeros(16))\n percept = model.predict_percept(implant)\n npt.assert_equal(isinstance(percept, Percept), True)\n npt.assert_equal(percept.shape, list(model.grid.x.shape) + [1])\n npt.assert_almost_equal(percept.data, 0)\n npt.assert_equal(percept.time, None)\n\n # Should be equal to axon map model if effects models return 1\n model = BiphasicAxonMapSpatial(engine=engine, xystep=2)\n def bright_model(freq, amp, pdur): return 1\n def size_model(freq, amp, pdur): return 1\n def streak_model(freq, amp, pdur): return 1\n model.bright_model = bright_model\n model.size_model = size_model\n model.streak_model = streak_model\n model.build()\n axon_map = AxonMapSpatial(xystep=2).build()\n implant = ArgusII()\n implant.stim = Stimulus({'A5' : BiphasicPulseTrain(20, 1, 0.45)})\n percept = model.predict_percept(implant)\n percept_axon = axon_map.predict_percept(implant)\n npt.assert_almost_equal(percept.data[:, :, 0], percept_axon.get_brightest_frame())\n\n # Effect models must be callable\n model = BiphasicAxonMapSpatial(engine=engine, xystep=2)\n model.bright_model = 1.0\n with pytest.raises(TypeError):\n model.build()\n\n # If t_percept is not specified, there should only be one frame \n model = BiphasicAxonMapSpatial(engine=engine, xystep=2)\n model.build()\n implant = ArgusII()\n implant.stim = Stimulus({'A5' : BiphasicPulseTrain(20, 1, 0.45)})\n percept = model.predict_percept(implant)\n npt.assert_equal(percept.time is None, True)\n # If t_percept is specified, only first frame should have data\n # and the rest should be empty\n percept = model.predict_percept(implant, t_percept=[0, 1, 2, 5, 10])\n npt.assert_equal(len(percept.time), 5)\n npt.assert_equal(np.any(percept.data[:, :, 0]), True)\n npt.assert_equal(np.any(percept.data[:, :, 1:]), False)\n\n # Test that default models give expected values\n model = BiphasicAxonMapSpatial(engine=engine, rho=400, axlambda=600, xystep=1,\n xrange=(-20, 20), yrange=(-15, 15))\n model.build()\n implant = ArgusII()\n implant.stim = Stimulus({'A4' : BiphasicPulseTrain(20, 1, 1)})\n percept = model.predict_percept(implant)\n npt.assert_equal(np.sum(percept.data > 1), 82)\n npt.assert_equal(np.sum(percept.data > 2), 59)\n npt.assert_equal(np.sum(percept.data > 3), 44)\n npt.assert_equal(np.sum(percept.data > 5), 25)\n npt.assert_equal(np.sum(percept.data > 7), 14)\n\n\n@pytest.mark.parametrize('engine', ('serial', 'cython', 'jax'))\ndef test_biphasicAxonMapModel(engine):\n set_params = {'xystep': 2, 'engine': engine, 'rho': 432, 'axlambda': 20,\n 'n_axons': 9, 'n_ax_segments': 50,\n 'xrange': (-30, 30), 'yrange': (-20, 20),\n 'loc_od': (5, 6), 'do_thresholding' : False}\n model = BiphasicAxonMapModel(engine=engine)\n for param in set_params:\n npt.assert_equal(hasattr(model.spatial, param), True)\n\n # We can set and get effects model params\n for atr in ['a' + str(i) for i in range(0, 10)]:\n npt.assert_equal(hasattr(model, atr), True)\n model.a0 = 5\n # Should propogate to size and bright model\n # But should not be a member of streak or spatial\n npt.assert_equal(model.spatial.size_model.a0, 5)\n npt.assert_equal(model.spatial.bright_model.a0, 5)\n npt.assert_equal(hasattr(model.spatial.streak_model, 'a0'), False)\n with pytest.raises(AttributeError):\n model.spatial.__getattribute__('a0')\n # If the spatial model and an effects model have a parameter with the\n # Same name, both need to be changed\n model.rho = 350\n model.axlambda = 450\n model.do_thresholding = True\n npt.assert_equal(model.spatial.size_model.rho, 350)\n npt.assert_equal(model.spatial.streak_model.axlambda, 450)\n npt.assert_equal(model.spatial.bright_model.do_thresholding, True)\n npt.assert_equal(model.rho, 350)\n npt.assert_equal(model.axlambda, 450)\n npt.assert_equal(model.do_thresholding, True)\n\n # If parameter is not an effects model param, it cant be set\n with pytest.raises(FreezeError):\n model.invalid_param = 5\n\n # Custom parameters also propogate to effects models\n model = BiphasicAxonMapModel(engine=engine)\n class TestSizeModel():\n def __init__(self):\n self.test_param = 5\n def __call__(self, freq, amp, pdur):\n return 1\n model.size_model = TestSizeModel()\n model.test_param = 10\n npt.assert_equal(model.spatial.size_model.test_param, 10)\n with pytest.raises(AttributeError):\n model.spatial.__getattribute__('test_param')\n\n # Values are passed correctly even in another classes __init__\n # This also tests for recursion error in another classes __init__\n class TestInitClassGood():\n def __init__(self):\n self.model = BiphasicAxonMapModel()\n # This shouldnt raise an error\n self.model.a0\n class TestInitClassBad():\n def __init__(self):\n self.model = BiphasicAxonMapModel()\n # This should\n self.model.a10 = 999\n # If this fails, something is wrong with getattr / setattr logic\n TestInitClassGood()\n with pytest.raises(FreezeError):\n TestInitClassBad()\n\n # User can override default values\n model = BiphasicAxonMapModel(engine=engine)\n for key, value in set_params.items():\n setattr(model.spatial, key, value)\n npt.assert_equal(getattr(model.spatial, key), value)\n model = BiphasicAxonMapModel(**set_params)\n model.build(**set_params)\n for key, value in set_params.items():\n npt.assert_equal(getattr(model.spatial, key), value)\n\n # Zeros in, zeros out:\n implant = ArgusII(stim=np.zeros(60))\n npt.assert_almost_equal(model.predict_percept(implant).data, 0)\n implant.stim = np.zeros(60)\n npt.assert_almost_equal(model.predict_percept(implant).data, 0)\n\n # Implant and model must be built for same eye:\n with pytest.raises(ValueError):\n implant = ArgusII(eye='LE', stim=np.zeros(60))\n model.predict_percept(implant)\n with pytest.raises(ValueError):\n BiphasicAxonMapModel(eye='invalid').build()\n with pytest.raises(ValueError):\n BiphasicAxonMapModel(xystep=5).build(eye='invalid')\n\n # Lambda cannot be too small:\n with pytest.raises(ValueError):\n BiphasicAxonMapModel(axlambda=9).build()\n","sub_path":"pulse2percept/models/tests/test_granley2021.py","file_name":"test_granley2021.py","file_ext":"py","file_size_in_byte":9293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"234144750","text":"import configparser\r\nimport pymongo\r\nimport telepot\r\nfrom modules import info, keyboard\r\n\r\n\r\ndef newUser(id, name, bot):\r\n if mycol.find_one({\"id\": id}) is None: # se non presente inserisci\r\n mydict = {\"id\": id, \"name\": name, \"admin\": False, \"banned\": False}\r\n mycol.insert_one(mydict)\r\n usr = getUser(id)\r\n if usr == 2:\r\n bot.sendMessage(id, \"Risulti essere un utente bannato\", reply_markup=keyboard.getKeyboard(usr))\r\n elif usr == 1:\r\n bot.sendMessage(id, \"Scegli un opzione\", reply_markup=keyboard.getKeyboard(usr))\r\n else:\r\n bot.sendMessage(id, \"Scegli un opzione\", reply_markup=keyboard.getKeyboard(usr))\r\n\r\ndef getUser(id):\r\n x = mycol.find_one({\"id\": id}, {\"admin\": 1, \"banned\": 1})\r\n if x[\"banned\"] == True:\r\n return 2\r\n elif x[\"admin\"] == True:\r\n return 1\r\n else:\r\n return 0\r\n\r\ndef doAdmin(name, chat_id, bot):\r\n myquery = {\"name\": name}\r\n newvalues = {\"$set\": {\"admin\": True}}\r\n if mycol.find(myquery).count() > 0:\r\n mycol.update_one(myquery, newvalues)\r\n bot.sendMessage(chat_id, \"L'utente \" + name + \" è stato reso admin\")\r\n info.NotiUpgradeToAdmin(name, bot.getChat(chat_id)[\"first_name\"])\r\n else:\r\n bot.sendMessage(chat_id, 'Nessun utente con nome \"' + name + '\" è stato trovato')\r\n\r\n\r\ndef doUser(name, chat_id, bot):\r\n myquery = {\"name\": name}\r\n newvalues = {\"$set\": {\"admin\": False}}\r\n if mycol.find(myquery).count() > 0:\r\n mycol.update_one(myquery, newvalues)\r\n bot.sendMessage(chat_id, \"L'utente \" + name + \" è stato retrocesso\")\r\n info.NotiUpgradeToUser(name, bot.getChat(chat_id)[\"first_name\"])\r\n else:\r\n bot.sendMessage(chat_id, 'Nessun utente con nome \"' + name + '\" è stato trovato')\r\n\r\n\r\ndef getIdByName(name):\r\n return mycol.find_one({\"name\": name})[\"id\"]\r\n\r\n\r\ndef banUser(name, chat_id, bot):\r\n myquery = {\"name\": name}\r\n newvalues = {\"$set\": {\"banned\": True}}\r\n if mycol.find(myquery).count() > 0:\r\n mycol.update_one(myquery, newvalues)\r\n bot.sendMessage(chat_id, \"L'utente \" + name + \" è stato bannato\")\r\n bot.sendMessage(getIdByName(name), \"Sei appena stato bandito da questo bot da \" + name, reply_markup=keyboard.getKeyboard(2))\r\n info.NotiBan(name, bot.getChat(chat_id)[\"first_name\"])\r\n else:\r\n bot.sendMessage(chat_id, 'Nessun utente con nome \"' + name + '\" è stato trovato')\r\n\r\nread_config = configparser.ConfigParser()\r\nread_config.read(\"prop.ini\")\r\n\r\nmyclient = pymongo.MongoClient(read_config.get(\"Database\", \"dbconnection\"))\r\nmydb = myclient[read_config.get(\"Database\", \"dbName\")]\r\nmycol = mydb[read_config.get(\"Database\", \"users\")]\r\n","sub_path":"BotPY/modules/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"543018441","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\n\n#翻訳する英文を指定\nenglish = \"ball\"\n\n#グーグル翻訳のアドレス(翻訳したい文章がURLの末尾に付く)\nurl = \"https://translate.google.co.jp/#en/ja/{0}\".format(english)\n\n#PhantomJSを起動\ndriver = webdriver.PhantomJS()\n\n#指定したURLに移動\ndriver.get(url)\n\n#指定したURLのソースコードを取得\nhtml = driver.page_source\n\n#htmlをBeautifulSoupで扱えるようにする\nsoup = BeautifulSoup(html,'html.parser')\n\n#結果を表示\nprint(\"English: \" + english)\nprint(\"Japanese: \" + soup.find(\"span\", class_=\"tlid-translation translation\").string)\n\n","sub_path":"Google Translation.py","file_name":"Google Translation.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"545034224","text":"import requests\nfrom urllib import request\nfrom bs4 import BeautifulSoup\nfrom dateutil import parser\nfrom datetime import datetime, timedelta\nfrom datetime import datetime\nimport csv\n\nBASE_URL = 'https://zcash.flypool.org/miners/t1NDwS7YBXt7pfbmpaRsy6kkGZgM39Ywyix/payouts'\nDEBUG = 1\n\n\ndef get_html(url):\n \"\"\"\n Получаем html по заданному url\n :param url:\n :return:\n \"\"\"\n req = request.Request(url, None, {'User-agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})\n response = request.urlopen(req)\n return response.read()\n\n\ndef get_yobit_data(coin):\n \"\"\"\n Получаем с биржи Yobit последний курс по монете\n \"\"\"\n base_url = 'https://yobit.net/api/3/ticker/'\n url = base_url + coin\n resp = requests.get(url)\n json = resp.json()\n return json[coin]['last']\n\n\ndef get_flypool_data():\n \"\"\"\n Получаю с флайпула json с данными\n Не буду использовать, т.к. в json непонятные значения (ethPerMin) и т.д.\n \"\"\"\n url = 'http://zcash.flypool.org/api/miner_new/t1NDwS7YBXt7pfbmpaRsy6kkGZgM39Ywyix'\n resp = requests.get(url)\n return resp.json()\n\n\ndef get_hashrate():\n \"\"\"\n Получаем с флайпула средний hashrate\n через json\n :return:\n \"\"\"\n url = 'http://zcash.flypool.org/api/miner_new/t1NDwS7YBXt7pfbmpaRsy6kkGZgM39Ywyix'\n resp = requests.get(url)\n json = resp.json()\n hashrate = json['avgHashrate']\n return int(hashrate)\n\n\ndef get_zec_day():\n url = 'https://zcash.flypool.org/miners/t1NDwS7YBXt7pfbmpaRsy6kkGZgM39Ywyix/payouts'\n html = get_html(url)\n soup = BeautifulSoup(html, \"lxml\")\n zec_day = soup.find('table', class_='table table-condensed table-bordered').find_all('tr')[3].find_all('td')[1].text\n return float(zec_day)\n\n\ndef write_csv(data):\n with open ('avito.csv', 'a') as f:\n writer = csv.writer(f, lineterminator='\\n')\n\n writer.writerow( (data['title'],\n data['price'],\n data['metro'],\n data['url']) )\n\n\ndef main():\n # Все монеты биржи Yobit - https://yobit.net/api/3/info\n\n zec_day = round(get_zec_day(), 8) # Сколько зарабатываем zec в день\n avg_hashrate = get_hashrate() # Средний хэшрейт\n now = datetime.strftime(datetime.now(), \"%Y.%m.%d %H:%M\") # Время\n zec_btc = get_yobit_data('zec_btc') # Курс zec_btc с биржи Yobit\n btc_usd = round(get_yobit_data('btc_usd'), 2) # Курс btc_usd с биржи Yobit\n btc_rur = round(get_yobit_data('btc_rur'), 2) # Курс btc_rur с биржи Yobit\n\n # -----Прогнозируемый заработок в сутки-----\n btc_per_day = round(zec_day * zec_btc, 8) # В биткоинах\n usd_per_day = round(btc_per_day * btc_usd, 2) # В долларах\n rub_per_day = round(btc_per_day * btc_rur, 2) # В рублях\n\n if DEBUG:\n print(\"Time: \\t\\t\\t\"+now)\n # print(\"ZEC in DAY: \\t\" + str(zec_day))\n print(\"Avg. Hashrate: \\t\" + str(avg_hashrate)+\" H/s\")\n print(\"ZEC/BTC: \\t\\t\" + str(zec_btc))\n print(\"BTC/USD: \\t\\t\" + str(btc_usd))\n print(\"BTC/RUR: \\t\\t\" + str(btc_rur))\n print('\\n-----Прогнозируемая доходность-----')\n print('\\t\\tDay\\t\\t\\t\\tWeek\\t\\t\\tMonth')\n print('ZEC:\\t' + str(zec_day)+'\\t\\t\\t'+str(round(zec_day*7, 8))+'\\t\\t\\t'+str(round(zec_day*30.5, 8)))\n print('BTC:\\t' + str(btc_per_day)+'\\t\\t'+str(round(btc_per_day*7, 8))+'\\t\\t'+str(round(btc_per_day*30.5, 8)))\n print('USD:\\t' + str(usd_per_day)+'\\t\\t\\t'+str(round(usd_per_day*7, 8))+'\\t\\t\\t'+str(round(usd_per_day*30.5, 8)))\n print('RUB:\\t' + str(rub_per_day)+'\\t\\t\\t'+str(round(rub_per_day*7, 8))+'\\t\\t\\t'+str(round(rub_per_day*30.5, 8)))\n\n # -----Запись данных в файл-----\n with open ('fly_data.csv', 'a') as f:\n writer = csv.writer(f, lineterminator='\\n')\n writer.writerow((now,\n zec_btc,\n btc_usd,\n btc_rur,\n avg_hashrate,\n zec_day,\n btc_per_day,\n usd_per_day,\n rub_per_day))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"flypool_parser_3.py","file_name":"flypool_parser_3.py","file_ext":"py","file_size_in_byte":4628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"332842263","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.IndexView.as_view(),name='index'),\n # path('signin', views.SigninView.as_view(), name='signin'),\n path('dashboard', views.DashboardView.as_view(), name='dashboard'),\n path('home', views.HomeView.as_view(), name='home'),\n path('record', views.RecordView.as_view(), name='record'),\n\n path('kakao/login/', views.kakao_login, name='kakao_login'),\n path('kakao/callback/', views.kakao_callback, name='kakao_callback'),\n path('kakao/login/finish/', views.KakaoLogin.as_view(), name='kakao_login_todjango'),\n path('kakao/logout/', views.kakao_logout, name='kakao_logout'),\n]","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"217882456","text":"# let the robot cheerleader cheer for you!\n\nan_letters = \"AEFHILMNORSX\"\nword = input(\"I will cheer for you! Enter a word: \").upper()\ntimes = int(input(\"Enthusiastic level (0-10): \"))\n\n# i = 0\n\n# while i < len(word):\n# char = word[i]\nfor char in word:\n if char in an_letters:\n print(\"Give me an {}! {}\".format(char, char))\n else:\n print(\"Give me a {}! {}\".format(char, char))\n # i += 1\n\nprint(\"What does that spell??\")\n\nfor i in range(times):\n print(word, \"!!!\")\n\n# print((word + \"!!!\\n\") * (times))\n","sub_path":"MIT_Python/robot_cheerleader.py","file_name":"robot_cheerleader.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"505832841","text":"from __future__ import absolute_import\n\nfrom sentry.models import (\n EventTag, GroupTagKey, GroupTagValue, ScheduledDeletion, TagKey, TagValue\n)\nfrom sentry.tasks.deletion import run_deletion\nfrom sentry.testutils import TestCase\n\n\nclass DeleteTagKeyTest(TestCase):\n def test_simple(self):\n team = self.create_team(name='test', slug='test')\n project = self.create_project(team=team, name='test1', slug='test1')\n group = self.create_group(project=project)\n tk = TagKey.objects.create(key='foo', project_id=project.id)\n TagValue.objects.create(key='foo', value='bar', project_id=project.id)\n GroupTagKey.objects.create(key='foo', group_id=group.id, project_id=project.id)\n GroupTagValue.objects.create(\n key='foo', value='bar', group_id=group.id, project_id=project.id\n )\n EventTag.objects.create(\n key_id=tk.id,\n group_id=group.id,\n value_id=1,\n project_id=project.id,\n event_id=1,\n )\n\n project2 = self.create_project(team=team, name='test2')\n group2 = self.create_group(project=project2)\n tk2 = TagKey.objects.create(key='foo', project_id=project2.id)\n gtk2 = GroupTagKey.objects.create(key='foo', group_id=group2.id, project_id=project2.id)\n gtv2 = GroupTagValue.objects.create(\n key='foo', value='bar', group_id=group2.id, project_id=project2.id\n )\n EventTag.objects.create(\n key_id=tk2.id,\n group_id=group2.id,\n value_id=1,\n project_id=project.id,\n event_id=1,\n )\n\n deletion = ScheduledDeletion.schedule(tk, days=0)\n deletion.update(in_progress=True)\n\n with self.tasks():\n run_deletion(deletion.id)\n\n assert not GroupTagValue.objects.filter(key=tk.key, project_id=project.id).exists()\n assert not GroupTagKey.objects.filter(key=tk.key, project_id=project.id).exists()\n assert not TagValue.objects.filter(key=tk.key, project_id=project.id).exists()\n assert not TagKey.objects.filter(id=tk.id).exists()\n assert not EventTag.objects.filter(key_id=tk.id).exists()\n\n assert TagKey.objects.filter(id=tk2.id).exists()\n assert GroupTagKey.objects.filter(id=gtk2.id).exists()\n assert GroupTagValue.objects.filter(id=gtv2.id).exists()\n assert EventTag.objects.filter(key_id=tk2.id).exists()\n","sub_path":"tests/sentry/deletions/test_tagkey.py","file_name":"test_tagkey.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"432586269","text":"import pandas as pd\nimport networkx as nx\nimport json\nimport matplotlib.pyplot as plt\nfrom operator import itemgetter\nimport sys\n\n\nif __name__ == \"__main__\":\n input_file = sys.argv[1]\n gexf_output = sys.argv[2]\n json_output = sys.argv[3]\n tweets = []\n with open(input_file, \"r\", encoding=\"utf-8\") as f:\n for line in f.readlines():\n tweet = json.loads(line)\n\n tweets.append(tweet)\n\n weight_map = {}\n G = nx.DiGraph()\n for t in tweets:\n if 'text' in t:\n usr = t['user']['screen_name']\n G.add_node(usr)\n\n if 'retweeted_status' in t:\n\n rt = t['retweeted_status']['user']['screen_name']\n\n if (usr, rt) in weight_map:\n weight_map[(usr, rt)] += 1\n\n else:\n weight_map[(usr, rt)] = 1\n\n G.add_edge(usr, rt, weight = weight_map[(usr, rt)])\n\n nx.write_gexf(G, gexf_output)\n\n\n num_edges = G.number_of_edges()\n num_nodes = G.number_of_nodes()\n\n\n max_edge = -1\n max_node = ''\n end = ''\n\n outgoing = {}\n incoming = {}\n\n for u, v, weight in G.edges(data=\"weight\"):\n if weight is not None:\n \n if u in outgoing:\n outgoing[u] += weight\n else:\n outgoing[u] = weight\n \n if v in incoming:\n incoming[v] += weight\n else:\n incoming[v] = weight\n \n if weight > max_edge:\n max_edge = weight\n max_node = u\n end = v\n \n max_rtd = max(incoming, key=incoming.get)\n max_rtr = max(outgoing, key=outgoing.get)\n max_rtd_num = G.in_degree(max(incoming, key=incoming.get), weight='weight')\n max_rtr_num = G.out_degree(max(outgoing, key=outgoing.get), weight='weight')\n\n result = {}\n\n result['n_nodes'] = num_nodes\n result['n_edges'] = num_edges\n\n result['max_retweeted_user'] = max_rtd\n result['max_retweeted_number'] = max_rtd_num\n\n result['max_retweeter_user'] = max_rtr\n result['max_retweeter_number'] = max_rtr_num\n\n\n with open(json_output, 'w') as outfile:\n json.dump(result, outfile)\n\n\n","sub_path":"hw3/griffin_weinhold_hw3/griffin_weinhold_hw3/griffin_weinhold_task1.py","file_name":"griffin_weinhold_task1.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"215436422","text":"#\n# settings.py -- Settings storage operations for extensions.\n#\n# Copyright (c) 2010-2013 Beanbag, Inc.\n# Copyright (c) 2008-2010 Christian Hammond\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext as _\n\nfrom djblets.extensions.signals import settings_saved\n\n\nclass Settings(dict):\n \"\"\"\n Settings data for an extension. This is a glorified dictionary that\n acts as a proxy for the extension's stored settings in the database.\n\n Callers must call save() when they want to make the settings persistent.\n\n If a key is not found in the dictionary, extension.default_settings\n will be checked as well.\n \"\"\"\n def __init__(self, extension):\n dict.__init__(self)\n self.extension = extension\n self.load()\n\n def __getitem__(self, key):\n \"\"\"Retrieve an item from the dictionary.\n\n This will attempt to return a default value from\n extension.default_settings if the setting has not\n been set.\n \"\"\"\n if super(Settings, self).__contains__(key):\n return super(Settings, self).__getitem__(key)\n\n if key in self.extension.default_settings:\n return self.extension.default_settings[key]\n\n raise KeyError(\n _('The settings key \"%(key)s\" was not found in extension %(ext)s')\n % {\n 'key': key,\n 'ext': self.extension.id\n })\n\n def __contains__(self, key):\n \"\"\"Indicate if the setting is present.\n\n If the key is not present in the settings dictionary\n check the default settings as well.\n \"\"\"\n if super(Settings, self).__contains__(key):\n return True\n\n return key in self.extension.default_settings\n\n def get(self, key, default=None):\n \"\"\"Returns a setting.\n\n This will return the setting's stored value, or its default value if\n unset.\n\n If the key isn't a valid setting, the provided default will be\n returned instead.\n \"\"\"\n # dict.get doesn't call __getitem__ internally, and instead looks up\n # straight from the internal dictionary data. So, we need to handle it\n # ourselves in order to support defaults through __getitem__.\n try:\n return self[key]\n except KeyError:\n return default\n\n def set(self, key, value):\n \"\"\"Sets a setting's value.\n\n This is equivalent to setting the value through standard dictionary\n attribute storage.\n \"\"\"\n self[key] = value\n\n def load(self):\n \"\"\"Loads the settings from the database.\"\"\"\n try:\n self.update(self.extension.registration.settings)\n except ValueError:\n # The settings in the database are invalid. We'll have to discard\n # it. Note that this should never happen unless the user\n # hand-modifies the entries and breaks something.\n pass\n\n def save(self):\n \"\"\"Saves all current settings to the database.\"\"\"\n registration = self.extension.registration\n registration.settings = dict(self)\n registration.save()\n\n settings_saved.send(sender=self.extension)\n\n # Make sure others are aware that the configuration changed.\n self.extension.extension_manager._bump_sync_gen()\n","sub_path":"djblets/extensions/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"278804155","text":"import random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torchvision.models as models\nfrom torch.autograd import Variable\nimport numpy as np\nfrom model.utils.config import cfg\nfrom model.rpn.rpn import _RPN\nfrom model.roi_pooling.modules.roi_pool import _RoIPooling\nfrom model.roi_crop.modules.roi_crop import _RoICrop\nfrom model.roi_align.modules.roi_align import RoIAlignAvg\nfrom model.rpn.proposal_target_layer_cascade import _ProposalTargetLayer\n\nfrom model.da_faster_rcnn.DA import _ImageDA\nfrom model.da_faster_rcnn.DA import _InstanceDA\nimport time\nimport pdb\nfrom model.utils.net_utils import _smooth_l1_loss, _crop_pool_layer, _affine_grid_gen, _affine_theta\n\nclass _fasterRCNN(nn.Module):\n \"\"\" faster RCNN \"\"\"\n def __init__(self, classes, class_agnostic):\n super(_fasterRCNN, self).__init__() # 继承父类的__init__()方法\n self.classes = classes\n self.n_classes = len(classes)\n self.class_agnostic = class_agnostic\n # loss\n self.RCNN_loss_cls = 0\n self.RCNN_loss_bbox = 0\n\n # define rpn\n # 实例化,RPN网络(self.dout_base_model)是512,vgg16子类中定义,输入rpn的维度\n self.RCNN_rpn = _RPN(self.dout_base_model)\n self.RCNN_proposal_target = _ProposalTargetLayer(self.n_classes)\n self.RCNN_roi_pool = _RoIPooling(cfg.POOLING_SIZE, cfg.POOLING_SIZE, 1.0/16.0)\n self.RCNN_roi_align = RoIAlignAvg(cfg.POOLING_SIZE, cfg.POOLING_SIZE, 1.0/16.0)\n\n # grid_size = 7 * 2 = 14\n self.grid_size = cfg.POOLING_SIZE * 2 if cfg.CROP_RESIZE_WITH_MAX_POOL else cfg.POOLING_SIZE\n self.RCNN_roi_crop = _RoICrop()\n\n # dout_base_model = 512\n self.RCNN_imageDA = _ImageDA(self.dout_base_model)\n self.RCNN_instanceDA = _InstanceDA()\n self.consistency_loss = torch.nn.MSELoss(size_average=False)\n\n # 前向传播 (最最最最关键)\n def forward(self, im_data, im_info, gt_boxes, num_boxes, need_backprop,\n tgt_im_data, tgt_im_info, tgt_gt_boxes, tgt_num_boxes, tgt_need_backprop):\n # 源域需要BP,目标域不需要BP时正常,否则报错\n assert need_backprop.detach()==1 and tgt_need_backprop.detach()==0\n\n # 读取相关数据\n batch_size = im_data.size(0)\n im_info = im_info.data #(size1,size2, image ratio(new image / source image) )\n gt_boxes = gt_boxes.data\n num_boxes = num_boxes.data\n need_backprop=need_backprop.data\n\n\n # feed image data to base model to obtain base feature map\n # 在vgg16的子类中定义,是分类网络不要最后一个最大池化层,输出(512维,大小不固定(根据输入图片而定)) -> 所谓feature_map\n base_feat = self.RCNN_base(im_data)\n\n # feed base feature map tp RPN to obtain rois\n # 设置rpn网络在训练状态\n self.RCNN_rpn.train()\n # 把feature_map和标注的参数输入rpn网络,进行fg/bg的分类\n '''\n 输入:\n base_feat -> feature_map -> size(1,512,H,W)\n im_info -> image W,H,ratio -> size(1,3)\n gt_boxes -> GroundTruthBox -> size(1,数量,5)\n num_boxes -> 目标框的数量 -> size(1)\n 输出:\n rois -> size([1, num_proposal, 5])\n rois是anchor经过fg/bg预测 + nms 筛选过后的proposal, num_proposal<=2000, 最后一维[第一个元素恒定为0,x1,y1,x2,y2]\n rpn_loss_cls -> 单个值\n rpn_loss_bbox -> 单个值\n '''\n rois, rpn_loss_cls, rpn_loss_bbox = self.RCNN_rpn(base_feat, im_info, gt_boxes, num_boxes)\n\n # if it is training phrase, then use ground trubut bboxes for refining\n if self.training:\n '''\n 作用:\n 再次对roi进行筛选(到256个vgg16.yml中设定)\n roi对应的GT标签(之前的步骤只有fg,bg,这里得到的是class)\n roi的GT变化量(之后就是要通过这个做回归)\n 得到权重\n 输入:\n rois -> size([1, num_proposal, 5])\n rois是anchor经过rpn预测保留的前景fg + nms 筛选过后的proposal, num_proposal<=2000, 最后一维[第一个元素恒定为0,x1,y1,x2,y2]\n gt_boxes -> GroundTruthBox -> size(1,数量,5)\n num_boxes -> 目标框的数量 -> size(1)\n 输出:\n rois_data -> list\n rois -> size([1,256,5]) 预测框:最后一维 前1:0 后4:坐标\n rois_label -> size([1,256]) 正样本的标签\n rois_target -> size([1,256,4]) -> 两个平移变化量,两个缩放变化量\n rois_inside_ws -> size([1,256,4]) -> 最后一维度:(1.0, 1.0, 1.0, 1.0)\n rois_outside_ws -> size([1,256,4]) -> 最后一维度:(1.0, 1.0, 1.0, 1.0)\n '''\n roi_data = self.RCNN_proposal_target(rois, gt_boxes, num_boxes)\n rois, rois_label, rois_target, rois_inside_ws, rois_outside_ws = roi_data\n\n rois_label = Variable(rois_label.view(-1).long())\n rois_target = Variable(rois_target.view(-1, rois_target.size(2)))\n rois_inside_ws = Variable(rois_inside_ws.view(-1, rois_inside_ws.size(2)))\n rois_outside_ws = Variable(rois_outside_ws.view(-1, rois_outside_ws.size(2)))\n else:\n rois_label = None\n rois_target = None\n rois_inside_ws = None\n rois_outside_ws = None\n rpn_loss_cls = 0\n rpn_loss_bbox = 0\n\n rois = Variable(rois)\n # do roi pooling based on predicted rois\n\n # roi_pooling\n # POOLING_MODE = 'crop' 进行裁剪\n if cfg.POOLING_MODE == 'crop':\n # pdb.set_trace()\n # pooled_feat_anchor = _crop_pool_layer(base_feat, rois.view(-1, 5))\n '''\n # rois.view(-1, 5) 大小 -> (proposal数量,5)\n # base_feat 大小 -> (1,512,H,W)\n # self.grid_size -> 14\n '''\n grid_xy = _affine_grid_gen(rois.view(-1, 5), base_feat.size()[2:], self.grid_size)\n grid_yx = torch.stack([grid_xy.data[:,:,:,1], grid_xy.data[:,:,:,0]], 3).contiguous()\n pooled_feat = self.RCNN_roi_crop(base_feat, Variable(grid_yx).detach())\n if cfg.CROP_RESIZE_WITH_MAX_POOL:\n pooled_feat = F.max_pool2d(pooled_feat, 2, 2)\n elif cfg.POOLING_MODE == 'align':\n pooled_feat = self.RCNN_roi_align(base_feat, rois.view(-1, 5))\n elif cfg.POOLING_MODE == 'pool':\n pooled_feat = self.RCNN_roi_pool(base_feat, rois.view(-1,5))\n\n # feed pooled features to top model\n # pooled_feat 大小变化 ([256,512,7,7]) -> ([256, 4096])\n # 利用vgg16的顶层(除最后一层) 输出 4096 个值\n pooled_feat = self._head_to_tail(pooled_feat)\n\n # compute bbox offset\n # 是回归输出 4 * class 个值\n # bbox_pred -> ([256, 4*9])\n bbox_pred = self.RCNN_bbox_pred(pooled_feat)\n # 如果是在训练中,并且是类相关的\n if self.training and not self.class_agnostic:\n # select the corresponding columns according to roi labels\n # bbox_pred_view -> size([256, 9, 4])\n bbox_pred_view = bbox_pred.view(bbox_pred.size(0), int(bbox_pred.size(1) / 4), 4)\n # rois_label.view(rois_label.size(0), 1, 1).expand(rois_label.size(0), 1, 4) -> size([256, 1, 4])\n # 选出对应预测标签的4个坐标回归值 bbox_pred_select -> size([256, 1, 4])\n bbox_pred_select = torch.gather(bbox_pred_view, 1, rois_label.view(rois_label.size(0), 1, 1).expand(rois_label.size(0), 1, 4))\n # bbox_pred -> size([256, 4])\n bbox_pred = bbox_pred_select.squeeze(1)\n\n # compute object classification probability\n # 用于在 roi_pooling后的分类 维度 4096 -> 9\n # cls_score -> size([256, 9])\n cls_score = self.RCNN_cls_score(pooled_feat)\n # 进行分类\n # cls_prob -> size([256, 9])\n cls_prob = F.softmax(cls_score, 1)\n\n RCNN_loss_cls = 0\n RCNN_loss_bbox = 0\n\n # 根据分类和回归计算 RCNN_loss\n if self.training:\n # classification loss\n RCNN_loss_cls = F.cross_entropy(cls_score, rois_label)\n\n # bounding box regression L1 loss\n RCNN_loss_bbox = _smooth_l1_loss(bbox_pred, rois_target, rois_inside_ws, rois_outside_ws)\n\n # cls_prob -> size([1, 256, 9])\n cls_prob = cls_prob.view(batch_size, rois.size(1), -1)\n # bbox_pred -> size([1, 256, 4])\n bbox_pred = bbox_pred.view(batch_size, rois.size(1), -1)\n\n \"\"\" =================== for target ==========================\"\"\"\n \"\"\" =================== 对于 目标域 ==========================\"\"\"\n tgt_batch_size = tgt_im_data.size(0)\n tgt_im_info = tgt_im_info.data # (size1,size2, image ratio(new image / source image) )\n tgt_gt_boxes = tgt_gt_boxes.data\n tgt_num_boxes = tgt_num_boxes.data\n tgt_need_backprop = tgt_need_backprop.data\n\n # feed image data to base model to obtain base feature map\n # 提取featuremap\n tgt_base_feat = self.RCNN_base(tgt_im_data)\n\n # feed base feature map tp RPN to obtain rois\n # 设定为测试,不进行training步骤,不算损失\n self.RCNN_rpn.eval()\n # 前景背景判断,仅仅预测roi,目标域无标签不进行loss计算\n # tgt_rois -> size([1, num_proposal, 5]) -> num_proposal<=300(和源域不同), 最后一维[第一个元素恒定为0,x1,y1,x2,y2]\n tgt_rois, tgt_rpn_loss_cls, tgt_rpn_loss_bbox = \\\n self.RCNN_rpn(tgt_base_feat, tgt_im_info, tgt_gt_boxes, tgt_num_boxes)\n\n # if it is training phrase, then use ground trubut bboxes for refining\n\n tgt_rois_label = None\n tgt_rois_target = None\n tgt_rois_inside_ws = None\n tgt_rois_outside_ws = None\n tgt_rpn_loss_cls = 0\n tgt_rpn_loss_bbox = 0\n\n tgt_rois = Variable(tgt_rois)\n # do roi pooling based on predicted rois\n\n #roi pooling\n if cfg.POOLING_MODE == 'crop':\n # pdb.set_trace()\n # pooled_feat_anchor = _crop_pool_layer(base_feat, rois.view(-1, 5))\n tgt_grid_xy = _affine_grid_gen(tgt_rois.view(-1, 5), tgt_base_feat.size()[2:], self.grid_size)\n tgt_grid_yx = torch.stack([tgt_grid_xy.data[:, :, :, 1], tgt_grid_xy.data[:, :, :, 0]], 3).contiguous()\n tgt_pooled_feat = self.RCNN_roi_crop(tgt_base_feat, Variable(tgt_grid_yx).detach())\n if cfg.CROP_RESIZE_WITH_MAX_POOL:\n tgt_pooled_feat = F.max_pool2d(tgt_pooled_feat, 2, 2)\n elif cfg.POOLING_MODE == 'align':\n tgt_pooled_feat = self.RCNN_roi_align(tgt_base_feat, tgt_rois.view(-1, 5))\n elif cfg.POOLING_MODE == 'pool':\n tgt_pooled_feat = self.RCNN_roi_pool(tgt_base_feat, tgt_rois.view(-1, 5))\n\n # feed pooled features to top model\n # 输入顶层网络\n tgt_pooled_feat = self._head_to_tail(tgt_pooled_feat)\n\n \"\"\" DA loss \"\"\"\n \"\"\" 域对抗损失 \"\"\"\n\n # DA LOSS\n DA_img_loss_cls = 0\n DA_ins_loss_cls = 0\n\n tgt_DA_img_loss_cls = 0\n tgt_DA_ins_loss_cls = 0\n\n # 提取源域特征\n # 这里的need_backprop??\n base_score, base_label = self.RCNN_imageDA(base_feat, need_backprop)\n\n # Image DA 图像级对齐\n base_prob = F.log_softmax(base_score, dim=1)\n DA_img_loss_cls = F.nll_loss(base_prob, base_label)\n\n # 实例级对齐\n '''\n 输入roi特征,输出域特征\n 输入:\n pooled_feat -> size([256,4096])\n need_backprop -> size([1])\n 输出:\n instance_sigmoid-> size([256,1])\n same_size_label -> size([256,1])\n '''\n instance_sigmoid, same_size_label = self.RCNN_instanceDA(pooled_feat, need_backprop)\n instance_loss = nn.BCELoss()\n DA_ins_loss_cls = instance_loss(instance_sigmoid, same_size_label)\n\n # 一致性对齐\n #consistency_prob = torch.max(F.softmax(base_score, dim=1),dim=1)[0]\n consistency_prob = F.softmax(base_score, dim=1)[:,1,:,:]\n consistency_prob=torch.mean(consistency_prob)\n consistency_prob=consistency_prob.repeat(instance_sigmoid.size())\n\n DA_cst_loss=self.consistency_loss(instance_sigmoid,consistency_prob.detach())\n\n \"\"\" ************** taget loss **************** \"\"\"\n\n tgt_base_score, tgt_base_label = \\\n self.RCNN_imageDA(tgt_base_feat, tgt_need_backprop)\n\n # Image DA\n tgt_base_prob = F.log_softmax(tgt_base_score, dim=1)\n tgt_DA_img_loss_cls = F.nll_loss(tgt_base_prob, tgt_base_label)\n\n\n tgt_instance_sigmoid, tgt_same_size_label = \\\n self.RCNN_instanceDA(tgt_pooled_feat, tgt_need_backprop)\n tgt_instance_loss = nn.BCELoss()\n\n tgt_DA_ins_loss_cls = \\\n tgt_instance_loss(tgt_instance_sigmoid, tgt_same_size_label)\n\n\n tgt_consistency_prob = F.softmax(tgt_base_score, dim=1)[:, 0, :, :]\n tgt_consistency_prob = torch.mean(tgt_consistency_prob)\n tgt_consistency_prob = tgt_consistency_prob.repeat(tgt_instance_sigmoid.size())\n\n tgt_DA_cst_loss = self.consistency_loss(tgt_instance_sigmoid, tgt_consistency_prob.detach())\n\n '''\n 输出:\n rois -> size([1,256,5]) 预测框:最后一维 前1:0 后4:坐标\n cls_prob -> size([1, 256, 9]) 预测类别:onehot,softmax后\n bbox_pred -> size([1, 256, 4]) 预测框的坐标值(rois回归后)\n rpn_loss_cls -> 单个值 RPN分类损失\n rpn_loss_box -> 单个值 RPN回归损失\n RCNN_loss_cls -> 单个值 分类损失\n RCNN_loss_bbox -> 单个值 回归损失\n rois_label -> size([256]) 正样本标签\n DA_img_loss_cls -> 单个值 image-level源域损失\n DA_ins_loss_cls -> 单个值 instance-level源域损失\n tgt_DA_img_loss_cls -> 单个值 image-level目标域损失\n tgt_DA_ins_loss_cls -> 单个值 instance-level目标域损失\n DA_cst_loss -> 单个值 一致性源域损失\n tgt_DA_cst_loss -> 单个值 一致性目标域损失\n '''\n return rois, cls_prob, bbox_pred, rpn_loss_cls, rpn_loss_bbox, RCNN_loss_cls, RCNN_loss_bbox, rois_label,\\\n DA_img_loss_cls,DA_ins_loss_cls,tgt_DA_img_loss_cls,tgt_DA_ins_loss_cls,DA_cst_loss,tgt_DA_cst_loss\n\n\n def _init_weights(self):\n def normal_init(m, mean, stddev, truncated=False):\n \"\"\"\n weight initalizer: truncated normal and random normal.\n \"\"\"\n # x is a parameter\n if truncated:\n m.weight.data.normal_().fmod_(2).mul_(stddev).add_(mean) # not a perfect approximation\n else:\n m.weight.data.normal_(mean, stddev)\n m.bias.data.zero_()\n\n normal_init(self.RCNN_rpn.RPN_Conv, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_rpn.RPN_cls_score, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_rpn.RPN_bbox_pred, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_cls_score, 0, 0.01, cfg.TRAIN.TRUNCATED)\n normal_init(self.RCNN_bbox_pred, 0, 0.001, cfg.TRAIN.TRUNCATED)\n\n def create_architecture(self):\n # 初始化模型,在vgg16的子类中定义\n self._init_modules()\n # 初始化参数\n self._init_weights()\n","sub_path":"lib/model/da_faster_rcnn/faster_rcnn.py","file_name":"faster_rcnn.py","file_ext":"py","file_size_in_byte":16110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"323738192","text":"from MultiDimDict import MDDict\nimport sys\nimport math\nclass HMM():\n def __init__(self,data,num_y,vocab_x,vocab_y):\n self.data = data\n self.vocab_x = vocab_x\n self.vocab_y = vocab_y\n self.num_y = num_y \n self.num_x = 1\n \n def divider_helper(self, c1,c2,c3, vocab):\n if len(vocab) == 2:\n for i in vocab[0]:\n for j in vocab[1]:\n if c3[i] > 0:\n c1[i][j] = c2[i][j] / c3[i]\n else:\n c1[i][j] = 0\n return c1\n else:\n for i in vocab[0]:\n c1[i] = self.divider_helper(c1[i], c2[i], c3[i], vocab[1:])\n return c1\n\n\n def calculate_emissions(self):\n\n axes_for_emissions = []\n axes_for_emissions.append('y')\n axes_for_emissions.append('x')\n vocab_for_emissions = []\n for axe in axes_for_emissions:\n if axe == 'y':\n vocab_for_emissions.append(self.vocab_y)\n elif axe == 'x':\n vocab_for_emissions.append(self.vocab_x)\n self.emissions = MDDict(vocab_for_emissions)\n count_emit = MDDict(vocab_for_emissions)\n count_yi = MDDict(vocab_for_emissions[:-1])\n\n for i, row in self.data.iterrows():\n _iter = 1\n x = row['x']\n y = row['y']\n\n while _iter < len(y) - 2:\n _data = [y[_iter]]+[x[_iter-1]] \n count_emit.add_value(_data,1)\n count_yi.add_value([y[_iter]],1)\n _iter += 1\n \n\n self.emissions.data = self.divider_helper(self.emissions.data, count_emit.data, count_yi.data, vocab_for_emissions)\n return self.emissions\n\n\n def calculate_transitions(self):\n axes_for_transitions = []\n for i in range(self.num_y + 1):\n axes_for_transitions.append('y')\n vocab_for_transitions = []\n for axe in axes_for_transitions:\n if axe == 'y':\n vocab_for_transitions.append(self.vocab_y)\n self.transitions = MDDict(vocab_for_transitions)\n count_transit = MDDict(vocab_for_transitions)\n count_yi = MDDict(vocab_for_transitions[1:])\n\n for i, row in self.data.iterrows():\n _iter = 1\n y = row['y']\n\n while _iter < len(y) - 2:\n _data = []\n list_y = []\n for i in range(self.num_y+1):\n if (_iter - i) >= 0:\n list_y.append(y[_iter - i])\n else:\n list_y.append(':')\n list_y = list_y[::-1] # so that the list is []....,y-2, y-1, y]\n _data = list_y\n count_transit.add_value(_data,1)\n count_yi.add_value(list_y[:-1],1)\n _iter += 1\n self.transitions.data = self.divider_helper(self.transitions.data, count_transit.data, count_yi.data, vocab_for_transitions)\n return self.transitions\n\n def __get_pi(self, p, lst):\n l = lst[0]\n if len(lst) == 1:\n return p[self.vocab_y.index(l)]\n else:\n return self.__get_pi(p[self.vocab_y.index(l)], lst[1:])\n\n def __calculate_pi(self,pred, iter ,length , lst, list_x, PI):\n if length == 1:\n _ = []\n if iter >= 0:\n for i in self.vocab_y:\n _lst = [i] + lst\n a = self.emissions.get_sum([pred]+list_x)\n b = self.transitions.get_sum(_lst + [pred])\n nlog_a = sys.maxsize/1000\n nlog_b = sys.maxsize/1000\n if a > pow(10,-7):\n nlog_a = -1 * math.log(a)\n if b > pow(10,-7):\n nlog_b = -1 * math.log(b)\n if len(PI) == 0:\n _.append(nlog_a+ nlog_b)\n else:\n _pi = self.__get_pi(PI[-1], _lst[::-1])\n _.append(nlog_a+ nlog_b+ _pi)\n else:\n for i in self.vocab_y:\n _lst = [':'] + lst\n a = self.emissions.get_sum([pred]+list_x)\n b = self.transitions.get_sum(_lst + [pred])\n nlog_a = sys.maxsize/1000\n nlog_b = sys.maxsize/1000\n if a > pow(10,-7):\n nlog_a = -1 * math.log(a)\n if b > pow(10,-7):\n nlog_b = -1 * math.log(b)\n if len(PI) == 0:\n _.append(nlog_a+ nlog_b)\n else:\n _pi = self.__get_pi(PI[-1], _lst[::-1])\n _.append(nlog_a+ nlog_b+ _pi)\n return min(_)\n else:\n if iter >= 0:\n return [self.__calculate_pi(pred, iter-1, length-1, [i]+lst,list_x, PI) for i in self.vocab_y]\n else: \n return [self.__calculate_pi(pred, iter-1, length-1, [':']+lst,list_x, PI) for i in self.vocab_y]\n \n def argmin(self, lst):\n return lst.index(min(lst))\n \n def __get_argmax_pi(self, PIn, y_star, len):\n if len == self.num_y:\n _ = []\n for i, v in enumerate(self.vocab_y):\n _.append(self.__get_argmax_pi(PIn[i], y_star, len-1))\n m = self.argmin(_)\n return self.vocab_y[m]\n else:\n sum = 0\n if len == 0:\n return PIn\n else:\n for i,v in enumerate(self.vocab_y):\n sum += self.__get_argmax_pi(PIn[i], y_star, len-1)\n return sum\n\n\n def viterbi(self, test_x):\n ## Final Goal: Find PI(n,v) where n is the length of y without start and stop\n ## We wont use PI we will maximize negative log pi\n ## Step 1: Find PI(1,v)\n\n k = 1\n PI=[]\n while k < len(test_x)+1:\n list_x = []\n _pi = []\n for i in range(self.num_x):\n if (k - i - 1) >= 0:\n list_x.append(test_x[k - i - 1]) \n else:\n list_x.append(':')\n list_x = list_x[::-1]\n \n for pred_y_k in self.vocab_y:\n _pi.append(self.__calculate_pi(pred_y_k, k, self.num_y, [], list_x, PI))\n\n PI.append(_pi)\n\n k+= 1\n if k%100 == 0:\n print(k)\n\n print(len(PI), 'Should be ')\n\n\n\n PI = PI[::-1]\n y_star = 'STOP'\n final_Y = []\n final_Y.append(y_star)\n for index, _PI in enumerate(PI):\n list_x = []\n for i in range(self.num_x):\n if (index - i) >= 0:\n list_x.append(test_x[index - i]) \n else:\n list_x.append(':')\n list_x = list_x[::-1]\n y_star = self.__get_argmax_pi(_PI, y_star, self.num_y)\n final_Y.append(y_star)\n\n final_Y.append('START')\n final_Y = final_Y[::-1]\n return final_Y\n \n","sub_path":"ClassicalHMM.py","file_name":"ClassicalHMM.py","file_ext":"py","file_size_in_byte":7143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"15515483","text":"\"\"\"\r\nGraph related content\r\n\"\"\"\r\n\r\n\r\nfrom collections import defaultdict\r\nfrom collections import deque\r\n\r\nclass Graph:\r\n def __init__(self):\r\n self.graph = defaultdict(list)\r\n\r\n def add_edge(self, node, neighbour):\r\n self.graph[node].append(neighbour)\r\n\r\n def show_edges(self):\r\n for k, v in self.graph.items():\r\n print(k, v)\r\n\r\n def find_path(self, start, end, path=[]):\r\n path = path + [start]\r\n if start == end:\r\n return path\r\n\r\n for node in self.graph[start]:\r\n if node not in path:\r\n new_path = self.find_path(node, end, path)\r\n # After recursive call-stack ends, the end will be in PATH\r\n if new_path:\r\n return new_path\r\n return None\r\n\r\n def BFS(self, start):\r\n visited = {}\r\n result_path = []\r\n for k in self.graph:\r\n visited[k] = False\r\n\r\n q = deque(start)\r\n visited[start] = True\r\n\r\n while q:\r\n print(\"The queue is:\", q)\r\n vertex = q.popleft()\r\n print(\"The vertex is:\", vertex)\r\n for neighbours in self.graph[vertex]:\r\n if not visited[neighbours]:\r\n visited[neighbours] = True\r\n q.append(neighbours)\r\n result_path.append(vertex)\r\n return result_path\r\n\r\n def DFS(self, start):\r\n visited = {}\r\n result_path = []\r\n for i in self.graph:\r\n visited[i] = False\r\n\r\n stack = [start]\r\n visited[start] = True\r\n\r\n while stack:\r\n vertex = stack.pop(len(stack) - 1)\r\n for neighbours in self.graph[vertex]:\r\n if not visited[neighbours]:\r\n stack.append(neighbours)\r\n visited[neighbours] = True\r\n result_path.append(vertex)\r\n return result_path\r\n\r\ng = Graph()\r\n\r\ng.add_edge('1', '2')\r\ng.add_edge('1', '3')\r\ng.add_edge('2', '3')\r\ng.add_edge('2', '1')\r\ng.add_edge('3', '1')\r\ng.add_edge('3', '2')\r\ng.add_edge('3', '4')\r\ng.add_edge('4', '3')\r\n\r\n\r\n\r\n\r\nprint(\"Showing the edges\")\r\ng.show_edges()\r\n\r\n\"\"\"\r\nflow = g.find_path('4', '1')\r\nprint(flow)\r\n\"\"\"\r\nresult = g.BFS('1')\r\nprint(\"BFS\", result)\r\n\r\nresult = g.DFS('1')\r\nprint(\"DFS\", result)\r\n\r\npath = g.find_path(5, 3)\r\n\r\n\r\n# Other things to learn\r\n\"\"\"\r\n1. Djikstra shortest path \r\n2. Floyd Warshall - shortest path from every vertex to every other vertex\r\n3. Prim / Kruskal - Minimum Spanning Tree\r\n\r\nDFS Applications\r\n\r\n1. Detecting cycle in a graph\r\n2. Path finding\r\n3. Topological sort\r\n4. Testing if a graph is bi-partite\r\n\r\nBFS Applications\r\n1. Shortest path / MST for unweighted graph\r\n2. Cycle detection in undirected / directed graph\r\n3. Testing if a graph is bi-partite\r\n4. Path finding b/w 2 vertices\r\n5. Finding all nodes within one connected component.\r\n to find all nodes reachable from a given node.\r\n\r\nAnother technique to learn is Union-Find - Need to know what that technique is.\r\n\r\nOther representations of graph are:\r\n1. adjacency matrix\r\nwe generally use adjacency matric if we know that the number of edges is\r\nhigher than the number of nodes.\r\n\r\n2. linked representation\r\nhere, we make actual node objects, not commonly used in interviews\r\n\"\"\"\r\n\r\n# Check cycle in undirected graph\r\nfrom collections import defaultdict\r\n\r\nclass Solution:\r\n def validTree(self, n: int, edges: List[List[int]]) -> bool:\r\n if len(edges) != n - 1:\r\n return False\r\n\r\n # Constructing the Graph\r\n graph = defaultdict(list)\r\n for u, v in edges:\r\n graph[u].append(v)\r\n graph[v].append(u)\r\n # print(graph)\r\n\r\n parent = {0: -1}\r\n stack = [0]\r\n\r\n while stack:\r\n node = stack.pop()\r\n # print(\"The node is:\", node)\r\n for neighbour in graph[node]:\r\n # print(\"the neighbor is:\",neighbour)\r\n if neighbour == parent[node]:\r\n continue\r\n # if node is in the parent hashmap but is not your direct parent\r\n if neighbour in parent:\r\n # print(\"Entering here\")\r\n return False\r\n parent[neighbour] = node\r\n stack.append(neighbour)\r\n\r\n # print(parent)\r\n # print(\"************\")\r\n\r\n return len(parent) == n\r\n\r\n# Clean Smarter solution\r\ndef validTree(self, n: int, edges: List[List[int]]) -> bool:\r\n if len(edges) != n - 1: return False\r\n\r\n # Create an adjacency list.\r\n adj_list = [[] for _ in range(n)]\r\n for A, B in edges:\r\n adj_list[A].append(B)\r\n adj_list[B].append(A)\r\n\r\n # We still need a seen set to prevent our code from infinite\r\n # looping if there *is* cycles (and on the trivial cycles!)\r\n seen = {0}\r\n stack = [0]\r\n\r\n while stack:\r\n node = stack.pop()\r\n for neighbour in adj_list[node]:\r\n if neighbour in seen:\r\n continue\r\n seen.add(neighbour)\r\n stack.append(neighbour)\r\n\r\n return len(seen) == n\r\n\r\n### Just to check if you have parsed everything\r\nfrom collections import defaultdict\r\nfrom collections import deque\r\n\r\n\r\nclass Solution:\r\n def __init__(self):\r\n self.graph = defaultdict(list)\r\n\r\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\r\n # Generating the Graph\r\n for i, c in enumerate(rooms):\r\n for d in c:\r\n self.graph[str(i)].append(str(d))\r\n\r\n # Just do regular DFS / BFS traversal, and see if we can vist all nodes.\r\n visited = {}\r\n start = '0'\r\n\r\n for k in range(len(rooms)):\r\n visited[str(k)] = False\r\n\r\n q = deque(start)\r\n visited[start] = True\r\n\r\n while q:\r\n vertex = q.pop() # DFS\r\n #\tvertex = q.popleft() # BFS\r\n for neighbour in self.graph[vertex]:\r\n if visited[neighbour] == False:\r\n visited[neighbour] = True\r\n q.append(neighbour)\r\n\r\n val = visited.values()\r\n\r\n if all(c for c in val):\r\n return True\r\n return False\r\n\r\n# BFS / DFS on all nodes templates\r\n\r\n### To check if Graph is Bi-partite or not\r\nfrom collections import defaultdict\r\n\r\n\r\nclass Solution:\r\n def isBipartite(self, graph: List[List[int]]) -> bool:\r\n adj_map = defaultdict(list)\r\n for i, c in enumerate(graph):\r\n adj_map[i] = c\r\n print(adj_map)\r\n\r\n n = len(graph)\r\n color = [-1] * n\r\n\r\n for start in range(n):\r\n if color[start] == -1:\r\n color[start] = 0\r\n stack = [start, ]\r\n\r\n while stack:\r\n parent = stack.pop()\r\n\r\n for child in adj_map[parent]:\r\n if color[child] == -1:\r\n color[child] = 1 - color[parent]\r\n stack.append(child)\r\n elif color[parent] == color[child]:\r\n return False, color\r\n return True, color","sub_path":"cheat_sheet_2.py","file_name":"cheat_sheet_2.py","file_ext":"py","file_size_in_byte":7146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"340170154","text":"a=int(input())\nb=[]\nfor x in range(0,a):\n c=input()\n b.append(c)\nd=[]\nfor x in b:\n if x not in d:\n d.append(x)\nd.sort(reverse=True)\nprint (\"\".join(d))\n","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"593578102","text":"#!/usr/bin/python3\n\"\"\"Gather data from API\"\"\"\nimport csv\nimport json\nimport requests\nfrom sys import argv\n\n\nif __name__ == \"__main__\":\n \"\"\"Gather data from API and export as CSV\"\"\"\n url = \"https://jsonplaceholder.typicode.com/\"\n user = requests.get('{}users/{}'.format(url, argv[1]))\n todo = requests.get('{}todos?userId={}'.format(url, argv[1]))\n user_dic = json.loads(user.text)\n todo_dic = json.loads(todo.text)\n csv.register_dialect('myDialect',\n quoting=csv.QUOTE_ALL,\n skipinitialspace=True)\n with open('{}.csv'.format(argv[1]), 'w') as csvfile:\n spamwriter = csv.writer(csvfile, dialect='myDialect')\n for attr in todo_dic:\n row = []\n row.append('{}'.format(user_dic.get(\"id\")))\n row.append('{}'.format(user_dic.get(\"username\")))\n row.append('{}'.format(attr.get(\"completed\")))\n row.append('{}'.format(attr.get(\"title\")))\n spamwriter.writerow(row)\n csvfile.close()\n","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"213741868","text":"import os\r\nimport time\r\nimport subprocess\r\nimport configparser\r\nimport logging\r\n\r\n\r\nlogging.basicConfig(\r\n filename=os.path.join(os.path.dirname(os.path.dirname(__file__)), \"log\", \"launcher.log\"),\r\n level=logging.INFO,\r\n format=\"%(asctime)s %(levelname)-8s %(message)s\",\r\n datefmt=\"%H:%M:%S %d.%m.%Y\")\r\n\r\npath_tmp = os.path.join(os.path.dirname(os.path.dirname(__file__)), \"tmp\")\r\n\r\n\r\nclass ConfigParser(object):\r\n def __init__(self):\r\n self._config_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), \"config\", \"launcher.config\")\r\n self._config = configparser.ConfigParser()\r\n self._config.read(self._config_path)\r\n logging.debug(\"config_path set to: {}\".format(self._config_path))\r\n\r\n @property\r\n def get_applications(self):\r\n logging.debug(\"get_applications\")\r\n return self._config['applications']\r\n\r\n @property\r\n def get_time_to_wait(self):\r\n logging.debug(\"get_time_to_wait\")\r\n return self._config['setup']['time']\r\n\r\n def get_type(self, appl):\r\n logging.debug(\"get_type\")\r\n return self._config['applications'][appl]\r\n\r\n\r\nclass Application(object):\r\n def __init__(self, prod_path, appl, input_type):\r\n self._appl = appl\r\n self._appl_name = appl.split(\"Appl.\")[0]\r\n self._appl_prod_path = os.path.join(prod_path, self._appl_name)\r\n self._input_type = input_type\r\n self._last_run = None\r\n self._check_prod_path()\r\n\r\n @property\r\n def get_prod_path(self):\r\n logging.debug(\"get_prod_path\")\r\n return self._appl_prod_path\r\n\r\n @property\r\n def get_type(self):\r\n logging.debug(\"get_type\")\r\n return self._input_type\r\n\r\n @property\r\n def get_appl(self):\r\n logging.debug(\"get_appl\")\r\n return self._appl\r\n\r\n def set_last_run(self):\r\n logging.debug(\"set_last_run\")\r\n self._last_run = time.ctime()\r\n\r\n @property\r\n def get_last_run(self):\r\n logging.debug(\"get_last_run\")\r\n return self._last_run\r\n\r\n @property\r\n def get_appl_name(self):\r\n return self._appl_name\r\n\r\n def _check_prod_path(self):\r\n logging.debug(\"check_prod_path\")\r\n try:\r\n os.listdir(self._appl_prod_path)\r\n except FileNotFoundError:\r\n logging.error(\"could not find {}-> create path\".format(self._appl_prod_path))\r\n os.mkdir(self._appl_prod_path)\r\n try:\r\n os.listdir(os.path.join(self._appl_prod_path, \"bearbeitet\"))\r\n except FileNotFoundError:\r\n logging.error(\"could not find {}-> create path\".format(os.path.join(self._appl_prod_path, \"bearbeitet\")))\r\n os.mkdir(os.path.join(self._appl_prod_path, \"bearbeitet\"))\r\n\r\n\r\nclass Worker(object):\r\n def __init__(self, path):\r\n self._path = path\r\n\r\n def work(self, appl_list):\r\n for appl in appl_list:\r\n if not os.path.isfile(os.path.join(path_tmp, appl.get_appl_name+\".pid\")):\r\n files = os.listdir(appl.get_prod_path)\r\n mode = False\r\n for file in files:\r\n if appl.get_type in file:\r\n mode = True\r\n break\r\n if mode == True:\r\n try:\r\n subprocess.Popen(os.path.join(self._path, appl.get_appl), shell=True)\r\n appl.set_last_run()\r\n except (OSError, Exception):\r\n print(\"Fehler\")\r\n logging.error(\"could not run appl: {}\".format(appl.get_appl))\r\n\r\n\r\nclass Output(object):\r\n @staticmethod\r\n def console_out(appl_list):\r\n os.system(\"cls\")\r\n print(\"\\n\\tvoran.toolbox\")\r\n for i in range(len(appl_list)):\r\n print(\"{:25}: {}\".format(appl_list[i].get_appl, appl_list[i].get_last_run))\r\n print(\"{:25}: {}\".format(\"voran.toolbox\", time.ctime()))\r\n\r\n\r\nclass Scheduler(object):\r\n def __init__(self):\r\n self._application_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), \"voran.toolbox\")\r\n self._prod_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), \"prod\")\r\n self._config = ConfigParser()\r\n self._worker = Worker(self._application_path)\r\n self._active_applications = self._set_active_applications\r\n self._time_to_wait = self._set_time_to_wait\r\n self._applications_in_path = self._set_applications_in_path\r\n self._application_list = []\r\n self._setup()\r\n self._production()\r\n\r\n @property\r\n def _set_active_applications(self):\r\n logging.debug(\"set_active_applications\")\r\n return self._config.get_applications\r\n\r\n @property\r\n def _set_time_to_wait(self):\r\n logging.debug(\"set_time_to_wait\")\r\n return self._config.get_time_to_wait\r\n\r\n @property\r\n def _set_applications_in_path(self):\r\n logging.debug(\"set_applications_in_path\")\r\n return os.listdir(self._application_path)\r\n\r\n def _setup(self):\r\n logging.debug(\"setup\")\r\n for application in self._applications_in_path:\r\n if application in self._active_applications:\r\n logging.info(\"application found: {}\".format(application))\r\n appl_input = self._config.get_type(application)\r\n appl = Application(self._prod_path, application, appl_input)\r\n self._application_list.append(appl)\r\n\r\n def _production(self):\r\n logging.debug(\"production\")\r\n while True:\r\n Output.console_out(self._application_list)\r\n self._worker.work(self._application_list)\r\n time.sleep(int(self._time_to_wait))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n test = Scheduler()\r\n","sub_path":"hf.toolbox/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":5786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"291978504","text":"import numpy as np\nfrom random import shuffle\nfrom past.builtins import xrange\n\n\ndef softmax_loss_naive(W, X, y, reg):\n \"\"\"\n Softmax loss function, naive implementation (with loops)\n\n Inputs have dimension D, there are C classes, and we operate on minibatches\n of N examples.\n\n Inputs:\n - W: A numpy array of shape (D, C) containing weights.\n - X: A numpy array of shape (N, D) containing a minibatch of data.\n - y: A numpy array of shape (N,) containing training labels; y[i] = c means\n that X[i] has label c, where 0 <= c < C.\n - reg: (float) regularization strength\n\n Returns a tuple of:\n - loss as single float\n - gradient with respect to weights W; an array of same shape as W\n \"\"\"\n # Initialize the loss and gradient to zero.\n loss = 0.0\n dW = np.zeros_like(W)\n\n num_train = X.shape[0]\n\n for i in xrange(num_train):\n X_i = X[:, i]\n score_i = W.dot(X_i)\n\n # Normalize the scores to avoid computational problems with the exponential\n # Normalize max as zero\n shifter = -np.max(score_i, axis=1, keepdims=True)\n exp_scores_i = np.exp(score_i + shifter)\n\n # loss = -fyi-logC + log(sum(e^fyj + logC))\n loss += -score_i[y[i]] - shifter + np.log(np.sum(exp_scores_i))\n\n # Update dscore_i and dW\n dscore_i = exp_scores_i\n dscore_i *= np.sum(exp_scores_i)\n dW += np.dot(X_i.T, dscore_i)\n\n loss = loss / num_train + 0.5 * reg * np.sum(W * W)\n dW = dW / num_train + reg * W\n\n return loss, dW\n\n\ndef softmax_loss_vectorized(W, X, y, reg):\n \"\"\"\n Softmax loss function, vectorized version.\n\n Inputs and outputs are the same as softmax_loss_naive.\n \"\"\"\n # Initialize the loss and gradient to zero.\n loss = 0.0\n dW = np.zeros_like(W)\n num_train = X.shape[1]\n\n score = X.dot(W)\n shifter = -np.max(score, axis=1, keepdims=True) # the dimension of shifter is (N,)\n score += shifter\n exp_score = np.exp(score)\n sum_score = np.sum(exp_score, axis=1, keepdims=True) # the dimension of sum_score is (N,)\n sum_score_log = np.log(sum_score)\n\n loss_vector = sum_score_log - (y + shifter)\n loss += np.sum(loss_vector)\n\n loss = loss / num_train + 0.5 * reg * np.sum(W * W)\n\n dscore = (exp_score.T * sum_score).T # the dimension of dscore is still (N, C)\n dW += np.dot(X.T, dscore)\n dW = dW / num_train + reg * W\n\n return loss, dW\n","sub_path":"PixelBasedVisualReconginition/cs231n/classifiers/softmax.py","file_name":"softmax.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"187326859","text":"from sanic import Sanic\nfrom sanic_jinja2 import SanicJinja2\nfrom sanic.response import json\n\napp = Sanic()\n\njinja = SanicJinja2(app)\n\nmovies = [\n {\"id\": 1, \"title\": \"Gone with wind\"},\n {\"id\": 2, \"title\": \"Về nhà đi con\"},\n {\"id\": 3, \"title\": \"Người nhện xa nhà\"},\n]\n\n\n@app.route('/')\n@jinja.template('index.html')\nasync def index(request):\n return\n\n\n@app.route('/movies/all')\nasync def get_movie(request):\n return json(movies)\n\n\n@app.route('/movies')\nasync def get_movie(request):\n print(request.args[\"id\"][0])\n print(request.query_args)\n return json(request.args)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8000, debug=True)\n","sub_path":"AppIOS/Day5 Autolayout/GET_QUERY/get_query.py","file_name":"get_query.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"387564213","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nUsing a source email address, identify a unique user and their Team memberships\nApply all Team memberships to the target user(s), identified by target email address\n\"\"\"\n\nimport os\nimport json\nimport logging, logging.config\nimport sys\nfrom argparse import ArgumentParser\nimport requests\nimport pdpyras\npdpyras.APISession.raise_if_http_error = True\n\nSECRETS_FILE = 'secrets.json'\nLOGGER_FILE = 'logging.json'\n\n\ndef parse_args():\n \"\"\"\n Argument parsing is fun!\n \"\"\"\n\n parser = ArgumentParser()\n parser.add_argument(\n '--secrets',\n help='Full path to secrets file.',\n metavar='path'\n )\n parser.add_argument(\n '--source',\n help='Email address of an existing user from whom to copy Team memberships.',\n metavar='source'\n )\n parser.add_argument(\n '--target',\n action='append',\n help='Email address(es) of the user(s) to apply the copied Team memberships to.',\n metavar='target'\n )\n return parser.parse_args()\n\n\ndef post_message(webhook, channel, botname, message):\n \"\"\"\n Push the message to the channel as the botname\n \"\"\"\n\n payload = {\"channel\": channel,\n \"username\": botname,\n \"text\": message,\n \"icon_emoji\": \":thumbsup:\"}\n try:\n response = requests.post(webhook, data=json.dumps(payload))\n return response.text\n except requests.exceptions.RequestException as error:\n logging.warning(u'Post message to Slack failed: %s', error)\n\n\ndef main():\n \"\"\"\n For each user, add them to every team they are not already a member of\n \"\"\"\n\n\n if os.path.exists(LOGGER_FILE):\n with open(LOGGER_FILE, 'rt') as logger_file:\n logging_config = json.load(logger_file)\n logging.config.dictConfig(logging_config)\n else:\n logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\n\n # Parse configuration\n args = parse_args()\n with open(args.secrets or SECRETS_FILE) as secrets:\n secrets = json.load(secrets)\n if args.source is None:\n logging.fatal(\"No source email address supplied. Exiting.\")\n exit(1)\n if args.target is None:\n logging.fatal(\"No target email address supplied. Exiting.\")\n exit(2)\n\n # instantiate a PagerDuty Python REST API Sessions object\n pdapi = pdpyras.APISession(secrets.get('pagerduty').get('key'))\n\n # Find source user in PagerDuty API by email address\n user_source = pdapi.find('users', args.source, attribute='email')\n if user_source is None:\n logging.fatal(\"Supplied source email address (%s) did not match a user. Exiting.\", args.source)\n exit(3)\n else:\n logging.info(\"Found source user %s (%s) with %d Teams\", user_source.get('name'), user_source.get('email'), len(user_source.get('teams')))\n for team in user_source.get('teams'):\n logging.debug(\"Source Team: %s: %s\", team.get('id'), team.get('summary'))\n\n # Find target user(s) in PagerDuty API by email address\n for target in args.target:\n try:\n user_target = pdapi.find('users', target, attribute='email')\n except pdpyras.PDClientError as error:\n logging.critical(error)\n exit(4)\n if user_target is None:\n logging.error(\"Supplied target email address (%s) did not match a user.\", target)\n else:\n logging.info(\"Found target user %s (%s) with %d Teams\", user_target.get('name'), user_target.get('email'), len(user_target.get('teams')))\n for team in user_source.get('teams'):\n # scan the target user's teams for this team id - don't add them if it's already present\n if not any(d['id'] == team.get('id') for d in user_target.get('teams')):\n method = '/teams/{:s}/users/{:s}'.format(team.get('id'), user_target.get('id'))\n response = pdapi.request('PUT', method)\n if response.ok:\n logging.info(\"User %s (%s) added to Team %s: %s\", user_target.get('name'), user_target.get('email'), team.get('id'), team.get('summary'))\n else:\n logging.warning(\"User%s (%s) WAS NOT added to Team %s: %s\", user_target.get('name'), user_target.get('email'), team.get('id'), team.get('summary'))\n else:\n logging.info(\"User %s is already a member of %s\", user_target.get('name'), team.get('summary'))\n\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"add_users_to_groups.py","file_name":"add_users_to_groups.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"28853466","text":"# -*- coding: utf-8 -*-\n\n\ndef grep(filepath, match_pattern, dont_match_pattern):\n \"\"\"\n finds patt in file - patt is a compiled regex\n returns all lines that match patt\n\n http://grantmcwilliams.com/tech/programming/python/item/581-grep-a-file-in-python\n\n \"\"\"\n matchlines = []\n f = open(filepath)\n for line in f.readlines():\n match = match_pattern.search(line)\n if match and not dont_match_pattern.search(line):\n matchlines.append(line)\n results = '\\n '.join(matchlines)\n if results:\n return results\n else:\n return None\n","sub_path":"djinter/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"521616150","text":"#app.py\n#from flask import Flask, render_template, flash, request, redirect\nfrom flask import Flask, render_template, request, redirect, abort, flash, url_for, jsonify\n#from werkzeug.utils import secure_filename\nfrom werkzeug.urls import url_parse\nfrom werkzeug.utils import secure_filename\nimport os\n#import magic\nimport urllib.request\nimport modules.xer_analyzer\napp = Flask(__name__)\n\npath='D:/XER-Output'\ntry: \n os.mkdir(path) \nexcept OSError as error: \n print(error) \n\n\nUPLOAD_FOLDER = path\n \napp.secret_key = \"Cairocoders-Ednalan\"\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\n \nALLOWED_EXTENSIONS = set([ 'xer'])\n \ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n \n@app.route('/')\ndef upload_form():\n return render_template('upload.html')\n \n@app.route('/', methods=['POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the files part\n if 'files[]' not in request.files:\n flash('No file part')\n return redirect(request.url)\n files = request.files.getlist('files[]')\n xer_analyzer.ImportedFiles(files,path)\n\n for file in files:\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n #file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n flash('File(s) successfully uploaded')\n return redirect('/')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"362285169","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# Created by Roberto Preste\nimport os\nimport unittest\n\nimport pandas as pd\n\nfrom ..config_parsers import (\n fastqc_outputs, get_bed_files, get_genome_files, get_fasta_files,\n get_genome_vcf_files, get_mt_genomes, get_analysis_species,\n ref_genome_mt_to_species\n\n)\n\nANALYSIS_TAB = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"data\",\n \"analysis.tab\"\n)\nDATASETS_TAB = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"data\",\n \"datasets.tab\"\n)\nREFERENCE_TAB = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"data\",\n \"reference_genomes.tab\"\n)\nFASTQC_OUT = [\n \"{}/5517_hypo_1.R1_fastqc.html\",\n \"{}/5517_hypo_1.R2_fastqc.html\",\n \"{}/5517_hypo_2.R1_fastqc.html\",\n \"{}/5517_hypo_2.R2_fastqc.html\",\n \"{}/5517_liver_1.R1_fastqc.html\",\n \"{}/5517_liver_1.R2_fastqc.html\",\n \"{}/5517_liver_2.R1_fastqc.html\",\n \"{}/5517_liver_2.R2_fastqc.html\"\n]\n\nFASTQC_OUT_FILT = [\n \"{}/5517_hypo_1_qc_R1_fastqc.html\",\n \"{}/5517_hypo_1_qc_R2_fastqc.html\",\n \"{}/5517_hypo_2_qc_R1_fastqc.html\",\n \"{}/5517_hypo_2_qc_R2_fastqc.html\",\n \"{}/5517_liver_1_qc_R1_fastqc.html\",\n \"{}/5517_liver_1_qc_R2_fastqc.html\",\n \"{}/5517_liver_2_qc_R1_fastqc.html\",\n \"{}/5517_liver_2_qc_R2_fastqc.html\",\n \"{}/5517_hypo_1_qc_U_fastqc.html\",\n \"{}/5517_hypo_2_qc_U_fastqc.html\",\n \"{}/5517_liver_1_qc_U_fastqc.html\",\n \"{}/5517_liver_2_qc_U_fastqc.html\"\n]\n# FASTQC_OUT_FILT = FASTQC_OUT + [\n# \"{}/5517_hypo_1_qc_U_fastqc.html\",\n# \"{}/5517_hypo_2_qc_U_fastqc.html\",\n# \"{}/5517_liver_1_qc_U_fastqc.html\",\n# \"{}/5517_liver_2_qc_U_fastqc.html\",\n# ]\n\n\nclass TestConfigParsers(unittest.TestCase):\n\n def setUp(self) -> None:\n self.analysis_tab = pd.read_table(ANALYSIS_TAB, sep=\"\\t\", comment=\"#\")\n self.datasets_tab = pd.read_table(DATASETS_TAB, sep=\"\\t\", comment=\"#\")\n self.reference_tab = (pd.read_table(REFERENCE_TAB, sep=\"\\t\", comment='#')\n .set_index(\"ref_genome_mt\", drop=False))\n\n def test_ref_genome_mt_to_species(self):\n # Given\n expected = \"ggallus\"\n # When\n result = ref_genome_mt_to_species(ref_genome_mt=\"NC_001323.1\", reference_tab=self.reference_tab)\n # Then\n self.assertEqual(expected, result)\n\n def test_get_analysis_species(self):\n # Given\n expected = [\"ggallus\", \"human\"]\n # When\n result1 = get_analysis_species(\"NC_001323.1\", reference_tab=self.reference_tab, config_species=None)\n result2 = get_analysis_species(\"NC_001323.1\", reference_tab=self.reference_tab, config_species=\"human\")\n # Then\n self.assertEqual(expected, [result1, result2])\n \n def test_get_mt_genomes(self):\n # Given\n expected = [\"NC_001323.1\"]\n\n # When\n result = get_mt_genomes(self.analysis_tab)\n\n # Then\n self.assertEqual(expected, result)\n\n def test_fastqc_outputs_raw(self):\n # Given\n expected = [el.format(\"results/fastqc_raw\")\n for el in FASTQC_OUT]\n\n # When\n result = fastqc_outputs(datasets_tab=self.datasets_tab,\n analysis_tab=self.analysis_tab,\n out=\"raw\")\n\n # Then\n self.assertEqual(expected, result)\n\n def test_fastqc_outputs_filtered(self):\n # Given\n expected = [el.format(\"results/fastqc_filtered\")\n for el in FASTQC_OUT_FILT]\n\n # When\n result = fastqc_outputs(datasets_tab=self.datasets_tab,\n analysis_tab=self.analysis_tab,\n out=\"filtered\")\n\n # Then\n self.assertEqual(sorted(expected), sorted(result))\n\n def test_fastqc_outputs_error(self):\n # Given/When\n with self.assertRaises(ValueError):\n fastqc_outputs(datasets_tab=self.datasets_tab,\n analysis_tab=self.analysis_tab,\n out=\"test\")\n\n def test_get_genome_vcf_files(self):\n # Given\n expected = [\"results/vcf/NC_001323.1_GCF_000002315.5.vcf\"]\n\n # When\n result = get_genome_vcf_files(df=self.analysis_tab)\n\n # Then\n self.assertEqual(expected, result)\n\n def test_get_bed_files(self):\n # Given\n expected = [\n \"results/5517_hypo/5517_hypo_NC_001323.1_GCF_000002315.5.bed\",\n \"results/5517_liver/5517_liver_NC_001323.1_GCF_000002315.5.bed\"\n ]\n\n # When\n result = get_bed_files(df=self.analysis_tab)\n\n # Then\n self.assertEqual(expected, result)\n\n def test_get_fasta_files(self):\n # Given\n expected = [\n \"results/5517_hypo/5517_hypo_NC_001323.1_GCF_000002315.5.fasta\",\n \"results/5517_liver/5517_liver_NC_001323.1_GCF_000002315.5.fasta\"\n ]\n\n # When\n result = get_fasta_files(df=self.analysis_tab)\n\n # Then\n self.assertEqual(expected, result)\n\n def test_get_genome_files(self):\n # Given\n expected = [\"GCF_000002315.5_GRCg6a_genomic_mt.fna\"]\n\n # When\n result = get_genome_files(df=self.reference_tab,\n ref_genome_mt=\"NC_001323.1\",\n field=\"ref_genome_mt_file\")\n\n # Then\n self.assertEqual(expected, result)\n","sub_path":"modules/tests/test_config_parsers.py","file_name":"test_config_parsers.py","file_ext":"py","file_size_in_byte":5423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"499498029","text":"import os\nimport numpy as np\nimport matplotlib\n#matplotlib.use(\"TkAgg\")\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfrom copy import copy\nfrom PIL import Image, ImageOps\nfrom scipy.ndimage.morphology import binary_closing\nimport trimesh\n\n\nclass Mesh:\n def __init__(self, filepath=None, pointcloud=None):\n if pointcloud is not None:\n self.verts = pointcloud.astype(\"float32\")\n self.faces = None\n\n elif filepath is not None:\n self.verts = []\n self.faces = []\n self.load_mesh(filepath)\n\n def load_mesh(self, filepath):\n \"\"\" Store vertices and faces of the mesh \"\"\"\n self.verts = []\n self.faces = []\n\n with open(filepath, 'r') as file:\n # Read the file a line at a time, identifying vertices and faces\n for line in file:\n if line[0] == 'v':\n self.verts.append([float(vi) for vi in line[2:].split(' ')])\n elif line[0] == 'f':\n self.faces.append([int(fi) - 1 for fi in line[2:].split(' ')])\n else:\n pass\n\n self.verts = np.array(self.verts, dtype=\"float32\")\n self.faces = np.array(self.faces, dtype=int)\n\n def __repr__(self):\n \"\"\" Represent object as the arrays of its vertices and faces \"\"\"\n return str({\"Vertices\": self.verts, \"Faces\": self.faces})\n\n def rotate(self, theta=(0, 0, 0), save=True):\n # Construct the rotation matrices\n theta_x = np.radians(theta[1])\n theta_y = np.radians(theta[2])\n theta_z = np.radians(theta[0])\n\n R_x = np.array([[1, 0, 0], [0, np.cos(theta_x), -np.sin(theta_x)], [0, np.sin(theta_x), np.cos(theta_x)]])\n R_y = np.array([[np.cos(theta_y), 0, -np.sin(theta_y)], [0, 1, 0], [np.sin(theta_z), 0, np.cos(theta_z)]])\n R_z = np.array([[np.cos(theta_z), -np.sin(theta_z), 0], [np.sin(theta_z), np.cos(theta_z), 0], [0, 0, 1]])\n R = np.matmul(R_z, R_y, R_x)\n\n new_verts = np.array([np.dot(R, vert) for vert in self.verts])\n if save:\n self.verts = new_verts\n\n return new_verts\n\n def render3D(self):\n \"\"\" Render the mesh in 3D \"\"\"\n mesh = trimesh.Trimesh(vertices=self.verts, faces=self.faces)\n mesh.show(resolution=(512, 512))\n\n def render_silhouette_pers(self, dim=(256, 256), cam_zdist=1, morph_mask=\"default\", show=True, title=\"silhouette\"):\n \"\"\" Render silhouette by projecting (taking account of perspective) the point cloud \"\"\"\n # Define the scale factors\n x_sf = dim[0] - 1\n y_sf = dim[1] - 1\n\n # Collapse the points onto the x-y plane by dropping the z-coordinate, adjusting for the camera position (in distance in z-coordinate from projective plane)\n verts = copy(self.verts)\n verts_z = verts[:, 2]\n mesh_slice = verts[:, :2]\n\n mesh_slice[:, 0] *= x_sf/verts_z * cam_zdist\n mesh_slice[:, 1] *= y_sf/verts_z * cam_zdist\n\n coords = np.round(mesh_slice).astype(\"uint8\")\n\n # Create background to project silhouette on\n image = np.ones(shape=dim, dtype=\"uint8\")\n for coord in coords:\n # Fill in values with a silhouette coordinate on them\n x = coord[1]\n y = coord[0]\n\n if x <= x_sf and y <= y_sf:\n # Only show the silhouette if it is visible\n image[x, y] = 0\n\n if morph_mask is not None:\n # Optionally apply a morphological closing operation to fill in the silhouette\n if morph_mask == \"default\":\n # Use a circular mask as the default operator\n morph_mask = np.array([[0.34, 0.34, 0.34],\n [0.34, 1.00, 0.34],\n [0.34, 0.34, 0.34]\n ])\n image = np.invert(image.astype(bool))\n image = np.invert(binary_closing(image, structure=morph_mask, iterations=2)).astype(np.uint8)\n image *= 255\n\n if show:\n plt.imshow(image, cmap=\"gray\")\n plt.title(title)\n plt.show()\n\n return image\n\n def render_silhouette(self, dim=(256, 256), morph_mask=None, show=True, title=\"silhouette\"):\n \"\"\" Create a(n orthographic) silhouette out of a 2D slice of the pointcloud \"\"\"\n x_sf = dim[0] - 1\n y_sf = dim[1] - 1\n\n # Collapse the points onto the x-y plane by dropping the z-coordinate\n verts = copy(self.verts)\n mesh_slice = verts[:, :2]\n mesh_slice[:, 0] += 1\n mesh_slice[:, 1] += 1.2\n mesh_slice *= np.mean(dim)/2.2\n coords = np.round(mesh_slice)\n x_mask = coords[:, 0] <= x_sf\n y_mask = coords[:, 1] <= y_sf\n mask = x_mask * y_mask\n coords = coords[mask]\n coords = coords.astype(\"uint8\")\n\n # Create background to project silhouette on\n image = np.ones(shape=dim, dtype=\"uint8\")\n for coord in coords:\n # Fill in values with a silhouette coordinate on them\n image[y_sf-coord[1], coord[0]] = 0\n\n # Finally, perform a morphological closing operation to fill in the silhouette\n if morph_mask is None:\n # Use a circular mask as the default operator\n morph_mask = np.array([[0.34, 0.34, 0.34],\n [0.34, 1.00, 0.34],\n [0.34, 0.34, 0.34]\n ])\n image = np.invert(image.astype(bool))\n image = np.invert(binary_closing(image, structure=morph_mask, iterations=2)).astype(np.uint8)\n image *= 255\n\n if show:\n plt.imshow(image, cmap=\"gray\")\n plt.title(title)\n plt.show()\n\n return image\n\n def render_silhouette_centre(self, dim=(256, 256), padding=0.00, morph_mask=None, show=True, title=\"silhouette\"):\n \"\"\" Create a(n orthographic) silhouette out of a 2D slice of the pointcloud \"\"\"\n # Define the scale factors and padding\n x_sf = dim[0] - 1\n y_sf = dim[1] - 1\n\n # Collapse the points onto the x-y plane by dropping the z-coordinate\n verts = copy(self.verts)\n mesh_slice = verts[:, :2]\n\n # Adjust the x-y coordinates by shifting appropriately (considering padding)\n mesh_slice[:, 0] -= np.min(mesh_slice[:, 0]) - padding\n mesh_slice[:, 1] -= np.min(mesh_slice[:, 1]) - padding\n\n # Scale the array such that the largest value is 1.0 (then pad)\n array_max = np.max([np.max(mesh_slice[:, 0]), np.max(mesh_slice[:, 1])])\n mesh_slice[:, 0] = ((1 + padding/2) + mesh_slice[:, 0] / array_max) * x_sf\n mesh_slice[:, 1] = ((1 + padding/2) - (mesh_slice[:, 1] / array_max)) * y_sf\n mesh_slice[:, 0] += ((1 - padding) - np.max(mesh_slice[:, 0]))/2\n mesh_slice[:, 1] += ((1 - padding) - np.min(mesh_slice[:, 1]))/2\n\n # Convert to uint8 coordinate values and shift such that the image is roughly central\n coords = np.round(mesh_slice).astype(\"uint8\")\n\n # Create background to project silhouette on\n image = np.ones(shape=dim, dtype=\"uint8\")\n for coord in coords:\n # Fill in values with a silhouette coordinate on them\n image[coord[1], coord[0]] = 0\n\n # Finally, perform a morphological closing operation to fill in the silhouette\n if morph_mask is None:\n # Use a circular mask as the default operator\n morph_mask = np.array([[0.34, 0.34, 0.34],\n [0.34, 1.00, 0.34],\n [0.34, 0.34, 0.34]\n ])\n image = np.invert(image.astype(bool))\n image = np.invert(binary_closing(image, structure=morph_mask, iterations=2)).astype(np.uint8)\n image *= 255\n\n if show:\n plt.imshow(image, cmap=\"gray\")\n plt.title(title)\n plt.show()\n\n return image\n\n def render2D(self, theta=None, save_path=None, show=True):\n \"\"\" Create a 2D rendering of a slice of the mesh \"\"\"\n if theta is not None:\n verts = self.rotate(theta, save=False)\n else:\n verts = self.verts\n\n # Collapse the points onto the x-y plane by dropping the z-coordinate\n mesh_slice = verts[:, :2]\n\n # Use pyplot to plot the resulting points\n fig = plt.figure(frameon=False)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n\n ax.scatter(mesh_slice[:, 0], mesh_slice[:, 1])\n ax.set_aspect(\"equal\", adjustable=\"datalim\")\n\n if save_path is not None:\n fig.savefig(save_path, format=\"png\", cmap=\"gray\")\n image = Image.open(save_path).convert(\"L\")\n image = ImageOps.fit(image, (128, 128), Image.ANTIALIAS)\n image.save(save_path, format=\"png\")\n\n plt.close()\n\n return image\n elif show:\n plt.show()\n\n plt.close()\n\nif __name__ == \"__main__\":\n mesh_dir = \"../example_meshes/\"\n obj_paths = os.listdir(mesh_dir)\n for obj_path in obj_paths:\n mesh = Mesh(os.path.join(mesh_dir, obj_path))\n mesh.render_silhouette()\n mesh.render3D()\n","sub_path":"projects/deep_optimiser/code/tools/rendering_helpers.py","file_name":"rendering_helpers.py","file_ext":"py","file_size_in_byte":9332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"303728937","text":"from rest_framework import serializers,exceptions\n\nfrom user.models import User, Employee\n\n\nclass UserModelSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = (\"username\", \"real_name\", \"password\", \"gender\",\"register_time\")\n extra_kwargs = {\n \"username\": {\n \"required\": True,\n \"min_length\": 2,\n \"error_messages\": {\n \"required\": \"用户名是必填的\",\n \"min_length\": \"用户名长度太短\"\n }\n },\n \"real_name\": {\n \"required\": True,\n \"min_length\": 2,\n \"error_messages\": {\n \"required\": \"真实姓名是必填的\",\n \"min_length\": \"真实姓名长度太短,不合法!\"\n }\n },\n \"register_time\": {\n \"required\": True,\n \"error_messages\": {\n \"required\": \"注册时间是必填的\",\n }\n },\n }\n\n # 全局校验钩子\n # def validate(self, attrs):\n # pwd = attrs.get(\"password\")\n # re_pwd = attrs.pop(\"password2\")\n # print(attrs)\n # if pwd != re_pwd:\n # raise exceptions.ValidationError(\"两次密码不一致\")\n #\n # return attrs\n def validate(self, attrs):\n username = attrs.get(\"username\")\n print(username)\n st_obj = User.objects.filter(username=username)\n if st_obj:\n raise serializers.ValidationError(\"用户名已存在,请换一个!\")\n return attrs\n\n # def validate_username(self, value):\n # print(value)\n # st_obj = User.objects.filter(username=value)\n # if st_obj:\n # raise serializers.ValidationError(\"用户名已存在,请换一个!\")\n # return value\n\n# class UserModelSerializer1(serializers.ModelSerializer):\n#\n# class Meta:\n# model = User\n# fields = (\"__all__\")\n\n\nclass EmployeeModelSerializer(serializers.ModelSerializer):\n class Meta:\n model = Employee\n fields = (\"__all__\")\n extra_kwargs = {\n \"emp_name\": {\n \"required\": True,\n \"min_length\": 2,\n \"error_messages\": {\n \"required\": \"用户名是必填的\",\n \"min_length\": \"用户名长度太短\"\n }\n },\n \"salary\": {\n \"required\": True,\n \"error_messages\": {\n \"required\": \"工资不能为空\",\n }\n },\n \"age\": {\n \"required\": True,\n \"error_messages\": {\n \"required\": \"年龄不能为空\",\n }\n }\n }\n\n","sub_path":"user/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"539735044","text":"import sys\nimport os\nsrc = os.path.join(os.pardir, os.pardir, 'src')\nsys.path.append(src)\nsys.path.append(os.path.join(os.pardir))\nsys.path.append(os.path.join(src, 'neuralNetwork'))\nsys.path.append(os.path.join(src, 'constrainedChasingEscapingEnv'))\nsys.path.append(os.path.join(src, 'algorithms'))\nimport pandas as pd\nimport policyValueNet as net\nimport pickle\nfrom collections import OrderedDict\nfrom trajectoriesSaveLoad import GetSavePath\nimport trainTools\nimport random\n\n\ndef dictToFileName(parameters):\n sortedParameters = sorted(parameters.items())\n nameValueStringPairs = [\n parameter[0] + '=' + str(parameter[1]) for parameter in sortedParameters\n ]\n modelName = '_'.join(nameValueStringPairs).replace(\" \", \"\")\n return modelName\n\n\nclass GenerateTrainedModel:\n\n def __init__(self, getSavePathForModel, getSavePathForDataSet,\n getGenerateModel, generateTrain, generateLRModifier,\n generateReporter):\n self.getSavePathForModel = getSavePathForModel\n self.generateTrain = generateTrain\n self.getGenerateModel = getGenerateModel\n self.getSavePathForDataSet = getSavePathForDataSet\n self.generateLRModifier = generateLRModifier\n self.generateReporter = generateReporter\n\n def __call__(self, df):\n batchSize = df.index.get_level_values('batchSize')[0]\n trainingStep = df.index.get_level_values('trainingStep')[0]\n neuronsPerLayer = df.index.get_level_values('neuronsPerLayer')[0]\n sharedLayers = df.index.get_level_values('sharedLayers')[0]\n actionLayers = df.index.get_level_values('actionLayers')[0]\n valueLayers = df.index.get_level_values('valueLayers')[0]\n numOfFrame = df.index.get_level_values('numOfFrame')[0]\n numOfStateSpace = df.index.get_level_values('numOfStateSpace')[0]\n trainingDataType = df.index.get_level_values('trainingDataType')[0]\n learningRate = df.index.get_level_values('lr')[0]\n generateModel = self.getGenerateModel(numOfStateSpace * numOfFrame)\n dataSetparameters = {\n \"numOfStateSpace\": numOfStateSpace,\n \"numOfFrame\": numOfFrame,\n \"trainingDataType\": trainingDataType\n }\n dataSetPath = self.getSavePathForDataSet(dataSetparameters)\n with open(dataSetPath, 'rb') as f:\n trainData = pickle.load(f)\n indexLevelNames = df.index.names\n parameters = {\n levelName: df.index.get_level_values(levelName)[0]\n for levelName in indexLevelNames\n }\n saveModelDir = self.getSavePathForModel(parameters)\n modelName = dictToFileName(parameters)\n modelPath = os.path.join(saveModelDir, modelName)\n model = generateModel([neuronsPerLayer] * sharedLayers,\n [neuronsPerLayer] * actionLayers,\n [neuronsPerLayer] * valueLayers)\n if not os.path.exists(saveModelDir):\n lrModifier = self.generateLRModifier(learningRate)\n reporter = self.generateReporter(trainingStep)\n train = self.generateTrain(trainingStep, batchSize, lrModifier, reporter)\n trainedModel = train(model, trainData)\n net.saveVariables(trainedModel, modelPath)\n return pd.Series({\"train\": 'done'})\n\n\ndef main():\n dataDir = os.path.join(os.pardir, os.pardir, 'data',\n 'evaluateByStateDimension')\n\n # generate NN model\n numOfActionSpace = 8\n regularizationFactor = 1e-4\n getGenerateModel = lambda numOfStateSpace: net.GenerateModel(\n numOfStateSpace, numOfActionSpace, regularizationFactor)\n\n # generate NN train\n lossChangeThreshold = 1e-6\n lossHistorySize = 10\n trainTerminalController = trainTools.TrainTerminalController(\n lossHistorySize, lossChangeThreshold)\n initActionCoefficient = (1, 1)\n initValueCoefficient = (1, 1)\n coefficientController = trainTools.CoefficientCotroller(\n initActionCoefficient, initValueCoefficient)\n reportInterval = 1000\n generateReporter = lambda maxStep: trainTools.TrainReporter(maxStep, reportInterval)\n decayRate = 1\n decayStep = 1\n generateLRModifier = lambda initLearningRate: trainTools.LearningRateModifier(\n initLearningRate, decayRate, decayStep)\n generateTrain = lambda trainingStep, batchSize, lrModifier, reporter: net.Train(\n trainingStep, batchSize, net.sampleData, lrModifier,\n trainTerminalController, coefficientController, reporter)\n\n # split\n independentVariables = OrderedDict()\n independentVariables['trainingDataType'] = ['actionLabel']\n independentVariables['trajectory'] = [6000]\n independentVariables['batchSize'] = [64]\n independentVariables['augment'] = [False]\n independentVariables['trainingStep'] = [\n num for num in range(0, 500001, 50000)\n ]\n independentVariables['neuronsPerLayer'] = [128]\n independentVariables['sharedLayers'] = [8]\n independentVariables['actionLayers'] = [1]\n independentVariables['valueLayers'] = [1]\n independentVariables['numOfFrame'] = [1, 3]\n independentVariables['numOfStateSpace'] = [8]\n independentVariables['lr'] = [1e-4]\n\n levelNames = list(independentVariables.keys())\n levelValues = list(independentVariables.values())\n levelIndex = pd.MultiIndex.from_product(levelValues, names=levelNames)\n toSplitFrame = pd.DataFrame(index=levelIndex)\n\n trainedModelDir = os.path.join(dataDir, \"trainedModel\")\n if not os.path.exists(trainedModelDir):\n os.mkdir(trainedModelDir)\n getModelSavePath = GetSavePath(trainedModelDir, \"\")\n\n # get train data\n trainingDataDir = os.path.join(dataDir, 'trainingData')\n getDataSavePath = GetSavePath(trainingDataDir, \".pickle\")\n\n generateTrainingOutput = GenerateTrainedModel(getModelSavePath,\n getDataSavePath,\n getGenerateModel,\n generateTrain,\n generateLRModifier,\n generateReporter)\n resultDF = toSplitFrame.groupby(levelNames).apply(generateTrainingOutput)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"exec/evaluateByStateDimension/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"314921725","text":"import os\nimport psycopg2\nfrom PIL import Image\nfrom PIL import ImageDraw\n\nmatchID = input('Match ID: ')\nteamID = input('Match ID: ')\nDATABASE_URL = 'postgres://guutwjjarimvko:71a1eeb140752e9c5d555bd2004caef0056b65362926a29bb64e8be1727bb1a8@ec2-54-165-164-38.compute-1.amazonaws.com:5432/ddb8599tmhdji5'\nconn = psycopg2.connect(DATABASE_URL, sslmode='require')\ncur = conn.cursor()\ncur.execute('SELECT * FROM public.aerials WHERE \"MatchID\" = %s AND \"TeamID\" = %s', (matchID,teamID,))\n\nrows = cur.fetchall()\n\nimg = Image.open(\"./assets/images/HockeyPitchAerials.png\").convert('RGB')\ndraw = ImageDraw.Draw(img)\n\nfor row in rows:\n if row[6] == True:\n colour = (255,0,0)\n else:\n colour = (0,255,0)\n draw.line((row[4],row[5], row[2],row[3]), fill=colour, width=3)\n\nimg.save('./assets_output/' + 'Aerials.png')","sub_path":"aerials.py","file_name":"aerials.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"595925494","text":"\"\"\"Load from a Dataframe object\"\"\"\nfrom typing import Any, Iterator, List\n\nfrom langchain.docstore.document import Document\nfrom langchain.document_loaders.base import BaseLoader\n\n\nclass DataFrameLoader(BaseLoader):\n \"\"\"Load Pandas DataFrame.\"\"\"\n\n def __init__(self, data_frame: Any, page_content_column: str = \"text\"):\n \"\"\"Initialize with dataframe object.\n\n Args:\n data_frame: Pandas DataFrame object.\n page_content_column: Name of the column containing the page content.\n Defaults to \"text\".\n \"\"\"\n import pandas as pd\n\n if not isinstance(data_frame, pd.DataFrame):\n raise ValueError(\n f\"Expected data_frame to be a pd.DataFrame, got {type(data_frame)}\"\n )\n self.data_frame = data_frame\n self.page_content_column = page_content_column\n\n def lazy_load(self) -> Iterator[Document]:\n \"\"\"Lazy load records from dataframe.\"\"\"\n\n for _, row in self.data_frame.iterrows():\n text = row[self.page_content_column]\n metadata = row.to_dict()\n metadata.pop(self.page_content_column)\n yield Document(page_content=text, metadata=metadata)\n\n def load(self) -> List[Document]:\n \"\"\"Load full dataframe.\"\"\"\n return list(self.lazy_load())\n","sub_path":"langchain/document_loaders/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"243428042","text":"# 075 Пірати і монети\nq=input().split()\na=int(q[0])\nm=int(q[1])\nk=0\nwhile True:\n k+=1\n m-=a\n a+=1\n if m==2*a:\n break\n\nprint(k+1)\n","sub_path":"1-999/075.py","file_name":"075.py","file_ext":"py","file_size_in_byte":161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"55518330","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sp\nimport scipy.ndimage as ndi\nfrom pathlib import Path\nimport skimage as ski\nimport skimage.morphology as morph\nfrom skimage.morphology import disk\nimport skimage.filter.rank as rank\nimport skimage.filter as filter\nimport skimage.feature as feature\n\nwith Path(\"imagem1.jpeg\") as imfile:\n im1 = ndi.imread(imfile)\n\ncont = np.zeros_like(im1)\nfor n in range(3):\n cont[:,:,n] = morph.erosion(im1[:,:,n], disk(1))\n\nim = np.where(cont[:,:,1] > 100, 1, 0)\n\n#Soma das linhas para obtermos as posiões de inicio e fim de cada um a das linhas do texto\ncoluna = np.zeros(1072, dtype=np.int)\nfor i in range(0, 1072):\n coluna[i] = sum(im[i])\nim_inv = np.invert(im)\n\n#Declaração das variaveis\ninicio_lin = []\nfim_lin = []\n\ninicio_col = []\nfim_col = []\n\n\ninicio_lin.append(0)\nfor i in range(0, 1072):\n if coluna[i] == 800 and coluna[i-1] != 800:\n fim_lin.append(i)\n elif coluna[i] == 800 and coluna[i+1] != 800:\n inicio_lin.append(i)\n\n#Remove o ultimo elemento do vetor inicio_lin pois existe um ponto na parte de baixo da imagem que não queremos que seja considerado\ninicio_lin.remove(inicio_lin[len(inicio_lin)-1])\n\nlinha = np.zeros(800, dtype=np.int)\nfor i in range(0, 800):\n for j in range(inicio_lin[2], fim_lin[2]+1):\n linha[i] += im[j][i]\n\nfor i in range(0, 799):\n if linha[i] == 30 and linha[i-1] != 30:\n fim_col.append(i)\n elif linha[i] == 30 and linha[i+1] != 30:\n inicio_col.append(i)\n\nprint(inicio_col)\nprint(\"\\n\")\nprint(fim_col)\n\nfor i in range(0, len(inicio_lin)):\n plt.imshow(im_inv[inicio_lin[i]:fim_lin[i]][:], cmap=\"gray\")\n plt.show()\n print(i)\n","sub_path":"testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"27461650","text":"from __future__ import unicode_literals\nfrom django.db import models\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.core.validators import RegexValidator\nfrom django.core.validators import URLValidator\n\n\nclass ShareLogin(models.Model):\n user = models.ForeignKey(User, related_name=\"user\", default=True)\n site = models.CharField(max_length=200, validators=[URLValidator()])\n username = models.CharField(max_length=60)\n password = models.CharField(max_length=20)\n others = models.CharField(max_length=100, blank=True)\n created_time = models.DateTimeField(editable=False, auto_now=True)\n modified_time = models.DateTimeField(null=True, blank=True)\n\n def save(self, *args, **kwargs):\n if not self.id:\n self.created = timezone.now()\n self.modified = timezone.now()\n return super(ShareLogin, self).save(*args, **kwargs)\n\n def __str__(self):\n return str(self.pk)\n\n def __unicode__(self):\n return str(self.pk)\n","sub_path":"base/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"557381838","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 22 11:31:03 2019\n\n@author: Asus\n\"\"\"\n\nnpm = input(\"NPM: \")\n\nval = int(npm[4])\nval2 = int(npm[5])\nval3 = int(npm[6])\n\nsubs = val + val2 + val3\n\nprint(\"Input: \"+npm)\nprint(\"Output: \")\n\nwhile subs > 0:\n print(\"Hallo, \"+npm[4:7]+\" Apa Kabar?\")\n subs = subs - 1","sub_path":"Chapter 2/D4 TI B/Syabriena Putri Veriane(1184094)/1184094.py/loop2.py","file_name":"loop2.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"296577237","text":"from data import DICTIONARY, LETTER_SCORES\nfrom collections import namedtuple\nimport json\nfrom functools import reduce\nimport os\n\nWordScore = namedtuple('WordScore', 'word score')\n\n\ndef clear():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n\ndef load_words() -> object:\n \"\"\"\n Load dictionary into a list and return list\n \"\"\"\n with open(DICTIONARY, 'r') as f:\n return f.read().split('\\n')\n\n\ndef calc_word_value(word):\n \"\"\"\n Calculate the value of the word entered into function\n using imported constant mapping LETTER_SCORES\n \"\"\"\n return reduce(\n lambda accum, char: accum + LETTER_SCORES.get(char.upper(), 0),\n list(word), 0\n )\n\n\ndef calc_word_value2(word):\n \"\"\"\n Calculate the value of the word entered into function\n using imported constant mapping LETTER_SCORES\n \"\"\"\n result: int = 0\n for letter in word.upper():\n result += LETTER_SCORES.get(letter, 0)\n return result\n\n\ndef max_word_and_value(words=load_words()):\n \"\"\"\n Calculate the word with the max value, can receive a list\n of words as arg, if none provided uses default DICTIONARY\n \"\"\"\n current_max = 0\n current_word = ''\n for word in words:\n score = calc_word_value(word)\n if score > current_max:\n current_max = score\n current_word = word\n return WordScore(current_word, current_max)\n\n\ndef max_word_value(words=load_words()):\n \"\"\"\n Calculate the word with the max value, can receive a list\n of words as arg, if none provided uses default DICTIONARY\n \"\"\"\n current_max = 0\n current_word = ''\n for word in words:\n score = calc_word_value(word)\n if score > current_max:\n current_max = score\n current_word = word\n return current_word\n\n\ndef calculate_all_scores(words=load_words()):\n return {word: calc_word_value(word) for word in words}\n\n\ndef dump_words_to_file_json(name, words=load_words()):\n word_count = len(words)\n print(f'Starting writing to file {name}')\n with open(name, 'w') as f:\n for i in range(0, len(words), 1000):\n f.writelines(json.dumps(calculate_all_scores(words[i:i + 1001]), indent=4))\n clear()\n print(f'{i + 1000}/{word_count} words written to file...')\n\n clear()\n print(f'Done writing {word_count} words to file {name}')\n\n\nif __name__ == \"__main__\":\n print('book', calc_word_value('book'))\n load_words()\n word_score = max_word_and_value(['book', 'machine', 'computer'])\n return_string = (\n f'{word_score.word.capitalize()} was the best word with '\n f'{word_score.score} points'\n )\n print(return_string)\n word_scores = json.dumps(\n calculate_all_scores(['book', 'machine', 'computer', 'imperative']),\n indent=4,\n )\n print(word_scores)\n\n filename = 'dictionary_json.txt'\n dump_words_to_file_json(filename)\n","sub_path":"01/wordvalue.py","file_name":"wordvalue.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"604853642","text":"# https://stackoverflow.com/questions/20546182/how-to-perform-coordinates-affine-transformation-using-python-part-2\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport readOpenPoseJson\nimport calcTransformationMatrix\nimport util\n\n\n# probleem:\n# foto5 & jochen_foto4 => LEGS geeft vrij defitge transformatie, maar benen zijn wel gedraaid => rotatie/hoek zoeken\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 BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\ndef evaluateError(max_error, sum_error, transformation_matrix):\n # Zeker fout, geen match\n if (max_error >= 80 or sum_error >= 140):\n return bcolors.FAIL + \"no_match\" + bcolors.ENDC + \" max_error: \" + str(max_error) + \" sum: \" + str(sum_error)\n # Zeker juist, wel een match\n elif (max_error <= 75 or sum_error <= 110):\n rotation_1 = np.abs(np.math.atan2(-transformation_matrix[0][1], transformation_matrix[0][0]) * 57.3)\n rotation_2 = np.abs(np.math.atan2(transformation_matrix[1][0], transformation_matrix[1][1]) * 57.3)\n if (max([rotation_1, rotation_2]) > 30):\n return bcolors.WARNING + \"match, but rotation to high: \" + bcolors.ENDC + str(rotation_1) + \" \" + str(\n rotation_2) + \" max_error: \" + str(max_error) + \" sum: \" + str(sum_error)\n else:\n return bcolors.OKGREEN + \"match! \" + bcolors.ENDC + str(rotation_1) + \" \" + str(\n rotation_2) + \" max_error: \" + str(max_error) + \" sum: \" + str(sum_error)\n else:\n return \"no_conclusion\" + \" max_error: \" + str(max_error) + \" sum: \" + str(sum_error)\n\n\ndef evaluateError_face(max_error, sum_error, transformation_matrix):\n # Zeker fout, geen match\n if (max_error >= 80 or sum_error >= 180):\n return bcolors.FAIL + \"no_match max_error: \" + bcolors.ENDC + str(max_error) + \" sum: \" + str(sum_error)\n # Zeker juist, wel een match\n elif (max_error <= 50 or sum_error <= 100):\n rotation_1 = np.abs(np.math.atan2(-transformation_matrix[0][1], transformation_matrix[0][0]) * 57.3)\n rotation_2 = np.abs(np.math.atan2(transformation_matrix[1][0], transformation_matrix[1][1]) * 57.3)\n if (max([rotation_1, rotation_2]) > 65):\n return bcolors.WARNING + \"match, but rotation to high: \" + bcolors.ENDC + str(rotation_1) + \" \" + str(\n rotation_2) + \" max_error: \" + str(max_error) + \" sum: \" + str(sum_error)\n else:\n return bcolors.OKGREEN + \"match! \" + bcolors.ENDC + str(rotation_1) + \" \" + str(\n rotation_2) + \" max_error: \" + str(max_error) + \" sum: \" + str(sum_error)\n else:\n return \"no_conclusion\" + \" max_error: \" + str(max_error) + \" sum: \" + str(sum_error)\n\n\ndef evaluateMSE(input, model_transformation):\n # https://stackoverflow.com/questions/16774849/mean-squared-error-in-numpy\n # The effect of each error on RMSD is proportional to the size of the squared error thus larger errors have a disproportionately large effect on RMSD.\n # Consequently, RMSD is sensitive to outliers.[2][3]\n\n #laatste 0 kolom verwijderen\n input = input[:, :-1]\n model_transformation = model_transformation[:, :-1]\n #print(input - model_transformation)\n #rint(((input - model_transformation) ** 2))\n print(((input - model_transformation) ** 2).mean(axis=1))\n #print()\n mse = (((input - model_transformation) ** 2).mean(axis=1)) **(1/2)\n mse_max = max(mse)\n\n if mse_max > 350:\n return \"no match mse_max: \" + str(mse_max) + \" mse: \" + str(mse)\n else:\n return \"match mse_max: \" + str(mse_max) + \" mse: \" + str(mse)\n\n\nmodelFoto = \"foto1\" # \"foto3\"\ninputFoto = \"jochen_foto4\" # \"foto1\"\n\n# plot vars\nmarkersize = 3\n\nim_model = plt.imread('Pictures/' + modelFoto + '.jpg')\n# print(\"res: \", im_model.shape[0])\n# portrait foto, gsm jochen\nresolutieX_model = im_model.shape[1] # 1440\nresolutieY_model = im_model.shape[0] # 1920\n\nim_input = plt.imread('Pictures/' + inputFoto + '.jpg')\n# rendered foto\nresolutieX = im_input.shape[1] # 1440 #1280\nresolutieY = im_input.shape[0] # 1920 #720\n\n# 2D array. Elke entry is een coordinatenkoppel(joint-point) in 3D , z-coordinaat wordt nul gekozen want we werken in 2D\n# Bevat 18 coordinatenkoppels want openpose returnt 18 joint-points\nprimary = readOpenPoseJson.readJsonFile('json_data/' + modelFoto + '.json')\nsecondary = readOpenPoseJson.readJsonFile('json_data/' + inputFoto + '.json')\n\n# enkel subarrays\n# NEK WORDT MOMENTEEL NIET GEBRUIKT, geeft minder nauwkeurige resultaten ??\nprint(\"ts-est\", primary[0][:])\nprimary_torso = primary[2:8]\nsecondary_torso = secondary[2:8]\n\nprimary_legs = primary[8:14]\nsecondary_legs = secondary[8:14]\n\nprimary_face = np.vstack([primary[0], primary[14:18]])\nsecondary_face = np.vstack([secondary[0], secondary[14:18]])\n\n#(modelTransform_torso, A_torso) = calcTransformationMatrix.calcTransformationMatrix(primary_torso, secondary_torso)\n#(modelTransform_legs, A_legs) = calcTransformationMatrix.calcTransformationMatrix(primary_legs, secondary_legs)\n#(modelTransform_face, A_face) = calcTransformationMatrix.calcTransformationMatrix(primary_face, secondary_face)\n\n#input |-> model\n(modelTransform_torso, A_torso) = calcTransformationMatrix.calcTransformationMatrix(secondary_torso,primary_torso)\n(modelTransform_legs, A_legs) = calcTransformationMatrix.calcTransformationMatrix(secondary_legs, primary_legs)\n(modelTransform_face, A_face) = calcTransformationMatrix.calcTransformationMatrix(secondary_face, primary_face)\n\n# print(\"--MSE torso: \", (((secondary_torso - modelTransform_torso) ** 2).mean(axis=1)) ** 1 / 2)\n# print(\"-MSE legs: \", (((secondary_legs - modelTransform_legs) ** 2).mean(axis=1)) ** 1 / 2)\n# print(\"--MSE torso: \", ((secondary_torso - modelTransform_torso) ** 2).mean(axis=None))\n# print(\"-MSE legs: \", ((secondary_legs - modelTransform_legs) ** 2).mean(axis=None))\n# mse_torso_sum = ((secondary_torso - modelTransform_torso) ** 2).mean(axis=None)\n# psnr_torso = np.log10([19940**2, mse_torso_sum])\n# print(\"PSNR: \" , psnr_torso)\n\nprint(\"A- transformatie matrix: FACE\")\nprint(A_face)\n# print(\"a: \" , A_legs[0][0])\n# print(\"a: \" , A_legs[0][1])\n# print(\"Input:\")\n# print(secondary)\n# print(\"Result- transformatie van model:\")\n# print(modelTransform)\n\n# Gewoon MAX[ xi-x'i en yi-y'i ]\nmaxError_torso = np.abs(primary_torso - modelTransform_torso)\nprint(\"Max error torso:\", maxError_torso.max())\n\nmaxError_legs = np.abs(primary_legs - modelTransform_legs)\nprint(\"Max error legs:\", maxError_legs.max())\n\nmaxError_face = np.abs(primary_face - modelTransform_face)\nprint(\"Max error face:\", maxError_face.max())\n# print(maxError)\n\n# np.sqrt(np.sum((maxError[:,0] - maxError[:,1]) ** 2))\neuclDis_torso = ((maxError_torso[:, 0]) ** 2 + maxError_torso[:, 1] ** 2) ** 0.5\neuclDisNorm_torso = ((maxError_torso[:, 0] / resolutieX_model) ** 2 + (maxError_torso[:, 1] / resolutieY_model) ** 2) ** 0.5\nprint(\"@@@@@Eucl dis TORSO: \", euclDis_torso)\n\neuclDis_legs = ((maxError_legs[:, 0]) ** 2 + maxError_legs[:, 1] ** 2) ** 0.5\neuclDisNorm_legs = ((maxError_legs[:, 0] / resolutieX_model) ** 2 + (maxError_legs[:, 1] / resolutieY_model) ** 2) ** 0.5\nprint(\"@@@@@Eucl dis LEGS: \" , euclDis_legs)\n\n\neuclDis_face = ((maxError_face[:, 0]) ** 2 + maxError_face[:, 1] ** 2) ** 0.5\neuclDisNorm_face = ((maxError_face[:, 0] / resolutieX_model) ** 2 + (maxError_face[:, 1] / resolutieY_model) ** 2) ** 0.5\n\nmax_euclDis_norm_torso = max(euclDis_torso)\nsum_max_euclDis_norm_torso = np.sum(euclDis_torso)\nprint(\"\\n----- Euclidean dis TORSO -----\")\nprint(\"euclid dis ; \", euclDisNorm_torso)\nprint(\"Max euclidean dis : \", max_euclDis_norm_torso)\nprint(\"Sum euclidean dis: \", sum_max_euclDis_norm_torso)\n\n\nmax_euclDis_norm_legs = max(euclDis_legs)\nsum_max_euclDis_norm_legs = np.sum(euclDis_legs)\nprint(\"\\n----- Euclidean dis LEGS -----\")\nprint(\"euclid dis ; \", euclDisNorm_legs)\nprint(\"Max euclidean dis: \", max_euclDis_norm_legs)\nprint(\"Sum euclidean dis: \", sum_max_euclDis_norm_legs)\n\nmax_euclDis_norm_face = max(euclDis_face)\nsum_max_euclDis_norm_face = np.sum(euclDis_face)\nprint(\"\\n----- Euclidean dis FACE -----\")\nprint(\"euclid dis ; \", euclDisNorm_face)\nprint(\"Max euclidean dis : \", max_euclDis_norm_face)\nprint(\"Sum euclidean dis: \", sum_max_euclDis_norm_face)\n\n# plot img\n\nf, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, sharey=True, figsize=(14, 6))\nimplot = ax1.imshow(im_model)\nax1.set_title(modelFoto + '(model)')\nax1.plot(*zip(*primary_torso), marker='o', color='r', ls='', label='model', ms=markersize) # ms = markersize\nax1.plot(*zip(*primary_legs), marker='o', color='c', ls='', label='model', ms=markersize) # ms = markersize\nax1.plot(*zip(*primary_face), marker='o', color='orange', ls='', label='model', ms=markersize) # ms = markersize\nred_patch = mpatches.Patch(color='red', label='model')\nax1.legend(handles=[red_patch])\n\nax2.set_title(inputFoto)\nax2.imshow(im_input)\nax2.plot(*zip(*secondary_torso), marker='o', color='b', ls='', ms=markersize)\nax2.plot(*zip(*secondary_legs), marker='o', color='b', ls='', ms=markersize)\nax2.plot(*zip(*secondary_face), marker='o', color='b', ls='', ms=markersize)\nax2.legend(handles=[mpatches.Patch(color='blue', label='input')])\n\nax3.set_title('Transformation of input')\nax3.imshow(im_model)\nax3.plot(*zip(*modelTransform_torso), marker='o', color='y', ls='', ms=markersize)\nax3.plot(*zip(*modelTransform_legs), marker='o', color='y', ls='', ms=markersize)\nax3.plot(*zip(*modelTransform_face), marker='o', color='y', ls='', ms=markersize)\nax3.legend(handles=[mpatches.Patch(color='yellow', label='Transformation of model')])\n\nax4.set_title('Transformatie + model')\nax4.imshow(im_model)\nax4.plot(*zip(*primary_torso), marker='o', color='b', ls='', ms=markersize)\nax4.plot(*zip(*primary_legs), marker='o', color='b', ls='', ms=markersize)\nax4.plot(*zip(*primary_face), marker='o', color='b', ls='', ms=markersize)\nax4.plot(*zip(*modelTransform_torso), marker='o', color='y', ls='', ms=markersize)\nax4.plot(*zip(*modelTransform_legs), marker='o', color='y', ls='', ms=markersize)\nax4.plot(*zip(*modelTransform_face), marker='o', color='y', ls='', ms=markersize)\n\nprint(bcolors.HEADER + \"Evaluation TORSO: \" + bcolors.ENDC,\n evaluateError(max_euclDis_norm_torso, sum_max_euclDis_norm_torso, A_torso))\nprint(bcolors.HEADER + \"Evaluation LEGS: \" + bcolors.ENDC,\n evaluateError(max_euclDis_norm_legs, sum_max_euclDis_norm_legs, A_legs))\nprint(bcolors.HEADER + \"Evaluation FACE: \" + bcolors.ENDC,\n evaluateError_face(max_euclDis_norm_face, sum_max_euclDis_norm_face, A_face))\n\nprint(\"\")\n\n#print(bcolors.OKBLUE + \"Evaluation MSE TORSO: \" + bcolors.ENDC, evaluateMSE(secondary_torso, modelTransform_torso))\n#print(bcolors.OKBLUE + \"Evaluation MSE LEGS: \" + bcolors.ENDC, evaluateMSE(secondary_legs, modelTransform_legs))\nplt.show()\n","sub_path":"shit/input_to_model.py","file_name":"input_to_model.py","file_ext":"py","file_size_in_byte":10915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"384963137","text":"import sqlite3\nconn = sqlite3.connect(\"database.db\")\n\nc = conn.cursor()\n# c.execute(\"CREATE TABLE friends (name TEXT ,age INTEGER)\")\n\n# people =[\n# (\"a\",1),\n# (\"b\",2),\n# (\"c\",32),\n# (\"d\",4),]\n# qur = \"INSERT INTO friends VALUES (?,?)\"\n# c.executemany(qur,people)\n# c.execute(\"select * from friends\")\n# print(c.fetchall())\n\nconn.commit()\nconn.close()\n\n","sub_path":"python_sql/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"219124562","text":"from __future__ import division\nimport numpy as np\nfrom numpy import genfromtxt\nimport matplotlib.pyplot as plt\n\n# Note this script runs independent of the app.\n\n'''\n' Extract the features from an example\n'''\ndef extract_features_etc(example):\n arr = np.zeros(9)\n id_val = arr[0]\n real_class = example[len(example)-1]\n for i in range(1,10):\n arr[i-1] = example[i]\n return arr, id_val, real_class \n\n'''\n' For testing\n'''\ndef signs(a, b):\n predicted = 1.0\n if(a < 0):\n predicted = -1.0\n if(predicted == b):\n #print('returning: '+str(predicted))\n return 1\n return 0\n\n'''\n' Train on a set of pre-classified crimes for best parameter values.\n'''\ndef train_classifier(train, vs, test):\n train_set = train \n valid_set = vs\n test_set = test\n num_steps = 100\n max_epochs = 50\n block = 0\n step_a_param = 0.02\n step_b_param = 50\n lda = 1\n ### Algorithm ###\n lda_arr = [1, 10**-1, 10**-2]\n #accuracies = np.zeros((1,500))\n acc_num = 0\n\n final_a = None\n final_b = None\n for row in range(0,2):\n a = np.zeros(9)\n b = 0\n lda = lda_arr[row]\n acc_num = 0\n print(lda)\n for r in range(max_epochs): # epochs\n np.random.shuffle(train_set)\n sub_valid_set = train_set[0:50]\n sub_train_set = train_set[50:]\n for k in range(100): # steps\n w = np.random.randint(433)\n x, id_val, yi = extract_features_etc(sub_train_set[w]) \n gamma = (a).dot(x) + b\n step_len = step_a_param / (r+step_b_param)\n ak = np.zeros(9)\n bk = 0\n val = np.zeros(9)\n if (yi * (a.dot(x)+b)) >= 1:\n val1 = lda*a\n val2 = 0\n else:\n val1 = lda*a - yi*x\n val2 = -yi\n ak = a - step_len*val1\n bk = b - step_len*val2\n a = ak.copy()\n b = bk\n block += 1\n final_a = a.copy()\n final_b = b\n return final_a, final_b # the winners!\n\n# RUN\n# train_classifier('train.txt', 'valid.txt', 'test.txt')\n\n\n\n","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"569374864","text":"import logging\nfrom rq import Queue\nfrom redis import Redis\n\nfrom aiohttp import web\nfrom screenshoter import get_screenshot\n\nredis_conn = Redis()\nqueue = Queue(connection=redis_conn)\n\n\nFORMAT = '%(asctime)s - %(levelname)s - %(message)s'\nlogging.basicConfig(\n format=FORMAT,\n level=10,\n filename='logs/server/server.log',\n filemode='a',\n)\n\n\nasync def screen_server(request):\n params = request.rel_url.query\n url = params.get('url')\n id = params.get('id')\n token = params.get('token')\n request_url = params.get('host')\n\n if url is None or id is None or token is None or request_url is None:\n return web.HTTPBadRequest(text='Нужные параметры отсутствуют')\n\n queue.enqueue(\n get_screenshot,\n args=(id, url, token, request_url),\n result_ttl=0,\n job_timeout=30\n )\n\n return web.HTTPOk(text='Ваш запрос принят')\n\n\napp = web.Application()\napp.router.add_route('GET', '/', screen_server)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"626613830","text":"import re\n\n\n# 9. Write a Python program that matches a string that has an 'a' followed by anything, ending in 'b'\n\ndef match_string9(string):\n pattern = '^a.*b$'\n if re.search(pattern, string):\n x = re.findall(pattern, string)\n y = re.search(pattern, string)\n return x, y\n else:\n return 'no match found! ex9'\n\n\nprint(match_string9('hi'))\nprint(match_string9('a'))\nprint(match_string9('ab'))\nprint(match_string9('abc'))\nprint(match_string9('aab'))\nprint(match_string9('aaakjdhfskjsdb'))\nprint(match_string9('himynameisb'))\n\n\n#\n#\n# 10. Write a Python program that matches a word at the beginning of a string.\n\n\ndef word_match10(string):\n pattern = '\\A[^\\s]*'\n if re.search(pattern, string):\n x = re.findall(pattern, string)\n y = re.search(pattern, string)\n return x, y\n else:\n return 'no match found! ex10'\n\n\nprint(word_match10('hi my name is babak'))\nprint(word_match10('himy name is babak'))\nprint(word_match10('himynameisbabak'))\n\n#\n#\n# 11. Write a Python program that matches a word at end of string, with optional punctuation.\n\n\ndef word_match11(string):\n pattern = '\\w+\\S*$'\n if re.search(pattern, string):\n x = re.findall(pattern, string)\n y = re.search(pattern, string)\n return x, y\n else:\n return 'no match found! ex11'\n\n\nprint(word_match11('hi my name is babak'))\nprint(word_match11('hi my name is bakak.'))\nprint(word_match11('hi my name is nobody else;'))\n","sub_path":"Internet/www.w3resource.com/Regular Expression/(19 May,2019)--[9:].py","file_name":"(19 May,2019)--[9:].py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"278032403","text":"# -*- coding: utf-8 -*-\n#\nfrom .helpers import _s3, _s21\n\nfrom ..helpers import untangle\n\n\nclass SevenPoint(object):\n def __init__(self):\n self.name = 'seven-point'\n self.degree = 3\n data = [\n (0.45, _s3()),\n (0.05, _s21(0.0)),\n (2.0/15.0, _s21(0.5)),\n ]\n self.bary, self.weights = untangle(data)\n self.points = self.bary[:, 1:]\n return\n","sub_path":"quadpy/triangle/seven_point.py","file_name":"seven_point.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"614271164","text":"from odoo import models, fields, api,_\nfrom datetime import date\n\n\nclass PickingTemplateWizard(models.TransientModel):\n _name='picking.template.wizard'\n\n pickin_temp_ids=fields.Many2many('stock.picking.template', string='Picking Templates')\n\n\n # to assign product to selected picking template from wizard\n @api.multi\n def assign_product(self):\n product_id=self._context.get('active_id')\n for temp in self.pickin_temp_ids:\n # filter templates on wizard which are selected to assign product\n if temp:\n # to check whether product already exist on picking template line\n for tmp in temp:\n exist_temp_line_id=self.env['stock.picking.template'].search([('temp_lines.product_id.id','=', product_id),('id','=',tmp.id)])\n if not exist_temp_line_id:\n vals={\n 'pick_temp_id':tmp.id,\n 'product_id':product_id,\n 'suggested_qty':0.0\n }\n temp_line_id=self.env['stock.picking.template.line'].create(vals)\n\n# class PickingTemplate(models.TransientModel):\n# _name='picking.template'\n\n# name=fields.Char(string='Picking Template')\n# picking_type=fields.Many2one('stock.picking.type', string='Picking Type')\n# pick_date=fields.Date(string='Picking Date')\n# wizard_id = fields.Many2one('picking.template.wizard')\n# pick_temp_id=fields.Many2one('stock.picking.template')\n# assign=fields.Boolean(string='Assign to Product')\n# week_day=fields.Char(string='Day of Week')\n# categ=fields.Char(string='Category')","sub_path":"stock_shop_template/wizard/picking_template_wizard.py","file_name":"picking_template_wizard.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"380874072","text":"from base.base_driver import init_driver\nfrom page.contact_list_page import ContactListPage\nfrom page.new_contact_page import NewContactPage\nfrom page.saved_page import SavedPage\n\n\nclass TestContact:\n\n def setup(self):\n self.driver = init_driver()\n\n self.contact_list_page = ContactListPage(self.driver)\n self.new_contact_page = NewContactPage(self.driver)\n self.saved_page = SavedPage(self.driver)\n\n def teardown(self):\n self.driver.quit()\n\n # name, phone\n # xiaoming, 188\n # xiaohong, 177\n # xiaoqiang, 166\n def test_new_contact(self):\n name = \"xiaoming\"\n self.contact_list_page.click_new_contact()\n self.new_contact_page.click_local_save()\n self.new_contact_page.input_name(name)\n self.new_contact_page.input_phone(\"1888\")\n self.new_contact_page.click_back()\n\n assert name == self.saved_page.get_large_title_text()\n","sub_path":"scripts/test_contact.py","file_name":"test_contact.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"548644364","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n#import lines_a\n\n#import star_1608\nimport sys\nfrom pyke import knowledge_engine,krb_traceback\nimport extras\nimport numpy as np\ng_engine = knowledge_engine.engine(__file__)\ng_engine.reset()\ng_engine.activate('rules_b','rules_f')\n\n#Lineas = lines_a.Todo_lineas\n#Relaciones = lines_a.Todo_Interacciones\n#Intersecciones = lines_a.Todo_Intersecciones\n\n\n\n\ndef lineas_level(Lineas,Intersecciones,Set,Tolerance,Tol_inter):\n\n g_engine.reset()\n g_engine.activate('rules_b','rules_f')\n g_engine.assert_('base','tolerance',Tolerance)\n Lineas_rule = []\n for renglon in Lineas:\n for elem in renglon.values:\n Lineas_rule.append(elem)\n\n Intersection = []\n for renglon in Intersecciones:\n for elem in renglon.values:\n Intersection.append(elem)\n\n #g_engine.assert_('base','inter_tol',Tol_inter)\n\n for elem in Lineas_rule:\n g_engine.assert_('base','line',elem)\n\n for elem in Lineas_rule:\n g_engine.assert_('base','p_line',elem)\n\n for elem in Intersection:\n g_engine.assert_('base','relation',elem)\n\n Nuevas_lineas = []\n with g_engine.prove_goal('rules_b.n_line($id, $pix, $piy, $pfx, $pfy, $len, $slope)') as gen:\n for vars, no_plan in gen:\n #print(vars)\n #C = [vars['id'],vars['len'],vars['slope'],'set_a']\n C = [vars['len'],vars['slope'],Set]\n Nuevas_lineas.append(C)\n\n Objects = []\n with g_engine.prove_goal('rules_b.something($ids)') as gen:\n for v_p, no_plan in gen:\n Objects.append(set(v_p['ids']))\n\n Objects = extras.agrupar_set(Objects)\n\n #g_engine.get_kb('base').dump_specific_facts()\n\n Lineas_solas = []\n for elem in Objects:\n if len(elem) == 1:\n Lineas_solas.append(elem)\n\n return Nuevas_lineas\n\ndef lineas_level2(lines,Set,Tolerance,Tol_inter):\n\n g_engine.reset()\n g_engine.activate('rules_b','rules_f')\n g_engine.assert_('base','tolerance',Tolerance)\n\n g_engine.assert_('base','inter_tol',Tol_inter)\n\n Lines_level2 = []\n for renglon in lines.values:\n Lines_level2.append(renglon)\n #print(renglon)\n\n for elem in Lines_level2:\n g_engine.assert_('base','line',elem)\n\n #g_engine.get_kb('base').dump_specific_facts()\n\n Nuevas_lineas = []\n with g_engine.prove_goal('rules_b.line_2($id,$pix,$piy,$pfx,$pfy,$len,$slope,$type)') as gen:\n for vars, no_plan in gen:\n #print(vars)\n C = [vars['len'],vars['slope'],vars['type'],Set]\n #C = [vars['id'],vars['len'],vars['slope'],vars['type'],Set]\n Nuevas_lineas.append(C)\n\n return Nuevas_lineas\n\ndef punteadas(Separacion):\n\n g_engine.assert_('base','separation',Separacion)\n\n Punteada = []\n with g_engine.prove_goal('rules_b.punteada_b($id1,$id2)') as gen:\n for vars, no_plan in gen:\n C = {vars['id1'],vars['id2']}\n if C not in Punteada:\n Punteada.append(C)\n #print(Punteada)\n Punteada = extras.agrupar_set(Punteada)\n\n #g_engine.get_kb('base').dump_specific_facts()\n\n return Punteada\n\ndef Objects(Lineas,Intersecciones,Tolerance,Tol_inter):\n\n g_engine.reset()\n g_engine.activate('rules_b','rules_f')\n g_engine.assert_('base','tolerance',Tolerance)\n\n g_engine.assert_('base','inter_tol',Tol_inter)\n\n Lines = []\n for renglon in Lineas.values:\n Lines.append(renglon)\n\n for elem in Lines:\n g_engine.assert_('base','line_2',elem)\n\n Intersection = []\n for renglon in Intersecciones.values:\n Intersection.append(renglon)\n\n for elem in Intersection:\n g_engine.assert_('base','relation',elem)\n\n g_engine.get_kb('base').dump_specific_facts()\n\n Objects = []\n with g_engine.prove_goal('rules_b.something2($ids)') as gen:\n for v_p, no_plan in gen:\n Objects.append(set(v_p['ids']))\n\n Figure = []\n with g_engine.prove_goal('rules_b.figure($ids)') as gen:\n for v_p, no_plan in gen:\n C = set(v_p['ids'])\n if C not in Figure:\n Figure.append(C)\n\n Figure_i = []\n with g_engine.prove_goal('rules_b.figure_i($ids)') as gen:\n for v_p, no_plan in gen:\n C = set(v_p['ids'])\n if C not in Figure_i:\n Figure_i.append(C)\n\n Objects = extras.agrupar_set(Objects)\n #Figure = extras.agrupar_set(Figure)\n #Figure_i = extras.agrupar_set(Figure_i)\n\n return Figure, Figure_i,Objects\n\ndef T_C(Lineas,Intersecciones,Tolerance,Tol_inter):\n\n g_engine.reset()\n g_engine.activate('rules_b','rules_f')\n g_engine.assert_('base','tolerance',Tolerance)\n\n g_engine.assert_('base','inter_tol',Tol_inter)\n\n Lines = []\n for renglon in Lineas.values:\n Lines.append(renglon)\n\n for elem in Lines:\n g_engine.assert_('base','line',elem)\n\n Intersection = []\n for renglon in Intersecciones.values:\n Intersection.append(renglon)\n\n for elem in Intersection:\n g_engine.assert_('base','relation',elem)\n\n #g_engine.get_kb('base').dump_specific_facts()\n\n Triangles = []\n Triangles_corner = []\n with g_engine.prove_goal('rules_b.triangle($id1,$id2,$id3,$corner)') as gen:\n for v_tri, no_plan in gen:\n #print(\"Triangulo\")\n #print(v_tri)\n C = {v_tri['id1'],v_tri['id2'],v_tri['id3']}\n if C not in Triangles:\n Triangles.append(C)\n Triangles_corner.append(v_tri)\n\n Triangles_i = []\n Triangles_i_corner = []\n with g_engine.prove_goal('rules_b.triangle_i($id1,$id2,$id3,$corner)') as gen:\n for v_tri, no_plan in gen:\n #print(\"Triangulo\")\n #print(v_tri)\n C = {v_tri['id1'],v_tri['id2'],v_tri['id3']}\n if C not in Triangles_i:\n Triangles_i.append(C)\n Triangles_i_corner.append(v_tri)\n\n Squares = []\n Squares_corner = []\n with g_engine.prove_goal('rules_b.fig4($id1,$id2,$id3,$id4,$corner)') as gen:\n for v_prueba, no_plan in gen:\n C = {v_prueba['id1'],v_prueba['id2'],v_prueba['id3'],v_prueba['id4']}\n if C not in Squares:\n Squares_corner.append(v_prueba)\n Squares.append(C)\n\n Squares_i = []\n Squares_i_corner = []\n with g_engine.prove_goal('rules_b.fig4_i($id1,$id2,$id3,$id4,$corner)') as gen:\n for v_prueba, no_plan in gen:\n C = {v_prueba['id1'],v_prueba['id2'],v_prueba['id3'],v_prueba['id4']}\n if C not in Squares_i:\n Squares_i.append(C)\n Squares_i_corner.append(v_prueba)\n\n Objects = []\n with g_engine.prove_goal('rules_b.something($ids)') as gen:\n for v_p, no_plan in gen:\n Objects.append(set(v_p['ids']))\n\n Objects = extras.agrupar_set(Objects)\n\n# for elem in Squares:\n# if elem in Objects:\n# Objects.remove(elem)\n#\n# for elem in Triangles:\n# if elem in Objects:\n# Objects.remove(elem)\n\n return Triangles_corner,Triangles_i_corner,Squares_corner,Squares_i_corner,Objects\n\ndef quebradas():\n\n Quebrada = []\n with g_engine.prove_goal('rules_b.aline_q($id1,$id2,$id3,$resultado)') as gen:\n for vars, no_plan in gen:\n C = {vars['id1'],vars['id2'],vars['id3']}\n if C not in Quebrada:\n Quebrada.append(C)\n\n Quebrada = extras.agrupar_set(Quebrada)\n return Quebrada\n\n\n\ndef open_objects():\n\n Open_obj = []\n with g_engine.prove_goal('rules_b.open($ids)') as gen:\n for v_p, no_plan in gen:\n Open_obj.append(set(v_p['ids']))\n\n Open_obj = extras.agrupar_set(Open_obj)\n for elem in Open_obj:\n if len(elem) == 1:\n Open_obj.remove(elem)\n\n Open_3 = []\n with g_engine.prove_goal('rules_b.open_3($id1,$id2,$id3)') as gen:\n for v_prueba, no_plan in gen:\n C = {v_prueba['id1'],v_prueba['id2'],v_prueba['id3']}\n if C not in Open_3:\n Open_3.append(C)\n\n return Open_obj,Open_3\n\ndef pos_abs(Obj,Tolerance,size,Set):\n\n g_engine.reset()\n g_engine.activate('rules_b','rules_f')\n g_engine.assert_('base','tolerance',Tolerance)\n\n image_pos(size)\n\n #id = 0\n\n if Obj is not None:\n for elem in Obj:\n if len(elem) != 16:\n C = [elem['open_close']+' '+str(elem['num_lines'])+' '+elem['type'],[elem['cenx'],elem['ceny']]]\n g_engine.assert_('base','object',C)\n if len(elem) == 16:\n C = [elem['open_close']+' '+str(elem['num_sides'])+' '+elem['type'] ,[elem['cenx'],elem['ceny']],elem['area'],elem['per'],elem['sides'],elem['angs'],elem['list_convex'],elem['numconvex']]\n g_engine.assert_('base','object',C)\n #print(C)\n\n\n\n# if Obj is not None:\n# for elem in Obj:\n# name = \"obj\" + str(id) + Set\n# elem.pop(0)\n# elem.insert(0,name)\n# id = id + 1\n# g_engine.assert_('base','object',elem)\n\n #g_engine.get_kb('base').dump_specific_facts()\n\n Relative_position = []\n Inside = []\n with g_engine.prove_goal('rules_b.position($pos,$id1,$id2)') as gen:\n for v_p, no_plan in gen:\n if v_p['pos'] == 'inside':\n Inside.append([v_p['pos'],v_p['id1'],v_p['id2'],Set])\n #Inside.append(v_p)\n else:\n Relative_position.append([v_p['pos'],v_p['id1'],v_p['id2'],Set])\n# with g_engine.prove_goal('rules_b.position($pos,$id1,$id2)') as gen:\n# for v_p, no_plan in gen:\n# C = {v_p['pos'],v_p['id1'],v_p['id2']}\n# if C not in Relative_position:\n# Relative_position.append(C)\n# if len(C & {'inside'}) != 0:\n# Inside.append(C)\n#\n# #print(Relative_position)\n# R_P = Relative_position\n# for elem1 in Inside:\n# for elem2 in Relative_position[:]:\n# if len(elem1 & elem2) == 2:\n# R_P.remove(elem2)\n\n Absolute_position = []\n with g_engine.prove_goal('base.obj_pos_abs($id,$x,$y)') as gen:\n for v_p, no_plan in gen:\n Absolute_position.append([v_p['id'],v_p['x'],v_p['y'],Set])\n\n Aline = []\n #print(\"Alineacion\")\n with g_engine.prove_goal('rules_b.aline($id1,$id2,$id3,$slope)') as gen:\n for v_p, no_plan in gen:\n C = {v_p['id1'],v_p['id2'],v_p['id3'],v_p['slope']}\n if C not in Aline:\n Aline.append(C)\n Aline = extras.agrupar_set_aline(Aline)\n #print(Aline)\n #g_engine.get_kb('base').dump_specific_facts()\n\n return Aline,Relative_position,Absolute_position,Inside\n\ndef corners(lista):\n\n #print(\"Esquinas\")\n Corner = []\n Corner_T = []\n Corners = []\n Final = []\n for elem in lista:\n verificacion = convert_set(combinaciones(list(elem),2))\n Corners = []\n for id1 in elem:\n with g_engine.prove_goal('base.corner($id1,$id2,$ang,$x,$y)',id1=id1) as gen:\n for v_p, no_plan in gen:\n ver = {v_p['id1'],v_p['id2']}\n C = {v_p['id1'],v_p['id2'],v_p['ang'],v_p['x'],v_p['y']}\n if C not in Corners and ver in verificacion:\n Corners.append(C)\n Corner.append(v_p)\n Corner_T.append([elem,Corner])\n Corner = []\n\n for elem in Corner_T:\n if ((len(elem[0]) != 1) & (len(elem[1]) == 0)):\n print('No relation')\n else:\n Final.append(elem)\n\n return Final\n\ndef corners_I(lista):\n\n #print(\"Esquinas_I\")\n Corner = []\n Corner_T = []\n Corners = []\n Final = []\n for elem in lista:\n verificacion = convert_set(combinaciones(list(elem),2))\n Corners = []\n for id1 in elem:\n with g_engine.prove_goal('base.i_corner($id1,$id2,$ang,$x,$y)',id1=id1) as gen:\n for v_p, no_plan in gen:\n ver = {v_p['id1'],v_p['id2']}\n C = {v_p['id1'],v_p['id2'],v_p['ang'],v_p['x'],v_p['y']}\n if C not in Corners and ver in verificacion:\n Corners.append(C)\n Corner.append(v_p)\n Corner_T.append([elem,Corner])\n Corner = []\n\n for elem in Corner_T:\n if ((len(elem[0]) != 1) & (len(elem[1]) == 0)):\n print('No relation')\n else:\n Final.append(elem)\n\n return Final\n\ndef format1(lista):\n\n Dict = {}\n i = 1\n ids = 'id' + str(i)\n\n Corner = []\n for id in lista[0]:\n Dict[ids] = id\n i = i + 1\n ids = 'id' + str(i)\n print(id)\n print('----------------')\n for corner in lista[1]:\n C = [corner['id1'],corner['id2'],corner['x'],corner['y']]\n Corner.append(C)\n Dict['corner'] = tuple(Corner)\n\n return Dict\n\ndef format(lista):\n Format = []\n for elem in lista:\n Format.append(format1(elem))\n return Format\n\ndef Otras(lista):\n\n Tolerancia = (5,10)\n g_engine.reset()\n g_engine.activate('rules_b','rules_f')\n g_engine.assert_('base','tolerance',Tolerancia)\n\n for elem in lista:\n #print(elem[0])\n #print('---------------------------------------')\n for elem1 in elem[1]:\n C = (elem1['id1'],elem1['id2'],elem1['ang'],elem1['x'],elem1['y'])\n g_engine.assert_('base','corner',C)\n\ndef Open_Close(lista):\n Relation = []\n Open = []\n Close = []\n Close1 = []\n for elem in lista:\n F = []\n for id in elem[0]:\n #print('-------------------------')\n #print(id)\n C = []\n for dict in elem[1]:\n E = id in dict.values()\n #print(E)\n C.append(E)\n\n F.append(C.count(True))\n\n###############################################################################\n #Original --> if F.count(2) == len(F):\n if F.count(2) == len(F) or F.count(4) == len(F):\n Close1.append(elem)\n else:\n Open.append(elem)\n###############################################################################\n R = []\n Final = []\n for elem in Close1:\n R = []\n for i in range (len(elem[1]) - 1):\n #print((len(elem[1]))-1)\n #print('--------------------------')\n for j in range (i+1,len(elem[1])):\n A = elem[1][i]\n #print(A)\n B = elem[1][j]\n #print(B)\n with g_engine.prove_goal('rules_b.similar($id1,$id2,$id3,$x1,$x2,$result)',id1=A['id1'],id2=B['id2'],x1=A['x'],x2=B['x']) as gen:\n for v_p, no_plan in gen:\n #print(v_p['result'])\n R.append(v_p['result'])\n Final.append((elem,R))\n #print(Final)\n\n for elem in Final:\n if True in elem[1] or len(elem[1]) == 0:\n Open.append(elem[0])\n else:\n Close.append(elem[0])\n\n return Open,Close\n\ndef R_I(lista,OpenClose):\n\n print('Forma regularidad convexidad')\n Tolerancia = (5,10)\n g_engine.reset()\n g_engine.activate('rules_b','rules_f')\n g_engine.assert_('base','tolerance',Tolerancia)\n\n for elem in lista:\n g_engine.assert_('base','object',elem)\n\n g_engine.get_kb('base').dump_specific_facts()\n\n Objects = []\n with g_engine.prove_goal('rules_b.type($id,($cenx,$ceny),$area,$per,$sides,$angs,$list_convex,$numconvex,$type,$regular,$convex,$num_sides,$open_close,$size)') as gen:\n for v_p, no_plan in gen:\n #print(v_p['id'],v_p['num_sides'],v_p['type'],v_p['regular'],v_p['convex'])\n v_p['num_lines'] = v_p['num_sides']\n v_p['num_inter'] = v_p['num_sides']\n Objects.append(v_p)\n\n with g_engine.prove_goal('rules_b.type($id,($cenx,$ceny),$inter,$num_inter,$end_points,$num_lines,$type,$open_close)') as gen:\n for v_p, no_plan in gen:\n Objects.append(v_p)\n\n return Objects\n\n\n\ndef check(a, b, tol = 10):\n if a > b - tol and a < b + tol:\n return True\n else:\n return False\n\ndef image_pos(size):\n x,y = size\n# g_engine.assert_('base','x',(0,x*1/3,'rigth'))\n# g_engine.assert_('base','x',(x*1/3,x*2/3,'centrerx'))\n# g_engine.assert_('base','x',(x*2/3,x,'left'))\n# g_engine.assert_('base','y',(0,y*1/3,'up'))\n# g_engine.assert_('base','y',(y*1/3,y*2/3,'centery'))\n# g_engine.assert_('base','y',(y*2/3,y,'down'))\n g_engine.assert_('base','x',(0,x*1/3,'left'))\n g_engine.assert_('base','x',(x*1/3,x*2/3,'centrerx'))\n g_engine.assert_('base','x',(x*2/3,x,'right'))\n g_engine.assert_('base','y',(0,y*1/3,'up'))\n g_engine.assert_('base','y',(y*1/3,y*2/3,'centery'))\n g_engine.assert_('base','y',(y*2/3,y,'down'))\n\ndef inserta(x, lst, i):\n \"\"\"Devuelve una nueva lista resultado de insertar\n x dentro de lst en la posición i.\n \"\"\"\n return lst[:i] + [x] + lst[i:]\n\ndef inserta_multiple(x, lst):\n \"\"\"Devuelve una lista con el resultado de\n insertar x en todas las posiciones de lst.\n \"\"\"\n return [inserta(x, lst, i) for i in range(len(lst) + 1)]\n\ndef permuta(c):\n \"\"\"Calcula y devuelve una lista con todas las\n permutaciones posibles que se pueden hacer\n con los elementos contenidos en c.\n \"\"\"\n if len(c) == 0:\n return [[]]\n return sum([inserta_multiple(c[0], s)\n for s in permuta(c[1:])],\n [])\n\ndef potencia(c):\n \"\"\"Calcula y devuelve el conjunto potencia del\n conjunto c.\n \"\"\"\n if len(c) == 0:\n return [[]]\n r = potencia(c[:-1])\n return r + [s + [c[-1]] for s in r]\n\ndef imprime_ordenado(c):\n \"\"\"Imprime en la salida estándar todos los\n subconjuntos del conjunto c (una lista de\n listas) ordenados primero por tamaño y\n luego lexicográficamente. Cada subconjunto\n se imprime en su propia línea. Los\n elementos de los subconjuntos deben ser\n comparables entre sí, de otra forma puede\n ocurrir un TypeError.\n \"\"\"\n for e in sorted(c, key=lambda s: (len(s), s)):\n print(e)\n\ndef combinaciones(c, n):\n \"\"\"Calcula y devuelve una lista con todas las\n combinaciones posibles que se pueden hacer\n con los elementos contenidos en c tomando n\n elementos a la vez.\n \"\"\"\n return [s for s in potencia(c) if len(s) == n]\n\ndef convert_set(lista):\n A = []\n for elem in lista:\n A.append(set(elem))\n return A\n####################\ndef eliminar_inter(Open,Close,Conected):\n New_open = []\n if len(Close) != 0:\n New_conected = Conected[:] # Nueva linea New_conected = []\n for elem_1 in Conected:\n for elem_2 in Close:\n if len(elem_1[0] & elem_2[0]) != 0: #Nueva linea\n if elem_1 in New_conected: #Nueva linea \n New_conected.remove(elem_1) #Nueva linea\n #New_conected.append(elem_1)\n\n for elem_3 in Open:\n for elem_4 in New_conected:\n if len(elem_3[0] & elem_4[0]) != 0: #Nueva linea\n if elem_3 in New_conected: #Nueva linea \n New_conected.remove(elem_3) #Nueva line\n if len(elem_3[0] & elem_4[0]) == len(elem_4[0]):\n New_open.append(elem_4)\n\n for elem_1 in Open:\n for elem_2 in Close:\n if len(elem_1[0] & elem_2[0]) != 0: #Nueva linea\n if elem_1 in New_conected: #Nueva linea \n New_conected.remove(elem_1) #Nueva linea\n #New_open.append(elem_1)\n\n New_open.extend(New_conected)\n\n else:\n# Exist = []\n# for elem_3 in Open:\n# for elem_4 in Conected:\n# if len(elem_3[0] & elem_4[0]) == 0:\n# New_open.append(elem_4)\n New_conected = quitar_inter(Conected)\n New_open.extend(New_conected)\n\n return New_open\n\n#D = [[{'0-5', '0-16', '0-15'}, [{'id1': '0-5', 'id2': '0-15', 'ang': 107.22913429868744, 'x': 243.6934730056406, 'y': 72.21182759772803}, {'id1': '0-15', 'id2': '0-16', 'ang': 101.40772416054487, 'x': 121.02184152274532, 'y': 156.9849074918027}]], [{'1-43', '1-40', '1-41', '1-3'}, [{'id1': '1-40', 'id2': '1-41', 'ang': 62.47826189178451, 'x': 334.3356541670583, 'y': 213.28054676649646}, {'id1': '1-3', 'id2': '1-43', 'ang': 120.12533135595294, 'x': 94.69501418914243, 'y': 195.76722884894906}, {'id1': '1-41', 'id2': '1-43', 'ang': 127.03689134264474, 'x': 265.8542303593578, 'y': 156.03383938086336}]]]\n\ndef quitar_inter(lista):\n Final = []\n for elem in lista:\n conj = set()\n R = []\n #print(elem)\n #conj = set((elem[1][0]['id1'],elem[1][0]['id2']))\n #R.append(elem[1][0])\n #print('hola')\n #print(conj)\n for inter in elem[1]:\n #C = (set((inter['id1'],inter['id2']))&elem[0])\n C = (set((inter['id1'],inter['id2']))&elem[0]) \n if len(C & conj) <= 1:\n #print(inter)\n R.append(inter)\n #conj = C | conj #nueva\n Final.append([elem[0],R])\n return Final\n####################\n","sub_path":"python/driver_rules.py","file_name":"driver_rules.py","file_ext":"py","file_size_in_byte":21246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"25996931","text":"#!/usr/bin/env python\n\n\"\"\"\n\nThis is a rewrite of a past project to report potential ARP poisoning.\nThe original product was written in C.\n\nWell-behaved ARP behavior requires both a request and a reply.\n With a conversation as an analogy, this could be said as:\n * Host A: I'm looking for someone at this address B\n * Host B: Hey Host A, I'm Host B, and I'm over here.\n\nARP poisoning involves a malicious host constandly sending out\n crafted ARP messages to interfere with the ARP tables of the victim.\n With a conversation as an analogy, this could be said as:\n * Host C: Hey Host A, I'm host B, and I'm over here (honest!)\n * Host C: Hey Host A, I'm host B, and I'm over here (honest!)\n\nThis script makes judgements based on imbalances of ARP replies to ARP requests.\n * An imbalance of requests for a particular address suggests a client trying to reach something on an unused address.\n This is unfortunate for the person making the request, but not harmful.\n* An imbalance of replies for a particular address suggests that ARP poisoning is taking place.\n\"\"\"\n\nfrom __future__ import print_function\nimport getopt, getpass, os, pwd, re, struct, subprocess, sys, time\n\n#\n# Common Colours and Message Functions\n###\n\ndef _print_message(header_colour, header_text, message, stderr=False):\n f=sys.stdout\n if stderr:\n f=sys.stderr\n print(\"%s[%s]: %s\" % (colour_text(header_text, header_colour), colour_text(os.path.basename(sys.argv[0]), COLOUR_GREEN), message), file=f)\n\ndef colour_text(text, colour = None):\n if not colour:\n colour = COLOUR_BOLD\n # A useful shorthand for applying a colour to a string.\n return \"%s%s%s\" % (colour, text, COLOUR_OFF)\n\ndef enable_colours(force = False):\n global COLOUR_PURPLE\n global COLOUR_RED\n global COLOUR_GREEN\n global COLOUR_YELLOW\n global COLOUR_BLUE\n global COLOUR_BOLD\n global COLOUR_OFF\n if force or sys.stdout.isatty():\n # Colours for standard output.\n COLOUR_PURPLE = '\\033[1;35m'\n COLOUR_RED = '\\033[1;91m'\n COLOUR_GREEN = '\\033[1;92m'\n COLOUR_YELLOW = '\\033[1;93m'\n COLOUR_BLUE = '\\033[1;94m'\n COLOUR_BOLD = '\\033[1m'\n COLOUR_OFF = '\\033[0m'\n else:\n # Set to blank values if not to standard output.\n COLOUR_PURPLE = ''\n COLOUR_RED = ''\n COLOUR_GREEN = ''\n COLOUR_YELLOW = ''\n COLOUR_BLUE = ''\n COLOUR_BOLD = ''\n COLOUR_OFF = ''\nenable_colours()\n\nerror_count = 0\ndef print_error(message):\n global error_count\n error_count += 1\n _print_message(COLOUR_RED, \"Error\", message)\n\ndef print_exception(e, msg=None):\n # Shorthand wrapper to handle an exception.\n # msg: Used to provide more context.\n sub_msg = \"\"\n if msg:\n sub_msg = \" (%s)\" % msg\n print_error(\"Unexpected %s%s: %s\" % (colour_text(type(e).__name__, COLOUR_RED), sub_msg, str(e)))\n\ndef print_info(message):\n _print_message(COLOUR_GREEN, \"Info\", message)\n\ndef print_notice(message):\n _print_message(COLOUR_BLUE, \"Notice\", message)\n\ndef print_warning(message):\n _print_message(COLOUR_YELLOW, \"Warning\", message)\n\n###########################################\n\n# Common Argument Handling Structure\n# My own implementation of an argparse-like structure to add args and\n# build a help menu that I have a bit more control over.\n#\n# Note: These functions assume that my common message functions are also being used.\n# If this is not the case or if the functions are in a different module:\n# * Adjust print_foo functions.\n# * Adjust colour_text() calls.\n# * Adjust all mentions of COLOUR_* variables.\n\nMASK_OPT_TYPE_LONG = 1\nMASK_OPT_TYPE_ARG = 2\n\nOPT_TYPE_FLAG = 0\nOPT_TYPE_SHORT = MASK_OPT_TYPE_ARG\nOPT_TYPE_LONG_FLAG = MASK_OPT_TYPE_LONG\nOPT_TYPE_LONG = MASK_OPT_TYPE_LONG | MASK_OPT_TYPE_ARG\n\nTITLE_HELP = \"help\"\n\nclass ArgHelper:\n\n args = {}\n defaults = {}\n raw_args = {}\n operands = []\n\n operand_text = None\n\n errors = []\n validators = []\n\n opts = {OPT_TYPE_FLAG: {}, OPT_TYPE_SHORT: {}, OPT_TYPE_LONG: {}, OPT_TYPE_LONG_FLAG: {}}\n opts_by_label = {}\n\n def __init__(self):\n self.add_opt(OPT_TYPE_FLAG, \"h\", TITLE_HELP, description=\"Display a help menu and then exit.\")\n\n def __contains__(self, arg):\n return arg in self.args\n\n def __getitem__(self, arg, default = None):\n opt = self.opts_by_label.get(arg)\n\n if not opt:\n # There was no registered option.\n # Giving give the args dictionary an attempt in case\n # something like a validator went and added to it.\n return self.args.get(arg)\n if opt.multiple:\n default = []\n\n # Silly note: Doing a get() out of a dictionary when the stored\n # value of the key is None will not fall back to default\n value = self.args.get(arg)\n if value is None:\n if opt.environment:\n value = os.environ.get(opt.environment, self.defaults.get(arg))\n else:\n value = self.defaults.get(arg)\n\n if value is None:\n return default\n return value\n\n def __setitem__(self, key, value):\n self.args[key] = value\n\n def add_opt(self, opt_type, flag, label, description = None, required = False, default = None, default_colour = None, default_announce = False, environment = None, converter=str, multiple = False, strict_single = False):\n\n if opt_type not in self.opts:\n raise Exception(\"Bad option type: %s\" % opt_type)\n\n has_arg = opt_type & MASK_OPT_TYPE_ARG\n\n prefix = \"-\"\n match_pattern = \"^[a-z0-9]$\"\n if opt_type & MASK_OPT_TYPE_LONG:\n prefix = \"--\"\n match_pattern = \"^[a-z0-9\\-]+$\" # ToDo: Improve on this regex?\n\n arg = prefix + flag\n\n # Check for errors. Developer errors get intrusive exceptions instead of the error list.\n if not label:\n raise Exception(\"No label defined for flag: %s\" % arg)\n if not flag:\n raise Exception(\"No flag defined for label: %s\" % label)\n if not opt_type & MASK_OPT_TYPE_LONG and len(flag) - 1:\n raise Exception(\"Short options must be 1-character long.\") # A bit redundant, but more informative\n if not re.match(match_pattern, flag, re.IGNORECASE):\n raise Exception(\"Invalid flag value: %s\" % flag) # General format check\n for g in self.opts:\n if opt_type & MASK_OPT_TYPE_LONG == g & MASK_OPT_TYPE_LONG and arg in self.opts[g]:\n raise Exception(\"Flag already defined: %s\" % label)\n if label in self.opts_by_label:\n raise Exception(\"Duplicate label (new: %s): %s\" % (arg, label))\n if multiple and strict_single:\n raise Exception(\"Cannot have an argument with both 'multiple' and 'strict_single' set to True.\")\n # These do not cover harmless checks on arg modifiers with flag values.\n\n obj = OptArg(self)\n obj.opt_type = opt_type\n obj.label = label\n obj.required = required and opt_type & MASK_OPT_TYPE_ARG\n obj.default = default\n obj.default_colour = default_colour\n obj.default_announce = default_announce\n obj.environment = environment\n obj.multiple = multiple\n obj.description = description\n obj.converter = converter\n obj.has_arg = has_arg\n obj.strict_single = strict_single\n\n self.opts_by_label[label] = self.opts[opt_type][arg] = obj\n if not has_arg:\n default = False\n elif multiple:\n default = []\n self.defaults[label] = default\n\n def add_validator(self, fn):\n self.validators.append(fn)\n\n def _get_opts(self):\n s = \"\".join([k for k in sorted(self.opts[OPT_TYPE_FLAG])])\n s += \"\".join([\"%s:\" % k for k in sorted(self.opts[OPT_TYPE_SHORT])])\n return s.replace('-', '')\n\n def _get_opts_long(self):\n l = [\"%s=\" % key for key in sorted(self.opts[OPT_TYPE_LONG].keys())] + sorted(self.opts[OPT_TYPE_LONG_FLAG].keys())\n return [re.sub(\"^-+\", \"\", i) for i in l]\n\n def convert_value(self, raw_value, opt):\n value = None\n\n try:\n value = opt.converter(raw_value)\n except:\n pass\n\n if value is None:\n self.errors.append(\"Unable to convert %s to %s: %s\" % (colour_text(opt.label), opt.converter.__name__, colour_text(raw_value)))\n\n return value\n\n get = __getitem__\n\n def hexit(self, exit_code = 0):\n\n s = \"./%s\" % os.path.basename(sys.argv[0])\n lines = []\n for label, section in [(\"Flags\", OPT_TYPE_FLAG), (\"Options\", OPT_TYPE_SHORT), (\"Long Flags\", OPT_TYPE_LONG_FLAG), (\"Long Options\", OPT_TYPE_LONG)]:\n if not self.opts[section]:\n continue\n\n lines.append(\"%s:\" % label)\n for f in sorted(self.opts[section].keys()):\n obj = self.opts[section][f]\n s+= obj.get_printout_usage(f)\n lines.append(obj.get_printout_help(f))\n\n if self.operand_text:\n s += \" %s\" % self.operand_text\n\n _print_message(COLOUR_PURPLE, \"Usage\", s)\n for l in lines:\n print(l)\n\n if exit_code >= 0:\n exit(exit_code)\n\n def last_operand(self, default = None):\n if not len(self.operands):\n return default\n return self.operands[-1]\n\n def load_args(self, cli_args = []):\n if cli_args == sys.argv:\n cli_args = cli_args[1:]\n\n if not cli_args:\n return True\n\n try:\n output_options, self.operands = getopt.gnu_getopt(cli_args, self._get_opts(), self._get_opts_long())\n except Exception as e:\n self.errors.append(\"Error parsing arguments: %s\" % str(e))\n return False\n\n for opt, optarg in output_options:\n found = False\n for has_arg, opt_type_tuple in [(True, (OPT_TYPE_SHORT, OPT_TYPE_LONG)), (False, (OPT_TYPE_FLAG, OPT_TYPE_LONG_FLAG))]:\n if found:\n break\n for opt_key in opt_type_tuple:\n if opt in self.opts[opt_key]:\n found = True\n obj = self.opts[opt_key][opt]\n if has_arg:\n if obj.label not in self.raw_args:\n self.raw_args[obj.label] = []\n self.raw_args[obj.label].append(optarg)\n else:\n # Flag, single-argument\n self.args[obj.label] = True\n return True\n\n def process(self, args = [], exit_on_error = True, print_errors = True):\n validate = True\n if not self.load_args(args):\n validate = False\n\n if self[TITLE_HELP]:\n self.hexit(0)\n\n if validate:\n self.validate()\n\n if self.errors:\n if print_errors:\n for e in self.errors:\n print_error(e)\n\n if exit_on_error:\n exit(1)\n return not self.errors\n\n def set_operand_help_text(self, text):\n self.operand_text = text\n\n def validate(self):\n for key in self.raw_args:\n obj = self.opts_by_label[key]\n if not obj.has_arg:\n self.args[obj.label] = True\n if not obj.multiple:\n if obj.strict_single and len(self.raw_args[obj.label]) > 1:\n self.errors.append(\"Cannot have multiple %s values.\" % colour_text(obj.label))\n else:\n value = self.convert_value(self.raw_args[obj.label][-1], obj)\n if value is not None:\n self.args[obj.label] = value\n elif obj.multiple:\n self.args[obj.label] = []\n for i in self.raw_args[obj.label]:\n value = self.convert_value(i, obj)\n if value is not None:\n self.args[obj.label].append(value)\n elif self.raw_args[obj.label]:\n value = self.convert_value(self.raw_args[obj.label][-1], obj)\n if value is not None:\n self.args[obj.label] = value\n for m in [self.opts_by_label[o].label for o in self.opts_by_label if self.opts_by_label[o].required and o not in self.raw_args]:\n self.errors.append(\"Missing %s value.\" % colour_text(m))\n for v in self.validators:\n r = v(self)\n if r:\n if isinstance(r, list):\n self.errors.extend(r) # Append all list items\n else:\n self.errors.append(r) # Assume that this is a string.\n\nclass OptArg:\n\n def __init__(self, args):\n self.opt_type = 0\n self.args = args\n\n def is_flag(self):\n return self.opt_type in (OPT_TYPE_FLAG, OPT_TYPE_LONG_FLAG)\n\n def get_printout_help(self, opt):\n\n desc = self.description or \"No description defined\"\n\n if self.is_flag():\n s = \" %s: %s\" % (opt, desc)\n else:\n s = \" %s <%s>: %s\" % (opt, self.label, desc)\n\n if self.environment:\n s += \" (Environment Variable: %s)\" % colour_text(self.environment)\n\n if self.default_announce:\n # Manually going to defaults table allows this core module\n # to have its help display reflect retroactive changes to defaults.\n s += \" (Default: %s)\" % colour_text(self.args.defaults.get(self.label), self.default_colour)\n return s\n\n def get_printout_usage(self, opt):\n\n if self.is_flag():\n s = opt\n else:\n s = \"%s <%s>\" % (opt, self.label)\n if self.required:\n return \" %s\" % s\n else:\n return \" [%s]\" % s\n\n#\n# Script Functions\n###\n\nARP_INSTANCES = {}\nLAST_SCRIPT_RUN = {}\nTIME_START = 0\nTIME_SPAN = 0\nTIME_RECENT = 0\n\nARP_SPOOF_EVENT_HEAL = \"SPOOF\"\nARP_SPOOF_EVENT_SPOOF = \"SPOOF\"\n\nDEFAULT_EXPIRY = 300\nDEFAULT_LIST = False\nDEFAULT_REPORT_THRESHOLD = 5\nDEFAULT_SCRIPT_COOLDOWN = 300\nDEFAULT_VERBOSE = False\n\nPCAP_FILTER = \"arp\"\n\nTITLE_SCRIPT_COOLDOWN = \"script cooldown\"\nTITLE_EXPIRY = \"expiry period\"\nTITLE_INTERFACE = \"interface\"\nTITLE_LIST = \"list ips\"\nTITLE_PCAP_FILE = \"PCAP file\"\nTITLE_REPORT_THRESHOLD = \"report threshold\"\nTITLE_SCRIPT = \"processing script\"\nTITLE_SCRIPT_USER = \"processing script user\"\nTITLE_VERBOSE = \"verbose\"\n\n# Argument Validators\n\ndef validate_integers(self):\n errors = []\n for key in (TITLE_SCRIPT_COOLDOWN, TITLE_EXPIRY, TITLE_REPORT_THRESHOLD):\n if self[key] <= 0:\n errors.append(\"Value of %s must be a positive integer.\" % colour_text(key))\n\n if self[TITLE_REPORT_THRESHOLD] <= 2 and self[TITLE_REPORT_THRESHOLD] > 0:\n # Also tack on a warning\n print_warning(\"A low %s value of %s could generate a lot of false positives.\" % (colour_text(TITLE_REPORT_THRESHOLD), colour_text(self[TITLE_REPORT_THRESHOLD])))\n\n if self[TITLE_SCRIPT_COOLDOWN] > self[TITLE_EXPIRY]:\n print_warning(\"Value for %s (%s) is less than that of %s (%s). Script may run more often than expected.\" % (colour_text(TITLE_SCRIPT), colour_text(self[TITLE_SCRIPT_COOLDOWN]), colour_text(TITLE_EXPIRY), colour_text(self[TITLE_EXPIRY])))\n\n return errors\n\ndef validate_input(self):\n\n errors = []\n\n # Note: Intentionally checking for both PCAP and interface errors, even if we are about to complain about the user trying to do both.\n\n # Validate PCAP file\n if TITLE_PCAP_FILE in self and not os.path.isfile(self[TITLE_PCAP_FILE]):\n errors.append(\"PCAP file does not exist: %s\" % colour_text(args[TITLE_INTERFACE], COLOUR_GREEN))\n # Validate interface.\n if TITLE_INTERFACE in self:\n if not os.path.isdir(\"/sys/class/net/%s\" % self[TITLE_INTERFACE]):\n errors.append(\"Listening interface does not exist: %s\" % colour_text(args[TITLE_INTERFACE], COLOUR_GREEN))\n if os.geteuid():\n errors.append(\"Must be %s to capture on a live interface.\" % colour_text(\"root\", COLOUR_RED))\n\n if TITLE_PCAP_FILE in self and TITLE_INTERFACE in self:\n errors.append(\"Cannot specify both an input file and a capture interface.\")\n elif not TITLE_INTERFACE in self and not TITLE_PCAP_FILE in self:\n errors.append(\"No interface or PCAP file defined.\")\n\n return errors\n\ndef validate_module(self):\n try:\n import pcap\n except ImportError:\n return \"Unable to import PCAP module, not installed. To install: dnf install -y libpcap-devel python-devel redhat-rpm-config && pip install pypcap\"\n\ndef validate_script(self):\n\n errors = []\n if self[TITLE_SCRIPT]:\n if os.path.isdir(self[TITLE_SCRIPT]):\n print_error(\"Processing script path is a directory: %s\" % colour_text(args[TITLE_SCRIPT], COLOUR_GREEN))\n elif not os.path.isfile(args[TITLE_SCRIPT]):\n errors.append(\"Processing script does not exist: %s\" % colour_text(args[TITLE_SCRIPT], COLOUR_GREEN))\n elif not os.access(args[TITLE_SCRIPT], os.X_OK):\n errors.append(\"Processing script is not executable: %s\" % colour_text(args[TITLE_SCRIPT], COLOUR_GREEN))\n\n try:\n global userinfo\n userinfo = pwd.getpwnam(self.get(TITLE_SCRIPT_USER, getpass.getuser()))\n except KeyError:\n print_error(\"Could not get information for %s: %s\" % (colour_text(TITLE_SCRIPT_USER), colour_text(self[TITLE_SCRIPT_USER])))\n else:\n # Check for arguments that work off of the processing script.\n # I am divided on whether or not these should be warnings or errors...\n for check in [TITLE_SCRIPT_COOLDOWN, TITLE_SCRIPT_USER]:\n if check in self:\n print_warning(\"A value for %s was set, but no %s is defined.\" % (colour_text(TITLE_SCRIPT), colour_text(check)))\n\n# Classes\n\nclass ARP():\n def __init__(self, ts, pkt):\n\n self.ts = ts\n\n initial_offset = 0\n offset = initial_offset\n\n if not offset:\n # Ethernet Header (should technically be separate if this were a larger-scale application...)\n\n edst = pkt[offset:offset+6] # Ethernet Header Destination\n self.edst = self._mac_bytes_to_str(edst)\n offset += 6\n\n esrc = pkt[offset:offset+6] # Ethernet Header Source\n self.esrc = self._mac_bytes_to_str(esrc)\n offset += 6\n\n self.type = struct.unpack('!H', pkt[offset:offset+2])[0] # Ethernet Header Protocol Type\n offset += 2\n else:\n self.type = -1\n self.edst = None\n self.esrc = None\n\n self.hw_type = struct.unpack('!H', pkt[offset:offset+2])[0] # Hardware Type\n offset += 2\n\n self.proto_type = struct.unpack('!H', pkt[offset:offset+2])[0] # Protocol Type\n offset += 2\n\n self.hw_size = struct.unpack('BBBBBB', bytes(pkt[offset]))[0] # Hardware Address Size\n offset += 1\n\n self.proto_size = struct.unpack('BBBB', bytes(pkt[offset]))[0] # Protocol Size\n offset += 1\n\n self.opcode = struct.unpack('!H', pkt[offset:offset+2])[0]\n offset += 2\n\n # ARP Header Source\n asrc = pkt[offset:offset+6]\n self.asrc = self._mac_bytes_to_str(asrc)\n offset += 6\n\n # Network Source IP\n self.nsrc = self._ipv4_bytes_to_str(pkt, offset)\n offset += 4\n\n # ARP Header Destination\n adst = pkt[offset:offset+6]\n self.adst = self._mac_bytes_to_str(adst)\n offset += 6\n\n # Network Destination IP\n self.ndst = self._ipv4_bytes_to_str(pkt, offset)\n offset += 4\n\n if self.opcode == 1: # Request\n # Request\n self.id = \"%s%s\" % (self.asrc, self.ndst)\n elif self.opcode == 2: # Reply\n self.id = \"%s%s\" % (self.adst, self.nsrc)\n else:\n self.id = \"0000000000\" # Placeholder, fallback. This will be discarded soon anyways.\n\n # Format the ID into a string for debug purposes.\n self.id_s = ''\n for b in self.id:\n self.id_s += '%02x' % ord(b)\n\n def _ipv4_bytes_to_str(self, pkt, offset):\n nsrc = bytes(pkt[offset:offset+4])\n return \"%d.%d.%d.%d\" % (nsrc[0], nsrc[1], nsrc[2], nsrc[3])\n\n def _mac_bytes_to_str(self, raw_bytes):\n unpacked = struct.unpack('BBBBBB', raw_bytes)\n result = ''\n for b in unpacked:\n result += '%02x:' % b\n return result[:-1]\n\ndef attempt_script(event, ts, arp, args):\n if event not in LAST_SCRIPT_RUN:\n LAST_SCRIPT_RUN[event] = {}\n\n if TITLE_SCRIPT not in args or not (ts - LAST_SCRIPT_RUN[event].get(arp.id, ts)) > args[TITLE_SCRIPT_COOLDOWN]:\n return # No script defined or cooldown not exceeded.\n\n # Mark timestamp by starting time.\n LAST_SCRIPT_RUN[event][arp.id] = ts\n\n # Run script\n try:\n subprocess.Popen([args[TITLE_SCRIPT], event, arp.nsrc, arp.asrc, arp.ndst, arp.adst, arp.esrc, arp.edst], preexec_fn=demote(userinfo.pw_uid, userinfo.pw_gid))\n except OSError:\n print_error(\"Problem executing script hook: %s\" % colour_text(args[TITLE_SCRIPT], COLOUR_GREEN))\n\ndef demote(user_uid, user_gid):\n def result():\n os.setgid(user_gid)\n os.setuid(user_uid)\n return result\n\ndef do_pcap_callback(ts, pkt, obj):\n # Reject too-short packets that could never be built into ARP messages\n if len(pkt) < 38:\n return\n\n arp = ARP(ts, pkt)\n\n if arp.opcode == 1: # ARP Request OpCode\n op = \"REPLY\"\n if obj.args[TITLE_VERBOSE]:\n print_notice(\"%s: Who has %s? Tell %s (%s)\" % (colour_text(op), colour_text(arp.ndst, COLOUR_GREEN), colour_text(arp.nsrc, COLOUR_GREEN), colour_text(arp.asrc)))\n elif arp.opcode == 2: # ARP Reply OpCode\n op = \"REPLY\"\n if obj.args[TITLE_VERBOSE]:\n print_notice(\"%s: %s is at %s (To: %s at %s)\" % (colour_text(op), colour_text(arp.nsrc, COLOUR_GREEN), colour_text(arp.asrc), colour_text(arp.ndst, COLOUR_GREEN), colour_text(arp.adst)))\n else:\n return # Not a request or reply.\n\n global TIME_RECENT\n global TIME_START\n TIME_RECENT = ts\n if not TIME_START:\n TIME_START = ts\n\n if arp.asrc != arp.esrc:\n obj.print_alert(\"%s for IP %s claiming to be from MAC %s, but is actually from MAC %s. Likely a forged healing packet!\" % (colour_text(COLOUR_BOLD, op), colour_text(COLOUR_GREEN, arp.nsrc), colour_text(COLOUR_BOLD, arp.asrc), colour_text(COLOUR_BOLD, arp.esrc)))\n list_ipv4_addresses_by_mac(arp.esrc)\n attempt_script(ARP_SPOOF_EVENT_HEAL, ts, arp, obj.args)\n\n # Immediately return.\n # The point in tracking events is that we normally cannot track poisoning by a single packet.\n # However, healing packets from ettercap/arpspoof/etc trying to cover its tracks\n # are blatant enough that they can be identified right away.\n # Do not track event to avoid false positives.\n return\n\n # Is an interaction of this ID currently stored in the dictionary?\n if arp.id not in ARP_INSTANCES:\n ARP_INSTANCES[arp.id] = [arp] # Create list and add ARP packet\n else:\n ARP_INSTANCES[arp.id].append(arp) # Append ARP packet to existing chain.\n\n # Need to clear out old instances.\n # If we are reading from a PCAP file, then we can only really\n # compare against the current timestamp.\n # If we are reading from a live capture, then we can use the current\n # time as a reference (which should be pretty much be\n # the provided timestamp anyways).\n for k in ARP_INSTANCES.keys():\n # May as well clear through all instances.\n i = 0\n while i < len(ARP_INSTANCES[k]):\n if (ts - ARP_INSTANCES[k][i].ts) > obj.args[TITLE_EXPIRY]:\n del ARP_INSTANCES[k][i]\n # Do not increment, since i will now be the old i+1.\n else:\n i += 1\n if not ARP_INSTANCES[k]:\n # Delete empty lists, mostly for tidiness.\n del ARP_INSTANCES[k]\n for key in LAST_SCRIPT_RUN:\n for subkey in LAST_SCRIPT_RUN[key]:\n if arp.id in LAST_SCRIPT_RUN[key][subkey]:\n del LAST_SCRIPT_RUN[key][subkey][arp.id]\n\n # Sweep through non-expired instances of this ID to look for potential poisoning.\n score = 0\n i = 0\n while i < len(ARP_INSTANCES[arp.id]):\n if ARP_INSTANCES[arp.id][i].opcode == 1: # Request\n # Machine sent out a request, behooving real machine to reply and countering poison attack.\n # Still under consideration, have a request simply decrement the score instead?\n score = 0\n else: # Reply\n score += 1\n i += 1\n\n if score >= obj.args[TITLE_REPORT_THRESHOLD]:\n #\n # TODO: Existing reporting currently has a bit of a flaw:\n # - Does not account for one IP \"legitimately\" being stepped on by two devices, creating an imbalance.\n # This still impedes network performance, but it's more \"ARP high cholesterol\" than \"ARP poisoning\".\n # Still bad for your network, but not necessarily malicious.\n\n obj.print_alert(\"%s (%s) is likely being ARP poisoned by %s (spoofing %s, ARP imbalance of %s over %s seconds)\" % (colour_text(arp.ndst, COLOUR_GREEN), colour_text(arp.adst), colour_text(arp.esrc), colour_text(arp.nsrc, COLOUR_GREEN), colour_text(score), colour_text(obj.args[TITLE_REPORT_THRESHOLD])));\n\n list_ipv4_addresses_by_mac(arp.esrc, obj.args[TITLE_LIST])\n attempt_script(ARP_SPOOF_EVENT_SPOOF, ts, arp, obj.args)\n\ndef list_ipv4_addresses_by_mac(mac, do_list):\n\n if not do_list:\n return # Listing is not enabled.\n\n try:\n with open(\"/proc/net/arp\", \"r\") as f:\n content = f.readlines()\n f.close()\n except OSError as e:\n # File error.\n print_error(e)\n return\n\n addresses = []\n\n for line in content:\n cols = re.sub('\\s+', ' ', line).split(\" \")\n if cols[3] == mac:\n addresses.append(colour_text(cols[0], COLOUR_GREEN))\n\n if addresses:\n print_info(\"IPv4 entries for %s in current ARP table: %s\" % (colour_text(mac), \", \".join(addresses)))\n\nclass ToxScreen:\n def __init__(self):\n self.args = ArgHelper()\n\n self.args.add_opt(OPT_TYPE_SHORT, \"c\", TITLE_SCRIPT_COOLDOWN, \"Cooldown between script invocations.\", converter=int, default = DEFAULT_SCRIPT_COOLDOWN, default_announce = True)\n self.args.add_opt(OPT_TYPE_SHORT, \"e\", TITLE_EXPIRY, \"Time in seconds that it takes for an ARP event to fall off this script's radar.\", converter=int, default = DEFAULT_EXPIRY, default_announce = True)\n self.args.add_opt(OPT_TYPE_SHORT, \"f\", TITLE_PCAP_FILE, \"PCAP file to load.\")\n self.args.add_opt(OPT_TYPE_SHORT, \"i\", TITLE_INTERFACE, \"Network interface to listen for ARP poisoning on.\")\n self.args.add_opt(OPT_TYPE_FLAG, \"l\", TITLE_LIST, \"Attempt to resolve offending MAC address to an IP address.\")\n self.args.add_opt(OPT_TYPE_SHORT, \"s\", TITLE_SCRIPT, \"Script to run when a suspicious event is detected.\")\n self.args.add_opt(OPT_TYPE_SHORT, \"t\", TITLE_REPORT_THRESHOLD, \"Cooldown between script invocations.\", converter=int, default = DEFAULT_REPORT_THRESHOLD, default_announce = True)\n self.args.add_opt(OPT_TYPE_SHORT, \"u\", TITLE_SCRIPT_USER, \"User to run script as. Only effective if script is run as root.\")\n self.args.add_opt(OPT_TYPE_FLAG, \"v\", TITLE_VERBOSE, \"Enable verbose output.\")\n\n self.args.add_validator(validate_module)\n self.args.add_validator(validate_integers)\n self.args.add_validator(validate_input)\n self.args.add_validator(validate_script)\n\n self.alert_count = 0\n\n def do_pcap(self):\n\n target = self.args.get(TITLE_INTERFACE, self.args[TITLE_PCAP_FILE])\n import pcap\n pcap_obj = pcap.pcap(name=target, promisc=True, immediate=True, timeout_ms=50)\n try:\n pcap_obj.setfilter(PCAP_FILTER)\n except:\n print_error(\"Illegal PCAP filter: %s\" % colour_text(PCAP_FILTER))\n exit(1)\n\n try:\n pcap_obj.loop(0, do_pcap_callback, self)\n except KeyboardInterrupt:\n print(\"\\n\")\n\n global TIME_RECENT\n global TIME_SPAN\n global TIME_START\n\n if TITLE_INTERFACE in self.args:\n TIME_RECENT = time.time()\n\n TIME_SPAN = int(TIME_RECENT - TIME_START)\n\n def print_alert(self, message):\n self.alert_count += 1\n _print_message(COLOUR_RED, \"ALERT\", message)\n\n def run(self, raw_args):\n self.args.process(raw_args)\n self.summarize_arguments()\n\n self.do_pcap()\n\n colour = COLOUR_RED\n if not self.alert_count:\n colour = COLOUR_GREEN\n\n if TITLE_PCAP_FILE in self.args:\n print_notice(\"Observed instances of ARP poisoning in PCAP file '%s' over %s seconds: %s\" % (colour_text(os.path.basename(self.args[TITLE_PCAP_FILE]), COLOUR_GREEN), colour_text(TIME_SPAN), colour_text(self.alert_count, colour)))\n else:\n # Interface printing.\n print_notice(\"Observed instances of ARP poisoning on '%s' interface over %s seconds: %s\" % (colour_text(COLOUR_GREEN, os.path.basename(self.args[TITLE_INTERFACE])), colour_text(TIME_SPAN), colour_text((self.alert_count, colour))))\n\n def summarize_arguments(self):\n if TITLE_INTERFACE in self.args:\n on = (\"Listening\", \"on interface\", colour_text(self.args[TITLE_INTERFACE]))\n else:\n on = (\"Looking\", \"in file\", colour_text(self.args[TITLE_PCAP_FILE], COLOUR_GREEN))\n print_notice(\"%s for ARP poisoning cases %s: %s\" % on)\n print_notice(\"Poisoning threshold: %s imbalanced replies will imply poisoning.\" % colour_text(self.args[TITLE_REPORT_THRESHOLD]))\n print_notice(\"Poisoning expiry time: %s\" % colour_text(\"%ds\" % self.args[TITLE_EXPIRY]))\n if TITLE_SCRIPT in self.args:\n user_colour = COLOUR_BOLD\n if self.args[TITLE_SCRIPT_USER] == \"root\":\n user_colour = COLOUR_RED\n print_notice(\"Processing script: %s as %s (cooldown per instance: %s)\" % (colour_text(self.args[TITLE_SCRIPT], COLOUR_GREEN), colour_text(self.args[TITLE_SCRIPT_USER], user_colour), colour_text(\"%ds\" % self.args[TITLE_SCRIPT_COOLDOWN])))\n if self.args[TITLE_LIST]:\n print_notice(\"Suspicious MAC addresses will be checked against our current ARP table for matches.\")\n\nif __name__ == \"__main__\":\n\n screen = ToxScreen()\n screen.run(sys.argv)\n","sub_path":"scripts/networking/arp_toxscreen.py","file_name":"arp_toxscreen.py","file_ext":"py","file_size_in_byte":30826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"295941133","text":"import calendar\nimport xlrd\nimport pandas as pd\nfrom openpyxl import load_workbook\nclass Worker:\n def __init__(self, name, workdays, endTime=9, cCount=0):\n self.name = name #TA's name\n self.workdays = self.beautifyWorkDays(workdays) #TA's days of work\n self.cleanCount = cCount #TA's number of times cleaned\n self.workEnd = endTime #time the TA gets off work\n\n def stats(self):\n \"\"\" prints the instance variables of a TA\"\"\"\n print(self.name, self.workdays, self.cleanCount, self.workEnd)\n\n def beautifyWorkDays(self,ugly):\n \"\"\" Removes white space and commas for a TA's workdays from the excel file \n Workdays must be comma deliminated to work\n \n Takes in the string ugly and returns pretty\"\"\"\n\n pretty = []\n tempString = \"\"\n for duck in ugly:\n if duck == \",\":\n pretty.append(tempString)\n tempString = \"\"\n elif duck == \" \":\n pass\n else:\n tempString += duck\n pretty.append(tempString)\n \n return pretty\n\n def getName(self):\n return self.name\n \n def getWorkDays(self):\n return self.workdays\n\n def getCleanCount(self):\n return self.cleanCount\n\n def getWorkEnd(self):\n return self.workEnd\n\n def cleaned(self):\n self.cleanCount += 1\n\n def mopped(self):\n self.cleanCount += 2\n\n\ndef calendarDays(excluded=[]):\n \"\"\" Returns a list of repeated Mon-Sun days of the week\n Corresponds to the lab days for the month\n\n excluded: the dates without lab days\n a list of numbers\n \"\"\"\n #Use Calendar to get the right days and dates for the month/year\n labDays = []\n weekdays = {0: \"Mon\", 1: \"Tue\", 2: \"Wed\", 3: \"Thu\", 4: \"Sun\"}\n\n #IMPORTANT# \n #IMPORTANT# \n year = 2019 #Change this for the correct year\n #IMPORTANT# \n #IMPORTANT# \n days = []\n month = int(input(\"What month number is it?:\"))\n cal = calendar.Calendar()\n for i in cal.itermonthdays(year, month): # loops through the month and adds only lab days \n if i in excluded: # if the date is in the list of dates to exclude, don't do anything\n pass\n elif i > 0:\n days.append(i)\n day = calendar.weekday(year, month, i)\n if 0 <= day <= 4: # if the date is Sun-Thur\n labDays.append(weekdays[day])\n print(days)\n return labDays\n\ndef getAvailableWorkers(day, labDays,workers):\n \"\"\"returns a list of only the TAs available for this day\n day: the current day (0-31)\n labDays: list of labDays consiting of Mon-Thu repetitions\n workers: list of worker objects\n \"\"\"\n availableWorkers = []\n for worker in workers:\n if labDays[day] in worker.getWorkDays():\n availableWorkers.append(worker)\n return availableWorkers\n \ndef decideWorkers(availableWorkers,today,num=4,mopping=False):\n \"\"\" takes the available workers and appends num workers with lowest clean count to the current work day.\n \n availableworkers: workers that are available to work on the current day\n daySched: a list representing who works the current day\n num: how many people to pick for working\"\"\"\n secondary = 0 # count for how many secondaries are working today\n\n availableWorkers.sort(key=lambda worker: worker.getCleanCount())\n for minion in availableWorkers[:num]: # take the first four lowest\n if minion.getWorkEnd() != 9.0: # find the number of secondaries\n secondary += 1\n\n for minion in availableWorkers[:num+secondary]: # take the first four lowest and additionals to replace secondaries\n if mopping and (minion.getWorkEnd() == 9.0): #only people who will be at the end of lab to mop gets mopping counted\n minion.mopped()\n else: #if they aren't mopping or cannot mop, they only clean\n minion.cleaned()\n # Add this assignment to the schedule\n working = (minion.getName(),minion.getCleanCount()) #make the name and clean count a tuple\n \n \n \n today.append(working)\n return today\n\ndef makeSchedule(labDays, workers,mopFreq=3):\n \"\"\" Returns a list of lists representing who works each day lab is open\n \n labDays: list of lab days\n workers: list of workers \n mopFreq: how often to mop AKA every # days to mop\"\"\"\n cleaningSched = [] #nested list of who cleans each day\n #For every day in labDays\n mopTime = False\n mopCount = 2\n for i in range(len(labDays)):\n daySched = [] # list of today's workers\n daySched.append(labDays[i]) # Add Current Day to the list\n\n if mopCount%mopFreq==0:\n mopTime = True\n \n availableWorkers = getAvailableWorkers(i,labDays,workers) #find who can work today\n cleaningSched.append(decideWorkers(availableWorkers,daySched,4,mopTime)) # add workers to the day and append it to the cleaning schedule\n \n #append \"Mopped\" to the end of the day's schedule instead of the beginning\n if mopTime:\n daySched.append(\"Mopped\")\n #set mopTime to false, so we don't make everyone mop\n mopTime = False\n mopCount += 1\n return cleaningSched\n\n\ndef main():\n \n workers = []\n #find the excel sheet\n loc = (\"TASched.xlsx\")\n rb = xlrd.open_workbook(loc)\n sheet = rb.sheet_by_index(0)\n #############################\n # each row is a person\n # make a TA object out of them\n for i in range(1,sheet.nrows):\n person = Worker(sheet.cell_value(i,0), list(sheet.cell_value(i,1)), sheet.cell_value(i,2), sheet.cell_value(i,3))\n workers.append(person)\n #print(sheet.cell_value(i,0))\n ##############################\n\n #Use Calendar to get the right days and dates for the month/year\n exclusions = [11,29,30]\n print(exclusions)\n labDays = calendarDays(exclusions)\n ###########################################################################################\n #Create the cleaning schedule then print it\n cleaningSched = makeSchedule(labDays,workers)\n for day in cleaningSched:\n print(day)\n ########################################################################## \n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"237287855","text":"import logging\n\nimport click\nimport requests\nfrom requests import Response\n\nfrom bubuku.config import load_config, KafkaProperties, Config\nfrom bubuku.env_provider import EnvProvider\nfrom bubuku.features.remote_exec import RemoteCommandExecutorCheck\nfrom bubuku.zookeeper import load_exhibitor_proxy, BukuExhibitor\n\n_LOG = logging.getLogger('bubuku.cli')\n\n\ndef _print_table(table: list, print_function=None):\n if not print_function:\n print_function = print\n names = sorted(set([v for v in sum([list(k.keys()) for k in table], [])]))\n lengths = {n: len(n) for n in names}\n for d in table:\n for k, v in d.items():\n if lengths[k] < len(str(v)):\n lengths[k] = len(str(v))\n format_string = ' '.join(['{!s:' + str(lengths[n]) + 's}' for n in names])\n print_function(format_string.format(*names))\n for item in table:\n print_function(format_string.format(*[item.get(n, '') for n in names]))\n\n\ndef __validate_not_empty(ctx, param, value):\n if not value:\n raise click.BadParameter('Parameter must have value')\n return value\n\n\ndef __get_opt_broker_id(broker_id: str, config: Config, zk: BukuExhibitor, env_provider: EnvProvider) -> str:\n if not broker_id:\n kafka_properties = KafkaProperties(config.kafka_settings_template, '/tmp/tmp.props'.format(config.kafka_dir))\n broker_id_manager = env_provider.create_broker_id_manager(zk, kafka_properties)\n broker_id = broker_id_manager.get_broker_id()\n _LOG.info('Will use broker_id {}'.format(broker_id))\n running_brokers = zk.get_broker_ids()\n if broker_id not in running_brokers:\n raise Exception('Broker id {} is not registered ({}), can not restart'.format(broker_id, running_brokers))\n return broker_id\n\n\ndef __check_all_broker_ids_exist(broker_ids: list, zk: BukuExhibitor):\n registered_brokers = zk.get_broker_ids()\n unknown_brokers = [broker_id for broker_id in broker_ids if broker_id not in registered_brokers]\n if len(unknown_brokers) == 1:\n raise Exception('1 broker id is not valid: {}'.format(unknown_brokers[0]))\n if len(unknown_brokers) > 1:\n raise Exception('{} broker ids are not valid: {}'.format(len(unknown_brokers), \",\".join(unknown_brokers)))\n\n\ndef __prepare_configs():\n config = load_config()\n _LOG.info('Using config: {}'.format(config))\n env_provider = EnvProvider.create_env_provider(config)\n return config, env_provider\n\n\nlogging.basicConfig(level=getattr(logging, 'INFO', None))\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command('restart', help='Restart kafka instance')\n@click.option('--broker', type=click.STRING,\n help='Broker id to restart. By default current broker id is restarted')\ndef restart_broker(broker: str):\n config, env_provider = __prepare_configs()\n with load_exhibitor_proxy(env_provider.get_address_provider(), config.zk_prefix) as zookeeper:\n broker_id = __get_opt_broker_id(broker, config, zookeeper, env_provider)\n RemoteCommandExecutorCheck.register_restart(zookeeper, broker_id)\n\n\n@cli.command('rebalance', help='Run rebalance process on one of brokers. If rack-awareness is enabled, replicas will '\n 'only be move to other brokers in the same rack')\n@click.option('--broker', type=click.STRING,\n help=\"Broker instance on which to perform rebalance. By default, any free broker will start it\")\n@click.option('--empty_brokers', type=click.STRING,\n help=\"Comma-separated list of brokers to empty. All partitions will be moved to other brokers\")\n@click.option('--exclude_topics', type=click.STRING, help=\"Comma-separated list of topics to exclude from rebalance\")\n@click.option('--bin-packing', is_flag=True, help=\"Use bean packing approach instead of one way processing\")\n@click.option('--parallelism', type=click.INT, default=1, show_default=True,\n help=\"Amount of partitions to move in a single rebalance step\")\ndef rebalance_partitions(broker: str, empty_brokers: str, exclude_topics: str, parallelism: int, bin_packing: bool):\n config, env_provider = __prepare_configs()\n with load_exhibitor_proxy(env_provider.get_address_provider(), config.zk_prefix) as zookeeper:\n empty_brokers_list = [] if empty_brokers is None else empty_brokers.split(',')\n exclude_topics_list = [] if exclude_topics is None else exclude_topics.split(',')\n __check_all_broker_ids_exist(empty_brokers_list, zookeeper)\n broker_id = __get_opt_broker_id(broker, config, zookeeper, env_provider) if broker else None\n RemoteCommandExecutorCheck.register_rebalance(zookeeper, broker_id, empty_brokers_list,\n exclude_topics_list, parallelism, bin_packing)\n\n\n@cli.command('migrate', help='Replace one broker with another for all partitions')\n@click.option('--from', 'from_', type=click.STRING, callback=__validate_not_empty,\n help='List of brokers to migrate from (separated with \",\")')\n@click.option('--to', type=click.STRING, callback=__validate_not_empty,\n help='List of brokers to migrate to (separated with \",\")')\n@click.option('--shrink', is_flag=True, default=False, show_default=True,\n help='Whether or not to shrink replaced broker ids form partition assignment')\n@click.option('--broker', type=click.STRING, help='Optional broker id to execute check on')\n@click.option('--parallelism', type=click.INT, show_default=True, default=1,\n help=\"Amount of partitions to move in a single migration step\")\ndef migrate_broker(from_: str, to: str, shrink: bool, broker: str, parallelism: int):\n config, env_provider = __prepare_configs()\n with load_exhibitor_proxy(env_provider.get_address_provider(), config.zk_prefix) as zookeeper:\n broker_id = __get_opt_broker_id(broker, config, zookeeper, env_provider) if broker else None\n RemoteCommandExecutorCheck.register_migration(zookeeper, from_.split(','), to.split(','), shrink, broker_id,\n parallelism)\n\n\n@cli.command('swap_fat_slim', help='Move one partition from fat broker to slim one')\n@click.option('--threshold', type=click.INT, default=\"100000\", show_default=True, help=\"Threshold in kb to run swap\")\ndef swap_partitions(threshold: int):\n config, env_provider = __prepare_configs()\n with load_exhibitor_proxy(env_provider.get_address_provider(), config.zk_prefix) as zookeeper:\n RemoteCommandExecutorCheck.register_fatboy_slim(zookeeper, threshold_kb=threshold)\n\n\n@cli.group(name='actions', help='Work with running actions')\ndef actions():\n pass\n\n\n@actions.command('list', help='List all the actions on broker(s)')\n@click.option('--broker', type=click.STRING,\n help='Broker id to list actions on. By default all brokers are enumerated')\ndef list_actions(broker: str):\n table = []\n config, env_provider = __prepare_configs()\n\n for broker_id, address in _list_broker_addresses(config, env_provider, broker):\n try:\n response = requests.get('http://{}:{}/api/controller/queue'.format(address, config.health_port))\n except Exception as e:\n print('Failed to query information on {} ({})'.format(broker_id, address))\n _LOG.error('Failed to query information on {} ({})'.format(broker_id, address), exc_info=e)\n continue\n line = {\n '_broker_id': broker_id,\n '_broker_address': address,\n }\n if response.status_code != 200:\n line['error'] = _extract_error(response)\n table.append(line)\n else:\n changes = response.json()\n if not changes:\n line.update({\n 'type': None,\n 'description': None,\n 'running': None\n })\n table.append(line)\n else:\n for change in changes:\n line_copy = dict(line)\n line_copy.update(change)\n table.append(line_copy)\n if not table:\n print('No brokers found')\n else:\n _print_table(table)\n\n\n@actions.command('delete', help='Remove all actions of specified type on broker(s)')\n@click.option('--action', type=click.STRING,\n help='Action to delete')\n@click.option('--broker', type=click.STRING,\n help='Broker id to delete actions on. By default actions are deleted on all brokers')\ndef delete_actions(action: str, broker: str):\n if not action:\n print('No action specified. Please specify it')\n config, env_provider = __prepare_configs()\n\n for broker_id, address in _list_broker_addresses(config, env_provider, broker):\n try:\n response = requests.delete(\n 'http://{}:{}/api/controller/queue/{}'.format(address, config.health_port, action))\n except Exception as e:\n print('Failed to query information on {} ({})'.format(broker_id, address))\n _LOG.error('Failed to query information on {} ({})'.format(broker_id, address), exc_info=e)\n continue\n if response.status_code not in (200, 204):\n print('Failed to delete action from {} ({}): {}'.format(broker, address, _extract_error(response)))\n else:\n print('Removed action {} from {} ({})'.format(action, broker_id, address))\n\n\ndef _extract_error(response: Response):\n try:\n return response.json()['message']\n except Exception as e:\n _LOG.error('Failed to parse response message', exc_info=e)\n return response.text()\n\n\ndef _list_broker_addresses(config, env_provider, broker):\n with load_exhibitor_proxy(env_provider.get_address_provider(), config.zk_prefix) as zookeeper:\n for broker_id in zookeeper.get_broker_ids():\n if broker and broker != broker_id:\n continue\n yield broker_id, zookeeper.get_broker_address(broker_id)\n\n\n@cli.command('stats', help='Display statistics about brokers')\ndef show_stats():\n config, env_provider = __prepare_configs()\n with load_exhibitor_proxy(env_provider.get_address_provider(), config.zk_prefix) as zookeeper:\n disk_stats = zookeeper.get_disk_stats()\n table = []\n for broker_id in zookeeper.get_broker_ids():\n disk = disk_stats.get(broker_id, {}).get('disk') if disk_stats else {}\n table.append({\n 'Broker Id': broker_id,\n 'Address': zookeeper.get_broker_address(broker_id),\n 'Free kb': disk.get('free_kb'),\n 'Used kb': disk.get('used_kb')\n })\n _print_table(table)\n\n\n@cli.group(name='validate', help='Validates internal structures of kafka/zk')\ndef validate():\n pass\n\n\n@validate.command('replication', help='Returns all partitions whose ISR size differs from the replication factor or '\n 'have not registered broker ids')\n@click.option('--factor', type=click.INT, default=3, show_default=True, help='Replication factor')\ndef validate_replication(factor: int):\n config, env_provider = __prepare_configs()\n with load_exhibitor_proxy(env_provider.get_address_provider(), config.zk_prefix) as zookeeper:\n brokers = {int(x) for x in zookeeper.get_broker_ids()}\n table = []\n for topic_name, partition, state in zookeeper.load_partition_states():\n if len(state['isr']) != factor or not set(state['isr']).issubset(brokers):\n table.append({\n 'Partition': partition,\n 'Topic': topic_name,\n 'State': state\n })\n if table:\n _LOG.info('Invalid topics:')\n _print_table(table)\n else:\n print('All replica lists look valid')\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"bubuku/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":11887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"559563734","text":"class Solution:\n def firstMissingPositive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dict_num={}\n minnum=pow(2,31)-1\n maxnum=-1\n for i in nums:\n if i>0:\n minnum=min(minnum,i)\n maxnum=max(maxnum,i)\n dict_num[str(i)]=1\n if minnum>1:\n return 1\n else:\n ret=minnum+1\n flag=1\n while flag:\n if str(ret) in dict_num:\n ret+=1\n else:\n break\n return ret\n\n\nif __name__=='__main__':\n a=Solution()\n list=[1,2,0]\n print (a.firstMissingPositive(list))","sub_path":"41.py","file_name":"41.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"309092520","text":"def transform(data):\n '''Transform this data.'''\n\n return [\n item * idx\n for idx, item in enumerate(data)\n ]\n\n\nprint(transform([1, 2, 3]))\nprint(transform([['a'], ['b'], ['c']]))\n\n\ndef multiple_by_index(data: list[int]) -> list[int]:\n '''Multiply the numbers by their index.'''\n\n return [\n num * idx\n for idx, num in enumerate(data)\n ]\n\n\nprint(multiple_by_index([1, 2, 3]))\nprint(multiple_by_index([['a'], ['b'], ['c']]))","sub_path":"_drafts/Guide/Python/_drafts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"363706137","text":"import datetime\nimport errno\nimport os\nimport re\n\nbasedir_log = '../logs/'\n\n\ndef make_split_file():\n log_dir = '%Y-%m-%d_%H-%M'\n log_filename = '%Y-%m-%d_%H-%M_'\n log_level_info = 'info.log'\n log_level_warning = 'warning.log'\n log_level_error = 'error.log'\n\n log_filename_all = '%Y-%m-%d_%H-%M_all.log'\n\n now = datetime.datetime.now() - datetime.timedelta(minutes=1)\n\n dirc = basedir_log + now.strftime(log_dir)\n print(dirc)\n\n if os.path.exists(dirc):\n log_today_all = \"%s%s\" % (dirc + \"/\", now.strftime(log_filename_all))\n log_today_info = \"%s%s\" % (dirc + \"/\", now.strftime(log_filename + log_level_info))\n log_today_warning = \"%s%s\" % (dirc + \"/\", now.strftime(log_filename + log_level_warning))\n log_today_error = \"%s%s\" % (dirc + \"/\", now.strftime(log_filename + log_level_error))\n try:\n fd_info = os.open(log_today_info, os.O_CREAT | os.O_EXCL)\n fd_warning = os.open(log_today_warning, os.O_CREAT | os.O_EXCL)\n fd_error = os.open(log_today_error, os.O_CREAT | os.O_EXCL)\n # if coming here, the log file was created successfully\n os.close(fd_info)\n os.close(fd_warning)\n os.close(fd_error)\n\n except OSError as e:\n if e.errno != errno.EEXIST:\n # should not happen\n raise\n return log_today_all, log_today_info, log_today_warning, log_today_error\n\n else:\n print('error!!! no ' + dirc)\n return False\n\n\ndef split_logfile():\n file_path = make_split_file()\n print(file_path)\n if file_path:\n with open(file_path[1], 'a+') as f1, open(file_path[2], 'w+') as f2, open(file_path[3], 'w+') as f3:\n for line in open(file_path[0]): # \"../logs/2019-04-18_17-30/2019-04-18_17-30_all.log\"\n level = re.compile(\" \").sub('', line.split('-')[6])\n if level == 'INFO':\n f1.write(line)\n elif level == 'WARNING':\n f2.write(line)\n elif level == 'ERROR':\n f3.write(line)\n else:\n print('No such log !')\n else:\n print('no dir')\n\n\nsplit_logfile()\n","sub_path":"logtest02/config/splitlog.py","file_name":"splitlog.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"377802082","text":"import requests\nimport json\nimport random\n\nclass Multilinguist:\n \"\"\"This class represents a world traveller who knows \n what languages are spoken in each country around the world\n and can cobble together a sentence in most of them\n (but not very well)\n \"\"\"\n\n translatr_base_url = \"http://bitmakertranslate.herokuapp.com\"\n countries_base_url = \"https://restcountries.eu/rest/v2/name\"\n #{name}?fullText=true\n #?text=The%20total%20is%2020485&to=ja&from=en\n\n def __init__(self):\n \"\"\"Initializes the multilinguist's current_lang to 'en'\n \n Returns\n -------\n Multilinguist\n A new instance of Multilinguist\n \"\"\"\n self.current_lang = 'en'\n\n def language_in(self, country_name):\n \"\"\"Uses the RestCountries API to look up one of the languages\n spoken in a given country\n\n Parameters\n ----------\n country_name : str\n The full name of a country.\n\n Returns\n -------\n bool \n 2 letter iso639_1 language code.\n \"\"\"\n params = {'fullText': 'true'}\n response = requests.get(f\"{self.countries_base_url}/{country_name}\", params=params)\n json_response = json.loads(response.text)\n return json_response[0]['languages'][0]['iso639_1']\n\n def travel_to(self, country_name):\n \"\"\"Sets current_lang to one of the languages spoken\n in a given country\n\n Parameters\n ----------\n country_name : str\n The full name of a country.\n\n Returns\n -------\n str\n The new value of current_lang as a 2 letter iso639_1 code.\n \"\"\"\n local_lang = self.language_in(country_name)\n self.current_lang = local_lang\n return self.current_lang\n\n def say_in_local_language(self, msg):\n \"\"\"(Roughly) translates msg into current_lang using the Transltr API\n\n Parameters\n ----------\n msg : str\n A message to be translated.\n\n Returns\n -------\n str\n A rough translation of msg.\n \"\"\"\n params = {'text': msg, 'to': self.current_lang, 'from': 'en'}\n response = requests.get(self.translatr_base_url, params=params)\n json_response = json.loads(response.text)\n return json_response['translationText']\n\n# The multilinguist documentation tells us that this class represents a world-traveller who speaks many languages. \n\n# The first child class that we're going to define represents a world-travelling math genius who can speak many languages and mentally add up huge lists of numbers.\n# Instances of this class should be able to accept a list of numbers and returtouchn a sentence stating the sum of the numbers. \n# Make use of the inherited Multilinguist methods to ensure this sentence will always be delivered in the local language.\n# me = MathGenius()\n# print(me.report_total([23,45,676,34,5778,4,23,5465])) # The total is 12048\n# me.travel_to(\"India\")\n# print(me.report_total([6,3,6,68,455,4,467,57,4,534])) # है को कुल 1604\n# me.travel_to(\"Italy\")\n# print(me.report_total([324,245,6,343647,686545])) # È Il totale 1030767\n\n# Quote collector\n# The second child class we're going to define represents a person who loves to memorize quotes and then travel the world, \n# unleashing poor translations of them to unsuspecting passers-by.\n\n# Each instance of this class should have its own ever-growing collection of favourite quotes. \n# It should have the ability to add a new quote to its collection as well as the ability to select a random quote to share in the local language.\n\n# Stretch goals\n# Improve the quote collector's conversational skills be allowing them to keep track of the topic of each quote (eg. \"wisdom\", \"friendship\") \n# and add the ability to share a quote according to a specific topic, in addition to being able to share a random one.\n# Come up with a third child class that can make use of the multilinguist's abilities.\n# Give the math genius additional math-related skills besides adding long lists of numbers. Check out Python's Math module for inspiration.\n\njason = Multilinguist()\njason.travel_to(\"Brazil\")\nprint(jason.say_in_local_language(\"Hello world, this is some text that is being translated into portugese\"))\n\nclass MathGenius(Multilinguist):\n def report_total(self, list_of_numbers):\n return self.say_in_local_language(f' The total is: {sum(num for num in list_of_numbers)}')\n\nme = MathGenius()\nprint(me.report_total([23,45,676,34,5778,4,23,5465])) # The total is 12048\nme.travel_to(\"India\")\nprint(me.report_total([6,3,6,68,455,4,467,57,4,534])) # है को कुल 1604\nme.travel_to(\"Italy\")\nprint(me.report_total([324,245,6,343647,686545])) # È Il totale 1030767\n\n\nclass QuoteCollector(Multilinguist):\n known_quotes=[\n \"A Bird in the hand is worth two in the bush\",\n \"Do or do not there is no try\",\n \"Talent borrows, genius steals\"\n ]\n\n def learn_quote(self, new_quote):\n self.known_quotes.append(new_quote)\n \n def random_quote(self):\n quotepick = random.choice(self.known_quotes)\n translate_quote = self.say_in_local_language(quotepick)\n return(translate_quote)\n\nyou = QuoteCollector()\nprint(you.random_quote())\nyou.travel_to(\"Italy\")\nprint(you.random_quote())","sub_path":"multilinguist.py","file_name":"multilinguist.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"315693489","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport random\nimport hashlib\nimport time\nfrom string import lowercase, digits\n\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.conf import settings\n\n\nclass LoginRequiredMixin(object):\n \"\"\" login required mixin for class based view \"\"\"\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)\n\n\ndef json_response(context=None, **kwargs):\n \"\"\" response method for ajax request \"\"\"\n\n context = context or {}\n\n return HttpResponse(\n json.dumps(context),\n content_type='application/json',\n **kwargs\n )\n\n\ndef _get_rand_str(length=10):\n \"\"\" get random string contains lowercase chars and digits \"\"\"\n chars = lowercase + digits\n return ''.join(random.choice(chars) for i in range(length))\n\n\ndef _shuffle_str(s):\n char_list = list(s)\n random.shuffle(char_list)\n return ''.join(char_list)\n\n\ndef generate_key(seed=''):\n \"\"\" generate random md5 key \"\"\"\n seed += str(time.time()) + _get_rand_str()\n random.seed(seed)\n s = str(random.random())[2:] + settings.SECRET_KEY\n s = _shuffle_str(s)\n return hashlib.md5(s).hexdigest()\n","sub_path":"blog/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"95408484","text":"# -*- coding: utf-8 -*-\n\n# Sample code to use string producer.\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef one_hot(x, n):\n \"\"\"\n :param x: label (int)\n :param n: number of bits\n :return: one hot code\n \"\"\"\n o_h = np.zeros(n)\n o_h[x] = 1\n return o_h\n\n\nnum_classes = 3\nbatch_size = 4\n\n\n# --------------------------------------------------\n#\n# DATA SOURCE\n#\n# --------------------------------------------------\n\ndef dataSource(paths, batch_size):\n min_after_dequeue = 10 # train start delay\n capacity = min_after_dequeue + 3 * batch_size # max size\n\n example_batch_list = []\n label_batch_list = []\n\n # open files\n for i, p in enumerate(paths):\n filename = tf.train.match_filenames_once(p)\n filename_queue = tf.train.string_input_producer(filename, shuffle=False)\n reader = tf.WholeFileReader()\n # image decode\n _, file_image = reader.read(filename_queue)\n image, label = tf.image.decode_jpeg(file_image), [float(i)] # [one_hot(float(i), num_classes)]\n image = tf.image.resize_image_with_crop_or_pad(image, 80, 140)\n # 24 to 8 bits\n image = tf.image.rgb_to_grayscale(image)\n image = tf.reshape(image, [80, 140, 1]) # 2d to 3d tensor\n image = tf.to_float(image) / 255. - 0.5\n # feed buffer it up capacity\n example_batch, label_batch = tf.train.shuffle_batch([image, label], batch_size=batch_size, capacity=capacity,\n min_after_dequeue=min_after_dequeue)\n example_batch_list.append(example_batch)\n label_batch_list.append(label_batch) # one_hot labels\n\n # tensor joiner\n example_batch = tf.concat(values=example_batch_list, axis=0)\n label_batch = tf.concat(values=label_batch_list, axis=0)\n\n return example_batch, label_batch\n\n\n# --------------------------------------------------\n#\n# MODEL\n#\n# --------------------------------------------------\n\ndef myModel(X, reuse=False):\n with tf.variable_scope('ConvNet', reuse=reuse):\n o1 = tf.layers.conv2d(inputs=X, filters=32, kernel_size=3, activation=tf.nn.relu)\n o2 = tf.layers.max_pooling2d(inputs=o1, pool_size=2, strides=2)\n o3 = tf.layers.conv2d(inputs=o2, filters=64, kernel_size=3, activation=tf.nn.relu)\n o4 = tf.layers.max_pooling2d(inputs=o3, pool_size=2, strides=2)\n\n # exit nums, elements that we'll use\n h = tf.layers.dense(inputs=tf.reshape(o4, [batch_size * num_classes, 18 * 33 * 64]), units=5,\n activation=tf.nn.relu)\n y = tf.layers.dense(inputs=h, units=num_classes,\n activation=tf.nn.softmax) # sigmoid only accepts 1, for that is 'tf.nn.softmax'\n return y\n\n\nexample_batch_train, label_batch_train = dataSource([\"dataset/0/train/*.jpg\", \"dataset/1/train/*.jpg\", \"dataset/2/train/*.jpg\"], batch_size=batch_size)\nexample_batch_valid, label_batch_valid = dataSource([\"dataset/0/valid/*.jpg\", \"dataset/1/valid/*.jpg\", \"dataset/2/valid/*.jpg\"], batch_size=batch_size)\nexample_batch_test, label_batch_test = dataSource([\"dataset/0/test/*.jpg\", \"dataset/1/test/*.jpg\", \"dataset/2/test/*.jpg\"], batch_size=batch_size)\n\n# reuse is true for avoid mix data in the same model,\nexample_batch_train_predicted = myModel(example_batch_train, reuse=False)\nexample_batch_valid_predicted = myModel(example_batch_valid, reuse=True)\nexample_batch_test_predicted = myModel(example_batch_test, reuse=True)\n\n# train cost 'square sum'\ncost = tf.reduce_sum(tf.square(example_batch_train_predicted - label_batch_train))\ncost_valid = tf.reduce_sum(tf.square(example_batch_valid_predicted - label_batch_valid))\ncost_test = tf.reduce_sum(tf.square(example_batch_test_predicted - label_batch_test))\n# cost = tf.reduce_mean(-tf.reduce_sum(label_batch * tf.log(y), reduction_indices=[1]))\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(\n cost) # learning_rate; amount inversely proportional to learning\n\n# --------------------------------------------------\n#\n# TRAINING\n#\n# --------------------------------------------------\n\n# Add ops to save and restore all the variables.\n\nsaver = tf.train.Saver()\n\nwith tf.Session() as sess:\n file_writer = tf.summary.FileWriter('./logs', sess.graph)\n\n sess.run(tf.local_variables_initializer())\n sess.run(tf.global_variables_initializer())\n\n # Start populating the filename queue.\n # thread manager\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord, sess=sess)\n\n error_train_values = []\n error_validation_values = []\n\n for _ in range(430):\n sess.run(optimizer)\n error_train = sess.run(cost)\n error_validation = sess.run(cost_valid)\n if _ % 20 == 0:\n # print(\"Iter:\", _, \"---------------------------------------------\")\n # print(sess.run(label_batch_valid))\n # print(sess.run(example_batch_valid_predicted))\n # print(\"Error:\", sess.run(cost_valid))\n if _ > 1:\n diff = abs(error_validation_values[-2] - error_validation_values[-1])\n if diff < .0001:\n break\n print(\"Iter:\", _, \"Error train:\", error_train)\n print(\"\\tError validation:\", error_validation)\n error_train_values.append(error_train)\n error_validation_values.append(error_validation)\n\n\n save_path = saver.save(sess, \"./tmp/model.ckpt\")\n print(\"Model saved in file: %s\" % save_path)\n\n training_plot, = plt.plot(error_train_values)\n validation_plot, = plt.plot(error_validation_values)\n plt.legend(handles=[training_plot, validation_plot],\n labels=['Error', 'Validation'])\n plt.title(\"Training vs Validation\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Error\")\n plt.show()\n\n coord.request_stop()\n coord.join(threads)","sub_path":"convmodel.py","file_name":"convmodel.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"297773595","text":"import numpy as np\n\ndef outProduct(A, B):\n return determinant(A[0], B[0], A[1], B[1])\n\n\ndef determinant(x1, x2, y1, y2):\n return x1 * y2 - x2 * y1\n\n\ndef intersect(l1, l2):\n aa = l1.point1; bb = l1.point2; cc = l2.point1; dd = l2.point2\n delta = determinant(bb.x - aa.x, cc.x - dd.x, bb.y - aa.y, cc.y - dd.y)\n if delta >= - (1e-6) and delta <= (1e-6):\n return False\n\n namenda = determinant(cc.x - aa.x, cc.x - dd.x, cc.y - aa.y, cc.y - dd.y) / delta\n if namenda > 1 or namenda < 0:\n return False\n\n miu = determinant(bb.x - aa.x, cc.x - aa.x, bb.y - aa.y, cc.y - aa.y) / delta\n if miu > 1 or miu < 0:\n return False\n return True\n\n\ndef intersect2(l1, l2):\n aa = l1.point1; bb = l1.point2; cc = l2.point1; dd = l2.point2\n ACX = cc.x - aa.x; ACY = cc.y - aa.y\n ABX = bb.x - aa.x; ABY = bb.y - aa.y\n ADX = dd.x - aa.x; ADY = dd.y - aa.y\n flag1 = (determinant(ACX, ABX, ACY, ABY) * determinant(ADX, ABX, ADY, ABY) < - (1e-6))\n CAX = aa.x - cc.x; CAY = aa.y - cc.y\n CDX = dd.x - cc.x; CDY = dd.y - cc.y\n CBX = bb.x - cc.x; CBY = bb.y - cc.y\n flag2 = (determinant(CAX, CDX, CAY, CDY) * determinant(CBX, CDX, CBY, CDY) < - (1e-6))\n if flag1 and flag2:\n return True\n else:\n return False\n\n\ndef rectCheck(X1, Y1, X2, Y2):\n rect1 = rect(X1, Y1)\n rect2 = rect(X2, Y2)\n for cl1 in rect1.crossLine:\n for bl2 in rect2.boundLine:\n if intersect2(cl1, bl2):\n return True\n for cl2 in rect2.crossLine:\n for bl1 in rect1.boundLine:\n if intersect2(cl2, bl1):\n return True\n return False\n\n\ndef carBox(x0, phi, w, l):\n car1 = x0[0:2] + np.mat([[np.cos(phi) * l], [np.sin(phi) * l]]) + np.mat([[np.sin(phi) * w], [-np.cos(phi) * w]])\n car2 = x0[0:2] + np.mat([[np.cos(phi) * l], [np.sin(phi) * l]]) - np.mat([[np.sin(phi) * w], [-np.cos(phi) * w]])\n car3 = x0[0:2] - np.mat([[np.cos(phi) * l], [np.sin(phi) * l]]) + np.mat([[np.sin(phi) * w], [-np.cos(phi) * w]])\n car4 = x0[0:2] - np.mat([[np.cos(phi) * l], [np.sin(phi) * l]]) - np.mat([[np.sin(phi) * w], [-np.cos(phi) * w]])\n x = [car1[0,0],car2[0,0],car4[0,0],car3[0,0],car1[0,0]]\n y = [car1[1,0],car2[1,0],car4[1,0],car3[1,0],car1[1,0]]\n return x, y\n\n\ndef pointInRect(x, y, X, Y):\n A = [X[0] - x, Y[0] - y]\n B = [X[1] - x, Y[1] - y]\n C = [X[2] - x, Y[2] - y]\n D = [X[3] - x, Y[3] - y]\n flag = outProduct(A, B)\n if flag * outProduct(B, C) > (1e-6) and flag * outProduct(C, D) > (1e-6) and flag * outProduct(D, A) > (1e-6):\n return True\n else:\n return False\n\n\nclass rect(object):\n def __init__(self, X1, Y1):\n self.crossLine = [line(X1[0], Y1[0], X1[2], Y1[2]), line(X1[1], Y1[1], X1[3], Y1[3])]\n self.boundLine = [line(X1[0], Y1[0], X1[1], Y1[1]),\n line(X1[1], Y1[1], X1[2], Y1[2]),\n line(X1[2], Y1[2], X1[3], Y1[3]),\n line(X1[3], Y1[3], X1[0], Y1[0])]\n\n\nclass line(object):\n def __init__(self, x1, y1, x2, y2):\n self.point1 = point(x1, y1)\n self.point2 = point(x2, y2)\n\n\nclass point(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y","sub_path":"geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"66357454","text":"import itertools\n\nfrom pyproj import CRS, Transformer\nfrom pyproj.aoi import AreaOfInterest\nfrom pyproj.database import query_utm_crs_info\nfrom shapely.geometry import JOIN_STYLE, GeometryCollection, MultiPolygon, Polygon\nfrom shapely.ops import unary_union\nfrom werkzeug.utils import cached_property\n\ntransformers = {\n utm_code: {\n # WGS84 (World Geodetic System, 1984) is a standard which\n # defines the size and shape of the earth. Coordinates in the\n # data we get from ONS, and that we output as CAP XML are\n # expressed relative to the constants in WGS84.\n \"from_wgs84\": Transformer.from_crs(\"EPSG:4326\", utm_code, always_xy=True),\n \"to_wgs84\": Transformer.from_crs(utm_code, \"EPSG:4326\", always_xy=True),\n }\n for utm_code in {\n # These are the names of coordinate reference systems, which\n # provide mathemtical functions for transforming WGS84\n # coordinates to linear measures of distance across the earth’s\n # surface. The functions are different in different areas of the\n # earth because the earth is not a perfect sphere.\n # —\n # The UK, west to east\n \"EPSG:32629\", # Zone 29N: Between 12°W and 6°W, equator and 84°N\n \"EPSG:32630\", # Zone 30N: Between 6°W and 0°W, equator and 84°N\n \"EPSG:32631\", # Zone 31N: Between 0°E and 6°E, equator and 84°N\n # Santa Claus village (Finland)\n \"EPSG:32635\", # Zone 35N: Between 24°E and 30°E, equator and 84°N\n }\n}\n\n\nclass Polygons:\n\n # Estimated amount of bleed into neigbouring areas based on typical\n # range/separation of cell towers.\n approx_bleed_in_m = 1_500\n\n # Controls how much buffer to add for a shape of a given perimeter.\n # Smaller number means more buffering and a smoother shape. For\n # example `1000` means 1m of buffer for every 1km of perimeter, or\n # 20m of buffer for a 5km square. This gives us control over how\n # much we fill in very concave features like channels, harbours and\n # zawns.\n perimeter_to_buffer_ratio = 1000\n\n # Ratio of how much detail a shape of a given perimeter has once\n # simplified. Smaller number means less detail. For example `1000`\n # means that for a shape with a perimeter of 1000m, the simplified\n # line will never deviate more than 1m from the original.\n # Or for a 5km square, the line won’t deviate more than 20m. This\n # gives us approximate control over the total number of points.\n perimeter_to_simplification_ratio = 1_620\n\n # The threshold for removing very small areas from the map. These\n # areas are likely glitches in the data where the shoreline hasn’t\n # been subtracted from the land properly\n minimum_area_size_square_metres = 6_500\n\n output_precision_in_decimal_places = 6\n\n def __init__(self, polygons, utm_crs=None):\n\n if not isinstance(polygons, list):\n raise TypeError(\n f\"First argument to {self.__class__.__name__} must be a list \" f\"(not {type(polygons).__name__})\"\n )\n\n self.polygons = polygons\n self.utm_crs = utm_crs\n\n if self.utm_crs:\n if utm_crs not in transformers:\n raise ValueError(\n f\"Could not find {self.utm_crs} in expected coordinate \"\n f\"systems (are the coordinates in longitude/latitude \"\n f\"order?)\"\n )\n else:\n for polygon in self:\n if isinstance(polygon, Polygon):\n raise TypeError(f\"Can’t initiate with {Polygon.__name__} objects and no CRS\")\n if not isinstance(polygon, list):\n raise TypeError(f\"Can’t make {Polygon.__name__} from {type(polygon).__name__} `{polygon}`\")\n\n @cached_property\n def transform_from_wgs84(self):\n return transformers[self.utm_crs][\"from_wgs84\"]\n\n @cached_property\n def transform_to_wgs84(self):\n return transformers[self.utm_crs][\"to_wgs84\"]\n\n @cached_property\n def utm_polygons(self):\n\n if all(isinstance(polygon, Polygon) for polygon in self):\n # These polygons already have UTM coordinates\n return self\n\n if not self.polygons:\n return Polygons([])\n\n if not self.utm_crs:\n shapely_polygons = MultiPolygon([Polygon(p) for p in self])\n utm_crs_list = query_utm_crs_info(\n datum_name=\"WGS 84\",\n area_of_interest=AreaOfInterest(*shapely_polygons.bounds),\n )\n if not utm_crs_list:\n raise ValueError(\n f\"Could not find coordinates \"\n f\"{shapely_polygons.bounds} anywhere on the \"\n f\"surface of the earth (are they in \"\n f\"in WGS84 format?)\"\n )\n self.utm_crs = str(CRS.from_epsg(utm_crs_list[0].code))\n\n return Polygons(\n [self._polygon_from_wgs84_coords(polygon) for polygon in self],\n utm_crs=self.utm_crs,\n )\n\n def _polygon_from_wgs84_coords(self, coords):\n return Polygon(\n self.transform_coords(\n coords,\n transformer=self.transform_from_wgs84,\n )\n )\n\n @staticmethod\n def transform_coords(coords, transformer):\n return [list(transformer.transform(x, y)) for x, y in coords]\n\n def __getitem__(self, index):\n return self.polygons[index]\n\n def __len__(self):\n return len(self.polygons)\n\n @cached_property\n def perimeter_length(self):\n \"\"\"\n Total distance around all polygons in degrees. Polygons may have\n larger perimeter for a number of reasons:\n - they have a larger area\n - they are more jagged or detailed, for example a rocky coastline\n - they are made up of lots of small polygons, rather than one\n large one\n \"\"\"\n return sum(polygon.length for polygon in self.utm_polygons)\n\n @property\n def bounds(self):\n \"\"\"\n The bounds, of all polygons. In other words, the coordinates\n that would draw a box containing all the polygons.\n \"\"\"\n if not self.polygons:\n raise ValueError(f\"Can't determine bounds of empty {self.__class__.__name__}\")\n all_min_x, all_min_y, all_max_x, all_max_y = zip(*(polygon.bounds for polygon in self.utm_polygons))\n\n min_x_wgs84, min_y_wgs84 = self.transform_to_wgs84.transform(\n min(all_min_x),\n min(all_min_y),\n )\n max_x_wgs84, max_y_wgs84 = self.transform_to_wgs84.transform(\n max(all_max_x),\n max(all_max_y),\n )\n\n return (\n min_x_wgs84,\n min_y_wgs84,\n max_x_wgs84,\n max_y_wgs84,\n )\n\n @cached_property\n def buffer_outward_in_m(self):\n \"\"\"\n Calculates the distance (in metres) by which to buffer outwards\n when smoothing a given set of polygons. Larger and more complex\n polygons get a larger buffer.\n \"\"\"\n return (\n # If two areas are close enough that the distance between\n # them is less than the typical bleed of a cell\n # broadcast then this joins them together. The aim is to\n # reduce the total number of polygons in areas with many\n # small shapes like Orkney or the Isles of Scilly.\n self.approx_bleed_in_m\n / 3\n ) + (self.perimeter_length / self.perimeter_to_buffer_ratio)\n\n @cached_property\n def buffer_inward_in_m(self):\n \"\"\"\n Calculates the distance (in metres) by which to buffer inwards\n when smoothing a given set of polygons. Larger and more complex\n polygons get a larger buffer, to negate the larger outwards\n buffer.\n \"\"\"\n return (\n self.buffer_outward_in_m\n - (\n # We should leave the shape expanded by at least the\n # simplification tolerance in all places, so the\n # simplification never moves a point inside the original\n # shape. In practice half of the tolerance is enough to\n # acheive this.\n self.simplification_tolerance_in_m\n / 2\n )\n - (\n # This reduces the inward buffer by an additional fixed\n # ammount. This helps ensure we bound very small polygons\n # entirely, while not making a significant difference to\n # large polygons.\n 15\n )\n )\n\n @cached_property\n def simplification_tolerance_in_m(self):\n \"\"\"\n Calculates a tolerance (in metres) for how much a point can\n deviate from a line joining its two neighbours. Larger and more\n complex polygons get a wider tolerance, in order to keep the\n point count down. See also\n https://shapely.readthedocs.io/en/stable/manual.html#object.simplify\n \"\"\"\n return self.perimeter_length / self.perimeter_to_simplification_ratio\n\n @cached_property\n def smooth(self):\n \"\"\"\n Fills in areas which aren’t covered by the polygons, but would\n likely receive the broadcast anyway because of the bleed. This\n includes very convex areas like harbours, and places where two\n polygons are close to touching each other. By removing detail in\n these areas we can preserve it in places where it’s more\n relevant.\n \"\"\"\n return (\n self.bleed_by(self.buffer_outward_in_m)\n .bleed_by(-1 * self.buffer_inward_in_m)\n .remove_smaller_than(area_in_square_metres=1)\n )\n\n @cached_property\n def simplify(self):\n \"\"\"\n Reduces the number of points in a polygon. See\n https://shapely.readthedocs.io/en/stable/manual.html#object.simplify\n \"\"\"\n return Polygons(\n [polygon.simplify(self.simplification_tolerance_in_m) for polygon in self.utm_polygons],\n utm_crs=self.utm_crs,\n )\n\n def bleed_by(self, distance_in_m):\n \"\"\"\n Expands the area of each polygon to give an estimation of how\n far a broadcast would bleed into neighbouring areas.\n \"\"\"\n return Polygons(\n union_polygons(\n [\n polygon.buffer(\n distance_in_m,\n resolution=4,\n join_style=JOIN_STYLE.round,\n )\n for polygon in self.utm_polygons\n ]\n ),\n utm_crs=self.utm_crs,\n )\n\n @cached_property\n def remove_too_small(self):\n \"\"\"\n Filters out polygons below a certain area. Useful for removing\n artefacts from datasets that haven’t been cleaned up properly,\n often by trying to automatically subtract the shoreline from the\n land.\n \"\"\"\n return self.remove_smaller_than(self.minimum_area_size_square_metres)\n\n def remove_smaller_than(self, area_in_square_metres):\n return Polygons(\n [polygon for polygon in self.utm_polygons if polygon.area > area_in_square_metres], utm_crs=self.utm_crs\n )\n\n @cached_property\n def as_coordinate_pairs_long_lat(self):\n \"\"\"\n For formats that specify coordinates in latitude/longitude\n order, for example leaflet.js.\n \"\"\"\n return [\n [\n [\n round(x, self.output_precision_in_decimal_places),\n round(y, self.output_precision_in_decimal_places),\n ]\n for x, y in coords\n ]\n for coords in self.as_wgs84_coordinates\n ]\n\n @property\n def as_wgs84_coordinates(self):\n if all(isinstance(polygon, list) for polygon in self):\n return self.polygons\n return [\n self.transform_coords(\n polygon.exterior.coords,\n transformer=self.transform_to_wgs84,\n )\n for polygon in self\n ]\n\n @cached_property\n def as_coordinate_pairs_lat_long(self):\n \"\"\"\n For formats that specify coordinates in latitude/longitude\n order, for example CAP XML.\n \"\"\"\n return [[[y, x] for x, y in coordinate_pairs] for coordinate_pairs in self.as_coordinate_pairs_long_lat]\n\n @cached_property\n def point_count(self):\n \"\"\"\n Total number of points in all polygons.\n \"\"\"\n return len(list(itertools.chain(*self.as_coordinate_pairs_long_lat)))\n\n @property\n def estimated_area(self):\n \"\"\"\n Area of all polygons. Only an estimate because it does an\n approximate conversion of degrees to square miles for UK\n latitudes, rather than a projection.\n \"\"\"\n return sum(polygon.area for polygon in self.utm_polygons)\n\n def ratio_of_intersection_with(self, polygons):\n \"\"\"\n Given another Polygons object, this works how much the two\n overlap, as a fraction of the area of this Polygons object.\n It assumes that neither of the objects already contain\n overlapping polygons.\n \"\"\"\n if self.estimated_area == 0:\n return 0\n return sum(intersection.area for intersection in self.intersection_with(polygons)) / self.estimated_area\n\n def intersection_with(self, polygons):\n for comparison in polygons.utm_polygons:\n for polygon in self.utm_polygons:\n yield polygon.intersection(comparison)\n\n def intersects(self, polygons):\n for comparison in polygons.utm_polygons:\n for polygon in self.utm_polygons:\n if polygon.intersects(comparison):\n return True\n return False\n\n\ndef flatten_polygons(polygons):\n if isinstance(polygons, GeometryCollection):\n return []\n if isinstance(polygons, MultiPolygon):\n return [p for p in polygons.geoms]\n else:\n return [polygons]\n\n\ndef union_polygons(polygons):\n return flatten_polygons(unary_union(polygons))\n","sub_path":"notifications_utils/polygons.py","file_name":"polygons.py","file_ext":"py","file_size_in_byte":14228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"149476647","text":"\n\n#calss header\nclass _SEMITIC():\n\tdef __init__(self,): \n\t\tself.name = \"SEMITIC\"\n\t\tself.definitions = [u'relating to the race of people that includes Arabs and Jews, or to their languages: ', u'Jewish', u'used to refer to races such as the Babylonians and Phoenicians that existed in ancient times']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_semitic.py","file_name":"_semitic.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"322220114","text":"import csv\ndatasets = [\"android\", \"apple\", \"askubuntu\", \"quora\", \"sprint\" , \"superuser\"]\nfor dataset in datasets:\n\tpath = \"data/\"+dataset +\"/combined/\"\n\tfull= path+\"full_converted.csv\"\n\ttrain= path+\"train_converted.csv\"\n\ttest= path +\"test_converted.csv\"\n\n\twith open(full) as myfile:\n\t\treader = csv.reader(myfile, delimiter=',')\n\t\tcount = 0\n\t\tfor row in reader:\n\t\t\tcount +=1\n\n\tnesbat = 4./5\n\n\ttrainsize = int (nesbat* count)\n\n\n\ttrainfile= open(train, \"wb\" )\n\ttrainwriter = csv.writer(trainfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n\ttrainwriter.writerow([\"id\", \"qid1\", \"qid2\", \"question1\", \"question2\", \"is_duplicate\"])\n\n\ttestfile= open(test, \"wb\" )\n\ttestwriter = csv.writer(testfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n\ttestwriter.writerow([\"id\", \"qid1\", \"qid2\", \"question1\", \"question2\", \"is_duplicate\"])\n\n\twith open(full) as myfile:\n\t\treader = csv.reader(myfile, delimiter=',')\n\t\tcount = 0\n\t\tfor row in reader:\n\t\t\tif count ==0 :\n\t\t\t\tcount+=1\n\t\t\t\tcontinue\n\t\t\tif count < trainsize :\n\t\t\t\ttrainwriter.writerow([row[0] , row[1] , row[2] , row[3], row[4], row[5]] )\n\t\t\telse:\n\t\t\t\ttestwriter.writerow(row)\n\t\t\tcount +=1\n","sub_path":"visualization/splitfulldataset.py","file_name":"splitfulldataset.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"82754578","text":"\"\"\"autotestpy3 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom apitest import views\nfrom product import proviews\nfrom set import setviews\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('test/', views.test),\n path('login/', views.login),\n path('home/', views.home),\n path('logout/', views.logout),\n path('product_manage/', proviews.product_manage),\n path('apitest_manage/', views.apitest_manage),\n path('apistep_manage/', views.apistep_manage),\n path('apis_manage/', views.apis_manage),\n path('set_manage/', setviews.set_manage),\n path('set_user/', setviews.set_user),\n path('test_report/', views.test_report),\n path('left/', views.left),\n path('apisearch/', views.apisearch),\n path('apissearch/', views.apissearch),\n path('setsearch/', setviews.setsearch),\n path('productsearch/', proviews.productsearch),\n path('welcome/', views.welcome),\n path('apistep_manage/', views.apistep_manage,name='apistep_manage'),\n]\n","sub_path":"autotestpy3/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"189328683","text":"import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email.mime.text import MIMEText\nfrom email import encoders\n\ngmail_user = 'dvhs.makerspace@gmail.com'\n\nsent_from = gmail_user\nto = 'vishakh.arora29@gmail.com'\nsubject = 'Python Mail Test'\nbody = 'mail test; this is the body\\nThanks,\\nSan Ramon Makerspace'\n\nemail_text = \"\"\"\\\nFrom: %s\nTo: %s\nSubject: %s\n\n%s\n\"\"\" % (sent_from, to, subject, body)\n\ndef createMessage(subject, text=None):\n msg = MIMEMultipart()\n msg['Subject'] = subject\n if text != None:\n msg.attach(MIMEText(text))\n return msg\n\ntry:\n server = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server.ehlo()\n server.login(gmail_user, gmail_password)\n msg = createMessage(subject, body)\n server.sendmail(sent_from, to, msg.as_string())\n server.close()\n\n print('Email sent!')\nexcept Exception as e:\n print(e)\n","sub_path":"SRVUSD-Lockers/DV-Lockers/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"85998380","text":"class Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n n = len(s)\n d = set()\n for i in range(k):\n for j in range(n - i):\n d.add(s[j: j + i + 1])\n\n for i in range(1 << (k + 1) - 1):\n f = ''\n t = i\n while t > 0:\n f = chr(48 + (t & 1)) + f\n t = t >> 1\n\n f = '0' * (k - len(f)) + f\n if f not in d:\n return False\n return True\n\n\nif __name__ == '__main__':\n print(Solution().hasAllCodes(s=\"0000000001011100\", k=4))\n","sub_path":"src/leetcode/P1461.py","file_name":"P1461.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"605819038","text":"import logging\nfrom unittest import TestCase\nfrom unittest.mock import Mock\n\nfrom notify import build_dispatcher\nfrom notify.backends import Backend, BackendFactory\nfrom notify.config import Config, SelectedBackend, SelectedStrategy, Stack\nfrom notify.strategies import StrategyFactory\n\n\nclass TestIntegrationDispatcher(TestCase):\n def test(self):\n strategy = Mock(['should_notify', 'timeout'])\n strategy.should_notify = Mock(return_value=True)\n strategy.timeout = 42\n\n strategy_factory = Mock(spec=StrategyFactory)\n strategy_factory.create.return_value = strategy\n\n backend = Mock(spec=Backend)\n backend.notify = Mock()\n\n backend_factory = Mock(spec=BackendFactory)\n backend_factory.create.return_value = backend\n\n cfg = Config(notifications_backend=SelectedBackend(\"test\"), logger_name=\"\",\n logger_level=logging.getLevelName(logging.CRITICAL),\n notifications_strategy=SelectedStrategy(\"test\", args=['42']),\n success_title=\"\",\n success_message=\"\",\n failure_title=\"#fail (in 0s)\",\n failure_message=\"{command_line}\")\n\n stack = Stack([cfg])\n\n d = build_dispatcher(\n stack=stack,\n strategy_factory=strategy_factory,\n backend_factory=backend_factory,\n logger=logging.getLogger(__name__)\n )\n\n d.dispatch('set-command-complete-timeout', [\"1\"])\n self.assertEqual([1], stack.notifications_strategy.args)\n\n d.dispatch('before-command', ['ls -l'])\n d.dispatch('after-command', ['1'])\n\n backend.notify.assert_called_once()\n\n n = backend.notify.call_args[0][0]\n\n self.assertEqual('#fail (in 0s)', n.title)\n self.assertEqual('ls -l', n.message)\n self.assertIsNone(n.icon)\n self.assertIsNone(n.sound)\n","sub_path":"notify/test_integration_dispatcher.py","file_name":"test_integration_dispatcher.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"604982313","text":"from collections import defaultdict\nfrom .reference import Reference\nfrom .entity import Entity\nfrom .relationship import Relationship\n\nfrom six import string_types as basestring\n\n\nclass OBOParser(object):\n def __init__(self, handle):\n self.handle = handle\n self.terms = {}\n self.current_term = None\n self.parse()\n\n def pack(self):\n if self.current_term is None:\n return\n entity = Entity(self, **{k: v[0] if len(v) == 1 else v for k, v in self.current_term.items()})\n try:\n is_as = entity['is_a']\n if isinstance(is_as, basestring):\n is_as = Reference.fromstring(is_as)\n # self[is_as].children.append(entity)\n else:\n is_as = map(Reference.fromstring, is_as)\n # for term in is_as:\n # self[term].children.append(entity)\n entity['is_a'] = is_as\n except KeyError:\n pass\n try:\n relationships = entity['relationship']\n if not isinstance(relationships, list):\n relationships = [relationships]\n relationships = [Relationship.fromstring(r) for r in relationships]\n for rel in relationships:\n entity[rel.predicate] = rel\n except KeyError:\n pass\n self.terms[entity['id']] = entity\n self.current_term = None\n\n def _connect_parents(self):\n for term in self.terms.values():\n try:\n if isinstance(term.is_a, Reference):\n self.terms[term.is_a].children.append(term)\n else:\n for is_a in term.is_a:\n self.terms[is_a].children.append(term)\n except KeyError:\n continue\n\n def parse(self):\n for line in self.handle.readlines():\n line = line.decode('utf-8')\n line = line.strip()\n if not line:\n continue\n elif line == \"[Typedef]\":\n if self.current_term is not None:\n self.pack()\n self.current_term = None\n elif line == \"[Term]\":\n if self.current_term is not None:\n self.pack()\n self.current_term = defaultdict(list)\n else:\n if self.current_term is None:\n continue\n key, sep, val = line.partition(\":\")\n self.current_term[key].append(val.strip())\n self.pack()\n self._connect_parents()\n\n def __getitem__(self, key):\n return self.terms[key]\n\n def __iter__(self):\n return iter(self.terms.items())\n","sub_path":"psims/controlled_vocabulary/obo.py","file_name":"obo.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"429371274","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n 如果向子进程发送信号,但却不知道他们的进程ID,可以使用一个进程组关联这些子进程,使他们能一同收到信号\n\n 进程组使用 os.setpgrp() 创建,将进程组ID设置为当前进程的进程ID\n\n 所有子进程都会从其父进程继承进程组\n\n 由于这个组只能在由 Popen 及其子进程创建的 shell 中设置,所以不能在创建 Popen 的同一进程中调用 os.setpgrp()\n\n 实际上,这个函数要作为 preexec_fn 参数传至 Popen,以便新进程执行 fork() 之后运行,之后才能使用 exec() 运行 shell\n\n 要向整个进程组发送信号,可以使用 os.killpg() 并提供 Popen 实例的 pid 值\n\n\n 事件序列如下:\n\n 1. 父进程实例化 Popen\n 2. Popen 实例创建一个新进程\n 3. 这个新进程运行 os.setpgrp()\n 4. 这个新进程运行 exec 以启动 shell\n 5. shell 运行 shell 脚本\n 6. shell 脚本再次创建新进程,该进程执行 Python\n 7. Python 运行 signal_child.py\n 8. 父进程使用 shell 的 pid 向进程组发送信号\n 9. shell 和 python 进程收到信号\n 10. shell 忽略该信号\n 11. 运行 signal_child.py 的 Python 进程调用信号处理器\n\"\"\"\n\nimport os\nimport signal\nimport subprocess\nimport tempfile\nimport time\nimport sys\n\n\ndef show_setting_prgrp():\n print('Calling os.setpgrp() from {}'.format(os.getpid()))\n os.setpgrp()\n print('Process group is now {}'.format(os.getpid(), os.getpgrp()))\n sys.stdout.flush()\n\n\nscript = '''#!/bin/sh\necho \"Shell script in process $$\"\nset -x\npython3 signal_child.py\n'''\nscript_file = tempfile.NamedTemporaryFile('wt')\nscript_file.write(script)\nscript_file.flush()\n\nproc = subprocess.Popen(\n ['sh', script_file.name],\n preexec_fn=show_setting_prgrp\n)\n\nprint('PARENT : Pausing before signaling {}...'.format(proc.pid))\n\nsys.stdout.flush()\n\ntime.sleep(1)\n\nprint('PARENT : Signaling process group {}'.format(proc.pid))\n\nsys.stdout.flush()\n\nos.killpg(proc.pid, signal.SIGUSR1)\n\ntime.sleep(3)\n\n# Result :\n\n# Calling os.setpgrp() from 3229\n# Process group is now 3229\n# PARENT : Pausing before signaling 3229...\n# Shell script in process 3229\n# + python3 signal_child.py\n# CHILD 3230: Setting up signal handler\n# CHILD 3230: Pausing to wait for signal\n# PARENT : Signaling process group 3229\n# CHILD 3230: Received USR1\n","sub_path":"concurrent/subprocess/signaling_between_processes/subprocess_signal_setgrp.py","file_name":"subprocess_signal_setgrp.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"242861194","text":"from models.user import User\n\n\ndef main():\n \"\"\"Start.\"\"\"\n # u = User(login=\"Bob\", password=\"adhjoaskdj12312\", about=\"About Bob\")\n # print(u.login, u.about, u)\n # #u.save()\n\n # users = [\n # +,\n # User(login=\"Derek\", password=\"Derekadhjoaskdj12312\", about=\"About Derek\"),\n # User(login=\"Josh\", password=\"Joshadhjoaskdj12312\", about=\"About Josh\"),\n # ]\n # # print(users)\n\n # for u in users:\n # u.save()\n\n users = User.all() # [User(), User(),...]\n print(users)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day5/Lect17/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"453500619","text":"class Statistic:\n def __init__(self, seconds, level, variables, used, original, conflicts, learned, limit,\n agility, MB):\n self.MB = MB\n self.agility = agility\n self.limit = limit\n self.learned = learned\n self.conflicts = conflicts\n self.used = used\n self.original = original\n self.variables = variables\n self.level = level\n self.seconds = seconds\n\n\n def get_data(self):\n return [self.seconds,\n self.level,\n self.variables,\n self.used,\n self.original,\n self.conflicts,\n self.learned,\n self.limit,\n self.agility,\n self.MB]\n\n\n def __str__(self):\n return \"[\" + \\\n self.seconds + \", \" + \\\n self.level + \", \" + \\\n self.variables + \", \" + \\\n self.used + \", \" + \\\n self.original + \", \" + \\\n self.conflicts + \", \" + \\\n self.learned + \", \" + \\\n self.limit + \", \" + \\\n self.agility + \", \" + \\\n self.MB + \", \" + \\\n \"]\"\n","sub_path":"solver/statistic.py","file_name":"statistic.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"608375824","text":"import tensorflow as tf\nimport numpy as np\n\nW1 = tf.Variable(np.arange(216).reshape((3, 3, 3, 8)), dtype=tf.float32, name=\"W1\")\nW2 = tf.Variable(np.arange(1152).reshape((3, 3, 8, 16)), dtype=tf.float32, name=\"W2\")\n\nsaver = tf.train.Saver()\nwith tf.Session() as sess:\n saver.restore(sess, \"./model.ckpt\")\n print(\"weights:\", sess.run(W1[0][0]))\n #print(\"biases:\", sess.run(W2))","sub_path":"read_variable.py","file_name":"read_variable.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"564955996","text":"import numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom PIL import Image\n\nimport cv2\nimport time\n\n\n# This is needed since the notebook is stored in the object_detection folder.\n# sys.path.append(\"..\")\nfrom object_detection.utils import ops as utils_ops\n\nfrom object_detection.utils import label_map_util\n\nfrom object_detection.utils import visualization_utils as vis_util\n\n#if tf.__version__ < '1.4.0':\n# raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')\n\nprint(\"OpenCV version : {0}\".format(cv2.__version__))\n\n# Should run under docker container from tensorflow_object_detection\nROOT = '/opt/tf_model/research/object_detection/'\n\nTEST_DIR='/home/lenovo/tensorflow3/test/ssd_mobilenet_v1_coco_2018_01_28/testing/image_2/'\nRESULT_DIR='/home/lenovo/tensorflow3/test/ssd_mobilenet_v1_coco_2018_01_28/result/'\n\n# Download pre-train SSD-MobileNet model from\n# http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_2017_11_17.tar.gz\n# What model to download.\nMODEL_NAME = 'object_detection/ssd_kitti'\nMODEL_FILE = MODEL_NAME + '.tar.gz'\nDOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = os.path.join('object_detection', 'data', 'kitti_map.pbtxt')\n\nNUM_CLASSES = 3\n\n\n \ndef detect_objects(image_np, sess, detection_graph):\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n\n # Each box represents a part of the image where a particular object was detected.\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n\n t1 = cv2.getTickCount()\n # Actual detection.\n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n t2 = cv2.getTickCount()\n print((t2 - t1) / cv2.getTickFrequency())\n\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8)\n t2 = cv2.getTickCount()\n print(cv2.getTickFrequency()/(t2 - t1))\n return image_np\n\n\nif __name__ == '__main__':\n # This is needed since the notebook is stored in the object_detection folder.\n\n #video_capture = cv2.VideoCapture(0)\n #if not video_capture.isOpened():\n # print('No video camera found')\n # exit()\n ##_____________________Ven___Displaying the fps________________________##\n \n # Find OpenCV version\n (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')\n \n # With webcam get(CV_CAP_PROP_FPS) does not work.\n # Let's see for ourselves.\n \n #if int(major_ver) < 3 :\n # fps = video_capture.get(cv2.cv.CV_CAP_PROP_FPS)\n # print (\"Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}\".format(fps))\n # else :\n # fps = video_capture.get(cv2.CAP_PROP_FPS)\n # print (\"Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}\".format(fps))\n \n \n # Number of frames to capture\n #num_frames = 120;\n \n \n #print (\"Capturing {0} frames\".format(num_frames))\n \n # Start time\n #start = time.time()\n \n # Grab a few frames\n #for i in range(0, num_frames) :\n # ret, frame = video_capture.read()\n \n # End time\n #end = time.time()\n \n # Time elapsed\n #seconds = end - start\n #print (\"Time taken : {0} seconds\".format(seconds))\n \n # Calculate frames per second\n #fps = num_frames / seconds;\n #print (\"Estimated frames per second : {0}\".format(fps));\n ##___________________________________________________________##\n\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\n\n category_index = label_map_util.create_category_index(categories)\n with detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n # Definite input and output Tensors for detection_graph\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\n detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n\n for filename in os.listdir(TEST_DIR):\n img_name = os.path.join(TEST_DIR,filename)\n frame = cv2.imread(img_name)\n #frame = cv2.imread(TEST_DIR+'00'+str(i)+'.png')\n #height, width, channels = frame_org.shape\n #frame = frame_org[0:height, 0:(int(width/2))]\n #frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n result_rgb = detect_objects(frame, sess, detection_graph)\n\n #result_bgr = cv2.cvtColor(result_rgb, cv2.COLOR_RGB2BGR)\n\n cv2.imshow('image', result_rgb)\n cv2.imwrite(RESULT_DIR+filename,result_rgb)\n\n #if cv2.waitKey(1) & 0xFF == ord('q'): ##Ven___Added to break the loop\n # break\n\n video_capture.release()\ncv2.destroyAllWindows()\n\n","sub_path":"kitti_test_2.py","file_name":"kitti_test_2.py","file_ext":"py","file_size_in_byte":6891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"266376719","text":"import os\nimport pickle\nimport pprint\npath = '/home/tmp_data_dir/zhuzezhou/codalab/CTest'\nlist1 = os.listdir(path)\nlist1 = sorted(list1)\noutput = open('test_prediction.pkl','wb')\nfp = open('test_label_result','r')\ndic = {}\ncount = 0\nfor line in fp.readlines():\n\tline = line.strip().split('\\n')\n\tif int(line[0]) == 0:\n\t\tdic[list1[count]] = 'fake'\n\telse:\n\t\tdic[list1[count]] = 'true'\n\tcount = count + 1\npickle.dump(dic, output)\n\noutput.close()\nfp.close()\n\n\npkl_file = open('test_prediction.pkl', 'rb')\n\ndata1 = pickle.load(pkl_file)\npprint.pprint(data1)\n\npkl_file.close()\n\n","sub_path":"pro_result.py","file_name":"pro_result.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"87496420","text":"'''\n@Author: xiaoming\n@Date: 2018-12-29 11:28:34\n@LastEditors: xiaoming\n@LastEditTime: 2019-01-02 10:24:10\n@Description: 测试过程日志\n'''\nimport logging\nimport os\nimport time\nfrom logging import handlers\nfrom conditions.confing.confing import base_bath\n\n\nclass Logger(object):\n level_relations = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'crit': logging.CRITICAL\n }\n\n def __init__(self, filename, level='info', fmt=\"[%(asctime)s]-%(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s\"):\n self.logger = logging.getLogger(filename)\n log_format = logging.Formatter(fmt)\n self.logger.setLevel(self.level_relations.get(level))\n sh = logging.StreamHandler()\n sh.setFormatter(log_format)\n file = handlers.WatchedFileHandler(filename, encoding='UTF-8')\n file.setFormatter(log_format)\n self.logger.addHandler(sh)\n self.logger.addHandler(file)\n\n\ndef setup_logger(logfile, loglevel):\n log = Logger(logfile, level=loglevel)\n return log\n\n\nif not os.path.exists('{}/log'.format(base_bath)):\n os.makedirs('{}/log'.format(base_bath))\nlog = setup_logger('{}/log/{}.log'.format(base_bath, str(\n time.strftime(\"%Y-%m-%d\", time.localtime()))), 'info').logger\n\n\nif __name__ == '__main__':\n log.info(\"11111\")","sub_path":"conditions/common/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"573628612","text":"\"\"\"Process notes and store results in database.\n\nPreprocessors insert metadata blocks into notes as code blocks.\nThey are mainly used to pass note metadata to Pandoc filters even when\nthe input is the concatenation of several files.\n\"\"\"\n\nfrom configparser import ConfigParser\nfrom hashlib import sha256\nfrom pathlib import Path\nfrom sqlite3 import Connection\nimport sys\nfrom typing import Any, Sequence\n\nfrom . import utils\nfrom .batch import Batch\nfrom .data import process_csvs\nfrom .scan import build_command\nfrom .secparse import parse_sections, SectionParser\n\n\nDOKUWIKI_TEMPLATE = \"\"\"\n\n[slipbox-metadata]\n{}\n\n\"\"\"\n\n# NOTE Some brackets are escaped.\nLATEX_TEMPLATE = r\"\"\"\n\\begin{{verbatim}}\n[slipbox-metadata]\n{}\n\\end{{verbatim}}\n\"\"\"\n\nMARKDOWN_TEMPLATE = \"\"\"\n```\n[slipbox-metadata]\n{}\n```\n\"\"\"\n\nMEDIAWIKI_TEMPLATE = \"\"\"\n
[slipbox-metadata]\n{}
\n\"\"\"\n\nORG_TEMPLATE = \"\"\"\n#+begin_example\n[slipbox-metadata]\n{}\n#+end_example\n\"\"\"\n\nRST_TEMPLATE = \"\"\"\n.. code::\n\n [slipbox-metadata]\n {}\n\n\"\"\"\n\nT2T_TEMPLATE = MARKDOWN_TEMPLATE\n\nTEXTILE_TEMPLATE = \"\"\"\nbc. [slipbox-metadata]\n{}\n\n\"\"\"\n\nMETADATA_TEMPLATES = {\n \".dokuwiki\": DOKUWIKI_TEMPLATE,\n \".latex\": LATEX_TEMPLATE,\n \".markdown\": MARKDOWN_TEMPLATE,\n \".md\": MARKDOWN_TEMPLATE,\n \".mdown\": MARKDOWN_TEMPLATE,\n \".org\": ORG_TEMPLATE,\n \".rst\": RST_TEMPLATE,\n \".t2t\": T2T_TEMPLATE,\n \".tex\": LATEX_TEMPLATE,\n \".textile\": TEXTILE_TEMPLATE,\n \".wiki\": MEDIAWIKI_TEMPLATE,\n}\n\n\ndef render_metadata(template: str, **fields: Any) -> str:\n \"\"\"Render metadata code block using template.\"\"\"\n body = '\\n'.join(\n f\"{k}={v}\"\n for k, v in fields.items()\n )\n return template.format(body)\n\n\ndef preprocess(template: str, *sources: Path, basedir: Path) -> str:\n \"\"\"Preprocess notes (sources) by inserting code blocks generated\n using the template.\n \"\"\"\n def preprocess_single(source: Path) -> str:\n \"\"\"Preprocess a single file.\"\"\"\n content = source.read_bytes()\n filename = str(source.relative_to(basedir))\n _hash = sha256(content).hexdigest()\n metadata = render_metadata(template, filename=filename, hash=_hash)\n return metadata + content.decode(encoding=\"utf-8\")\n return \"\".join(preprocess_single(source) for source in sources)\n\n\ndef store_html(conn: Connection,\n html: str,\n sources: Sequence[Path]) -> None:\n \"\"\"Insert HTML sections into Notes table.\"\"\"\n if not html.strip() or not sources:\n return\n cur = conn.cursor()\n\n def callback(this: SectionParser) -> None:\n \"\"\"Callback for parse_sections.\"\"\"\n cur.execute(\n \"UPDATE Notes SET html = ? WHERE id = ?\",\n (this.section, this.id_)\n )\n parse_sections(html, callback)\n\n\ndef create_preprocessed_input(\n tempdir: Path,\n batch: Batch,\n basedir: Path\n) -> Path:\n \"\"\"Create preprocessed input to be passed to Pandoc.\"\"\"\n template = METADATA_TEMPLATES.get(batch.extension, MARKDOWN_TEMPLATE)\n path = tempdir/(\"input\" + batch.extension)\n path.write_text(\n preprocess(template, *batch.paths, basedir=basedir),\n encoding=\"utf-8\"\n )\n return path\n\n\ndef process_batch(conn: Connection,\n batch: Batch,\n config: ConfigParser,\n basedir: Path) -> None:\n \"\"\"Process batch of input notes.\"\"\"\n with utils.temporary_directory() as tempdir:\n preprocessed_input = create_preprocessed_input(tempdir, batch, basedir)\n html = tempdir/\"temp.html\"\n cmd = build_command(preprocessed_input, str(html), basedir,\n config.get(\"slipbox\", \"content_options\"))\n retcode = utils.run_command(cmd, cwd=tempdir)\n if retcode:\n print(\"Scan failed.\", file=sys.stderr)\n return\n process_csvs(conn, tempdir)\n store_html(conn, html.read_text(encoding=\"utf-8\"), batch.paths)\n conn.commit()\n","sub_path":"cli/slipbox/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"218971004","text":"import PhysicsTools.HeppyCore.framework.config as cfg\nfrom PhysicsTools.HeppyCore.framework.config import printComps\n\n# Tau-tau analyzers\nfrom CMGTools.H2TauTau.proto.analyzers.TauEleAnalyzer import TauEleAnalyzer\nfrom CMGTools.H2TauTau.proto.analyzers.H2TauTauTreeProducerTauEle import H2TauTauTreeProducerTauEle\nfrom CMGTools.H2TauTau.proto.analyzers.DYLLReweighterTauEle import DYLLReweighterTauEle\nfrom CMGTools.H2TauTau.proto.analyzers.TauDecayModeWeighter import TauDecayModeWeighter\nfrom CMGTools.H2TauTau.proto.analyzers.TauFakeRateWeighter import TauFakeRateWeighter\nfrom CMGTools.H2TauTau.proto.analyzers.LeptonWeighter import LeptonWeighter\nfrom CMGTools.H2TauTau.proto.analyzers.SVfitProducer import SVfitProducer\n\n# common configuration and sequence\nfrom CMGTools.H2TauTau.htt_ntuple_base_cff import commonSequence, genAna, dyJetsFakeAna, puFileData, puFileMC, eventSelector\n\n# e-tau specific configuration settings\n\n# 'Nom', 'Up', 'Down', or None\nshift = None\nsyncntuple = False\ncomputeSVfit = False\nproduction = True # production = True run on batch, production = False run locally\n\n#production = True # production = True run on batch, production = False run locally\n\n# When ready, include weights from CMGTools.H2TauTau.proto.weights.weighttable\n\n# hlt_tauEffWeight_mc = 'effTau_eTau_MC_2012ABCDSummer13'\n# hlt_tauEffWeight = 'effTau_eTau_Data_2012ABCDSummer13'\n# hlt_eleEffWeight_mc = 'effEle_eTau_MC_2012ABCD'\n# hlt_eleEffWeight = 'effEle_eTau_Data_2012ABCDSummer13'\n\nhlt_tauEffWeight_mc = None\nhlt_tauEffWeight = None\nhlt_eleEffWeight_mc = None\nhlt_eleEffWeight = None\n\ndyJetsFakeAna.channel = 'et'\n\n# Define e-tau specific modules\n\ntauEleAna = cfg.Analyzer(\n TauEleAnalyzer,\n name='TauEleAnalyzer',\n pt1=23,\n eta1=2.1,\n iso1=0.1,\n looseiso1=9999.,\n pt2=20,\n eta2=2.3,\n iso2=1.5,\n looseiso2=9999.,\n m_min=10,\n m_max=99999,\n dR_min=0.5,\n from_single_objects=True,\n verbose=False\n)\n\ndyLLReweighterTauEle = cfg.Analyzer(\n DYLLReweighterTauEle,\n name='DYLLReweighterTauEle',\n # 2012\n W1p0PB=1., # 1.37, # weight for 1 prong 0 Pi Barrel\n W1p0PE=1., # 1.11,\n W1p1PB=1., # 2.18,\n W1p1PE=1., # 0.47,\n verbose=False\n)\n\ntauDecayModeWeighter = cfg.Analyzer(\n TauDecayModeWeighter,\n name='TauDecayModeWeighter',\n legs=['leg2']\n)\n\ntauFakeRateWeighter = cfg.Analyzer(\n TauFakeRateWeighter,\n name='TauFakeRateWeighter'\n)\n\ntauWeighter = cfg.Analyzer(\n LeptonWeighter,\n name='LeptonWeighter_tau',\n effWeight=None,\n effWeightMC=None,\n lepton='leg2',\n verbose=False,\n disable=True,\n)\n\neleWeighter = cfg.Analyzer(\n LeptonWeighter,\n name='LeptonWeighter_ele',\n effWeight=None,\n effWeightMC=None,\n lepton='leg1',\n verbose=False,\n disable=True,\n idWeight=None,\n isoWeight=None\n)\n\ntreeProducer = cfg.Analyzer(\n H2TauTauTreeProducerTauEle,\n name='H2TauTauTreeProducerTauEle'\n)\n\nsyncTreeProducer = cfg.Analyzer(\n H2TauTauTreeProducerTauEle,\n name='H2TauTauSyncTreeProducerTauEle',\n varStyle='sync',\n # skimFunction='event.isSignal'\n)\n\n\nsvfitProducer = cfg.Analyzer(\n SVfitProducer,\n name='SVfitProducer',\n # integration='VEGAS',\n integration='MarkovChain',\n # verbose=True,\n # order='21', # muon first, tau second\n l1type='ele',\n l2type='tau'\n)\n\n###################################################\n### CONNECT SAMPLES TO THEIR ALIASES AND FILES ###\n###################################################\n# from CMGTools.H2TauTau.proto.samples.phys14.connector import httConnector\n# my_connect = httConnector('htt_6mar15_manzoni_nom', 'htautau_group',\n# '.*root', 'et', production=production)\n# my_connect.connect()\n# MC_list = my_connect.MC_list\n\nfrom CMGTools.RootTools.samples.samples_13TeV_74X import TT_pow, DYJetsToLL_M50, WJetsToLNu, WJetsToLNu_HT100to200, WJetsToLNu_HT200to400, WJetsToLNu_HT400to600, WJetsToLNu_HT600toInf, QCDPtEMEnriched, WWTo2L2Nu, ZZp8, WZp8, SingleTop, QCDPtbcToE\nfrom CMGTools.RootTools.samples.samples_13TeV_DATA2015 import SingleElectron_Run2015B_17Jul, SingleElectron_Run2015B\nfrom CMGTools.H2TauTau.proto.samples.spring15.triggers_tauEle import mc_triggers as mc_triggers_et\nfrom CMGTools.H2TauTau.proto.samples.spring15.triggers_tauEle import data_triggers as data_triggers_et\n\n# from CMGTools.H2TauTau.proto.samples.spring15.higgs import HiggsGGH125, HiggsVBF125, HiggsTTH125\n\nfrom CMGTools.RootTools.utils.splitFactor import splitFactor\n\n# Get all heppy options; set via \"-o production\" or \"-o production=True\"\n\n\n\n\nsamples = [TT_pow, DYJetsToLL_M50, WJetsToLNu, WJetsToLNu_HT100to200, WJetsToLNu_HT200to400, WJetsToLNu_HT400to600, WJetsToLNu_HT600toInf]\n\nsamples = [TT_pow, DYJetsToLL_M50, WJetsToLNu, WWTo2L2Nu, ZZp8, WZp8]\n\n# samples += [HiggsGGH125, HiggsVBF125, HiggsTTH125]\nsamples += SingleTop + QCDPtEMEnriched + QCDPtbcToE\n\nsplit_factor = 1e5\n\nfor sample in samples:\n sample.triggers = mc_triggers_et\n sample.splitFactor = splitFactor(sample, split_factor)\n\ndata_list = [SingleElectron_Run2015B_17Jul, SingleElectron_Run2015B]\n\nfor sample in data_list:\n sample.triggers = data_triggers_et\n sample.splitFactor = splitFactor(sample, split_factor)\n sample.json = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions15/13TeV/Cert_246908-251883_13TeV_PromptReco_Collisions15_JSON_v2.txt'\n sample.lumi = 40.03\n\n\nfor sample in samples:\n sample.triggers = mc_triggers_et\n sample.splitFactor = splitFactor(sample, split_factor)\n\n\n\n###################################################\n### ASSIGN PU to MC ###\n###################################################\nfor mc in samples:\n mc.puFileData = puFileData\n mc.puFileMC = puFileMC\n\n###################################################\n### SET COMPONENTS BY HAND ###\n###################################################\nselectedComponents = samples\nselectedComponents = [DYJetsToLL_M50]\nselectedComponents = data_list\n# selectedComponents = mc_dict['HiggsGGH125']\n# for c in selectedComponents : c.splitFactor *= 5\n\n###################################################\n### SEQUENCE ###\n###################################################\nsequence = commonSequence\nsequence.insert(sequence.index(genAna), tauEleAna)\nsequence.append(tauDecayModeWeighter)\nsequence.append(tauFakeRateWeighter)\nsequence.append(tauWeighter)\nsequence.append(eleWeighter)\nsequence.insert(sequence.index(dyJetsFakeAna) + 1, dyLLReweighterTauEle)\nif computeSVfit:\n sequence.append(svfitProducer)\nsequence.append(treeProducer)\nif syncntuple:\n sequence.append(syncTreeProducer)\n\n###################################################\n### CHERRY PICK EVENTS ###\n###################################################\n# eventSelector.toSelect = [186583]\n# sequence.insert(0, eventSelector)\n\n###################################################\n### SET BATCH OR LOCAL ###\n###################################################\nif not production:\n cache = True\n # comp = my_connect.mc_dict['HiggsGGH125']\n # comp = ggh160\n comp = selectedComponents[0]\n selectedComponents = [comp]\n comp.splitFactor = 1\n comp.fineSplitFactor = 1\n# comp.files = comp.files[:1]\n\n\n# the following is declared in case this cfg is used in input to the\n# heppy.py script\nfrom PhysicsTools.HeppyCore.framework.eventsfwlite import Events\nconfig = cfg.Config(components=selectedComponents,\n sequence=sequence,\n services=[],\n events_class=Events\n )\n\nprintComps(config.components, True)\n\n\ndef modCfgForPlot(config):\n config.components = []\n","sub_path":"CMGTools/H2TauTau/cfgPython/et/tauEle_2015_cfg.py","file_name":"tauEle_2015_cfg.py","file_ext":"py","file_size_in_byte":7734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"92151820","text":"#\n# Copyright (c) European Molecular Biology Laboratory (EMBL)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n__author__ = ['S. Basu']\n__license__ = 'MIT'\n__date__ = '2019/08/08'\n\n\nimport os\nimport pathlib\nimport json\nimport jsonschema\nimport logging\nimport subprocess as sub\nimport time\nfrom collections import Counter\nfrom datetime import datetime\n\nfrom edna2.lib.autocryst.src.Image import ImageHandler as Im\nfrom edna2.lib.autocryst.src.cell_analysis import Cell\nfrom edna2.lib.autocryst.src.geom import Geom\nfrom edna2.lib.autocryst.src.point_group import *\nfrom edna2.lib.autocryst.src.stream import Stream\nfrom edna2.lib.autocryst.src.parser import ResultParser\n\nlogger = logging.getLogger('autoCryst')\n\n\nclass AutoCrystFEL(object):\n \"\"\"\n\n :rtype: object to run CrystFEL at ESRF or elsewhere as an automated workflow.\n One can run it as a module with required dependencies. It is part of autocryst project\n Input and output - both are json dictionaries. One can run it on commandLine.\n python run_crystfel.py --help : check how to run as commandLine, which essentially calls AutoCrystFEL\n as a module and creates necessary input dictionary based on commandLine.\n\n \"\"\"\n def __init__(self, jData):\n self._ioDict = dict()\n self._ioDict['inData'] = json.dumps(jData, default=str)\n self._ioDict['outData'] = json.dumps(dict(), default=str)\n self._ioDict['success'] = True\n self._ioDict['crystFEL_WorkingDirectory'] = None\n self.filelist = []\n return\n\n def get_inData(self):\n return json.loads(self._ioDict['inData'])\n\n def set_inData(self, jData):\n self._ioDict['inData'] = json.dumps(jData, default=str)\n\n jshandle = property(get_inData, set_inData)\n\n def get_outData(self):\n return json.loads(self._ioDict['outData'])\n\n def set_outData(self, results):\n self._ioDict['outData'] = json.dumps(results, default=str)\n\n results = property(get_outData, set_outData)\n\n def writeInputData(self, inData):\n # Write input data\n if self._ioDict['crystFEL_WorkingDirectory'] is not None:\n jsonName = \"inData_\" + self.__class__.__name__ + \".json\"\n with open(str(self.getOutputDirectory() / jsonName), 'w') as f:\n f.write(json.dumps(inData, default=str, indent=4))\n return\n\n def writeOutputData(self, results):\n self.set_outData(results)\n if self._ioDict['crystFEL_WorkingDirectory'] is not None:\n jsonName = \"outData_\" + self.__class__.__name__ + \".json\"\n with open(str(self.getOutputDirectory() / jsonName), 'w') as f:\n f.write(json.dumps(results, default=str, indent=4))\n return\n\n def setFailure(self):\n self._ioDict['success'] = False\n\n def is_success(self):\n return self._ioDict['success']\n\n def setOutputDirectory(self, path=None):\n if path is None:\n directory = self.jshandle.get('processing_directory', os.getcwd())\n self._ioDict['crystFEL_WorkingDirectory'] = pathlib.Path(directory)\n else:\n self._ioDict['crystFEL_WorkingDirectory'] = pathlib.Path(path)\n\n def getOutputDirectory(self):\n return self._ioDict['crystFEL_WorkingDirectory']\n\n @staticmethod\n def getInDataSchema():\n return {\n \"type\": \"object\",\n \"required\": [\"image_directory\", \"detectorType\", \"prefix\", \"suffix\"],\n \"properties\": {\n \"image_directory\": {\"type\": \"string\"},\n \"detectorType\": {\"type\": \"string\"},\n \"suffix\": {\"type\": \"string\"},\n \"prefix\": {\"type\": \"string\"},\n \"ImageRange\": {\"type\": \"array\",\n \"items\": {\n \"type\": \"integer\"\n }\n },\n \"listofImages\": {\"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"maxchunksize\": {\"type\": \"integer\"},\n \"processing_directory\": {\"type\": \"string\"},\n \"doSubmit\": {\"type\": \"boolean\"},\n \"doMerging\": {\"type\": \"boolean\"},\n \"GeneratePeaklist\": {\"type\": \"boolean\"},\n \"geometry_file\": {\"type\": \"string\"},\n \"unit_cell_file\": {\"type\": \"string\"},\n \"num_processors\": {\"type\": \"string\"},\n \"beamline\": {\"type\": \"string\"},\n \"indexing_method\": {\"type\": \"string\"},\n \"peak_search\": {\"type\": \"string\"},\n \"peak_info\": {\"type\": \"string\"},\n \"int_method\": {\"type\": \"string\"},\n \"peak_radius\": {\"type\": \"string\"},\n \"int_radius\": {\"type\": \"string\"},\n \"min_peaks\": {\"type\": \"string\"},\n \"min_snr\": {\"type\": \"string\"},\n \"threshold\": {\"type\": \"string\"},\n \"local_bg_radius\": {\"type\": \"string\"},\n \"min_res\": {\"type\": \"string\"},\n \"highres\": {\"type\": \"string\"},\n \"wait_time\": {\"type\": \"string\"}\n },\n }\n\n @staticmethod\n def getOutDataSchema():\n return {\n \"type\": \"object\",\n \"properties\": {\n \"QualityMetrics\": {\n \"type\": \"object\",\n \"properties\": {\n \"centering\": {\"type\": \"string\"},\n \"num_indexed_frames\": {\"type\": \"integer\"},\n \"lattice\": {\"type\": \"string\"},\n \"unique_axis\": {\"type\": \"string\"},\n \"unit_cell\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"number\"},\n },\n \"point_group\": {\"type\": \"string\"},\n \"space_group\": {\"type\": \"string\"},\n \"resolution_limit\": {\"type\": \"number\"},\n \"average_num_spots\": {\"type\": \"number\"}\n }\n },\n \"PeaksDictionary\": {\n \"type\": \"object\",\n \"properties\": {\n \"items\": {\"type\": \"array\"},\n }\n }\n }\n }\n\n @staticmethod\n def is_executable(program):\n def is_exe(filepath):\n return os.path.isfile(filepath) and os.access(filepath, os.X_OK)\n\n fpath, fname = os.path.split(program)\n if fpath:\n return is_exe(program)\n\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return True\n\n return\n\n @staticmethod\n def run_as_command(command):\n pipes = sub.Popen(command, shell=True, stdout=sub.PIPE, stderr=sub.PIPE, cwd=os.getcwd())\n stdout, stderr = pipes.communicate()\n if pipes.returncode != 0:\n err = '{0}, code {1}'.format(stderr, pipes.returncode)\n logger.error('Error:'.format(err))\n return\n\n @staticmethod\n def oarshell_submit(shellfile, crystfel_cmd):\n oar_handle = open(shellfile, 'w')\n\n oar_handle.write(\"#!/bin/bash \\n\\n\")\n\n oar_handle.write(\"#OAR -q mx \\n\")\n oar_handle.write(\"#OAR -n autoCryst \\n\")\n oar_handle.write(\"#OAR -l nodes=1, walltime=01:00:00 \\n\\n\")\n oar_handle.write(crystfel_cmd)\n oar_handle.close()\n sub.call('chmod +x %s' % shellfile, shell=True)\n\n AutoCrystFEL.run_as_command('oarsub -S %s' % shellfile)\n return\n\n @staticmethod\n def slurm_submit(shellFile, workingDir, crystfel_cmd, partition=\"low\"):\n # workingDir = str(self.getOutputDirectory())\n if workingDir.startswith(\"/mntdirect/_users\"):\n workingDir = workingDir.replace(\"/mntdirect/_users\", \"/home/esrf\")\n nodes = 1\n core = 10\n time = '1:00:00'\n mem = 8000 # 4 Gb memory by default\n script = '#!/bin/bash\\n'\n script += '#SBATCH --mem={0}\\n'.format(mem)\n script += '#SBATCH --nodes={0}\\n'.format(nodes)\n script += '#SBATCH --partition={0}\\n'.format(partition)\n script += '#SBATCH --nodes=1\\n' # Necessary for not splitting jobs! See ATF-57\n script += '#SBATCH --cpus-per-task={0}\\n'.format(core)\n script += '#SBATCH --time={0}\\n'.format(time)\n script += '#SBATCH --chdir={0}\\n'.format(workingDir)\n script += '#SBATCH --output=stdout.txt\\n'\n script += '#SBATCH --error=stderr.txt\\n'\n script += crystfel_cmd + '\\n'\n # shellFile = self.getOutputDirectory() / (jobName + '_slurm.sh')\n with open(shellFile, 'w') as f:\n f.write(script)\n f.close()\n sub.call('chmod +x %s' % shellFile, shell=True)\n \n # AutoCrystFEL.run_as_command('sbatch --wait -J autoCryst %s' %shellFile)\n\n @staticmethod\n def combine_streams():\n slurm_handle = open('tmp_cat.sh', 'w')\n slurm_handle.write(\"#!/bin/bash \\n\\n\")\n slurm_handle.write(\"cat *.stream >> alltogether.stream\")\n slurm_handle.close()\n AutoCrystFEL.run_as_command('chmod +x tmp_cat.sh')\n AutoCrystFEL.run_as_command('sbatch --wait -d singleton -p nice -J autoCryst tmp_cat.sh')\n return\n\n @staticmethod\n def partialator_cmd(stream_name, point_group, nproc):\n base_str = stream_name.split('.')\n outhkl = base_str[0] + '.hkl'\n command = 'partialator -i %s -o %s -y %s ' \\\n % (stream_name, outhkl, point_group)\n command += ' --model=unity --push-res=1.5 --iterations=1 -j %s --no-deltacchalf --no-logs' % nproc\n\n return command\n\n @staticmethod\n def check_hkl_cmd(hklfile, point_group, cellfile, rescut):\n statfile = hklfile.split('.')[0] + '_snr.dat'\n command = 'check_hkl -y %s -p %s --nshells=20 --shell-file=%s ' \\\n % (point_group, cellfile, statfile)\n command += '--lowres=20 --highres=%f %s' % (rescut, hklfile)\n\n return command\n\n @staticmethod\n def compare_hkl_cmd(hkl1, hkl2, cellfile, rescut, fom='CCstar'):\n base_str = hkl1.split('.')[0]\n statout = base_str + '_' + fom + '.dat'\n\n command = 'compare_hkl -p %s --nshells=20 --shell-file=%s ' % (cellfile, statout)\n command += '--fom=%s --lowres=20 --highres=%s ' % (fom, rescut)\n command += '%s %s' % (hkl1, hkl2)\n return command\n\n @staticmethod\n def write_cell_file(cellinfo):\n # Method to write out crystFEL formatted *.cell file, compatible with other crystFEL programs\n try:\n cwrite = open('auto.cell', 'w')\n cwrite.write('CrystFEL unit cell file version 1.0\\n\\n')\n cwrite.write('lattice_type = %s\\n' % cellinfo['lattice'])\n cwrite.write('centering = %s\\n' % cellinfo['centering'])\n cwrite.write('unique_axis = %s\\n' % cellinfo['unique_axis'])\n cwrite.write('a = %s A\\n' % cellinfo['unit_cell'][0])\n cwrite.write('b = %s A\\n' % cellinfo['unit_cell'][1])\n cwrite.write('c = %s A\\n' % cellinfo['unit_cell'][2])\n cwrite.write('al = %s deg\\n' % cellinfo['unit_cell'][3])\n cwrite.write('be = %s deg\\n' % cellinfo['unit_cell'][4])\n cwrite.write('ga = %s deg\\n' % cellinfo['unit_cell'][5])\n cwrite.close()\n\n except (OSError, KeyError) as err:\n logger.info('Cell_file_Error:{}'.format(err))\n print(\"Needed a dictionary with keys: lattice, centering, unique_axis, and unit_cell\\n\")\n print(\"unit_cell key has a list of cell parameters as value\")\n raise err\n return\n\n def datafinder(self):\n datadir = pathlib.Path(self.jshandle['image_directory'])\n listofimagefiles = self.jshandle.get('listofImages', [])\n image_range = self.jshandle.get('ImageRange', ())\n if datadir.exists():\n if len(image_range) > 0:\n for index in range(image_range[0], image_range[1]+1):\n imageName = self.jshandle['prefix'] + '{0:04d}'.format(index) + '.' + self.jshandle['suffix']\n imagePath = datadir / imageName\n self.filelist.append(imagePath.as_posix())\n elif len(listofimagefiles) != 0:\n self.filelist = listofimagefiles\n else:\n listofimagefiles = list(datadir.glob(self.jshandle['prefix'] + '*' + self.jshandle['suffix']))\n for fname in listofimagefiles:\n if 'master.h5' not in str(fname):\n self.filelist.append(fname.as_posix())\n else:\n pass\n else:\n self.setFailure()\n logger.error('dataError:{}'.format('no data found'))\n return\n\n def makeOutputDirectory(self):\n self.setOutputDirectory()\n datadir = pathlib.Path(self.jshandle['image_directory'])\n image_folder_basename = datadir.name\n image_folder_structure = datadir.parents\n procdir = self.getOutputDirectory() / image_folder_structure[0].name / image_folder_basename\n outname = datetime.now().strftime('autoCryst_%Y-%m-%d_%H-%M-%S')\n crystfel_dir = procdir / outname\n crystfel_dir.mkdir(parents=True, exist_ok=True)\n os.chdir(str(crystfel_dir))\n self.setOutputDirectory(str(crystfel_dir))\n return\n\n def make_geometry_file(self, **kwargs):\n geomfile = self.jshandle.get('geometry_file', None)\n if geomfile is None:\n image1 = type('', (), {}) # initialize image1 as an empty object\n if self.jshandle['suffix'] == 'cbf':\n image1 = Im(self.filelist[0])\n elif self.jshandle['suffix'] == 'h5':\n master_str = self.jshandle['prefix'] + '*master.h5'\n masterfile = list(pathlib.Path(self.jshandle['image_directory']).glob(master_str))[0]\n image1 = Im(str(masterfile))\n else:\n self.setFailure()\n logger.error('format_error:{}'.format('cbf/h5/cxi formats supported'))\n g = Geom(image1.imobject.headers['detector_name'][0], image1.imobject.headers['detector_name'][1])\n g.write_geomfile(image1.imobject.headers, **kwargs)\n geomfile = self.getOutputDirectory() / g.geomfilename\n else:\n geomfile = pathlib.Path(geomfile)\n return geomfile\n\n def make_list_events(self, geometryfile):\n if self.jshandle['suffix'] == 'cxi' or self.jshandle['suffix'] == 'h5':\n datalst = str(self.getOutputDirectory() / 'input.lst')\n fh = open(datalst, 'w')\n for fname in self.filelist:\n fh.write(fname)\n fh.write('\\n')\n fh.close()\n if os.path.exists(geometryfile):\n self.filelist = []\n all_events = str(self.getOutputDirectory() / 'all_events.lst')\n cmd = 'list_events -i %s -g %s -o %s' % (datalst, geometryfile, all_events)\n self.run_as_command(cmd)\n f = open(all_events, 'r')\n for line in f:\n line = line.strip('\\n')\n self.filelist.append(line)\n f.close()\n else:\n self.setFailure()\n logger.error('List_events_Error:No Geom file exists')\n else:\n # cbf files are not multi-events\n pass\n return\n\n def indexamajig_cmd(self, infile, streamfile, geometryfile):\n command = \"\"\n unitcell = self.jshandle.get('unit_cell_file', None)\n indexing_method = self.jshandle.get('indexing_method', 'xgandalf')\n peak_search = self.jshandle.get('peak_search', 'peakfinder8')\n int_method = self.jshandle.get('int_method', 'rings-grad')\n int_radius = self.jshandle.get('int_radius', '3,4,6')\n highres = self.jshandle.get('highres', '0.0')\n nproc = self.jshandle.get('num_processors', '20')\n waiting = self.jshandle.get('wait_time', '0')\n\n if self.is_executable('indexamajig'):\n command = 'indexamajig -i %s -o %s -g %s' \\\n % (infile, streamfile, geometryfile)\n command += ' --indexing=%s --peaks=%s' \\\n % (indexing_method, peak_search)\n command += ' --integration=%s --int-radius=%s -j %s --no-check-peaks --highres=%s' \\\n % (int_method, int_radius, nproc, highres)\n\n if unitcell is not None and os.path.isfile(unitcell):\n command += ' -p %s --tolerance=%s' % (unitcell, '10,10,10,1.5')\n\n if peak_search == 'cxi' or peak_search == 'hdf5':\n peak_info = self.jshandle.get('peak_info', '/data/peakinfo')\n command += ' --hdf5-peaks=%s --no-revalidate' % peak_info\n\n else:\n peak_radius = self.jshandle.get('peak_radius', '3,4,5')\n local_bg_radius = self.jshandle.get('local_bg_radius', '10')\n min_peaks = self.jshandle.get('min_peaks', '30')\n min_snr = self.jshandle.get('min_snr', '4')\n min_res = self.jshandle.get('min_res', '50')\n threshold = self.jshandle.get('threshold', '10')\n\n command += ' --peak-radius=%s --min-peaks=%s --wait-for-file=%s' \\\n % (peak_radius, min_peaks, waiting)\n command += ' --min-snr=%s --threshold=%s --local-bg-radius=%s --min-res=%s' \\\n % (min_snr, threshold, local_bg_radius, min_res)\n command += ' --no-non-hits-in-stream'\n else:\n self.setFailure()\n logger.error('Error:{}'.format('indexamajig could not be found in PATH'))\n\n return command\n\n def scale_merge(self, streamfile):\n stat = dict()\n try:\n nproc = self.jshandle.get('num_processors', '20')\n final_stream = pathlib.Path(streamfile)\n base_str = str(final_stream.name) # type: str\n base_str = base_str.split('.') # type: list\n ohkl = str(final_stream.parent / (base_str[0] + '.hkl')) # type: str\n ohkl1 = str(final_stream.parent / (base_str[0] + '.hkl1')) # type: str\n ohkl2 = str(final_stream.parent / (base_str[0] + '.hkl2')) # type: str\n snrfile = ohkl.split('.')[0] + '_snr.dat'\n ccfile = ohkl.split('.')[0] + '_CCstar.dat'\n rsplitfile = ohkl.split('.')[0] + '_Rsplit.dat'\n\n cmd = self.partialator_cmd(str(final_stream), self.results['point_group'], nproc)\n cmd += '\\n\\n'\n\n cmd += self.check_hkl_cmd(ohkl, self.results['point_group'], 'auto.cell', self.results['resolution_limit'])\n cmd += '\\n\\n'\n\n cmd += self.compare_hkl_cmd(ohkl1, ohkl2, 'auto.cell', self.results['resolution_limit'])\n cmd += '\\n\\n'\n\n cmd += self.compare_hkl_cmd(ohkl1, ohkl2, 'auto.cell', self.results['resolution_limit'], fom='Rsplit')\n cmd += '\\n\\n'\n shellfile = str(self.getOutputDirectory() / 'merge.sh')\n if self.is_executable('bsub'):\n self.oarshell_submit(shellfile, cmd)\n self.check_oarstat(wait_count=6000)\n elif self.is_executable('sbatch'):\n self.slurm_submit(shellfile, str(final_stream.parent), cmd)\n sub.call('sbatch -J autoCryst %s' %shellfile, shell=True)\n else:\n self.run_as_command(cmd)\n\n if self.is_success():\n statparser = ResultParser()\n for statfile, fom in zip([ccfile, rsplitfile, snrfile], ['ccstar', 'rsplit', 'snr']):\n statparser.getstats(statfile, fom=fom)\n stat[fom] = statparser.results['DataQuality']\n stat['overall_' + fom] = statparser.results.get('overall_' + fom, 0.0)\n stat['overall_multiplicity'] = statparser.results.get('overall_multiplicity', 0.0)\n else:\n logger.error('Merging did not run')\n\n except (IOError, KeyError) as err:\n self.setFailure()\n logger.error('Merging_Error:{}'.format(err))\n return stat\n\n def run_indexing(self):\n\n try:\n jsonschema.validate(instance=self.jshandle, schema=self.getInDataSchema())\n self.datafinder()\n self.makeOutputDirectory()\n kk = {}\n if self.jshandle['suffix'] == 'cxi':\n kk['cxi'] = \"\"\"dim0 = %\\ndim1 = ss\\ndim2 = fs\\ndata = /data/data\\n\"\"\"\n geomfile = self.make_geometry_file(**kk)\n else:\n geomfile = self.make_geometry_file(**kk)\n\n self.make_list_events(str(geomfile))\n\n maxchunksize = self.jshandle.get('maxchunksize', 10)\n doSubmit = self.jshandle.get('doSubmit', True)\n\n if doSubmit:\n if len(self.filelist) % maxchunksize == 0:\n file_chunk = int(len(self.filelist) / maxchunksize)\n else:\n file_chunk = int(len(self.filelist) / maxchunksize) + 1\n for jj in range(file_chunk):\n start = maxchunksize * jj\n stop = maxchunksize * (jj + 1)\n try:\n images = self.filelist[start:stop]\n except IndexError:\n stop = start + (len(self.filelist) - stop)\n images = self.filelist[start:stop]\n\n infile = str(self.getOutputDirectory() / ('%d.lst' % jj))\n outstream = str(self.getOutputDirectory() / ('%d.stream' % jj))\n shellfile = str(self.getOutputDirectory() / ('%d.sh' % jj))\n\n ofh = open(infile, 'w')\n for fname in images:\n ofh.write(fname)\n ofh.write('\\n')\n ofh.close()\n\n if self.is_executable('bsub'):\n self.oarshell_submit(shellfile, self.indexamajig_cmd(infile, outstream, str(geomfile)))\n elif self.is_executable('sbatch'):\n self.slurm_submit(shellfile, str(self.getOutputDirectory()), self.indexamajig_cmd(infile, outstream, str(geomfile)))\n sub.call('sbatch -J autoCryst %s' %shellfile, shell=True)\n else:\n error_message = \"doSubmit was set True but queue system is unavailable in running node; \" \\\n \"please change doSubmit to False\"\n logger.error(error_message)\n else:\n infile = str(self.getOutputDirectory() / 'input.lst')\n outname = datetime.now().strftime('%H-%M-%S.stream')\n outstream = str(self.getOutputDirectory() / outname)\n\n ofh = open(infile, 'w')\n for fname in self.filelist:\n ofh.write(fname)\n ofh.write('\\n')\n ofh.close()\n\n self.run_as_command(self.indexamajig_cmd(infile, outstream, str(geomfile)))\n\n except Exception as err:\n self.setFailure()\n logger.error('Error:{}'.format(err))\n return\n\n def check_oarstat(self, wait_count=200):\n wait = 0\n njobs = sub.check_output('oarstat -u $USER | wc -l', shell=True)[:-1]\n wait_max = int(njobs) * wait_count\n while int(njobs) > 2:\n time.sleep(1)\n msg = \"all jobs are not yet finished\"\n logger.info('Indexing_running:{}'.format(msg))\n wait += 2\n njobs = sub.check_output('oarstat -u $USER | wc -l', shell=True)[:-1]\n njobs = int(njobs)\n if wait > wait_max:\n logger.error('Run_Error:{}'.format('OAR is taking too long to finish'))\n self.setFailure()\n break\n else:\n pass\n\n if self.is_success():\n cmd = 'cat *.stream >> alltogether.stream'\n self.run_as_command(cmd)\n else:\n pass\n\n return\n\n @staticmethod\n def report_cell(streampath):\n # cellobject = type('', (), {}) # c is a Cell type which is initialized as None type for python 2.7.\n results = dict()\n if os.path.exists(streampath):\n cellobject = Cell(streampath)\n cellobject.get_lattices()\n cellobject.calc_modal_cell()\n results['cellobject'] = cellobject\n try:\n results['centering'] = cellobject.most_common_centering\n results['num_indexed_frames'] = cellobject.cell_array.shape[0]\n if cellobject.most_common_lattice_type == 'triclinic':\n lat, ua, cell_list = lattice_from_cell([cellobject.a_mode, cellobject.b_mode,\n cellobject.c_mode, cellobject.al_mode,\n cellobject.be_mode, cellobject.ga_mode])\n\n assert isinstance(lat, str)\n results['lattice'] = lat\n assert isinstance(ua, str)\n results['unique_axis'] = ua\n assert isinstance(cell_list, list)\n results['unit_cell'] = cell_list\n else:\n results['lattice'] = cellobject.most_common_lattice_type\n results['unique_axis'] = cellobject.most_common_unique_axis\n results['unit_cell'] = [cellobject.a_mode, cellobject.b_mode,\n cellobject.c_mode, cellobject.al_mode,\n cellobject.be_mode, cellobject.ga_mode]\n\n pg, sg_str, sg_num = assign_point_group(results['lattice'], results['centering'],\n results['unique_axis'])\n assert isinstance(pg, str)\n results['point_group'] = pg\n results['space_group'] = sg_str\n results['space_group_number'] = sg_num\n\n except AssertionError as err:\n logger.error(\"Cell_Error:{}\".format(err))\n else:\n logger.error(\"Cell_Error:{}\".format(\"%s file did not exist\" % streampath))\n return results\n\n @staticmethod\n def report_stats(streampath):\n stats = {}\n try:\n stats = AutoCrystFEL.report_cell(streampath)\n if not stats:\n err = 'alltogether.stream file does not exist or empty'\n logger.error('Job_Error:'.format(err))\n return\n\n rescut = []\n npeaks = []\n\n for each_chunk in stats['cellobject'].stream_handle.stream_data:\n try:\n rescut.append(each_chunk['rescut'])\n npeaks.append(each_chunk['nPeaks'])\n except KeyError:\n pass\n if len(rescut) > 0 and len(npeaks) > 0:\n stats['resolution_limit'] = Counter(rescut).most_common(1)[0][0]\n stats['average_num_spots'] = Counter(npeaks).most_common(1)[0][0]\n else:\n err = \"either nothing detected as hit or indexed in the stream file\"\n logger.error('Job_Error:{}'.format(err))\n\n # Run partialator and calculate standard stats from crystfel..\n # self.scale_merge(streampath)\n\n except Exception as err:\n logger.error('Job_Error:{}'.format(err))\n\n return stats\n\n def extract_peaklist(self, streampath):\n spots_data = {}\n try:\n sh = Stream(streampath) # streampath is a string, not Path object\n sh.get_chunk_pointers()\n sh.read_chunks(sh.codgas_lookup['begin_chunk'], sh.codgas_lookup['end_chunk'])\n sh.get_peaklist(sh.codgas_lookup['begin_peaklist'], sh.codgas_lookup['end_peaklist'])\n sh.close()\n spots_data['peaks_per_pattern'] = sh.image_peaks\n except Exception as err:\n self.setFailure()\n logger.error('Stream_Error:{}'.format(err))\n return spots_data\n\n\ndef __run__(inData):\n crystTask = AutoCrystFEL(inData)\n results = {}\n try:\n crystTask.run_indexing()\n crystTask.writeInputData(inData)\n\n if crystTask.is_executable('bsub'):\n crystTask.check_oarstat()\n\n elif crystTask.is_executable('sbatch'):\n crystTask.combine_streams()\n else:\n pass\n #if crystTask.is_success():\n # crystTask.run_as_command('cat *.stream >> alltogether.stream')\n #else:\n # pass\n streampath = crystTask.getOutputDirectory() / 'alltogether.stream'\n results['QualityMetrics'] = crystTask.report_stats(str(streampath))\n if results:\n crystTask.write_cell_file(results['QualityMetrics'])\n\n if inData.get(\"doMerging\", False):\n crystTask.set_outData(results['QualityMetrics'])\n merging_stats = crystTask.scale_merge(str(streampath))\n results['QualityMetrics'].update(merging_stats)\n\n if inData.get(\"GeneratePeaklist\", False):\n results['PeaksDictionary'] = crystTask.extract_peaklist(str(streampath))\n if crystTask.is_success():\n crystTask.writeOutputData(results)\n logger.info('Indexing_Results:{}'.format(crystTask.results))\n else:\n crystTask.setFailure()\n logger.error(\"AutoCrystFEL_ERROR:{}\".format(\"crystfel pipeline upstream error\"))\n except Exception as err:\n crystTask.setFailure()\n logger.error(\"Error:{}\".format(err))\n return results\n\n\ndef optparser():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--image_directory\", type=str, required=True,\n help=\"provide path MeshScan, containing images in cbf or h5 formats\")\n parser.add_argument(\"--detectorType\", type=str, required=True,\n help=\"provide detector type, either pilatus or eiger\")\n parser.add_argument(\"--prefix\", type=str, required=True,\n help=\"filename prefix, a wildcard to look for files\")\n parser.add_argument(\"--suffix\", type=str, required=True,\n help=\"image fileformat, either cbf, h5, or cxi\")\n parser.add_argument(\"--maxchunksize\", type=int, required=True,\n help=\"max number of images per batch\")\n parser.add_argument(\"--num_processors\", type=str, default='20')\n parser.add_argument(\"--beamline\", type=str,\n help=\"optional key, not needed\")\n parser.add_argument(\"--processing_directory\", type=str,\n help=\"optional key, if you want to dump at a different folder\")\n parser.add_argument(\"--doMerging\", type=bool, default=False)\n parser.add_argument(\"--doSubmit\", type=bool, default=True)\n parser.add_argument(\"--GeneratePeaklist\", type=bool, default=False)\n parser.add_argument(\"--indexing_method\", type=str, default=\"xgandalf\",\n help=\"change to asdf,or dirax or xds if needed\")\n parser.add_argument(\"--peak_search\", type=str, default=\"peakfinder8\",\n help=\"alternatively, peakfinder9 can be tried\")\n parser.add_argument(\"--peak_info\", type=str, default=\"/data/peakinfo\")\n parser.add_argument(\"--int_method\", type=str, default='rings-grad')\n parser.add_argument(\"--int_radius\", type=str, default='3,4,6')\n parser.add_argument(\"--min_peaks\", type=str, default='30')\n parser.add_argument(\"--peak_radius\", type=str, default='3,4,6')\n parser.add_argument(\"--min_snr\", type=str, default='4.0')\n parser.add_argument(\"--threshold\", type=str, default='10')\n parser.add_argument(\"--local_bg_radius\", type=str, default='10')\n parser.add_argument(\"--min_res\", type=str, default='50',\n help=\"Applied to avoid regions near beamstop in peak search\")\n parser.add_argument(\"--unit_cell_file\", type=str,\n help=\"optional key, if you want to index with a given unit-cell\")\n parser.add_argument(\"--geometry_file\", type=str,\n help=\"optional key, only if you have a better detector geometry file\")\n\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%y-%m-%d %H:%M',\n filename='autoCryst.log',\n filemode='a+')\n op = optparser()\n input_Dict = dict()\n for k, v in op.__dict__.items():\n if v is not None:\n input_Dict[k] = v\n else:\n pass\n output = __run__(input_Dict)\n print(output)\n","sub_path":"edna2/lib/autocryst/src/run_crystfel.py","file_name":"run_crystfel.py","file_ext":"py","file_size_in_byte":34235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"288723298","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\nimport csv\n\nimport nltk as nltk\nimport pandas\nimport pandas as pd\nimport numpy as np\nfrom sklearn import linear_model\nfrom datetime import datetime\n\neasy_words_list = []\nawl_list = []\nl1 = []\nl2 = []\nl3 = []\nl4 = []\nl5 = []\nl6 = []\nl7 = []\nl8 = []\nl9 = []\nl10 = []\n\n\ndef open_files():\n \"\"\"\n This function open train dataset file, invoke clean data,write_report_to_file, prepare_target_for_test_data\n and prepare_submission_file functions.\n \"\"\"\n print(\"Open Train dataset file\")\n columns_list = [\"id\", \"excerpt\", \"target\", \"standard_error\"]\n file_name = \"train.csv\"\n dataset_parsed = parse_data_from_dataset(columns_list, file_name)\n\n awl_file_name = \"AWL.csv\"\n awl_columns_list = [\"l1\", \"l2\", \"l3\", \"l4\", \"l5\", \"l6\", \"l7\", \"l8\", \"l9\", \"l10\"]\n #parse_list_from_awl(awl_columns_list, awl_file_name)\n clean_data = check_missing_values(dataset_parsed)\n report_list = prepare_report_list(clean_data)\n write_report_to_file(report_list)\n prepare_target_for_test_data()\n prepare_submission_file()\n\n\ndef check_missing_values(pandas_dataframe):\n \"\"\"\n This function checks if the dataset/dataframe contains any missing values and prints the result\n :param pandas_dataframe: This is the dataframe already parsed from the CSV file by pandas\n \"\"\"\n # Check if dataframe contains null value\n print(\"Check missing values\")\n dataframe_checked = np.where(pd.isnull(pandas_dataframe))\n # If dataframe contains any element with null value, print a message\n if len(dataframe_checked) == 0:\n print(\"No missing value found in the dataset.\")\n else:\n count = 0\n count_value = 0\n missing_value_row = list()\n missing_value_column = list()\n # Loop through the tuple with containing the rows and columns number with missing values\n for missing_values in dataframe_checked:\n # If missing_values size is zero, it means there is no missing values found\n if len(missing_values) == 0:\n # Print a message and break the loop.\n print(\"No missing value found in the dataset.\")\n return pandas_dataframe\n # Else, save the missing values row and columns into two different lists to print later\n else:\n if count == 0:\n print(f\"We found {len(missing_values)} missing values in the dataset:\\n\")\n for value in missing_values:\n if count == 0 or (count / 2) == 0:\n missing_value_row.append(value + 2)\n # print(f\"Row of missing value {count_value + 1}: {value + 2}\")\n count_value += 1\n else:\n missing_value_column.append(value + 1)\n # print(f\"Column missing value {count_value + 1}: {value + 1}\")\n count_value += 1\n count_value = 0\n count += 1\n\n # Loop through each row and columns lists and print the missing values\n count = 1\n for row in missing_value_row:\n for column in missing_value_column:\n print(f\"Missing value {count}: Row {row}, Column {column}\")\n break\n count += 1\n print(\"\\nClean dataset.\")\n return clean_dataset(pandas_dataframe, missing_value_row)\n\n\ndef clean_dataset(dataset, row_numbers):\n \"\"\"\n This function clean the dataset.\n :param dataset: This is the dataframe already parsed from the CSV file by pandas\n :param row_numbers: Number of rows which has missing data.\n :return: clean dataset.\n \"\"\"\n print(\"Clean dataset\")\n for row_number in row_numbers:\n dataset.drop(row_number - 2, axis=0, inplace=True)\n return dataset\n\n\ndef prepare_submission_file():\n \"\"\"\n This function prepare submission file for Kaggle competition.\n \"\"\"\n print(\"Prepare submission file\")\n test_file_name = \"test.csv\"\n submission_file = \"submission.csv\"\n report_file = \"cleanreport.csv\"\n\n # Read from report.csv to calculate Multiple Regression Model\n report_file = pandas.read_csv(report_file)\n X = report_file[[\"total_words\", \"total_sentences\", \"total_syllables\", \"ave_syllables\", \"ave_sentence_length\",\n \"num_verb_noun\", \"num_adj_noun\", \"per_diff_words\",\n \"flesch_score\", \"dale_score\", \"sumner_level\", \"coleman_index\", \"readability_index\",\n \"gunning_fog_score\", \"awl_index\"]]\n y = report_file['target']\n\n # Print out the statistics\n # print(model.summary())\n\n regr_model = linear_model.LinearRegression()\n regr_model.fit(X, y)\n # print(regr_model.coef_)\n # print(\"intercept\")\n # print(regr_model.__dict__)\n\n test_file = pandas.read_csv(test_file_name)\n test_file_list = test_file[[\"id\", \"excerpt\"]]\n submission_report_list = []\n\n for n in range(len(test_file_list)):\n id = test_file_list.values[n][0]\n text = test_file_list.values[n][1]\n sentences = tokenize_by_sentence(text)\n total_sentences = len(sentences)\n words_list = extract_words_from_text(text)\n total_words = len(words_list)\n awl_index = calculate_awl_index(words_list)\n num_verb_noun = chunk_verb_noun(text)\n num_adj_noun = chunk_adj_noun(text)\n\n total_letters = get_total_letters_from_text(text)\n total_syllables = syllables_in_text(words_list)\n ave_syllables = total_syllables / total_words\n average_sentence_length_in_words = total_words / total_sentences\n per_diff_words = get_percentage_of_difficult_words(words_list, easy_words_list)\n flesch_score = flesch_reading_ease(total_words, total_sentences, total_syllables)\n dale_chall_score = dale_chall_readability_score(per_diff_words, average_sentence_length_in_words)\n sumner_level = powers_sumner_kearl_grade_level(total_words, total_sentences, total_syllables)\n coleman_index = coleman_liau_index(total_words, total_sentences, total_letters)\n readability_score = automated_readability_index(total_words, total_sentences, total_letters)\n gunning_fog_score = gunning_fog(per_diff_words, average_sentence_length_in_words)\n\n target = regr_model.predict([[total_words, total_sentences, total_syllables, ave_syllables,\n average_sentence_length_in_words, num_verb_noun, num_adj_noun,\n per_diff_words, flesch_score, dale_chall_score, sumner_level, coleman_index,\n readability_score, gunning_fog_score, awl_index]])\n # print(target)\n submission_report_list.append([id, target[0]])\n\n with open(submission_file, 'w', newline=\"\") as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow([\"id\", \"target\"])\n for report in submission_report_list:\n writer.writerow([report[0], report[1]])\n\n\ndef write_report_to_file(report_list):\n \"\"\"\n This function write the report list to report.csv file.\n :param report_list: List of the report for the text file.\n \"\"\"\n print(\"Write calculated data to report file\")\n with open('report.csv', 'w', newline=\"\") as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow([\"id\", \"target\", \"standard_error\", \"total_words\", \"total_sentences\", \"total_syllables\",\n \"ave_syllables\", \"ave_sentence_length\", \"num_verb_noun\", \"num_adj_noun\", \"per_diff_words\",\n \"flesch_score\", \"dale_score\", \"sumner_level\",\n \"coleman_index\", \"readability_index\", \"gunning_fog_score\", \"awl_index\"])\n for report in report_list:\n writer.writerow([report.id, report.target, report.std_error, report.total_words, report.total_sentences,\n report.total_syllables, report.ave_syllables, report.ave_sentence_length,\n report.num_verb_noun, report.num_adj_noun, report.per_diff_words,\n report.flesch_score, report.dale_score, report.sumner_level, report.coleman_index,\n report.readability_index, report.gunning_fog_score, report.awl_index])\n\n\ndef prepare_target_for_test_data():\n \"\"\"\n This function calculate target score for train dataset to clean dataset.\n \"\"\"\n print(\"Calculate target score to clean outlineers.\")\n clean_report_file = \"cleanreport.csv\"\n report_file = \"report.csv\"\n\n # Read from report.csv to calculate Multiple Regression Model\n report_file = pandas.read_csv(report_file)\n X = report_file[[\"total_words\", \"total_sentences\", \"total_syllables\", \"ave_syllables\", \"ave_sentence_length\",\n \"num_verb_noun\", \"num_adj_noun\", \"per_diff_words\",\n \"flesch_score\", \"dale_score\", \"sumner_level\", \"coleman_index\", \"readability_index\",\n \"gunning_fog_score\", \"awl_index\"]]\n y = report_file['target']\n\n regr_model = linear_model.LinearRegression()\n regr_model.fit(X, y)\n\n # old_file = pandas.read_csv(report_file)\n old_file_list = report_file[[\"id\", \"target\", \"standard_error\", \"total_words\", \"total_sentences\", \"total_syllables\",\n \"ave_syllables\", \"ave_sentence_length\", \"num_verb_noun\", \"num_adj_noun\",\n \"per_diff_words\", \"flesch_score\", \"dale_score\", \"sumner_level\",\n \"coleman_index\", \"readability_index\", \"gunning_fog_score\", \"awl_index\"]]\n new_file_list = []\n t = 0;\n print(\"Clean train dataset.\")\n with open(clean_report_file, 'w', newline=\"\") as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow([\"id\", \"target\", \"standard_error\", \"total_words\", \"total_sentences\", \"total_syllables\",\n \"ave_syllables\", \"ave_sentence_length\", \"num_verb_noun\", \"num_adj_noun\", \"per_diff_words\",\n \"flesch_score\", \"dale_score\", \"sumner_level\",\n \"coleman_index\", \"readability_index\", \"gunning_fog_score\", \"awl_index\", \"new_target\"])\n\n for n in range(len(old_file_list)):\n target = regr_model.predict(\n [[old_file_list.values[n][3], old_file_list.values[n][4], old_file_list.values[n][5],\n old_file_list.values[n][6], old_file_list.values[n][7], old_file_list.values[n][8],\n old_file_list.values[n][9], old_file_list.values[n][10], old_file_list.values[n][11],\n old_file_list.values[n][12], old_file_list.values[n][13], old_file_list.values[n][14],\n old_file_list.values[n][15], old_file_list.values[n][16], old_file_list.values[n][17]]])\n if (old_file_list.values[n][1] - old_file_list.values[n][2]) < target[0] < (\n old_file_list.values[n][1] + old_file_list.values[n][2]):\n writer.writerow([old_file_list.values[n][0], old_file_list.values[n][1], old_file_list.values[n][2],\n old_file_list.values[n][3],\n old_file_list.values[n][4], old_file_list.values[n][5], old_file_list.values[n][6],\n old_file_list.values[n][7],\n old_file_list.values[n][8], old_file_list.values[n][9], old_file_list.values[n][10],\n old_file_list.values[n][11],\n old_file_list.values[n][12], old_file_list.values[n][13], old_file_list.values[n][13],\n old_file_list.values[n][15], old_file_list.values[n][16], old_file_list.values[n][17],\n target[0]])\n # print(target)\n\n\ndef parse_data_from_dataset(columns, dataset_path):\n \"\"\" This function parse data from a csv dataset\n It uses pandas package to parse and read data from the csv dataset using only the columns from columns_list.\n :param columns: This argument receives a list of columns that will be used in the dataframe\n :param dataset_path: Thi argument receives the dataset name and path to be loaded by pandas\n :return: Returns the tabulated parsed data\n \"\"\"\n # This try and except block tries to read from the dataset using pandas and throws an exception\n # if file does not exists\n try:\n dataset = pd.read_csv(dataset_path, index_col=False, usecols=columns)\n return dataset\n # If file does not exists, it will show a message to the user\n except FileNotFoundError:\n print(\"File does not exists! Please certify if the file name or path is correct.\")\n\n\ndef parse_list_from_awl(columns, dataset_path):\n \"\"\" This function parse data from a csv dataset\n It uses pandas package to parse and read data from the csv dataset using only the columns from columns_list.\n :param columns: This argument receives a list of columns that will be used in the dataframe\n :param dataset_path: Thi argument receives the dataset name and path to be loaded by pandas\n :return: Returns the tabulated parsed data\n \"\"\"\n # This try and except block tries to read from the dataset using pandas and throws an exception\n # if file does not exists\n try:\n dataset = pd.read_csv(dataset_path, index_col=False, usecols=columns)\n for count in range(len(dataset)):\n l1.append(dataset.iloc[count].l1)\n l2.append(dataset.iloc[count].l2)\n l3.append(dataset.iloc[count].l3)\n l4.append(dataset.iloc[count].l4)\n l5.append(dataset.iloc[count].l5)\n l6.append(dataset.iloc[count].l6)\n l7.append(dataset.iloc[count].l7)\n l8.append(dataset.iloc[count].l8)\n l9.append(dataset.iloc[count].l9)\n l10.append(dataset.iloc[count].l10)\n\n # If file does not exists, it will show a message to the user\n except FileNotFoundError:\n print(\"File does not exists! Please certify if the file name or path is correct.\")\n\n\ndef create_easy_word_list():\n \"\"\"\n This function creates a easy words list from a file.\n :return: list of easy words\n \"\"\"\n my_file = open(\"dale-chall-word-list.txt\", \"r\")\n content = my_file.read()\n easy_word_list = []\n for easy_word in content.split():\n easy_word_list.append(easy_word)\n return easy_word_list\n\n\ndef get_percentage_of_difficult_words(words_list, easy_words_list):\n \"\"\"\n This function calculate percentage of the difficult words in a text by using easy words list from a file.\n :return: percentage of the difficult words\n \"\"\"\n count = 0\n for word in words_list:\n if (not word.isdigit()) and (word not in easy_words_list) and (syllables_in_word(word) > 2):\n count += 1\n return 100 * count / len(words_list)\n\n\ndef calculate_awl_index(words_list):\n awl_index = 0\n for word in words_list:\n if word in l1:\n awl_index += 1\n if word in l2:\n awl_index += 2\n if word in l3:\n awl_index += 3\n if word in l4:\n awl_index += 4\n if word in l5:\n awl_index += 5\n if word in l6:\n awl_index += 6\n if word in l7:\n awl_index += 7\n if word in l8:\n awl_index += 8\n if word in l9:\n awl_index += 9\n if word in l10:\n awl_index += 10\n return awl_index\n\n\ndef prepare_report_list(dataset):\n \"\"\"\n This function prepares a list of readability score and grade level for a text file.\n :param dataset: Text for the analysing.\n :return: List of reports.\n \"\"\"\n print(\"Prepare report list for train dataset.\")\n report_list = []\n number_of_text = len(dataset)\n # number_of_text = 20\n global easy_words_list\n easy_words_list = create_easy_word_list()\n\n for count in range(number_of_text):\n id = dataset.iloc[count].id\n target = dataset.iloc[count].target\n std_error = dataset.iloc[count].standard_error\n text = dataset.iloc[count].excerpt\n sentences = tokenize_by_sentence(text)\n total_sentences = len(sentences)\n words_list = extract_words_from_text(text)\n total_words = len(words_list)\n\n num_verb_noun = chunk_verb_noun(text)\n num_adj_noun = chunk_adj_noun(text)\n awl_index = calculate_awl_index(words_list)\n\n total_letters = get_total_letters_from_text(text)\n total_syllables = syllables_in_text(words_list)\n ave_syllables = total_syllables / total_words\n average_sentence_length_in_words = total_words / total_sentences\n per_diff_words = get_percentage_of_difficult_words(words_list, easy_words_list)\n flesch_score = flesch_reading_ease(total_words, total_sentences, total_syllables)\n dale_chall_score = dale_chall_readability_score(per_diff_words, average_sentence_length_in_words)\n sumner_level = powers_sumner_kearl_grade_level(total_words, total_sentences, total_syllables)\n coleman_index = coleman_liau_index(total_words, total_sentences, total_letters)\n readability_score = automated_readability_index(total_words, total_sentences, total_letters)\n gunning_fog_score = gunning_fog(per_diff_words, average_sentence_length_in_words)\n new_report = Reports(id, target, std_error, total_words, total_sentences, total_syllables, ave_syllables,\n average_sentence_length_in_words, num_verb_noun, num_adj_noun, per_diff_words,\n flesch_score, dale_chall_score,\n sumner_level, coleman_index, readability_score, gunning_fog_score, awl_index)\n report_list.append(new_report)\n return report_list\n\n\ndef tokenize_by_sentence(text_to_tokenize):\n \"\"\"\n This function tokenizes text by sentences, it creates a python list by\n breaking text into individual sentences.\n :param text_to_tokenize: Text that need to be tokenized\n \"\"\"\n # Tokenize the text in sentences and save as a list in the variable\n sentences_tokenized = nltk.sent_tokenize(text_to_tokenize)\n # Return the text tokenized by sentence\n return sentences_tokenized\n\n\ndef get_total_letters_from_text(text):\n \"\"\"\n This function calculates total digit and letters in a text.\n :param text: text\n \"\"\"\n total_letters = 0\n for letter in text:\n if letter.isdigit() or letter.isalpha():\n total_letters += 1\n return total_letters\n\n\ndef extract_words_from_text(text_to_tokenize):\n \"\"\"\n This function extracts words from a text by using split method.\n :param text_to_tokenize: Text which will be extracted.\n \"\"\"\n words_list = []\n split_words = text_to_tokenize.split()\n for word in split_words:\n words_list.append(word)\n return words_list\n\n\ndef syllables_in_text(word_list):\n \"\"\"\n This function calculate total syllables in a text.\n :return: Total number of syllables in the text.\n \"\"\"\n total_syllables = 0\n vowels = 'aeiouy'\n for word in word_list:\n count = 0\n if word[0] in vowels:\n count += 1\n for index in range(1, len(word)):\n if word[index] in vowels and word[index - 1] not in vowels:\n count += 1\n if word.endswith('e'):\n count -= 1\n if word.endswith('le') and len(word) > 2 and word[-3] not in vowels:\n count += 1\n if count == 0:\n count += 1\n total_syllables += count\n return total_syllables\n\n\ndef syllables_in_word(word):\n \"\"\"\n This function calculate total syllables in a text.\n :return: Total number of syllables in the text.\n \"\"\"\n vowels = 'aeiouy'\n count = 0\n if word[0] in vowels:\n count += 1\n for index in range(1, len(word)):\n if word[index] in vowels and word[index - 1] not in vowels:\n count += 1\n if word.endswith('e'):\n count -= 1\n if word.endswith('le') and len(word) > 2 and word[-3] not in vowels:\n count += 1\n if count == 0:\n count += 1\n\n return count\n\n\ndef chunk_verb_noun(text_to_chunk):\n \"\"\"\n This function creates a chunk of words by using special regexp syntax to find pattern in the text.\n In this case the function uses a regexp rule to find a VB (Verb) followed by a NN (Noun), it it\n finds the patters, it saves each chunk in a list and returns it.\n :param text_to_chunk: Text used to find words + noun in it.\n \"\"\"\n words = extract_words_from_text(text_to_chunk)\n # Tags each token word with from the list with its own respective type: (Verb, noun, adjective, etc)\n chunk_tags = nltk.pos_tag(words)\n # Create the regexp pattern to find anything starting with a Verb and followed by a Noun\n chunk_rule = \"\"\"Chunk:{+}\"\"\"\n # Creates the regex parser\n regex_parser = nltk.RegexpParser(chunk_rule)\n # Parse all tagged words and saves into a variable\n parsed_sentence = regex_parser.parse(chunk_tags)\n\n # Code to filter the chunk words from the nltk.Tree\n # (https://stackoverflow.com/questions/58617920/how-print-only-the-string-result-of-the-chunking-with-nltk)\n # Filter only the Chunk matched by the chunk_rules an save into a list tu return only the chunks\n count = 0\n for chunk in parsed_sentence:\n if isinstance(chunk, nltk.tree.Tree):\n if chunk.label() == \"Chunk\":\n count += 1\n return count\n\n\ndef chunk_adj_noun(text_to_chunk):\n \"\"\"\n This function creates a chunk of words by using special regexp syntax to find pattern in the text.\n In this case the function uses a regexp rule to find a VB (Verb) followed by a NN (Noun), it it\n finds the patters, it saves each chunk in a list and returns it.\n :param text_to_chunk: Text used to find words + noun in it.\n \"\"\"\n words = extract_words_from_text(text_to_chunk)\n chunk_tags = nltk.pos_tag(words)\n chunk_rule = \"\"\"Chunk:{
?++}\"\"\"\n regex_parser = nltk.RegexpParser(chunk_rule)\n parsed_sentence = regex_parser.parse(chunk_tags)\n count = 0\n for chunk in parsed_sentence:\n if isinstance(chunk, nltk.tree.Tree):\n if chunk.label() == \"Chunk\":\n count += 1\n return count\n\n\n# https://readable.com/blog/the-flesch-reading-ease-and-flesch-kincaid-grade-level/\ndef flesch_reading_ease(total_words, total_sentences, total_syllables):\n \"\"\"\n This function calculate The Flesch Reading Ease score for a given text.\n The score is between 1 and 100 and 100 is the highest readability score.\n :param total_words: number of total words in the text.\n :param total_sentences: number of total sentences in the text.\n :param total_syllables: number of total syllables in the text.\n :return: return the The Flesch Reading Ease score\n \"\"\"\n return 206.835 - 1.015 * (total_words / total_sentences) - 84.6 * (total_syllables / total_words)\n\n\ndef dale_chall_readability_score(percentage_of_difficult_words, average_sentence_length_in_words):\n \"\"\"\n This function calculates the Dale Chall Readability Score.\n :param percentage_of_difficult_words: percentage of the difficult words in the text.\n :param average_sentence_length_in_words: average length of a sentence in words.\n :return: Dale Chall Readability Score\n \"\"\"\n if percentage_of_difficult_words <= 5:\n return 0.1579 * percentage_of_difficult_words + 0.0496 * average_sentence_length_in_words\n else:\n return 0.1579 * percentage_of_difficult_words + 0.0496 * average_sentence_length_in_words + 3.6365\n\n\ndef gunning_fog(per_diff_words, average_sentence_length_in_words):\n \"\"\"\n This function calculate Gunning Fog readability score for a text.\n \"\"\"\n return 0.4 * (average_sentence_length_in_words + per_diff_words)\n\n\ndef powers_sumner_kearl_grade_level(total_words, total_sentences, total_syllables):\n \"\"\"\n This function calculates Powers Sumner Kearl grade level of a text by using parameters.\n :param total_words: number of total words in the text\n :param total_sentences: number of total sentences in the text.\n :param total_syllables: number of total syllables in the text.\n :return: Powers Sumner Kearl grade level\n \"\"\"\n average_sentence_length = total_words / total_sentences\n average_syllables_length = 100 * total_syllables / total_words\n return 0.0778 * average_sentence_length + .0455 * average_syllables_length - 2.2029\n\n\ndef coleman_liau_index(total_words, total_sentences, total_letters):\n \"\"\"\n This function calculates the Coleman Liau Index of a text.\n :param total_words: number of total words in the text\n :param total_sentences: number of total sentences in the text.\n :param total_letters: number of total letters and digits in the text.\n :return: the Coleman Liau Index\n \"\"\"\n average_number_of_letters = 100 * total_letters / total_words\n average_number_of_sentences = 100 * total_sentences / total_words\n return 0.0588 * average_number_of_letters - 0.296 * average_number_of_sentences - 15.8\n\n\ndef automated_readability_index(total_words, total_sentences, total_letters):\n \"\"\"\n This function calculates the Automated Readability Index of a text.\n :param total_words: number of total words in the text\n :param total_sentences: number of total sentences in the text.\n :param total_letters: number of total letters and digits in the text.\n :return: the Automated Readability Index\n \"\"\"\n return 4.71 * (total_letters / total_words) + 0.5 * (total_words / total_sentences) - 21.43\n\n\nclass Reports:\n \"\"\"\n A class to represent Report object.\n Report class has one constructor (__init__) to create Report object a\n \"\"\"\n\n def __init__(self, id, target, std_error, total_words, total_sentences, total_syllables, ave_syllables,\n ave_sentence_length, num_verb_noun, num_adj_noun,\n per_diff_words, flesch_score, dale_score, sumner_level, coleman_index, readability_index,\n gunning_fog_score, awl_index):\n \"\"\"Constructor to create Report object by using 13 parameters.\"\"\"\n self.id = id\n self.target = target\n self.std_error = std_error\n self.total_words = total_words\n self.total_sentences = total_sentences\n self.total_syllables = total_syllables\n self.ave_syllables = ave_syllables\n self.ave_sentence_length = ave_sentence_length\n self.per_diff_words = per_diff_words\n self.flesch_score = flesch_score\n self.dale_score = dale_score\n self.sumner_level = sumner_level\n self.coleman_index = coleman_index\n self.readability_index = readability_index\n self.gunning_fog_score = gunning_fog_score\n self.num_verb_noun = num_verb_noun\n self.num_adj_noun = num_adj_noun\n self.awl_index = awl_index\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n \"\"\"\n Main function start the program.\n \"\"\"\n print(datetime.now())\n open_files()\n print(datetime.now())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":27259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"480826085","text":"def test_solution():\n from solution import Node\n\n items = Node(10)\n items.left = Node(11)\n items.left.left = Node(7)\n items.right = Node(9)\n items.right.left = Node(15)\n items.right.right = Node(8)\n val = 12\n items.insert(val)\n assert items.left.right.key == 12\n","sub_path":"data_structures/binary_trees/3_insert_node/solution/test_public.py","file_name":"test_public.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"322452392","text":"import numpy as np\nimport pandas as pd\nimport csv\nimport sys\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.externals import joblib\nclf = joblib.load('pow3')\ntrace_hour = 7\npower = 3\nremoved_features = [1, 10, 14, 15, 16, 17]\nfeatures = 18 - len(removed_features)\n# Extract Feachers\ntestdata = pd.read_csv(sys.argv[1], header = None, encoding = 'big5')\ntest_data = testdata.iloc[:, 2:]\ntest_data[test_data == 'NR'] = 0\ntest_data = test_data.to_numpy()\n\n\ntest_x = np.empty([240, features * trace_hour], dtype = float)\nfor i in range(240):\n tmp = test_data[18 * i: 18* (i + 1), -trace_hour:]\n test_x[i, :] = np.delete(tmp, removed_features, axis = 0).reshape(1, -1)\n\n# preprocess wrong data\nfor n in range(240):\n for feature in range(features):\n for time in range(trace_hour):\n if test_x[n][feature * trace_hour + time] < 0:\n #print(test_x[n][feature * 9 + time])\n neighbor_n = 0\n neighbor_v = 0.0\n for i in range (time - 1, time + 2):\n if i >=0 and i < trace_hour and test_x[n][feature * trace_hour + i] > 0:\n neighbor_n += 1\n neighbor_v += test_x[n][feature * trace_hour + i]\n if neighbor_n == 0:\n j = time + 1\n while j < trace_hour:\n if test_x[n][feature * trace_hour + j] > 0:\n neighbor_n = 1\n neighbor_v = test_x[n][feature * trace_hour + j]\n break\n else:\n j += 1\n test_x[n][feature * trace_hour + time] = neighbor_v/neighbor_n\n #print(test_x[n][feature * 9 + time])\n\ntest_x = np.hstack((test_x**(i+1) for i in range(power)))\nmean_x = np.load('mean_pow3.npy')\nstd_x = np.load('std_pow3.npy')\nfor i in range(len(test_x)):\n for j in range(len(test_x[0])):\n if std_x[j] != 0:\n test_x[i][j] = (test_x[i][j] - mean_x[j]) / std_x[j]\ntest_x = np.concatenate((np.ones([240, 1]), test_x), axis = 1).astype(float)\n\n\n# predict\n\n#w = np.load('weight_pow3.npy')\n#ans_y = np.dot(test_x, w)\nans_y = clf.predict(test_x)\nans_y = np.round(ans_y)\nans_y[ans_y < 0] = 0\n\n# output result\nwith open(sys.argv[2], mode='w', newline='') as submit_file:\n csv_writer = csv.writer(submit_file)\n header = ['id', 'value']\n print(header)\n csv_writer.writerow(header)\n for i in range(240):\n row = ['id_' + str(i), ans_y[i][0]]\n csv_writer.writerow(row)\n print(row)","sub_path":"hw1/test_pow3.py","file_name":"test_pow3.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"440127742","text":"# Copyright 2019 AUI, Inc. Washington DC, USA\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\"\"\"\nthis module will be included in the api\n\"\"\"\n\nimport numpy as np\nfrom numba import jit\n# silence NumbaPerformanceWarning\nimport warnings\nfrom numba.errors import NumbaPerformanceWarning\nimport scipy\n\n#warnings.filterwarnings(\"ignore\", category=NumbaPerformanceWarning) #Suppress NumbaPerformanceWarning: '@' is faster on contiguous arrays warning. This happens for phasor_loop and apply_rotation_matrix functions.\n\ndef phase_rotate_numba(vis_dataset, global_dataset, rotation_parms, sel_parms, storage_parms):\n \"\"\"\n Rotate uvw with faceting style rephasing for multifield mosaic.\n The specified phasecenter and field phase centers are assumed to be in the same frame.\n This does not support east-west arrays, emphemeris objects or objects within the nearfield.\n (no refocus).\n \n Parameters\n ----------\n vis_dataset : xarray.core.dataset.Dataset\n input Visibility Dataset\n Returns\n -------\n psf_dataset : xarray.core.dataset.Dataset\n \"\"\"\n #based on UVWMachine and FTMachine\n #measures/Measures/UVWMachine.cc\n \n #Important: Can not applyflags before calling rotate (uvw coordinates are also flagged). This will destroy the rotation transform.\n #Performance improvements apply_rotation_matrix (jit code)\n \n #print('1. numba',vis_dataset.DATA[:,0,0,0].values)\n \n from ngcasa._ngcasa_utils._store import _store\n from scipy.spatial.transform import Rotation as R\n import scipy\n import numpy as np\n import copy\n import dask.array as da\n import xarray as xr\n from ngcasa._ngcasa_utils._check_parms import _check_storage_parms, _check_sel_parms, _check_existence_sel_parms\n from ._imaging_utils._check_imaging_parms import _check_rotation_parms\n import time\n import numba\n from numba import double\n import dask\n \n _sel_parms = copy.deepcopy(sel_parms)\n _rotation_parms = copy.deepcopy(rotation_parms)\n _storage_parms = copy.deepcopy(storage_parms)\n \n assert(_check_sel_parms(_sel_parms,{'uvw_in':'UVW','uvw_out':'UVW_ROT','data_in':'DATA','data_out':'DATA_ROT'})), \"######### ERROR: sel_parms checking failed\"\n assert(_check_existence_sel_parms(vis_dataset,{'uvw_in':_sel_parms['uvw_in'],'data_in':_sel_parms['data_in']})), \"######### ERROR: sel_parms checking failed\"\n assert(_check_rotation_parms(_rotation_parms)), \"######### ERROR: rotation_parms checking failed\"\n assert(_check_storage_parms(_storage_parms,'dataset.vis.zarr','phase_rotate')), \"######### ERROR: storage_parms checking failed\"\n \n assert(_sel_parms['uvw_out'] != _sel_parms['uvw_in']), \"######### ERROR: sel_parms checking failed sel_parms['uvw_out'] can not be the same as sel_parms['uvw_in'].\"\n assert(_sel_parms['data_out'] != _sel_parms['data_in']), \"######### ERROR: sel_parms checking failed sel_parms['data_out'] can not be the same as sel_parms['data_in'].\"\n\n #Phase center\n ra_image = _rotation_parms['image_phase_center'][0]\n dec_image = _rotation_parms['image_phase_center'][1]\n \n rotmat_image_phase_center = R.from_euler('XZ',[[np.pi/2 - dec_image, - ra_image + np.pi/2]]).as_matrix()[0]\n image_phase_center_cosine = _directional_cosine([ra_image,dec_image])\n \n n_fields = global_dataset.dims['field']\n field_names = global_dataset.field\n uvw_rotmat = np.zeros((n_fields,3,3),np.double)\n phase_rotation = np.zeros((n_fields,3),np.double)\n \n fields_phase_center = global_dataset.FIELD_PHASE_DIR.values[:,:,vis_dataset.attrs['ddi']]\n \n #print(fields_phase_center)\n \n #Create a rotation matrix for each field\n for i_field in range(n_fields):\n #Not sure if last dimention in FIELD_PHASE_DIR is the ddi number\n field_phase_center = fields_phase_center[i_field,:]\n # Define rotation to a coordinate system with pole towards in-direction\n # and X-axis W; by rotating around z-axis over -(90-long); and around\n # x-axis (lat-90).\n rotmat_field_phase_center = R.from_euler('ZX',[[-np.pi/2 + field_phase_center[0],field_phase_center[1] - np.pi/2]]).as_matrix()[0]\n uvw_rotmat[i_field,:,:] = np.matmul(rotmat_image_phase_center,rotmat_field_phase_center).T\n \n if _rotation_parms['common_tangent_reprojection'] == True:\n uvw_rotmat[i_field,2,0:2] = 0.0 # (Common tangent rotation needed for joint mosaics, see last part of FTMachine::girarUVW in CASA)\n \n field_phase_center_cosine = _directional_cosine(field_phase_center)\n phase_rotation[i_field,:] = np.matmul(rotmat_image_phase_center,(image_phase_center_cosine - field_phase_center_cosine))\n\n #Apply rotation matrix to uvw\n #@jit(nopython=True, cache=True, nogil=True)\n def apply_rotation_matrix(uvw, field_id, uvw_rotmat):\n #print(uvw.shape,field_id.shape,uvw_rotmat.shape)\n for i_time in range(uvw.shape[0]):\n #print('The index is',np.where(field_names==field[i_time])[1][0],field_id[i_time,0,0])\n #uvw[i_time,:,0:2] = -uvw[i_time,:,0:2] this gives the same result as casa (in the ftmachines uvw(negateUV(vb)) is used). In ngcasa we don't do this since the uvw definition in the gridder and vis.zarr are the same.\n #uvw[i_time,:,:] = np.matmul(uvw[i_time,:,:],uvw_rotmat[field_id[i_time],:,:])\n uvw[i_time,:,:] = uvw[i_time,:,:] @ uvw_rotmat[field_id[i_time,0,0],:,:]\n return uvw\n \n uvw = da.map_blocks(apply_rotation_matrix,vis_dataset[_sel_parms['uvw_in']].data, vis_dataset.field_id.data[:,None,None],uvw_rotmat,dtype=np.double)\n\n #dask.visualize(uvw,filename='uvw')\n \n\n \n chan_chunk_size = vis_dataset[_sel_parms['data_in']].chunks[2][0]\n freq_chan = da.from_array(vis_dataset.coords['chan'].values, chunks=(chan_chunk_size))\n \n #print('2. numba',vis_dataset[_sel_parms['data_in']][:,0,0,0].values)\n vis_rot = da.map_blocks(apply_phasor,vis_dataset[_sel_parms['data_in']].data,uvw[:,:,:,None], vis_dataset.field_id.data[:,None,None,None],freq_chan[None,None,:,None],phase_rotation,_rotation_parms['common_tangent_reprojection'],dtype=np.complex)\n \n #dask.visualize(uvw,filename='uvw_rot')\n #dask.visualize(vis_rot,filename='vis_rot')\n \n vis_dataset[_sel_parms['uvw_out']] = xr.DataArray(uvw, dims=vis_dataset[_sel_parms['uvw_in']].dims)\n vis_dataset[_sel_parms['data_out']] = xr.DataArray(vis_rot, dims=vis_dataset[_sel_parms['data_in']].dims)\n \n# dask.visualize(vis_dataset[_sel_parms['uvw_out']],filename='uvw_rot_dataset')\n# dask.visualize(vis_dataset[_sel_parms['data_out']],filename='vis_rot_dataset')\n# dask.visualize(vis_dataset,filename='vis_dataset_before_append')\n \n list_xarray_data_variables = [vis_dataset[_sel_parms['uvw_out']],vis_dataset[_sel_parms['data_out']]]\n return _store(vis_dataset,list_xarray_data_variables,_storage_parms)\n\n\n@jit(nopython=True,cache=True, nogil=True)\ndef phasor_loop(phase_direction,uvw,phase_rotation,field_id,end_slice):\n for i_time in range(uvw.shape[0]):\n phase_direction[i_time,:] = uvw[i_time,:,0:end_slice,0] @ phase_rotation[field_id[i_time,0,0,0],0:end_slice]\n\n\ndef _directional_cosine(phase_center_in_radians):\n '''\n # In https://arxiv.org/pdf/astro-ph/0207413.pdf see equation 160\n phase_center_in_radians (RA,DEC)\n '''\n import numpy as np\n \n phase_center_cosine = np.zeros((3,))\n phase_center_cosine[0] = np.cos(phase_center_in_radians[0])*np.cos(phase_center_in_radians[1])\n phase_center_cosine[1] = np.sin(phase_center_in_radians[0])*np.cos(phase_center_in_radians[1])\n phase_center_cosine[2] = np.sin(phase_center_in_radians[1])\n return phase_center_cosine\n\n \n\n#Apply rotation to vis data\n@jit(nopython=True,cache=True, nogil=True)\ndef apply_phasor(vis_data,uvw, field_id,freq_chan,phase_rotation,common_tangent_reprojection):\n #print(vis_data.shape,uvw.shape,field_id.shape,freq_chan.shape,phase_rotation.shape)\n \n #print(vis_data[:,0,0,0])\n \n if common_tangent_reprojection:\n end_slice = 2\n else:\n end_slice = 3\n \n \n #start = time.time()\n \n N_time = vis_data.shape[0]\n N_baseline = vis_data.shape[1]\n N_chan = vis_data.shape[2]\n N_pol = vis_data.shape[3]\n \n #########################\n for i_time in range(N_time):\n for i_baseline in range(N_baseline):\n if common_tangent_reprojection:\n phase_direction = uvw[i_time,i_baseline,0,0] * phase_rotation[field_id[i_time,0,0,0],0] + uvw[i_time,i_baseline,1,0] * phase_rotation[field_id[i_time,0,0,0],1]\n else:\n phase_direction = uvw[i_time,i_baseline,0,0] * phase_rotation[field_id[i_time,0,0,0],0] + uvw[i_time,i_baseline,1,0] * phase_rotation[field_id[i_time,0,0,0],1] +uvw[i_time,i_baseline,2,0] * phase_rotation[field_id[i_time,0,0,0],2]\n \n \n for i_chan in range(N_chan):\n for i_pol in range(N_pol):\n vis_data[i_time,i_baseline,i_chan,i_pol] = vis_data[i_time,i_baseline,i_chan,i_pol]*np.exp(2.0*1j*np.pi*phase_direction*freq_chan[0,0,i_chan,0]/scipy.constants.c)\n #print('Time to apply phasor',time.time()-start)\n \n #print(vis_data[:,0,0,0])\n \n #vis_rot[np.isnan(vis_rot)] = np.nan\n vis_data = (vis_data.astype(np.complex64)).astype(np.complex128)\n \n return vis_data\n","sub_path":"ngcasa/imaging/phase_rotate_numba.py","file_name":"phase_rotate_numba.py","file_ext":"py","file_size_in_byte":9916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"264986107","text":"n=int(input())\na=input().split()\nar=[]\ns=\"\"\nfor i in a:\n ar.append(i)\nfor i in range(0,n-1):\n c=0\n for j in range(i+1,n-1):\n if(ar[i]==ar[j]):\n c=c+1\n if(c!=0 and (ar[i] not in s)):\n s=s+str(ar[i])+\" \"\nif(s==\"\"):\n print(\"Unique\")\nelse:\n print(s)\n","sub_path":"duplicate.py","file_name":"duplicate.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"166306194","text":"# coding=utf-8\n# Author: Jianghan LI\n# Question: 416.Partition_Equal_Subset_Sum\n# Date: 2017-04-29 2:02 - 2:07\n\n\nclass Solution(object):\n\n def canPartition(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n if sum(nums) & 1 == 0:\n target = sum(nums) >> 1\n cur = {0}\n for i in nums:\n cur |= {i + x for x in cur}\n if target in cur:\n return True\n return False\n\n def canPartition(self, nums):\n return (sum(nums) / 2.) in reduce(lambda cur, x: cur | {v + x for v in cur}, nums, {0})\n\n# https://discuss.leetcode.com/topic/64124/4-line-passed-python-solution/2\n","sub_path":"problems/416.Partition_Equal_Subset_Sum/li.py","file_name":"li.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"467339377","text":"# Configuration file for jupyterhub.\nimport os\nimport socket\nfrom kubespawner import KubeSpawner\nimport dummyauthenticator\nimport pymysql\nfrom oauthenticator.generic import GenericOAuthenticator, GenericLoginHandler\nfrom tornado import gen, web\nfrom tornado.httpclient import AsyncHTTPClient, HTTPRequest\nfrom tornado.httputil import url_concat\nfrom traitlets.config import get_config, json, sys\nfrom kubernetes.client.rest import ApiException\nfrom jupyterhub.utils import exponential_backoff\nimport base64\nimport urllib\nimport json\nimport time\nimport urllib.request\nfrom jose import jwk, jwt\nfrom jose.utils import base64url_decode\nimport os\n\n## AWS Cognito Configuration\nclass Custom_Cognito_Authenticator(GenericOAuthenticator):\n @staticmethod\n def id_token_decoder(id_token):\n token = id_token\n region = os.environ['AWS_COGNITO_REGION']\n userpool_id = os.environ['AWS_COGNITO_USERPOOL_ID']\n app_client_id = os.environ['AWS_COGNITO_CLIENT_ID']\n keys_url = 'https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json'.format(region, userpool_id)\n # instead of re-downloading the public keys every time\n # we download them only on cold start\n # https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/\n with urllib.request.urlopen(keys_url) as f:\n response = f.read()\n keys = json.loads(response.decode('utf-8'))['keys']\n # get the kid from the headers prior to verification\n headers = jwt.get_unverified_headers(token)\n kid = headers['kid']\n # search for the kid in the downloaded public keys\n key_index = -1\n for i in range(len(keys)):\n if kid == keys[i]['kid']:\n key_index = i\n break\n if key_index == -1:\n print('Public key not found in jwks.json')\n return False\n # construct the public key\n public_key = jwk.construct(keys[key_index])\n # get the last two sections of the token,\n # message and signature (encoded in base64)\n message, encoded_signature = str(token).rsplit('.', 1)\n # decode the signature\n decoded_signature = base64url_decode(encoded_signature.encode('utf-8'))\n # verify the signature\n if not public_key.verify(message.encode(\"utf8\"), decoded_signature):\n print('Signature verification failed')\n return False\n print('Signature successfully verified')\n # since we passed the verification, we can now safely\n # use the unverified claims\n claims = jwt.get_unverified_claims(token)\n # additionally we can verify the token expiration\n if time.time() > claims['exp']:\n print('Token is expired')\n return False\n # and the Audience (use claims['client_id'] if verifying an access token)\n if claims['aud'] != app_client_id:\n print('Token was not issued for this audience')\n return False\n # now we can use the claims\n print(\"****************************************************\")\n print(claims)\n global list_of_roles\n list_of_roles = []\n if 'cognito:groups' in claims:\n list_of_roles.append(claims['cognito:groups'])\n return claims\n\n @gen.coroutine\n def authenticate(self, handler, data=None):\n code = handler.get_argument(\"code\")\n # TODO: Configure the curl_httpclient for tornado\n http_client = AsyncHTTPClient()\n\n params = dict(\n redirect_uri=self.get_callback_url(handler),\n code=code,\n grant_type='authorization_code'\n )\n params.update(self.extra_params)\n\n if self.token_url:\n url = self.token_url\n else:\n raise ValueError(\"Please set the OAUTH2_TOKEN_URL environment variable\")\n\n b64key = base64.b64encode(\n bytes(\n \"{}:{}\".format(self.client_id, self.client_secret),\n \"utf8\"\n )\n )\n\n headers = {\n \"Accept\": \"application/json\",\n \"User-Agent\": \"JupyterHub\",\n \"Authorization\": \"Basic {}\".format(b64key.decode(\"utf8\"))\n }\n req = HTTPRequest(url,\n method=\"POST\",\n headers=headers,\n validate_cert=self.tls_verify,\n body=urllib.parse.urlencode(params) # Body is required for a POST...\n )\n\n resp = yield http_client.fetch(req)\n resp_json = json.loads(resp.body.decode('utf8', 'replace'))\n self.log.info(\"######################################\")\n self.log.info(resp_json)\n\n access_token = resp_json['access_token']\n refresh_token = resp_json.get('refresh_token', None)\n token_type = resp_json['token_type']\n id_token = resp_json['id_token']\n ########\n self.id_token_decoder(id_token) \n ########\n scope = resp_json.get('scope', '')\n if (isinstance(scope, str)):\n scope = scope.split(' ') \n\n # Determine who the logged in user is\n headers = {\n \"Accept\": \"application/json\",\n \"User-Agent\": \"JupyterHub\",\n \"Authorization\": \"{} {}\".format(token_type, access_token)\n }\n if self.userdata_url:\n url = url_concat(self.userdata_url, self.userdata_params)\n self.log.info(\"%%%%%%%%%%%%%%%%%%%%%%%%\")\n self.log.info(url)\n else:\n raise ValueError(\"Please set the OAUTH2_USERDATA_URL environment variable\")\n\n req = HTTPRequest(url,\n method=self.userdata_method,\n headers=headers,\n validate_cert=self.tls_verify,\n )\n resp = yield http_client.fetch(req)\n resp_json = json.loads(resp.body.decode('utf8', 'replace'))\n self.log.info(resp_json)\n\n if not resp_json.get(self.username_key):\n self.log.error(\"OAuth user contains no key %s: %s\", self.username_key, resp_json)\n return\n self.log.info(resp_json)\n \n return {\n 'name': resp_json.get(self.username_key),\n 'auth_state': {\n 'access_token': access_token,\n 'refresh_token': refresh_token,\n 'oauth_user': resp_json,\n 'scope': scope,\n }\n }\n \nc.JupyterHub.authenticator_class = Custom_Cognito_Authenticator\nc.OAuthenticator.client_id = os.environ['AWS_COGNITO_CLIENT_ID']\nc.OAuthenticator.client_secret = os.environ['AWS_COGNITO_CLIENT_SECRET'] \nc.OAuthenticator.login_service = os.environ['AWS_COGNITO_LOGIN_SERVICE'] \nc.OAuthenticator.oauth_callback_url = os.environ['AWS_COGNITO_OAUTH_CALLBACK_URL']\n\nc.Authenticator.allowed_users = {'iammanshi116@gmail.com', 'abcd@gmail.com'}\nc.Authenticator.admin_users = {'iammanshi116@gmail.com'}\n\n## Custom Kubespawner\nclass Custon_KubeSpawner(KubeSpawner):\n @gen.coroutine\n def _start(self):\n \"\"\"Start the user's pod\"\"\"\n\n # load user options (including profile)\n yield self.load_user_options()\n\n ## load roles\n self.log.info(\"******************************\")\n self.log.info(list_of_roles)\n roles = []\n if len(list_of_roles)> 0 :\n roles = list_of_roles[0]\n else:\n roles = ['RECENTLY_SIGNED']\n self.log.info(roles)\n # custom volume mount path \n admin_volume_path = [{'mountPath': '/home/myuser/work/',\n 'name': 'persistent-storage',\n 'subPath': 'home-folder'}]\n student_engine_volume_path = [{'mountPath': '/home/myuser/work/',\n 'name': 'persistent-storage',\n 'subPath': 'home-folder/pyspark-engine'}]\n recommendation_engine_volume_path = [{'mountPath': '/home/myuser/work/',\n 'name': 'persistent-storage',\n 'subPath': 'home-folder/scipy-engine'}]\n analytics_engine_volume_path = [{'mountPath': '/home/myuser/work/',\n 'name': 'persistent-storage',\n 'subPath': 'home-folder/datascience-engine'}]\n\n if (\"ADMIN\" in roles):\n self.image = 'aws_account_id.dkr.ecr.region.amazonaws.com/datascience-notebook:latest'\n self.volume_mounts = admin_volume_path\n elif (\"PYSPARK_RUNTIME_USER\" in roles):\n self.image = 'aws_account_id.dkr.ecr.region.amazonaws.com/pyspark-notebook:latest'\n self.volume_mounts = student_engine_volume_path\n elif (\"SCIPY_RUNTIME_USER\" in roles):\n self.image = 'aws_account_id.dkr.ecr.region.amazonaws.com/scipy-notebook:latest'\n self.volume_mounts = student_engine_volume_path\n elif (\"DATASCIENCE_RUNTIME_USER\" in roles):\n self.image = 'aws_account_id.dkr.ecr.region.amazonaws.com/scipy-notebook:latest'\n self.volume_mounts = student_engine_volume_path\n else:\n # spawn a normal notebook only\n self.image = 'jupyter/base-notebook:latest'\n\n # record latest event so we don't include old\n # events from previous pods in self.events\n # track by order and name instead of uid\n # so we get events like deletion of a previously stale\n # pod if it's part of this spawn process\n events = self.events\n if events:\n self._last_event = events[-1].metadata.uid\n\n if self.storage_pvc_ensure:\n # Try and create the pvc. If it succeeds we are good. If\n # returns a 409 indicating it already exists we are good. If\n # it returns a 403, indicating potential quota issue we need\n # to see if pvc already exists before we decide to raise the\n # error for quota being exceeded. This is because quota is\n # checked before determining if the PVC needed to be\n # created.\n\n pvc = self.get_pvc_manifest()\n\n try:\n yield self.asynchronize(\n self.api.create_namespaced_persistent_volume_claim,\n namespace=self.namespace,\n body=pvc\n )\n except ApiException as e:\n if e.status == 409:\n self.log.info(\"PVC \" + self.pvc_name + \" already exists, so did not create new pvc.\")\n\n elif e.status == 403:\n t, v, tb = sys.exc_info()\n\n try:\n yield self.asynchronize(\n self.api.read_namespaced_persistent_volume_claim,\n name=self.pvc_name,\n namespace=self.namespace)\n\n except ApiException as e:\n raise v.with_traceback(tb)\n\n self.log.info(\"PVC \" + self.pvc_name + \" already exists, possibly have reached quota though.\")\n\n else:\n raise\n\n # If we run into a 409 Conflict error, it means a pod with the\n # same name already exists. We stop it, wait for it to stop, and\n # try again. We try 4 times, and if it still fails we give up.\n # FIXME: Have better / cleaner retry logic!\n retry_times = 4\n pod = yield self.get_pod_manifest()\n if self.modify_pod_hook:\n pod = yield gen.maybe_future(self.modify_pod_hook(self, pod))\n for i in range(retry_times):\n try:\n yield self.asynchronize(\n self.api.create_namespaced_pod,\n self.namespace,\n pod,\n )\n break\n except ApiException as e:\n if e.status != 409:\n # We only want to handle 409 conflict errors\n self.log.exception(\"Failed for %s\", pod.to_str())\n raise\n self.log.info('Found existing pod %s, attempting to kill', self.pod_name)\n # TODO: this should show up in events\n yield self.stop(True)\n\n self.log.info('Killed pod %s, will try starting singleuser pod again', self.pod_name)\n else:\n raise Exception(\n 'Can not create user pod %s already exists & could not be deleted' % self.pod_name)\n\n # we need a timeout here even though start itself has a timeout\n # in order for this coroutine to finish at some point.\n # using the same start_timeout here\n # essentially ensures that this timeout should never propagate up\n # because the handler will have stopped waiting after\n # start_timeout, starting from a slightly earlier point.\n try:\n yield exponential_backoff(\n lambda: self.is_pod_running(self.pod_reflector.pods.get(self.pod_name, None)),\n 'pod/%s did not start in %s seconds!' % (self.pod_name, self.start_timeout),\n timeout=self.start_timeout,\n )\n except TimeoutError:\n if self.pod_name not in self.pod_reflector.pods:\n # if pod never showed up at all,\n # restart the pod reflector which may have become disconnected.\n self.log.error(\n \"Pod %s never showed up in reflector, restarting pod reflector\",\n self.pod_name,\n )\n self._start_watching_pods(replace=True)\n raise\n\n pod = self.pod_reflector.pods[self.pod_name]\n self.pod_id = pod.metadata.uid\n if self.event_reflector:\n self.log.debug(\n 'pod %s events before launch: %s',\n self.pod_name,\n \"\\n\".join(\n [\n \"%s [%s] %s\" % (event.last_timestamp or event.event_time, event.type, event.message)\n for event in self.events\n ]\n ),\n )\n return (pod.status.pod_ip, self.port)\n\nc.JupyterHub.spawner_class = Custon_KubeSpawner\n\nc.JupyterHub.ip = '0.0.0.0'\nc.JupyterHub.hub_ip = '0.0.0.0'\nc.Spawner.http_timeout = 60 * 5\nc.KubeSpawner.start_timeout = 60 * 5\nc.JupyterHub.cleanup_servers = False\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.connect((\"8.8.8.8\", 80))\nhost_ip = s.getsockname()[0]\ns.close()\nc.KubeSpawner.hub_connect_ip = host_ip\nc.JupyterHub.redirect_to_server = True\nc.JupyterHub.allow_named_servers = True\nc.JupyterHub.cleanup_servers = True\nc.JupyterHub.shutdown_on_logout = True\n\nc.KubeSpawner.service_account = 'default'\nc.KubeSpawner.image_pull_policy = 'IfNotPresent'\n\n## database\nc.JupyterHub.db_url = os.environ['DB_URL']\n\n## switch from notebook to lab\n#c.KubeSpawner.default_url ='/user/{username}/lab?'\n#c.Spawner.default_url = '/lab'\n\n# resources configuration\nc.KubeSpawner.cpu_limit = 1\nc.KubeSpawner.cpu_guarantee = 0.1\nc.KubeSpawner.mem_limit = '1G'\nc.KubeSpawner.mem_guarantee = '100M'\n\nif os.environ['ENVIRONMENT']=='local':\n ## volumes and volume mounts in NFS (Local)\n c.KubeSpawner.volumes = [\n {\n 'name': 'persistent-storage',\n 'persistentVolumeClaim': {\n 'claimName': 'nfs-pvc-claim'\n }\n }\n ]\nelse:\n ## volumes and volume mounts in EFS (AWS)\n c.KubeSpawner.volumes = [\n {\n 'name': 'persistent-storage',\n 'persistentVolumeClaim': {\n 'claimName': 'efs-claim'\n }\n }\n ]\n\n## cull_idle\nc.JupyterHub.services = [\n {\n 'name': 'cull-idle',\n 'admin': True,\n 'command': 'python3 cull_idle.py --timeout=600'.split(),\n }\n]\n\n\n\n\n","sub_path":"jupyterhub/jupyterhub_config.py","file_name":"jupyterhub_config.py","file_ext":"py","file_size_in_byte":15857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"237407598","text":"import falcon\nimport json\n\nfrom collections import OrderedDict\nfrom myretail_restful_service.common import common, exceptions\n\n\nclass Resource(object):\n def on_get(self, req, resp, id):\n redis_db = common.Common().verify_successful_redis_connection()\n product = RetrieveData()\n resp.body = json.dumps(product.get_combined_data(id, redis_db))\n resp.status = falcon.HTTP_200\n\n def on_put(self, req, resp, id):\n redis_db = common.Common().verify_successful_redis_connection()\n new_product = req.stream.read()\n write_data = UpdateData().write_price_to_db(id, new_product, redis_db)\n resp.body = write_data\n resp.status = falcon.HTTP_200\n\n\nclass UpdateData(object):\n def write_price_to_db(self, id, new_product, redis_db):\n new_value = self.get_new_product_price(new_product)\n external_api = common.Common().get_external_api()\n product_id = common.Common().verify_id_exists_in_external_api(\n id, external_api)\n common.Common().verify_id_exists_in_database(id)\n redis_db.hset(product_id, \"value\", new_value)\n return ('New Product Value Written to Database Successfully')\n\n def get_new_product_price(self, new_product):\n try:\n return json.loads(new_product)[\"current_price\"][\"value\"]\n except Exception:\n exceptions.FalconExceptions().json_wrong_type()\n\n\nclass RetrieveData(object):\n def get_external_data(self, id):\n external_dict = {}\n # get external api from common method\n external_api = common.Common().get_external_api()\n # check if id that is passed it is in the external API\n # and return product_id\n product_id = common.Common().verify_id_exists_in_external_api(\n id, external_api)\n title = (\n external_api['product']['item']['product_description']['title'])\n\n external_dict['id'] = product_id\n external_dict['name'] = title\n\n return external_dict\n\n def get_database_data(self, id, redis_db):\n price_dict = {}\n # use id from URL\n if common.Common().verify_id_exists_in_database(id):\n current_price = redis_db.hgetall(id)\n # convert price from string that redis stores to float\n current_price['value'] = float(current_price['value'])\n price_dict['current_price'] = current_price\n\n return price_dict\n\n def get_combined_data(self, id, redis_db):\n external_data = self.get_external_data(id)\n database_data = self.get_database_data(id, redis_db)\n combined_data = {}\n\n # combine data into one dict\n for data in (external_data, database_data):\n combined_data.update(data)\n\n # order the dict using OrderedDict for output\n key_order = ('id', 'name', 'current_price')\n ordered_combined_data = OrderedDict(\n (k, combined_data[k]) for k in key_order)\n return ordered_combined_data\n","sub_path":"myretail_restful_service/products/products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"368199367","text":"import random\nimport logging\n\nimport numpy as np\n\ndef kill_signal(recordings, threshold, window_size):\n \"\"\"\n Thresholds recordings, values above 'threshold' are considered signal\n (set to 0), a window of size 'window_size' is drawn around the signal\n points and those observations are also killed\n\n Returns\n -------\n recordings: numpy.ndarray\n The modified recordings with values above the threshold set to 0\n is_noise_idx: numpy.ndarray\n A boolean array with the same shap as 'recordings' indicating if the\n observation is noise (1) or was killed (0).\n \"\"\"\n recordings = np.copy(recordings)\n\n T, C = recordings.shape\n R = int((window_size-1)/2)\n\n # this will hold a flag 1 (noise), 0 (signal) for every obseration in the\n # recordings\n is_noise_idx = np.zeros((T, C))\n\n # go through every neighboring channel\n for c in range(C):\n\n # get obserations where observation is above threshold\n idx_temp = np.where(np.abs(recordings[:, c]) > threshold)[0]\n\n # shift every index found\n for j in range(-R, R+1):\n\n # shift\n idx_temp2 = idx_temp + j\n\n # remove indexes outside range [0, T]\n idx_temp2 = idx_temp2[np.logical_and(idx_temp2 >= 0,\n idx_temp2 < T)]\n\n # set surviving indexes to nan\n recordings[idx_temp2, c] = np.nan\n\n # noise indexes are the ones that are not nan\n # FIXME: compare to np.nan instead\n is_noise_idx_temp = (recordings[:, c] == recordings[:, c])\n\n # standarize data, ignoring nans\n recordings[:, c] = recordings[:, c]/np.nanstd(recordings[:, c])\n\n # set non noise indexes to 0 in the recordings\n recordings[~is_noise_idx_temp, c] = 0\n\n # save noise indexes\n is_noise_idx[is_noise_idx_temp, c] = 1\n\n return recordings, is_noise_idx\n\n\ndef noise_cov(recordings, temporal_size, window_size, sample_size=1000,\n threshold=3.0, max_trials_per_sample=100,\n allow_smaller_sample_size=False):\n \"\"\"Compute noise temporal and spatial covariance\n\n Parameters\n ----------\n recordings: numpy.ndarray\n Recordings\n\n temporal_size:\n Waveform size\n\n sample_size: int\n Number of noise snippets of temporal_size to search\n\n threshold: float\n Observations below this number are considered noise\n\n Returns\n -------\n spatial_SIG: numpy.ndarray\n\n temporal_SIG: numpy.ndarray\n \"\"\"\n logger = logging.getLogger(__name__)\n\n # kill signal above threshold in recordings\n logger.info('Get Noise Floor')\n rec, is_noise_idx = kill_signal(recordings, threshold, window_size)\n\n # compute spatial covariance, output: (n_channels, n_channels)\n logger.info('Compute Spatial Covariance')\n spatial_cov = np.divide(np.matmul(rec.T, rec),\n np.matmul(is_noise_idx.T, is_noise_idx))\n\n # compute spatial sig\n w_spatial, v_spatial = np.linalg.eig(spatial_cov)\n spatial_SIG = np.matmul(np.matmul(v_spatial,\n np.diag(np.sqrt(w_spatial))),\n v_spatial.T)\n\n # apply spatial whitening to recordings\n logger.info('Compute Temporal Covaraince')\n spatial_whitener = np.matmul(np.matmul(v_spatial,\n np.diag(1/np.sqrt(w_spatial))),\n v_spatial.T)\n rec = np.matmul(rec, spatial_whitener)\n\n # search single noise channel snippets\n noise_wf = search_noise_snippets(\n rec, is_noise_idx, sample_size,\n temporal_size,\n channel_choices=None,\n max_trials_per_sample=max_trials_per_sample,\n allow_smaller_sample_size=allow_smaller_sample_size)\n\n w, v = np.linalg.eig(np.cov(noise_wf.T))\n\n temporal_SIG = np.matmul(np.matmul(v, np.diag(np.sqrt(w))), v.T)\n\n return spatial_SIG, temporal_SIG\n\n\ndef search_noise_snippets(recordings, is_noise_idx, sample_size,\n temporal_size, channel_choices=None,\n max_trials_per_sample=100,\n allow_smaller_sample_size=False):\n \"\"\"\n Randomly search noise snippets of 'temporal_size'\n\n Parameters\n ----------\n channel_choices: list\n List of sets of channels to select at random on each trial\n max_trials_per_sample: int, optional\n Maximum random trials per sample\n allow_smaller_sample_size: bool, optional\n If 'max_trials_per_sample' is reached and this is True, the noise\n snippets found up to that time are returned\n\n Raises\n ------\n ValueError\n if after 'max_trials_per_sample' trials, no noise snippet has been\n found this exception is raised\n\n Notes\n -----\n Channels selected at random using the random module from the standard\n library (not using np.random)\n \"\"\"\n logger = logging.getLogger(__name__)\n\n T, C = recordings.shape\n\n if channel_choices is None:\n noise_wf = np.zeros((sample_size, temporal_size))\n else:\n lenghts = set([len(ch) for ch in channel_choices])\n\n if len(lenghts) > 1:\n raise ValueError('All elements in channel_choices must have '\n 'the same length, got {}'.format(lenghts))\n\n n_channels = len(channel_choices[0])\n noise_wf = np.zeros((sample_size, temporal_size, n_channels))\n\n count = 0\n\n logger.debug('Starting to search noise snippets...')\n\n trial = 0\n\n # repeat until you get sample_size noise snippets\n while count < sample_size:\n\n # random number for the start of the noise snippet\n t_start = np.random.randint(T-temporal_size)\n\n if channel_choices is None:\n # random channel\n ch = random.randint(0, C - 1)\n else:\n ch = random.choice(channel_choices)\n\n t_slice = slice(t_start, t_start+temporal_size)\n\n # get a snippet from the recordings and the noise flags for the same\n # location\n snippet = recordings[t_slice, ch]\n snipped_idx_noise = is_noise_idx[t_slice, ch]\n\n # check if all observations in snippet are noise\n if snipped_idx_noise.all():\n # add the snippet and increase count\n noise_wf[count] = snippet\n count += 1\n trial = 0\n\n logger.debug('Found %i/%i...', count, sample_size)\n\n trial += 1\n\n if trial == max_trials_per_sample:\n if allow_smaller_sample_size:\n return noise_wf[:count]\n else:\n raise ValueError(\"Couldn't find snippet {} of size {} after \"\n \"{} iterations (only {} found)\"\n .format(count + 1, temporal_size,\n max_trials_per_sample,\n count))\n\n return noise_wf\n","sub_path":"src/yass/augment/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":6963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"407316623","text":"import dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.graph_objs as go\nimport pandas as pd\nimport pathlib\nfrom app import app\n\n# get relative data folder\nPATH = pathlib.Path(__file__).parent\nDATA_PATH = PATH.joinpath(\"../datasets\").resolve()\n\ncovid = pd.read_csv(DATA_PATH.joinpath('Covid 19 data 2020-01-22 to 2020-12-25.csv'))\n\nlayout = html.Div([\n\nhtml.Div([\n html.Div([\n\n html.P('World: Covid - 19 data 2020-01-22 to 2020-12-25', className = 'fix_label', style = {'color': 'black', 'margin-top': '2px'}),\n dcc.Dropdown(id = 'select_country1',\n multi = False,\n clearable = True,\n disabled = False,\n style = {'display': True},\n value = 'US',\n placeholder = 'Select country',\n options = [{'label': c, 'value': c}\n for c in (covid['Country/Region'].unique())], className = 'dcc_compon'),\n\n html.P('Select Category', className = 'fix_label', style = {'color': 'black', 'margin-top': '2px'}),\n dcc.RadioItems(id = 'radio_items',\n labelStyle = {\"display\": \"inline-block\"},\n options = [{'label': 'Confirmed', 'value': 'confirmed1'},\n {'label': 'Deaths', 'value': 'deaths1'},\n {'label': 'Recovered', 'value': 'recovered1'},\n {'label': 'Active', 'value': 'active1'}],\n value = 'confirmed1',\n style = {'text-align': 'center', 'color': 'black'}, className = 'dcc_compon'),\n\n ], className = \"create_container2 four columns\", style = {'margin-bottom': '20px', \"margin-top\": \"20px\"}),\n\n ], className = \"row flex-display\"),\n\n html.Div([\n html.Div([\n\n dcc.Graph(id = 'map_2',\n config = {'displayModeBar': 'hover'}),\n\n ], className = \"create_container2 eight columns\"),\n\n ], className = \"row flex-display\"),\n\n\n\n\n], id=\"mainContainer\", style={\"display\": \"flex\", \"flex-direction\": \"column\"})\n\n\n@app.callback(Output('map_2', 'figure'),\n [Input('select_country1', 'value')],\n [Input('radio_items', 'value')])\ndef update_graph(select_country1, radio_items):\n covid1 = covid.groupby(['Country/Region', 'Lat', 'Long'])[['confirmed', 'death', 'recovered', 'active']].max().reset_index()\n covid2 = covid1[covid1['Country/Region'] == select_country1]\n\n\n if radio_items == 'confirmed1':\n\n return {\n 'data': [go.Scattermapbox(\n lon = list(covid2['Long']),\n lat = list(covid2['Lat']),\n mode = 'markers',\n marker = dict(\n size = covid2['confirmed'] / 4000,\n color = 'orange',\n sizemode = 'area'),\n\n hoverinfo = 'text',\n hovertext =\n 'Country: ' + covid2['Country/Region'].astype(str) + '
' +\n 'Lat: ' + [f'{x:.4f}' for x in covid2['Lat']] + '
' +\n 'Long: ' + [f'{x:.4f}' for x in covid2['Long']] + '
' +\n 'Confirmed: ' + [f'{x:,.0f}' for x in covid2['confirmed']] + '
'\n\n )],\n\n 'layout': go.Layout(\n margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0},\n hovermode='closest',\n mapbox=dict(\n accesstoken='pk.eyJ1IjoicXM2MjcyNTI3IiwiYSI6ImNraGRuYTF1azAxZmIycWs0cDB1NmY1ZjYifQ.I1VJ3KjeM-S613FLv3mtkw', # Create free account on Mapbox site and paste here access token\n center=go.layout.mapbox.Center(lat=36, lon=-5.4),\n style='open-street-map',\n # style='dark',\n zoom=1.2\n ),\n autosize=True,\n\n )\n\n }\n\n elif radio_items == 'deaths1':\n\n return {\n 'data': [go.Scattermapbox(\n lon = covid2['Long'],\n lat = covid2['Lat'],\n mode = 'markers',\n marker = dict(\n size = covid2['death'] / 500,\n color = '#dd1e35',\n sizemode = 'area'),\n\n hoverinfo = 'text',\n hovertext =\n 'Country: ' + covid2['Country/Region'].astype(str) + '
' +\n 'Lat: ' + [f'{x:.4f}' for x in covid2['Lat']] + '
' +\n 'Long: ' + [f'{x:.4f}' for x in covid2['Long']] + '
' +\n 'Deaths: ' + [f'{x:,.0f}' for x in covid2['death']] + '
'\n\n )],\n\n 'layout': go.Layout(\n margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0},\n hovermode='closest',\n mapbox=dict(\n accesstoken='pk.eyJ1IjoicXM2MjcyNTI3IiwiYSI6ImNraGRuYTF1azAxZmIycWs0cDB1NmY1ZjYifQ.I1VJ3KjeM-S613FLv3mtkw', # Create free account on Mapbox site and paste here access token\n center=go.layout.mapbox.Center(lat=36, lon=-5.4),\n style='open-street-map',\n # style='dark',\n zoom=1.2\n ),\n autosize=True,\n\n )\n\n }\n\n elif radio_items == 'recovered1':\n\n return {\n 'data': [go.Scattermapbox(\n lon = covid2['Long'],\n lat = covid2['Lat'],\n mode = 'markers',\n marker = dict(\n size = covid2['recovered'] / 4000,\n color = 'green',\n sizemode = 'area'),\n\n hoverinfo = 'text',\n hovertext =\n 'Country: ' + covid2['Country/Region'].astype(str) + '
' +\n 'Lat: ' + [f'{x:.4f}' for x in covid2['Lat']] + '
' +\n 'Long: ' + [f'{x:.4f}' for x in covid2['Long']] + '
' +\n 'Recovered: ' + [f'{x:,.0f}' for x in covid2['recovered']] + '
'\n\n )],\n\n 'layout': go.Layout(\n margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0},\n hovermode='closest',\n mapbox=dict(\n accesstoken='pk.eyJ1IjoicXM2MjcyNTI3IiwiYSI6ImNraGRuYTF1azAxZmIycWs0cDB1NmY1ZjYifQ.I1VJ3KjeM-S613FLv3mtkw', # Create free account on Mapbox site and paste here access token\n center=go.layout.mapbox.Center(lat=36, lon=-5.4),\n style='open-street-map',\n # style='dark',\n zoom=1.2\n ),\n autosize=True,\n\n )\n\n }\n\n elif radio_items == 'active1':\n\n return {\n 'data': [go.Scattermapbox(\n lon = covid2['Long'],\n lat = covid2['Lat'],\n mode = 'markers',\n marker = dict(\n size = covid2['active'] / 4000,\n color = '#e55467',\n sizemode = 'area'),\n\n hoverinfo = 'text',\n hovertext =\n 'Country: ' + covid2['Country/Region'].astype(str) + '
' +\n 'Lat: ' + [f'{x:.4f}' for x in covid2['Lat']] + '
' +\n 'Long: ' + [f'{x:.4f}' for x in covid2['Long']] + '
' +\n 'Active: ' + [f'{x:,.0f}' for x in covid2['active']] + '
'\n\n )],\n\n 'layout': go.Layout(\n margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0},\n hovermode='closest',\n mapbox=dict(\n accesstoken='pk.eyJ1IjoicXM2MjcyNTI3IiwiYSI6ImNraGRuYTF1azAxZmIycWs0cDB1NmY1ZjYifQ.I1VJ3KjeM-S613FLv3mtkw', # Create free account on Mapbox site and paste here access token\n center=go.layout.mapbox.Center(lat=36, lon=-5.4),\n style='open-street-map',\n # style='dark',\n zoom=1.2\n ),\n autosize=True,\n\n )\n\n }\n","sub_path":"apps/World_covid_19_data.py","file_name":"World_covid_19_data.py","file_ext":"py","file_size_in_byte":8146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"148136920","text":"class Employee:\n\n raise_amt = 1.04\n\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.email = first + '.' + last + '@email.com'\n self.pay = pay\n\n def fullname(self):\n return '{} {}'.format(self.first, self.last)\n\n def apply_raise(self):\n self.pay = int(self.pay * self.raise_amt)\n\n\nclass Developer(Employee): # by inheritance, the Developer class has all the attributes and functions of the Employer.\n raise_amt = 1.1 # by changing the attibute in a sub-class, the parent will be unaffected\n\n def __init__(self, first, last, pay, prog_lang):\n super().__init__(first, last, pay) # calling the constructor of the parent\n self.prog_lang = prog_lang\n\n\nclass Manager(Employee):\n def __init__(self, first, last, pay, employees=None): # !!! Never pass a mutable data type as a default argument\n super().__init__(first, last, pay)\n if employees is None:\n self.employees = []\n else:\n self.employees = employees\n\n def add_emp(self, emp):\n if emp not in self.employees:\n self.employees.append(emp)\n\n def remove_emp(self, emp):\n if emp in self.employees:\n self.employees.remove(emp)\n\n def print_emp(self):\n for employee in self.employees:\n print('-->', employee.fullname())\n\n\nprint(help(Developer)) # you can see the \"Method resolution order\", all the attibutes and methods\ndev_1 = Developer('Corey', 'Schafer', 50000, 'Python')\nemp_1 = Employee('Test', 'Employee', 60000)\nmgr_1 = Manager('Ben', 'Abe', 90000, [dev_1])\n\nprint(dev_1.pay)\ndev_1.apply_raise()\nprint(dev_1.pay)\n\nprint(emp_1.pay)\nemp_1.apply_raise()\nprint(emp_1.pay)\n\nprint(dev_1.email)\nprint(dev_1.prog_lang)\n\nprint(mgr_1.email)\nmgr_1.add_emp(emp_1)\nmgr_1.print_emp()\nmgr_1.remove_emp(dev_1)\nmgr_1.print_emp()\n\nprint(isinstance(mgr_1, Manager)) # True\nprint(isinstance(mgr_1, Employee)) # True\nprint(isinstance(mgr_1, Developer)) # False\nprint(issubclass(Manager, Employee)) # True\nprint(issubclass(Manager, Developer)) # False\n","sub_path":"OOP/4. Inheritance.py","file_name":"4. Inheritance.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"368084898","text":"\"\"\"\n- Export demos\n- Collects scan durations for resting state\n- Checks that all subjects are present and compare par and nii count, export nii count\n- Reduces scans file\n- Calculates session durations\n\"\"\"\n\nimport os\nfrom lhab_pipelines.utils import read_tsv\nfrom lhab_pipelines.nii_conversion.post_conversion_utils import calc_demos, calc_session_duration, get_scan_duration, \\\n compare_par_nii, reduce_sub_files\n\nimport argparse\nimport getpass\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('raw_dir', help='The directory with the RAW input dataset.'\n '\\n original: bids_dir')\n parser.add_argument('output_base_dir', help='The directory where the output files '\n 'should be stored.'\n '\\n original: output_dir')\n parser.add_argument('--participant_file', help='participants that should be analyzed.'\n 'For the conversion wf this should be given as lhab_1234')\n\n parser.add_argument('--no-public_output',\n help=\"Don't create public output.\\nIf public_output: strips all info about original \"\n \"subject_id, file, date \\nDefault: use public_output\",\n default=True, dest=\"public_output\", action='store_false')\n parser.add_argument('--no-use_new_ids', help=\"Don't use new subject ids. \"\n \"\\nDefault: Use new ids from mapping file\",\n default=True, dest=\"use_new_ids\", action='store_false')\n parser.add_argument('--ds_version', help=\"Data set version (is added to output path)\", default=\"dev\")\n\n args = parser.parse_args()\n\n raw_dir = args.raw_dir\n\n # privacy settings\n public_output = args.public_output\n use_new_ids = args.use_new_ids\n if not (public_output and use_new_ids):\n private_str = \"_PRIVATE\"\n else:\n private_str = \"\"\n\n output_dir = os.path.join(args.output_base_dir, \"LHAB_\" + args.ds_version + private_str, \"sourcedata\")\n\n ###\n if args.participant_file:\n old_sub_id_list = read_tsv(args.participant_file, no_header=True).ix[:,0].tolist()\n else:\n raise Exception(\"No subjects specified\")\n\n ses_id_list = [\"T1\", \"T2\", \"T3\", \"T4\", \"T5\"]\n in_ses_folder = \"01_noIF\"\n new_id_lut_file = os.path.join(raw_dir, \"00_PRIVATE_sub_lists/new_sub_id_lut.tsv\")\n demo_file = os.path.join(raw_dir, \"00_PRIVATE_sub_lists/dob.zip\")\n\n #\n pwd = getpass.getpass(\"Enter the Password for dob file:\")\n\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n\n info_list = [\n {\"bids_name\": \"T1w\", \"bids_modality\": \"anat\", \"search_str\": \"_t1w_\"},\n {\"bids_name\": \"FLAIR\", \"bids_modality\": \"anat\", \"search_str\": \"_2dflair_\", \"acq\": \"2D\"},\n {\"bids_name\": \"FLAIR\", \"bids_modality\": \"anat\", \"search_str\": \"_3dflair_\", \"acq\": \"3D\"},\n {\"bids_name\": \"dwi\", \"bids_modality\": \"dwi\", \"search_str\": \"_dti_T\", \"only_use_last\": True, \"acq\": \"ap\"},\n {\"bids_name\": \"bold\", \"bids_modality\": \"func\", \"search_str\": \"_fmri_T\", \"task\": \"rest\", \"physio\": True},\n {\"bids_name\": \"bold\", \"bids_modality\": \"fmap\", \"search_str\": \"_fmri_pa_T\", \"acq\": \"pa\"},\n {\"bids_name\": \"dwi\", \"bids_modality\": \"fmap\", \"search_str\": \"_dti_pa_T\", \"acq\": \"pa\"},\n {\"bids_name\": \"dwi\", \"bids_modality\": \"fmap\", \"search_str\": \"_dti_ap_T\", \"acq\": \"ap\"}\n\n ]\n\n\n\n print(\"Exporting demos...\")\n calc_demos(output_dir,\n ses_id_list,\n raw_dir,\n in_ses_folder,\n demo_file,\n pwd,\n use_new_ids=use_new_ids,\n new_id_lut_file=new_id_lut_file,\n public_output=public_output,\n )\n\n print(\"Collecting scan durations...\")\n get_scan_duration(output_dir)\n\n print(\"\\n Check that all subjecst are present and compare par and nii count, export nii count...\")\n compare_par_nii(output_dir, old_sub_id_list, raw_dir, ses_id_list, in_ses_folder, info_list, new_id_lut_file)\n\n print(\"\\nReducing scans file...\")\n reduce_sub_files(output_dir, \"scans.tsv\", \"scans.tsv\")\n\n\n if not (public_output and use_new_ids):\n print(\"\\nCalculating session durations...\")\n calc_session_duration(output_dir, public_output, use_new_ids)\n","sub_path":"scripts/nii_conversion/run_post_conversion_routines.py","file_name":"run_post_conversion_routines.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"588489944","text":"import logging\nimport os\nimport sys\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Any, Iterator, List\n\nimport click\nfrom pre_commit.staged_files_only import staged_files_only\nfrom pre_commit.util import CalledProcessError, cmd_output, noop_context\n\nimport bento.git\nfrom bento.context import Context\nfrom bento.tool_runner import Runner, RunStep\nfrom bento.util import AutocompleteSuggestions, Colors, echo_error, echo_newline\n\nPATCH_CACHE = str(Path.home() / \".cache\" / \"bento\" / \"patches\")\n\n\nclass StatusCode:\n Added = \"A\"\n Deleted = \"D\"\n Renamed = \"R\"\n Unmerged = \"U\"\n Untracked = \"?\"\n Ignored = \"!\"\n\n\nGitStatus = namedtuple(\"GitStatus\", [\"added\", \"removed\", \"unmerged\"])\n\n\ndef git_status() -> GitStatus:\n \"\"\"\n Gets added, removed, and unmerged paths from the git index\n \"\"\"\n status_output = (\n cmd_output(\"git\", \"status\", \"--porcelain\", \"-z\")[1].rstrip().split(\"\\0\")\n )\n next_is_file = False\n added = []\n removed = []\n unmerged = []\n for s in status_output:\n if not s.strip():\n continue\n if next_is_file:\n # We are in source line of rename\n next_is_file = False\n removed.append(s)\n continue\n if s[0] == StatusCode.Untracked or s[0] == StatusCode.Ignored:\n continue\n\n fname = s[3:]\n # The following detection for unmerged codes comes from `man git-status`\n if (\n s[0] == StatusCode.Added\n and s[1] == StatusCode.Added\n or s[0] == StatusCode.Deleted\n and s[1] == StatusCode.Deleted\n or s[0] == StatusCode.Unmerged\n or s[1] == StatusCode.Unmerged\n ):\n unmerged.append(fname)\n if s[0] == StatusCode.Renamed:\n added.append(fname)\n next_is_file = True\n if s[0] == StatusCode.Added:\n added.append(fname)\n if s[0] == StatusCode.Deleted:\n removed.append(fname)\n logging.info(\n f\"Git status:\\nadded: {added}\\nremoved: {removed}\\nunmerged: {unmerged}\"\n )\n return GitStatus(added, removed, unmerged)\n\n\ndef _abort_if_untracked_and_removed(removed: List[str]) -> None:\n \"\"\"\n Aborts execution if any path is removed from the git index but also appears\n in the filesystem.\n\n :param removed (list): Removed paths\n :raises SystemExit: If any removed paths are present on filesystem\n \"\"\"\n untracked_removed = [r.replace(\" \", r\"\\ \") for r in removed if Path(r).exists()]\n if untracked_removed:\n joined = \" \".join(untracked_removed)\n\n def echo_cmd(cmd: str) -> None:\n click.echo(f\" $ {click.style(cmd, bold=True)}\\n\", err=True)\n\n echo_error(\n \"One or more files deleted from git exist on the filesystem. Aborting to prevent data loss. To \"\n \"continue, please stash by running the following two commands:\"\n )\n echo_newline()\n echo_cmd(f\"git stash -u -- {joined}\")\n echo_cmd(f\"git rm {joined}\")\n click.secho(\n \"Stashed changes can later be recovered by running:\\n\",\n err=True,\n fg=Colors.ERROR,\n )\n echo_cmd(f\"git stash pop\")\n sys.exit(3)\n\n\n@contextmanager\ndef head_context() -> Iterator[None]:\n \"\"\"\n Runs a block of code on files from the current branch HEAD.\n\n :raises subprocess.CalledProcessError: If git encounters an exception\n :raises SystemExit: If unmerged files are detected\n \"\"\"\n repo = bento.git.repo()\n\n if not repo:\n yield\n\n else:\n added, removed, unmerged = git_status()\n\n # Need to look for unmerged files first, otherwise staged_files_only will eat them\n if unmerged:\n echo_error(\n \"Please resolve merge conflicts in these files before continuing:\"\n )\n for f in unmerged:\n click.secho(f, err=True)\n sys.exit(3)\n\n with staged_files_only(PATCH_CACHE):\n tree = cmd_output(\"git\", \"write-tree\")[1].strip()\n _abort_if_untracked_and_removed(removed)\n try:\n for a in added:\n Path(a).unlink()\n cmd_output(\"git\", \"checkout\", \"HEAD\", \"--\", \".\")\n yield\n finally:\n # git checkout will fail if the checked-out index deletes all files in the repo\n # In this case, we still want to continue without error.\n # Note that we have no good way of detecting this issue without inspecting the checkout output\n # message, which means we are fragile with respect to git version here.\n try:\n cmd_output(\"git\", \"checkout\", tree.strip(), \"--\", \".\")\n except CalledProcessError as ex:\n if (\n ex.output\n and len(ex.output) >= 2\n and \"pathspec '.' did not match any file(s) known to git\"\n in ex.output[1].strip()\n ):\n logging.warning(\n \"Restoring git index failed due to total repository deletion; skipping checkout\"\n )\n else:\n raise ex\n if removed:\n cmd_output(\"git\", \"rm\", *removed)\n\n\n@contextmanager\ndef run_context(\n context: Context,\n target_paths: List[Path],\n staged: bool,\n run_step: RunStep,\n show_bars: bool = True,\n) -> Iterator[Runner]:\n \"\"\"\n Provides a context within which to run tools.\n\n This context obeys the following behaviors:\n\n Filesystem modifications:\n staged is true - file diffs are removed\n otherwise - no changes\n\n Paths to be checked:\n explicit paths - these paths are used\n staged is true - only paths with staged changes are used\n otherwise - only paths with diffs vs the head git index are used\n\n :param context: The Bento command context\n :param input_paths: A list of paths to check, or None to indicate that check should operate\n against the base path\n :param staged: Whether to use remove file diffs\n :param run_step: Which run step is in use (baseline if tool is determining baseline, check if tool is finding new results)\n :param show_bars: If true, attempts to configure Runner to display progress bars (these may not be displayed if not supported by environment)\n :return: A Python with-expression, which is passed a Runner object\n :raises Exception: If comparison is not HEAD and run_step is not CHECK\n \"\"\"\n use_cache = False\n skip_setup = True\n if staged and run_step == RunStep.BASELINE:\n stash_context = head_context()\n use_cache = True\n elif staged:\n # run_step = RunStep.CHECK\n stash_context = staged_files_only(PATCH_CACHE)\n else:\n # staged is False\n stash_context = noop_context()\n skip_setup = False\n\n with stash_context:\n yield Runner(\n paths=target_paths,\n use_cache=use_cache,\n skip_setup=skip_setup,\n show_bars=show_bars,\n )\n\n\ndef list_paths(ctx: Any, args: List[str], incomplete: str) -> AutocompleteSuggestions:\n \"\"\"\n Lists paths when tab autocompletion is used on a path argument.\n\n Note that click always adds a space at the end of a suggestion, so repeated tabbing\n can not be used to fill a path. :(\n\n :param ctx: Unused\n :param args: Unused\n :param incomplete: Any partial completion currently under the cursor\n :return: A list of completion suggestions\n \"\"\"\n # Cases for \"incomplete\" variable:\n # - '': Search '.', no filtering\n # - 'part_of_file': Search '.', filter\n # - 'path/to/dir/': Search 'path/to/dir', no filter\n # - 'path/to/dir/part_of_file': Search 'path/to/dir', filter\n dir_root = os.path.dirname(incomplete)\n path_stub = incomplete[len(dir_root) :]\n if path_stub.startswith(\"/\"):\n path_stub = path_stub[1:]\n if dir_root == \"\":\n dir_to_list = \".\"\n else:\n dir_to_list = dir_root\n return [\n os.path.join(dir_root, p)\n for p in os.listdir(dir_to_list)\n if not path_stub or p.startswith(path_stub)\n ]\n","sub_path":"bento/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":8407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"609180215","text":"'''\n phase1_2 : read POI IMAGE file and do CNN processing\n'''\nimport sys\nimport random as r\nimport time as t\nimport phase1_2_cnn_function as p1_2\n\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Convolution2D, Flatten, MaxPooling2D, GlobalMaxPool2D\nfrom keras.optimizers import Adam\nfrom keras import backend as kb\n\n\nif __name__ == \"__main__\" :\n\n ts = t.time()\n poiTYPE, side, poiIMG = p1_2.arg_setting (sys.argv)\n x_train, y_train, x_test, y_test = p1_2.departTrainTest (poiIMG, side)\n\n\n # Build CNN model\n model = Sequential()\n\n # Conv layer 1\n model.add (Convolution2D(32, 5, 5, border_mode='same', dim_ordering='th', input_shape=(1, side, side)))\n model.add (Activation('relu'))\n\n # Pooling layer 1\n model.add (MaxPooling2D(pool_size=(2,2), strides=(2,2), border_mode='same'))\n\n # Convolution layer 2\n model.add (Convolution2D(32, 7, 7, border_mode='same'))\n model.add (Activation('relu'))\n\n # Convolution layer 3\n model.add (Convolution2D(64, 5, 5, border_mode='same'))\n model.add (Activation('relu'))\n\n # Fully Connected layer 1\n model.add (Flatten())\n\n # Fully connected layer 2\n model.add (Dense(512))\n\n # Fully connected layer 3\n model.add (Dense(128))\n model.add (Activation('relu'))\n\n # Output layer\n model.add (Dense(1))\n model.add (Activation('relu'))\n\n\n # Optimizer\n adam = Adam(lr=5e-5)\n\n\n # Metrics method\n model.compile (optimizer=adam, loss='mse', metrics=['accuracy'])\n\n\n print (\"------------- Training ---------------\")\n\n # Train model\n model.fit (x_train, y_train, nb_epoch=64, batch_size=8)\n\n\n print (\"-------------- Testing ---------------\")\n\n # Evalution\n loss, accuracy = model.evaluate (x_test, y_test)\n\n\n print (\"--------------------------------------\")\n print (\"Layers : {}\".format(len(model.layers)))\n print (\"Tess loss : {}\".format(loss))\n print (\"Test accuracy : {}\".format(accuracy))\n\n\n # Regression Prediction\n y_pred = model.predict (x_test)\n\n\n print (len(y_pred))\n yp = []\n for cnt in range(len(y_pred)) :\n yp.append (y_pred[cnt][0])\n\n\n print (\"Ground Truth : {}\".format(len(y_test)))\n print (y_test)\n print (\"Predict :\")\n print (yp)\n\n\n # Get result index (ordered)\n yp_sort_pos = sorted (range(len(yp)), key=lambda k: yp[k])\n yp_sort_pos.reverse()\n\n y_test_sort_pos = sorted (range(len(y_test)), key=lambda k:y_test[k])\n y_test_sort_pos.reverse()\n\n ran = list(range(len(y_test)))\n r.shuffle (ran)\n\n \n print (\"Ground Truth position : {}\".format(y_test_sort_pos))\n print (\"Test output position : {}\".format(yp_sort_pos))\n print (\"Random position : {}\".format(ran))\n print (\"------------------------------------------------------\")\n ndcg5 = p1_2.NDCG(yp_sort_pos, y_test_sort_pos, 5)\n ndcg10 = p1_2.NDCG(yp_sort_pos, y_test_sort_pos, 10)\n print (\"NDCG5 : {}\".format(ndcg5))\n print (\"NDCG10 : {}\".format(ndcg10))\n print (\"------------------------------------------------------\")\n ran_ndcg5 = p1_2.NDCG(ran, y_test_sort_pos, 5)\n ran_ndcg10 = p1_2.NDCG(ran, y_test_sort_pos, 10)\n print (\"Random NDCG5 : {}\".format(ran_ndcg5))\n print (\"Random NDCG10 : {}\".format(ran_ndcg10))\n print (\"------------------------------------------------------\")\n\n wor = []\n for cnt in range(len(y_test_sort_pos)) :\n wor.append (y_test_sort_pos[len(y_test_sort_pos)-cnt-1])\n print (\"Worst NDCG5 : {}\".format(p1_2.NDCG(wor, y_test_sort_pos, 5)))\n print (\"Worst NDCG10 : {}\".format(p1_2.NDCG(wor, y_test_sort_pos, 10)))\n\n\n # Write result to file\n fileName = \"testResult_phase1_test1_\" + poiTYPE\n fw = open (fileName, 'a+')\n fw.write (str(ndcg5))\n fw.write ('\\t')\n fw.write (str(ndcg10))\n fw.write ('\\t')\n fw.write (str(ran_ndcg5))\n fw.write ('\\t')\n fw.write (str(ran_ndcg10))\n fw.write ('\\n')\n fw.close()\n\n\n te = t.time()\n print (\"Program excecuting time : {} (secs)\".format(te-ts))\n\n","sub_path":"phase_1/phase1_2.py","file_name":"phase1_2.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"347562968","text":"import re\r\nimport random\r\nfrom math import pi, log10, cos, sqrt\r\nfrom cmath import exp as cexp\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom scipy import optimize\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport glob\r\nimport seaborn as sns \r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nfrom const import *\r\nfrom func import calc_dist\r\n\r\nconst = Const()\r\n\r\n#クラスタAP間距離と選択されたシステムの関係\r\ndef graph_usedsystem():\r\n path = 'C:\\\\Users\\\\soraya-PC\\\\code\\\\data\\\\result\\\\UsedSystem\\\\'\r\n file_list = glob.glob(path+'*')\r\n\r\n sns.set_style(\"darkgrid\")\r\n\r\n BIN = 200\r\n DIST_BIN = np.arange(BIN, 1400, BIN)\r\n\r\n fig, ax = plt.subplots(2, 2)\r\n plt.style.use('ggplot') \r\n font = {'family' : 'meiryo'}\r\n matplotlib.rc('font', **font)\r\n\r\n for i in range(len(file_list)):\r\n print('file name=',file_list[i])\r\n\r\n df = pd.DataFrame(index=DIST_BIN, columns=const.SYSTEM_LIST)\r\n data = pd.read_csv(file_list[i],dtype={'system':int}) \r\n\r\n #df[i] = pd.read_csv(file_list[i],index_col='dist', dtype={'dist':int})\r\n #df[i] = df[i].drop('Unnamed: 0', axis=1)\r\n for b in DIST_BIN:\r\n tmp = data[(data['dist']>=(b-BIN))&(data['dist']=b)&(data['dist_ap']=d)&(tmp['dist_clu'] List[int]:\n bins = []\n for i in range(num + 1):\n c = collections.Counter(bin(i))\n if '1' not in c:\n bins.append(0)\n else:\n bins.append(c['1'])\n return bins","sub_path":"python/0338.Counting Bits.py","file_name":"0338.Counting Bits.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"} +{"seq_id":"132813736","text":"# Tai Sakuma \n\n##__________________________________________________________________||\ndef create_file_start_length_list(file_nevents_list, max_events_per_run = -1, max_events_total = -1, max_files_per_run = 1):\n\n file_nevents_list = _apply_max_events_total(file_nevents_list, max_events_total)\n\n return _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run)\n\n##__________________________________________________________________||\ndef _apply_max_events_total(file_nevents_list, max_events_total = -1):\n\n if max_events_total < 0: return file_nevents_list\n\n ret = [ ]\n for file, nevents in file_nevents_list:\n if max_events_total == 0: break\n nevents = min(max_events_total, nevents)\n ret.append((file, nevents))\n max_events_total -= nevents\n return ret\n\n##__________________________________________________________________||\ndef _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run):\n\n if not file_nevents_list:\n return [ ]\n\n total_nevents = sum([n for f, n, in file_nevents_list])\n if total_nevents == 0:\n return [ ]\n\n if max_files_per_run == 0:\n return [ ]\n\n if max_events_per_run == 0:\n return [ ]\n\n if max_events_per_run < 0:\n max_events_per_run = total_nevents\n\n total_nfiles = len(set([f for f, n, in file_nevents_list]))\n if max_files_per_run < 0:\n max_files_per_run = total_nfiles\n\n\n files = [ ]\n nevents = [ ]\n start = [ ]\n length = [ ]\n i = 0\n for file_, nev in file_nevents_list:\n\n if nev == 0:\n continue\n\n if i == len(files):\n # create a new run\n files.append([ ])\n nevents.append(0)\n start.append(0)\n length.append(0)\n\n files[i].append(file_)\n nevents[i] += nev\n\n if max_events_per_run >= nevents[i]:\n length[i] = nevents[i]\n\n else:\n dlength = max_events_per_run - length[i]\n length[i] = max_events_per_run\n\n i += 1\n files.append([file_])\n nevents.append(nevents[i-1] - length[i-1])\n start.append(dlength)\n\n while max_events_per_run < nevents[i]:\n length.append(max_events_per_run)\n\n i += 1\n files.append([file_])\n nevents.append(nevents[i-1] - length[i-1])\n start.append(start[i-1] + length[i-1])\n\n length.append(nevents[i])\n\n if max_events_per_run == nevents[i]:\n i += 1 # to next run\n continue\n\n if max_files_per_run == len(files[i]):\n i += 1 # to next run\n\n # print files, nevents, start, length\n ret = list(zip(files, start, length))\n\n return ret\n\n##__________________________________________________________________||\ndef _start_length_pairs_for_split_lists(ntotal, max_per_list):\n # e.g., ntotal = 35, max_per_list = 10\n\n if max_per_list < 0: return [(0, ntotal)]\n\n nlists = ntotal//max_per_list\n # https://stackoverflow.com/questions/1282945/python-integer-division-yields-float\n # nlists = 3\n\n ret = [(i*max_per_list, max_per_list) for i in range(nlists)]\n # e.g., [(0, 10), (10, 10), (20, 10)]\n\n remainder = ntotal % max_per_list\n # e.g., 5\n\n if remainder > 0:\n last = (nlists*max_per_list, remainder)\n # e.g, (30, 5)\n\n ret.append(last)\n\n # e.g., [(0, 10), (10, 10), (20, 10), (30, 5)]\n return ret\n\n##__________________________________________________________________||\ndef _minimum_positive_value(vals):\n # returns -1 if all negative or empty\n vals = [v for v in vals if v >= 0]\n if not vals: return -1\n return min(vals)\n\n##__________________________________________________________________||\n","sub_path":"alphatwirl/loop/splitfuncs.py","file_name":"splitfuncs.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"11"}